MultiTaskBattery 1.4.0__tar.gz → 1.4.3__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 (25) hide show
  1. multitaskbattery-1.4.3/MultiTaskBattery/__init__.py +9 -0
  2. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/experiment_block.py +36 -35
  3. multitaskbattery-1.4.3/MultiTaskBattery/gamepad.py +144 -0
  4. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/task_blocks.py +6 -5
  5. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/PKG-INFO +2 -1
  6. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/SOURCES.txt +1 -0
  7. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/requires.txt +1 -0
  8. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/PKG-INFO +2 -1
  9. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/pyproject.toml +1 -0
  10. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/tests/test_tasks.py +2 -3
  11. multitaskbattery-1.4.0/MultiTaskBattery/__init__.py +0 -4
  12. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/LICENSE +0 -0
  13. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/battery.py +0 -0
  14. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/fetch.py +0 -0
  15. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/screen.py +0 -0
  16. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/task_details.json +0 -0
  17. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/task_file.py +0 -0
  18. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/task_table.tsv +0 -0
  19. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/ttl_clock.py +0 -0
  20. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery/utils.py +0 -0
  21. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/dependency_links.txt +0 -0
  22. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/entry_points.txt +0 -0
  23. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/MultiTaskBattery.egg-info/top_level.txt +0 -0
  24. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/README.md +0 -0
  25. {multitaskbattery-1.4.0 → multitaskbattery-1.4.3}/setup.cfg +0 -0
@@ -0,0 +1,9 @@
1
+ """MultiTaskBattery: a toolbox for running multi-domain cognitive and motor
2
+ tasks during fMRI sessions, built on PsychoPy."""
3
+
4
+ import os
5
+
6
+ # PsychoPy imports pygame when it is installed (MTB needs it for gamepads): hide its banner
7
+ os.environ.setdefault('PYGAME_HIDE_SUPPORT_PROMPT', '1')
8
+
9
+ __version__ = "1.4.3"
@@ -3,14 +3,16 @@
3
3
  # Revised 2023: Bassel Arafat, Jorn Diedrichsen, Ince Husain
4
4
 
5
5
  import json
6
+ import os
6
7
  import pandas as pd
7
8
  import sys
8
9
  import numpy as np
9
10
  from datetime import datetime
10
11
  import psychopy
11
- from psychopy import visual, gui, event, core
12
+ from psychopy import visual, gui, event, core, logging
12
13
  import MultiTaskBattery
13
14
  import MultiTaskBattery.utils as ut
15
+ import MultiTaskBattery.gamepad as gamepad
14
16
  import MultiTaskBattery.task_blocks as tasks
15
17
  from MultiTaskBattery.ttl_clock import TTLClock
16
18
  from MultiTaskBattery.screen import Screen
@@ -43,6 +45,9 @@ class Experiment:
43
45
  ### set the resolution of the subject screen here:
44
46
  self.screen = screen if screen is not None else Screen(const.screen)
45
47
 
48
+ # game controller: set gamepad_buttons in constants.py to answer with a pad (see gamepad.py)
49
+ gamepad.setup(const)
50
+
46
51
  # quit key: works at any point of the experiment (checked on every flip / key read); set quit_key = None in constants.py to disable
47
52
  quit_key = getattr(const, 'quit_key', 'escape')
48
53
  if quit_key:
@@ -70,11 +75,16 @@ class Experiment:
70
75
  """Closes the window and quits the experiment (bound to const.quit_key).
71
76
  Exits with code 3, so a script that started the run can tell it was stopped.
72
77
  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)."""
78
+ check, makes PsychoPy fail while it goes through its open windows).
79
+ os._exit, not sys.exit: on Windows the key arrives in a callback of the window,
80
+ which swallows a SystemExit, so sys.exit there does not stop the run."""
74
81
  if getattr(self, 'manifest', None):
75
82
  self.write_manifest('stopped')
76
83
  self.write_events() # the blocks finished before Esc
77
- sys.exit(3)
84
+ logging.flush()
85
+ sys.stdout.flush()
86
+ sys.stderr.flush()
87
+ os._exit(3)
78
88
 
79
89
  def write_events(self):
80
90
  """Writes a BIDS events file for this scan into <subj>/events/, named by scan_num
@@ -82,8 +92,8 @@ class Experiment:
82
92
  folder as it is. One row for each instruction period ('instruction') and one for each
