fig3.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. """Figure 3 plots, use run -i fig3.py"""
  2. mi = pd.MultiIndex.from_product([grtmseustrs, OPTOS], names=['mseu', 'opto'])
  3. columns = ['trialis', 'rates', 'blankrates', 'blankcondrates', # single trials
  4. 'burstratios', 'blankburstratios', 'blankcondburstratios', # single trials
  5. 'meanrate', 'blankmeanrate', 'blankcondmeanrate',
  6. 'meanburstratio', 'blankmeanburstratio', 'blankcondmeanburstratio',
  7. 'osi', 'oripref', 'f1f0',
  8. 'phi', 'bphi', 'nbphi', 'dphi', 'dbphi', 'dnbphi']
  9. fig3 = pd.DataFrame(index=mi, columns=columns) # excludes kind and st8
  10. ## NOTE: make sure that rows are not overwritten due to temporarily enabling iteration
  11. ## over st8 in any of the following loops!
  12. # plot grating rasters for each unit by state and opto condition:
  13. showbursts = True
  14. ## TODO: fix hard-coding:
  15. if EXPTYPE == 'negntsrmvis':
  16. NTRIALSPERCONDITION = 8 # per stimi and opto combination
  17. inchespertrial = 1/20*RASTERSCALEX
  18. else:
  19. NTRIALSPERCONDITION = 10 # per stimi and opto combination
  20. inchespertrial = 1/25*RASTERSCALEX
  21. #outliers = ['PVCre_2018_0001_s02_e02_u36', 'PVCre_2018_0001_s02_e06_u36',
  22. # 'PVCre_2018_0001_s02_e02_u64', 'PVCre_2018_0001_s02_e06_u64']
  23. for mseustr in []:#grtmseu2exmpli: #grtmseustrs: #outliers:
  24. #['Ntsr1Cre_2019_0008_s06_e02_u46']
  25. #['Ntsr1Cre_2020_0001_s04_e04_u12'] # negntsr fig
  26. for st8 in ['none']:#ALLST8S:
  27. for opto in OPTOS:
  28. dt = grtresp.loc[mseustr, st8, opto]['dt']
  29. wdt = -OFFSETS[0] + dt + OFFSETS[1] # wide raster duration, sec
  30. tmin, tmax = 0 + OFFSETS[0], dt + OFFSETS[1]
  31. optotrange = grtresp.loc[mseustr, st8, opto]['optotrange']
  32. wraster = grtresp.loc[mseustr, st8, opto]['wraster']
  33. if np.any(pd.isna(wraster)): # no raster for this condition
  34. continue
  35. ntrials = len(wraster)
  36. title = '%s grating %s %s raster' % (mseustr, st8, opto)
  37. burstis = None
  38. if showbursts:
  39. wburstis = grtresp.loc[mseustr, st8, opto]['wburstis']
  40. a = simpletraster(raster=wraster, alpha=0.5, s=1, dt=dt, offsets=OFFSETS,
  41. scatter=True, # False: low quality, but fast
  42. title=title, inchespersec=1.5*RASTERSCALEX,
  43. inchespertrial=inchespertrial,
  44. xaxis=True, burstis=wburstis)
  45. if opto:
  46. # plot horizontal line signifying opto ON period, just above axes:
  47. ton, toff = optotrange
  48. a.hlines(-5, ton, toff, colors=optoblue, lw=4, clip_on=False,
  49. in_layout=False)
  50. # plot horizontal line signifying stimulus period, just above axes:
  51. a.hlines(-2, 0, dt, colors='k', lw=4, clip_on=False, in_layout=False)
  52. # plot vertical coloured line just right of axes
  53. #vlinexpos = dt + OFFSETS[1] + wdt*0.02
  54. #y0, y1 = a.get_ylim()
  55. #clr = st82clr[st8]
  56. #alpha = opto2alpha[opto]
  57. #a.vlines(vlinexpos, y0, y1, colors=clr, lw=4, alpha=alpha, clip_on=False,
  58. # in_layout=False)
  59. a.set_xlim(tmin, tmax)
  60. #a.set_xticks(range(0, intround(dt)+1)) # force integer 1 sec tick marks
  61. # force ticks on trial axis separating ori conditions:
  62. a.set_yticks(range(0, ntrials+1, NTRIALSPERCONDITION))
  63. # Plot grating tuning curves for example units. Requires a database connection.
  64. # Uses effectively same grey as 0.4 alpha for opto True condition:
  65. try:
  66. tun
  67. except:
  68. print("WARNING: Can't plot tuning curves without database connection")
  69. tun = None
  70. if tun is not None:
  71. for mseustr in grtmseu2exmpli: #grtmseustrs:#['Ntsr1Cre_2020_0001_s04_e04_u55']
  72. tunrow = (tun & {**mseustr2key(mseustr), 'st8_crit':'none'})
  73. if tunrow:
  74. tunrow.plot(cs=['k', optoblue])
  75. ## TODO: plot f1/f0 vs. ori for some example units, e.g. Ntsr1Cre_2020_0001_s04_e04_u55
  76. ## Some of the time, or maybe even much of the time, f1/f0 vs. ori might show better
  77. ## orientation tuning than firing rate vs. ori.
  78. ## calculate cycle averages (i.e. grating PSTHs), F1/F0, and phi for all units:
  79. ## TODO: fit sinusoids and use fit error to evaluate how linear the responses are?
  80. PLOTCYCPSTH = False
  81. CYCPSTHTHRESH = 10 # minimum cycle average peak, Hz
  82. F1F0THRESH = 0.25 # minimum grating modulation index
  83. # minimum ratio of suppression burst cycle average peak to suppression of all spikes
  84. # cycle average peak, at maxori:
  85. BURSTRATIOTHRESH = 0.1
  86. TESTPEAKS = 'both' # test peak amplitude of 'either' or 'both' cycle PSTH opto conditions
  87. ncyclesoffset = 0.25 # fraction of previous and next cycle to plot
  88. figsize = DEFAULTFIGURESIZE
  89. for st8 in ['none']:#ALLST8S:
  90. color = st82clr[st8]
  91. f1f0offs, f1f0ons = [], []
  92. phioffs, phions, bphioffs, bphions, nbphioffs, nbphions = [], [], [], [], [], []
  93. dphis, dbphis, dnbphis = [], [], []
  94. exmplis, exmplmseustrs, normlis = [], [], []
  95. keptmseui = 0 # manually init and increment instead of using enumerate()
  96. for mseustr in grtmseustrs: #['Ntsr1Cre_2020_0001_s04_e04_u12']
  97. cycpsths, cycbpsths, cycts = {}, {}, {} # indexed by ori and opto
  98. f1f0s, phis = {}, {} # indexed by ori and opto
  99. rasters = grtresp.loc[mseustr, st8]['raster']
  100. brasters = grtresp.loc[mseustr, st8]['braster']
  101. if rasters.isna().any():
  102. print('%s: missing one or both raster opto conditions, skipping' % mseustr)
  103. continue
  104. if brasters.isna().any():
  105. print('%s: missing one or both braster opto conditions, skipping' % mseustr)
  106. continue
  107. orisopto = grtresp.loc[mseustr, st8]['oris'] # sorted, correspond to rows in raster
  108. ## TODO: maybe instead of enforcing this, just pull out all existing oris in both
  109. ## opto conditions, and do unique on those, and if any don't exist then handle that
  110. ## in the innermost loop?
  111. assert np.equal(*orisopto).all() # make sure oris are identical across opto
  112. # get oris from arbitrary condition, convert to int for use as dict keys:
  113. uoris = np.int64(np.unique(orisopto[False]))
  114. for ori in uoris:
  115. cycpsths[ori], cycbpsths[ori], cycts[ori] = {}, {}, {}
  116. f1f0s[ori], phis[ori] = {}, {}
  117. for opto in OPTOS:
  118. raster = rasters[opto]
  119. braster = brasters[opto]
  120. oris = orisopto[opto]
  121. dt = grtresp.loc[mseustr, st8, opto]['dt']
  122. tfreq = grtresp.loc[mseustr, st8, opto]['tfreq']
  123. cycdt = 1 / tfreq # cycle duration, s
  124. t0 = 0 + cycdt # exclude first cycle...
  125. t1 = dt # ...include up to end of last cycle
  126. offsets = np.array([-cycdt, cycdt]) * ncyclesoffset
  127. # to avoid edge effects of Guassian smoothing in raster2psth(), give it a wide
  128. # set of bins, and then slice out a slightly narrower (one bin width less at
  129. # each end) set of bins:
  130. wtrange = 0+offsets[0], cycdt+offsets[1] # wide (full) trange
  131. ntrange = wtrange[0]+binw, wtrange[1]-binw # narrow trange
  132. wcycbins = split_tranges([wtrange], binw, tres)
  133. ncycbins = split_tranges([ntrange], binw, tres)
  134. # find which rows in wcycbins correpond to those in ncycbins, based on the
  135. # start time of each bin:
  136. nbinis = wcycbins[:, 0].searchsorted(ncycbins[:, 0])
  137. orirowis = oris == ori
  138. rast = raster[orirowis] # raster restricted to rows corrsponding to ori
  139. brast = braster[orirowis]
  140. cycraster = wrap_raster(rast, t0, t1, cycdt, offsets=offsets)
  141. cycbraster = wrap_raster(brast, t0, t1, cycdt, offsets=offsets)
  142. f0, _ = raster2freqcomp(rast, dt, 0, mean='vector')
  143. f1, phi = raster2freqcomp(rast, dt, tfreq, mean='vector')
  144. if f0 == 0.0: # no spikes at all for this ori and opto combination
  145. f1f0s[ori][opto] = np.nan
  146. phis[ori][opto] = np.nan
  147. else:
  148. f1f0s[ori][opto] = f1 / f0
  149. phis[ori][opto] = np.angle(np.exp(1j*phi)) + pi # wrapped +ve angle, rad
  150. cycts[ori][opto] = ncycbins.mean(axis=1) # save narrow raster timepoints
  151. wrast = raster2psth(cycraster, wcycbins, binw, tres, kernel) # wide raster
  152. wbrast = raster2psth(cycbraster, wcycbins, binw, tres, kernel) # wide burst raster
  153. cycpsths[ori][opto] = wrast[nbinis] # slice down to narrow raster
  154. cycbpsths[ori][opto] = wbrast[nbinis]
  155. # find ori with max cycle average peak, across opto conditions:
  156. maxcycpsthvals = []
  157. for ori in uoris:
  158. maxcycpsthvals.append(max(cycpsths[ori][False].max(), cycpsths[ori][True].max()))
  159. maxcycpsthvali = np.argmax(maxcycpsthvals)
  160. maxori = uoris[maxcycpsthvali]
  161. if TESTPEAKS == 'either':
  162. # test for minimum PSTH peak height in at least one opto condition:
  163. maxcycpsthval = maxcycpsthvals[maxcycpsthvali]
  164. if maxcycpsthval < CYCPSTHTHRESH:
  165. continue # skip this mseu
  166. elif TESTPEAKS == 'both':
  167. # test for minimum PSTH peak height in both opto conditions:
  168. maxcycpsthoff = cycpsths[maxori][False].max()
  169. maxcycpsthon = cycpsths[maxori][True].max()
  170. if (np.array([maxcycpsthoff, maxcycpsthon]) < CYCPSTHTHRESH).any():
  171. continue # skip this mseu
  172. # test for minimum f1/f0 in at least one opto condition:
  173. maxf1f0atmaxori = max(f1f0s[maxori][False], f1f0s[maxori][True])
  174. if maxf1f0atmaxori < F1F0THRESH:
  175. continue # skip this mseu
  176. # collect f1f0 and phi values at maxori:
  177. f1f0off, f1f0on = f1f0s[maxori][False], f1f0s[maxori][True]
  178. f1f0offs.append(f1f0off)
  179. f1f0ons.append(f1f0on)
  180. phioff, phion = phis[maxori][False], phis[maxori][True]
  181. if EXPTYPE == 'pvmvis':
  182. # wrap some points:
  183. if (phioff < 60*pi/180) & (phion > 240*pi/180):
  184. phioff += 360*pi/180 # wrap point up over the y=x line
  185. elif (phioff > 340*pi/180) & (phion < 15*pi/180):
  186. phioff -= 360*pi/180 # wrap point down over the y=x line
  187. elif EXPTYPE == 'ntsrmvis':
  188. # wrap one point:
  189. if (phioff < 30*pi/180) & (phion > 340*pi/180):
  190. phioff += 360*pi/180 # wrap point up over the y=x line
  191. phioffs.append(phioff)
  192. phions.append(phion)
  193. fig3.loc[mseustr, 'phi'] = phioff*180/pi, phion*180/pi # save
  194. dphi = np.angle(np.exp(1j*phioff) / np.exp(1j*phion)) # phioff - phion
  195. dphis.append(dphi)
  196. if dphi < (-75*pi/180):
  197. print('OUTLIER: %s dphi=%g' % (mseustr, dphi))
  198. fig3.loc[mseustr, 'dphi'] = dphi*180/pi, dphi*180/pi # save, ignore opto field
  199. # collect phi of mseus that meet minimum ratio of suppression burst cycle average peak
  200. # to suppression all spikes cycle average peak, at maxori:
  201. cycbpsthmax, cycpsthmax = cycbpsths[maxori][True].max(), cycpsths[maxori][True].max()
  202. if cycpsthmax == 0.0:
  203. if cycbpsthmax == 0.0: # numerator and denominator are both 0
  204. suppburstratioatmaxori = 0.0
  205. else:
  206. suppburstratioatmaxori = np.inf
  207. else:
  208. suppburstratioatmaxori = cycbpsthmax / cycpsthmax
  209. # if suppression burst cycle average peak is big enough, treat is as a burst mseu,
  210. # otherwise treat it as a nonburst mseu:
  211. if suppburstratioatmaxori >= BURSTRATIOTHRESH:
  212. bphioffs.append(phioff)
  213. bphions.append(phion)
  214. fig3.loc[mseustr, 'bphi'] = phioff*180/pi, phion*180/pi # save
  215. dbphi = np.angle(np.exp(1j*phioff) / np.exp(1j*phion)) # bphioff - bphion
  216. dbphis.append(dbphi)
  217. fig3.loc[mseustr, 'dbphi'] = dbphi*180/pi, dbphi*180/pi # save, ignore opto field
  218. else:
  219. nbphioffs.append(phioff)
  220. nbphions.append(phion)
  221. fig3.loc[mseustr, 'nbphi'] = phioff*180/pi, phion*180/pi # save
  222. dnbphi = np.angle(np.exp(1j*phioff) / np.exp(1j*phion)) # nbphioff - nbphion
  223. dnbphis.append(dnbphi)
  224. fig3.loc[mseustr, 'dnbphi'] = dnbphi*180/pi, dnbphi*180/pi # save, ignore opto field
  225. ## plot maxori cycle average:
  226. if PLOTCYCPSTH:# and mseustr in grtmseu2exmpli:#['PVCre_2018_0003_s03_e02_u51']
  227. f, a = plt.subplots(figsize=(2, figsize[1]))
  228. title = ('%s %s PSTH maxori=%d offset=%g'
  229. % (mseustr, st8, maxori, ncyclesoffset))
  230. wintitle(title)
  231. for opto in OPTOS:
  232. c = desat(color, opto2alpha[opto]) # do manual alpha mixing
  233. bc = desat(burstclr, opto2alpha[opto]) # do manual alpha mixing
  234. fb = opto2fb[opto].title()
  235. if st8 == 'none':
  236. label = fb
  237. else:
  238. label = ', '.join([fb, st8.title()])
  239. cyct = cycts[maxori][opto]
  240. cycpsth = cycpsths[maxori][opto]
  241. cycbpsth = cycbpsths[maxori][opto]
  242. a.plot(cyct, cycpsth, '-', color=c, label=label)
  243. a.plot(cyct, cycbpsth, '-', color=bc, label=label+', Burst')
  244. a.axvline(x=0, ls='--', marker='', color='lightgray', zorder=-np.inf)
  245. a.axvline(x=cycdt, ls='--', marker='', color='lightgray', zorder=-np.inf)
  246. #l = a.legend(frameon=False)
  247. #l.set_draggable(True)
  248. a.set_xlabel('Time (s)')
  249. a.set_ylabel('Firing rate (spk/s)')
  250. a.set_xlim(cyct[0], cyct[-1])
  251. if mseustr in grtmseu2exmpli:
  252. exmplis.append(keptmseui)
  253. exmplmseustrs.append(mseustr)
  254. else:
  255. normlis.append(keptmseui)
  256. keptmseui += 1 # manually increment
  257. f1f0offs, f1f0ons = np.asarray(f1f0offs), np.asarray(f1f0ons)
  258. phioffs, phions = np.asarray(phioffs), np.asarray(phions)
  259. bphioffs, bphions = np.asarray(bphioffs), np.asarray(bphions)
  260. nbphioffs, nbphions = np.asarray(nbphioffs), np.asarray(nbphions)
  261. dphis, dbphis, dnbphis = np.asarray(dphis), np.asarray(dbphis), np.asarray(dnbphis)
  262. ## scatter plot collected maxori f1f0s:
  263. figsize = DEFAULTFIGURESIZE
  264. f, a = plt.subplots(figsize=figsize)
  265. wintitle('opto f1f0 maxori grating %s CYCPSTHTHRESH=%g F1F0THRESH=%g '
  266. 'TESTPEAKS=%s' % (st8, CYCPSTHTHRESH, F1F0THRESH, TESTPEAKS))
  267. # plot y=x line:
  268. linmin, linmax = 0, 2
  269. xyline = [linmin, linmax], [linmin, linmax]
  270. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  271. # plot normal (non-example) points:
  272. a.scatter(f1f0ons[normlis], f1f0offs[normlis], clip_on=False,
  273. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  274. # plot example points, one at a time:
  275. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  276. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  277. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  278. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  279. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  280. a.scatter(f1f0ons[exmpli], f1f0offs[exmpli], clip_on=False,
  281. marker=marker, c=c, s=sz, lw=lw)
  282. a.set_xlabel('Suppression F1/F0')
  283. a.set_ylabel('Feedback F1/F0')
  284. #a.set_xscale('log', basex=2)
  285. #a.set_yscale('log', basey=2)
  286. #a.set_xlim(0.125, 2)
  287. #a.set_ylim(0.125, 2)
  288. #a.set_xticks([0.125, 0.25, 0.5, 1, 2])
  289. #a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  290. #axes_disable_scientific(a)
  291. a.set_xlim(linmin, linmax)
  292. a.set_ylim(linmin, linmax)
  293. a.set_xticks(np.arange(linmin, linmax+1))
  294. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  295. a.minorticks_off()
  296. a.set_aspect('equal')
  297. a.spines['left'].set_position(('outward', 4))
  298. a.spines['bottom'].set_position(('outward', 4))
  299. t, p = ttest_rel(f1f0ons, f1f0offs) # paired t-test
  300. a.add_artist(AnchoredText('p$=$%.1g' % p, loc='upper left', frameon=False))
  301. ## scatter plot all collected maxori phis, regardless of burst classification:
  302. figsize = DEFAULTFIGURESIZE[0]*1.02, DEFAULTFIGURESIZE[1] # tweak to make space for labels
  303. f, a = plt.subplots(figsize=figsize)
  304. wintitle('opto phi maxori grating %s CYCPSTHTHRESH=%g F1F0THRESH=%g '
  305. 'TESTPEAKS=%s' % (st8, CYCPSTHTHRESH, F1F0THRESH, TESTPEAKS))
  306. # plot y=x line:
  307. #linmin, linmax, linstep = -180, 180, 180
  308. linmin, linmax, linstep = 0, 360, 180
  309. xyline = [linmin, linmax], [linmin, linmax]
  310. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  311. # plot normal (non-example) points:
  312. a.scatter(phions[normlis]*180/pi, phioffs[normlis]*180/pi, clip_on=False,
  313. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  314. # plot example points, one at a time:
  315. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  316. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  317. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  318. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  319. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  320. a.scatter(phions[exmpli]*180/pi, phioffs[exmpli]*180/pi, clip_on=False,
  321. marker=marker, c=c, s=sz, lw=lw)
  322. a.set_xlabel('Suppression')# $\phi$ ($\degree$)')
  323. a.set_ylabel('Feedback')# $\phi$ ($\degree$)')
  324. a.set_xlim(linmin, linmax)
  325. a.set_ylim(linmin-10.5, linmax+52)
  326. a.set_xticks(np.arange(linmin, linmax+linstep, linstep))
  327. a.set_yticks(a.get_xticks()) # make y ticks the same as x ticks
  328. a.minorticks_off()
  329. a.set_aspect('equal')
  330. a.spines['left'].set_position(('outward', 4))
  331. a.spines['bottom'].set_position(('outward', 4))
  332. ## plot maxori delta phi PDF:
  333. figsize = DEFAULTFIGURESIZE
  334. f, a = plt.subplots(figsize=figsize)
  335. wintitle('opto delta phi grating pdf %s BURSTRATIOTHRESH=%g' % (st8, BURSTRATIOTHRESH))
  336. phibins = np.arange(-180, 180+15, 15)
  337. a.hist(dnbphis*180/pi, bins=phibins, color='black', histtype='step') # non burst mseus
  338. a.hist(dbphis*180/pi, bins=phibins, color='red', histtype='step') # burst mseus
  339. #a.axvline(x=0, ls='--', marker='', color='lightgray', zorder=-np.inf)
  340. a.set_xlabel('$\Delta\phi=\phi_{\mathregular{fb}}-\phi_{\mathregular{sup}}$ ($\degree$)')
  341. a.set_ylabel('Unit count')
  342. a.set_xlim(-180, 180)
  343. a.set_xticks([-180, 0, 180])
  344. #p, k = kuiper(dnbphis, dbphis, axis=0) # test if dnbphis and dbphis are different
  345. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  346. ## plot maxori delta phi CDF:
  347. figsize = DEFAULTFIGURESIZE
  348. f, a = plt.subplots(figsize=figsize)
  349. wintitle('opto delta phi grating cdf %s BURSTRATIOTHRESH=%g' % (st8, BURSTRATIOTHRESH))
  350. # add extra max bin to prevent vertical line:
  351. dnbphibins = list(np.unique(dnbphis*180/pi)) + [180]
  352. a.hist(dnbphis*180/pi, bins=dnbphibins, density=True, cumulative=True, histtype='step',
  353. color='black') # non burst mseus
  354. dbphibins = list(np.unique(dbphis*180/pi)) + [180]
  355. a.hist(dbphis*180/pi, bins=dbphibins, density=True, cumulative=True, histtype='step',
  356. color='red') # non burst mseus
  357. a.axvline(x=0, ls='--', marker='', color='lightgray', zorder=-np.inf)
  358. a.set_xlabel('$\Delta\phi=\phi_{\mathregular{fb}}-\phi_{\mathregular{sup}}$ ($\degree$)')
  359. a.set_ylabel('Cumulative probability')
  360. a.set_xlim(-110, 110)
  361. #a.set_xticks([-180, 0, 180])
  362. a.set_yticks([0, 0.5, 1])
  363. nnbadv = (dnbphis > 0).sum() # non-bursting units whose phase advanced
  364. nnbtotal = len(dnbphis) # total number of non-bursting units
  365. pnb = scipy.stats.binom_test(nnbadv, nnbtotal) # test if nnbadv and nnbtotal are equal
  366. print('non-burst units that advanced: %d/%d, p_binom=%g' % (nnbadv, nnbtotal, pnb))
  367. nbadv = (dbphis > 0).sum() # bursting units whose phase advanced
  368. nbtotal = len(dbphis) # total number of bursting units
  369. pb = scipy.stats.binom_test(nbadv, nbtotal) # test if nbadv and nbtotal are equal
  370. print('burst units that advanced: %d/%d, p_binom=%g' % (nbadv, nbtotal, pb))
  371. # scatter plot grating meanrates:
  372. figsize = DEFAULTFIGURESIZE[0]*1.02, DEFAULTFIGURESIZE[1] # tweak to make space for log units
  373. logmin, logmax = -1.1, 2
  374. if EXPTYPE == 'ntsrmvis':
  375. logmin, logmax = -1.5, 2
  376. logticks = np.array([-1, 0, 1, 2])
  377. #log0min = logmin + 0.05
  378. for st8 in ['none']:#ALLST8S:
  379. f, a = plt.subplots(figsize=figsize)
  380. wintitle('opto meanrate grating %s' % st8)
  381. rons, roffs, sgnfs, exmplis, exmplmseustrs, normlis = [], [], [], [], [], []
  382. keptmseui = 0 # manually init and increment instead of using enumerate()
  383. for mseustr in grtmseustrs:
  384. trialis = grtresp.loc[mseustr, st8]['trialis'] # non-blank & blank trialis
  385. if trialis.isna().any(): # missing for at least one opto condition
  386. continue
  387. ntrials = { opto:len(trialis[opto]) for opto in OPTOS } # should be equal
  388. ratesfull = pd.Series({ opto:np.full(ntrials[opto], np.nan) # pad
  389. for opto in [False, True] })
  390. meanrate = grtresp.loc[mseustr, st8]['meanrate']
  391. if meanrate.isna().any(): # missing for at least one opto condition, can't plot
  392. fig3.loc[mseustr][blnksname] = ratesfull # save nans for all trials
  393. continue
  394. rons.append(meanrate[True])
  395. roffs.append(meanrate[False])
  396. rates = grtresp.loc[mseustr, st8]['rates'] # trial-wise non-blank rates
  397. nnblnktrials = { opto:len(rates[opto]) for opto in OPTOS } # num non-blank trials
  398. for opto in OPTOS:
  399. ratesfull[opto][:nnblnktrials[opto]] = rates[opto]
  400. _, pval = ttest_ind(rates[False], rates[True], equal_var=False)
  401. sgnfs.append(pval < SCATTERPTHRESH) # bool
  402. fig3.loc[mseustr, 'meanrate'] = meanrate[False], meanrate[True] # save
  403. fig3.loc[mseustr]['trialis'] = trialis # save, for joining DataFrames trial-wise
  404. fig3.loc[mseustr]['rates'] = ratesfull # save padded trial-wise values
  405. if mseustr in grtmseu2exmpli:
  406. exmplis.append(keptmseui)
  407. exmplmseustrs.append(mseustr)
  408. else:
  409. normlis.append(keptmseui)
  410. keptmseui += 1 # manually increment
  411. rons = np.asarray(rons)
  412. roffs = np.asarray(roffs)
  413. sgnfs = np.asarray(sgnfs)
  414. # replace off-scale low values with log0min, so the points remain visible:
  415. #pltrons, pltroffs = rons.copy(), roffs.copy()
  416. #pltrons[pltrons <= 10**logmin] = 10**log0min
  417. #pltroffs[pltroffs <= 10**logmin] = 10**log0min
  418. # plot y=x line:
  419. xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  420. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  421. insgnfis, = np.where(sgnfs == False)
  422. sgnfis, = np.where(sgnfs == True)
  423. normlinsgnfis = np.intersect1d(normlis, insgnfis)
  424. normlsgnfis = np.intersect1d(normlis, sgnfis)
  425. nsgnabovediag = (roffs[sgnfis] > rons[sgnfis]).sum()
  426. nsgnbelowdiag = (roffs[sgnfis] < rons[sgnfis]).sum()
  427. print('npoints=%d, nsgnf=%d, ninsgnf=%d, nsgnabovediag=%d, nsgnbelowdiag=%d'
  428. % (len(sgnfs), len(sgnfis), len(insgnfis), nsgnabovediag, nsgnbelowdiag))
  429. if len(normlinsgnfis) > 0:
  430. # plot normal (non-example) insignificant points:
  431. c = desat(st82clr[st8], SGNF2ALPHA[False]) # do manual alpha mixing
  432. a.scatter(rons[normlinsgnfis], roffs[normlinsgnfis], clip_on=False,
  433. marker='.', c='None', edgecolor=c, s=DEFSZ)
  434. if len(normlsgnfis) > 0:
  435. # plot normal (non-example) significant points:
  436. c = desat(st82clr[st8], SGNF2ALPHA[True]) # do manual alpha mixing
  437. a.scatter(rons[normlsgnfis], roffs[normlsgnfis], clip_on=False,
  438. marker='.', c='None', edgecolor=c, s=DEFSZ)
  439. # plot example points, one at a time:
  440. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  441. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  442. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  443. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  444. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  445. a.scatter(rons[exmpli], roffs[exmpli], clip_on=False,
  446. marker=marker, c=c, s=sz, lw=lw)
  447. a.set_xlabel('Suppression')# FR (spk/s)')
  448. a.set_ylabel('Feedback')# FR (spk/s)')
  449. a.set_xscale('log')
  450. a.set_yscale('log')
  451. a.set_xlim(10**logmin, 10**logmax)
  452. a.set_ylim(10**logmin, 10**logmax)
  453. a.set_xticks(10.0**logticks)
  454. a.set_yticks(a.get_xticks()) # make log scale y ticks the same as x ticks
  455. a.minorticks_off()
  456. axes_disable_scientific(a)
  457. a.set_aspect('equal')
  458. a.spines['left'].set_position(('outward', 4))
  459. a.spines['bottom'].set_position(('outward', 4))
  460. #t, p = ttest_rel(rons, roffs) # paired t-test
  461. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='lower right', frameon=False))
  462. #mu = rons.mean(), roffs.mean()
  463. #txt = '$\mathregular{\mu=%.1f, %.1f}$' % mu
  464. #a.add_artist(AnchoredText(txt, loc='upper left', frameon=False))
  465. # scatter plot grating burst ratio:
  466. figsize = DEFAULTFIGURESIZE[0]*1.04, DEFAULTFIGURESIZE[1] # tweak to make space for log units
  467. logmin, logmax = -3.55, 0
  468. if EXPTYPE == 'ntsrmvis':
  469. logmin, logmax = -3.83, 0
  470. logticks = np.array([-3, -2, -1, 0])
  471. for st8 in ['none']:#ALLST8S:
  472. f, a = plt.subplots(figsize=figsize)
  473. wintitle('opto burst ratio grating %s' % st8)
  474. brons, broffs, sgnfs, exmplis, exmplmseustrs, normlis = [], [], [], [], [], []
  475. keptmseui = 0 # manually init and increment instead of using enumerate()
  476. for mseustr in grtmseustrs:
  477. trialis = grtresp.loc[mseustr, st8]['trialis'] # non-blank & blank trialis
  478. if trialis.isna().any(): # missing for at least one opto condition
  479. continue
  480. ntrials = { opto:len(trialis[opto]) for opto in OPTOS } # should be equal
  481. burstratiosfull = pd.Series({ opto:np.full(ntrials[opto], np.nan) # pad
  482. for opto in [False, True] })
  483. br = grtresp.loc[mseustr, st8]['meanburstratio']
  484. if br.isna().any(): # missing for at least one opto condition, can't plot
  485. fig3.loc[mseustr]['burstratios'] = burstratiosfull # save nans for all trials
  486. continue
  487. brons.append(br[True])
  488. broffs.append(br[False])
  489. burstratios = grtresp.loc[mseustr, st8]['burstratios'] # non-blank burst ratios
  490. nnblnktrials = { opto:len(burstratios[opto]) for opto in OPTOS } # num non-blank trials
  491. for opto in OPTOS:
  492. burstratiosfull[opto][:nnblnktrials[opto]] = burstratios[opto]
  493. _, pval = ttest_ind(burstratios[False], burstratios[True], equal_var=False)
  494. sgnfs.append(pval < SCATTERPTHRESH) # bool
  495. fig3.loc[mseustr, 'meanburstratio'] = br[False], br[True] # save
  496. fig3.loc[mseustr]['burstratios'] = burstratiosfull # save padded trial-wise values
  497. if mseustr in grtmseu2exmpli:
  498. exmplis.append(keptmseui)
  499. exmplmseustrs.append(mseustr)
  500. else:
  501. normlis.append(keptmseui)
  502. keptmseui += 1 # manually increment
  503. brons, broffs = np.asarray(brons), np.asarray(broffs)
  504. sgnfs = np.asarray(sgnfs)
  505. # plot y=x line:
  506. xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  507. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  508. insgnfis, = np.where(sgnfs == False)
  509. sgnfis, = np.where(sgnfs == True)
  510. normlinsgnfis = np.intersect1d(normlis, insgnfis)
  511. normlsgnfis = np.intersect1d(normlis, sgnfis)
  512. if len(normlinsgnfis) > 0:
  513. # plot normal (non-example) insignificant points:
  514. c = desat(st82clr[st8], SGNF2ALPHA[False]) # do manual alpha mixing
  515. a.scatter(brons[normlinsgnfis], broffs[normlinsgnfis], clip_on=True,
  516. marker='.', c='None', edgecolor=c, s=DEFSZ) # clip_on=False fails
  517. if len(normlsgnfis) > 0:
  518. # plot normal (non-example) significant points:
  519. c = desat(st82clr[st8], SGNF2ALPHA[True]) # do manual alpha mixing
  520. a.scatter(brons[normlsgnfis], broffs[normlsgnfis], clip_on=True,
  521. marker='.', c='None', edgecolor=c, s=DEFSZ) # clip_on=False fails
  522. # plot example points, one at a time:
  523. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  524. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  525. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  526. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  527. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  528. a.scatter(brons[exmpli], broffs[exmpli], clip_on=False,
  529. marker=marker, c=c, s=sz, lw=lw)
  530. a.set_xlabel('Suppression')# BR') # keep it short to maximize space for axes
  531. a.set_ylabel('Feedback')# BR')
  532. a.set_xscale('log')
  533. a.set_yscale('log')
  534. a.set_xlim(10**logmin, 10**logmax)
  535. a.set_ylim(10**logmin, 10**logmax)
  536. a.set_xticks(10.0**logticks)
  537. a.set_yticks(a.get_xticks()) # make log scale y ticks the same as x ticks
  538. a.minorticks_off()
  539. axes_disable_scientific(a)
  540. a.set_aspect('equal')
  541. a.spines['left'].set_position(('outward', 4))
  542. a.spines['bottom'].set_position(('outward', 4))
  543. #t, p = ttest_rel(brons, broffs) # paired t-test
  544. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  545. # scatter plot grating opto OSI, R2, and orientation preference:
  546. oris = np.arange(360) # get nice smooth model output in 1 deg steps
  547. OSITHRESH = 0.02 # minimum OSI required in both conditions to include in oripref scatter
  548. R2THRESH = 0.5 # minimum R2 tuning curve fit threshold to include in oripref scatter
  549. for st8 in ['none']:#ALLST8S:
  550. color = st82clr[st8]
  551. osioffs, osions, oproffs, oprons, R2offs, R2ons = [], [], [], [], [], []
  552. exmplis, exmplmseustrs, normlis, mseustrs = [], [], [], []
  553. keptmseui = 0 # manually init and increment instead of using enumerate()
  554. for mseustr in grtmseustrs:
  555. tunparams = grtresp.loc[mseustr, st8]['tun']
  556. tunrsqs = grtresp.loc[mseustr, st8]['tunrsq']
  557. if tunparams.isna().any(): # missing one or both tunparams
  558. print('%s: missing one or both opto conditions, skipping' % mseustr)
  559. continue
  560. offparams, onparams = tunparams[False], tunparams[True]
  561. # don't subtract spont (params[5]) - negative rates lead to OSI exceeding 1 a lot more:
  562. offrates = sum_of_gaussians(oris, *offparams[:5])# - offparams[5] # model output
  563. onrates = sum_of_gaussians(oris, *onparams[:5])# - onparams[5] # model output
  564. osioff, osion = vector_OSI(oris, offrates), vector_OSI(oris, onrates)
  565. osioffs.append(osioff)
  566. osions.append(osion)
  567. fig3.loc[mseustr, 'osi'] = osioff, osion # save
  568. if mseustr in grtmseu2exmpli: # print out OSI values for example units
  569. print('Example OSI %s, opto_on: %.3f, opto_off: %.3f' % (mseustr, osion, osioff))
  570. oproff, opron = offparams[0] % 180, onparams[0] % 180 # direction pref mod 180
  571. oproffs.append(oproff)
  572. oprons.append(opron)
  573. R2offs.append(tunrsqs[False])
  574. R2ons.append(tunrsqs[True])
  575. if mseustr in grtmseu2exmpli:
  576. exmplis.append(keptmseui)
  577. exmplmseustrs.append(mseustr)
  578. else:
  579. normlis.append(keptmseui)
  580. mseustrs.append(mseustr)
  581. keptmseui += 1 # manually increment
  582. osioffs, osions = np.asarray(osioffs), np.asarray(osions)
  583. oproffs, oprons = np.asarray(oproffs), np.asarray(oprons)
  584. R2offs, R2ons = np.asarray(R2offs), np.asarray(R2ons)
  585. mseustrs = np.asarray(mseustrs)
  586. ## scatter plot OSI:
  587. figsize = DEFAULTFIGURESIZE[0]*1.02, DEFAULTFIGURESIZE[1] # tweak for log units
  588. f, a = plt.subplots(figsize=figsize)
  589. wintitle('opto osi grating %s' % st8)
  590. logmin, logmax, logstep = -2.2, 0, 1
  591. logticks = np.array([-2, -1, 0])
  592. # replace off-scale low values with log0min, so the points remain visible:
  593. #pltosions, pltosioffs = osions.copy(), osioffs.copy()
  594. #pltosions[pltosions <= 10**logmin] = 10**log0min
  595. #pltosioffs[pltosioffs <= 10**logmin] = 10**log0min
  596. # plot y=x line:
  597. xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  598. #xyline = [linmin, linmax], [linmin, linmax]
  599. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  600. # plot normal (non-example) points:
  601. a.scatter(osions[normlis], osioffs[normlis], clip_on=False,
  602. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  603. # plot example points, one at a time:
  604. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  605. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  606. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  607. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  608. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  609. a.scatter(osions[exmpli], osioffs[exmpli], clip_on=False,
  610. marker=marker, c=c, s=sz, lw=lw)
  611. a.set_xlabel('Suppression')# OSI')
  612. a.set_ylabel('Feedback')# OSI')
  613. a.set_xscale('log')
  614. a.set_yscale('log')
  615. a.set_xlim(10**logmin, 10**logmax)
  616. a.set_ylim(10**logmin, 10**logmax)
  617. a.set_xticks(10.0**logticks)
  618. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  619. a.minorticks_off()
  620. axes_disable_scientific(a)
  621. a.set_aspect('equal')
  622. a.spines['left'].set_position(('outward', 4))
  623. a.spines['bottom'].set_position(('outward', 4))
  624. #t, p = ttest_rel(osions, osioffs) # paired t-test
  625. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  626. ## scatter plot R2:
  627. figsize = DEFAULTFIGURESIZE
  628. f, a = plt.subplots(figsize=figsize)
  629. wintitle('opto R2 grating %s' % st8)
  630. linmin, linmax, linstep = 0, 1, 0.5
  631. xyline = [linmin, linmax], [linmin, linmax]
  632. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  633. # plot normal (non-example) points, coloring by state:
  634. a.scatter(R2ons[normlis], R2offs[normlis], clip_on=False,
  635. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  636. # plot example points, one at a time:
  637. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  638. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  639. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  640. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  641. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  642. a.scatter(R2ons[exmpli], R2offs[exmpli], clip_on=False,
  643. marker=marker, c=c, s=sz, lw=lw)
  644. a.set_xlabel(r'Suppression $\mathregular{R^2}$')
  645. a.set_ylabel(r'Feedback $\mathregular{R^2}$')
  646. a.set_xlim(linmin, linmax)
  647. a.set_ylim(linmin, linmax)
  648. a.set_xticks(np.arange(linmin, linmax+linstep, linstep))
  649. a.set_yticks(a.get_xticks())
  650. a.minorticks_off()
  651. a.set_aspect('equal')
  652. a.spines['left'].set_position(('outward', 4))
  653. a.spines['bottom'].set_position(('outward', 4))
  654. t, p = ttest_rel(R2ons, R2offs) # paired t-test
  655. a.add_artist(AnchoredText('p$=$%.2g' % p, loc='lower right', frameon=False))
  656. ## scatter plot oripref:
  657. figsize = DEFAULTFIGURESIZE[0]*1.02, DEFAULTFIGURESIZE[1] # tweak tick labels
  658. f, a = plt.subplots(figsize=figsize)
  659. wintitle('opto oripref grating %s OSITHRESH=%g R2THRESH=%g' % (st8, OSITHRESH, R2THRESH))
  660. linmin, linmax, linstep = 0, 180, 90
  661. xyline = [linmin, linmax], [linmin, linmax]
  662. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  663. if EXPTYPE == 'pvmvis':
  664. # wrap some points:
  665. wrapis = (oproffs < 15) & (oprons > 175)
  666. assert wrapis.sum() == 2
  667. oproffs[wrapis] = oproffs[wrapis] + 180 # wrap 2 points up over the y=x line
  668. # plot only units whose OSI satisfies OSITHRESH and R2 satisfies R2THRESH,
  669. # get indices of units that are well-tuned and well-fit in both conditions:
  670. tunis, = np.where((osioffs >= OSITHRESH) & (osions >= OSITHRESH) &
  671. (R2offs >= R2THRESH) & (R2ons >= R2THRESH))
  672. normlis = np.intersect1d(tunis, normlis)
  673. exmplis = np.intersect1d(tunis, exmplis)
  674. for mseustr, oproff, opron in zip(mseustrs[tunis], oproffs[tunis], oprons[tunis]):
  675. fig3.loc[mseustr, 'oripref'] = oproff, opron # save
  676. # plot normal (non-example) points, coloring by state:
  677. a.scatter(oprons[normlis], oproffs[normlis], clip_on=False,
  678. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  679. # plot normal (non-example) points, coloring by min OSI:
  680. '''
  681. minosi = np.vstack([osions[normlis], osioffs[normlis]]).min(axis=0)
  682. scatt = a.scatter(oproffs[normlis], oprons[normlis],
  683. marker='.', c=minosi, vmax=0.1, s=100)
  684. f.colorbar(scatt)
  685. '''
  686. # plot example points, one at a time:
  687. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  688. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  689. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  690. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  691. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  692. a.scatter(oprons[exmpli], oproffs[exmpli], clip_on=False,
  693. marker=marker, c=c, s=sz, lw=lw)
  694. a.set_xlabel(r'Suppression')# $\theta$ ($\degree$)')
  695. a.set_ylabel(r'Feedback')# $\theta$ ($\degree$)')
  696. a.set_xlim(linmin, linmax)
  697. a.set_ylim(ymin=linmin)
  698. a.set_xticks(np.arange(linmin, linmax+linstep, linstep))
  699. a.set_yticks(a.get_xticks())
  700. a.minorticks_off()
  701. a.set_aspect('equal')
  702. a.spines['left'].set_position(('outward', 4))
  703. a.spines['bottom'].set_position(('outward', 4))
  704. #t, p = ttest_rel(oprons[tunis], oproffs[tunis]) # paired t-test
  705. #oriprefm, oriprefb, oriprefr, _, _ = linregress(oproffs[tunis], oprons[tunis])
  706. #oriprefrsq = oriprefr * oriprefr
  707. #txt = ('$\mathregular{R^2=}$%.2g\n'
  708. # '$\mathregular{p=}$%.2g' % (oriprefrsq, p))
  709. #a.add_artist(AnchoredText(txt, loc='upper left', frameon=False))
  710. ## plot OSI distributions, for choosing OSITHRESH:
  711. f, a = plt.subplots(figsize=figsize)
  712. wintitle('opto osi grating pdf %s' % st8)
  713. osibins = np.logspace(-2, 0, 15)
  714. offclr, onclr = desat(color, opto2alpha[False]), desat(color, opto2alpha[True])
  715. a.hist(osioffs, bins=osibins, color=offclr, histtype='step')
  716. a.hist(osions, bins=osibins, color=onclr, histtype='step')
  717. a.axvline(x=OSITHRESH, ls='--', marker='', color='lightgray', zorder=-np.inf)
  718. a.set_xlabel('OSI')
  719. a.set_ylabel('Unit count')
  720. a.set_xscale('log')
  721. ## plot R2 distributions, for choosing R2THRESH:
  722. f, a = plt.subplots(figsize=figsize)
  723. wintitle('opto R2 grating pdf %s' % st8)
  724. R2bins = np.linspace(0, 1, 11)
  725. a.hist(R2offs, bins=R2bins, color=offclr, histtype='step')
  726. a.hist(R2ons, bins=R2bins, color=onclr, histtype='step')
  727. a.axvline(x=R2THRESH, ls='--', marker='', color='lightgray', zorder=-np.inf)
  728. a.set_xlabel('Fit $\mathregular{R^2}$')
  729. a.set_ylabel('Unit count')
  730. # scatter plot grating opto mean f1 and f1/f0:
  731. logmin, logmax = -1, 2
  732. logticks = np.array([-1, 0, 1, 2])
  733. for st8 in ['none']:#ALLST8S:
  734. f1offs, f1ons, f1f0offs, f1f0ons, exmplis, exmplmseustrs, normlis = [], [], [], [], [], [], []
  735. keptmseui = 0 # manually init and increment instead of using enumerate()
  736. for mseustr in grtmseustrs:
  737. rasters = grtresp.loc[mseustr, st8]['raster']
  738. dt = grtresp.loc[mseustr, st8, False]['dt']
  739. tfreq = grtresp.loc[mseustr, st8, False]['tfreq']
  740. if rasters.isna().any(): # missing one or both rasters
  741. print('%s: missing one or both opto conditions, skipping' % mseustr)
  742. continue
  743. offraster, onraster = rasters[False], rasters[True]
  744. ## maybe consider std as well, to gauge significance of each f1f0 measure...
  745. f0off, _ = raster2freqcomp(offraster, dt, 0, mean='scalar')
  746. f1off, _ = raster2freqcomp(offraster, dt, tfreq, mean='scalar')
  747. f0on, _ = raster2freqcomp(onraster, dt, 0, mean='scalar')
  748. f1on, _ = raster2freqcomp(onraster, dt, tfreq, mean='scalar')
  749. f1f0off = f1off / f0off
  750. f1f0on = f1on / f0on
  751. f1offs.append(f1off)
  752. f1ons.append(f1on)
  753. f1f0offs.append(f1f0off)
  754. f1f0ons.append(f1f0on)
  755. fig3.loc[mseustr, 'f1f0'] = f1f0off, f1f0on # save
  756. if mseustr in grtmseu2exmpli:
  757. exmplis.append(keptmseui)
  758. exmplmseustrs.append(mseustr)
  759. else:
  760. normlis.append(keptmseui)
  761. keptmseui += 1 # manually increment
  762. f1offs = np.asarray(f1offs)
  763. f1ons = np.asarray(f1ons)
  764. f1f0offs = np.asarray(f1f0offs)
  765. f1f0ons = np.asarray(f1f0ons)
  766. ## scatter plot mean f1:
  767. figsize = DEFAULTFIGURESIZE
  768. f, a = plt.subplots(figsize=figsize)
  769. wintitle('opto mean f1 grating %s' % st8)
  770. # plot y=x line:
  771. xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  772. #linmin, linmax = 0, 75
  773. #xyline = [linmin, linmax], [linmin, linmax]
  774. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  775. # plot normal (non-example) points:
  776. a.scatter(f1ons[normlis], f1offs[normlis], clip_on=False,
  777. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  778. # plot example points, one at a time:
  779. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  780. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  781. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  782. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  783. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  784. a.scatter(f1ons[exmpli], f1offs[exmpli], marker=marker, clip_on=False,
  785. c=c, s=sz, lw=lw)
  786. a.set_xlabel('Suppression F1')
  787. a.set_ylabel('Feedback F1')
  788. a.set_xscale('log')
  789. a.set_yscale('log')
  790. a.set_xlim(10**logmin, 10**logmax)
  791. a.set_ylim(10**logmin, 10**logmax)
  792. a.set_xticks(10.0**logticks)
  793. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  794. a.minorticks_off()
  795. axes_disable_scientific(a)
  796. a.set_aspect('equal')
  797. a.spines['left'].set_position(('outward', 4))
  798. a.spines['bottom'].set_position(('outward', 4))
  799. #t, p = ttest_rel(f1ons, f1offs) # paired t-test
  800. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='lower right', frameon=False))
  801. ## scatter plot mean f1/f0
  802. figsize = DEFAULTFIGURESIZE
  803. f, a = plt.subplots(figsize=figsize)
  804. wintitle('opto mean f1f0 grating %s' % st8)
  805. # plot y=x line:
  806. linmin, linmax = 0, 2
  807. xyline = [linmin, linmax], [linmin, linmax]
  808. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  809. # plot normal (non-example) points:
  810. a.scatter(f1f0ons[normlis], f1f0offs[normlis], clip_on=False,
  811. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  812. # plot example points, one at a time:
  813. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  814. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  815. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  816. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  817. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  818. a.scatter(f1f0ons[exmpli], f1f0offs[exmpli], clip_on=False,
  819. marker=marker, c=c, s=sz, lw=lw)
  820. a.set_xlabel('Suppression')# F1/F0')
  821. a.set_ylabel('Feedback')# F1/F0')
  822. #a.set_xscale('log', basex=2)
  823. #a.set_yscale('log', basey=2)
  824. #a.set_xlim(0.125, 2)
  825. #a.set_ylim(0.125, 2)
  826. #a.set_xticks([0.125, 0.25, 0.5, 1, 2])
  827. #a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  828. #axes_disable_scientific(a)
  829. a.set_xlim(linmin, linmax)
  830. a.set_ylim(linmin, linmax)
  831. a.set_xticks(np.arange(linmin, linmax+1))
  832. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  833. a.minorticks_off()
  834. a.set_aspect('equal')
  835. a.spines['left'].set_position(('outward', 4))
  836. a.spines['bottom'].set_position(('outward', 4))
  837. #t, p = ttest_rel(f1f0ons, f1f0offs) # paired t-test
  838. #a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  839. '''
  840. # scatter plot grating opto local/global max f1/f0 and max f1:
  841. figsize = DEFAULTFIGURESIZE
  842. logmin, logmax = -1.5, 2
  843. logticks = np.array([-1, 0, 1, 2])
  844. for maxmethod in ['local', 'global']:
  845. for st8 in ['none']:#ALLST8S:
  846. maxf1f0s, maxf1s, exmplis, exmplmseustrs, normlis = [], [], [], [], []
  847. keptmseui = 0 # manually init and increment instead of using enumerate()
  848. for mseustr in grtmseustrs:
  849. f0s, f1s = [[], []], [[], []]
  850. rasters = grtresp.loc[mseustr, st8]['raster']
  851. dt = grtresp.loc[mseustr, st8, False]['dt']
  852. tfreq = grtresp.loc[mseustr, st8, False]['tfreq']
  853. if rasters.isna().any(): # missing one or both rasters
  854. print('%s: missing one or both opto conditions, skipping' % mseustr)
  855. continue
  856. offraster, onraster = rasters[False], rasters[True]
  857. for optoi, opto in enumerate(OPTOS):
  858. stimis = grtresp.loc[mseustr, st8, opto]['stimis']
  859. ustimis = np.unique(stimis)
  860. for stimi in ustimis:
  861. trialis = stimis == stimi # boolean array
  862. stimiraster = rasters[opto][trialis] # raster including only stimi's trials
  863. f0, _ = raster2freqcomp(stimiraster, dt, 0, mean='vector')
  864. f1, _ = raster2freqcomp(stimiraster, dt, tfreq, mean='vector')
  865. f0s[optoi].append(f0)
  866. f1s[optoi].append(f1)
  867. f0s = np.array(f0s) # 2D array, row0:False, row1:True
  868. f0s[f0s == 0] = np.nan # prevent div by 0, replace 0s with nans
  869. f1s = np.array(f1s)
  870. f1f0s = f1s / f0s # 2D array, row0:False, row1:True
  871. if maxmethod == 'local':
  872. # get max for each opto condition separately:
  873. #maxf1f0 = np.nanmax(f1f0s, axis=1)
  874. maxrowis = np.array([0, 1])
  875. maxcolis = np.nanargmax(f1f0s, axis=1) # 2 values, one per row
  876. maxf1f0 = f1f0s[maxrowis, maxcolis]
  877. maxf1 = f1s[maxrowis, maxcolis]
  878. elif maxmethod == 'global':
  879. # find global max, use it to pick paired value of other opto condition:
  880. flatmaxi = np.nanargmax(f1f0s)
  881. maxrowi, maxcoli = np.unravel_index(flatmaxi, f1f0s.shape)
  882. maxf1f0 = f1f0s[:, maxcoli]
  883. maxf1 = f1s[:, maxcoli]
  884. maxf1f0s.append(maxf1f0)
  885. maxf1s.append(maxf1)
  886. if mseustr in grtmseu2exmpli:
  887. exmplis.append(keptmseui)
  888. exmplmseustrs.append(mseustr)
  889. else:
  890. normlis.append(keptmseui)
  891. keptmseui += 1 # manually increment
  892. maxf1f0s = np.asarray(maxf1f0s).T # 2D array: optoi, mseui
  893. maxf1s = np.asarray(maxf1s).T # 2D array: optoi, mseui
  894. ## scatter plot max f1/f0:
  895. f, a = plt.subplots(figsize=figsize)
  896. wintitle('opto %s max f1f0 grating %s' % (maxmethod, st8))
  897. # plot y=x line:
  898. #xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  899. linmin, linmax = 0, 2
  900. xyline = [linmin, linmax], [linmin, linmax]
  901. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  902. # plot normal (non-example) points:
  903. a.scatter(maxf1f0s[1, normlis], maxf1f0s[0, normlis],
  904. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  905. # plot example points, one at a time:
  906. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  907. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  908. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  909. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  910. a.scatter(maxf1f0s[1, exmpli], maxf1f0s[0, exmpli], marker=marker, c=c, s=sz)
  911. a.set_xlabel('Suppression max F1/F0')
  912. a.set_ylabel('Feedback max F1/F0')
  913. a.set_xlim(linmin, linmax+0.1)
  914. a.set_ylim(linmin, linmax+0.1)
  915. a.set_xticks(np.arange(linmin, linmax+1))
  916. #a.set_xscale('log')
  917. #a.set_yscale('log')
  918. #a.set_xlim(10**logmin, 10**logmax)
  919. #a.set_ylim(10**logmin, 10**logmax)
  920. #a.set_xticks(10.0**logticks)
  921. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  922. a.minorticks_off()
  923. a.set_aspect('equal')
  924. t, p = ttest_rel(maxf1f0s[1], maxf1f0s[0]) # paired t-test
  925. a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  926. ## scatter plot max f1:
  927. f, a = plt.subplots(figsize=figsize)
  928. wintitle('opto %s max f1 grating %s' % (maxmethod, st8))
  929. # plot y=x line:
  930. xyline = [10**logmin, 10**logmax], [10**logmin, 10**logmax]
  931. #linmin, linmax = 0, 2
  932. #xyline = [linmin, linmax], [linmin, linmax]
  933. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  934. # plot normal (non-example) points:
  935. a.scatter(maxf1s[1, normlis], maxf1s[0, normlis],
  936. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  937. # plot example points, one at a time:
  938. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  939. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  940. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  941. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  942. a.scatter(maxf1s[1, exmpli], maxf1s[0, exmpli], marker=marker, c=c, s=sz)
  943. a.set_xlabel('Suppression max F1')
  944. a.set_ylabel('Feedback max F1')
  945. #a.set_xlim(linmin, linmax+0.1)
  946. #a.set_ylim(linmin, linmax+0.1)
  947. #a.set_xticks(np.arange(linmin, linmax+1))
  948. a.set_xscale('log')
  949. a.set_yscale('log')
  950. a.set_xlim(10**logmin, 10**logmax)
  951. a.set_ylim(10**logmin, 10**logmax)
  952. a.set_xticks(10.0**logticks)
  953. a.set_yticks(a.get_xticks()) # make scale y ticks the same as x ticks
  954. a.minorticks_off()
  955. axes_disable_scientific(a)
  956. a.set_aspect('equal')
  957. t, p = ttest_rel(maxf1s[1], maxf1s[0]) # paired t-test
  958. a.add_artist(AnchoredText('p$=$%.2g' % p, loc='upper left', frameon=False))
  959. '''
  960. # fig4S1a: scatter plot grating meanburstratio FMI vs meanrate FMI:
  961. figsize = DEFAULTFIGURESIZE[0]*0.95, DEFAULTFIGURESIZE[1] # tweak to match others in 4S1
  962. linmin, linmax, linstep = -1, 1, 1
  963. ticks = np.arange(linmin, linmax+linstep, linstep)
  964. for st8 in ['none']:#ALLST8S:
  965. for measure in ['meanburstratio']:
  966. if measure.startswith('meanrate'):
  967. continue # don't bother plotting meanrate* against meanrate
  968. axislabel = measure2axislabel[measure]
  969. rfmis, msrfmis = [], []
  970. exmplis, exmplmseustrs, normlis = [], [], []
  971. keptmseui = 0 # manually init and increment instead of using enumerate()
  972. for mseustr in grtmseustrs:
  973. rfmi = grtFMI.loc[mseustr, st8]['meanrate']
  974. msrfmi = grtFMI.loc[mseustr, st8][measure]
  975. if pd.isna(rfmi) or pd.isna(msrfmi): # missing at least one FMI value
  976. continue
  977. rfmis.append(rfmi)
  978. msrfmis.append(msrfmi)
  979. if mseustr in grtmseu2exmpli:
  980. exmplis.append(keptmseui)
  981. exmplmseustrs.append(mseustr)
  982. else:
  983. normlis.append(keptmseui)
  984. keptmseui += 1 # manually increment
  985. rfmis, msrfmis = np.asarray(rfmis), np.asarray(msrfmis)
  986. ## scatter plot FMIs:
  987. f, a = plt.subplots(figsize=figsize)
  988. wintitle('opto FMI %s vs FMI rate %s' % (measure, st8))
  989. # plot x=0 and y=0 lines:
  990. a.axhline(y=0, ls='--', marker='', color='lightgray', zorder=-np.inf)
  991. a.axvline(x=0, ls='--', marker='', color='lightgray', zorder=-np.inf)
  992. # plot y=x line:
  993. xyline = [linmin, linmax], [linmin, linmax]
  994. a.plot(xyline[0], xyline[1], '--', color='gray', zorder=-1)
  995. # plot normal (non-example) points:
  996. a.scatter(rfmis[normlis], msrfmis[normlis], clip_on=False,
  997. marker='.', c='None', edgecolor=st82clr[st8], s=DEFSZ)
  998. # plot example points, one at a time:
  999. for exmpli, mseustr in zip(exmplis, exmplmseustrs):
  1000. marker = exmpli2mrk[grtmseu2exmpli[mseustr]]
  1001. c = exmpli2clr[grtmseu2exmpli[mseustr]]
  1002. sz = exmpli2sz[grtmseu2exmpli[mseustr]]
  1003. lw = exmpli2lw[grtmseu2exmpli[mseustr]]
  1004. a.scatter(rfmis[exmpli], msrfmis[exmpli], marker=marker, c=c, s=sz, lw=lw)
  1005. #mm, b, rr, p, stderr = linregress(rfmis, msrfmis)
  1006. #rsq = rr * rr
  1007. #x = np.array([rfmis.min(), rfmis.max()])
  1008. #y = mm * x + b
  1009. #txt = ('$\mathregular{R^{2}=%.2g}$' % rsq)
  1010. #a.add_artist(AnchoredText(txt, loc='upper left', frameon=False))
  1011. #a.plot(x, y, '-', color='red') # plot linregress fit
  1012. a.set_xlabel('Firing rate FMI')
  1013. if axislabel.islower():
  1014. axislabel = axislabel.capitalize()
  1015. ylabel = '%s FMI' % axislabel
  1016. a.set_ylabel(ylabel)
  1017. a.set_xlim(linmin, linmax)
  1018. a.set_ylim(linmin, linmax)
  1019. a.set_xticks(ticks)
  1020. a.set_yticks(ticks)
  1021. a.set_aspect('equal')
  1022. a.spines['left'].set_position(('outward', 4))
  1023. a.spines['bottom'].set_position(('outward', 4))