MultiTaskBattery 1.3.2__tar.gz → 1.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (23) hide show
  1. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/__init__.py +1 -1
  2. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/experiment_block.py +123 -11
  3. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/screen.py +4 -0
  4. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/task_blocks.py +76 -46
  5. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/task_details.json +8 -0
  6. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/task_file.py +5 -1
  7. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/PKG-INFO +1 -1
  8. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/PKG-INFO +1 -1
  9. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/tests/test_tasks.py +23 -4
  10. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/LICENSE +0 -0
  11. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/battery.py +0 -0
  12. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/fetch.py +0 -0
  13. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/task_table.tsv +0 -0
  14. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/ttl_clock.py +0 -0
  15. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery/utils.py +0 -0
  16. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/SOURCES.txt +0 -0
  17. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/dependency_links.txt +0 -0
  18. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/entry_points.txt +0 -0
  19. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/requires.txt +0 -0
  20. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/MultiTaskBattery.egg-info/top_level.txt +0 -0
  21. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/README.md +0 -0
  22. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/pyproject.toml +0 -0
  23. {multitaskbattery-1.3.2 → multitaskbattery-1.4.0}/setup.cfg +0 -0
@@ -1,4 +1,4 @@
1
1
  """MultiTaskBattery: a toolbox for running multi-domain cognitive and motor
2
2
  tasks during fMRI sessions, built on PsychoPy."""
3
3
 
4
- __version__ = "1.3.2"
4
+ __version__ = "1.4.0"
@@ -2,11 +2,14 @@
2
2
  # March 2021: First version: Ladan Shahshahani - Maedbh King - Suzanne Witt,
3
3
  # Revised 2023: Bassel Arafat, Jorn Diedrichsen, Ince Husain
4
4
 
5
+ import json
5
6
  import pandas as pd
6
7
  import sys
7
8
  import numpy as np
8
9
  from datetime import datetime
10
+ import psychopy
9
11
  from psychopy import visual, gui, event, core
12
+ import MultiTaskBattery
10
13
  import MultiTaskBattery.utils as ut
11
14
  import MultiTaskBattery.task_blocks as tasks
12
15
  from MultiTaskBattery.ttl_clock import TTLClock
@@ -64,9 +67,101 @@ class Experiment:
64
67
  self.tk = pl.EyeLink('100.1.1.1')
65
68
 
66
69
  def quit(self):
