-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_respiratoryMEG_with_ET.py
More file actions
469 lines (370 loc) · 16.1 KB
/
example_respiratoryMEG_with_ET.py
File metadata and controls
469 lines (370 loc) · 16.1 KB
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 25 2021
@author: au281249
"""
from datetime import datetime # uncoment to use data and time in output file names
from psychopy import gui, monitors, visual, event, core
import psychopy
import platform
from ET_functions import *
import cfin_psychoLink as pl
####################################################################################
############ Things you might want to set ############
####################################################################################
# keys
instructionsOKkey = ['space','1']
quitKey = 'q'
# timing
blockTime = 0.1 # minutes
periBlockTime = 1 # seconds
blockTimeSecs = 60*blockTime
# monitor
monSpeed = 60
# Create gui dialog
dialogBox = True
# save settings
save = True
filePrefix='rMREG'
saveDirWindows = 'C:\\Users\\stimuser\\Desktop\\Malthe\\data'
saveDirMac = "/Users/au281249/Documents/data/rMEG"
saveFolder = os.getcwd() + "/data"
####################################################################################
############ GUI indput ############
####################################################################################
# Get input from the experimenter when the experiment starts if dialogBox == True
if dialogBox:
#fields in the dialog box
dlgOrder = ['Subject ID','Age',"Gender"]
dlgDict ={"Subject ID":"0001",
"Age" : "int",
"Gender" : ["female","male","other"],
"Airway manipulation":[False,True],
"Full screen":[True,False],
"Eyetracking":[True, False],
"ET_gaze_contingency":[True, False],
"ET_Test":[True, False]
}
# create the box
dlg = gui.DlgFromDict(dictionary=dlgDict,title='TestExperiment', order=dlgOrder)
if dlg.OK:
# check id entered Subject ID is okay, else ask again
while len(dlgDict['Subject ID']) != 4 or not dlgDict['Subject ID'].isdigit():
dlg = gui.DlgFromDict(dictionary=dlgDict,title='Subject ID must only contain ints and must be 4 characters long. Please zero pad if Subject ID < 1000', order=dlgOrder)
if dlg.OK:
print(dlgDict)
else:
print('User Cancelled')
# set parameters based on the experimenter input
subjectID = dlgDict['Subject ID']
age= dlgDict['Age']
gender=dlgDict['Gender']
fullScreen = True if dlgDict['Full screen']=="True" else False
ET = dlgDict["Eyetracking"]
ETGC = dlgDict["ET_gaze_contingency"]
ETtest = dlgDict["ET_Test"]
else:
print('User Cancelled')
else:
# participant info
subjectID = "999"
age=99
gender="male"
# Full screen
fullScreen = True
ET = True
ETGC = True
ETtest = True
####################################################################################
############ OS and path things ############
####################################################################################
# finding the OS
platform = platform.system()
# setting path and filenames of logs based on OS
if platform == "Windows":
from pypixxlib import _libdpx as dp
folder = saveDirWindows
fileName = filePrefix + "_{}_{}".format(
subjectID, str(datetime.now()).replace(" ", "_").replace(":","_")[0:-10]
) # uncoment to use data and time in output file names
fileName = folder + "\\trialLogs"+fileName + ".csv" # uncoment to use data and time in output file names
# set monitor details
monDistance = 40 # in cm
monWidth = 53.146 # in cm
monitorSizePix = [1920, 1080] # Pixel-dimensions
myMonitor = monitors.Monitor('myMonitor', width=monWidth, distance=monDistance)
myMonitor.setSizePix(monitorSizePix)
elif platform == "Darwin":
folder = saveDirMac
fileName = filePrefix + "_{}_{}".format(
subjectID, str(datetime.now()).replace(" ", "_").replace(":","_")[0:-10]
) # uncoment to use data and time in output file names
fileName = folder + fileName + ".csv" # uncoment to use data and time in output file names
# set monitor details
monDistance = 40 # in cm
monWidth = 35 # in cm
monitorSizePix = [1920, 1080]#[3072, 1920] # Pixel-dimensions
myMonitor = monitors.Monitor('myMonitor', width=monWidth, distance=monDistance)
myMonitor.setSizePix(monitorSizePix)
else:
NameError
####################################################################################
############ Block structure ############
####################################################################################
# structure
subBlockTypes = [
['F','N','M'],
['F','M','N'],
['N','M','F'],
['N','F','M'],
['M','N','F'],
['M','F','N']
]
subBlocks = subBlockTypes[int(subjectID)%6] # select block order based on subject ID
blocks = 2 * subBlocks
print(blocks)
####################################################################################
############ Objects ############
####################################################################################
### Calibrate ET
# Calibrating before setting up the window, because calibration requires py27
if ET:
print("ET is True")
calibrate_using_2_7()
# window
REFRESH = 120.
SIZE = displayResolution
fullScreen = True
monitor = monitors.Monitor('MEGmonitor')
# fetch the most recent calib for this monitor
monitor.setDistance(monDistance)
monitor.setWidth(monWidth)
monitor.setSizePix(SIZE)
# win = visual.Window(monitorSizePix, fullscr=fullScreen)
win = psychopy.visual.Window(size=SIZE, allowGUI=False, monitor=monitor,
fullscr=fullScreen,units="deg")
fix = fixation = visual.TextStim(win, '+')
noseOn = visual.TextStim(win, 'If you are wearing the mouthpiece - please remove it.\n Please put on the nose clip.') #visual.ImageStim(win, 'images/')
mouthOn = visual.TextStim(win, 'If you are wearing the nose clip - please remove it.\n Please put on the mouthbiece.') #visual.ImageStim(win, 'images/')
modOff = visual.TextStim(win, 'If you are wearing the nose clip or the mouthpiece - please remove them') #visual.ImageStim(win, 'images/')
# triggerStim = visual.Rect(
# win=win,
# color=(0,0,0),
# size=triggerSize,
# colorSpace='rgb255',
# pos=triggerLocation,
# units="pix",
#
# )
px_location = [-displayResolution[0] // 2, displayResolution[1] // 2]
px_size = [2, 2]
triggerStim = visual.Rect(win=win, fillColor=(0, 0, 0), size=px_size, colorSpace='rgb255', pos=px_location, units='pix', autoDraw=True)
triggerStim.color=(0,0,0)
# clock
clock = core.Clock()
# ---------- Eyetracking Functions in Script -----------#
# ---- put this after you created a win = psychopy.visual.Window ----
#-------------------------------------------------------#
Recalibrate = False
def set_recalibrate():
"""
Sets a global variable, "Recalibrate" to True - typically done using psychopy.event.globalkeys
PUT THIS FUNCTION INTO YOUR SCRIPT
typical use (set in the beginning of the experiment)
if ET:
recalibrateKey = 'c'
psychopy.event.globalKeys.add(recalibrateKey, set_recalibrate)
# Recalibrate mid experiment, 'c'
typical use (at the start of a trial)
if Recalibrate:
recalibrate_et(win, default_fullscreen=fullscreen,saveFolder=saveFolder,subjectID=subjectID)
et_client = setup_et(win, hz, saveFileEDF=create_save_file_EDF(saveFolder, subjectID))
et_client.sendMsg(msg="New start of experiment")
et_client.startTrial(trialNr=no) # starts eyetracking recording.
Recalibrate = False # set it back to false
"""
global Recalibrate
Recalibrate = True
def clean_quit():
"""
PUT THIS FUNCTION INTO YOUR SCRIPT - name your et_client "et_client" and name your csv savefile "behavfile"
clean quit is advised when running ET; to save ET-data if anything happens during the experiment which quires this
it means that a key can be hit during the eksperiment, for example "p", and then
the behavioral data is saved, the pixel mode in the pypixx is disabled, and the
et_client performs a cleanup (i.e it stops recording and saves the data)
before it performs a psychopy.core.quit()
typical use:
if ET:
forceQuitKey = "p"
psychopy.event.globalKeys.add(forceQuitKey, clean_quit)
"""
try:
if behavfile is not None:
behavfile.close()
else:
print("behaveFile is None")
except:
print("no 'behavfile' - can't close")
if ET:
try:
et_client.sendMsg(msg="Closing the client")
et_client.cleanUp()
except:
print("exception during cleanup")
print("attempting to disable pixelmode on VPixx projector")
try:
from pypixxlib import _libdpx as dp
dp.DPxDisableDoutPixelMode()
dp.DPxWriteRegCache()
dp.DPxClose()
print("pixelmode closed")
except:
print("attempted close of pixelmode failed - invalid triggers may appear in MEG file")
psychopy.core.quit()
# -------------------------------------------------------
####################################################################################
############ Helper functions ############
####################################################################################
# triggers
def triggerColor(name):
if name == "F":
return (1,0,0)
elif name == "N":
return (2,0,0)
elif name == "M":
return (3,0,0)
else:
NotImplementedError(f'{name} has no defined trigger value')
####################################################################################
############ Display functions ############
####################################################################################
# dispaly functions
def blank():
triggerStim.draw()
win.flip()
event.waitKeys( keyList=instructionsOKkey)
def instructions(block):
#select instructions based on block
if block == "F":
instructions = modOff
elif block == "N":
instructions = noseOn
elif block == "M":
instructions = mouthOn
else:
NotImplementedError(f'{block} has no defined instructions')
# display instructions until keypress
instructions.draw()
triggerStim.draw()
win.flip()
event.waitKeys(keyList=instructionsOKkey)
triggerStim.draw()
win.flip()
def runBlocks(blocks,et_client,ET,ETGC,Recalibrate):
for block in blocks:
print(block)
instructions(block)
if ET and ETGC:# pre-stim GC check
et_client.startTrial(trialNr=block)
correctFixation = False
print("Wait for Fixation at StimFIX - mystimfix - prestim")
et_client.sendMsg(msg="WaitingForFixation_prestim") # this seems to arrive 3 ms after the second line gets time from et_client
while correctFixation == False:
if Recalibrate:
recalibrate_et(win,client=et_client, default_fullscreen=fullscreen,saveFolder=saveFolder,subjectID=subjectID,
displayResolution=displayResolution,
monWidth=monWidth,
monHeight=monHeight,
monDistance=monDistance,
foregroundColor=foregroundColor,
backgroundColor=backgroundColor,
textHeightETclient=textHeightETclient)
et_client = setup_et(win, hz, saveFileEDF=create_save_file_EDF(saveFolder, subjectID),
displayResolution=displayResolution,
monWidth=monWidth,
monHeight=monHeight,
monDistance=monDistance,
foregroundColor=foregroundColor,
backgroundColor=backgroundColor,
textHeightETclient=textHeightETclient)
et_client.sendMsg(msg="New start of experiment")
et_client.startTrial(trialNr=block) # starts eyetracking recording.
Recalibrate = False
# Gaze Contingency
correctFixation, problemWithFixation,Recalibrate, StopGC,Refocusing = et_client.waitForFixation(fixDot=fix, maxDist=etMaxDist,
maxWait=etMaxWait, nRings=etNRings,
fixTime=etFixTime, test=ETtest, gazeDot=gazeDot) # participant need to look at fixation for 200 ms. can respond with "3" instead of space to try again.
if Refocusing: # if the rings have appeared, getting the participant to refocus, its natural that
# some time passes before other experimental stimuli is presented.
fix.draw()
win.flip()
psychopy.core.wait(refocusingTime)
if StopGC:
print("stop GC")
ETGC = False
correctFixation=True
et_client.sendMsg(msg="experimenter pressed q - stopping GC")
et_client.sendMsg(msg="problemWithFixation_prestim %s" % problemWithFixation)
else:
correctFixation=True
if ET:
et_client.sendMsg(msg="BeginningTrial - %s" % block)
# send MEG data trigger here if possible
triggerStim.draw()
fix.draw()
win.flip()
event.waitKeys(keyList=quitKey,maxWait=periBlockTime)
clock.reset()
key = None
while clock.getTime() < blockTimeSecs and key is None:
#send trigger pulse
triggerStim.color=triggerColor(block)
triggerStim.draw()
fix.draw()
win.flip()
# remove trigger
triggerStim.color=(0,0,0) # remove trigger
triggerStim.draw()
fix.draw()
win.flip()
key = event.waitKeys(keyList=quitKey, maxWait=1 , clearEvents=False)
print(key, type(key))
triggerStim.draw()
fix.draw()
win.flip()
event.waitKeys(keyList=quitKey,maxWait=periBlockTime)
#
if __name__ == '__main__':
if platform == "Windows":
dp.DPxOpen()
isReady = dp.DPxIsReady()
if isReady:
dp.DPxEnableDoutPixelMode()
dp.DPxWriteRegCache()
# setup ET
print("ET is {0}".format(ET))
if ET:
hz = win.getActualFrameRate(nIdentical=50, nMaxFrames=200, nWarmUpFrames=25, threshold=0.5)
et_client = setup_et(win, hz,saveFileEDF=create_save_file_EDF(saveFolder, subjectID),
displayResolution=displayResolution,
monWidth=monWidth,
monHeight=monHeight,
monDistance=monDistance,
foregroundColor=foregroundColor,
backgroundColor=backgroundColor,
textHeightETclient=textHeightETclient)
psychopy.event.globalKeys.clear()
psychopy.event.globalKeys.add(recalibrateKey, set_recalibrate) # Recalibrate mid experiment, 'c'
psychopy.event.globalKeys.add(forceQuitKey, clean_quit) # clean quits the experiment, 'p'
else:
et_client = None
blank()
runBlocks(blocks,et_client,ET,ETGC,Recalibrate)
if platform == "Windows":
dp.DPxDisableDoutPixelMode()
dp.DPxWriteRegCache()
dp.DPxClose()
et_client.cleanUp(saveFileEDF=create_save_file_EDF(saveFolder))
win.close()
core.quit()