-
Notifications
You must be signed in to change notification settings - Fork 0
/
exp.py
1629 lines (1191 loc) · 60 KB
/
exp.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 PyVMEC2.hw as hw
import random, json, copy, math, os, sys, shutil, glob
import numpy as np
from scipy import optimize
from time import time
from psychopy import event
# from psychopy.hardware import keyboard
# from pyglet.window import key
# to make the scripts leaner, we should use numpy and homebrew for saving csvs, but:
#import pandas as pd
def runExperiment(experiment, participant):
# FROM: https://discourse.psychopy.org/t/keypress-using-event-watikeys-not-working-until-after-mouse-click/9288
# # Kill switch for Psychopy3
# esc_key= 'escape'
# def quit():
# """ quit programme"""
# print ('User exited')
# win.close()
# core.quit()
# # call globalKeys so that whenever user presses escape, quit function called
# event.globalKeys.add(key=esc_key, func=quit)
cfg = {}
cfg['run'] = {}
cfg['run']['experiment'] = experiment
cfg['run']['participant'] = participant
cfg['run']['jsonfile'] = 'experiments/%s/%s.json'%(experiment, experiment)
cfg = setupRun(cfg)
# active ESCAPE key
cfg = runTrialSequence(cfg)
def setupRun(cfg):
# setup folders and check if they are already there
# (and filled with some data?)
[cfg, doCrashRecovery] = setupFolder(cfg)
if doCrashRecovery:
cfg = crashRecovery(cfg)
else:
cfg = loadJSON(cfg)
cfg = seedRNG(cfg)
cfg = getTrialSequence(cfg)
# these two will have to be done regardless
# because they create non-hashable (binary) objects
cfg = hw.setupHardware(cfg)
cfg = loadScripts(cfg)
saveState(cfg)
return(cfg)
def setupFolder(cfg):
cfg['run']['path'] = 'experiments/%s/data/%s/'%(cfg['run']['experiment'], cfg['run']['participant'])
if (os.path.exists(cfg['run']['path'])):
print('participant path already exists')
doCrashRecovery = True
else:
os.makedirs(cfg['run']['path'])
shutil.copy('experiments/%s/%s.json'%(cfg['run']['experiment'],cfg['run']['experiment']),cfg['run']['path'])
doCrashRecovery = False
return([cfg, doCrashRecovery])
def crashRecovery(cfg):
print('crash recovery not implemented: exiting')
sys.exit(1)
# implement:
# - get state from state.json on path
# - log a crash recovery in the state
# - and setup the hardware again (and potentially other non-hashables)
return(cfg)
def loadJSON(cfg):
with open(cfg['run']['jsonfile']) as fp:
cfg.update(json.load(fp))
return(cfg)
def getTrialSequence(cfg):
cfg['run']['triallist'] = []
# # simple start... shouldn't this be in the json?
# cfg['run']['basictrial'] = {'target' : 0,
# 'rotation' : 0,
# 'cursor' : 'normal',
# 'name' : '' }
# we can add other functionality later on:
# - aiming, cursor/target jumps, points... holding home/target
for el in copy.deepcopy(cfg['experiment']):
if el['type'] == 'task':
cfg = addTaskTrials(cfg=cfg, el=el)
if el['type'] == 'aiming':
cfg = addAimingTrials(cfg=cfg, el=el)
if el['type'] == 'supertask':
cfg = addSuperTaskTrials(cfg=cfg, el=el)
if el['type'] == 'pause':
# insert a specific pause:
# - display (instruction) text
# - force a wait time
# - require key-press
# not implemented:
# show an image
# play a video or audio recording (from the web?)
cfg = addPauseTask(cfg=cfg, el=el)
pass
return(cfg)
def addTaskTrials(cfg, el):
task = copy.deepcopy(cfg['settings']['basictrial'])
task.update(el)
var_prop_names = []
if 'order' in task.keys():
for p in task.keys():
if isinstance(task[p], list) & (p in task['order'].keys()):
var_prop_names.append(p)
variable_properties = {}
for vpn in var_prop_names:
variable_properties[vpn] = []
nblocks = int(math.ceil(task['trials'] / len(task[vpn])))
for block in range(nblocks):
values = copy.deepcopy(task[vpn])
if task['order'][vpn] == 'pseudorandom':
random.shuffle(values)
variable_properties[vpn] += values
variable_properties[vpn] = variable_properties[vpn][:task['trials']]
if task['order'][vpn] == 'random':
random.shuffle(variable_properties[vpn])
# make the basic trial template:
trial = copy.deepcopy(cfg['settings']['basictrial'])
strippedtask = copy.deepcopy(task)
remove_entries = var_prop_names + ['order']
for k in remove_entries:
strippedtask.pop(k, None)
trial.update(strippedtask)
# psedurandomize in blocks:
for trialno in range(task['trials']):
# else: get a trial to add to the list:
thistrial = copy.deepcopy(trial)
for vpn in var_prop_names:
thistrial[vpn] = variable_properties[vpn][trialno]
unkeys = ['trials']
for k in unkeys:
if (k in thistrial.keys()):
del thistrial[k]
thistrial['type'] = 'trial'
cfg['run']['triallist'] += [thistrial]
return(cfg)
def addAimingTrials(cfg, el):
# print('placeholder function: addAimingTrials()\n no aiming trials added!')
# print(el)
task = el
var_prop_names = []
if 'order' in task.keys():
for p in task.keys():
if isinstance(task[p], list) & (p in task['order'].keys()):
var_prop_names.append(p)
variable_properties = {}
for vpn in var_prop_names:
variable_properties[vpn] = []
nblocks = int(math.ceil(task['trials'] / len(task[vpn])))
for block in range(nblocks):
values = copy.deepcopy(task[vpn])
if task['order'][vpn] == 'pseudorandom':
random.shuffle(values)
variable_properties[vpn] += values
variable_properties[vpn] = variable_properties[vpn][:task['trials']]
if task['order'][vpn] == 'random':
random.shuffle(variable_properties[vpn])
# make the basic trial template:
trial = copy.deepcopy(task)
# strippedtask = copy.deepcopy(task)
remove_entries = var_prop_names + ['order']
for k in remove_entries:
trial.pop(k, None)
# trial.update(strippedtask)
# psedurandomize in blocks:
for trialno in range(task['trials']):
# else: get a trial to add to the list:
thistrial = copy.deepcopy(trial)
for vpn in var_prop_names:
thistrial[vpn] = variable_properties[vpn][trialno]
unkeys = ['trials']
for k in unkeys:
if (k in thistrial.keys()):
del thistrial[k]
thistrial['type'] = 'aiming'
# print(thistrial)
cfg['run']['triallist'] += [thistrial]
return(cfg)
def addSuperTaskTrials(cfg, el):
# nsubtasks = len(el['subtasks'])
# nproperties = len(el['properties'])
# nrepeats = el['repeats']
# prepare the subtask properties:
# subtasks X properties
# these are all the properties we need to assign:
# pro_dic = {}
prop_orders = {}
for gr_no in range(len(el['linkedproperties'])):
gr = el['linkedproperties'][gr_no]
prop_orders[gr_no] = []
# these are all the properties that we need to assign:
pro_dic = {}
for k in el['properties'].keys():
pro_dic[k] = []
# and we need to assign them to each sub-task:
subtask_properties = {}
for k in range(len(el['subtasks'])):
subtask_properties[el['subtasks'][k]['name']] = copy.deepcopy(pro_dic)
# list with property values to populate subtasks
# this will be refilled when empty while
# looping through repeats of subtasks
prop_vals = copy.deepcopy(subtask_properties)
# now we use:
# - prop_vals, and
# - prop_orders
# to assign values of properties to each subtask on each repeat
# add trials to triallist:
for repeat in range(el['repeats']):
# determine task order:
taskorder = range(len(el['subtasks']))
if el['taskorder'] == 'pseudorandom':
random.shuffle(taskorder)
# set property orders in all property groups:
for property_group_no in range(len(el['linkedproperties'])):
property_group = el['linkedproperties'][property_group_no]
if len(prop_orders[property_group_no]) == 0:
pk = list(property_group['values'].keys())[0]
temp_order = list(range(len(property_group['values'][pk][0])))
if property_group['order'] == 'pseudorandom':
random.shuffle(temp_order)
prop_orders[property_group_no] = temp_order
#
for task_idx in taskorder:
task_name = el['subtasks'][task_idx]['name']
# set up a sub-task instance:
subtask = copy.deepcopy(el['subtasks'][task_idx])
# populate it with the variable properties:
for property in el['properties'].keys():
if len(prop_vals[task_name][property]) == 0:
temp_vals = copy.deepcopy(el['properties'][property]['values'][task_idx])
if el['properties'][property]['order'] == 'pseudorandom':
random.shuffle(temp_vals)
prop_vals[task_name][property] = temp_vals
app_val = prop_vals[task_name][property].pop(0)
subtask_properties[task_name][property] += [app_val]
subtask[property] = subtask_properties[task_name][property].pop(0)
# now get the subtask its linked properties:
for property_group_no in range(len(el['linkedproperties'])):
property_group = el['linkedproperties'][property_group_no]
for prop in property_group['values'].keys():
prop_val = property_group['values'][prop][task_idx][prop_orders[property_group_no][0]]
subtask[prop] = prop_val
# now the subtask could be handed to addTaskTrials?
if subtask['type'] == 'task':
cfg = addTaskTrials( el = subtask,
cfg = cfg )
if subtask['type'] == 'aiming':
cfg = addAimingTrials( el = subtask,
cfg = cfg )
if subtask['type'] == 'pause':
cfg = addPauseTask( cfg = cfg,
el = subtask )
# remove property value indices we just used:
for property_group_no in range(len(el['linkedproperties'])):
prop_orders[property_group_no].pop(0)
return(cfg)
# def addSuperTaskTrials(cfg, el):
# nsubtasks = len(el['subtasks'])
# nproperties = len(el['properties'])
# nrepeats = el['repeats']
# # prepare the subtask properties:
# # subtasks X properties
# pro_dic = {} # an empty placeholder for all properties that are varied across subtasks
# for k in el['properties'].keys():
# pro_dic[k] = []
# # print(pro_dic)
# subtask_properties = {} # properties dictionary for each subtask: the empty one just made
# for k in range(len(el['subtasks'])):
# subtask_properties[el['subtasks'][k]['name']] = copy.deepcopy(pro_dic)
# # print(subtask_properties) # still empty?
# # list with property values to populate subtasks
# # this will be refilled when empty while
# # looping through repeats of subtasks
# prop_vals = copy.deepcopy(subtask_properties)
# # add trials to triallist:
# for repeat in range(el['repeats']):
# # determine task order:
# taskorder = range(len(el['subtasks']))
# if el['taskorder'] == 'pseudorandom':
# random.shuffle(taskorder)
# for task_idx in range(len(el['subtasks'])):
# task_name = el['subtasks'][task_idx]['name']
# # set up a sub-task instance:
# subtask = copy.deepcopy(el['subtasks'][task_idx])
# # populate it with the variable properties:
# for property in el['properties'].keys():
# #print(property)
# if len(prop_vals[task_name][property]) == 0:
# temp_vals = copy.deepcopy(el['properties'][property]['values'][task_idx])
# if el['properties'][property]['order'] == 'pseudorandom':
# random.shuffle(temp_vals)
# prop_vals[task_name][property] = temp_vals
# #print(task_name, property)
# app_val = prop_vals[task_name][property].pop(0)
# subtask_properties[task_name][property] += [app_val]
# subtask[property] = subtask_properties[task_name][property].pop(0)
# # now the subtask could be handed to addTaskTrials?
# if subtask['type'] == 'task':
# cfg = addTaskTrials( el = subtask,
# cfg = cfg )
# if subtask['type'] == 'pause':
# cfg = addPauseTask( cfg = cfg,
# el = subtask )
# #print(subtask_properties)
# return(cfg)
def addPauseTask(cfg, el):
# strip properties of regular tasks?
# what now? just add it... I guess
cfg['run']['triallist'] += [el]
return(cfg)
def seedRNG(cfg):
if cfg['settings']['randomization'] == 'individual':
seed_string = copy.deepcopy(cfg['run']['participant'])
if cfg['settings']['randomization'] == 'standard':
seed_string = copy.deepcopy(cfg['name'])
#sum([ord(l) for l in list(seed_string)])
random.seed(seed_string)
# if we want 2 separate random number generator states, we could use:
# random.getstate()
# random.setstate()
# we keep the two states, and can seed one for the experiment /group
# and the other for the individual participant(s)
# that means some subtasks or properties can be the same for all participants
# but other things are randomized individually
# if the RNG states are hashable, they can be stored in the state.json as well
# for this, we return the cfg dict
return(cfg)
def runTrialSequence(cfg):
cfg['run']['trialidx'] = 0
performance = {}
performance['label'] = []
performance['targetangle_deg'] = []
performance['rotation'] = []
performance['handerrorgain'] = []
performance['feedbacktype'] = []
performance['reachdeviation_deg'] = []
performance['reactiontime_s'] = []
performance['movementtime_s'] = []
performance['scoredpoints'] = []
performance['cursorerrorgain'] = []
performance['trialstarttime_s'] = []
# performance['W_hat'] = []
performance['event_idx'] = []
for key in cfg['settings']['customvariables'].keys():
performance[key] = []
# cfg['run']['new_W_hat'] = 0
cfg['run']['performance'] = performance
# print(cfg['run']['performance'])
aiming = {}
aiming['targetangle_deg'] = []
aiming['arrowoffset_deg'] = []
aiming['arrowdeviation_deg'] = []
aiming['steps'] = []
aiming['completiontime_s'] = []
aiming['event_idx'] = []
cfg['run']['aiming'] = aiming
# points are in here:
cfg = initializeTrialState(cfg)
# and steps? could shortcut to step 6 or whatever immediately ends the trial later on...
while cfg['run']['trialidx'] < len(cfg['run']['triallist']):
trialdict = copy.copy(cfg['run']['triallist'][cfg['run']['trialidx']])
trialtype = copy.copy(trialdict['type'])
# IFF the pretrialscript key exists in the trial dictionary
if ('pretrialscript' in trialdict.keys()):
pretrialscript = trialdict['pretrialscript']
# AND it is not None (and actually a string: a filename)
if (isinstance(pretrialscript, str)):
# the script should be here:
if pretrialscript in cfg['bin']['scripts'].keys():
#print(pretrialscript)
# startPTSprep = time()
# fetch the binary version of the script:
code = cfg['bin']['scripts'][pretrialscript]
# get performance on previous trials:
performance = copy.deepcopy(cfg['run']['performance'])
# and the list of UPCOMING trials only
# triallist = copy.deepcopy(cfg['run']['triallist'][cfg['run']['trialidx']:])
# deepcopy takes lots of time, especially on the biggest object:
triallist = copy.copy(cfg['run']['triallist'][cfg['run']['trialidx']:])
# this is also the 1 object that we allow people to change, so we can just use 'copy' instead
# as well as the trialstate dictionary:
trialstate = copy.deepcopy(cfg['run']['trialstate'])
# and the trialdict dictionary? this is actually in the triallist... for ALL upcoming trials
# which are put in a 'globals' dictionary
g = globals()
g['performance'] = performance
g['triallist'] = triallist
g['trialstate'] = trialstate
g['new_W_hat'] = 0
# finishPTSprep = time()
# print('%0.3f s preparing pre-trial script'%(finishPTSprep-startPTSprep))
# accompanied by an empty 'locals' dictionary
l = {}
# and it is executed
exec(code, g, l)
for check_key in l.keys():
if check_key == 'triallist':
cfg['run']['triallist'][cfg['run']['trialidx']:] = copy.copy(l['triallist'])
if check_key == 'new_W_hat':
cfg['run']['new_W_hat'] = copy.deepcopy(l['new_W_hat'])
if check_key == 'trialstate':
cfg['run']['trialstate']['persistent']['customvariables']['variables'] = copy.deepcopy(l['trialstate']['persistent']['customvariables']['variables'])
# # the updated triallist should now be in the 'locals' dictionary
# # so we copy it to the the running trial list
# cfg['run']['triallist'][cfg['run']['trialidx']:] = copy.deepcopy(l['triallist'])
# cfg['run']['new_W_hat'] = copy.deepcopy(l['new_W_hat'])
# cfg['run']['trialstate']['persistent']['customvariables']['variables'] = copy.deepcopy(l['trialstate']['persistent']['customvariables']['variables'])
# # print(cfg['run']['new_W_hat'])
if cfg['run']['trialidx'] >= len(cfg['run']['triallist']):
# break out of the while loop:
break
print('EVENT:',cfg['run']['trialidx']+1,' / ', len(cfg['run']['triallist']))
trialdict = copy.copy(cfg['run']['triallist'][cfg['run']['trialidx']])
trialtype = copy.copy(trialdict['type'])
if trialtype == 'trial':
print('type:', trialtype,
'cursor:', trialdict['cursor'],
'rot:', trialdict['rotation'],
'target:', trialdict['target'])
[cfg, trialdata] = runTrial(cfg=cfg)
# startSaveTrial = time()
# SAVE TRIAL DATA as file
saveTrialdata(cfg=cfg, trialdata=trialdata)
# finishSaveTrial = time()
# print('%0.3f s spent saving trial data'%(finishSaveTrial-startSaveTrial))
# store stuff in performance as well
# startStorePerformance = time()
cfg = storePerformance(cfg=cfg, trialdata=trialdata)
# finishStorePerformance = time()
# print('%0.3f s spent storing performance'%(finishStorePerformance-startStorePerformance))
if trialtype == 'pause':
cfg = runPause(cfg=cfg)
if trialtype == 'aiming':
cfg = runAiming(cfg=cfg)
# this has to be at the very end!
cfg['run']['trialidx'] +=1
# well... before this anyway:
saveState(cfg) # should this be called "saveState()" ?
savePerformance(cfg) # shorthand data... might be sufficient for some analyses?
saveAiming(cfg)
cfg['hw']['display'].shutDown()
return(cfg)
def runTrial(cfg):
# startTrialSetup = time()
trialdict = copy.deepcopy(cfg['run']['triallist'][cfg['run']['trialidx']])
# set step to -3, scoredpoints to 0, and all stimuli to not be shown
cfg = resetTransientTrialState(cfg)
# record trial start time:
cfg['run']['trialstate']['transient']['trialstarttime'] = time()
targetPos = getTargetPos(cfg)
targetangle_deg = trialdict['target']
targetangle_rad = (targetangle_deg/180) * math.pi
homePos = [0,0] # this could be changed at some point?
# three kinds of perturbations of visual feedback:
# 1: rotations:
rotation_deg = trialdict['rotation']
rotation_rad = (rotation_deg/180)*math.pi
# 2: cursor error gains:
if 'cursorerrorgain' in trialdict.keys():
cursorerrorgain = trialdict['cursorerrorgain']
else:
trialdict['cursorerrorgain'] = 1
cursorerrorgain = 1
# 2: hand error gains:
if 'handerrorgain' in trialdict.keys():
handerrorgain = trialdict['handerrorgain']
else:
trialdict['handerrorgain'] = 1
handerrorgain = 1
# 3: distance gains:
distancegain = 1 # NO USE FOR THIS YET: IMPLEMENT LATER
if trialdict['cursor'] == 'clamped':
clamped = True
else:
clamped = False
if 'holddurations' in trialdict.keys():
holddurations = trialdict['holddurations']
if 'start' not in holddurations.keys():
holddurations['start'] = 0.000
if 'target' not in holddurations.keys():
holddurations['target'] = 0.000
if 'finish' not in holddurations.keys():
holddurations['finish'] = 0.000
else:
holddurations = { 'start' : 0.000,
'target' : 0.000,
'finish' : 0.000 }
trialdict['holddurations'] = holddurations
# we need the radius of things:
[home_radius, target_radius, cursor_radius] = getRadii(cfg)
# feedbacktypes:
# - cursor (regular / default)
# - no-cursor (for reach aftereffects)
# - clamped (this can have a rotation or distancegain perturbation, but not the errorgain)
# we collect data about the trial here:
trialdata = copy.deepcopy(trialdict)
# we add lists to collect the trajectory:
trialdata['handx'] = []
trialdata['handy'] = []
trialdata['time'] = []
trialdata['step'] = []
trialdata['events'] = []
# what else?
trialdata['targetpos'] = targetPos
trialdata['scoredpoints'] = 0
#
# STEPS:
# -3 = get to home position before actual trial starts
# -2 = hold - without target (timehold)
# -1 = hold - with target (prephold)
# 0 = at home, start moving (go signal)
# 1 = left home, moving to target
# 2 = arrived at target or target distance or stopped at minimal distance... (include wait/hold at end point?)
# 3 = at target, home is there: start moving (or target-distance)
# 4 = moving back, not there yet
# 5 = at home... wait for some short period?
# 6 = post-trial period... ? maybe?
home_target_distance = getDistance(homePos, targetPos)
target_radius = cfg['hw']['display'].target.radius
inprogress = True
planned_events = []
# finishTrialSetup = time()
# print('time spent setting up trial: %0.1f s'%(finishTrialSetup-startTrialSetup))
while inprogress:
# visual feedback location depends on real location as well:
[X,Y,time_s] = cfg['hw']['tracker'].getPos()
trackerPos = [X,Y]
frame_events = []
cursorPos = trackerPos
home_cursor_distance = getDistance(homePos, cursorPos)
target_cursor_distance = getDistance(targetPos, cursorPos)
if clamped:
# cursorPos = [homePos[0] + (math.cos(targetangle_rad)*home_cursor_distance),
# homePos[1] + (math.sin(targetangle_rad)*home_cursor_distance)]
relX, relY, unrot = cursorPos[0] - homePos[0], cursorPos[1] - homePos[1], -1 * targetangle_rad
relX, relY = (relX * math.cos(unrot)) - (relY * math.sin(unrot)), 0
#print([relX, relY])
cursorPos = [(relX * math.cos(targetangle_rad)) - (relY * math.sin(targetangle_rad)),
(relX * math.sin(targetangle_rad)) + (relY * math.cos(targetangle_rad))]
if (handerrorgain != 1) and (not clamped):
relX, relY = cursorPos[0] - homePos[0], cursorPos[1] - homePos[1]
unrot = -1 * targetangle_rad
relativeCursorPos = [(relX * math.cos(unrot)) - (relY * math.sin(unrot)),
(relX * math.sin(unrot)) + (relY * math.cos(unrot))]
relativeCursorRad = math.atan2(relativeCursorPos[1], relativeCursorPos[0]) * handerrorgain
cursorPos = [(math.cos(targetangle_rad + relativeCursorRad) * home_cursor_distance) + homePos[0],
(math.sin(targetangle_rad + relativeCursorRad) * home_cursor_distance) + homePos[1]]
if rotation_deg != 0:
relX, relY = cursorPos[0] - homePos[0], cursorPos[1] - homePos[1]
unrot = -1 * targetangle_rad
relativeCursorPos = [(relX * math.cos(unrot)) - (relY * math.sin(unrot)),
(relX * math.sin(unrot)) + (relY * math.cos(unrot))]
relativeCursorRad = math.atan2(relativeCursorPos[1], relativeCursorPos[0])
cursorPos = [(math.cos(targetangle_rad + relativeCursorRad + rotation_rad) * home_cursor_distance) + homePos[0],
(math.sin(targetangle_rad + relativeCursorRad + rotation_rad) * home_cursor_distance) + homePos[1]]
if (cursorerrorgain != 1) and (not clamped):
relX, relY = cursorPos[0] - homePos[0], cursorPos[1] - homePos[1]
unrot = -1 * targetangle_rad
relativeCursorPos = [(relX * math.cos(unrot)) - (relY * math.sin(unrot)),
(relX * math.sin(unrot)) + (relY * math.cos(unrot))]
relativeCursorRad = math.atan2(relativeCursorPos[1], relativeCursorPos[0]) * cursorerrorgain
cursorPos = [(math.cos(targetangle_rad + relativeCursorRad) * home_cursor_distance) + homePos[0],
(math.sin(targetangle_rad + relativeCursorRad) * home_cursor_distance) + homePos[1]]
# recalculate distances with updated positions:
home_cursor_distance = getDistance(homePos, cursorPos)
target_cursor_distance = getDistance(targetPos, cursorPos)
# STEPS NEED TO BE TAKEN:
if cfg['run']['trialstate']['transient']['step'] < -1:
if (home_cursor_distance <= home_radius):
# start hold:
cfg['run']['trialstate']['transient']['step'] = -1
cfg['run']['trialstate']['transient']['StartHoldStartTime'] = copy.deepcopy(time_s)
if cfg['run']['trialstate']['transient']['step'] == -1:
if (home_cursor_distance > home_radius):
cfg['run']['trialstate']['transient']['step'] = -2
elif time_s >= (cfg['run']['trialstate']['transient']['StartHoldStartTime'] + holddurations['start']):
# hold is completed, we move on to step 0, and that is "go time"
cfg['run']['trialstate']['transient']['step'] = 0
cfg['run']['trialstate']['transient']['gotime'] = time_s
# if cfg['run']['trialstate']['transient']['step'] == 0:
# # PERIOD BEFORE CURSOR IS AT HOME
# # SPLIT FOR HOLD PERIODS... right now: only the go to home part
# if (home_cursor_distance <= home_radius):
# cfg['run']['trialstate']['transient']['step'] = 0
if cfg['run']['trialstate']['transient']['step'] == 0:
# AT HOME WITH TARGET PRESENTED... WAITING FOR REACTION
if (home_cursor_distance > home_radius):
# print('entering step 1')
cfg['run']['trialstate']['transient']['step'] = 1
cfg['run']['trialstate']['transient']['reactiontime'] = time_s - cfg['run']['trialstate']['transient']['gotime']
# cfg['run']['trialstate']['transient']['TargetHoldStartTime'] = 0
# cfg['run']['trialstate']['transient']['TargetHoldLocation'] = [0,0]
if cfg['run']['trialstate']['transient']['step'] == 1:
# IF criterion is DISTANCE:
if trialdict['reachcompletioncriterion']['type'] == 'homecursordistance':
if home_cursor_distance > (trialdict['reachcompletioncriterion']['hometargetdistance_prop'] * home_target_distance):
cfg['run']['trialstate']['transient']['step'] = 2
cfg['run']['trialstate']['transient']['TargetHoldStartTime'] = copy.deepcopy(time_s)
cfg['run']['trialstate']['transient']['TargetHoldLocation'] = cursorPos
# IF criterion is ACQUIRE:
if trialdict['reachcompletioncriterion']['type'] == 'acquire':
if target_cursor_distance < (trialdict['reachcompletioncriterion']['targetradius_prop'] * target_radius):
cfg['run']['trialstate']['transient']['step'] = 2
cfg['run']['trialstate']['transient']['TargetHoldStartTime'] = copy.deepcopy(time_s)
# update times in transient trial state upon reach completion:
if cfg['run']['trialstate']['transient']['step'] == 2:
cfg['run']['trialstate']['transient']['movementtime'] = time_s - cfg['run']['trialstate']['transient']['gotime'] - cfg['run']['trialstate']['transient']['reactiontime']
cfg['run']['trialstate']['transient']['completiontime'] = cfg['run']['trialstate']['transient']['reactiontime'] + cfg['run']['trialstate']['transient']['movementtime']
if cfg['run']['trialstate']['transient']['step'] == 2:
if trialdict['reachcompletioncriterion']['type'] == 'acquire':
if target_cursor_distance > (trialdict['reachcompletioncriterion']['targetradius_prop'] * target_radius):
cfg['run']['trialstate']['transient']['step'] = 1 # going back to previous state
elif time_s >= (cfg['run']['trialstate']['transient']['TargetHoldStartTime'] + holddurations['target']):
cfg['run']['trialstate']['transient']['step'] = 3
if trialdict['reachcompletioncriterion']['type'] == 'homecursordistance':
distmoved = getDistance(cfg['run']['trialstate']['transient']['TargetHoldLocation'], cursorPos)
if distmoved > (trialdict['reachcompletioncriterion']['hometargetdistance_prop'] * target_radius):
cfg['run']['trialstate']['transient']['step'] = 1 # going back to previous state
elif time_s >= (cfg['run']['trialstate']['transient']['TargetHoldStartTime'] + holddurations['target']):
cfg['run']['trialstate']['transient']['step'] = 3
if cfg['run']['trialstate']['transient']['step'] == 3:
# check if people have left the target:
if (home_cursor_distance < (home_target_distance - target_radius)):
#print('entering step 4')
cfg['run']['trialstate']['transient']['step'] = 4
# if cfg['run']['trialstate']['transient']['step'] == -1:
# if (home_cursor_distance > home_radius):
# cfg['run']['trialstate']['transient']['step'] = -2
# elif time_s >= (cfg['run']['trialstate']['transient']['StartHoldStartTime'] + holddurations['start']):
# # hold is completed, we move on to step 0, and that is "go time"
# cfg['run']['trialstate']['transient']['step'] = 0
# going back to the home position:
if cfg['run']['trialstate']['transient']['step'] == 4:
# print('in step 4')
if (home_cursor_distance < home_radius):
# print('switching to step 5')
cfg['run']['trialstate']['transient']['step'] = 5
cfg['run']['trialstate']['transient']['FinishHoldStartTime'] = copy.deepcopy(time_s)
# back at home
if cfg['run']['trialstate']['transient']['step'] == 5:
# print('in step 5')
# print('hold duration: %0.3f s'%(time_s - cfg['run']['trialstate']['transient']['FinishHoldStartTime']))
if (home_cursor_distance > home_radius):
# print('back to step 4...')
cfg['run']['trialstate']['transient']['step'] = 4
#cfg['run']['trialstate']['transient']['FinishHoldStartTime'] = time_s
elif time_s >= (cfg['run']['trialstate']['transient']['FinishHoldStartTime'] + holddurations['finish']):
cfg['run']['trialstate']['transient']['step'] = 6 # not sure what this would do, maybe a blank screen, but for now we say:
inprogress = False
# record trajectory:
trialdata['handx'].append(trackerPos[0])
trialdata['handy'].append(trackerPos[1])
trialdata['time'].append(time_s)
trialdata['step'].append(cfg['run']['trialstate']['transient']['step'])
trialdata['events'].append('') #
# distances to check feedback rules:
distances = {}
distances['home_cursor_distance'] = home_cursor_distance
distances['target_cursor_distance'] = target_cursor_distance
distances['home_target_distance'] = home_target_distance
# positions to implement certain feedback:
positions = {}
positions['home_pos'] = homePos
positions['cursor_pos'] = cursorPos
positions['target_pos'] = targetPos
# startCFB = time()
# check feedback rules:
trialdict = checkFeedbackRules( cfg = cfg,
trialdict = trialdict,
trialdata = trialdata,
distances = distances,
positions = positions )
# finishCFB = time()
# print('time spent checking feedback-rules: %0.f s'%(finishCFB - startCFB))
# see if anything needs to happen right now:
[cfg, trialdict] = handleEvents( cfg = cfg,
trialdict = trialdict,
trialdata = trialdata ) # not using trialdata so far...
# show visual elements
# THIS SHOULD BE OUTSOURCED to a function:
if (cfg['run']['trialstate']['transient']['showImprintTarget']):
cfg['hw']['display'].showTargetImprint(cfg['run']['trialstate']['transient']['imprintTargetPos'])
if (cfg['run']['trialstate']['transient']['showImprintCursor']):
cfg['hw']['display'].showCursorImprint(cfg['run']['trialstate']['transient']['imprintCursorPos'])
if (cfg['run']['trialstate']['transient']['showHome']):
cfg['hw']['display'].showHome(homePos)
if cfg['run']['trialstate']['transient']['showTargetArc']:
cfg['hw']['display'].showTargetArc(homePos)
if cfg['run']['trialstate']['transient']['showTarget']:
cfg['hw']['display'].showTarget(targetPos)
if cfg['run']['trialstate']['transient']['showCursor']:
cfg['hw']['display'].showCursor(cursorPos)
# instr = 'step: %d'%cfg['run']['trialstate']['transient']['step']
# cfg['hw']['display'].showInstructions(txt = instr,
# pos = (-8,-4) )
cfg['hw']['display'].doFrame()
return([cfg, trialdata])
def getTargetPos(cfg):
# get target angle:
trialdict = copy.deepcopy(cfg['run']['triallist'][cfg['run']['trialidx']])
# we need angle and distance:
angle = trialdict['target']
rad = (angle/180) * math.pi
# do we use norm or cm distance? depends on display-unit:
if (cfg['hw']['display'].units == 'cm'):
dist = trialdict['targetdistance_cm']
if (cfg['hw']['display'].units == 'norm'):
dist = trialdict['targetdistance_norm']
X = math.cos(rad) * dist
Y = math.sin(rad) * dist
return([X,Y])
def getRadii(cfg):
stimuli = copy.deepcopy(cfg['settings']['stimuli'])
home_radius = stimuli['home']['radius_cm']
target_radius = stimuli['target']['radius_cm']
cursor_radius = stimuli['cursor']['radius_cm']
# convert to norm units, if display uses those:
if (cfg['hw']['display'].units == 'norm'):
# for now: NO CONVERSION!
[home_radius, target_radius, cursor_radius] = cfg['hw']['display'].cm2norm([home_radius, target_radius, cursor_radius])
return([home_radius, target_radius, cursor_radius])
def getDistance(pos_a, pos_b=None):
# maybe this should be dimensionality agnostic
# so it could work in VR too?
if pos_b == None:
pos_b = [0,0]
return( math.sqrt( (pos_a[0]-pos_b[0])**2 + (pos_a[1]-pos_b[1])**2 ) )
def runPause(cfg):