83
93
  task period (trial_type = task name, plus the condition when the block has one).
84
94
  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:
95
+ trigger; turn on with write_events = True in constants.py (off by default)."""
96
+ if not getattr(self.const, 'write_events', False) or getattr(self, 'scan_num', None) is None:
87
97
  return
88
98
  if not self.run_data_file.exists():
89
99
  return
@@ -174,37 +184,28 @@ class Experiment:
174
184
 
175
185
  Args:
176
186
  """
177
- if not self.const.debug:
178
- # Step 1: Create a temporary small window for user feedback
179
- self.screen.start_screen(height=getattr(self.const, 'instruction_text_height', None),
180
- wrap_width=getattr(self.const, 'instruction_wrap_width', None))
181
-
182
- # a dialog box pops up so you can enter info
183
- #Set up input box
184
- inputDlg = gui.Dlg(title = f"{self.exp_name}")
185
- inputDlg.addField('Enter Subject id (str):',initial = self.subj_id) # run number (int)
186
- inputDlg.addField('Enter Run Number (int):',initial = self.run_number+1) # run number (int)
187
- inputDlg.addField('Wait for TTL pulse?', initial = True) # a checkbox for ttl pulse (set it true for scanning)
188
-
189
- inputDlg.show()
190
-
191
- if inputDlg.OK:
192
- self.subj_id = str(inputDlg.data[0])
193
- self.run_number = int(inputDlg.data[1])
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])
198
- else:
199
- sys.exit()
200
-
187
+ # Step 1: Create a temporary small window for user feedback
188
+ self.screen.start_screen(height=getattr(self.const, 'instruction_text_height', None),
189
+ wrap_width=getattr(self.const, 'instruction_wrap_width', None))
190
+
191
+ # a dialog box pops up so you can enter info
192
+ #Set up input box
193
+ inputDlg = gui.Dlg(title = f"{self.exp_name}")
194
+ inputDlg.addField('Enter Subject id (str):',initial = self.subj_id) # run number (int)
195
+ inputDlg.addField('Enter Run Number (int):',initial = self.run_number+1) # run number (int)
196
+ inputDlg.addField('Wait for TTL pulse?', initial = True) # a checkbox for ttl pulse (set it true for scanning)
197
+
198
+ inputDlg.show()
199
+
200
+ if inputDlg.OK:
201
+ self.subj_id = str(inputDlg.data[0])
202
+ self.run_number = int(inputDlg.data[1])
203
+ # the run file always follows the run number (run 3 -> run_03.tsv); a repeated
204
+ # run is kept apart by its attempt number
205
+ self.run_filename = self.const.default_run_filename.format(f'{self.run_number:02d}')
206
+ self.wait_ttl = bool(inputDlg.data[2])
201
207
  else:
202
- print("running in debug mode")
203
- # pass on the values for your debugging with the following keywords
204
- self.subj_id = 'test00'
205
- self.run_number = self.run_number+1
206
- self.run_filename = 'run_01.tsv'
207
- self.wait_ttl = True
208
+ sys.exit()
208
209
 
209
210
  def init_run(self):