67
- """Closes the window and quits the experiment (bound to const.quit_key)."""
68
- self.screen.window.close()
69
- core.quit()
70
+ """Closes the window and quits the experiment (bound to const.quit_key).
71
+ Exits with code 3, so a script that started the run can tell it was stopped.
72
+ The window closes as the program exits (closing it here, inside PsychoPy's key
73
+ check, makes PsychoPy fail while it goes through its open windows)."""
74
+ if getattr(self, 'manifest', None):
75
+ self.write_manifest('stopped')
76
+ self.write_events() # the blocks finished before Esc
77
+ sys.exit(3)
78
+
79
+ def write_events(self):
80
+ """Writes a BIDS events file for this scan into <subj>/events/, named by scan_num
81
+ (sub-<subj>_task-<exp_name>_run-<scan_num>_events.tsv), so it can be copied into a BIDS
82
+ folder as it is. One row for each instruction period ('instruction') and one for each
83
+ task period (trial_type = task name, plus the condition when the block has one).
84
+ Onsets are seconds since the first scanner trigger. Only for runs that waited for the
85
+ trigger; turn off with write_events = False in constants.py."""
86
+ if not getattr(self.const, 'write_events', True) or getattr(self, 'scan_num', None) is None:
87
+ return
88
+ if not self.run_data_file.exists():
89
+ return
90
+ blocks = pd.read_csv(self.run_data_file, sep='\t')
91
+ blocks = blocks[(blocks.run_num == self.run_number) & (blocks.attempt == self.attempt)]
92
+ rows = []
93
+ for task, (_, b) in zip(self.task_obj_list, blocks.iterrows()):
94
+ if b.real_task_start_time > b.real_block_start_time:
95
+ rows.append([b.real_block_start_time, b.real_task_start_time - b.real_block_start_time, 'instruction'])
96
+ trial_type = b.task_name
97
+ conds = task.trial_info['condition'].unique() if 'condition' in task.trial_info else []
98
+ if len(conds) == 1:
99
+ trial_type += f'_{conds[0]}'
100
+ rows.append([b.real_task_start_time, b.real_task_end_time - b.real_task_start_time, trial_type])
101
+ events = pd.DataFrame(rows, columns=['onset', 'duration', 'trial_type']).round(3)
102
+ sub = ''.join(c for c in str(self.subj_id).removeprefix('sub-') if c.isalnum())
103
+ task_label = ''.join(c for c in str(self.exp_name) if c.isalnum())
104
+ events_dir = self.const.data_dir / self.subj_id / 'events'
105
+ events_dir.mkdir(exist_ok=True)
106
+ events.to_csv(events_dir / f'sub-{sub}_task-{task_label}_run-{self.scan_num:02d}_events.tsv',
107
+ sep='\t', index=False)
108
+
109
+ def write_manifest(self, status):
110
+ """Writes <subj_id>_run-<NN>_attempt-<k>_manifest.json next to the subject's data: what
111
+ the run ran under (versions, the simple settings of constants.py, the display that opened)
112
+ and its status: 'running' at the start, then 'finished' or 'stopped' (a crash leaves
113
+ 'running'). The attempt k counts the tries at this run: 1, then 2 for a rerun, and so on;
114
+ it is also saved on every data row, so the tries stay apart. The first call of a run
115
+ writes the file; later calls update it."""
116
+ subj_dir = self.const.data_dir / self.subj_id
117
+ name = f"{self.subj_id}_run-{self.run_number:02d}_attempt-"
118
+ if not getattr(self, 'manifest', None):
119
+ self.attempt = len(list(subj_dir.glob(name + '*_manifest.json'))) + 1
120
+ settings = {}
121
+ for key in dir(self.const):
122
+ value = getattr(self.const, key)
123
+ if key.startswith('_'):
124
+ continue
125
+ try:
126
+ json.dumps(value) # keep only values a json file can hold (no folders, modules)
127
+ settings[key] = value
128
+ except TypeError:
129
+ pass
130
+ window = self.screen.window
131
+ self.manifest = {
132
+ 'subject': self.subj_id,
133
+ 'run_number': self.run_number,
134
+ 'attempt': self.attempt,
135
+ 'scan_num': None,
136
+ 'run_file': str(self.const.run_dir / self.run_filename),
137
+ 'wait_ttl': self.wait_ttl,
138
+ 'status': status,
139
+ 'start_time': datetime.now().isoformat(timespec='seconds'),
140
+ 'end_time': None,
141
+ 'versions': {'MultiTaskBattery': MultiTaskBattery.__version__,
142
+ 'psychopy': psychopy.__version__,
143
+ 'python': sys.version.split()[0]},
144
+ 'display': {'window_size': [int(s) for s in window.size],
145
+ 'refresh_rate_hz': round(1 / window.monitorFramePeriod, 2)},
146
+ 'settings': settings,
147
+ }
148
+ else:
149
+ self.manifest['status'] = status
150
+ if status != 'running':
151
+ self.manifest['end_time'] = datetime.now().isoformat(timespec='seconds')
152
+ manifest_file = subj_dir / f"{name}{self.attempt}_manifest.json"
153
+ with open(manifest_file, 'w') as f:
154
+ json.dump(self.manifest, f, indent=2)
155
+
156
+ def count_scan(self):
157
+ """Called once the first scanner trigger has arrived: scan_num is 1 + the number of this
158
+ subject's earlier runs that got a trigger, so it matches the scanner's own count of scans
159
+ (run 5 repeated after run 8 is scan 9). Without a trigger (wait_ttl False) it stays None."""
160
+ subj_dir = self.const.data_dir / self.subj_id
161
+ earlier = [json.load(open(f)).get('scan_num') for f in subj_dir.glob(f"{self.subj_id}_run-*_manifest.json")]
162
+ self.scan_num = sum(s is not None for s in earlier) + 1
163
+ self.manifest['scan_num'] = self.scan_num
164
+ self.write_manifest('running')
70
165
 
71
166
  def confirm_run_info(self):
72
167
  """
@@ -89,7 +184,6 @@ class Experiment:
89
184
  inputDlg = gui.Dlg(title = f"{self.exp_name}")
90
185
  inputDlg.addField('Enter Subject id (str):',initial = self.subj_id) # run number (int)
91
186
  inputDlg.addField('Enter Run Number (int):',initial = self.run_number+1) # run number (int)
92
- inputDlg.addField('Run File name (str):',initial = self.const.default_run_filename.format(f'{self.run_number + 1:02d}')) # run number (int)
93
187
  inputDlg.addField('Wait for TTL pulse?', initial = True) # a checkbox for ttl pulse (set it true for scanning)
94
188
 
95
189
  inputDlg.show()
@@ -97,8 +191,10 @@ class Experiment:
97
191
  if inputDlg.OK:
98
192
  self.subj_id = str(inputDlg.data[0])
99
193
  self.run_number = int(inputDlg.data[1])
100
- self.run_filename = str(inputDlg.data[2])
101
- self.wait_ttl = bool(inputDlg.data[3])
194
+ # the run file always follows the run number (run 3 -> run_03.tsv); a repeated
195
+ # run is kept apart by its attempt number
196
+ self.run_filename = self.const.default_run_filename.format(f'{self.run_number:02d}')
197
+ self.wait_ttl = bool(inputDlg.data[2])
102
198
  else:
103
199
  sys.exit()
104
200
 
@@ -149,9 +245,17 @@ class Experiment:
149
245
  run a run of the experiment
150
246
  """
