-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprobeData.py
More file actions
3775 lines (3315 loc) · 202 KB
/
Copy pathprobeData.py
File metadata and controls
3775 lines (3315 loc) · 202 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 17 12:19:20 2016
@author: SVC_CCG
"""
from __future__ import division
import fileIO
import datetime, h5py, json, math, ntpath, os, re, shelve, shutil
import numpy as np
import scipy.ndimage.filters
import scipy.optimize
import scipy.signal
import scipy.stats
from matplotlib import pyplot as plt
from matplotlib import gridspec
from matplotlib import cm
from astropy.convolution import Gaussian2DKernel, Gaussian1DKernel, convolve
import pandas
import extractWaveforms
import itertools
dataDir = r'C:\Users\SVC_CCG\Desktop\Data'
class probeData():
def __init__(self):
self.recording = 0
self.TTLChannelLabels = ['VisstimOn', 'CamExposing', 'CamSaving', 'OrangeLaserShutter']
self.channelMapFile = r'C:\Users\SVC_CCG\Documents\Python Scripts\imec_channel_map_D.prb'
self.sampleRate = 30000.0
self.digitalGain = 0.195
self.analogGain = 0.00015258789
self.wheelChannel = 134
self.diodeChannel = 135
self.visStimOnChannel = 136
self.blueLaserChannel = 137
self.orangeLaserChannel = 138
self.camExposingChannel = 139
self.camSavingChannel = 140
def loadKwd(self, filePath):
f = h5py.File(filePath, 'r')
datDict = {}
datDict['info'] = f['recordings'][str(self.recording)].attrs
datDict['data'] = f['recordings'][str(self.recording)]['data']
datDict['gains'] = f['recordings'][str(self.recording)]['application_data']['channel_bit_volts'][:]
datDict['sampleRate'] = datDict['info']['sample_rate']
datDict['startTime'] = datDict['info']['start_time']
datDict['firstAnalogSample'] = f['recordings'][str(self.recording)]['application_data']['timestamps'][0][0]
return datDict
def loadExperiment(self, dirPath=None, loadRunningData=False, loadUnits=True, loadWaveforms=False):
self.kwdFileList, self.nsamps = getKwdInfo(dirPath)
filelist = self.kwdFileList
filePaths = [os.path.dirname(f) for f in filelist]
self._d = []
for index, f in enumerate(filelist):
ff = os.path.basename(os.path.dirname(f))
ff = ff.split('_')[-1]
datDict = self.loadKwd(f)
datDict['protocolName'] = ff
datDict['numSamples'] = self.nsamps[index]
self._d.append(datDict)
if loadUnits:
self.getSingleUnits(fileDir=os.path.dirname(filePaths[0]))
if loadRunningData:
self.mapChannels()
self.visstimData = {}
self.behaviorData = {}
self.TTL = {}
for pro, proPath in enumerate(filePaths):
files = os.listdir(proPath)
visStimFound = False
eyeDataFound = False
self.behaviorData[str(pro)] = {}
for f in files:
if 'VisStim' in f:
self.getVisStimData(os.path.join(proPath, f), protocol=pro)
visStimFound = True
continue
#load eye tracking data
if 'MouseEyeTracker' in f:
self.getEyeTrackData(os.path.join(proPath, f), protocol=pro)
eyeDataFound = True
continue
ttlFile = [f for f in files if f.endswith('kwe')][0]
self.getTTLData(filePath=os.path.join(proPath, ttlFile), protocol=pro)
if loadRunningData:
wd = self._d[pro]['data'][:, self.wheelChannel]*self._d[pro]['gains'][self.wheelChannel]
wd = wd[::500]
self.behaviorData[str(pro)]['running'] = self.decodeWheel(wd)
if not visStimFound:
print('No vis stim data found for ' + os.path.basename(proPath))
if not eyeDataFound:
print('No eye tracking data found for ' + os.path.basename(proPath))
for i, pro in enumerate(self.kwdFileList):
if 'laser' in pro:
self.findAnalogPulses(self.blueLaserChannel, i)
if loadWaveforms:
self.getWaveforms()
def getTTLData(self, filePath=None, protocol=0):
if filePath is None:
ttlFileDir = self.filePath[:self.filePath.rfind('/')]
filelist = os.listdir(ttlFileDir)
filePath = ttlFileDir + '/' + [f for f in filelist if f.endswith('kwe')][0]
f = h5py.File(filePath, 'r')
recordingID = f['event_types']['TTL']['events']['recording'][:]
eventChannels = f['event_types']['TTL']['events']['user_data']['event_channels'][recordingID==self.recording]
edges = f['event_types']['TTL']['events']['user_data']['eventID'][recordingID==self.recording]
timeSamples = f['event_types']['TTL']['events']['time_samples'][recordingID==self.recording]
self.TTLChannels = np.unique(eventChannels)
self.TTL[str(protocol)] = {}
for chan in self.TTLChannels:
eventsForChan = np.where(eventChannels == chan)
self.TTL[str(protocol)][self.TTLChannelLabels[chan]] = {}
self.TTL[str(protocol)][self.TTLChannelLabels[chan]]['rising'] = timeSamples[np.intersect1d(eventsForChan, np.where(edges == 1))] - self._d[protocol]['firstAnalogSample']
self.TTL[str(protocol)][self.TTLChannelLabels[chan]]['falling'] = timeSamples[np.intersect1d(eventsForChan, np.where(edges ==0))] - self._d[protocol]['firstAnalogSample']
if str(protocol) in self.visstimData:
if not hasattr(self, 'frameSamples'):
self.alignFramesToDiode(protocol=protocol)
def getVisStimData(self, filePath=None, protocol=0):
if filePath is None:
filePath = fileIO.getFile()
dataFile = h5py.File(filePath)
self.visstimData[str(protocol)] = {}
for params in dataFile:
if dataFile[params].size > 1:
self.visstimData[str(protocol)][params] = dataFile[params][:]
else:
self.visstimData[str(protocol)][params] = dataFile[params][()]
def getEyeTrackData(self):
expDate,anmID,probeN = self.getExperimentInfo()
dirPath = os.path.join('\\\\allen\\programs\\braintv\\workgroups\\nc-ophys\\corbettb\\Probe',expDate+'_'+anmID,'EyeTrackAnalysis')
if not os.path.isdir(dirPath):
print('could not find '+dirPath)
return
for fileName in os.listdir(dirPath):
protocolName = re.findall('MouseEyeTracker_'+'(.+)'+'_\d{8,8}_\d{6,6}_analysis',fileName)[0]
protocolIndex = self.getProtocolIndex(protocolName)
protocol = str(protocolIndex)
eyeDataFile = h5py.File(os.path.join(dirPath,fileName))
frameTimes = eyeDataFile['frameTimes'][:]
if len(self.TTL[protocol])>0:
camExposingSamples = self.TTL[protocol]['CamExposing']['rising']
camSavingSamples = self.TTL[protocol]['CamSaving']['rising']
firstFrameSample = camExposingSamples[np.where(camExposingSamples<camSavingSamples[0])[0][-1]]
frameSamples = (frameTimes*self.sampleRate+firstFrameSample).astype(int)
else:
kwdFile = h5py.File(self.kwdFileList[protocolIndex])
thresh = 10000
camExposing,camSaving = kwdFile['recordings']['0']['data'][:,[self.camExposingChannel,self.camSavingChannel]].T
camExposingSamples = np.where(np.logical_and(camExposing[:-1]<=thresh,camExposing[1:]>thresh))[0]+1
camSavingSamples = np.where(np.logical_and(camSaving[:-1]<=thresh,camSaving[1:]>thresh))[0]+1
# frameSamples = camExposingSamples[np.searchsorted(camExposingSamples,camSavingSamples)-1]
firstFrameIndex = np.where(camExposingSamples<camSavingSamples[0])[0][-1]
frameSampleIndex = firstFrameIndex+np.concatenate(([0],np.cumsum(np.round(np.diff(frameTimes)*60)).astype(int)))
frameSamples = camExposingSamples[frameSampleIndex[frameSampleIndex<camExposingSamples.size]]
self.behaviorData[protocol]['eyeTracking'] = {'samples':frameSamples,'frameTimes':frameTimes}
for param in ('pupilArea','pupilX','pupilY','negSaccades','posSaccades'):
self.behaviorData[protocol]['eyeTracking'][param] = eyeDataFile[param][:]
def alignFramesToDiode(self, frameSampleAdjustment = None, plot = False, protocol=0):
if frameSampleAdjustment is None:
self._frameSampleAdjustment = np.round((4.5/60.0) * self.sampleRate)
thresh = 10000
visStimOn = self._d[protocol]['data'][:,self.visStimOnChannel]
self.visstimData[str(protocol)]['frameSamples'] = np.where(np.logical_and(visStimOn[:-1]<thresh,visStimOn[1:]>thresh))[0]+1+self._frameSampleAdjustment
# self.visstimData[protocol]['frameSamples'] = (self.TTL[protocol]['VisstimOn']['falling'] + self._frameSampleAdjustment).astype(int)
if plot:
plt.figure()
plt.plot(self.data[str(protocol)]['data'][:self.visstimData[str(protocol)]['frameSamples'][10], self.diodeChannel])
plt.plot(self.visstimData[str(protocol)]['frameSamples'][:10], np.ones(10) * np.max(self.data[str(protocol)]['data'][:self.visstimData[str(protocol)]['frameSamples'][10], self.diodeChannel]), 'go')
plt.figure()
plt.plot(self.data[str(protocol)]['data'][self.visstimData[str(protocol)]['frameSamples'][-10]:, self.diodeChannel])
plt.plot(self.visstimData[str(protocol)]['frameSamples'][-10:] - self.visstimData[str(protocol)]['frameSamples'][-10], np.ones(10) * np.max(self.data[str(protocol)]['data'][self.visstimData[str(protocol)]['frameSamples'][-10]:, self.diodeChannel]), 'go')
def mapChannels(self):
f = open(self.channelMapFile, 'r')
fdict = json.load(f)
self.channelMapping = np.array(fdict['0']['mapping'])
# self.channelMapping = self.channelMapping[np.where(self.channelMapping > 0)] - 1
self.channelMapping = self.channelMapping - 1
def decodeWheel(self, wheelData, kernelLength = 0.5, wheelSampleRate = 60.0):
sampleRate = wheelSampleRate
wheelData = wheelData - np.min(wheelData)
wheelData = 2*np.pi*wheelData/np.max(wheelData)
smoothFactor = sampleRate/60.0
angularWheelData = np.arctan2(np.sin(wheelData), np.cos(wheelData))
angularWheelData = np.convolve(angularWheelData, np.ones(int(smoothFactor)), 'same')/smoothFactor
artifactThreshold = (100.0/sampleRate)/7.6 #reasonable bound for how far (in radians) a mouse could move in one sample point (assumes top speed of 100 cm/s)
angularDisplacement = (np.diff(angularWheelData) + np.pi)%(2*np.pi) - np.pi
angularDisplacement[np.abs(angularDisplacement) > artifactThreshold ] = 0
wheelData = np.convolve(angularDisplacement, np.ones(int(kernelLength*sampleRate)), 'same')/(kernelLength*sampleRate)
wheelData *= 7.6*sampleRate
wheelData = np.insert(wheelData, 0, wheelData[0])
return wheelData
def filterChannel(self, chan, cutoffFreqs, protocol=0):
Wn = np.array(cutoffFreqs)/(self.sampleRate/2)
b,a = scipy.signal.butter(4, Wn, btype='bandpass')
return scipy.signal.filtfilt(b, a, self.data[str(protocol)]['data'][:, chan])
def thresholdChannel(self, chan, threshold, direction = -1, refractory = None, filterFreqs = None, protocol=0):
if filterFreqs is not None:
data = direction * self.filterChannel(chan, filterFreqs)
else:
data = direction * self.data[str(protocol)]['data'][:, chan]
threshold = direction * threshold
spikeTimes = np.array(np.where(data > threshold)[0])
if refractory is None:
refractory = 1.0/self.sampleRate
if spikeTimes.size > 0:
ISI = np.diff(spikeTimes)
goodISI = np.array(np.where(ISI > refractory*self.sampleRate)[0]) + 1
goodISI = np.insert(goodISI, 0, 0)
spikeTimes = spikeTimes[goodISI]
return spikeTimes
def computeFiringRate(self, spikeTimes, kernelLength = 0.05, protocol=0):
fr = np.zeros(self._d[protocol]['numSamples'])
fr[spikeTimes] = 1
fr = np.convolve(fr, np.ones(kernelLength*self.sampleRate), 'same')/(kernelLength)
return fr
def triggeredAverage(self, dataToAlign, alignmentPoints, win = [0.1, 0.1], sampleRate = None):
if sampleRate is None:
sampleRate = self.sampleRate
aligned = np.full([sampleRate*(win[0] + win[1]), len(alignmentPoints)], np.nan)
for index, point in enumerate(alignmentPoints):
try:
aligned[:, index] = dataToAlign[point - win[0]*sampleRate : point + win[1]*sampleRate]
except:
continue
return aligned
def triggeredSDF(self, units, protocol, triggerPoints, win=[-0.5, 1.0], sdfSampInt = 0.001, appendToUnitDict=False):
units, unitsYPos = self.getOrderedUnits(units)
winSamples = np.array(win)*self.sampleRate
sdf=[]
for u in units:
spikes = self.units[u]['times'][str(protocol)]
usdf, time = self.getSDF(spikes, triggerPoints + winSamples[0], np.diff(winSamples), sampInt=sdfSampInt, avg=True)
sdf.append(usdf)
if appendToUnitDict:
self.units[u][self.getProtocolLabel(protocol)] = {'_sdf': usdf, '_sdfTime': time}
return np.array(sdf), time
def findStatToRunPoints(self, protocol, runThresh=1, statThresh=1, window=2.0, wheelSampleRate=60, refractoryPeriod=5):
if 'running' not in self.behaviorData[str(protocol)]:
print('Could not find running data for this protocol')
return
w = self.behaviorData[str(protocol)]['running']
if np.mean(w) < 0:
w = -w
window = int(window*wheelSampleRate)
srt =[np.logical_and(np.mean(w[i:i+window]) > runThresh, all(w[i-window:i] < statThresh)) for i in np.arange(window, w.size-window)]
srt = np.array(srt)
srt = np.concatenate((np.array([False]*window), srt, np.array([False]*window)))
srt = np.where([np.logical_and(srt[i], not any(srt[i-refractoryPeriod:i])) for i in np.arange(refractoryPeriod, srt.size)])[0] + refractoryPeriod
for i,_ in enumerate(srt):
if w[srt[i]] > runThresh:
while w[srt[i]] > runThresh:
srt[i] -= 1
else:
while w[srt[i]] < runThresh:
srt[i] += 1
srt *= int(self.sampleRate/wheelSampleRate)
self.behaviorData[str(protocol)]['statToRunPoints'] = srt
def runTriggeredAverage(self, units=None, protocol=None, win=[-0.5, 1.0], runThresh=1, statThresh=1, refractoryPeriod=5, plot=True):
units, unitsYPos = self.getOrderedUnits(units)
if protocol is None:
protocol = range(len(self.kwdFileList))
elif not isinstance(protocol,list):
protocol = [protocol]
winSamples = np.array(win)*self.sampleRate
sdf = []
for u in units:
unitSDF = []
for pro in protocol:
if 'statToRunPoints' not in self.behaviorData[str(pro)]:
self.findStatToRunPoints(pro)
spikes = self.units[u]['times'][str(pro)]
rta, rtaTime = self.getSDF(spikes, self.behaviorData[str(pro)]['statToRunPoints'] + winSamples[0], np.diff(winSamples), avg=False)
unitSDF.append(rta)
unitSDF = np.array(unitSDF)
sdf.append(np.nanmean(np.concatenate(unitSDF), axis=0))
sdf = np.array(sdf)
numEvents = 0
wdTotal = []
for pro in protocol:
ps = self.behaviorData[str(pro)]['statToRunPoints']
ps = (ps/500).astype(np.int)
numEvents += len(ps)
rWin = [-win[0], win[1]]
wd = self.behaviorData[str(pro)]['running']
tr = self.triggeredAverage(-wd, ps, win=rWin, sampleRate=60.)
wdTotal.append(tr)
wdTotal = np.nanmean(np.concatenate(wdTotal, axis=1), axis=1)
if plot:
if len(units) > 1:
self.plotSDF1Axis(sdf, rtaTime)
a = plt.gca()
a.set_title(str(numEvents) + ' stat to run transitions')
y = a.get_ylim()
a.plot([rWin[0]]*2, [y[0], y[1]], 'k--')
plt.figure(facecolor='w')
plt.plot(rtaTime, np.nanmean(sdf, axis=0))
plt.plot(np.linspace(0, rtaTime[-1], wdTotal.shape[0]), wdTotal)
a = plt.gca()
y = a.get_ylim()
a.plot([rWin[0]]*2, [y[0], y[1]], 'k--')
else:
fig = plt.figure(facecolor='w')
a = fig.add_subplot(2,1,1)
a.plot(rtaTime, sdf[0, :], 'k')
a.set_title(str(numEvents) + ' stat to run transitions')
y = a.get_ylim()
a.plot([rWin[0]]*2, [y[0], y[1]], 'k--')
a2 = fig.add_subplot(2,1,2)
a2.plot(np.linspace(0, rtaTime[-1], wdTotal.shape[0]), wdTotal, 'r')
y = a2.get_ylim()
a2.plot([rWin[0]]*2, [y[0], y[1]], 'k--')
def findSpikesPerTrial(self, trialStarts, trialEnds, spikes):
spikesPerTrial = np.zeros(trialStarts.size)
for trialNum in range(trialStarts.size):
spikesPerTrial[trialNum] = np.count_nonzero(np.logical_and(spikes>=trialStarts[trialNum],spikes<=trialEnds[trialNum]))
return spikesPerTrial
def findRF(self, units=None, adjustForPupil=False, usePeakResp=True, sigma=1, plot=True, minLatency=0.05, maxLatency=0.15, trials=None, protocol=None, fit=True, saveTag='', useCache=False, cmap='Blues'):
units, unitsYPos = self.getOrderedUnits(units)
if protocol is None:
protocol = self.getProtocolIndex('sparseNoise')
protocol = str(protocol)
trialStartFrame = self.visstimData[protocol]['stimStartFrames']
trialEndFrame = trialStartFrame + self.visstimData[protocol]['trialDuration']
lastFullTrial = np.where(trialEndFrame<self.visstimData[protocol]['frameSamples'].size)[0][-1]
if trials is None:
trials = np.arange(lastFullTrial+1)
elif len(trials)<1:
return
else:
trials = np.array(trials)
trials = trials[trials<=lastFullTrial]
stimStartFrames = self.visstimData[protocol]['stimStartFrames'][trials]
stimStartSamples = self.visstimData[protocol]['frameSamples'][stimStartFrames]
# if trials is None:
# trials = np.arange(self.visstimData[protocol]['stimStartFrames'].size-1)
# else:
# trials = np.array(trials)
#
# if len(trials) == 0:
# return
minLatencySamples = minLatency*self.sampleRate
maxLatencySamples = maxLatency*self.sampleRate
posHistory = np.copy(self.visstimData[protocol]['boxPositionHistory'][trials])
xpos = np.unique(posHistory[:,0])
ypos = np.unique(posHistory[:,1])
pixPerDeg = self.visstimData[str(protocol)]['pixelsPerDeg']
elev, azim = ypos/pixPerDeg, xpos/pixPerDeg
gridExtent = self.visstimData[protocol]['gridBoundaries']
rfArea = np.full((len(units),2),np.nan)
adjustX = np.zeros_like(stimStartSamples).astype(float)
adjustY = np.zeros_like(stimStartSamples).astype(float)
eyeWindow = int(self.sampleRate*self.visstimData[protocol]['trialDuration']/60.0)
gridSpacing = self.visstimData[protocol]['gridSpacing']
if adjustForPupil:
if protocol not in self.behaviorData or 'eyeTracking' not in self.behaviorData[protocol]:
print('no eye tracking data')
if not plot:
return rfArea
px = self.behaviorData[protocol]['eyeTracking']['pupilX']
py = self.behaviorData[protocol]['eyeTracking']['pupilY']
eyeSamples = self.behaviorData[protocol]['eyeTracking']['samples']
for it, t in enumerate(trials):
trialEyeFrames = np.logical_and(eyeSamples >= stimStartSamples[t], eyeSamples < stimStartSamples[t] + eyeWindow)
# if np.nanmedian(px[trialEyeFrames]) < 25 or np.nanmedian(px[trialEyeFrames])>3:
# posHistory[t,0] = np.nan
# posHistory[t,1] = np.nan
if np.isnan(np.nanmedian(px[trialEyeFrames])):
# posHistory[t,0] = np.nan
# posHistory[t,1] = np.nan
pass
else:
adjustX[it] = np.round((np.nanmedian(px) - np.nanmedian(px[trialEyeFrames]))/gridSpacing)
adjustY[it] = np.round((np.nanmedian(py) - np.nanmedian(py[trialEyeFrames]))/gridSpacing)
currentXPosIndex = np.where(xpos==posHistory[t, 0])[0][0]
currentYPosIndex = np.where(ypos==posHistory[t, 1])[0][0]
newXindex = currentXPosIndex + adjustX[it]
newYindex = currentYPosIndex + adjustY[it]
if min(newXindex, newYindex)>=0 and np.logical_and(newXindex <= xpos.size-1, newYindex <= ypos.size-1):
posHistory[t,0] = xpos[newXindex]
posHistory[t,1] = ypos[newYindex]
else:
posHistory[t,0] = np.nan
posHistory[t,1] = np.nan
colorHistory = self.visstimData[protocol]['boxColorHistory'][trials, 0]
boxSizeHistory = self.visstimData[protocol]['boxSizeHistory'][trials]/pixPerDeg
boxSize = np.unique(boxSizeHistory)
sizeTuningOn = np.full((len(units),boxSize.size),np.nan)
sizeTuningOff = np.copy(sizeTuningOn)
sizeTuningSize = boxSize.copy()
sizeTuningLabel = boxSize.copy()
if any(boxSize>100):
sizeTuningSize[boxSize>100] = 50
sizeTuningLabel = list(sizeTuningLabel)
sizeTuningLabel[-1] = 'full'
boxSize = boxSize[boxSize<100]
onVsOff = np.full(len(units),np.nan)
respLatency = np.full((len(units),2),np.nan)
respNormArea = np.copy(respLatency)
respHalfWidth = np.copy(respLatency)
sdfSampInt = 0.001
sdfSigma = 0.01
sdfSamples = minLatencySamples+2*maxLatencySamples
gaussianKernel = Gaussian2DKernel(stddev=sigma)
if fit:
onFit = np.full((len(units),len(boxSize),7),np.nan)
offFit = np.copy(onFit)
onFitError = np.full((len(units),len(boxSize)),np.nan)
offFitError = np.copy(onFitError)
if plot:
fig = plt.figure(figsize=(10,10*len(units)),facecolor='w')
gs = gridspec.GridSpec(len(units)*(len(boxSize)+1),4)
for uindex, unit in enumerate(units):
spikes = self.units[unit]['times'][protocol]
if spikes.size<1:
continue
onResp = np.full((len(boxSize),ypos.size,xpos.size),np.nan)
offResp = np.copy(onResp)
sdfOn = np.zeros((len(boxSize),ypos.size,xpos.size,int(round(sdfSamples/self.sampleRate/sdfSampInt))))
sdfOff = np.zeros_like(sdfOn)
for sizeInd,size in enumerate(boxSize):
boxSizeTrials = boxSizeHistory==size
for i,y in enumerate(ypos):
for j,x in enumerate(xpos):
posTrials = np.logical_and(posHistory[:, 1] == y,posHistory[:, 0] == x)
posOnTrials = np.logical_and(posTrials, colorHistory == 1)
posOffTrials = np.logical_and(posTrials, colorHistory == -1)
posOnSamples = stimStartSamples[np.logical_and(posOnTrials,boxSizeTrials)]
if any(posOnSamples):
onResp[sizeInd,i,j] = np.mean(self.findSpikesPerTrial(posOnSamples+minLatencySamples,posOnSamples+maxLatencySamples,spikes))
sdfOn[sizeInd,i,j,:],_ = self.getSDF(spikes,posOnSamples-minLatencySamples,sdfSamples,sdfSigma,sdfSampInt)
posOffSamples = stimStartSamples[np.logical_and(posOffTrials,boxSizeTrials)]
if any(posOffSamples):
offResp[sizeInd,i,j] = np.mean(self.findSpikesPerTrial(posOffSamples+minLatencySamples,posOffSamples+maxLatencySamples,spikes))
sdfOff[sizeInd,i,j,:],sdfTime = self.getSDF(spikes,posOffSamples-minLatencySamples,sdfSamples,sdfSigma,sdfSampInt)
# convert spike count to spike rate
onResp /= maxLatency-minLatency
offResp /= maxLatency-minLatency
# get full field flash resp
fullFieldOnResp = fullFieldOffResp = np.nan
fullFieldTrials = boxSizeHistory>100
if any(fullFieldTrials):
ffOnSamples = stimStartSamples[np.logical_and(fullFieldTrials,colorHistory==1)]
if any(ffOnSamples):
fullFieldOnResp = np.mean(self.findSpikesPerTrial(ffOnSamples+minLatencySamples,ffOnSamples+maxLatencySamples,spikes))
fullFieldOnResp /= maxLatency-minLatency
fullFieldOnSDF,_ = self.getSDF(spikes,ffOnSamples-minLatencySamples,sdfSamples,sdfSigma,sdfSampInt)
ffOffSamples = stimStartSamples[np.logical_and(fullFieldTrials,colorHistory==-1)]
if any(ffOffSamples):
fullFieldOffResp = np.mean(self.findSpikesPerTrial(ffOffSamples+minLatencySamples,ffOffSamples+maxLatencySamples,spikes))
fullFieldOffResp /= maxLatency-minLatency
fullFieldOffSDF,_ = self.getSDF(spikes,ffOffSamples-minLatencySamples,sdfSamples,sdfSigma,sdfSampInt)
# optionally use peak resp instead of mean rate
inAnalysisWindow = np.logical_and(sdfTime>minLatency*2,sdfTime<minLatency+maxLatency)
if usePeakResp:
onResp = np.nanmax(sdfOn[:,:,:,inAnalysisWindow],axis=3)
offResp = np.nanmax(sdfOff[:,:,:,inAnalysisWindow],axis=3)
if not np.isnan(fullFieldOnResp):
fullFieldOnResp = np.nanmax(fullFieldOnSDF[inAnalysisWindow])
if not np.isnan(fullFieldOffResp):
fullFieldOffResp = np.nanmax(fullFieldOffSDF[inAnalysisWindow])
# calculate size tuning
sizeTuningOn[uindex,:boxSize.size] = np.nanmax(np.nanmax(onResp,axis=2),axis=1)
sizeTuningOff[uindex,:boxSize.size] = np.nanmax(np.nanmax(offResp,axis=2),axis=1)
if any(fullFieldTrials):
sizeTuningOn[uindex,-1] = fullFieldOnResp
sizeTuningOff[uindex,-1] = fullFieldOffResp
# estimate spontRate using random trials and interval 0:minLatency
nTrialTypes = np.unique(posHistory[~np.isnan(posHistory)]).size*boxSize.size*2
nTrials = int(np.count_nonzero(boxSizeHistory<100)/nTrialTypes)
nreps = 200
spontPeakDist = np.zeros(nreps)
spontCountDist = np.zeros(nreps)
for ind in range(nreps):
randTrials = np.random.choice(np.arange(trials.size),nTrials)
spontPeakDist[ind] = np.max(self.getSDF(spikes,stimStartSamples[randTrials],minLatencySamples,sdfSigma,sdfSampInt))
spontCountDist[ind] = np.mean(self.findSpikesPerTrial(stimStartSamples[randTrials],stimStartSamples[randTrials]+minLatencySamples,spikes))
spontRateDist = spontPeakDist if usePeakResp else spontCountDist/minLatency
spontRateMean = spontRateDist.mean()
spontRateStd = spontRateDist.std()
# determine which box sizes elicited significant responses
respThresh = spontRateMean+5*spontRateStd
hasOnResp = np.zeros(len(boxSize),dtype=bool)
hasOffResp = np.copy(hasOnResp)
for sizeInd,_ in enumerate(boxSize):
hasOnResp[sizeInd] = np.nanmax(onResp[sizeInd])>respThresh
hasOffResp[sizeInd] = np.nanmax(offResp[sizeInd])>respThresh
# filter responses for each box size
onRespRaw = onResp.copy()
offRespRaw = offResp.copy()
for resp in (onResp,offResp):
for sizeInd,_ in enumerate(boxSize):
resp[sizeInd] = convolve(resp[sizeInd], gaussianKernel, boundary='extend')
# fit significant responses
if fit:
maxOffGrid = 10
for sizeInd,_ in enumerate(boxSize):
for hasResp,resp,fitParams,fitError in zip((hasOnResp[sizeInd],hasOffResp[sizeInd]),(onResp[sizeInd],offResp[sizeInd]),(onFit[uindex,sizeInd],offFit[uindex,sizeInd]),(onFitError[uindex],offFitError[uindex])):
if hasResp and not np.any(np.isnan(resp)):
# params: x0 , y0, sigX, sigY, theta, amplitude, offset
i,j = np.unravel_index(np.argmax(resp),resp.shape)
sigmaGuess = (azim[1]-azim[0])*0.5*np.sqrt(np.count_nonzero(resp>resp.min()+0.5*(resp.max()-resp.min())))
initialParams = (azim[j],elev[i],sigmaGuess,sigmaGuess,0,resp.max(),np.percentile(resp,10))
fitResult,rmse = fitRF(azim,elev,resp,initialParams,maxOffGrid)
if fitResult is not None:
fitParams[:] = fitResult
fitError[sizeInd] = rmse
# compare on and off resp magnitude (max across all box sizes)
onMax = np.nanmax(onResp)
offMax = np.nanmax(offResp)
onVsOff[uindex] = (onMax-offMax)/(onMax+offMax)
# calculate response latency and duration
# SDF time is minLatency before stim onset through 2*maxLatency
# Hence stim starts at minLatency and analysisWindow starts at 2*minLatency
# Search analysisWindow for peak but allow searching outside analaysisWindow for halfMax
sdfMaxInd = np.zeros((2,4),dtype=int)
halfMaxInd = np.zeros((2,2),dtype=int)
respLatencyInd = np.zeros(2,dtype=int)
latencyThresh = spontPeakDist.mean()+5*spontPeakDist.std()
for i,sdf in enumerate((sdfOn,sdfOff)):
if not np.any(sdf[:,:,:,inAnalysisWindow]>latencyThresh):
continue
sdfMaxInd[i,:] = np.unravel_index(np.nanargmax(sdf[:,:,:,inAnalysisWindow]),sdf[:,:,:,inAnalysisWindow].shape)
sdfMaxInd[i,3] += np.where(inAnalysisWindow)[0][0]
bestSDF = np.copy(sdf[sdfMaxInd[i,0],sdfMaxInd[i,1],sdfMaxInd[i,2],:])
maxInd = sdfMaxInd[i,3]
# find last thresh cross before peak for latency
lastCrossing = np.where(bestSDF[:maxInd]<latencyThresh)[0]
respLatencyInd[i] = lastCrossing[-1]+1 if any(lastCrossing) else np.where(inAnalysisWindow)[0][0]
respLatency[uindex,i] = respLatencyInd[i]*sdfSampInt-minLatency
# subtract min for calculating resp duration
bestSDF -= np.min(bestSDF[inAnalysisWindow])
# respNormArea = (area under SDF in analysisWindow) / (peak * analysisWindow duration)
respNormArea[uindex,i] = np.trapz(bestSDF[inAnalysisWindow])*sdfSampInt/(bestSDF[maxInd]*(maxLatency-minLatency))
# find last half-max cross before peak
halfMax = 0.5*bestSDF[maxInd]
preHalfMax = np.where(bestSDF[:maxInd]<halfMax)[0]
halfMaxInd[i,0] = preHalfMax[-1]+1 if any(preHalfMax) else np.where(inAnalysisWindow)[0][0]
# find first half-max cross after peak
postHalfMax = np.where(bestSDF[maxInd:]<halfMax)[0]
halfMaxInd[i,1] = maxInd+postHalfMax[0]-1 if any(postHalfMax) else bestSDF.size-1
respHalfWidth[uindex,i] = (halfMaxInd[i,1]-halfMaxInd[i,0])*sdfSampInt
# cache results
self.units[unit]['sparseNoise' + saveTag] = {'gridExtent': gridExtent,
'elev': elev,
'azim': azim,
'boxSize': boxSize,
'onRespRaw': onRespRaw,
'offRespRaw': offRespRaw,
'onResp': onResp,
'offResp': offResp,
'spontRateMean': spontRateMean,
'spontRateStd': spontRateStd,
'onFit': onFit[uindex],
'offFit': offFit[uindex],
'onFitError': onFitError[uindex],
'offFitError': offFitError[uindex],
'sizeTuningOn': sizeTuningOn[uindex],
'sizeTuningOff': sizeTuningOff[uindex],
'onVsOff': onVsOff[uindex],
'respLatency': respLatency[uindex],
'respNormArea': respNormArea[uindex],
'respHalfWidth': respHalfWidth[uindex],
'trials': trials,
'_sdfOn': sdfOn,
'_sdfOff': sdfOff,
'_sdfTime': sdfTime}
if plot:
# sdfs and rf map
maxVal = max(np.nanmax(onResp), np.nanmax(offResp))
minVal = min(np.nanmin(onResp), np.nanmin(offResp))
sdfMax = max(np.nanmax(sdfOn),np.nanmax(sdfOff))
spacing = 0.2
sdfXMax = sdfTime[-1]
sdfYMax = sdfMax
for sizeInd,size in enumerate(boxSize):
for onOffInd,(sdf,hasResp,resp,fitParams) in enumerate(zip((sdfOn[sizeInd],sdfOff[sizeInd]),(hasOnResp[sizeInd],hasOffResp[sizeInd]),(onResp[sizeInd],offResp[sizeInd]),(onFit[uindex,sizeInd],offFit[uindex,sizeInd]))):
onOffTitle = 'Off' if onOffInd else 'On'
row = uindex*(len(boxSize)+1)+sizeInd
col = onOffInd*2
ax = fig.add_subplot(gs[row,col])
x = 0
y = 0
for i,_ in enumerate(ypos):
for j,_ in enumerate(xpos):
ax.plot(x+sdfTime,y+sdf[i,j,:],color='k')
if not np.isnan(respLatency[uindex,onOffInd]) and all((sizeInd,i,j)==sdfMaxInd[onOffInd,:3]):
ax.plot(x+sdfTime[halfMaxInd[onOffInd]],y+sdf[i,j,halfMaxInd[onOffInd]],color='r',linewidth=2)
ax.plot(x+sdfTime[respLatencyInd[onOffInd]],y+sdf[i,j,respLatencyInd[onOffInd]],'bo')
x += sdfXMax*(1+spacing)
x = 0
y += sdfYMax*(1+spacing)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
if onOffInd==0 and sizeInd==len(boxSize)-1:
ax.set_xticks([minLatency,minLatency+0.1])
ax.set_xticklabels(['','100 ms'])
ax.set_yticks([0,int(sdfMax)])
else:
ax.set_xticks([])
ax.set_yticks([])
ax.set_xlim([-sdfXMax*spacing,sdfXMax*(1+spacing)*xpos.size])
ax.set_ylim([-sdfYMax*spacing,sdfYMax*(1+spacing)*ypos.size])
if onOffInd==0:
ax.set_ylabel(str(int(size))+' deg',fontsize='medium')
if sizeInd==0:
ax.set_title('Unit '+str(unit),fontsize='medium')
ax = fig.add_subplot(gs[row,col+1])
im = ax.imshow(resp, cmap=cmap, clim=(minVal,maxVal), interpolation = 'none', origin = 'lower', extent = [gridExtent[0], gridExtent[2], gridExtent[1], gridExtent[3]])
if not np.all(np.isnan(fitParams)):
ax.plot(fitParams[0],fitParams[1],'kx',markeredgewidth=2)
fitX,fitY = getEllipseXY(*fitParams[:-2])
ax.plot(fitX,fitY,'k',linewidth=2)
ax.set_xlim(gridExtent[[0,2]]-0.5)
ax.set_ylim(gridExtent[[1,3]]-0.5)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xticks([])
ax.set_yticks([])
cb = plt.colorbar(im, ax=ax, fraction=0.05, shrink=0.5, pad=0.04)
cb.ax.tick_params(length=0,labelsize='x-small')
cb.set_ticks([math.ceil(minVal),int(maxVal)])
if sizeInd==0:
ax.set_title(onOffTitle,fontsize='medium')
if len(boxSize)>1:
ax = fig.add_subplot(gs[row+1,2])
ax.plot(sizeTuningSize,sizeTuningOn[uindex],'r')
ax.plot(sizeTuningSize,sizeTuningOff[uindex],'b')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlim([0,boxSize[-1]+boxSize[0]])
ax.set_ylim([0,1.05*max(np.nanmax(sizeTuningOn[uindex]),np.nanmax(sizeTuningOff[uindex]))])
ax.set_xticks(sizeTuningSize)
ax.set_xticklabels(sizeTuningLabel)
ax.set_xlabel('Size',fontsize='small')
ax.set_ylabel('Spikes/s',fontsize='small')
sizeInd = np.argmin(np.absolute(boxSize-10))
rfArea[:,0] = np.pi*np.prod(onFit[:,sizeInd,2:4],axis=1)
rfArea[:,1] = np.pi*np.prod(offFit[:,sizeInd,2:4],axis=1)
if adjustForPupil:
return rfArea
if plot and len(units)>1:
# population plots
# size tuning
if len(boxSize)>1:
plt.figure(facecolor='w')
gspec = gridspec.GridSpec(2,2)
for ind,(sizeResp,onOrOff) in enumerate(zip((sizeTuningOn,sizeTuningOff),('On','Off'))):
ax = plt.subplot(gspec[0,ind])
sizeRespNorm = sizeResp/np.nanmax(sizeResp,axis=1)[:,None]
sizeRespMean = np.nanmean(sizeRespNorm,axis=0)
sizeRespStd = np.nanstd(sizeRespNorm,axis=0)
ax.plot(sizeTuningSize,sizeRespMean,'k')
plt.fill_between(sizeTuningSize,sizeRespMean+sizeRespStd,sizeRespMean-sizeRespStd,color='0.6',alpha=0.3)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlim([0,boxSize[-1]+boxSize[0]])
ax.set_ylim([0,1.1])
ax.set_xticks(sizeTuningSize)
ax.set_yticks([0,0.5,1])
ax.set_xticklabels([])
if ind==0:
ax.set_ylabel('Norm Spikes/s',fontsize='medium')
else:
ax.set_yticklabels([])
ax.set_title(onOrOff,fontsize='large')
ax = plt.subplot(gspec[1,ind])
sizeRespNorm[sizeRespNorm<1] = 0
bestSizeCount = np.nansum(sizeRespNorm,axis=0)
ax.bar(sizeTuningSize,bestSizeCount)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlim([0,boxSize[-1]+boxSize[0]])
ax.set_xticks(sizeTuningSize)
ax.set_xticklabels(sizeTuningLabel)
ax.set_xlabel('Size',fontsize='medium')
if ind==0:
ax.set_ylabel('Best Size Count',fontsize='medium')
# onVsOff, respLatency, respNormArea, respHalfWidth, and rfArea
for i,(data,bins,label) in enumerate(zip((respLatency,respNormArea,rfArea),
(np.arange(0,0.275,0.025),np.arange(0,1.1,0.1),np.arange(0,4400,400)),
('Resp Latency','Resp Norm Area','RF Area'))):
plt.figure(facecolor='w')
for j,title in enumerate(('On','Off')):
ax = plt.subplot(1,2,j+1)
ax.hist(data[:,j][~np.isnan(data[:,j])],bins)
ax.set_xlim(bins[[0,-1]])
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlabel(label,fontsize='medium')
ax.set_title(title,fontsize='large')
if j==0:
ax.set_ylabel('# Units',fontsize='medium')
if fit:
# RF centers
plt.figure(facecolor='w')
ax = plt.subplot(1,1,1)
ax.plot(gridExtent[[0,2,2,0,0]],gridExtent[[1,1,3,3,1]],color='0.6')
ax.plot(onFit[:,sizeInd,0],onFit[:,sizeInd,1],'o',markeredgecolor='r',markerfacecolor='none')
ax.plot(offFit[:,sizeInd,0],offFit[:,sizeInd,1],'o',markeredgecolor='b',markerfacecolor='none')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlim(gridExtent[[0,2]]+[-maxOffGrid,maxOffGrid])
ax.set_ylim(gridExtent[[1,3]]+[-maxOffGrid,maxOffGrid])
ax.set_xlabel('Azimuth',fontsize='medium')
ax.set_ylabel('Elevation',fontsize='medium')
ax.set_title('RF center (red = on, blue = off)',fontsize='large')
# comparison of RF and probe position
plt.figure(facecolor='w')
gspec = gridspec.GridSpec(2,2)
unitsYPos = np.array(unitsYPos)
xlim = np.array([min(unitsYPos)-10,max(unitsYPos)+10])
for j,(rfCenters,onOrOff) in enumerate(zip((onFit[:,sizeInd,:2],offFit[:,sizeInd,:2]),('On','Off'))):
for i,azimOrElev in enumerate(('Azimuth','Elevation')):
ax = plt.subplot(gspec[i,j])
hasRF = np.logical_not(np.isnan(rfCenters[:,i]))
if np.count_nonzero(hasRF)>1:
# linFit = (slope, intercept, r-value, p-value, stderror)
linFit = scipy.stats.linregress(unitsYPos[hasRF],rfCenters[hasRF,i])
ax.plot(xlim,linFit[0]*xlim+linFit[1],color='0.6')
ax.text(0.5,0.95,'$\mathregular{r^2}$ = '+str(round(linFit[2]**2,2))+', p = '+str(round(linFit[3],2)),
transform=ax.transAxes,horizontalalignment='center',verticalalignment='bottom',color='0.6')
ax.plot(unitsYPos,rfCenters[:,i],'ko',markerfacecolor='none')
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax.set_xlim(xlim)
if i==0:
ax.set_title(onOrOff,fontsize='large')
ax.set_ylim(gridExtent[[0,2]]+[-maxOffGrid,maxOffGrid])
ax.set_xticklabels([])
else:
ax.set_xlabel('Probe Y Pos',fontsize='medium')
ax.set_ylim(gridExtent[[1,3]]+[-maxOffGrid,maxOffGrid])
if j==0:
ax.set_ylabel(azimOrElev,fontsize='medium')
else:
ax.set_yticklabels([])
def analyzeFlash(self, units=None, trials=None, protocol=None, responseLatency=0.25, plot=True, sdfSigma=0.005, useCache=False, saveTag=''):
units, unitsYPos = self.getOrderedUnits(units)
if protocol is None:
label = 'flash'
protocol = self.getProtocolIndex(label)
protocol = str(protocol)
if trials is None:
trials = np.arange(self.visstimData[str(protocol)]['stimStartFrames'].size-1)
else:
trials = np.array(trials)
if len(trials) == 0:
return
if plot:
plt.figure(figsize =(10, 4*len(units)),facecolor='w')
gs = gridspec.GridSpec(len(units)+1, 2)
trialStartFrames = self.visstimData[protocol]['stimStartFrames'][trials]
trialDuration = self.visstimData[protocol]['stimDur']
trialStartSamples = self.visstimData[protocol]['frameSamples'][trialStartFrames]
trialEndSamples = self.visstimData[protocol]['frameSamples'][trialStartFrames + trialDuration]
lumValues = np.unique(self.visstimData[protocol]['stimHistory'])
trialLumValues = self.visstimData[protocol]['stimHistory'][trials]
preTime = self.visstimData[protocol]['grayDur']/self.visstimData[protocol]['frameRate']
stimTime = self.visstimData[protocol]['stimDur']/self.visstimData[protocol]['frameRate']
postTime = preTime
sdfSamples = round((preTime+stimTime+postTime)*self.sampleRate)
sdfSampInt = 0.001
onLatencies = []
offLatencies = []
for uindex, unit in enumerate(units):
sdf = np.full((lumValues.size,round(sdfSamples/self.sampleRate/sdfSampInt)),np.nan)
sdfOn = []
sdfOff = []
spikes = self.units[str(unit)]['times'][protocol]
for lumindex, lum in enumerate(lumValues):
lumTrials = np.where(trialLumValues==lum)[0]
if len(lumTrials)>0:
sdf[lumindex], sdfTime = self.getSDF(spikes, trialStartSamples[lumTrials] - preTime*self.sampleRate, sdfSamples, sigma=sdfSigma)
if lum > 0:
sdfOn.append(sdf[lumindex])
soff, _ = self.getSDF(spikes, trialEndSamples[lumTrials] - preTime*self.sampleRate, sdfSamples, sigma=sdfSigma)
sdfOff.append(soff)
elif lum < 0:
sdfOff.append(sdf[lumindex])
son, _ = self.getSDF(spikes, trialEndSamples[lumTrials] - preTime*self.sampleRate, sdfSamples, sigma=sdfSigma)
sdfOn.append(son)
sdfOn = np.array(sdfOn)
sdfOff = np.array(sdfOff)
sdfMeans = np.array([np.mean(sdfOn, axis=0), np.mean(sdfOff, axis=0)])
baselineStart = 300
baselineEnd = 500
baselines = np.mean(sdf[:, baselineStart:baselineEnd], axis = 0)
onLatency = np.where(sdfMeans[0, 500:1000] > np.mean(sdfMeans[0, 300:500], axis=0) + 5*np.std(sdfMeans[0, 300:500], axis=0))[0]
onLatency = onLatency[0] if any(onLatency) else None
offLatency = np.where(sdfMeans[1, 500:1000] > np.mean(sdfMeans[1, 300:500], axis=0) + 5*np.std(sdfMeans[1, 300:500], axis=0))[0]
offLatency = offLatency[0] if any(offLatency) else None
if onLatency is not None:
onLatencies.append(onLatency)
if offLatency is not None:
offLatencies.append(offLatency)
self.units[unit]['flash' + saveTag] = {'meanResp': sdf,
'lumValues': lumValues,
'trials': trials}
if plot:
ax = plt.subplot(gs[uindex,0])
ax.tick_params(direction='out',top=False,right=False,labelsize='x-small')
for lumi, lum in enumerate(sdf):
rval = 1 if lumValues[lumi]>0 else 0
bval = 1 if lumValues[lumi]<0 else 0
color = (rval, 0, bval) if np.max([rval, bval])>0 else (1,1,1)
alpha = abs(lumValues[lumi]) if abs(lumValues[lumi])>0 else 0.5
ax.plot(lum, color=color, alpha=alpha)
ax.set_ylabel(str(unit), fontsize='small')
ax2 = plt.subplot(gs[uindex, 1])
ax2.tick_params(direction='out',top=False,right=False,labelsize='x-small')
ax2.plot(np.mean(sdfOn, axis=0), color='r')
ax2.plot(np.mean(sdfOff, axis=0), color='b')
if onLatency is not None:
ax2.plot(onLatency+500, sdfMeans[0, onLatency+500], 'ro')
if offLatency is not None:
ax2.plot(offLatency+500, sdfMeans[1, offLatency+500], 'bo')
if uindex==len(units)-1:
ax.set_xlabel('Time, ms', fontsize='medium')
ax2.set_xlabel('Time, ms', fontsize = 'medium')
else:
ax.tick_params(bottom='off', labelbottom='off')
ax2.tick_params(bottom='off', labelbottom='off')
if plot and len(units)>1:
plt.figure(facecolor='w')
if any(onLatencies):
plt.hist(onLatencies, bins=np.arange(0, 210, 10), color='r')
if any(offLatencies):
plt.hist(offLatencies, bins=np.arange(0, 210, 10), color='b', alpha=0.5)
a = plt.gca()
a.set_xlabel('Latency, ms')
a.set_ylabel('Count')
return sdfMeans
def analyzeGratings(self, units=None, trials=None, responseLatency=0.25, usePeakResp=False, sdfSigma = 0.02, plot=True, protocol=None, protocolType='stf', fit=True, saveTag='', useCache=False):
units, unitsYPos = self.getOrderedUnits(units)
if protocol is None:
if protocolType=='stf':
label = 'gratings'
elif protocolType=='ori':
label = 'gratings_ori'
protocol = self.getProtocolIndex(label)
protocol = str(protocol)
if trials is None:
trials = np.arange(self.visstimData[str(protocol)]['stimStartFrames'].size-1)
else:
trials = np.array(trials)
numFullTrials = self.visstimData[str(protocol)]['stimStartFrames'].size-1
trials = trials[trials<numFullTrials]