-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.py
1124 lines (1009 loc) · 46.5 KB
/
search.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 (v2024.1.4),
on Fr 01 Nov 2024 12:05:08 WET
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, hardware
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
# Run 'Before Experiment' code from code
from psychopy_visionscience.noise import NoiseStim
import time, atexit
from pupil_labs.realtime_api.simple import discover_one_device
def send_event(device, name, clock_offset):
client_time = time.time_ns()
device_time = client_time - clock_offset
device.send_event(
name,
event_timestamp_unix_ns=device_time
)
return client_time, device_time
def stop_recording(device):
device.recording_stop_and_save()
print("Recording stopped")
device.close()
if expInfo['eye_tracking']:
device = discover_one_device(max_search_duration_seconds=10)
if device is None:
print("No device found.")
raise SystemExit(-1)
atexit.register(stop_recording, device)
# --- Setup global variables (available in all functions) ---
# create a device manager to handle hardware (keyboards, mice, mirophones, speakers, etc.)
deviceManager = hardware.DeviceManager()
# 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 = '2024.1.4'
expName = 'search' # from the Builder filename that created this script
# information about this experiment
expInfo = {
'participant': f"{randint(0, 999999):06.0f}",
'session': '001',
'eye_tracking': True,
'date|hid': data.getDateStr(),
'expName|hid': expName,
'psychopyVersion|hid': psychopyVersion,
}
# --- Define some variables which will change depending on pilot mode ---
'''
To run in pilot mode, either use the run/pilot toggle in Builder, Coder and Runner,
or run the experiment with `--pilot` as an argument. To change what pilot
#mode does, check out the 'Pilot mode' tab in preferences.
'''
# work out from system args whether we are running in pilot mode
PILOTING = core.setPilotModeFromArgs()
# start off with values from experiment settings
_fullScr = True
_winSize = [1920, 1080]
_loggingLevel = logging.getLevel('warning')
# if in pilot mode, apply overrides according to preferences
if PILOTING:
# force windowed mode
if prefs.piloting['forceWindowed']:
_fullScr = False
# set window size
_winSize = prefs.piloting['forcedWindowSize']
# override logging level
_loggingLevel = logging.getLevel(
prefs.piloting['pilotLoggingLevel']
)
def showExpInfoDlg(expInfo):
"""
Show participant info dialog.
Parameters
==========
expInfo : dict
Information about this experiment.
Returns
==========
dict
Information about this experiment.
"""
# show participant info dialog
dlg = gui.DlgFromDict(
dictionary=expInfo, sortKeys=False, title=expName, alwaysOnTop=True
)
if dlg.OK == False:
core.quit() # user pressed cancel
# 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.
"""
# remove dialog-specific syntax from expInfo
for key, val in expInfo.copy().items():
newKey, _ = data.utils.parsePipeSyntax(key)
expInfo[newKey] = expInfo.pop(key)
# 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='/home/crombie/code/visual_search/search.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(_loggingLevel)
# save a log file for detail verbose info
logFile = logging.LogFile(filename+'.log', level=_loggingLevel)
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 PILOTING:
logging.debug('Fullscreen settings ignored as running in pilot mode.')
if win is None:
# if not given a window to setup, make one
win = visual.Window(
size=_winSize, fullscr=_fullScr, screen=1,
winType='pyglet', allowStencil=False,
monitor='testMonitor', color=[0,0,0], colorSpace='rgb',
backgroundImage='', backgroundFit='none',
blendMode='avg', useFBO=True,
units='deg',
checkTiming=False # we're going to do this ourselves in a moment
)
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 = 'deg'
if expInfo is not None:
# get/measure frame rate if not already in expInfo
if win._monitorFrameRate is None:
win.getActualFrameRate(infoMsg='Attempting to measure frame rate of screen, please wait...')
expInfo['frameRate'] = win._monitorFrameRate
win.mouseVisible = False
win.hideMessage()
# show a visual indicator if we're in piloting mode
if PILOTING and prefs.piloting['showPilotingIndicator']:
win.showPilotingIndicator()
return win
def setupDevices(expInfo, thisExp, win):
"""
Setup whatever devices are available (mouse, keyboard, speaker, eyetracker, etc.) and add them to
the device manager (deviceManager)
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
==========
bool
True if completed successfully.
"""
# --- Setup input devices ---
ioConfig = {}
# 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)
# store ioServer object in the device manager
deviceManager.ioServer = ioServer
# create a default keyboard (e.g. to check for escape)
if deviceManager.getDevice('defaultKeyboard') is None:
deviceManager.addDevice(
deviceClass='keyboard', deviceName='defaultKeyboard', backend='iohub'
)
if deviceManager.getDevice('instruction_key') is None:
# initialise instruction_key
instruction_key = deviceManager.addDevice(
deviceClass='keyboard',
deviceName='instruction_key',
)
if deviceManager.getDevice('done_calibrating') is None:
# initialise done_calibrating
done_calibrating = deviceManager.addDevice(
deviceClass='keyboard',
deviceName='done_calibrating',
)
if deviceManager.getDevice('key_resp') is None:
# initialise key_resp
key_resp = deviceManager.addDevice(
deviceClass='keyboard',
deviceName='key_resp',
)
# return True if completed successfully
return True
def pauseExperiment(thisExp, 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.
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()
# make sure we have a keyboard
defaultKeyboard = deviceManager.getDevice('defaultKeyboard')
if defaultKeyboard is None:
defaultKeyboard = deviceManager.addKeyboard(
deviceClass='keyboard',
deviceName='defaultKeyboard',
backend='ioHub',
)
# run a while loop while we wait to unpause
while thisExp.status == PAUSED:
# check for quit (typically the Esc key)
if defaultKeyboard.getKeys(keyList=['escape']):
endExperiment(thisExp, win=win)
# flip the screen
win.flip()
# if stop was requested while paused, quit
if thisExp.status == FINISHED:
endExperiment(thisExp, 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, 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.
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 = deviceManager.ioServer
# get/create a default keyboard (e.g. to check for escape)
defaultKeyboard = deviceManager.getDevice('defaultKeyboard')
if defaultKeyboard is None:
deviceManager.addDevice(
deviceClass='keyboard', deviceName='defaultKeyboard', backend='ioHub'
)
eyetracker = deviceManager.getDevice('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 "setup" ---
# --- Initialize components for Routine "instruction" ---
instruction_text = visual.TextStim(win=win, name='instruction_text',
text='Welcome to the search experiment.\n\nBefore the trial starts please fix your gaze on the cross. At the start of the trial a patch of noise will appear, there will be a small oriented grating somewhere in the noise patch. Your task is to move your eyes to search for the grating. Once you have found the grating keep your gaze fixed on that position and press the space bar.\n\nPress space to continue to the eye tracker calibration.',
font='Arial',
pos=(0, 0), height=1.0, wrapWidth=30.0, ori=0.0,
color='white', colorSpace='rgb', opacity=None,
languageStyle='LTR',
depth=0.0);
instruction_key = keyboard.Keyboard(deviceName='instruction_key')
# --- Initialize components for Routine "calibration" ---
polygon = visual.ShapeStim(
win=win, name='polygon', vertices='cross',
size=(2.5, 2.5),
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=None, depth=0.0, interpolate=True)
done_calibrating = keyboard.Keyboard(deviceName='done_calibrating')
calibration_prompt = visual.TextStim(win=win, name='calibration_prompt',
text="Press 'space' when calibration is complete.",
font='Arial',
pos=(0, -10), height=2.0, wrapWidth=None, ori=0.0,
color='white', colorSpace='rgb', opacity=1.0,
languageStyle='LTR',
depth=-2.0);
# --- Initialize components for Routine "search_trial" ---
fixation = visual.ShapeStim(
win=win, name='fixation', vertices='cross',
size=(1, 1),
ori=0.0, pos=(0, 0), anchor='center',
lineWidth=1.0, colorSpace='rgb', lineColor='white', fillColor='white',
opacity=None, depth=-1.0, interpolate=True)
grating = visual.GratingStim(
win=win, name='grating',
tex='sin', mask='gauss', anchor='center',
ori=45.0, pos=[0,0], size=(1, 1), sf=6.0, phase=0.0,
color=[1,1,1], colorSpace='rgb',
opacity=1.0, contrast=1.0, blendmode='add',
texRes=128.0, interpolate=True, depth=-2.0)
noise = visual.GratingStim(
win=win, name='noise',
tex='sin', mask=None, anchor='center',
ori=0.0, pos=(0, 0), size=(0.5, 0.5), sf=None, phase=0.0,
color=[1,1,1], colorSpace='rgb',
opacity=0.0, contrast=1.0, blendmode='avg',
texRes=128.0, interpolate=True, depth=-3.0)
key_resp = keyboard.Keyboard(deviceName='key_resp')
# create some handy timers
# global clock to track the time since experiment started
if globalClock is None:
# create a clock if not given one
globalClock = core.Clock()
if isinstance(globalClock, str):
# if given a string, make a clock accoridng to it
if globalClock == 'float':
# get timestamps as a simple value
globalClock = core.Clock(format='float')
elif globalClock == 'iso':
# get timestamps in ISO format
globalClock = core.Clock(format='%Y-%m-%d_%H:%M:%S.%f%z')
else:
# get timestamps in a custom format
globalClock = core.Clock(format=globalClock)
if ioServer is not None:
ioServer.syncClock(globalClock)
logging.setDefaultClock(globalClock)
# routine timer to track time remaining of each (possibly non-slip) routine
routineTimer = core.Clock()
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 "setup" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('setup.started', globalClock.getTime(format='float'))
# keep track of which components have finished
setupComponents = []
for thisComponent in setupComponents:
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 "setup" ---
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, 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 setupComponents:
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 "setup" ---
for thisComponent in setupComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('setup.stopped', globalClock.getTime(format='float'))
thisExp.nextEntry()
# the Routine "setup" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# --- Prepare to start Routine "instruction" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('instruction.started', globalClock.getTime(format='float'))
instruction_key.keys = []
instruction_key.rt = []
_instruction_key_allKeys = []
# keep track of which components have finished
instructionComponents = [instruction_text, instruction_key]
for thisComponent in instructionComponents:
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" ---
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_text* updates
# if instruction_text is starting this frame...
if instruction_text.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
instruction_text.frameNStart = frameN # exact frame index
instruction_text.tStart = t # local t and not account for scr refresh
instruction_text.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(instruction_text, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'instruction_text.started')
# update status
instruction_text.status = STARTED
instruction_text.setAutoDraw(True)
# if instruction_text is active this frame...
if instruction_text.status == STARTED:
# update params
pass
# *instruction_key* updates
waitOnFlip = False
# if instruction_key is starting this frame...
if instruction_key.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
instruction_key.frameNStart = frameN # exact frame index
instruction_key.tStart = t # local t and not account for scr refresh
instruction_key.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(instruction_key, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'instruction_key.started')
# update status
instruction_key.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(instruction_key.clock.reset) # t=0 on next screen flip
win.callOnFlip(instruction_key.clearEvents, eventType='keyboard') # clear events on next screen flip
if instruction_key.status == STARTED and not waitOnFlip:
theseKeys = instruction_key.getKeys(keyList=['space'], ignoreKeys=["escape"], waitRelease=False)
_instruction_key_allKeys.extend(theseKeys)
if len(_instruction_key_allKeys):
instruction_key.keys = _instruction_key_allKeys[-1].name # just the last key pressed
instruction_key.rt = _instruction_key_allKeys[-1].rt
instruction_key.duration = _instruction_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, 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 instructionComponents:
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" ---
for thisComponent in instructionComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('instruction.stopped', globalClock.getTime(format='float'))
# check responses
if instruction_key.keys in ['', [], None]: # No response was made
instruction_key.keys = None
thisExp.addData('instruction_key.keys',instruction_key.keys)
if instruction_key.keys != None: # we had a response
thisExp.addData('instruction_key.rt', instruction_key.rt)
thisExp.addData('instruction_key.duration', instruction_key.duration)
thisExp.nextEntry()
# the Routine "instruction" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# --- Prepare to start Routine "calibration" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('calibration.started', globalClock.getTime(format='float'))
done_calibrating.keys = []
done_calibrating.rt = []
_done_calibrating_allKeys = []
# keep track of which components have finished
calibrationComponents = [polygon, done_calibrating, calibration_prompt]
for thisComponent in 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 "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
# *polygon* updates
# if polygon is starting this frame...
if polygon.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
polygon.frameNStart = frameN # exact frame index
polygon.tStart = t # local t and not account for scr refresh
polygon.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(polygon, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'polygon.started')
# update status
polygon.status = STARTED
polygon.setAutoDraw(True)
# if polygon is active this frame...
if polygon.status == STARTED:
# update params
pass
# *done_calibrating* updates
waitOnFlip = False
# if done_calibrating is starting this frame...
if done_calibrating.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
done_calibrating.frameNStart = frameN # exact frame index
done_calibrating.tStart = t # local t and not account for scr refresh
done_calibrating.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(done_calibrating, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'done_calibrating.started')
# update status
done_calibrating.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(done_calibrating.clock.reset) # t=0 on next screen flip
win.callOnFlip(done_calibrating.clearEvents, eventType='keyboard') # clear events on next screen flip
if done_calibrating.status == STARTED and not waitOnFlip:
theseKeys = done_calibrating.getKeys(keyList=['y','n','left','right','space'], ignoreKeys=["escape"], waitRelease=False)
_done_calibrating_allKeys.extend(theseKeys)
if len(_done_calibrating_allKeys):
done_calibrating.keys = _done_calibrating_allKeys[-1].name # just the last key pressed
done_calibrating.rt = _done_calibrating_allKeys[-1].rt
done_calibrating.duration = _done_calibrating_allKeys[-1].duration
# a response ends the routine
continueRoutine = False
# *calibration_prompt* updates
# if calibration_prompt is starting this frame...
if calibration_prompt.status == NOT_STARTED and tThisFlip >= 0.0-frameTolerance:
# keep track of start time/frame for later
calibration_prompt.frameNStart = frameN # exact frame index
calibration_prompt.tStart = t # local t and not account for scr refresh
calibration_prompt.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(calibration_prompt, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'calibration_prompt.started')
# update status
calibration_prompt.status = STARTED
calibration_prompt.setAutoDraw(True)
# if calibration_prompt is active this frame...
if calibration_prompt.status == STARTED:
# update params
pass
# check for quit (typically the Esc key)
if defaultKeyboard.getKeys(keyList=["escape"]):
thisExp.status = FINISHED
if thisExp.status == FINISHED or endExpNow:
endExperiment(thisExp, 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 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 "calibration" ---
for thisComponent in calibrationComponents:
if hasattr(thisComponent, "setAutoDraw"):
thisComponent.setAutoDraw(False)
thisExp.addData('calibration.stopped', globalClock.getTime(format='float'))
# check responses
if done_calibrating.keys in ['', [], None]: # No response was made
done_calibrating.keys = None
thisExp.addData('done_calibrating.keys',done_calibrating.keys)
if done_calibrating.keys != None: # we had a response
thisExp.addData('done_calibrating.rt', done_calibrating.rt)
thisExp.addData('done_calibrating.duration', done_calibrating.duration)
# Run 'End Routine' code from start_recording
if expInfo['eye_tracking']:
estimate = device.estimate_time_offset()
clock_offset_ns = round(estimate.time_offset_ms.mean * 1000000)
recording_id = device.recording_start()
print(f"Started recording with id {recording_id}")
print("Waiting 5s...")
time.sleep(5)
thisExp.nextEntry()
# the Routine "calibration" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()
# set up handler to look after randomisation of conditions etc
search_trials = data.TrialHandler(nReps=10.0, method='random',
extraInfo=expInfo, originPath=-1,
trialList=data.importConditions('conditions_search.xlsx'),
seed=None, name='search_trials')
thisExp.addLoop(search_trials) # add the loop to the experiment
thisSearch_trial = search_trials.trialList[0] # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisSearch_trial.rgb)
if thisSearch_trial != None:
for paramName in thisSearch_trial:
globals()[paramName] = thisSearch_trial[paramName]
for thisSearch_trial in search_trials:
currentLoop = search_trials
thisExp.timestampOnFlip(win, 'thisRow.t', format=globalClock.format)
# pause experiment here if requested
if thisExp.status == PAUSED:
pauseExperiment(
thisExp=thisExp,
win=win,
timers=[routineTimer],
playbackComponents=[]
)
# abbreviate parameter names if possible (e.g. rgb = thisSearch_trial.rgb)
if thisSearch_trial != None:
for paramName in thisSearch_trial:
globals()[paramName] = thisSearch_trial[paramName]
# --- Prepare to start Routine "search_trial" ---
continueRoutine = True
# update component parameters for each repeat
thisExp.addData('search_trial.started', globalClock.getTime(format='float'))
# Run 'Begin Routine' code from send_event
grating_angle = np.random.choice(
np.arange(-np.pi, np.pi, 2 * np.pi / 32)
)
grating_xpos = grating_eccentricity * np.cos(grating_angle)
grating_ypos = grating_eccentricity * np.sin(grating_angle)
if expInfo['eye_tracking']:
send_event(device, 'trial_start', clock_offset_ns)
grating.setContrast(grating_contrast)
grating.setPos((grating_xpos, grating_ypos))
noise.setContrast(noise_contrast)
# Run 'Begin Routine' code from noise_code
noise = NoiseStim(
win=win, name='pink_noise', units='height',
noiseImage=None, mask='circle',
ori=0.0, pos=(0, 0), size=(1, 1), sf=None,
phase=0.0,
color=[1,1,1], colorSpace='rgb', opacity=None, blendmode='add', contrast=1.0,
texRes=128, filter=None,
noiseType='Filtered', noiseElementSize=[0.0625],
noiseBaseSf=8.0, noiseBW=1.0,
noiseBWO=30.0, noiseOri=0.0,
noiseFractalPower=-1.25, noiseFilterLower=1.0,
noiseFilterUpper=8.0, noiseFilterOrder=-2.0,
noiseClip=3.0, imageComponent='Phase', interpolate=False, depth=0.0)
noise.buildNoise()
key_resp.keys = []
key_resp.rt = []
_key_resp_allKeys = []
# keep track of which components have finished
search_trialComponents = [fixation, grating, noise, key_resp]
for thisComponent in search_trialComponents:
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 "search_trial" ---
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
# *fixation* updates
# if fixation is starting this frame...
if fixation.status == NOT_STARTED and tThisFlip >= 0.5-frameTolerance:
# keep track of start time/frame for later
fixation.frameNStart = frameN # exact frame index
fixation.tStart = t # local t and not account for scr refresh
fixation.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(fixation, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'fixation.started')
# update status
fixation.status = STARTED
fixation.setAutoDraw(True)
# if fixation is active this frame...
if fixation.status == STARTED:
# update params
pass
# if fixation is stopping this frame...
if fixation.status == STARTED:
# is it time to stop? (based on global clock, using actual start)
if tThisFlipGlobal > fixation.tStartRefresh + 0.9-frameTolerance:
# keep track of stop time/frame for later
fixation.tStop = t # not accounting for scr refresh
fixation.tStopRefresh = tThisFlipGlobal # on global time
fixation.frameNStop = frameN # exact frame index
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'fixation.stopped')
# update status
fixation.status = FINISHED
fixation.setAutoDraw(False)
# *grating* updates
# if grating is starting this frame...
if grating.status == NOT_STARTED and tThisFlip >= 1.5-frameTolerance:
# keep track of start time/frame for later
grating.frameNStart = frameN # exact frame index
grating.tStart = t # local t and not account for scr refresh
grating.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(grating, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'grating.started')
# update status
grating.status = STARTED
grating.setAutoDraw(True)
# if grating is active this frame...
if grating.status == STARTED:
# update params
pass
# *noise* updates
# if noise is starting this frame...
if noise.status == NOT_STARTED and tThisFlip >= 1.5-frameTolerance:
# keep track of start time/frame for later
noise.frameNStart = frameN # exact frame index
noise.tStart = t # local t and not account for scr refresh
noise.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(noise, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'noise.started')
# update status
noise.status = STARTED
noise.setAutoDraw(True)
# if noise is active this frame...
if noise.status == STARTED:
# update params
pass
# *key_resp* updates
waitOnFlip = False
# if key_resp is starting this frame...
if key_resp.status == NOT_STARTED and tThisFlip >= 1.5-frameTolerance:
# keep track of start time/frame for later
key_resp.frameNStart = frameN # exact frame index
key_resp.tStart = t # local t and not account for scr refresh
key_resp.tStartRefresh = tThisFlipGlobal # on global time
win.timeOnFlip(key_resp, 'tStartRefresh') # time at next scr refresh
# add timestamp to datafile
thisExp.timestampOnFlip(win, 'key_resp.started')
# update status
key_resp.status = STARTED
# keyboard checking is just starting
waitOnFlip = True
win.callOnFlip(key_resp.clock.reset) # t=0 on next screen flip
win.callOnFlip(key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip
if key_resp.status == STARTED and not waitOnFlip:
theseKeys = key_resp.getKeys(keyList=['space'], ignoreKeys=["escape"], waitRelease=False)
_key_resp_allKeys.extend(theseKeys)
if len(_key_resp_allKeys):
key_resp.keys = _key_resp_allKeys[-1].name # just the last key pressed
key_resp.rt = _key_resp_allKeys[-1].rt
key_resp.duration = _key_resp_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, 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 search_trialComponents:
if hasattr(thisComponent, "status") and thisComponent.status != FINISHED:
continueRoutine = True
break # at least one component has not yet finished