151
247
  print(f"Running the experiment - run {self.run_number}")
248
+ self.write_manifest('running')
249
+ for task in self.task_obj_list:
250
+ task.attempt = self.attempt # saved on every trial row
152
251
  self.screen.fixation_cross()
153
252
  self.ttl_clock.reset()
154
253
  self.ttl_clock.wait_for_first_ttl(wait = self.wait_ttl)
254
+ self.scan_num = None
255
+ if self.wait_ttl:
256
+ self.count_scan()
257
+ for task in self.task_obj_list:
258
+ task.scan_num = self.scan_num # saved on every trial row
155
259
  run_data = []
156
260
  run_end_timestamp = None
157
261
 
@@ -170,11 +274,11 @@ class Experiment:
170
274
  r_data = self.run_info.iloc[t_num].copy()
171
275
 
172
276
  # wait till it's time to start the task
173
- r_data['real_start_time'],r_data['start_ttl'],r_data['start_ttl_time'] = self.ttl_clock.wait_until(r_data.start_time)
277
+ r_data['real_block_start_time'],r_data['start_ttl'],r_data['start_ttl_time'] = self.ttl_clock.wait_until(r_data.start_time)
174
278
 
175
279
  ## sending a message to the edf file specifying task name
176
280
  if self.eye_tracker:
177
- self.pl.sendMessageToFile(f"task_name: {task.name} start_track: {self.pl.currentUsec()} real start time {r_data.real_start_time} TR count {self.ttl_clock.ttl_count}")
281
+ self.pl.sendMessageToFile(f"task_name: {task.name} start_track: {self.pl.currentUsec()} real start time {r_data.real_block_start_time} TR count {self.ttl_clock.ttl_count}")
178
282
 
179
283
  # display the instruction text for the task. (instructions are task specific)
180
284
  if r_data.instruction_dur > 0:
@@ -185,10 +289,11 @@ class Experiment:
185
289
 
186
290
  # Run the task (which saves its data to the target)
187
291
  task.start_time = self.ttl_clock.get_time()
292
+ r_data['real_task_start_time'] = task.start_time # after the instructions; real_block_start_time is before them
188
293
  r_data['acc'],r_data['rt'] = task.run()
189
294
 
190
295
  # Add the end time of the task
191
- r_data['real_end_time'] = self.ttl_clock.get_time()
296
+ r_data['real_task_end_time'] = self.ttl_clock.get_time()
192
297
  if getattr(self.const, 'record_task_end_timestamp', False):
193
298
  r_data['task_end_timestamp'] = datetime.now().isoformat()
194
299
  # Run-level stamp: a single wall-clock time taken after the last task.
@@ -199,10 +304,12 @@ class Experiment:
199
304
  run_data.append(r_data)
200
305
 
201
306
  # Optional: persist this task's data immediately so completed tasks survive a mid-run crash
202
- if getattr(self.const, 'save_per_task', False):
307
+ if getattr(self.const, 'save_per_task', True):
203
308
  task.save_data(self.subj_id, self.run_number)
204
309
  one_row = pd.DataFrame([r_data])
205
310
  one_row.insert(0, 'run_num', self.run_number)
311
+ one_row.insert(1, 'attempt', self.attempt)
312
+ one_row.insert(2, 'scan_num', self.scan_num)
206
313
  ut.append_data_to_file(self.run_data_file, one_row)
207
314
 
208
315
  self.screen.fixation_cross()
@@ -220,15 +327,20 @@ class Experiment:
220
327
  self.tk.receiveDataFile(self.tk_filename, self.tk_filename)
221
328
 
222
329
  run_data = pd.DataFrame(run_data)
223
- if not getattr(self.const, 'save_per_task', False):
330
+ if not getattr(self.const, 'save_per_task', True):
224
331
  # save the run data to the run file
225
332
  run_data.insert(0,'run_num',[self.run_number]*len(run_data))
333
+ run_data.insert(1, 'attempt', self.attempt)
334
+ run_data.insert(2, 'scan_num', self.scan_num)
226
335
  if getattr(self.const, 'record_run_end_timestamp', False) and run_end_timestamp is not None:
227
336
  run_data['run_end_timestamp'] = run_end_timestamp
