-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyamlTools.py
2017 lines (1660 loc) · 103 KB
/
yamlTools.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
import os, struct
import uuid
import datetime as dt
import dateutil
import numpy
import pandas
import pytz
import yaml
import tkinter as tk
from tkinter.filedialog import askopenfilename
from tkinter import simpledialog
# TOOLS to extract & Session, Subject, ElectrodeInfo, ShakerInfo & Behavioral Data from *.YAML files
# file format follow YAULAB convention of the task :
# visual cues + 2 shakers + footbar + eye tracking
#################################################################################
# Read YAML into Dictionary
#################################################################################}
def yaml2dict(filePathYAML = None, verbose=True):
if filePathYAML is None:
filePathYAML = askopenfilename(
title = 'Select a YAML file to load',
filetypes =[('yaml Files', '*.yaml')])
if not os.path.isfile(filePathYAML):
raise Exception("YAML-file-Path : {} doesn't exist ".format(filePathYAML))
_, fileName = os.path.split(os.path.abspath(filePathYAML))
if verbose:
print('\n... loading YAML file {} into python-dictionary..... \n'.format(fileName))
# Extract YAML as nested Dictionaries
with open(filePathYAML, 'r') as stream:
dictYAML = yaml.safe_load(stream)
return dictYAML
#################################################################################
# Read Binary EYE-startTime
#################################################################################
def getEyeStartTime(filePathEYE = None, verbose=True):
"""
The following is the format of the eye Binary-output.
float —> 32bit --> 4 bytes
char —> 8bit --> 1 byte
struct = {
char [12] // time stamp // 96 bit -> 12 bytes
float [1] // eye_pos_x // 32 bit -> 4 bytes
float [1] // eye_pos_y // 32 bit -> 4 bytes
float [1] // pupil_diameter // 32 bit -> 4 bytes
}
"""
if filePathEYE is None:
filePathEYE = askopenfilename(
title = 'Select an EYE file to load',
filetypes =[('eye Files', '*.eye')])
if not os.path.isfile(filePathEYE):
raise Exception("EYE-file-Path : {} doesn't exist ".format(filePathEYE))
_, fileName = os.path.split(os.path.abspath(filePathEYE))
if verbose:
print('\n... reading startTime EYE file {}..... \n'.format(fileName))
fBin = open(filePathEYE, 'rb')
datBin = fBin.read()
fBin.close()
nStream = len(datBin)
if nStream==0:
startTime = None
else:
if nStream % 24 != 0:
raise Exception("Binary data doesn't match proper dimensions : last sample has {} bytes out of 24".format(nStream % 24))
startTime = struct.unpack('@12s', datBin[0:12])
startTime = dt.datetime.strptime(startTime[0].decode(), "%H:%M:%S.%f").time()
return startTime
#################################################################################
# Read Binary EYE-data
#################################################################################
def getEyeData(filePathEYE = None, offsetSecs = 0, verbose=True):
"""
The following is the format of the eye Binary-output.
float —> 32bit --> 4 bytes
char —> 8bit --> 1 byte
struct = {
char [12] // time stamp // 96 bit -> 12 bytes
float [1] // eye_pos_x // 32 bit -> 4 bytes
float [1] // eye_pos_y // 32 bit -> 4 bytes
float [1] // pupil_diameter // 32 bit -> 4 bytes
}
"""
if filePathEYE is None:
filePathEYE = askopenfilename(
title = 'Select an EYE file to load',
filetypes =[('eye Files', '*.eye')])
if not os.path.isfile(filePathEYE):
raise Exception("EYE-file-Path : {} doesn't exist ".format(filePathEYE))
_, fileName = os.path.split(os.path.abspath(filePathEYE))
if verbose:
print('\n... loading EYE file {} into python-dictionary..... \n'.format(fileName))
fBin = open(filePathEYE, 'rb')
datBin = fBin.read()
fBin.close()
nStream = len(datBin)
eyeData = {'time': [], 'x': [], 'y': [], 'pupil': []}
if nStream>0:
if nStream % 24 != 0:
raise Exception("Binary data doesn't match proper dimensions : last sample has {} bytes out of 24".format(nStream % 24))
startTime = struct.unpack('@12s', datBin[0:12])
startTime = dt.datetime.strptime(startTime[0].decode(), "%H:%M:%S.%f")
for t in range(0, nStream, 24):
tDat = struct.unpack('@12s3f', datBin[t:t+24])
currentTime = dt.datetime.strptime(tDat[0].decode(), "%H:%M:%S.%f")
lapsedTime = (currentTime-startTime).total_seconds()
eyeData['time'].append(lapsedTime + offsetSecs)
eyeData['x'].append(tDat[1])
eyeData['y'].append(tDat[2])
eyeData['pupil'].append(tDat[3])
del tDat, currentTime, lapsedTime
return eyeData
#################################################################
# Some Variables used to get default parameters
#################################################################
currentPath, currentFileName = os.path.split(os.path.abspath(__file__))
monkeysDict = yaml2dict(os.path.join(currentPath, 'monkeyIDs.yaml'), verbose=False)
labInfo = yaml2dict(os.path.join(currentPath, 'yauLabInfo.yaml'), verbose=False)
electrodeDevices = pandas.read_excel(os.path.join(currentPath, 'ElectrodeDevices.xlsx'), sheet_name=None)
dictOutcomes = {
10 : 'correct',
11 : 'fail to fix CORRECT target',
12 : 'fail to fix ANY target',
13 : 'no saccade',
14 : 'eye-abort',
140 : 'foot-abort',
141 : 'eyeFoot-abort',
16 : 'experiment stopped'
}
dictOutcomes.update({i : 'incorrect choiceTarget {}'.format(i-30) for i in range(31, 61)})
dictOutcomes.update({i : 'fail to fix incorrect choiceTarget {}'.format(i-60) for i in range(61, 91)})
trialKeys2remove = ['OutCome', 'Marker Signal Sequence']
port_Labels = ['A', 'B', 'C', 'D']
################################################
# General Params & Functions for all YAMLs
###############################################
class expYAML:
###########################################################
# If exists, GET DEFAULT MONKEY INFO
###########################################################
@classmethod
def getMonkeyInfo(cls, dictYAML):
# Check if Monkey ID exist
monkeyNames = list(monkeysDict.keys())
monkeyInfo = None
for name in monkeyNames:
if name.lower() in dictYAML['Subject Info']['Subject ID'].lower():
monkeyInfo = monkeysDict[name]
return monkeyInfo
###########################################################
# Subject Info (nwb-like format)
###########################################################
@classmethod
def getSubjectInfo(cls, dictYAML, subject_id=None, description=None, sex=None,
species=None, date_of_birth=None, age=None):
# Check if monkey exist:
monkeyInfo = cls.getMonkeyInfo(dictYAML)
subject_id = dictYAML['Subject Info']['Subject ID']
description = dictYAML['Subject Info']['Subject ID']
# Extract REQUIRED info from YAML, If doesn't exist it will prompt a dialog window to enter the info
if monkeyInfo is None:
sbj = dictYAML['Subject Info']
# Sex is Required
if sex is None:
sex = sbj['Sex']
if sex is None:
root = tk.Tk()
root.withdraw()
sex = simpledialog.askstring(
title = 'Sex not found',
prompt = 'What is the sex of the subject \n'\
' “F” (female), “M” (male), “U” (unknown), or “O” (other) is recommended'
)
sex = sex[0].upper()
# Species is Required
if species is None:
species = sbj['Species']
if species is None:
root = tk.Tk()
root.withdraw()
species = simpledialog.askstring(
title = 'Species not found',
prompt = 'Species must be defined. \n'\
'The formal latin binomal name is recommended, e.g., “Mus musculus" '
)
if date_of_birth is None:
date_of_birth = sbj['Date of Birth']
if date_of_birth == 'n/a':
date_of_birth = None
if isinstance(date_of_birth, str):
# Try default dateFormat (Month/Day/Year)
date_of_birth = dateutil.parser(date_of_birth)
if age is None:
age = sbj['Age']
if age is not None:
if age.lower() == 'n/a':
age = None
# DOB or AGE is Required
if age is None and date_of_birth is None:
root = tk.Tk()
root.withdraw()
ageDOB = simpledialog.askstring(
title = 'Age/DOB not found',
prompt = 'The age of the subject or Date Of Birth is needed. \n'\
'Which input will be provided (type: AGE or DOB)',
)
if 'age' in ageDOB.lower():
root = tk.Tk()
root.withdraw()
age = simpledialog.askstring(
title = 'AGE',
prompt = 'Age : The ISO 8601 Duration format is recommended, e.g., “P90D” for 90 days old. \n'\
'A timedelta will automatically be converted to The ISO 8601 Duration format.',
)
else:
root = tk.Tk()
root.withdraw()
date_of_birth = simpledialog.askstring(
title = 'Date of Birth',
prompt = "Enter numeric datetime of the date of birth ('MM-DD-YYYY').",
)
date_of_birth = dt.datetime.strptime(date_of_birth, "%m-%d-%Y")
else:
print("Monkey ID was recognized .. getting default Params")
subject_id = monkeyInfo['Subject ID']
description = description + ' - Tatoo : ' + monkeyInfo['Tatoo']
species = monkeyInfo['Species']
sex = monkeyInfo['Sex']
date_of_birth = monkeyInfo['Date of Birth']
age = None
# Return SubjectInfo as a Dictionary matching the fields required by NWB-format
return {
'age': age,
'description': description,
'sex' : sex[0].upper(),
'species' : species,
'subject_id' : subject_id,
'date_of_birth': date_of_birth,
}
###########################################################
# Session Info (nwb-like format)
###########################################################
@classmethod
def getSessionInfo(cls, dictYAML, session_start_time, session_id = None, session_description = None, identifier=None):
if session_id is None:
# use YAML namefile
session_id = 'session_'+ dictYAML['Experiment Started'].replace(':', '')
if session_description is None:
if bool(dictYAML['Subject Info']['Comments']):
session_description = dictYAML['Subject Info']['Comments'] # required
#Training with Headfixed to keep eye at fix-target and categorize both hands
if identifier is None:
identifier=str(uuid.uuid4()) # required
return {
'session_id' : session_id,
'session_description' : session_description,
'identifier' : identifier,
'session_start_time' : session_start_time
}
###########################################################
# Experiment YAML-Metadata (nwb-like format)
###########################################################
@classmethod
def getExperimentInfo(cls, dictYAML,
lab=None, institution=None, protocol=None, experiment_description=None,
surgery = None, experimenter = None, stimulus_notes = None, notes = None,
keywords = None, related_publications = None
):
# Check if monkey exist:
monkeyInfo = cls.getMonkeyInfo(dictYAML)
if monkeyInfo is None:
if lab is None:
lab = dictYAML['Subject Info']['Lab']
if institution is None:
institution = dictYAML['Subject Info']['Institution']
if protocol is None:
protocol = dictYAML['Subject Info']['Protocol']
if surgery is None:
surgery = dictYAML['Subject Info']['Surgery']
else:
lab = monkeyInfo['Lab']
institution = monkeyInfo['Institution']
protocol = monkeyInfo['Protocol']
surgery = monkeyInfo['Surgery']
if experiment_description is None:
experiment_description = dictYAML['Subject Info']['Comments']
return {
'lab': lab,
'institution': institution,
'protocol': protocol,
'experiment_description': experiment_description,
'surgery': surgery,
'experimenter': experimenter,
'stimulus_notes': stimulus_notes,
'notes': notes,
'keywords': keywords,
'related_publications': related_publications
}
###########################################################
# Get the number of Electrode devices:
# Single electrodes (i.e. FHC)
# Single Probes (i.e. Plexon probes)
###########################################################
@classmethod
def getElectrodeList(cls, dictYAML):
electrodeDicts = [value for key, value in dictYAML['Subject Info'].items() if key.startswith('Electrode')]
electrodesKeys = [key for key, value in dictYAML['Subject Info'].items() if key.startswith('Electrode')]
nElectrodesGroups = len(electrodeDicts)
electrodeResults = {
'electrodesGroups': [{
'deviceName': 'Unknown-ElectrodeProbe',
'position': [float(0), float(0), float(0)],
'location': 'Unknown',
'nChans': int(0),
'group_id': int(0),
'port_ID': 'Unknown'
}],
'electrodes': []
}
for eD in range(nElectrodesGroups):
coordinates = [float(c) for c in str(electrodeDicts[eD]['Coordinates(AP, ML, DV)']).split(' ')]
electrodeDF = electrodeDevices[electrodeDicts[eD]['Name']]
nChans = len(electrodeDF)
# Each electrode group indicates a device. Each devices has a field called "Front end".
# It consists of 4 number: [frontEnd_id, MicroStim, startCountChannel, stopCountChannel]
# Each device can be connected up to 4 frontEnds (1 to 4)
# Each frontEnd has a True/False value whether is a microStimulation frontEnd or not
# Electrodes within each frontEnd are numbered starting from 1 up the number of electrodes connected to that fronEnd
if port_Labels.count(electrodeDicts[eD]['Port ID'])!=1:
raise Exception('{} has an incorrect Port ID: {}.\nDeviceName: {}, valid PortIDs: {})'.format(
electrodesKeys[eD], electrodeDicts[eD]['Port ID'], electrodeDicts[eD]['Name'], port_Labels
))
port_index = port_Labels.index(electrodeDicts[eD]['Port ID'])
id = []
port_ID = []
frontEnd_id = []
frontEnd_electrode_id = []
microStimChan = []
nFrontEnds = len(electrodeDicts[eD]['Front End'])
for f in range(nFrontEnds):
frontEnd_info = [int(c) for c in str(electrodeDicts[eD]['Front End'][f]).split(' ')]
for e in range(frontEnd_info[2], frontEnd_info[3]+1):
id.append(int(e + (128*port_index) + (32*(frontEnd_info[0]-1))))
port_ID.append(electrodeDicts[eD]['Port ID'])
frontEnd_id.append(int(frontEnd_info[0]))
frontEnd_electrode_id.append(int(e))
microStimChan.append(frontEnd_info[1]==1)
nChansYAML = len(id)
if nChansYAML!=nChans:
raise Exception(
'\nYAML chanNum (n={}) must match Device-ElectrodeGroup map (device: {}, expected # of Chans={})\n'.format(
nChansYAML, electrodeDicts[eD]['Name'], nChans) +
'YAML Group: {}\nYAML-electrode channels: {}'.format(
electrodesKeys[eD], frontEnd_electrode_id
))
electrodeResults['electrodesGroups'].append({
'deviceName': electrodeDicts[eD]['Name'],
'position': coordinates,
'location': electrodeDicts[eD]['Brain Area'],
'nChans': nChans,
'group_id': int(eD+1),
'port_ID': electrodeDicts[eD]['Port ID']
})
for c in range(nChans):
electrodeResults['electrodes'].append({
'deviceName': electrodeDicts[eD]['Name'],
'group_id': int(eD+1),
'location': electrodeDicts[eD]['Brain Area'],
'id': id[c],
'rel_id': int(electrodeDF.iloc[c]['chanNumProbe']),
'ap': coordinates[0]-float(electrodeDF.iloc[c]['ap']),
'ml': coordinates[1]-float(electrodeDF.iloc[c]['ml']),
'dv': coordinates[2]-float(electrodeDF.iloc[c]['dv']),
'rel_ap': float(electrodeDF.iloc[c]['ap']),
'rel_ml': float(electrodeDF.iloc[c]['ml']),
'rel_dv': float(electrodeDF.iloc[c]['dv']),
'port_ID': port_ID[c],
'frontEnd_id': frontEnd_id[c],
'frontEnd_electrode_id': frontEnd_electrode_id[c],
'microStimChan': microStimChan[c]
})
return electrodeResults
###########################################################
# Get the List of Electrodes enabled for microstimulation
###########################################################
@classmethod
def getMicroStimElectrodeList(cls, dictYAML):
electrodeDicts = [value for key, value in dictYAML['Subject Info'].items() if key.startswith('Electrode')]
electrodesKeys = [key for key, value in dictYAML['Subject Info'].items() if key.startswith('Electrode')]
nElectrodesGroups = len(electrodeDicts)
electrodeList = []
nFrontEndsMicroStim = 0
frontEndsMicroStim = []
for eD in range(nElectrodesGroups):
electrodeDF = electrodeDevices[electrodeDicts[eD]['Name']]
nChans = len(electrodeDF)
if port_Labels.count(electrodeDicts[eD]['Port ID'])!=1:
raise Exception('{} has an incorrect Port ID: {}.\nDeviceName: {}, valid PortIDs: {})'.format(
electrodesKeys[eD], electrodeDicts[eD]['Port ID'], electrodeDicts[eD]['Name'], port_Labels
))
port_index = port_Labels.index(electrodeDicts[eD]['Port ID'])
nChansYAML = 0
electrodeID_Name = []
nFrontEnds = len(electrodeDicts[eD]['Front End'])
for f in range(nFrontEnds):
frontEnd_info = [int(c) for c in str(electrodeDicts[eD]['Front End'][f]).split(' ')]
if frontEnd_info[1]==1:
nFrontEndsMicroStim += 1
frontEndsMicroStim.append('{} : {}{}'.format(electrodesKeys[eD], electrodeDicts[eD]['Port ID'], frontEnd_info[0]))
for e in range(frontEnd_info[2], frontEnd_info[3]+1):
port_id = electrodeDicts[eD]['Port ID']
frontEnd_id = int(frontEnd_info[0])
frontEnd_electrode_id = int(e)
if frontEnd_info[1]==1:
electrodeList.append({
'id': int(e + (128*port_index) + (32*(frontEnd_id-1))),
'port_id': port_id,
'frontEnd_id': frontEnd_id,
'frontEnd_electrode_id': frontEnd_electrode_id,
})
nChansYAML += 1
electrodeID_Name.append('{}{}-{}'.format(port_id, frontEnd_id, frontEnd_electrode_id))
if nChansYAML!=nChans:
raise Exception(
'\nYAML chanNum (n={}) must match Device-ElectrodeGroup map (device: {}, expected # of Chans={})\n'.format(
nChansYAML, electrodeDicts[eD]['Name'], nChans) +
'YAML Group: {}\nYAML-electrode channels: {}'.format(
electrodesKeys[eD], electrodeID_Name
))
if nFrontEndsMicroStim>1:
print('WARNING¡¡ {} FrontEnd(s) were enabled for microstimulation\nThe code has NOT been updated to handle more than one\nYAML-FrontEnd(s) enabled:\n'.format(
nFrontEndsMicroStim
))
for i in range(nFrontEndsMicroStim):
print(frontEndsMicroStim[i])
print('\n')
# Check for unique MicroStim Channels in the YAML (first Rep : trial by Trial)
channelID_trials = []
for i in range(cls.getNumTrialsRep(dictYAML, repID=1)):
trial = cls.getTrial_by_Index(dictYAML, repID=1, trialIndex=i)
# For-loop of Stim List of Params
stimList = [value for key, value in trial.items() if key.startswith('Stim ')]
for dictStim in stimList:
# Get MicroStim (Check Amplitude, Duration, Frequency)
microStimParams = cls.getMicroStimParams(dictStim, dictYAML=dictYAML, verbose=False)
if microStimParams['valid']:
for chanID in microStimParams['microStim']['Channel']:
if chanID>0 and channelID_trials.count(chanID)==0:
channelID_trials.append(chanID)
# Check that there is only one microStimChannel in the list
electrodesMicroStim = []
for chanID in channelID_trials:
chanIDInfo = [electDict for electDict in electrodeList if electDict['frontEnd_electrode_id']==chanID]
if len(chanIDInfo)==1:
electrodesMicroStim.append(chanIDInfo[0])
else:
print('ElectrodeID = {}, was found in {}-frontEnd(s) : '.format(chanID, len(chanIDInfo)))
for chan_i in chanIDInfo:
print(chan_i)
raise Exception('It should NOT be more than one microStimulation electrode with the same ID')
return electrodesMicroStim
###########################################################
# fix Mode option : eye, eyeNoPostChoice, foot, mouse
###########################################################
@classmethod
def getFixMode(cls, dictYAML):
fixMode = []
dictExp = dictYAML['Experimental Visual Settings']
keys = list(dictExp.keys())
searchEyeFix = True
if keys.count('Eye Fixation Without PostChoice')==1:
if dictExp['Eye Fixation Without PostChoice']==1:
fixMode.append('eyeNoPostchoice')
searchEyeFix = False
if keys.count('Foot Fixation Mode')==1:
if dictExp['Foot Fixation Mode']==1:
fixMode.append('foot')
if keys.count('Eye Fixation Mode')==1:
if dictExp['Eye Fixation Mode']==1 and searchEyeFix:
fixMode.append('eye')
# Assume that when nothing was chosen, mouse was used
if len(fixMode)==0:
fixMode.append('mouse')
return '-'.join(fixMode)
###########################################################
# response Mode option : eye, foot, noResponse, mouse
###########################################################
@classmethod
def getReponseMode(cls, dictYAML):
dictExp = dictYAML['Experimental Visual Settings']
keys = list(dictExp.keys())
footResp = False
if keys.count('Foot Response Mode')==1:
if dictExp['Foot Response Mode']==1 and keys.count('Target On')==1:
footResp = True
footID = 'foot'
elif dictExp['Foot Response Mode']==1 and keys.count('Target Off')==1:
footResp = True
footID = 'noResponse'
eyeResp = False
if keys.count('Eye Response Mode')==1:
if dictExp['Eye Response Mode']==1:
eyeResp = True
if footResp and eyeResp:
raise Exception('Eye and Foot response is not a valid Response Mode, check the code for updates or YAML file for errors')
elif footResp and not eyeResp:
responseMode = footID
elif not footResp and eyeResp:
responseMode = 'eye'
else:
fixMode = cls.getFixMode(dictYAML)
if fixMode=='mouse':
responseMode = 'mouse'
elif fixMode=='eyeNoPostchoice-foot' or fixMode=='eyeNoPostchoice':
responseMode = 'foot'
else:
responseMode = fixMode
return responseMode
################################################################################################
# Get the max number of Tactile, MicroStim and Visual stim & ChoiceTargetsShown per Trial
# It will use the first Repetition
################################################################################################
@classmethod
def getMaxStimTypes(cls, dictYAML):
nStim = 0
nTactileStim = 0
nMicroStim = 0
nVisualStim = 0
nChoiceTargetsShown = 0
for i in range(cls.getNumTrialsRep(dictYAML, repID=1)):
trial = cls.getTrial_by_Index(dictYAML, repID=1, trialIndex=i)
choiceTargetsShown = len(str(trial['Showing Target IDs']).split(' '))
stim = 0
tactStim = 0
microStim = 0
visualStim = 0
stimList = [value for key, value in trial.items() if key.startswith('Stim ')]
# For-loop of Stim List of Params
for dictStim in stimList:
stim += 1
# Check TACTILE Amplitude and Duration are higher than 0
leftExists = dictStim[0]['Duration']>0 and dictStim[0]['Amp']>0 and dictStim[0]['Freq']>0
rightExists = dictStim[1]['Duration']>0 and dictStim[1]['Amp']>0 and dictStim[1]['Freq']>0
if leftExists or rightExists:
tactStim += 1
# Get MicroStim (Check Amplitude, Duration, Frequency)
microStimParams = cls.getMicroStimParams(dictStim, dictYAML=dictYAML, verbose=False)
if microStimParams['valid']:
microStim += 1
# Chek Visual CUES (it assumes is the last dictionary)
cueIDs = [int(c) for c in str(dictStim[-1]['ID']).split(' ')]
if max(cueIDs)>0:
visualStim += len([i for i in cueIDs if i >0])
if stim>nStim:
nStim = stim
if tactStim>nTactileStim:
nTactileStim = tactStim
if microStim>nMicroStim:
nMicroStim = microStim
if visualStim>nVisualStim:
nVisualStim = visualStim
if choiceTargetsShown>nChoiceTargetsShown:
nChoiceTargetsShown = choiceTargetsShown
if cls.getReponseMode(dictYAML) == 'noResponse':
nChoiceTargetsShown = 0
return {'nStim': nStim,'nTactileStim': nTactileStim, 'nMicroStim': nMicroStim,
'nVisualStim': nVisualStim, 'nChoiceTargetsShown': nChoiceTargetsShown}
#################################################################################
# GET CHANNEL ID for MICROSTIMULATION
#################################################################################
@classmethod
def getGlobal_microStim_channelID(cls, dictYAML):
# check if XIPP Stimulus channel exists
if 'XIPP Stimulus Channel' in dictYAML:
channels_global = [int(i) for i in str(dictYAML['XIPP Stimulus Channel']).split(' ')]
else:
# Search for Channel info on a trial by trial basis
channels_global = None
return channels_global
#################################################################################
# Get Tactile parameters from YAML stim-dictionary
#################################################################################
@classmethod
def getTactileStimParams(cls, dictStim):
# Search for LEFT & RIGHT parameters from Stim-dictionary
tactStimParams = {'leftValid': False, 'rightValid': False}
# Default indices:
# dictStim[0] = LEFT
# dictStim[1] = RIGHT
###################
# Add Info
shakerID = ['left', 'right']
for s in range(0, 2):
# Check if exist Stim based on amplitude, freq, Duration
amplitudeCheck = dictStim[s]['Amp']>0
durationCheck = dictStim[s]['Duration']>0
freqCheck = dictStim[s]['Freq']>0
tactStimParams[shakerID[s]+'Valid'] = all([amplitudeCheck, durationCheck, freqCheck])
if tactStimParams[shakerID[s]+'Valid']:
tactStimParams.update( {shakerID[s]: dictStim[s]})
# if tactile nor valid reset values to default TactParams
else:
tactStimParams.update( {shakerID[s]: labInfo['StimDefaults']['Tactile']})
return tactStimParams
#################################################################################
# GET RIPPLE Micro-Stim Paramters from YAML stim-dictionary
#################################################################################
@classmethod
def getMicroStimParams(cls, dictStim, dictYAML=None, microStimChannel=None, expStartTime=None, verbose=True):
checkChannels_in_Stim = True # Default search for XIPP Stimulus channel in Stim dictionary
# Check if dictYAML is an input and search for XIPP Stimulus Channel
if dictYAML is not None:
channels_global = cls.getGlobal_microStim_channelID(dictYAML)
if channels_global is not None:
checkChannels_in_Stim = False
if expStartTime is None:
if verbose:
print('WARNING¡ YAML-startTime will be use as a default for "XIPP Stimulus Channel Times"')
expStartTime = cls.getStartTimeSecs(dictYAML)
# Check if stimChannel is already an input (i.e., read it from dictYAML in advance)
# WARINING: This input will supersede/overwrite dictYAML['XIPP Stimulus Channel']
if microStimChannel is not None:
channels_global = microStimChannel
checkChannels_in_Stim = False
# Search for MicroStimulation parameters from Stim-dictionary
microStimParams = {'valid': False}
existsMicroStim = False
for dictParams in dictStim:
if 'XIPP Stimulus' in dictParams:
existsMicroStim = True
if checkChannels_in_Stim:
if 'XIPP Stimulus Channel' in dictParams:
channelIDs = [int(i) for i in str(dictParams['XIPP Stimulus Channel']).split(' ')]
else:
raise Exception('[XIPP Stimulus Channel] info was not found ¡¡\n{}'.format(
dictParams
))
else:
channelIDs = channels_global
if 'XIPP Stimulus Channel Times' in dictParams:
start_chans = dictParams['XIPP Stimulus Channel Times']['startTime']
stop_chans = dictParams['XIPP Stimulus Channel Times']['stopTime']
else:
if expStartTime is None:
raise Exception('No MicroStim TimeStamps were found')
noMicroStim_time = expStartTime + float(labInfo['StimDefaults']['NoTime'])
start_chans = [noMicroStim_time, noMicroStim_time, noMicroStim_time, noMicroStim_time]
stop_chans = [noMicroStim_time, noMicroStim_time, noMicroStim_time, noMicroStim_time]
microStimParams['microStim'] = {
'Stimulus': dictParams['XIPP Stimulus'],
'StartTime': dictParams['XIPP Stim Start Time'],
'Channel': channelIDs,
'ChannelStart_time': start_chans,
'ChannelStop_time': stop_chans,
'ReturnChannel': int(dictParams['XIPP Return Channel']),
'Duration': [float(i) for i in str(dictParams['XIPP Duration (Sec)']).split(' ')],
'Frequency': [float(i) for i in str(dictParams['XIPP Frequency (HZ)']).split(' ')],
'InterphaseInterval': [float(i) for i in str(dictParams['XIPP Interphase Interval (uSec)']).split(' ')],
'Phase1_Width': [float(i) for i in str(dictParams['XIPP Phase 1 Width (uSec)']).split(' ')],
'Phase1_Amp': [float(i) for i in str(dictParams['XIPP Phase 1 Amp (uA)']).split(' ')],
'Phase2_Width': [float(i) for i in str(dictParams['XIPP Phase 2 Width (uSec)']).split(' ')],
'Phase2_Amp': [float(i) for i in str(dictParams['XIPP Phase 2 Amp (uA)']).split(' ')],
}
if not existsMicroStim:
microStimParams['microStim'] = labInfo['StimDefaults']['MicroStim']
# Check if exist MicroStim based on amplitude, freq, Duration
widthCheck1 = any([value>0 for value in microStimParams['microStim']['Phase1_Width']])
amplitudeCheck1 = any([value!=0 for value in microStimParams['microStim']['Phase1_Amp']])
widthCheck2 = any([value>0 for value in microStimParams['microStim']['Phase2_Width']])
amplitudeCheck2 = any([value!=0 for value in microStimParams['microStim']['Phase2_Amp']])
durationCheck = any([value>0 for value in microStimParams['microStim']['Duration']])
freqCheck = any([value>0 for value in microStimParams['microStim']['Frequency']])
chanCheck = any([value>0 for value in microStimParams['microStim']['Channel']])
stimCheck = microStimParams['microStim']['Stimulus']>0
widthCheck = any([widthCheck1, widthCheck2])
amplitudeCheck = any([amplitudeCheck1, amplitudeCheck2])
microStimParams['valid'] = all([stimCheck, chanCheck, widthCheck, amplitudeCheck, durationCheck, freqCheck])
return microStimParams
#################################################################################
# GET VisualCue Paramters from YAML stim-dictionary
#################################################################################
@classmethod
def getVisualStimParams(cls, dictStim):
visualStimParams = {'valid': False}
# Last dict from STIM should be Visual
visualStimParams['visualStim'] = {
'StartTime': float(dictStim[-1]['Cue Start Time']),
'Duration': float(dictStim[-1]['Cue Duration']),
'ID': [int(visID) for visID in str(dictStim[-1]['ID']).split(' ') if int(visID)>0],
}
visualStimParams['visualStim']['nStim'] = len(visualStimParams['visualStim']['ID'])
visualStimParams['valid'] = visualStimParams['visualStim']['Duration']>0 and visualStimParams['visualStim']['nStim']>0
return visualStimParams
######################################################################################################
# GET SHAKER INFORMATION BodyPlacement, Calibration coefficients & accelerometer sensitivity
# from YAML dictionary
######################################################################################################
@classmethod
def getTactorInfo(cls, dictYAML):
accelerometer = [float(c) for c in str(dictYAML['Experimental Visual Settings']['Accelerometer Sensitivity']).split(' ')]
leftCoeff = [float(i) for i in str(dictYAML['Left Vibe Stim Coeffs']).split(' ')]
rightCoeff = [float(i) for i in str(dictYAML['Right Vibe Stim Coeffs']).split(' ')]
# Get how many freqs were tested with calibration
shakerInfo = {
'freqCalibration': [],
'leftCoeffA': [],
'leftCoeffB': [],
'rightCoeffA': [],
'rightCoeffB': [],
}
for f in range(0, len(leftCoeff), 3):
if leftCoeff[f]==rightCoeff[f]:
shakerInfo['freqCalibration'].append(leftCoeff[f])
shakerInfo['leftCoeffA'].append(leftCoeff[f+1])
shakerInfo['leftCoeffB'].append(leftCoeff[f+2])
shakerInfo['rightCoeffA'].append(rightCoeff[f+1])
shakerInfo['rightCoeffB'].append(rightCoeff[f+2])
shakerInfo.update(labInfo['ShakerInfo'])
return {
'leftBodyPart' : str(dictYAML['Subject Info']['Left Placement']['Body Placement']),
'leftSegment' : str(dictYAML['Subject Info']['Left Placement']['Segment']),
'leftIndentation' : float(dictYAML['Subject Info']['Left Placement']['Indentation Depth']),
'leftAcclSensitivity': accelerometer[0],
'rightBodyPart' : str(dictYAML['Subject Info']['Right Placement']['Body Placement']),
'rightSegment' : str(dictYAML['Subject Info']['Right Placement']['Segment']),
'rightIndentation' : float(dictYAML['Subject Info']['Right Placement']['Indentation Depth']),
'rightAcclSensitivity': accelerometer[1],
'device': shakerInfo,
}
#################################################################################
# GET ALL VISUALCUE(s) INFORMATION (nVisualCues, IDs, shapes, 'RGBA', 'Position')
# from YAML dictionary
#################################################################################
@classmethod
def getVisualCueInfo(cls, dictYAML):
visualCuesDict = dictYAML['Experimental Visual Settings']['Visual Cue Settings']
visualCuesInfo = {'n': len(visualCuesDict), 'ID': [], 'Shape':[], 'Size': [], 'RGBA': [], 'Position': []}
for _, visualCue in visualCuesDict.items():
visualCuesInfo['ID'].append(int(visualCue['ID']))
visualCuesInfo['Shape'].append(visualCue['Shape'])
visualCuesInfo['Size'].append([float(s) for s in str(visualCue['Size']).split(' ')])
visualCuesInfo['RGBA'].append([float(s) for s in str(visualCue['Color']).split(' ')])
visualCuesInfo['Position'].append([float(s) for s in str(visualCue['Pos']).split(' ')])
# Check when Visual Cues END
if 'Cue Off at Post Choice End' in dictYAML['Experimental Visual Settings']['Control Settings'].keys():
if dictYAML['Experimental Visual Settings']['Control Settings']['Cue Off at Post Choice End']:
visualCuesInfo['visualENDwith'] = 'fixationOFF'
else:
visualCuesInfo['visualENDwith'] = 'choiceTargetON'
else:
visualCuesInfo['visualENDwith'] = 'choiceTargetON'
return visualCuesInfo
#####################################################################################
# GET ALL CHOICETARGETs INFORMATION (nChoiceTargets, ID, shape, 'RGBA', 'Position', ''ChoiceTargets_Window'')
# from YAML dictionary
#####################################################################################
@classmethod
def getChoiceTargetInfo(cls, dictYAML):
choiceTargetDict = dictYAML['Experimental Visual Settings']['Choice Target']
choiceTargetsInfo = {'n': len(choiceTargetDict), 'ID': [], 'Shape':[], 'Size': [], 'RGBA': [], 'Position': [],
'ChoiceTargets_Window': [
float(dictYAML['Experimental Visual Settings']['Choice Target Window Size']['X']),
float(dictYAML['Experimental Visual Settings']['Choice Target Window Size']['Y'])
]}
for _, choiceTarget in choiceTargetDict.items():
choiceTargetsInfo['ID'].append(int(choiceTarget['ID']))
choiceTargetsInfo['Shape'].append(choiceTarget['Shape'])
choiceTargetsInfo['Size'].append([float(s) for s in str(choiceTarget['Size']).split(' ')])
choiceTargetsInfo['RGBA'].append([float(s) for s in str(choiceTarget['Color']).split(' ')])
choiceTargetsInfo['Position'].append([float(s) for s in str(choiceTarget['Pos']).split(' ')])
return choiceTargetsInfo
#####################################################################################
# GET INFORMATION From FIXATION POINT (shape, 'RGBA', 'Position', FixTargetWindow)
#####################################################################################
@classmethod
def getFixTargetInfo(cls, dictYAML):
fixTarget = dictYAML['Experimental Visual Settings']['Fixation Target']
fixWindow = dictYAML['Experimental Visual Settings']['Fixation Window Size']
return {
'fixTarget_Shape': fixTarget['Shape'],
'fixTarget_Size': [float(val) for val in fixTarget['Size'].split(' ')],
'fixTarget_RGBA': [float(val) for val in fixTarget['Color'].split(' ')],
'fixTarget_Position': [float(val) for val in fixTarget['Pos'].split(' ')],
'fixTarget_Window': [float(fixWindow['X']), float(fixWindow['Y'])],
}
###########################################################
# GET START DATETIME
###########################################################
@classmethod
def getStartDateTime(cls, dictYAML, TimeZone = 'America/Chicago'):