-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstructorTools.py
1813 lines (1422 loc) · 80.3 KB
/
constructorTools.py
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
from yamlTools import expYAML, labInfo
import rippleTools
import numpy
import matplotlib.pyplot as plt
import datetime
import os
import time
import h5py
# TOOLS to extract & combine Behavioral Data from *.nev (markers) & *.YAML files into a NWB file
# file format follow YAULAB convention of the task : visual cues + 2 shakers + footbar + eye tracking
version = '0.1.0'
#######################################################################
# SOME DEFAULT PARAMS:
#######################################################################
defaultNoTime = float(labInfo['StimDefaults']['NoTime'])
add2stimDuration = float(labInfo['SecsToAddAccelerometer'][0])
add2stimStop = float(labInfo['AddFirstStimAccelerometer']['Secs'][0])
numTrials2addStopTime = labInfo['AddFirstStimAccelerometer']['trialNum'][0]
tolerancePhotodiode = float(labInfo['MarkerOffsetTolerance']['PhotodiodeON'][0])
add2fixOnset = float(labInfo['SecsToAddPhotodiode'][0])
timeZone = labInfo['LabInfo']['TimeZone']
thresholdReward_mV = float(labInfo['ThresholdReward_mV'])
thresholdFeet_mV = float(labInfo['ThresholdFeet_mV'])
# AnalogIOchannels nomenclature :
# chanName ChanNum
# 'leftCommand': 1,
# 'leftAccelerometer': 2,
# 'rightCommand': 3,
# 'rightAccelerometer': 4,
# 'eyeHorizontal': 5,
# 'pupilDiameter': 6,
# 'leftFoot': 7,
# 'rightFoot': 8,
# 'rewardON': 9,
# 'fixON': 10,
# 'visualON': 11,
# 'leftProbeTEMP': 12,
#
########################################################################################################################
# SOME FUNCTIONS TO PROCESS RIPPLE & YAML DATA
########################################################################################################################
def set_NWBtempdir_environ():
# CONFIRM or ADD TEMPORAL DIR ('NWB_PROCESSOR_TEMPDIR') into the variables of the environment
if not os.environ.get('NWB_PROCESSOR_TEMPDIR'):
os.environ['NWB_PROCESSOR_TEMPDIR'] = os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/NWB_tempdir')
print('NWB_PROCESSOR_TEMPDIR variable was created')
# CONFIRM THAT EXISTS or CREATE THE TEMPORAL DIR ('NWB_PROCESSOR_TEMPDIR')
if not os.path.exists(os.environ.get('NWB_PROCESSOR_TEMPDIR')):
os.mkdir(os.environ.get('NWB_PROCESSOR_TEMPDIR'))
print(' Temporal folder was created ')
def clear_NWBtempdir():
tempdir_path = os.environ.get('NWB_PROCESSOR_TEMPDIR')
if tempdir_path is not None:
# Clear tempDir
tempDir_list = os.listdir(tempdir_path)
for fname in tempDir_list:
tempFile_path = os.path.join(tempdir_path, fname)
if os.path.isfile(tempFile_path):
try:
os.remove(tempFile_path)
except:
print('Warning:\nUnable to delete the file:\n{}\nprobably is still open or in use\n\n'.format(tempFile_path))
##################################################################################################
# Plot a segment of time from an Analog class
def plot_analogEvent(analogIOchannel_cls, stimStartSecs, stimStopSecs):
stimStart_index = analogIOchannel_cls.get_timeIndex([stimStartSecs])[0]
stimStop_index = analogIOchannel_cls.get_timeIndex([stimStopSecs])[0]
analogIOchannel_cls.get_indexTime(range(stimStart_index-100, stimStop_index+100))
tSnippet1 = analogIOchannel_cls.get_indexTime(range(stimStart_index, stimStop_index))
snippet1 = analogIOchannel_cls.get_data(start_index=stimStart_index, index_count=stimStop_index-stimStart_index)
fig, axs1 = plt.subplots()
axs1.set_title(analogIOchannel_cls.get_info()['chanName'])
axs1.plot(tSnippet1, snippet1, color='C0')
axs1.set_xlabel("time (s)")
axs1.set_ylabel("Voltage")
plt.show()
##################################################################################################
# Extract a TimeSeries from Ripple (nsFile) as a dataset ("hdf5" file).
# First dimension is Time, all entities to be extracted must match on time-dimension (e.g., sampleRate)
# It will concatenate all the entityIndexes as columns
def temp_TimeSeries_hdf5(nsFile, entityIndexes, tempName, itemCount,
dtype='float',
compression="gzip",
compression_opts=4,
chunks=True,
verbose=True):
# Get Temporal folder information
tempFolder = os.environ.get('NWB_PROCESSOR_TEMPDIR')
if tempFolder is None:
set_NWBtempdir_environ()
tempFolder = os.environ.get('NWB_PROCESSOR_TEMPDIR')
temp_filePath = os.path.join(tempFolder, "{}.hdf5".format(tempName))
# Check if there is already a file with this name
if os.path.isfile(temp_filePath):
try:
os.remove(temp_filePath)
except:
print('Warning:\nUnable to delete the file:\n{}\nprobably is still open or in use\n\n'.format(temp_filePath))
# Ceate the h5 file
h5Temporal = h5py.File(name=temp_filePath, mode="w")
nChans = len(entityIndexes)
# 1D dataset
if nChans==1:
dset = h5Temporal.create_dataset(name="dataSet",
shape=(itemCount,),
dtype=dtype,
compression=compression,
compression_opts=compression_opts,
chunks=chunks)
nChunks_1d = int(numpy.ceil(dset.shape[0]/dset.chunks[0]))
chunksInfo = []
for t in range(nChunks_1d):
start_i = int(t*dset.chunks[0])
stop_i = min(dset.shape[0], (start_i+dset.chunks[0]))
chunksInfo.append({
'start_i': start_i,
'stop_i': stop_i,
'nCount': int(stop_i - start_i)
})
startTime = time.time()
nChunks = len(chunksInfo)
if verbose:
print('extracting: {} ....'.format(tempName))
nsEntity_i = nsFile.get_entity(entityIndexes[0])
for i in range(nChunks):
if verbose:
if (time.time()-startTime)>5:
print("extracting: {} .... chunk {} out of {}...........".format(tempName, i, nChunks))
startTime = time.time()
dset[chunksInfo[i]['start_i']:(chunksInfo[i]['stop_i'])] = nsEntity_i.get_analog_data(
start_index=chunksInfo[i]['start_i'], index_count=chunksInfo[i]['nCount'])
# 2D dataset
else:
dset = h5Temporal.create_dataset(name="dataSet",
shape=(itemCount, nChans),
dtype=dtype,
compression=compression,
compression_opts=compression_opts,
chunks=chunks)
# USE HDF5 chunk Size to extract data
# first dimension is time, 2nd dimension is Channels:
nChunks_1d = int(numpy.ceil(dset.shape[0]/dset.chunks[0]))
nChunks_2d = int(numpy.ceil(dset.shape[1]/dset.chunks[1]))
chunksInfo = []
# Chunks will be extracted by time first, and channels second
for c in range(nChunks_2d):
chan_i = int(c*dset.chunks[1])
chan_e = int(min(dset.shape[1], (chan_i+dset.chunks[1])))
for t in range(nChunks_1d):
start_i = int(t*dset.chunks[0])
stop_i = min(dset.shape[0], (start_i+dset.chunks[0]))
chunksInfo.append({
'start_i': start_i,
'stop_i': stop_i,
'nCount': int(stop_i - start_i),
'col_i': numpy.arange(chan_i, chan_e),
'entity_i': [int(entityIndexes[i]) for i in range(chan_i, chan_e)]
})
startTime = time.time()
nChunks = len(chunksInfo)
if verbose:
print('extracting: {} ....'.format(tempName))
for i in range(nChunks):
if verbose:
if (time.time()-startTime)>5:
print("extracting: {} .... chunk {} out of {}...........".format(tempName, i, nChunks))
startTime = time.time()
for e in range(len(chunksInfo[i]['entity_i'])):
dset[chunksInfo[i]['start_i']:(chunksInfo[i]['stop_i']), chunksInfo[i]['col_i'][e]] = nsFile.get_entity(
chunksInfo[i]['entity_i'][e]).get_analog_data(start_index=chunksInfo[i]['start_i'], index_count=chunksInfo[i]['nCount'])
h5Temporal.close()
return temp_filePath
def temp_TimeSeries_hdf5_analog_cls(nsFile, analog_chanNames, tempName, itemCount,
dtype='float',
compression="gzip",
compression_opts=4,
chunks=True,
verbose=True):
analogEntities = []
for chanName in analog_chanNames:
analogEntities.append(rippleTools.AnalogIOchannel(nsFile=nsFile, chanName=chanName))
# Get Temporal folder information
tempFolder = os.environ.get('NWB_PROCESSOR_TEMPDIR')
if tempFolder is None:
set_NWBtempdir_environ()
tempFolder = os.environ.get('NWB_PROCESSOR_TEMPDIR')
temp_filePath = os.path.join(tempFolder, "{}.hdf5".format(tempName))
# Check if there is already a file with this name
if os.path.isfile(temp_filePath):
try:
os.remove(temp_filePath)
except:
print('Warning:\nUnable to delete the file:\n{}\nprobably is still open or in use\n\n'.format(temp_filePath))
# Ceate the h5 file
h5Temporal = h5py.File(name=temp_filePath, mode="w")
nChans = len(analog_chanNames)
# 1D dataset
if nChans==1:
dset = h5Temporal.create_dataset(name="dataSet",
shape=(itemCount,),
dtype=dtype,
compression=compression,
compression_opts=compression_opts,
chunks=chunks)
nChunks_1d = int(numpy.ceil(dset.shape[0]/dset.chunks[0]))
chunksInfo = []
for t in range(nChunks_1d):
start_i = int(t*dset.chunks[0])
stop_i = min(dset.shape[0], (start_i+dset.chunks[0]))
chunksInfo.append({
'start_i': start_i,
'stop_i': stop_i,
'nCount': int(stop_i - start_i)
})
startTime = time.time()
nChunks = len(chunksInfo)
if verbose:
print('extracting: {} ....'.format(tempName))
nsEntity_i = analogEntities[0]
for i in range(nChunks):
if verbose:
if (time.time()-startTime)>5:
print("extracting: {} .... chunk {} out of {}...........".format(tempName, i, nChunks))
startTime = time.time()
dset[chunksInfo[i]['start_i']:(chunksInfo[i]['stop_i'])] = nsEntity_i.get_data(
start_index=chunksInfo[i]['start_i'], index_count=chunksInfo[i]['nCount'])
# 2D dataset
else:
dset = h5Temporal.create_dataset(name="dataSet",
shape=(itemCount, nChans),
dtype=dtype,
compression=compression,
compression_opts=compression_opts,
chunks=chunks)
# USE HDF5 chunk Size to extract data
# first dimension is time, 2nd dimension is Channels:
nChunks_1d = int(numpy.ceil(dset.shape[0]/dset.chunks[0]))
nChunks_2d = int(numpy.ceil(dset.shape[1]/dset.chunks[1]))
chunksInfo = []
# Chunks will be extracted by time first, and channels second
for c in range(nChunks_2d):
chan_i = int(c*dset.chunks[1])
chan_e = int(min(dset.shape[1], (chan_i+dset.chunks[1])))
for t in range(nChunks_1d):
start_i = int(t*dset.chunks[0])
stop_i = min(dset.shape[0], (start_i+dset.chunks[0]))
chunksInfo.append({
'start_i': start_i,
'stop_i': stop_i,
'nCount': int(stop_i - start_i),
'col_i': numpy.arange(chan_i, chan_e),
'entity_i': [i for i in range(chan_i, chan_e)]
})
startTime = time.time()
nChunks = len(chunksInfo)
if verbose:
print('extracting: {} ....'.format(tempName))
for i in range(nChunks):
if verbose:
if (time.time()-startTime)>5:
print("extracting: {} .... chunk {} out of {}...........".format(tempName, i, nChunks))
startTime = time.time()
for e in range(len(chunksInfo[i]['entity_i'])):
dset[chunksInfo[i]['start_i']:(chunksInfo[i]['stop_i']), chunksInfo[i]['col_i'][e]] = analogEntities[chunksInfo[i]['entity_i'][e]].get_data(
start_index=chunksInfo[i]['start_i'], index_count=chunksInfo[i]['nCount']
)
h5Temporal.close()
return temp_filePath
##################################################################################################
# Get the offset between eyePC timeStamps and NS-zeroTime
def get_eyePC_offset(dictYAML, eyePCstartTime, nsFile=None):
eyeDelta = datetime.timedelta(hours = eyePCstartTime.hour,
minutes= eyePCstartTime.minute,
seconds = eyePCstartTime.second,
microseconds = eyePCstartTime.microsecond)
eyeOFFset = eyeDelta.total_seconds()-expYAML.getStartTimeSecs(dictYAML)
if nsFile is not None:
nsTrialInfo = rippleTools.getTrialMarkers(nsFile)
trialsNEV = nsTrialInfo['trials']
startTrialNev = trialsNEV[0]['markerTime'][trialsNEV[0]['markerID'].index(1)]
else:
startTrialNev = 0
return startTrialNev + eyeOFFset
def get_averageTemp(analogTemp_cls, ti = None, tf = None):
therm_info = analogTemp_cls.get_info()
nSamples = int(therm_info['item_count'])
endTime = analogTemp_cls.get_indexTime([nSamples])[0]
if ti is None:
ti = 0
if tf is None:
tf = endTime
if tf>endTime:
print('Warning... TimeEnd to calculate average temprature is out of range, it will limited to the end of the recording')
tf = endTime
start_index = analogTemp_cls.get_timeIndex([ti])[0]
stop_index = analogTemp_cls.get_timeIndex([tf])[0]
return numpy.mean(analogTemp_cls.get_data(start_index, stop_index - start_index))
##################################################################################################
# Extract Foot Hold, Left, Right, Both as behavioral Events
# return Dictionary easy to convert to pd.dataframe & NWB-trial table
# colNames : 'start_time', 'stop_time', 'feetResponseID', 'feetResponse'
def get_feetEvents(nsFile, chunkSizeSecs = 60, showPlot = False):
eventID_description = [
'holdBoth', # 0
'releaseLeft', # 1
'releaseRight', # 2
'releaseBoth', # 3
]
nsAnalogLeftFeet = rippleTools.AnalogIOchannel(nsFile=nsFile, chanName='leftFoot')
nsAnalogRightFeet = rippleTools.AnalogIOchannel(nsFile=nsFile, chanName='rightFoot')
diffTime = 0.001 # time before change of status
leftInfo = nsAnalogLeftFeet.get_info()
nSamples = int(leftInfo['item_count'])
endTime = nsAnalogLeftFeet.get_indexTime([nSamples])[0]
chunkSize = int(numpy.ceil(chunkSizeSecs*leftInfo['samplingRate']))
chunkStart = [int(i) for i in range(0, nSamples, chunkSize)]
if len(chunkStart)==1:
chunkStop = [nSamples]
else:
if chunkStart[-1]==(nSamples-1):
chunkStart.pop(-1)
chunkStop = chunkStart[1:]
chunkStop.append(nSamples)
nChunks = len(chunkStart)
eventTime = []
eventID = []
for c in range(nChunks):
print('processing footSignals..... chunk {} out of {}.....'.format(c+1, nChunks))
start_index = chunkStart[c]
count_samples = int(chunkStop[c]-chunkStart[c])
leftData = nsAnalogLeftFeet.get_data(start_index, count_samples)
rightData = nsAnalogRightFeet.get_data(start_index, count_samples)
leftRight = (leftData>thresholdFeet_mV) + ((rightData>thresholdFeet_mV)*2)
events = numpy.nonzero(abs(numpy.diff(leftRight))>0)[0]
appendZERO = False
if c==0:
appendZERO = True
else:
# check if previous sample was the same
leftData_prev = nsAnalogLeftFeet.get_data(start_index-1, 1)>thresholdFeet_mV
rightData_prev = nsAnalogRightFeet.get_data(start_index-1, 1)>thresholdFeet_mV
leftRight_prev = leftData_prev + (rightData_prev*2)
if leftRight_prev!=leftRight[0]:
# print(leftRight_prev, leftRight[0])
appendZERO = True
if len(events)==0 and c==0:
eventTime.append(start_index/leftInfo['samplingRate'])
eventID.append(leftRight[0])
elif len(events)>0:
if appendZERO:
eventTime.append(start_index/leftInfo['samplingRate'])
eventID.append(leftRight[0])
for e in events:
eventTime.append((e+start_index)/leftInfo['samplingRate'])
eventID.append(leftRight[e+1])
if showPlot:
fig, axs1 = plt.subplots()
tData = nsAnalogLeftFeet.get_indexTime(range(start_index, start_index+count_samples))
axs1.set_title(nsAnalogLeftFeet.get_info()['chanName'] + ' and ' + nsAnalogRightFeet.get_info()['chanName'])
axs1.plot(tData, leftData-10, color='b')
axs1.plot(tData, rightData+10, color='g')
for i in range(len(eventTime)):
if eventTime[i]>=tData[0] and eventTime[i]<=tData[-1]:
axs1.vlines(x=eventTime[i], ymin= -0.3, ymax = 4000, colors='r')
axs1.text(x=eventTime[i], y=4005, s=str(eventID[i]),horizontalalignment='center',
verticalalignment='center', fontsize=8)
axs1.set_xlim(tData[0]-1, tData[-1]+1)
plt.show()
# Convert feetEvents into a dictionary of intervals
# list of dictionaries {start_time:, stop_time:, feetID, feetDescription}
nEv = len(eventID)
feetIntervals = []
for e in range(nEv):
if e==(nEv-1):
stopTime = endTime
else:
stopTime = eventTime[e+1] - diffTime
if stopTime<=eventTime[e]:
stopTime += diffTime
feetIntervals.append({
'start_time': eventTime[e],
'stop_time': stopTime,
'feetResponseID': eventID[e],
'feetResponse': eventID_description[eventID[e]]
})
return feetIntervals
##################################################################################################
# Extract Reward ON as a Dictionary colNames : 'start_time', 'stop_time'
def get_rewardEvents(analogReward_cls, chunkSizeSecs = 60, showPlot = False):
diffTime = 0.001 # time before change of status
rewardInfo = analogReward_cls.get_info()
nSamples = int(rewardInfo['item_count'])
endTime = analogReward_cls.get_indexTime([nSamples])[0]
chunkSize = int(numpy.ceil(chunkSizeSecs*rewardInfo['samplingRate']))
chunkStart = [int(i) for i in range(0, nSamples, chunkSize)]
if len(chunkStart)==1:
chunkStop = [nSamples]
else:
if chunkStart[-1]==(nSamples-1):
chunkStart.pop(-1)
chunkStop = chunkStart[1:]
chunkStop.append(nSamples)
nChunks = len(chunkStart)
eventTime = []
eventID = []
for c in range(nChunks):
print('processing Reward Signal..... chunk {} out of {}.....'.format(c+1, nChunks))
start_index = chunkStart[c]
count_samples = int(chunkStop[c]-chunkStart[c])
rewardData = analogReward_cls.get_data(start_index, count_samples)
rewardON = rewardData>thresholdReward_mV
events = numpy.nonzero(abs(numpy.diff(rewardON))>0)[0]
appendZERO = False
if c==0:
appendZERO = True
else:
# check if previous sample was the same
rewardData_prev = analogReward_cls.get_data(start_index-1, 1)>thresholdReward_mV
if rewardData_prev!=rewardON[0]:
appendZERO = True
if len(events)>0:
if appendZERO:
eventTime.append(start_index/rewardInfo['samplingRate'])
eventID.append(rewardON[0])
for e in events:
eventTime.append((e+start_index)/rewardInfo['samplingRate'])
eventID.append(rewardON[e+1])
if showPlot:
fig, axs1 = plt.subplots()
tData = analogReward_cls.get_indexTime(range(start_index, start_index+count_samples))
axs1.set_title(analogReward_cls.get_info()['chanName'])
axs1.plot(tData, rewardData, color='b')
for i in range(len(eventTime)):
if eventTime[i]>=tData[0] and eventTime[i]<=tData[-1]:
if eventID[i]:
label = 'ON'
y = 5005
else:
label = 'OFF'
y = -0.5
axs1.vlines(x=eventTime[i], ymin= -0.3, ymax = 5000, colors='r')
axs1.text(x=eventTime[i], y=y, s=label,horizontalalignment='center',
verticalalignment='center', fontsize=8)
axs1.set_xlim(tData[0]-1, tData[-1]+1)
plt.show()
# Convert feetEvents into a dictionary of intervals
# list of dictionaries {start_time:, stop_time:, feetID, feetDescription}
nEv = len(eventID)
rewardIntervals = []
for e in range(nEv):
# Only save RewardON eventID ==1
if eventID[e]==1:
if e==(nEv-1):
stopTime = endTime
else:
stopTime = eventTime[e+1] - diffTime
if stopTime<=eventTime[e]:
stopTime += diffTime
rewardIntervals.append({
'start_time': eventTime[e],
'stop_time': stopTime,
'label': 'rewardON',
'labelID': eventID[e]
})
return rewardIntervals
#######################################################################################################
# !! NO LONGER IN USE !!!
# This function does not take into account that the reward can be delivered manually at random times
# Reward times are saved as timeIntervals (like foot events)
#######################################################################################################
#
# Get Reward ON & OFF times
def get_trialRewardONOFF_fromAnalog(analogReward_cls, trialNEV, interTrialTime, showPlot=True):
threshold_mV = 2500
diffTime = 0.000 # time before change of status
rewardInfo = analogReward_cls.get_info()
####################################################
# Marker 1: fixationTarget is ON the screen
signal_start = trialNEV['markerTime'][trialNEV['markerID'].index(1)]
####################################################
# Stop of the trial
signal_stop = max(trialNEV['markerTime']) + (interTrialTime/1.2)
start_index = analogReward_cls.get_timeIndex([signal_start])[0]
stop_index = analogReward_cls.get_timeIndex([signal_stop])[0]
signal = analogReward_cls.get_data(start_index=start_index, index_count=stop_index-start_index)
peaks = numpy.nonzero(signal>threshold_mV)[0]
if len(peaks)>0:
timeUP = analogReward_cls.get_indexTime([start_index+peaks[0]-1])[0]-diffTime
timeDOWN = analogReward_cls.get_indexTime([start_index+peaks[-1]-1])[0]-diffTime
else:
timeUP = []
timeDOWN = []
if showPlot:
fig, axs1 = plt.subplots()
tData = analogReward_cls.get_indexTime(range(start_index, stop_index))
axs1.set_title(rewardInfo['chanName'] + ' - Trial: {}'.format(trialNEV['trialNum']))
axs1.plot(tData, signal, color='b')
if len(peaks)>0:
axs1.vlines(x=timeUP, ymin= -0.3, ymax = 5000, colors='r')
axs1.text(x=timeUP, y=5005, s='on', horizontalalignment='center',
verticalalignment='center', fontsize=8)
axs1.vlines(x=timeDOWN, ymin= -0.3, ymax = 5000, colors='r')
axs1.text(x=timeDOWN, y=5005, s='off', horizontalalignment='center',
verticalalignment='center', fontsize=8)
axs1.set_xlim(tData[0]-1, tData[-1]+1)
plt.show()
return {'rewardON': timeUP, 'rewardOFF': timeDOWN}
##################################################################################################
# Get FIX_ON and FIX_OFF based on photodiode signal. It will use marker 1 to cut the signal.
# To get the ON & OFF event it will normalize between the min & the max and use
# the variable normThreshold as a cut point
def get_trialFixONOFF_fromAnalog(analogFix_cls, trialNEV, interTrialTime, normThreshold, showPlot=False):
####################################################
# Marker 1: fixationTarget is ON the screen
fixTarget_Start = trialNEV['markerTime'][trialNEV['markerID'].index(1)]-tolerancePhotodiode
if trialNEV['trialNum']==1:
signal_start = 0
else:
signal_start = fixTarget_Start - (interTrialTime/1.2)
####################################################
# Stop of the trial
signal_stop = max(trialNEV['markerTime']) + (interTrialTime/1.2)
signal_start_index = analogFix_cls.get_timeIndex([signal_start])[0]
signal_stop_index = analogFix_cls.get_timeIndex([signal_stop])[0]
if signal_stop_index>analogFix_cls.get_info()['item_count']:
signal_stop_index = analogFix_cls.get_info()['item_count']
signal = analogFix_cls.get_data(start_index=signal_start_index, index_count=signal_stop_index-signal_start_index)
minSignal = min(signal)
maxSignal = max(signal)
stepSignal = ( (signal - minSignal) / (maxSignal - minSignal) )>= normThreshold
if stepSignal[0]:
stepSignal = stepSignal==False
peaks = numpy.nonzero(stepSignal)[0]
indexUP = peaks[0]
timeUP = analogFix_cls.get_indexTime([signal_start_index+indexUP])[0]
indexDOWN = peaks[-1]
timeDOWN = analogFix_cls.get_indexTime([signal_start_index+indexDOWN])[0]
if showPlot:
tSnippet = analogFix_cls.get_indexTime(range(signal_start_index, signal_stop_index))
fig, axs1 = plt.subplots()
axs1.set_title(analogFix_cls.get_info()['chanName'] + ' - Trial: {}'.format(trialNEV['trialNum']))
axs1.plot(tSnippet, signal, color='k')
axs1.vlines(x=timeUP, ymin= minSignal, ymax = maxSignal, colors='r')
axs1.vlines(x=timeDOWN, ymin= minSignal, ymax = maxSignal, colors='b')
axs1.set_xlabel("Time (s)")
axs1.set_ylabel("Amplitude (mV)")
plt.show()
return {'fixON': timeUP, 'fixOFF': timeDOWN}
####################################################################################################################
# Get VISUAL-EVENT_ON based on photodiode signal. It search for marker 15 (Visual Cue ON) or 5 (Choice Targets ON).
# To get the ON of any visual event it will normalize between the min & the max and use
# the variable normThreshold as a cut point. To detect the next event it will use the photodiodeDuration
def get_trialVisualEventsON_fromAnalog(analogVisualEvents_cls, trialNEV, normThreshold,
photodiodeDuration, choiceTargetON=True, showPlot=False, showWarningPlot=True):
samplesPulse = (photodiodeDuration*analogVisualEvents_cls.get_info()['samplingRate'])
visualEvents = {'cueON': [], 'choiceON': []}
# Check if marker 15 (Visual Cue ON) or 5 (Choice Targets ON) occurs
if any([trialNEV['markerID'].count(15), trialNEV['markerID'].count(5)]):
# Sort by time
nevIndex = numpy.argsort(numpy.array(trialNEV['markerTime']))
nNEV = len(trialNEV['markerTime'])
if choiceTargetON:
marker_idx = [nevIndex[i] for i in range(nNEV) if trialNEV['markerID'][nevIndex[i]]==15 or trialNEV['markerID'][nevIndex[i]]==5]
else:
marker_idx = [nevIndex[i] for i in range(nNEV) if trialNEV['markerID'][nevIndex[i]]==15]
visEv_ID = [trialNEV['markerID'][i] for i in marker_idx]
visEv_Time = [trialNEV['markerTime'][i] for i in marker_idx]
signal_index = analogVisualEvents_cls.get_timeIndex([min(trialNEV['markerTime']), max(trialNEV['markerTime'])])
signal = analogVisualEvents_cls.get_data(start_index=signal_index[0], index_count=signal_index[1] - signal_index[0])
minSignal = min(signal)
maxSignal = max(signal)
stepSignal = ( (signal - minSignal) / (maxSignal - minSignal) )>= normThreshold
samplesStep = numpy.floor(samplesPulse*0.5)
signalUP = numpy.nonzero(stepSignal)[0]
lenUP = numpy.size(signalUP)
diffUP = numpy.diff(signalUP)
upON = numpy.concatenate((numpy.array([0]), numpy.nonzero(diffUP>samplesStep)[0]+1))
nUPs = numpy.size(upON)
if nUPs>1:
upOFF = numpy.concatenate((upON[1:]-1, [lenUP-1]))
else:
upOFF = numpy.array([lenUP-1])
validPeaks = (upOFF - upON)>samplesStep
tVisualEvents = analogVisualEvents_cls.get_indexTime(signal_index[0] + signalUP[upON[validPeaks]])
warningPlotexist = False
raise_Exception = False
# Create New Markers
# 1st check if number of visual events Matches
if len(tVisualEvents)==len(visEv_Time):
for m in range(len(visEv_ID)):
if visEv_ID[m]==15:
visualEvents['cueON'].append(tVisualEvents[m])
elif visEv_ID[m]==5:
visualEvents['choiceON'].append(tVisualEvents[m])
else:
# Possible artifact on the photodiode can give more than ON events than expected
if len(tVisualEvents)>len(visEv_Time):
if showWarningPlot:
warningPlotexist = True
print('\nWARNING¡¡\nNumber of VisualEvents did NOT match:\nmarkerIDs: {}, n={} vs Detected={}\
\nmarkerTimes: {}\ntimesDetected: {}\nIt will take the closest timeStamp and ignore the other\n'.format(
visEv_ID, len(visEv_Time), len(tVisualEvents),
visEv_Time, tVisualEvents)
)
for m in range(len(visEv_ID)):
mID = visEv_ID[m]
if mID==15:
mName = 'cueON'
elif mID==5:
mName = 'choiceON'
closestAnalog = tVisualEvents[numpy.abs(numpy.asarray(tVisualEvents)-visEv_Time[m]).argmin()]
absDifference = abs(visEv_Time[m]-closestAnalog)
if absDifference<=tolerancePhotodiode:
newMarkerTime = closestAnalog
else:
warningPlotexist = True
newMarkerTime = min([closestAnalog, visEv_Time[m]])
print('Photodiode Time for marker {}({}) was not found closer to the expected time by the configFile.\n\
it will take the earlier timeStamp between YAML and photodiode.\n\
yaml timeStamp: {},\n\
closest Photodiode (NEV) timeStamp: {},\n\
absDifference (secs): {},\n\
TrialNev: {}\n\
Tolerance (secs): {}\n'.format(
mID, mName, visEv_Time[m], closestAnalog,
absDifference, trialNEV['trialNum'], tolerancePhotodiode))
visualEvents[mName].append(newMarkerTime)
elif len(tVisualEvents)<len(visEv_Time):
raise_Exception = True
warningPlotexist = True
print('Number of VisualEvents did NOT match:\nmarkerIDs: {}, n={} vs Detected={}\
\nmarkerTimes: {}\ntimesDetected: {}\n'.format(visEv_ID, len(visEv_Time), len(tVisualEvents),
visEv_Time, tVisualEvents)
)
# PLOT
if showPlot or warningPlotexist:
tSignal = analogVisualEvents_cls.get_indexTime(range(signal_index[0], signal_index[1]))
fig, axs1 = plt.subplots()
axs1.set_title(analogVisualEvents_cls.get_info()['chanName'] + ' Trial: {}'.format(trialNEV['trialNum']))
axs1.plot(tSignal, signal, color='k')
axs1.vlines(x=trialNEV['markerTime'], ymin= min(signal), ymax = max(signal), colors='r')
axs1.vlines(x=visualEvents['cueON'], ymin= min(signal), ymax = max(signal), colors='g')
axs1.vlines(x=visualEvents['choiceON'], ymin= min(signal), ymax = max(signal), colors='b')
for m in range(len(trialNEV['markerTime'])):
axs1.text(x=trialNEV['markerTime'][m], y=max(signal), s=str(trialNEV['markerID'][m]),
horizontalalignment='center', verticalalignment='center', fontsize=8)
plt.show()
if raise_Exception:
raise Exception()
return visualEvents
##################################################################################################
# !! NO LONGER IN USE !!!
# software was updated. Now there are two photodiodes to signal fixation-only and to signal ONSET
# of any other visual event (visual cues & choice targets)
##################################################################################################
#
# If FIX-photodiode is placed on top of the real fixation target, it can be possible to extract
# ONSET & OFFSET of visual cues draw on top of the fixation:
# It will use FIX_ON and FIX_OFF period to serch for changes in the photodiode signal.
# It will use marker 15 as a starting point to search for the first change.
# It will return visualCueON, OFF, and FIX_ON & FIX_OFF as a dictionary
def get_trialFixVisualEvents_fromAnalog(analogFix_cls, trialNEV, threshold_mV, minGap_cueOFF_fixOFF,
interTrialTime, normThreshold, showPlot=False):
# It will get the main ON-OFF event, using the min & max values
time_ONOFF = get_trialFixONOFF_fromAnalog(analogFix_cls, trialNEV, interTrialTime, normThreshold, showPlot=showPlot)
cueON = []
cueOFF = []
nVisualCue = trialNEV['markerID'].count(15)
# Assume that signal always start after marker 15
if nVisualCue>0:
if nVisualCue>1:
print('\n....... WARNING:\nfunction "get_visualCueATfix_fromAnalog" has not been fully tested\
to handle more than one visualCue at fixationLocation\n(trial {} has {} visualCues)'.format(
trialNEV['trialNum'], nVisualCue
))
visualCuesON = [trialNEV['markerTime'][i] for i in range(len(trialNEV['markerID'])) if trialNEV['markerID'][i]==15]
signal_start_index = analogFix_cls.get_timeIndex([time_ONOFF['fixON']])[0]
signal_stop_index = analogFix_cls.get_timeIndex([time_ONOFF['fixOFF']])[0]
signal = analogFix_cls.get_data(start_index=signal_start_index, index_count=signal_stop_index-signal_start_index)
stepMin = numpy.ceil(minGap_cueOFF_fixOFF*analogFix_cls.get_info()['samplingRate']).astype(int)
for v in range(len(visualCuesON)):
cueON_index = analogFix_cls.get_timeIndex([visualCuesON[v]])[0]
cueSignal = signal[cueON_index-signal_start_index:]
stepSignal = numpy.nonzero(abs(cueSignal-cueSignal[0])>=threshold_mV)[0]
if len(stepSignal)>0:
cueON_time = analogFix_cls.get_indexTime([cueON_index + stepSignal[0]])[0]
cueON.append(cueON_time)
jump_index = numpy.nonzero(numpy.diff(stepSignal)>=stepMin)[0]
if len(jump_index)>0:
cueOFF.append(analogFix_cls.get_indexTime([cueON_index + stepSignal[jump_index[0]-1]])[0])
else:
cueOFF.append(time_ONOFF['fixOFF'])
if showPlot:
if nVisualCue==0:
visualCuesON = [trialNEV['markerTime'][i] for i in range(len(trialNEV['markerID'])) if trialNEV['markerID'][i]==15]
signal_start_index = analogFix_cls.get_timeIndex([time_ONOFF['fixON']])[0]
signal_stop_index = analogFix_cls.get_timeIndex([time_ONOFF['fixOFF']])[0]
signal = analogFix_cls.get_data(start_index=signal_start_index, index_count=signal_stop_index-signal_start_index)
tSignal = analogFix_cls.get_indexTime(range(signal_start_index, signal_stop_index))
fig, axs1 = plt.subplots()
axs1.set_title('Fix Epoch - Trial: {}'.format(trialNEV['trialNum']))
axs1.plot(tSignal, signal, color='k')
axs1.vlines(x=cueON, ymin= min(signal), ymax = max(signal), colors='r')
axs1.vlines(x=cueOFF, ymin= min(signal), ymax = max(signal), colors='r')
axs1.vlines(x=visualCuesON, ymin= min(signal), ymax = max(signal), colors='b')
plt.show()
# Get Unique Times from cueON & cueOFF
if len(cueON)>0:
cueON = list(numpy.unique(numpy.array(cueON)))
if len(cueOFF)>0:
cueOFF = list(numpy.unique(numpy.array(cueOFF)))
time_ONOFF.update({'cueON': cueON, 'cueOFF': cueOFF})
return time_ONOFF
###########################################################################################
# Get Onset and Offset of an signal that crosses a threshold. It find the first and the last peak and use
# the midlle point of those peaks to center the signal according to the expected duration of the event.
def get_acclONOFF_fromAnalog(analogAccl_cls, stimStartSecs, stimStopSecs, stimDurationSecs=None,
thresholdHigh_std=15, thresholdLow_std=5, baselineStartSecs=-1, baselineStopSecs=-1,
showPlot=False, showPlot_lowThreshold=True, showPlot_noDetected=True,
trialID = None, stimID = None):
if trialID is None:
trialID = 'unknown'
if stimID is None:
stimID = 'unknown'
samplingRate = analogAccl_cls.get_info()['samplingRate']
stimStart_index = analogAccl_cls.get_timeIndex([stimStartSecs])[0]
stimStop_index = analogAccl_cls.get_timeIndex([stimStopSecs])[0]
if baselineStartSecs <0:
baselineStart_index = stimStart_index
else:
baselineStart_index = analogAccl_cls.get_timeIndex([baselineStartSecs])[0]
if baselineStopSecs <0:
baselineStop_index = stimStop_index
else:
baselineStop_index = analogAccl_cls.get_timeIndex([baselineStopSecs])[0]
stdBaseline = numpy.std(analogAccl_cls.get_data(start_index=baselineStart_index,
index_count=baselineStop_index-baselineStart_index))
snippet = analogAccl_cls.get_data(start_index=stimStart_index,
index_count=stimStop_index-stimStart_index)
snippet = numpy.absolute((snippet - numpy.mean(snippet))/stdBaseline)
peaks_index_high = numpy.nonzero(snippet>=thresholdHigh_std)
if peaks_index_high[0].size>0:
peaks_index = peaks_index_high
threshold_std = thresholdHigh_std
showPlot_lowThreshold=False
else:
peaks_index = numpy.nonzero(snippet>=thresholdLow_std)
threshold_std = thresholdLow_std
print('{} at Trial={}, stim={}, timeInterval: [{}-{}] used the low Threshold'.format(
analogAccl_cls.get_info()['chanName'], trialID, stimID, stimStartSecs, stimStopSecs
))
if peaks_index[0].size>0:
threshold2 = numpy.mean(snippet[peaks_index]) - (numpy.std(snippet[peaks_index])*1.5)
if threshold2>threshold_std:
peaks = numpy.nonzero(snippet>=threshold2)
else:
peaks = numpy.nonzero(snippet>=threshold_std)
centerPeak = numpy.min(peaks) + numpy.round((numpy.max(peaks)-numpy.min(peaks))/2).astype(int)
if stimDurationSecs is None:
stimDurationSecs = (numpy.max(peaks)-numpy.min(peaks))/samplingRate
durationSamples = numpy.ceil(stimDurationSecs*samplingRate).astype(int)
half = numpy.ceil(durationSamples/2).astype(int)
tStart_index = stimStart_index + centerPeak - half
tStop_index = stimStart_index + centerPeak + half
if showPlot or showPlot_lowThreshold:
tSnippet = analogAccl_cls.get_indexTime(range(stimStart_index, stimStop_index))
tSnippet1 = analogAccl_cls.get_indexTime(range(stimStart_index-20, stimStop_index+20))