PsychoPy + Pupil Labs + LSL#
This example demonstrates how to coordinate PsychoPy, LSL, and Pupil Labs.
1import os
2import random
3
4from psychopy import core, gui, logging, visual
5from psychopy.hardware import keyboard
6
7from pred_brain.exp import (
8 configure_pupil_labs_template,
9 create_fiducial_marker_stimuli,
10 get_pupil_labs_device,
11 send_event_to_pupil_labs,
12)
13from pred_brain.exp.lsl import (
14 check_lsl_streams,
15 create_markers_outlet,
16 launch_lab_recorder,
17 set_lab_recorder_filename,
18 start_recording_lab_recorder,
19 stop_recording_lab_recorder,
20 update_lab_recorder,
21)
22
23# ---------------------------------------------------------------------------
24# 1. Participant information
25# ---------------------------------------------------------------------------
26# Ask for the participant ID and run number. They are used to build
27# BIDS-style file names for the log and LabRecorder files.
28
29dlg = gui.Dlg(title="Participant Information")
30dlg.addField("Participant ID:")
31dlg.addField("Run:")
32dlg.show() # Blocks until the dialog is closed.
33if dlg.OK:
34 participant_id = dlg.data[0]
35 run = int(dlg.data[1])
36else:
37 core.quit() # The user pressed cancel.
38
39# ---------------------------------------------------------------------------
40# 2. Experiment configuration
41# ---------------------------------------------------------------------------
42# All timing and path settings are collected here so they are easy to change.
43
44TASK = "JudgeColor"
45N_TRIALS = 5
46FLASH_DURATION_SECONDS = 0.5 # How long the flash stays on screen.
47FLASH_TO_QUESTION_SECONDS = 1.0 # Blank delay between flash and question.
48ISI = 1.0 # Inter-trial interval after the response.
49STARTUP_SECONDS = 3.0 # Time for recorders to initialise before the first marker.
50
51log_directory = "examples_logs_and_data"
52lab_recorder_path = r"LabRecorder-1.18.0-Win_amd64\LabRecorder.exe"
53
54bids_file_stem = f"sub-{participant_id}_task-{TASK}_run-{run}"
55
56# ---------------------------------------------------------------------------
57# 3. PsychoPy logging
58# ---------------------------------------------------------------------------
59# Log INFO and above to the console and to a file. Events are logged at the
60# EXP level, which sits between INFO and WARNING.
61
62logging.console.setLevel(logging.INFO)
63os.makedirs(log_directory, exist_ok=True)
64
65# Keep a reference to the LogFile for the whole experiment; otherwise the file
66# may be closed when the object is garbage collected.
67log_file = logging.LogFile(
68 os.path.join(log_directory, f"{bids_file_stem}.log"),
69 level=logging.INFO,
70 filemode="w",
71)
72logging.info("Experiment initialization started")
73
74# ---------------------------------------------------------------------------
75# 4. LSL marker stream
76# ---------------------------------------------------------------------------
77# Create an LSL outlet with one string channel. Every experiment event is
78# pushed through it, and LabRecorder saves it together with the other streams.
79
80markers_outlet = create_markers_outlet()
81markers_outlet_name = markers_outlet.get_info().name()
82logging.info(f"{markers_outlet_name} LSL stream initialized")
83
84# ---------------------------------------------------------------------------
85# 5. Pupil Labs connection
86# ---------------------------------------------------------------------------
87# Connect to a Pupil Labs eye tracker if one is found. The clock offset
88# converts PsychoPy timestamps to the device clock. If no device is found,
89# `device` is None and the experiment still runs, sending markers over LSL only.
90
91device, clock_offset_ns = get_pupil_labs_device()
92
93# Make sure the device uses the recording template we expect.
94configure_pupil_labs_template(
95 device=device,
96 template_name="Recording with Notes",
97)
98
99
100# Define a helper function to send events to both LSL and Pupil Labs.
101def send_event_to_outputs(event_string: str) -> None:
102 """Send an event marker to LSL and, when connected, to Pupil Labs.
103
104 Schedule this function with ``win.callOnFlip`` when a marker should be
105 timestamped as close as possible to a visual change. PsychoPy's own log
106 uses ``win.logOnFlip`` separately so it receives PsychoPy's flip timestamp.
107 """
108 markers_outlet.push_sample([event_string])
109 if device is not None and clock_offset_ns is not None:
110 send_event_to_pupil_labs(
111 event_string=event_string,
112 device=device,
113 clock_offset_ns=clock_offset_ns,
114 )
115
116
117# ---------------------------------------------------------------------------
118# 6. LabRecorder and LSL stream check
119# ---------------------------------------------------------------------------
120# Start LabRecorder, point it to the output file, and refresh its stream list
121# so that it sees our marker stream.
122
123launch_lab_recorder(lab_recorder_path)
124set_lab_recorder_filename(root=log_directory, filename=f"{bids_file_stem}.xdf")
125update_lab_recorder()
126
127# Verify that every stream we want to record is visible on the network before
128# starting. Names are matched as regular expressions.
129expected_streams = [{"name": markers_outlet_name, "type": "Markers"}]
130if device is not None:
131 # Add expected streams for the Pupil Labs device if it is connected.
132 expected_streams.append({"name": r"Neon Gaze$", "type": "Gaze"})
133 expected_streams.append({"name": r"Neon Events$", "type": "Event"})
134
135streams_ok, found_streams = check_lsl_streams(expected_streams)
136
137if not streams_ok:
138 # Abort rather than collect data that is missing a stream.
139 logging.error(f"Expecting: {expected_streams}")
140 logging.error(f"Found streams: {found_streams}")
141 if device is not None:
142 device.close()
143 core.quit()
144
145# ---------------------------------------------------------------------------
146# 7. Display, stimuli and keyboard
147# ---------------------------------------------------------------------------
148
149win = visual.Window(fullscr=True)
150win.mouseVisible = False
151
152# Full-screen coloured rectangle used as the flash.
153stimulus = visual.Rect(
154 win=win, width=1, height=1, fillColor="white", units="norm", name="Stimulus"
155)
156
157# Text used for the instruction and, later, the question.
158text = visual.TextStim(
159 win=win,
160 text="Press the space bar to start",
161 height=0.05,
162 units="height",
163 name="Instruction",
164)
165
166# Fiducial markers in the screen corners let the Pupil Labs software map gaze
167# onto the display. With autoDraw they are drawn on every flip.
168markers = create_fiducial_marker_stimuli(
169 win=win,
170 marker_family="36h11",
171 marker_ids=range(4),
172 marker_size_pixels=200,
173 auto_layout=True,
174)
175for marker in markers:
176 marker.autoDraw = True
177
178# One keyboard device serves the start screen, the responses and the Escape
179# interruption callback.
180kb = keyboard.KeyboardDevice()
181
182
183# Helper function to end the experiment and release resources.
184def end_experiment(interrupted: bool = False) -> None:
185 """
186 End the experiment and release its resources.
187
188 An experiment-end marker is written to the PsychoPy log and the LSL event
189 stream. If a Pupil Labs recording is active, the marker is also sent to
190 the eye tracker before its recording is stopped and saved.
191 """
192 if interrupted:
193 event_string = "experiment end (interrupted)"
194 logging.warning(event_string)
195 else:
196 event_string = "experiment end"
197 logging.exp(event_string)
198
199 # Record the experiment end marker in the LSL stream.
200 markers_outlet.push_sample([event_string])
201
202 # Send the experiment end marker to the Pupil Labs device if it is connected.
203 if device is not None:
204 if clock_offset_ns is not None:
205 send_event_to_pupil_labs(
206 event_string=event_string,
207 device=device,
208 clock_offset_ns=clock_offset_ns,
209 )
210 device.recording_stop_and_save()
211 logging.info("Pupil Labs recording stopped and saved")
212 device.close()
213
214 # Flush pending messages before closing the window and terminating.
215 stop_recording_lab_recorder()
216 logging.info("LabRecorder stopped")
217 logging.flush()
218 win.close()
219 core.quit()
220
221
222# Pressing Escape calls `end_experiment(True)`. The callback is processed
223# whenever keyboard events are checked (e.g. inside `kb.waitKeys`).
224kb.registerCallback(
225 response="escape",
226 func=end_experiment,
227 args=[True],
228)
229
230
231# ---------------------------------------------------------------------------
232# 8. Start screen
233# ---------------------------------------------------------------------------
234
235text.draw()
236win.flip()
237
238# Wait for the participant (or experimenter) to press the space bar.
239kb.waitKeys(keyList=["space"])
240
241# Clear the instruction screen.
242win.flip()
243
244# ---------------------------------------------------------------------------
245# 9. Start recording
246# ---------------------------------------------------------------------------
247# Start the external recordings first and give them time to initialise, so the
248# experiment-start marker is not lost.
249
250start_recording_lab_recorder()
251if device is not None:
252 device.recording_start()
253 logging.info("Pupil Labs recording started")
254
255core.wait(STARTUP_SECONDS)
256
257experiment_start_event = "experiment start"
258send_event_to_outputs(experiment_start_event)
259logging.exp(experiment_start_event)
260logging.flush()
261
262# ---------------------------------------------------------------------------
263# 10. Trial loop
264# ---------------------------------------------------------------------------
265# Each trial: flash -> blank -> question -> response -> inter-trial interval.
266
267# From now on, `text` shows the response question.
268text.setName("question")
269text.setText("What color was the flash?\n<-- Red Blue -->")
270
271# Correct response key for each flash colour.
272correct_keys = {"red": "left", "blue": "right"}
273
274for trial_index in range(N_TRIALS):
275 # Choose the flash colour and prepare it in the back buffer. Nothing is
276 # visible until the next `win.flip()`.
277 color = random.choice(["red", "blue"])
278 stimulus.setFillColor(color)
279 stimulus.draw()
280
281 # Register two actions for the upcoming flip:
282 # * callOnFlip sends the LSL / Pupil Labs marker right after the flip,
283 # placing its timestamp close to the flash's visual onset;
284 # * logOnFlip lets PsychoPy log the event with its own flip timestamp.
285 event_name = "flash onset"
286 win.callOnFlip(send_event_to_outputs, event_name)
287 win.logOnFlip(level=logging.EXP, msg=event_name)
288
289 # Show the flash (this runs both callbacks) and keep it on screen.
290 win.flip()
291 core.wait(FLASH_DURATION_SECONDS)
292
293 # Flip again without drawing the stimulus to remove the flash, then wait.
294 win.flip()
295 core.wait(FLASH_TO_QUESTION_SECONDS)
296
297 # Show the question, marking its onset the same way as the flash.
298 text.draw()
299 event_name = "question onset"
300 win.callOnFlip(send_event_to_outputs, event_name)
301 win.logOnFlip(level=logging.EXP, msg=event_name)
302 win.flip()
303
304 # Wait for a response. Escape still ends the experiment through the
305 # callback registered earlier.
306 keys = kb.waitKeys(keyList=["left", "right"])
307 key_pressed = keys[0].name
308 correct_text = "correct" if key_pressed == correct_keys[color] else "incorrect"
309
310 # Record the response. No flip is involved, so log and send it directly.
311 event_name = f"response: {key_pressed} ({correct_text})"
312 send_event_to_outputs(event_name)
313 logging.data(event_name)
314
315 # Clear the question and wait before the next trial.
316 win.flip()
317 core.wait(ISI)
318
319 # Write queued log messages to disk after every trial.
320 logging.flush()
321
322# ---------------------------------------------------------------------------
323# 11. Normal experiment completion
324# ---------------------------------------------------------------------------
325# Sends the end marker, stops all recordings and closes the window.
326
327end_experiment(interrupted=False)