-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnew_8T.py
2523 lines (2231 loc) · 122 KB
/
new_8T.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This experiment was created using PsychoPy3 Experiment Builder (v2023.2.2),
on 二月 12, 2024, at 13:17
If you publish work using this script the most relevant publication is:
Peirce J, Gray JR, Simpson S, MacAskill M, Höchenberger R, Sogo H, Kastman E, Lindeløv JK. (2019)
PsychoPy2: Experiments in behavior made easy Behav Res 51: 195.
https://doi.org/10.3758/s13428-018-01193-y
"""
# --- Import packages ---
from psychopy import locale_setup
from psychopy import prefs
from psychopy import plugins
plugins.activatePlugins()
prefs.hardware['audioLib'] = 'ptb'
prefs.hardware['audioLatencyMode'] = '3'
from psychopy import sound, gui, visual, core, data, event, logging, clock, colors, layout
from psychopy.tools import environmenttools
from psychopy.constants import (NOT_STARTED, STARTED, PLAYING, PAUSED,
STOPPED, FINISHED, PRESSED, RELEASED, FOREVER, priority)
import numpy as np # whole numpy lib is available, prepend 'np.'
from numpy import (sin, cos, tan, log, log10, pi, average,
sqrt, std, deg2rad, rad2deg, linspace, asarray)
from numpy.random import random, randint, normal, shuffle, choice as randchoice
import os # handy system and path functions
import sys # to get file system encoding
import psychopy.iohub as io
from psychopy.hardware import keyboard
# --- Setup global variables (available in all functions) ---
# Ensure that relative paths start from the same directory as this script
_thisDir = os.path.dirname(os.path.abspath(__file__))
# Store info about the experiment session
psychopyVersion = '2023.2.2'
expName = 'new_8T' # from the Builder filename that created this script
expInfo = {
'participant': '001',
'group': '0',
'date': data.getDateStr(), # add a simple timestamp
'expName': expName,
'psychopyVersion': psychopyVersion,
}
def showExpInfoDlg(expInfo):
"""
Show participant info dialog.
Parameters
==========
expInfo : dict
Information about this experiment, created by the `setupExpInfo` function.
Returns
==========
dict
Information about this experiment.
"""
# temporarily remove keys which the dialog doesn't need to show
poppedKeys = {
'date': expInfo.pop('date', data.getDateStr()),
'expName': expInfo.pop('expName', expName),
'psychopyVersion': expInfo.pop('psychopyVersion', psychopyVersion),
}
# show participant info dialog
dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
if dlg.OK == False:
core.quit() # user pressed cancel
# restore hidden keys
expInfo.update(poppedKeys)
# return expInfo
return expInfo
def setupData(expInfo, dataDir=None):
"""
Make an ExperimentHandler to handle trials and saving.
Parameters
==========
expInfo : dict
Information about this experiment, created by the `setupExpInfo` function.
dataDir : Path, str or None
Folder to save the data to, leave as None to create a folder in the current directory.
Returns
==========
psychopy.data.ExperimentHandler
Handler object for this experiment, contains the data to save and information about
where to save it to.
"""
# data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
if dataDir is None:
dataDir = _thisDir
filename = u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date'])
# make sure filename is relative to dataDir
if os.path.isabs(filename):
dataDir = os.path.commonprefix([dataDir, filename])
filename = os.path.relpath(filename, dataDir)
# an ExperimentHandler isn't essential but helps with data saving
thisExp = data.ExperimentHandler(
name=expName, version='',
extraInfo=expInfo, runtimeInfo=None,
originPath='D:\\PSYCHOPY\\eyehand_baseline\\new_8T.py',
savePickle=True, saveWideText=True,
dataFileName=dataDir + os.sep + filename, sortColumns='time'
)
thisExp.setPriority('thisRow.t', priority.CRITICAL)
thisExp.setPriority('expName', priority.LOW)
# return experiment handler
return thisExp
def setupLogging(filename):
"""
Setup a log file and tell it what level to log at.
Parameters
==========
filename : str or pathlib.Path
Filename to save log file and data files as, doesn't need an extension.
Returns
==========
psychopy.logging.LogFile
Text stream to receive inputs from the logging system.
"""
# this outputs to the screen, not a file
logging.console.setLevel(logging.EXP)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=logging.EXP)
return logFile
def setupWindow(expInfo=None, win=None):
"""
Setup the Window
Parameters
==========
expInfo : dict
Information about this experiment, created by the `setupExpInfo` function.
win : psychopy.visual.Window
Window to setup - leave as None to create a new window.
Returns
==========
psychopy.visual.Window
Window in which to run this experiment.
"""
if win is None:
# if not given a window to setup, make one
win = visual.Window(
size=[1920, 1080], fullscr=True, screen=0,
winType='pyglet', allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
backgroundImage='', backgroundFit='none',
blendMode='avg', useFBO=True,
units='cm'
)
if expInfo is not None:
# store frame rate of monitor if we can measure it
expInfo['frameRate'] = win.getActualFrameRate()
else:
# if we have a window, just set the attributes which are safe to set
win.color = [0,0,0]
win.colorSpace = 'rgb'
win.backgroundImage = ''
win.backgroundFit = 'none'
win.units = 'cm'
win.mouseVisible = False
win.hideMessage()
return win
def setupInputs(expInfo, thisExp, win):
"""
Setup whatever inputs are available (mouse, keyboard, eyetracker, etc.)
Parameters
==========
expInfo : dict
Information about this experiment, created by the `setupExpInfo` function.
thisExp : psychopy.data.ExperimentHandler
Handler object for this experiment, contains the data to save and information about
where to save it to.
win : psychopy.visual.Window
Window in which to run this experiment.
Returns
==========
dict
Dictionary of input devices by name.
"""
# --- Setup input devices ---
inputs = {}
ioConfig = {}
# Setup eyetracking
ioConfig['eyetracker.hw.pupil_labs.pupil_core.EyeTracker'] = {
'name': 'tracker',
'runtime_settings': {
'pupillometry_only': False,
'surface_name': 'psychopy_iohub_surface',
'confidence_threshold': 0.6,
'pupil_remote': {
'ip_address': '127.0.0.1',
'port': 50020.0,
'timeout_ms': 1000.0,
},
'pupil_capture_recording': {
'enabled': True,
'location': '',
}
}
}
# Setup iohub keyboard
ioConfig['Keyboard'] = dict(use_keymap='psychopy')
ioSession = '1'
if 'session' in expInfo:
ioSession = str(expInfo['session'])
ioServer = io.launchHubServer(window=win, **ioConfig)
eyetracker = ioServer.getDevice('tracker')
# create a default keyboard (e.g. to check for escape)
defaultKeyboard = keyboard.Keyboard(backend='iohub')
# return inputs dict
return {
'ioServer': ioServer,
'defaultKeyboard': defaultKeyboard,
'eyetracker': eyetracker,
}
def pauseExperiment(thisExp, inputs=None, win=None, timers=[], playbackComponents=[]):
"""
Pause this experiment, preventing the flow from advancing to the next routine until resumed.
Parameters
==========
thisExp : psychopy.data.ExperimentHandler
Handler object for this experiment, contains the data to save and information about
where to save it to.
inputs : dict
Dictionary of input devices by name.
win : psychopy.visual.Window
Window for this experiment.
timers : list, tuple
List of timers to reset once pausing is finished.
playbackComponents : list, tuple
List of any components with a `pause` method which need to be paused.
"""
# if we are not paused, do nothing
if thisExp.status != PAUSED:
return
# pause any playback components
for comp in playbackComponents:
comp.pause()
# prevent components from auto-drawing
win.stashAutoDraw()
# run a while loop while we wait to unpause
while thisExp.status == PAUSED:
# make sure we have a keyboard
if inputs is None:
inputs = {
'defaultKeyboard': keyboard.Keyboard(backend='ioHub')
}
# check for quit (typically the Esc key)
if inputs['defaultKeyboard'].getKeys(keyList=['escape']):
endExperiment(thisExp, win=win, inputs=inputs)
# flip the screen
win.flip()
# if stop was requested while paused, quit
if thisExp.status == FINISHED:
endExperiment(thisExp, inputs=inputs, win=win)
# resume any playback components
for comp in playbackComponents:
comp.play()
# restore auto-drawn components
win.retrieveAutoDraw()
# reset any timers
for timer in timers:
timer.reset()
def run(expInfo, thisExp, win, inputs, globalClock=None, thisSession=None):
"""
Run the experiment flow.
Parameters
==========
expInfo : dict
Information about this experiment, created by the `setupExpInfo` function.
thisExp : psychopy.data.ExperimentHandler
Handler object for this experiment, contains the data to save and information about
where to save it to.
psychopy.visual.Window
Window in which to run this experiment.
inputs : dict
Dictionary of input devices by name.
globalClock : psychopy.core.clock.Clock or None
Clock to get global time from - supply None to make a new one.
thisSession : psychopy.session.Session or None
Handle of the Session object this experiment is being run from, if any.
"""
# mark experiment as started
thisExp.status = STARTED
# make sure variables created by exec are available globally
exec = environmenttools.setExecEnvironment(globals())
# get device handles from dict of input devices
ioServer = inputs['ioServer']
defaultKeyboard = inputs['defaultKeyboard']
eyetracker = inputs['eyetracker']
# make sure we're running in the directory for this experiment
os.chdir(_thisDir)
# get filename from ExperimentHandler for convenience
filename = thisExp.dataFileName
frameTolerance = 0.001 # how close to onset before 'same' frame
endExpNow = False # flag for 'escape' or other condition => quit the exp
# get frame duration from frame rate in expInfo
if 'frameRate' in expInfo and expInfo['frameRate'] is not None:
frameDur = 1.0 / round(expInfo['frameRate'])
else:
frameDur = 1.0 / 60.0 # could not measure, so guess
# Start Code - component code to be run after the window creation
# --- Initialize components for Routine "eye_tracker_connect" ---
# Run 'Begin Experiment' code from eye_connect_code
if eyetracker:
import zmq
import msgpack as serializer
from time import sleep, time
# Setup zmq context and remote helper
ctx = zmq.Context()
pupil_remote = zmq.Socket(ctx, zmq.REQ)
pupil_remote.connect('tcp://127.0.0.1:50020')
pupil_remote.send_string("PUB_PORT")
pub_port = pupil_remote.recv_string()
pub_socket = zmq.Socket(ctx, zmq.PUB)
pub_socket.connect("tcp://127.0.0.1:" + str(pub_port))
# set time to psychopy clock
# an internal clock which starts when the experiment starts
time_fn = core.monotonicClock.getTime
# set pupil's time to psychopy time
pupil_remote.send_string("T " + str(time_fn()))
print(pupil_remote.recv_string())
sleep(2.)
# send notification:
def notify(notification):
"""Sends ``notification`` to Pupil Remote"""
topic = "notify." + notification["subject"]
payload = serializer.dumps(notification, use_bin_type=True)
pupil_remote.send_string(topic, flags=zmq.SNDMORE)
pupil_remote.send(payload)
return pupil_remote.recv_string()
def send_trigger(trigger):
payload = serializer.dumps(trigger, use_bin_type=True)
pub_socket.send_string(trigger["topic"], flags=zmq.SNDMORE)
pub_socket.send(payload)
# Start the annotations plugin
notify({"subject": "start_plugin", "name": "Annotation_Capture", "args": {}})
# start recording
pupil_remote.send_string('R')
print(pupil_remote.recv_string())
sleep(1.)
def new_trigger(label, duration):
return {
"topic": "annotation",
"label": label,
"timestamp": time_fn(),
"duration": duration,
}
label = "start_experiment"
duration = 0.
minimal_trigger = new_trigger(label, duration)
send_trigger(minimal_trigger)
sleep(1.)
else:
continueRoutine = False
# --- Initialize components for Routine "eye_calibration" ---
# --- Initialize components for Routine "instruction_baseline" ---
instruction_baseline_text = visual.TextStim(win=win, name='instruction_baseline_text',
text='The green cursor represents the position of your hand movement.\n\nYou must start from the starting point in the center of the screen and move towards to hit the black target point that appears.\n\nYou should move in a straight line as fast and accurately as you can towards the target.\n\nOnce you hit the target, return to the starting point and wait for the next target to appear.\n\nPress [space] to continue...',
font='Open Sans',
pos=(0, 0), height=1.0, wrapWidth=None, ori=0.0,
color='white', colorSpace='rgb', opacity=1.0,
languageStyle='LTR',
depth=0.0);
instruction_baseline_key = keyboard.Keyboard()
# --- Initialize components for Routine "baseline" ---
# Run 'Begin Experiment' code from code_baseline
from psychopy.tools.coordinatetools import cart2pol
from psychopy.tools.coordinatetools import pol2cart
import random
from time import sleep
# Calculate Euclidean distance 计算欧氏距离
def euclidean_dist(vec1, vec2):
return sqrt((vec1[0] - vec2[0])**2 + (vec1[1] - vec2[1])**2)
# origin hold durations
random_origin_durations = [0.8, 1.0, 1.2, 1.4, 1.6]
# might change depending on which computer/screen is being used
target_radius = 16 # 12 # 10
# rotation angle
angle = 30.0
# group info: NoDelay=0, LongDelay=1
group = expInfo['group']
if group == '0':
feedback_delay = 0.05
blank_screen = 1.45
elif group == '1':
feedback_delay = 1.2
blank_screen = 0.3
# feedback duration 反馈显示的时长
feedback_duration = 1.0
mouse_baseline = event.Mouse(win=win)
x, y = [None, None]
mouse_baseline.mouseClock = core.Clock()
ring_baseline = visual.Polygon(
win=win, name='ring_baseline',units='cm',
edges=50, size=[1.0, 1.0],
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor=None,
opacity=1.0, depth=-2.0, interpolate=True)
fixation_ring_baseline = visual.Polygon(
win=win, name='fixation_ring_baseline',
edges=36, size=(1.1, 1.1),
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=0.0, depth=-3.0, interpolate=True)
mouse_startpoint_ring_baseline = visual.Polygon(
win=win, name='mouse_startpoint_ring_baseline',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='green', fillColor='green',
opacity=0.0, depth=-4.0, interpolate=True)
target_baseline = visual.Polygon(
win=win, name='target_baseline',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='black', fillColor='black',
opacity=0.0, depth=-5.0, interpolate=True)
feedback_ring_baseline = visual.Polygon(
win=win, name='feedback_ring_baseline',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='red',
opacity=0.0, depth=-6.0, interpolate=True)
# --- Initialize components for Routine "instruction_rotation" ---
instruction_rotation_text = visual.TextStim(win=win, name='instruction_rotation_text',
text='Brief Rest Period\n\nIn the next trials, the green cursor still represents your hand movements, but it will appear on the screen with some deviation.\n\nAs before, you must try to hit the black target point with the green cursor. \n\nYou will do the eye calibration first again...\n\n\nPress [space] to continue...',
font='Open Sans',
pos=(0, 0), height=1.0, wrapWidth=None, ori=0.0,
color='white', colorSpace='rgb', opacity=None,
languageStyle='LTR',
depth=0.0);
instruction_rotation_key = keyboard.Keyboard()
# --- Initialize components for Routine "rotation" ---
mouse_rotation = event.Mouse(win=win)
x, y = [None, None]
mouse_rotation.mouseClock = core.Clock()
ring_rotation = visual.Polygon(
win=win, name='ring_rotation',units='cm',
edges=50, size=[1.0, 1.0],
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor=None,
opacity=1.0, depth=-2.0, interpolate=True)
fixation_ring_rotation = visual.Polygon(
win=win, name='fixation_ring_rotation',
edges=36, size=(1.1, 1.1),
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=0.0, depth=-3.0, interpolate=True)
mouse_startpoint_ring_rotation = visual.Polygon(
win=win, name='mouse_startpoint_ring_rotation',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='green', fillColor='green',
opacity=0.0, depth=-4.0, interpolate=True)
target_rotation = visual.Polygon(
win=win, name='target_rotation',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='black', fillColor='black',
opacity=0.0, depth=-5.0, interpolate=True)
feedback_ring_rotation = visual.Polygon(
win=win, name='feedback_ring_rotation',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='red',
opacity=0.0, depth=-6.0, interpolate=True)
# --- Initialize components for Routine "instruction_aftereffect" ---
instruction_aftereffect_text = visual.TextStim(win=win, name='instruction_aftereffect_text',
text='End of Cursor Movement Phase\n\n\nYou need to move to target points directly with your hand, without using any strategy.\n\nHowever, there will be no cursor to indicate the position of your hand movement in the next trials.\n\n\nPress [space] to continue...\n',
font='Open Sans',
pos=(0, 0), height=1.0, wrapWidth=None, ori=0.0,
color='white', colorSpace='rgb', opacity=None,
languageStyle='LTR',
depth=0.0);
instruction_aftereffect_key = keyboard.Keyboard()
# --- Initialize components for Routine "aftereffect" ---
mouse_aftereffect = event.Mouse(win=win)
x, y = [None, None]
mouse_aftereffect.mouseClock = core.Clock()
ring_aftereffect = visual.Polygon(
win=win, name='ring_aftereffect',units='cm',
edges=50, size=[1.0, 1.0],
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor=None,
opacity=1.0, depth=-2.0, interpolate=True)
fixation_ring_aftereffect = visual.Polygon(
win=win, name='fixation_ring_aftereffect',
edges=36, size=(1.1, 1.1),
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=0.0, depth=-3.0, interpolate=True)
mouse_startpoint_ring_aftereffect = visual.Polygon(
win=win, name='mouse_startpoint_ring_aftereffect',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='green', fillColor='green',
opacity=0.0, depth=-4.0, interpolate=True)
target_aftereffect = visual.Polygon(
win=win, name='target_aftereffect',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='black', fillColor='black',
opacity=0.0, depth=-5.0, interpolate=True)
feedback_ring_aftereffect = visual.Polygon(
win=win, name='feedback_ring_aftereffect',
edges=36, size=(0.8, 0.8),
ori=0.0, pos=[0,0], anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='red',
opacity=0.0, depth=-6.0, interpolate=True)
# --- Initialize components for Routine "end" ---
end_text = visual.TextStim(win=win, name='end_text',
text='The experiment ends.\n\nThanks!',
font='Open Sans',
pos=(0, 0), height=2.0, wrapWidth=None, ori=0.0,
color='white', colorSpace='rgb', opacity=None,
languageStyle='LTR',
depth=0.0);
# --- Initialize components for Routine "end_eye" ---
# create some handy timers
if globalClock is None:
globalClock = core.Clock() # to track the time since experiment started
if ioServer is not None:
ioServer.syncClock(globalClock)
logging.setDefaultClock(globalClock)
routineTimer = core.Clock() # to track time remaining of each (possibly non-slip) routine
win.flip() # flip window to reset last flip timer
# store the exact time the global clock started
expInfo['expStart'] = data.getDateStr(format='%Y-%m-%d %Hh%M.%S.%f %z', fractionalSecondDigits=6)
# --- Prepare to start Routine "eye_tracker_connect" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('eye_tracker_connect.started', globalClock.getTime())
# keep track of which components have finished
eye_tracker_connectComponents = []
for thisComponent in eye_tracker_connectComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
frameN = -1
# --- Run Routine "eye_tracker_connect" ---
routineForceEnded = not continueRoutine
while continueRoutine:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# check for quit (typically the Esc key)
if defaultKeyboard.getKeys(keyList=["escape"]):
thisExp.status = FINISHED
if thisExp.status == FINISHED or endExpNow:
endExperiment(thisExp, inputs=inputs, win=win)
return
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
routineForceEnded = True
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in eye_tracker_connectComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# --- Ending Routine "eye_tracker_connect" ---
for thisComponent in eye_tracker_connectComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('eye_tracker_connect.stopped', globalClock.getTime())
# the Routine "eye_tracker_connect" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
break_trials1 = data.TrialHandler(nReps=2.0, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=[None],
seed=None, name='break_trials1')
thisExp.addLoop(break_trials1) # add the loop to the experiment
thisBreak_trials1 = break_trials1.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisBreak_trials1.rgb)
if thisBreak_trials1 != None:
for paramName in thisBreak_trials1:
globals()[paramName] = thisBreak_trials1[paramName]
for thisBreak_trials1 in break_trials1:
currentLoop = break_trials1
thisExp.timestampOnFlip(win, 'thisRow.t')
# pause experiment here if requested
if thisExp.status == PAUSED:
pauseExperiment(
thisExp=thisExp,
inputs=inputs,
win=win,
timers=[routineTimer],
playbackComponents=[]
)
# abbreviate parameter names if possible (e.g. rgb = thisBreak_trials1.rgb)
if thisBreak_trials1 != None:
for paramName in thisBreak_trials1:
globals()[paramName] = thisBreak_trials1[paramName]
# --- Prepare to start Routine "eye_calibration" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('eye_calibration.started', globalClock.getTime())
# Run 'Begin Routine' code from eye_calibration_code
if eyetracker:
win.winHandle.set_visible(False)
label = "start_calibration"
duration = 0.
minimal_trigger = new_trigger(label, duration)
send_trigger(minimal_trigger)
sleep(1.)
# start calibration
pupil_remote.send_string('C')
print(pupil_remote.recv_string())
sleep(15)
# keep track of which components have finished
eye_calibrationComponents = []
for thisComponent in eye_calibrationComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
frameN = -1
# --- Run Routine "eye_calibration" ---
routineForceEnded = not continueRoutine
while continueRoutine:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# check for quit (typically the Esc key)
if defaultKeyboard.getKeys(keyList=["escape"]):
thisExp.status = FINISHED
if thisExp.status == FINISHED or endExpNow:
endExperiment(thisExp, inputs=inputs, win=win)
return
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
routineForceEnded = True
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in eye_calibrationComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# --- Ending Routine "eye_calibration" ---
for thisComponent in eye_calibrationComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('eye_calibration.stopped', globalClock.getTime())
# Run 'End Routine' code from eye_calibration_code
if eyetracker:
label = "end_calibration"
duration = 0.
minimal_trigger = new_trigger(label, duration)
send_trigger(minimal_trigger)
sleep(1.)
win.winHandle.set_visible(True)
# the Routine "eye_calibration" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# --- Prepare to start Routine "instruction_baseline" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('instruction_baseline.started', globalClock.getTime())
instruction_baseline_key.keys = []
instruction_baseline_key.rt = []
_instruction_baseline_key_allKeys = []
# keep track of which components have finished
instruction_baselineComponents = [instruction_baseline_text, instruction_baseline_key]
for thisComponent in instruction_baselineComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
frameN = -1
# --- Run Routine "instruction_baseline" ---
routineForceEnded = not continueRoutine
while continueRoutine:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# *instruction_baseline_text* updates
# if instruction_baseline_text is starting this frame...
if instruction_baseline_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
instruction_baseline_text.frameNStart = frameN # exact frame index
instruction_baseline_text.tStart = t # local t and not account for scr refresh
instruction_baseline_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(instruction_baseline_text, 'tStartRefresh') # time at next scr refresh
# update status
instruction_baseline_text.status = STARTED
instruction_baseline_text.setAutoDraw(True)
# if instruction_baseline_text is active this frame...
if instruction_baseline_text.status == STARTED:
# update params
pass
# *instruction_baseline_key* updates
waitOnFlip = False
# if instruction_baseline_key is starting this frame...
if instruction_baseline_key.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
instruction_baseline_key.frameNStart = frameN # exact frame index
instruction_baseline_key.tStart = t # local t and not account for scr refresh
instruction_baseline_key.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(instruction_baseline_key, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'instruction_baseline_key.started')
# update status
instruction_baseline_key.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(instruction_baseline_key.clock.reset) # t=0 on next screen flip
win.callOnFlip(instruction_baseline_key.clearEvents, eventType='keyboard') # clear events on next screen flip
if instruction_baseline_key.status == STARTED and not waitOnFlip:
theseKeys = instruction_baseline_key.getKeys(keyList=['space'], ignoreKeys=["escape"], waitRelease=False)
_instruction_baseline_key_allKeys.extend(theseKeys)
if len(_instruction_baseline_key_allKeys):
instruction_baseline_key.keys = _instruction_baseline_key_allKeys[-1].name # just the last key pressed
instruction_baseline_key.rt = _instruction_baseline_key_allKeys[-1].rt
instruction_baseline_key.duration = _instruction_baseline_key_allKeys[-1].duration
# a response ends the routine
continueRoutine = False
# check for quit (typically the Esc key)
if defaultKeyboard.getKeys(keyList=["escape"]):
thisExp.status = FINISHED
if thisExp.status == FINISHED or endExpNow:
endExperiment(thisExp, inputs=inputs, win=win)
return
# check if all components have finished
if not continueRoutine: # a component has requested a forced-end of Routine
routineForceEnded = True
break
continueRoutine = False # will revert to True if at least one component still running
for thisComponent in instruction_baselineComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished
# refresh the screen
if continueRoutine: # don't flip if this routine is over or we'll get a blank screen
win.flip()
# --- Ending Routine "instruction_baseline" ---
for thisComponent in instruction_baselineComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('instruction_baseline.stopped', globalClock.getTime())
# check responses
if instruction_baseline_key.keys in ['', [], None]: # No response was made
instruction_baseline_key.keys = None
break_trials1.addData('instruction_baseline_key.keys',instruction_baseline_key.keys)
if instruction_baseline_key.keys != None: # we had a response
break_trials1.addData('instruction_baseline_key.rt', instruction_baseline_key.rt)
break_trials1.addData('instruction_baseline_key.duration', instruction_baseline_key.duration)
# the Routine "instruction_baseline" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
baseline_trials = data.TrialHandler(nReps=1.0, method='sequential',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('conditions_baseline1.xlsx'),
seed=None, name='baseline_trials')
thisExp.addLoop(baseline_trials) # add the loop to the experiment
thisBaseline_trial = baseline_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisBaseline_trial.rgb)
if thisBaseline_trial != None:
for paramName in thisBaseline_trial:
globals()[paramName] = thisBaseline_trial[paramName]
for thisBaseline_trial in baseline_trials:
currentLoop = baseline_trials
thisExp.timestampOnFlip(win, 'thisRow.t')
# pause experiment here if requested
if thisExp.status == PAUSED:
pauseExperiment(
thisExp=thisExp,
inputs=inputs,
win=win,
timers=[routineTimer],
playbackComponents=[]
)
# abbreviate parameter names if possible (e.g. rgb = thisBaseline_trial.rgb)
if thisBaseline_trial != None:
for paramName in thisBaseline_trial:
globals()[paramName] = thisBaseline_trial[paramName]
# --- Prepare to start Routine "baseline" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('baseline.started', globalClock.getTime())
# Run 'Begin Routine' code from code_baseline
win.mouseVisible = False
mouse_startpoint_ring_baseline.opacity = 0
## Initialize variables and flags 初始化变量和标志位
move_start = False # hand starts to move 标志手开始动
feedback_start = False # end feedback appears 标志终点反馈出现
blank_start = False
feedback_position_set = False
movement_frames = [] # save the position of each frame of the hand movement 用于保存手运动过程的每一帧位置
## clock 时钟
mouse_startpoint_time = core.Clock() # 用于记录mouse_startpoint_ring出现的时间
target_show_time = core.Clock()
move_start_time = core.Clock() # 用于记录运动开始的时间
move_end_time = core.Clock()
feedback_start_time = core.Clock()
mouse_startpoint_time.reset()
target_show_time.reset()
move_start_time.reset()
move_end_time.reset()
feedback_start_time.reset()
blank_start_time = core.Clock()
blank_start_time.reset()
## the hand position of the previous frame 得到上一帧的手位置
lastPos = mouse_baseline.getPos()
## Calculate the radius of the ring 计算ring的半径
x_mouse, y_mouse = mouse_baseline.getPos()
ring_radius = euclidean_dist([0,0], [x_mouse,y_mouse])
Ring_W = ring_radius
Ring_H = ring_radius
## Conversion of feedback position 反馈的位置的转换
[theta_mouse, rho_mouse] = cart2pol(x_mouse, y_mouse)
[feedback_x, feedback_y] = pol2cart(theta_mouse, target_radius)
## Set the ring size 设置ring的大小
if not move_start and not feedback_start:
ring_baseline.size = (ring_radius, ring_radius)
## choose how long the origin hold 选择在原点要待多久
random_origin_duration = random.choice(random_origin_durations)
## eye tracker
if eyetracker:
# record the trial start time in psychopy 记录psychopy里每次试验开始的时间
hand_trial_start=core.monotonicClock.getTime()
label = 'start_trial ' + str(baseline_trials.thisN)
duration = 0.
minimal_trigger = new_trigger(label, duration)
send_trigger(minimal_trigger)
sleep(1.)
# setup some python lists for storing info about the mouse_baseline
gotValidClick = False # until a click is received
mouse_baseline.mouseClock.reset()
target_baseline.setPos([target_x, target_y])
# keep track of which components have finished
baselineComponents = [mouse_baseline, ring_baseline, fixation_ring_baseline, mouse_startpoint_ring_baseline, target_baseline, feedback_ring_baseline]
for thisComponent in baselineComponents:
thisComponent.tStart = None
thisComponent.tStop = None
thisComponent.tStartRefresh = None
thisComponent.tStopRefresh = None
if hasattr(thisComponent, 'status'):
thisComponent.status = NOT_STARTED
# reset timers
t = 0
_timeToFirstFrame = win.getFutureFlipTime(clock="now")
frameN = -1
# --- Run Routine "baseline" ---
routineForceEnded = not continueRoutine
while continueRoutine:
# get current time
t = routineTimer.getTime()
tThisFlip = win.getFutureFlipTime(clock=routineTimer)
tThisFlipGlobal = win.getFutureFlipTime(clock=None)
frameN = frameN + 1 # number of completed frames (so 0 is the first frame)
# update/draw components on each frame
# Run 'Each Frame' code from code_baseline
# update mouse pos
x_mouse,y_mouse = mouse_baseline.getPos()
ring_radius = euclidean_dist([fixation_ring_baseline.pos[0],fixation_ring_baseline.pos[1]], [x_mouse,y_mouse])
Ring_W = ring_radius
Ring_H = ring_radius
# save last pos
thisPos = mouse_baseline.getPos()
mouseDist = euclidean_dist(lastPos, thisPos)
lastPos = thisPos
# hide rings