228
337
  ut.append_data_to_file(self.run_data_file, run_data )
229
338
 
230
339
  for task in self.task_obj_list:
231
340
  task.save_data(self.subj_id, self.run_number)
341
+ self.write_manifest('finished')
342
+ self.write_events()
343
+ self.manifest = None # Esc from here on (score board, dialog) leaves this run 'finished'
232
344
 
233
345
  # show the scoreboard (set show_scoreboard = False in constants.py to skip it)
234
346
  if getattr(self.const, 'show_scoreboard', True):
@@ -46,6 +46,10 @@ class Screen:
46
46
  units = self.units,
47
47
  color = self.color,
48
48
  allowGUI = self.allowGUI, allowStencil=True)
49
+ # optional shift of the whole display (deg, [x, y]), for a projected image that sits off
50
+ # the participant's line of sight; [0, 0] (the default) leaves it centred
51
+ self.window.viewPos = const.get('center_shift', [0, 0])
52
+ self.window.flip() # the shift applies from the next flip on
49
53
 
50
54
  def check_monitors(self):
51
55
 
@@ -94,6 +94,9 @@ class Task:
94
94
  t_data = self.run_trial(t_data)
95
95
  # Append the trial data
96
96
  self.trial_data.append(t_data)
97
+ # Hold the last trial's feedback until its end, as the next trial's start holds the others
98
+ if 'end_time' in self.trial_info:
99
+ self.ttl_clock.wait_until(self.start_time + self.trial_info['end_time'].iloc[-1])
97
100
  self.trial_data = pd.DataFrame(self.trial_data)
98
101
  # Calculate the feedback for the run
99
102
  acc = None
@@ -210,9 +213,13 @@ class Task:
210
213
 
211
214
  Args:
212
215
  subj_id (str): Subject id to determine name