210
211
  """initializing the run:
@@ -0,0 +1,144 @@
1
+ """Read a game controller as if its buttons were the response keys.
2
+
3
+ Set ``gamepad_buttons`` in constants.py, one button per entry of ``response_keys``,
4
+ in the same order::
5
+
6
+ response_keys = ['1', '2', '3', '4']
7
+ gamepad_buttons = ['X', 'Y', 'A', 'B']
8
+
9
+ A press of X then counts as the key '1', Y as '2', and so on, wherever MTB reads a
10
+ response. The keyboard keeps working. Without ``gamepad_buttons`` nothing changes.
11
+
12
+ A button is a name (A, B, X, Y, START, LEFTSHOULDER, DPAD_UP, ...) for a pad SDL
13
+ knows (Xbox, PlayStation, 8BitDo). A pad SDL does not know is taken to be a Current
14
+ Designs GMPD3 (on a 932 in joystick mode): its face buttons answer to A, B, X and Y,
15
+ by where they sit on an Xbox pad. For any other pad, give raw
16
+ button numbers instead, e.g. [0, 1, 2, 3].
17
+
18
+ The pad is polled, not buffered: a press counts when MTB looks for responses, and
19
+ presses made while it is not looking are dropped, as event.clearEvents() drops keys.
20
+ """
21
+ import os
22
+
23
+ from psychopy import event, core
24
+
25
+ _keys = {} # button -> response key
26
+ _held = set() # buttons down at the last poll
27
+ _pad = None # the opened pygame controller or joystick
28
+ _named = False # True: buttons are SDL names, False: raw numbers
29
+
30
+ # Current Designs GMPD3 (932 in joystick mode): SDL's raw button number of each face
31
+ # button, named by where it sits on an Xbox pad.
32
+ GMPD3_BUTTONS = {'Y': 0, 'B': 1, 'X': 2, 'A': 4}
33
+
34
+
35
+ def setup(const):
36
+ """Opens the pad if constants.py sets gamepad_buttons. Called once by the Experiment."""
37
+ global _pad, _named
38
+ close()
39
+ buttons = getattr(const, 'gamepad_buttons', None)
40
+ if not buttons:
41
+ return
42
+ if len(buttons) != len(const.response_keys):
43
+ raise ValueError(f"gamepad_buttons has {len(buttons)} buttons but response_keys has "
44
+ f"{len(const.response_keys)} keys: give one button per response key, in the same order.")
45
+
46
+ # the PsychoPy window has the focus, not pygame: without this SDL ignores the pad
47
+ os.environ['SDL_JOYSTICK_ALLOW_BACKGROUND_EVENTS'] = '1'
48
+ import pygame
49
+ from pygame._sdl2 import controller
50
+ pygame.display.init() # SDL's event loop, which updates the pad; opens no window
51
+ pygame.joystick.init()
52
+ controller.init()
53
+ _named = all(isinstance(b, str) for b in buttons)
54
+ names = [b.upper() for b in buttons] if _named else []
55
+ unknown = [b for b in names if not hasattr(pygame, f'CONTROLLER_BUTTON_{b}')]
56
+ if unknown:
57
+ raise ValueError(f"Unknown gamepad button(s) {unknown}: use A, B, X, Y, START, BACK, "
58
+ f"LEFTSHOULDER, RIGHTSHOULDER, DPAD_UP, DPAD_DOWN, DPAD_LEFT or DPAD_RIGHT.")
59
+ if pygame.joystick.get_count() == 0:
60
+ raise RuntimeError("gamepad_buttons is set in constants.py but no gamepad is plugged in. "
61
+ "Plug it in, or remove gamepad_buttons to use the keyboard only.")
62
+
63
+ if _named and controller.is_controller(0):
64
+ _pad = controller.Controller(0)
65
+ ids = [getattr(pygame, f'CONTROLLER_BUTTON_{b}') for b in names]
66
+ elif _named:
67
+ # no SDL names: read it as a GMPD3, whose raw buttons sit where an Xbox pad's do
68
+ name = pygame.joystick.Joystick(0).get_name()
69
+ missing = [b for b in names if b not in GMPD3_BUTTONS]
70
+ if missing:
71
+ raise RuntimeError(f"The gamepad '{name}' has no SDL button names and is read as a "
72
+ f"Current Designs GMPD3, which has only A, B, X and Y, not {missing}. "
73
+ f"For another pad, give its raw button numbers instead, e.g. [0, 1, 2, 3].")
74
+ _pad = pygame.joystick.Joystick(0)
75
+ _named = False
76
+ ids = [GMPD3_BUTTONS[b] for b in names]
77
+ print(f"Gamepad '{name}' has no SDL button names: reading it as a Current Designs GMPD3.")
78
+ elif all(isinstance(b, int) for b in buttons):
79
+ _pad = pygame.joystick.Joystick(0)
80
+ ids = list(buttons)
81
+ else:
82
+ raise ValueError("gamepad_buttons must be all names (e.g. ['X', 'Y', 'A', 'B']) "
83
+ "or all numbers (e.g. [0, 1, 2, 3]), not a mix.")
84
+ _keys.update(zip(ids, const.response_keys))
85
+ print(f"Gamepad: {pygame.joystick.Joystick(0).get_name()}, "
86
+ f"buttons {list(buttons)} = keys {list(const.response_keys)}")
87
+
88
+
89
+ def close():
90
+ """Releases the pad."""
91
+ global _pad
92
+ if _pad is not None:
93
+ _pad.quit()
94
+ _pad = None
95
+ _keys.clear()
96
+ _held.clear()
97
+
98
+
99
+ def _poll():
100
+ """Returns the response keys of the buttons pressed since the last poll."""
101
+ import pygame
102
+ pygame.event.pump()
103
+ down = {b for b in _keys if _pad.get_button(b)}
104
+ pressed = down - _held
105
+ _held.clear()
106
+ _held.update(down)
107
+ return [_keys[b] for b in pressed]
108
+
109
+
110
+ def get_keys(keyList=None, timeStamped=False):
111
+ """event.getKeys, plus the pad's presses as their response keys."""
112
+ keys = event.getKeys(keyList=keyList, timeStamped=timeStamped)
113
+ if _pad is None:
114
+ return keys
115
+ pad = [k for k in _poll() if keyList is None or k in keyList]
116
+ if not pad:
117
+ return keys
118
+ if timeStamped:
119
+ t = timeStamped.getTime() if hasattr(timeStamped, 'getTime') else core.getTime()
120
+ return sorted(list(keys) + [(k, t) for k in pad], key=lambda kt: kt[1])
121
+ return list(keys) + pad
122
+
123
+
124
+ def wait_keys(maxWait=float('inf'), keyList=None, timeStamped=False):
125
+ """event.waitKeys, plus the pad's presses. Returns None when maxWait runs out."""
126
+ if _pad is None:
127
+ return event.waitKeys(maxWait=maxWait, keyList=keyList, timeStamped=timeStamped)
128
+ end = core.getTime() + maxWait
129
+ while True:
130
+ keys = get_keys(keyList=keyList, timeStamped=timeStamped)
131
+ if keys:
132
+ return keys
133
+ if core.getTime() >= end:
134
+ return None
135
+ core.wait(0.001, hogCPUperiod=0)
136
+
137
+
138
+ def is_held(key):
139
+ """True while the pad button of this response key is held down."""
140
+ if _pad is None:
141
+ return False
142
+ import pygame
143
+ pygame.event.pump()
144
+ return any(_pad.get_button(b) for b, k in _keys.items() if k == key)
@@ -13,6 +13,7 @@ from psychopy import visual, sound, core, event
13
13
  from psychopy.tools.monitorunittools import deg2pix
