-
Notifications
You must be signed in to change notification settings - Fork 2
/
show_movie.py
260 lines (231 loc) · 7.11 KB
/
show_movie.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
#!/usr/bin/env python
import sys
from psychopy import prefs
prefs.general['audioLib'] = ['pygame']
from psychopy import visual, gui, event, logging
from psychopy import sound, core
import time as ptime
import serial
import os
from os.path import join as pjoin, exists as pexists
import json
import csv
import datetime
import shutil
skip_response = False
debug = False
# add a new level name called bids
# we will use this level to log information that will be saved
# in the _events.tsv file for this run
BIDS = 26
logging.addLevel(BIDS, 'BIDS')
def logbids(msg, t=None, obj=None):
"""logbids(message)
logs a BIDS related message
"""
logging.root.log(msg, level=BIDS, t=t, obj=obj)
logging.console.setLevel(logging.INFO) # receive nearly all messages
time_template = '%Y%m%dT%H%M%S'
def write_subjectlog(fn, info):
fieldnames = ['subject_id', 'run_nr', 'timestamp']
info_save = {key: info.get(key, '') for key in fieldnames}
with open(fn, 'ab') as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, delimiter='\t')
info_save['timestamp'] = datetime.datetime.now().isoformat()
writer.writerow(info_save)
def load_subjectlog(fn):
lastinfo = {
'subject_id': 'sidXXXXXX',
'run_nr': 1
}
if not pexists(fn):
with open(fn, 'wb') as f:
writer = csv.DictWriter(f,
fieldnames=['subject_id',
'run_nr',
'timestamp'],
delimiter='\t')
writer.writeheader()
else:
with open(fn, 'rb') as f:
reader = csv.DictReader(f, delimiter='\t')
rows = [r for r in reader]
lastinfo = rows[-1]
return lastinfo
# load config
with open('config.json', 'rb') as f:
config = json.load(f)
instructions = config['instructions']
n_parts = len(config['files'])
fixation_s = config['fixation_s']
subjectlog = config['log_subjects']
lastinfo = load_subjectlog(subjectlog)
# ask info to experimenter
info = {
'subject_id': lastinfo['subject_id'],
'run_nr': range(1, n_parts + 1),
'scanner?': True,
}
infdlg = gui.DlgFromDict(dictionary=info,
title="Movie Presentation",
order=['subject_id', 'run_nr', 'scanner?']
)
if not infdlg.OK:
core.quit()
# save log of subjects
write_subjectlog(subjectlog, info)
part = int(info['run_nr'])
subj = info['subject_id']
with open('subjectvolume.json', 'rb') as f:
try:
MOVIE_VOLUME = json.load(f)[subj]
except KeyError:
logging.warn("Subject {0} not present in volume file, "
"using default volume as 0.8")
MOVIE_VOLUME = 0.8
time = core.Clock()
STIMDIR = "stim"
RESDIR = "res"
RESDIR = pjoin(RESDIR, subj)
if not pexists(RESDIR):
os.makedirs(RESDIR)
log_fn = config['log_template'].format(
subj=subj,
task_name=config['task_name'],
runnr=part,
timestamp=ptime.strftime(time_template),
)
log_fn = pjoin(RESDIR, log_fn)
log_responses = logging.LogFile(log_fn, level=logging.INFO)
def move_halted_log(fn):
# flush log
logging.flush()
shutil.move(fn, fn.replace('.txt', '__halted.txt'))
# quit
core.quit()
# set up global key for quitting; if that happens, log will be moved to
# {log_fn}__halted.txt
event.globalKeys.add(key='q',
modifiers=['ctrl'],
func=move_halted_log,
func_args=[log_fn],
name='quit experiment gracefully')
print "Opening screen"
tbegin = time.getTime()
using_scanner = info['scanner?']
# Setting up visual
if using_scanner:
size = [1024, 768]
fullscr = True
else:
size = [1024, 768]
fullscr = False
scrwin = visual.Window(size=size,
allowGUI=False, units='pix',
screen=0, rgb=[-1, -1, -1],
fullscr=fullscr)
# loading movie clip
print "Loading movie part"
clip = config['files'][part - 1]
clip = pjoin(STIMDIR, clip)
loading = visual.TextStim(scrwin,
text=instructions,
height=31)
loading.draw()
scrwin.flip()
movie = visual.MovieStim3(scrwin, clip,
# this looks nice if file is in 16:9
# and frame size is 720 x 406
size=(1024, 577),
name='movie_part_{0}'.format(part))
movie._audioStream.setVolume(MOVIE_VOLUME)
scrwin.flip()
cross_hair = visual.TextStim(scrwin, text='+', height=31,
pos=(0, 0), color='#FFFFFF')
if using_scanner:
intro_msg = "Waiting for trigger..."
else:
intro_msg = "Press Enter to start"
intro = visual.TextStim(scrwin, text=intro_msg, height=31)
# Start of experiment
intro.draw()
scrwin.flip()
# open up serial port and wait for first trigger
if using_scanner:
ser_port = '/dev/ttyUSB0'
ser = serial.Serial(ser_port, 115200, timeout=.0001)
ser.flushInput()
trigger = ''
while trigger != '5':
trigger = ser.read()
else:
from psychopy.hardware.emulator import launchScan
event.waitKeys(keyList=['return'])
# XXX: set up TR here
MR_settings = {
'TR': 1,
'volumes': 280,
'sync': '5',
'skip': 3,
'sound': False,
}
vol = launchScan(scrwin, MR_settings, globalClock=time, mode='Test')
class FakeSerial(object):
@staticmethod
def read():
k = event.getKeys(['1', '2', '5'])
return k[-1] if k else ''
ser = FakeSerial()
# set up timer for experiment starting from first trigger
logging.exp("EXPERIMENT STARTING")
timer_exp = core.Clock()
trunbegin = timer_exp.getTime()
lasttrigger = trunbegin
cross_hair.draw()
scrwin.flip()
# setup bids log
logbids("onset\tduration\tframeidx\tvideotime\tlasttrigger")
# duration will be filled later
template_bids = '{onset:.3f}\t{{duration:.3f}}\t{frameidx}\t{videotime:.3f}' \
'\t{lasttrigger:.3f}'
# wait for fixation
# core.wait(fixation_s)
while timer_exp.getTime() - trunbegin < fixation_s:
if ser.read() == '5':
logging.info("TRIGGER")
lasttrigger = timer_exp.getTime()
iflips = 1
logging.exp("MOVIE STARTING")
logging.flush()
while movie.status != visual.FINISHED:
movie.draw()
scrwin.flip()
# save times
onset = timer_exp.getTime()
videotime = movie.getCurrentFrameTime()
logbids(template_bids.format(
onset=onset,
frameidx=iflips,
videotime=videotime,
lasttrigger=lasttrigger
))
# log every 30 second
if iflips % 1800 == 0:
logging.exp("MOVIE: FLIP {0:06d} ({1:.02f}s since start)".format(
iflips, time.getTime() - trunbegin))
logging.flush()
iflips += 1
if ser.read() == '5':
logging.info("TRIGGER")
lasttrigger = timer_exp.getTime()
logging.exp("MOVIE FINISHED")
scrwin.flip()
# wait 10 seconds at the end
cross_hair.draw()
core.wait(fixation_s)
tend = time.getTime()
logging.exp("EXPERIMENT FINISHED")
logging.exp("Done in {0:.2f}s".format(tend-tbegin))
logging.flush()
scrwin.close()
core.quit()