213
- run_num (int): Number of run - inserted as first column
216
+ run_num (int): Number of run - inserted as first column, with the attempt
217
+ at that run (self.attempt, set by the Experiment) as the second and the
218
+ scanner's count of scans (self.scan_num) as the third
214
219
  """
215
220
  self.trial_data.insert(0, 'run_num', [run_num]*len(self.trial_data))
221
+ self.trial_data.insert(1, 'attempt', getattr(self, 'attempt', 1))
222
+ self.trial_data.insert(2, 'scan_num', getattr(self, 'scan_num', None))
216
223
  trial_data_file = self.const.data_dir / subj_id / f"{subj_id}_task-{self.code}.tsv"
217
224
  ut.append_data_to_file(trial_data_file, self.trial_data)
218
225
 
@@ -306,8 +313,10 @@ class NBack(Task):
306
313
  self.stim[trial['trial_num']].draw()
307
314
  self.window.flip()
308
315
 
309
- # collect responses 0: no response 1-4: key pressed
310
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['trial_dur'])
316
+ # collect responses 0: no response 1-4: key pressed (until the trial's planned end; RT from the display onset)
317
+ onset = self.ttl_clock.get_time()
318
+ trial_end = self.start_time + trial['start_time'] + trial['trial_dur']
319
+ trial['response'],trial['rt'] = self.wait_response(onset, trial_end - onset)
311
320
  trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
312
321
 
313
322
  # display trial feedback
@@ -379,8 +388,8 @@ class VerbGeneration(Task):
379
388
 
380
389
  self.show_stim(trial['noun'], trial['condition'], trial.get('text_height', 2))
381
390
 
382
- # wait for trial duration
383
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
391
+ # wait until the trial's planned end (timed from its planned start, so delays do not add up)
392
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
384
393
 
385
394
  # ITI: blank the word but keep the cue on, so the context never disappears
386
395
  self.cue(trial['condition']).draw()
@@ -415,8 +424,8 @@ class TongueMovement(Task):
415
424
 
416
425
  self.window.flip()
417
426
 
418
- # wait for trial duration
419
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
427
+ # wait until the trial's planned end (timed from its planned start, so delays do not add up)
428
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
420
429
 
421
430
  # return to a plain fixation cross (no response, so no feedback)
422
431
  self.screen.fixation_cross()
@@ -455,10 +464,12 @@ class MotorLocalizer(Task):
455
464
 
456
465
  def run_trial(self, trial):
457
466
  """ Run a single row of the motor-localizer task. """
458
- # Condition label (body part) at the top of the screen, in black
459
- cond_visual = visual.TextStim(self.window, text=str(trial['condition']), pos=(0.0, trial.get('label_y', 6.0)),
460
- color=(-1, -1, -1), units='deg', height=trial.get('text_height', 1.5))
461
- cond_visual.draw()
467
+ # Condition label (body part) at the top of the screen, in black (unless show_label is
468
+ # False; older task files have no show_label column and show it)
469
+ if trial.get('show_label', True):
470
+ cond_visual = visual.TextStim(self.window, text=str(trial['condition']), pos=(0.0, trial.get('label_y', 6.0)),
471
+ color=(-1, -1, -1), units='deg', height=trial.get('text_height', 1.5))
472
+ cond_visual.draw()
462
473
 
463
474
  # Central fixation cross (drawn without flipping yet)
464
475
  self.screen.fixation_cross(flip=False)
@@ -497,8 +508,8 @@ class AuditoryNarrative(Task):
497
508
 
498
509
  trial_dur = audio_stim.getDuration()
499
510
 
500
- # wait for trial duration (fixation cross stays on screen during playback)
501
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
511
+ # wait until the trial's planned end (fixation cross stays on screen during playback)
512
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
502
513
 
503
514
  return trial
504
515
 
@@ -526,8 +537,8 @@ class SpatialNavigation(Task):
526
537
  # fixation cross stays on screen while the participant imagines the route (no response)
527
538
  self.screen.fixation_cross()
528
539
 
529
- # wait for trial duration
530
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
540
+ # wait until the trial's planned end
541
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
531
542
 
532
543
  return trial
533
544
 
@@ -573,8 +584,9 @@ class TheoryOfMind(Task):
573
584
  story_stim.draw()
574
585
  self.window.flip()
575
586
 
576
- # wait until story duration
577
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['story_dur'])
587
+ # story until its planned end (timed from the trial's planned start, so delays do not add up)
588
+ story_end = self.start_time + trial['start_time'] + trial['story_dur']
589
+ self.ttl_clock.wait_until(story_end)
578
590
 
579
591
  # Flush any keys in buffer
580
592
  event.clearEvents()
@@ -584,8 +596,9 @@ class TheoryOfMind(Task):
584
596
  question_stim.draw()
585
597
  self.window.flip()
586
598
 
587
- # collect responses 0: no response 1-4: key pressed
588
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['question_dur'])
599
+ # collect responses 0: no response 1-4: key pressed (until the question's planned end; RT from its onset)
600
+ onset = self.ttl_clock.get_time()
601
+ trial['response'],trial['rt'] = self.wait_response(onset, story_end + trial['question_dur'] - onset)
589
602
  trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
590
603
 
591
604
  # display trial feedback
@@ -613,8 +626,8 @@ class PassageListening(Task):
613
626
  audio_stim = sound.Sound(str(audio_path))
614
627
  audio_stim.play()
615
628
 
616
- # wait for trial duration (fixation cross stays on screen during playback)
617
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
629
+ # wait until the trial's planned end (fixation cross stays on screen during playback)
630
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
618
631
 
619
632
  return trial
620
633
 
@@ -735,6 +748,7 @@ class DemandGrid(Task):
735
748
  num_steps = 3
736
749
 
737
750
  step_dur = trial['sequence_dur']/num_steps
751
+ t0 = self.start_time + trial['start_time'] # planned trial start: steps and answer window end on schedule
738
752
  self.square_size = trial.get('square_size', 1.5)
739
753
  self.answer_offset = trial.get('answer_offset', 5)
740
754
  self.grid = self.create_grid(grid_size=grid_size)
@@ -758,7 +772,7 @@ class DemandGrid(Task):
758
772
  for rect in row:
759
773
  rect.draw()
760
774
  self.window.flip()
761
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + step_dur)
775
+ self.ttl_clock.wait_until(t0 + (i + 1) * step_dur)
762
776
 
763
777
  for tuple in step_sequence:
764
778
  x, y = tuple
@@ -780,7 +794,7 @@ class DemandGrid(Task):
780
794
  for rect in row:
781
795
  rect.draw()
782
796
  self.window.flip()
783
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + step_dur)
797
+ self.ttl_clock.wait_until(t0 + (i // 2 + 1) * step_dur)
784
798
 
785
799
  # Reset colors after the pair
786
800
  for x, y in pair:
@@ -800,12 +814,17 @@ class DemandGrid(Task):
800
814
  modified_grid = self.create_grid(sequence=modified_sequence, position='left' if correct_side == 'right' else 'right', grid_size=grid_size)
801
815
  self.window.flip()
802
816
 
803
- # collect responses 0: no response 1-4: key pressed
804
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['question_dur'])
817
+ # collect responses 0: no response 1-4: key pressed (until the planned end of the answer window; RT from its onset)
818
+ onset = self.ttl_clock.get_time()
819
+ question_end = t0 + trial['sequence_dur'] + trial['question_dur']
820
+ trial['response'],trial['rt'] = self.wait_response(onset, question_end - onset)
805
821
  trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
806
822
 
807
823
  # Provide feedback if necessary
808
- self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
824
+ # feedback only if a key was pressed; on a miss the screen is left as it is until the next
825
+ # trial draws over it, so nothing flashes at the trial's end
826
+ if trial['response'] != 0:
827
+ self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
809
828
 
810
829
  return trial
811
830
 
@@ -826,12 +845,13 @@ class Reading(Task):
826
845
  sentence = trial['stim']
827
846
  words = sentence.split()
828
847
 
829
- #show words seqeuntially each for 450ms
830
- for word in words:
848
+ #show words seqeuntially each for 450ms (each ends at its planned time, so delays do not add up)
849
+ t0 = self.start_time + trial['start_time']
850
+ for k, word in enumerate(words):
831
851
  word_stim = visual.TextStim(self.window, text=word, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=trial.get('text_height', 2))
832
852
  word_stim.draw()
833
853
  self.window.flip()
834
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + 0.45)
854
+ self.ttl_clock.wait_until(t0 + (k + 1) * 0.45)
835
855
 
836
856
  event.clearEvents()
837
857
 
@@ -839,7 +859,8 @@ class Reading(Task):
839
859
  button_stim = visual.ImageStim(self.window, image=str(ut.find_stim(self.const, self.name, 'hand_press_transparent.png')), size=(trial.get('stim_width', 14.4), None))
840
860
  button_stim.draw()
841
861
  self.window.flip()
842
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), 0.4)
862
+ onset = self.ttl_clock.get_time()
863
+ trial['response'],trial['rt'] = self.wait_response(onset, t0 + len(words) * 0.45 + 0.4 - onset)
843
864
 
844
865
  # show blank_transparent image
845
866
  blank_stim = visual.ImageStim(self.window, image=str(ut.find_stim(self.const, self.name, 'blank_transparent.png')), size=(trial.get('stim_width', 14.4), None))
@@ -893,7 +914,8 @@ class OddBall(Task):
893
914
 
894
915
  word_stim.draw()
895
916
  self.window.flip()
896
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
917
+ letter_end = self.start_time + trial['start_time'] + trial['trial_dur'] # planned, so delays do not add up
918
+ self.ttl_clock.wait_until(letter_end)
897
919
 
898
920
  # blank the letter to a fixation cross during the response window (no per-trial feedback)
899
921
  self.screen.fixation_cross()
@@ -902,7 +924,8 @@ class OddBall(Task):
902
924
  event.clearEvents()
903
925
 
904
926
  # collect responses 0: no response 1-4: key pressed
905
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['iti_dur'])
927
+ now = self.ttl_clock.get_time()
928
+ trial['response'],trial['rt'] = self.wait_response(now, letter_end + trial['iti_dur'] - now)
906
929
 
907
930
  # method 2 for accuracy for oddball
908
931
  if trial['trial_type'] == 1:
@@ -1034,7 +1057,7 @@ class FlexionExtension(Task):
1034
1057
  color=(-1, -1, -1), units='deg', height=trial.get('text_height', 1.5))
1035
1058
  stim.draw()
1036
1059
  self.window.flip()
1037
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + trial['trial_dur'])
1060
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + trial['trial_dur'])
1038
1061
  return trial
1039
1062
 
1040
1063
  class SemanticPrediction(Task):
@@ -1077,18 +1100,20 @@ class SemanticPrediction(Task):
1077
1100
  sentence = trial['sentence']
1078
1101
  words = sentence.split('|')
1079
1102
 
1080
- #show words seqeuntially each for 800ms
1081
- for word in words:
1103
+ #show words seqeuntially each for 800ms (each ends at its planned time, so delays do not add up)
1104
+ t0 = self.start_time + trial['start_time']
1105
+ for k, word in enumerate(words):
1082
1106
  word_stim = visual.TextStim(self.window, text=word, pos=(0.0, 0.0), color=(-1, -1, -1), units='deg', height=height_word)
1083
1107
  word_stim.draw()
1084
1108
  self.window.flip()
1085
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + 0.8)
1109
+ self.ttl_clock.wait_until(t0 + (k + 1) * 0.8)
1086
1110
 
1087
1111
  event.clearEvents()
1088
1112
 
1089
1113
  # Fixation cross
1090
1114
  self.screen.fixation_cross()
1091
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + 0.5)
1115
+ last_word_onset = t0 + len(words) * 0.8 + 0.5
1116
+ self.ttl_clock.wait_until(last_word_onset)
1092
1117
  event.clearEvents()
1093
1118
 
1094
1119
  # Display last word
@@ -1098,8 +1123,9 @@ class SemanticPrediction(Task):
1098
1123
 
1099
1124
  event.clearEvents()
1100
1125
 
1101
- # collect responses 0: no response 1-4: key pressed
1102
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['sentence_dur'])
1126
+ # collect responses 0: no response 1-4: key pressed (until the planned end; RT from the last word's onset)
1127
+ onset = self.ttl_clock.get_time()
1128
+ trial['response'],trial['rt'] = self.wait_response(onset, last_word_onset + trial['sentence_dur'] - onset)
1103
1129
  trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
1104
1130
 
1105
1131
  # display trial feedback
@@ -1218,8 +1244,10 @@ class VisualSearch(Task):
1218
1244
 
1219
1245
  self.window.flip()
1220
1246
 
1221
- # collect responses
1222
- trial['response'],trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['trial_dur'])
1247
+ # collect responses until the trial's planned end (RT from the display onset)
1248
+ onset = self.ttl_clock.get_time()
1249
+ trial_end = self.start_time + trial['start_time'] + trial['trial_dur']
1250
+ trial['response'],trial['rt'] = self.wait_response(onset, trial_end - onset)
1223
1251
  trial['correct'] = (trial['response'] == self.corr_key[trial['trial_type']])
1224
1252
 
1225
1253
  self.display_trial_feedback(trial['display_trial_feedback'], trial['correct'])
@@ -1319,8 +1347,10 @@ class Affective(Task):
1319
1347
  self.stim[trial['trial_num']].draw()
1320
1348
  self.window.flip()
1321
1349
 
1322
- # Wait for response
1323
- trial['response'], trial['rt'] = self.wait_response(self.ttl_clock.get_time(), trial['trial_dur'])
1350
+ # Wait for response until the trial's planned end (from the block start, so the flip's
1351
+ # wait for the screen refresh does not add up over trials); RT from the image onset
1352
+ onset = self.ttl_clock.get_time()
1353
+ trial['response'], trial['rt'] = self.wait_response(onset, self.start_time + trial['start_time'] + trial['trial_dur'] - onset)
1324
1354
 
1325
1355
  # Determine correct response
1326
1356
  correct_key = trial['key_pleasant'] if trial['trial_type'] == 2 else trial['key_unpleasant']
@@ -1375,8 +1405,8 @@ class SerialReactionTime(Task):
1375
1405
  trial_stim = int(trial['stim'])
1376
1406
  target_index = trial_stim - 1
1377
1407
 
1378
- # wait until absolute stimulus time
1379
- stim_onset = self.ttl_clock.get_time()
1408
+ # the trial's planned start, so delays do not add up over the block
1409
+ stim_onset = self.start_time + trial['start_time']
1380
1410
 
1381
1411
  # show stimulus
1382
1412
  for j, box in enumerate(self.boxes):
@@ -1434,7 +1464,7 @@ class FingerRhythmic(Task):
1434
1464
  txt = (f"New trial starts now") # this text shows when a new trials starts
1435
1465
  visual.TextStim(self.window, text=txt,height=self.const.instruction_text_height, color=[-1, -1, -1], wrapWidth=self.const.instruction_wrap_width).draw()
1436
1466
  self.window.flip()
1437
- self.ttl_clock.wait_until(self.ttl_clock.get_time() + 2)
1467
+ self.ttl_clock.wait_until(self.start_time + trial['start_time'] + 2)
1438
1468
 
1439
1469
  self.screen.fixation_cross()
1440
1470
  event.clearEvents()
@@ -1034,6 +1034,14 @@
1034
1034
  "type": "float",
1035
1035
  "description": "Height of the task text (degrees of visual angle)."
1036
1036
  },
1037
+ "label_y": {
1038
+ "type": "float",
1039
+ "description": "Height of the condition label above the centre (degrees of visual angle)."
1040
+ },
1041
+ "show_label": {
1042
+ "type": "bool",
1043
+ "description": "Whether the condition label is shown during the block (default True). Turn it off only when the block has one condition that the instructions already name."
1044
+ },
1037
1045
  "start_time": {
1038
1046
  "type": "float",
1039
1047
  "description": "Row onset, relative to the block start (in seconds)."
@@ -426,7 +426,8 @@ class MotorLocalizer(TaskFile):
426
426
  condition=['hand', 'foot', 'tongue'],
427
427
  file_name=None,
428
428
  text_height=1.5,
429
- label_y=6):
429
+ label_y=6,
430
+ show_label=True):
430
431
  """