14
14
  from pyglet.window import key
15
15
  import MultiTaskBattery.utils as ut
16
+ import MultiTaskBattery.gamepad as gamepad
16
17
  from ast import literal_eval
17
18
  from copy import deepcopy
18
19
  from moviepy.audio.io.AudioFileClip import AudioFileClip
@@ -182,7 +183,7 @@ class Task:
182
183
  show_last_seconds=show_last_seconds,
183
184
  y_pos=6)
184
185
  self.window.flip()
185
- keys=event.getKeys(keyList= self.const.response_keys, timeStamped=self.ttl_clock.clock)
186
+ keys=gamepad.get_keys(keyList= self.const.response_keys, timeStamped=self.ttl_clock.clock)
186
187
  if len(keys)>0:
187
188
  response_made = True
188
189
  key_char = keys[0][0]
@@ -992,7 +993,7 @@ class FingerSequence(Task):
992
993
  while self.ttl_clock.get_time() - sequence_start_time < trial['trial_dur'] and num_presses < num_items:
993
994
  self.ttl_clock.update()
994
995
 
995
- keys = event.getKeys(keyList=self.const.response_keys, timeStamped=self.ttl_clock.clock)
996
+ keys = gamepad.get_keys(keyList=self.const.response_keys, timeStamped=self.ttl_clock.clock)
996
997
  if keys:
997
998
  key_char, key_press_time = keys[0]
998
999
  key = self.const.response_keys.index(key_char) + 1
@@ -1426,7 +1427,7 @@ class SerialReactionTime(Task):
1426
1427
  # collect responses until absolute end_time
1427
1428
  responses = []
1428
1429
  while self.ttl_clock.get_time() < (stim_onset + trial['trial_dur'] + trial['iti_dur']):
1429
- keys = event.getKeys(
1430
+ keys = gamepad.get_keys(
1430
1431
  keyList=self.const.response_keys,
1431
1432
  timeStamped=self.ttl_clock.clock
1432
1433
  )
@@ -1495,7 +1496,7 @@ class FingerRhythmic(Task):
1495
1496
  beep_time = clk.getTime()
1496
1497
  beep_times.append(beep_time)
1497
1498
  break
1498
- res = event.waitKeys(maxWait=deadline - now,
1499
+ res = gamepad.wait_keys(maxWait=deadline - now,
1499
1500
  keyList=self.const.response_keys,
1500
1501
  timeStamped=clk)
1501
1502
  if res:
@@ -1508,7 +1509,7 @@ class FingerRhythmic(Task):
1508
1509
  now = clk.getTime()
1509
1510
  if now >= end_abs:
1510
1511
  break
1511
- res = event.waitKeys(maxWait=end_abs - now,
1512
+ res = gamepad.wait_keys(maxWait=end_abs - now,
1512
1513
  keyList=self.const.response_keys,
1513
1514
  timeStamped=clk)
1514
1515
  if res:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MultiTaskBattery
3
- Version: 1.4.0
3
+ Version: 1.4.3
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
@@ -29,6 +29,7 @@ Requires-Dist: pooch
29
29
  Requires-Dist: numba
30
30
  Requires-Dist: nibabel
31
31
  Requires-Dist: psychopy-sounddevice
32
+ Requires-Dist: pygame
32
33
  Provides-Extra: docs
33
34
  Requires-Dist: numpy; extra == "docs"
34
35
  Requires-Dist: sphinx>=1.4; extra == "docs"
@@ -5,6 +5,7 @@ MultiTaskBattery/__init__.py
5
5
  MultiTaskBattery/battery.py
6
6
  MultiTaskBattery/experiment_block.py
7
7
  MultiTaskBattery/fetch.py
8
+ MultiTaskBattery/gamepad.py
8
9
  MultiTaskBattery/screen.py
9
10
  MultiTaskBattery/task_blocks.py
10
11
  MultiTaskBattery/task_details.json
@@ -13,6 +13,7 @@ pooch
13
13
  numba
14
14
  nibabel
15
15
  psychopy-sounddevice
16
+ pygame
16
17
 
17
18
  [docs]
18
19
  numpy
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: MultiTaskBattery
3
- Version: 1.4.0
3
+ Version: 1.4.3
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
@@ -29,6 +29,7 @@ Requires-Dist: pooch
29
29
  Requires-Dist: numba
30
30
  Requires-Dist: nibabel
31
31
  Requires-Dist: psychopy-sounddevice
32
+ Requires-Dist: pygame
32
33
  Provides-Extra: docs
33
34
  Requires-Dist: numpy; extra == "docs"
34
35
  Requires-Dist: sphinx>=1.4; extra == "docs"
@@ -31,6 +31,7 @@ dependencies = [
31
31
  "numba",
32
32
  "nibabel",
33
33
  "psychopy-sounddevice",
34
+ "pygame",
34
35
  ]
35
36
  dynamic = ["version"]
36
37
 
@@ -20,7 +20,7 @@ def const(tmp_path_factory):
20
20
  return types.SimpleNamespace(
21
21
  exp_name='smoke', exp_dir=d, task_dir=d / 'task_files', run_dir=d / 'run_files',
22
22
  data_dir=d / 'data', stim_dir=ut._PACKAGE_STIM_DIR, default_run_filename='run_01.tsv',
23
- response_keys=['a', 's', 'd', 'f'], eye_tracker=False, debug=True, show_scoreboard=False,
23
+ response_keys=['a', 's', 'd', 'f'], eye_tracker=False, show_scoreboard=False, write_events=True,
24
24
  screen={'size': [800, 600], 'fullscr': False, 'number': 0, 'width': 53, 'distance': 57})
25
25
 
26
26
 
@@ -49,8 +49,7 @@ def test_task(name, const, screen):
49
49
  tf.make_run_file([name], [f'{name}.tsv'], instruction_dur=1, task_dur=dur,
50
50
  shuffle=False).to_csv(const.run_dir / 'run_01.tsv', sep='\t', index=False)
51
51
  e = exp_block.Experiment(const, subj_id=name, screen=screen)
52
- e.confirm_run_info()
53
- e.subj_id, e.wait_ttl = name, False
52
+ e.run_number, e.run_filename, e.wait_ttl = 1, 'run_01.tsv', False # what the run dialog sets
54
53
  e.init_run()
55
54
  e.run()
56
55
 
@@ -1,4 +0,0 @@
1
- """MultiTaskBattery: a toolbox for running multi-domain cognitive and motor
2
- tasks during fMRI sessions, built on PsychoPy."""
3
-
4
- __version__ = "1.4.0"