431
432
  Create a motor-localizer task file. The block is split into one equal
432
433
  segment per condition (segment_dur = task_dur / len(condition), e.g.
@@ -449,6 +450,8 @@ class MotorLocalizer(TaskFile):
449
450
  file_name (str): Name of the file to save the task data.
450
451
  text_height (float): Height of the task text in degrees of visual angle.
451
452
  label_y (float): Height of the condition label above the centre, in degrees of visual angle.
453
+ show_label (bool): Show the condition label during the block. Turn it off only when
454
+ the block has one condition that the instructions already name.
452
455
 
453
456
  Returns:
454
457
  pd.DataFrame: Task information as a DataFrame.
@@ -467,6 +470,7 @@ class MotorLocalizer(TaskFile):
467
470
  trial['trial_num'] = n
468
471
  trial['text_height'] = text_height
469
472
  trial['label_y'] = label_y
473
+ trial['show_label'] = show_label
470
474
  trial['condition'] = cond
471
475
  trial['trial_type'] = 1 - (p % 2) # 1 = circle present, 0 = circle absent
472
476
  trial['trial_dur'] = trial_dur
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MultiTaskBattery
3
- Version: 1.3.2
3
+ Version: 1.4.0
4
4
  Summary: A flexible Python toolbox for running multi-domain cognitive and motor tasks during fMRI sessions, built on PsychoPy.
5
5
  Author: Diedrichsenlab
6
6
  License-Expression: MIT
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MultiTaskBattery
3
- Version: 1.3.2
3
+ Version: 1.4.0
4
4
  Summary: A flexible Python toolbox for running multi-domain cognitive and motor tasks during fMRI sessions, built on PsychoPy.
5
5
  Author: Diedrichsenlab
6
6
  License-Expression: MIT
@@ -8,7 +8,7 @@ import MultiTaskBattery.utils as ut
8
8
  import MultiTaskBattery.experiment_block as exp_block
9
9
 
10
10
  # shortest block (s) each task can fill; tasks not listed run 6 s
11
- DUR = {'finger_rhythmic': 70, 'time_perception': 10, 'demand_grid': 10,
11
+ DUR = {'finger_rhythmic': 70, 'time_perception': 10, 'demand_grid': 18,
12
12
  'action_observation': 15, 'passage_listening': 15, 'semantic_prediction': 15,
13
13
  'theory_of_mind': 15,
14
14
  'movie': 30, 'auditory_narrative': 30, 'spatial_navigation': 30}
@@ -38,8 +38,11 @@ def test_task(name, const, screen):
38
38
  # task file
39
39
  task_file = ut.get_task_file_class(const, tf.get_task_class(name))(const)
40
40
  args = {'task_dur': dur, 'file_name': f'{name}.tsv'}
41
- if 'run_number' in inspect.signature(task_file.make_task_file).parameters:
41
+ params = inspect.signature(task_file.make_task_file).parameters
42
+ if 'run_number' in params:
42
43
  args['run_number'] = 1
44
+ if 'iti_dur' in params:
45
+ args['iti_dur'] = 0 # no gap between trials, so a trial that runs long delays the next one
43
46
  task_file.make_task_file(**args)
44
47
 
45
48
  # one-block run
@@ -54,5 +57,21 @@ def test_task(name, const, screen):
54
57
  # data saved, block starts on time and does not run past its end
55
58
  block = pd.read_csv(const.data_dir / name / f'{name}.tsv', sep='\t').iloc[-1]
56
59
  assert list((const.data_dir / name).glob(f'{name}_task-*.tsv')), 'no trial data saved'
57
- assert abs(block.real_start_time - block.start_time) < 0.1
58
- assert block.real_end_time < block.end_time + 0.5, 'block ran past its end'
60
+ assert abs(block.real_block_start_time - block.start_time) < 0.1
61
+ assert block.real_task_end_time < block.end_time + 0.5, 'block ran past its end'
62
+ assert abs(block.real_task_start_time - (block.start_time + block.instruction_dur)) < 0.1, 'task did not start after its instructions'
63
+
64
+ # events file: written as if the run had waited for the trigger (scan 1)
65
+ e.scan_num = 1
66
+ e.write_events()
67
+ events = pd.read_csv(next((const.data_dir / name / 'events').glob('*_run-01_events.tsv')), sep='\t')
68
+ assert list(events.trial_type) == ['instruction', events.trial_type.iloc[1]] and events.trial_type.iloc[1].startswith(name)
69
+ assert abs(events.onset.iloc[1] - block.real_task_start_time) < 0.001
70
+
71
+ # trials keep to their schedule: each trial starts as late as the first one, give or take
72
+ # 30 ms, so delays do not add up over the block
73
+ trials = pd.concat(pd.read_csv(f, sep='\t') for f in (const.data_dir / name).glob(f'{name}_task-*.tsv'))
74
+ if len(trials) > 1 and 'real_start_time' in trials:
75
+ lag = trials.real_start_time - trials.start_time
76
+ drift = lag.max() - lag.min()
77
+ assert drift < 0.03, f'trial starts drift by {drift:.3f} s over the block'