From 1b9f45f8179dcbd91cae9245008cc9031498be03 Mon Sep 17 00:00:00 2001 From: AxelNoun <150222552+AxelNoun@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:32:22 +0100 Subject: [PATCH 1/3] Add an HBN-EEG response time regression task HBNResponseTimeRegression cuts one window per contrast change detection trial, 0.5 to 2.5 s after the target stimulus by default, and predicts the response time, as in challenge 1 of the EEG Foundation Challenge 2025. Trials are built with the rule of build_trial_table in EEGDash, which the challenge starter kit uses. Optional filters drop fast responses or wrong-hand responses. --- docs/api/tasks.rst | 1 + ...health.tasks.HBNResponseTimeRegression.rst | 16 + pyhealth/tasks/__init__.py | 3 + pyhealth/tasks/hbn_response_time.py | 384 ++++++++++++++++++ tests/core/test_hbn_response_time.py | 341 ++++++++++++++++ 5 files changed, 745 insertions(+) create mode 100644 docs/api/tasks/pyhealth.tasks.HBNResponseTimeRegression.rst create mode 100644 pyhealth/tasks/hbn_response_time.py create mode 100644 tests/core/test_hbn_response_time.py diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 9796b94ed..9b3020fd8 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -284,6 +284,7 @@ Available Tasks Sleep Staging Sequences (ISRUC) Sleep Staging (HMC) Psychopathology Regression (HBN-EEG) + Response Time Regression (HBN-EEG) Seizure Onset Zone Localization (HUP iEEG) Sleep Staging (DREAMT) Temple University EEG Tasks diff --git a/docs/api/tasks/pyhealth.tasks.HBNResponseTimeRegression.rst b/docs/api/tasks/pyhealth.tasks.HBNResponseTimeRegression.rst new file mode 100644 index 000000000..d32156600 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.HBNResponseTimeRegression.rst @@ -0,0 +1,16 @@ +pyhealth.tasks.HBNResponseTimeRegression +======================================== + +Regression of the response time of each trial of the HBN-EEG contrast +change detection task, from a window of EEG that follows the target +stimulus, as in challenge 1 of the EEG Foundation Challenge 2025. Trials of +a participant are correlated: split by participant. + +.. autoclass:: pyhealth.tasks.HBNResponseTimeRegression + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.tasks.hbn_response_time.read_ccd_trials + +.. autofunction:: pyhealth.tasks.hbn_response_time.events_file_for diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index abf5ac825..3df6aa302 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -347,6 +347,9 @@ from .hbn_psychopathology import ( HBNPsychopathologyRegression as HBNPsychopathologyRegression, ) +from .hbn_response_time import ( + HBNResponseTimeRegression as HBNResponseTimeRegression, +) from .soz_localization_hup import ( SOZLocalizationHUP as SOZLocalizationHUP, ) diff --git a/pyhealth/tasks/hbn_response_time.py b/pyhealth/tasks/hbn_response_time.py new file mode 100644 index 000000000..1eb818368 --- /dev/null +++ b/pyhealth/tasks/hbn_response_time.py @@ -0,0 +1,384 @@ +"""Regression of the response time in the HBN-EEG contrast change detection task. + +Author: Axel Coiffard-Donaty +Paper: S. Y. Shirazi et al. "HBN-EEG: The FAIR implementation of the + Healthy Brain Network (HBN) electroencephalography dataset". bioRxiv, + 2024. https://doi.org/10.1101/2024.10.03.615261 +Description: Implements ``HBNResponseTimeRegression``: one EEG window per + trial of the contrast change detection task, anchored on the target + stimulus, as input, and the response time of that trial (button press + minus target onset, in seconds) as a continuous target, as in challenge 1 + of the EEG Foundation Challenge 2025 (https://eeg2025.github.io/). +""" + +import csv +import logging +import math +from pathlib import Path +from typing import Any, ClassVar + +import numpy as np + +from .base_task import BaseTask +from .hbn_psychopathology import _parse_factor, read_hbn_recording + +logger = logging.getLogger(__name__) + +#: BIDS task name of the contrast change detection paradigm. +CCD_BIDS_TASK = "contrastChangeDetection" + +_TRIAL_START = "contrastTrial_start" +_TARGETS = ("left_target", "right_target") +_PRESSES = ("left_buttonPress", "right_buttonPress") +_END = "end_experiment" + + +def events_file_for(signal_file: str | Path) -> Path: + """Path of the BIDS ``*_events.tsv`` that sits next to a recording. + + Args: + signal_file: Path to a ``*_eeg.bdf`` or ``*_eeg.edf`` recording. + + Returns: + The same path with ``_eeg.`` replaced by ``_events.tsv``. + + Raises: + ValueError: If the name does not end with ``_eeg.bdf`` or + ``_eeg.edf``. + + Examples: + >>> from pyhealth.tasks.hbn_response_time import events_file_for + >>> events_file_for("sub-X_task-contrastChangeDetection_run-1_eeg.bdf").name + 'sub-X_task-contrastChangeDetection_run-1_events.tsv' + """ + path = Path(signal_file) + for suffix in ("_eeg.bdf", "_eeg.edf"): + if path.name.lower().endswith(suffix): + return path.with_name(path.name[: -len(suffix)] + "_events.tsv") + raise ValueError(f"Expected a *_eeg.bdf or *_eeg.edf file, got {signal_file}.") + + +def read_ccd_trials(events_file: str | Path) -> list[dict[str, Any]]: + """Build the trial table of one contrast change detection recording. + + The rule is the one of ``build_trial_table`` in EEGDash + (``eegdash/hbn/windows.py``), which the challenge 1 starter kit uses, so + that the targets match the challenge: + + - the rows are sorted by ``onset`` (stable sort); + - a trial runs from one ``contrastTrial_start`` to the next one. The + last trial ends at ``end_experiment`` when that event comes after it; + otherwise it has no end and is dropped; + - the stimulus is the first ``left_target`` or ``right_target`` of the + trial; + - the response is the first ``left_buttonPress`` or + ``right_buttonPress`` at or after the stimulus and before the next + trial (from the trial start when there is no stimulus). A press that + comes after the next ``contrastTrial_start`` belongs to that next + trial, where it precedes the stimulus and is ignored; + - ``correct`` is True for ``feedback == "smiley_face"``, False for + ``"sad_face"`` (the other hand), None otherwise. + + Args: + events_file: Path to a BIDS ``*_events.tsv`` with at least the + ``onset`` and ``value`` columns. + + Returns: + One dict per trial, in time order, with ``trial_start``, + ``trial_stop``, ``stimulus_onset`` and ``response_onset`` (seconds, + None when absent), ``response_time`` (response minus stimulus, None + unless both exist), ``response_type`` (the button value or None) and + ``correct``. + + Raises: + ValueError: If the file lacks the ``onset`` or ``value`` column, or + an onset is not a number. + + Examples: + >>> from pyhealth.tasks.hbn_response_time import read_ccd_trials + >>> trials = read_ccd_trials("run-1_events.tsv") # doctest: +SKIP + >>> trials[0]["response_time"] # doctest: +SKIP + 2.13 + """ + with open(events_file, newline="", encoding="utf-8") as handle: + rows = list(csv.DictReader(handle, delimiter="\t")) + if rows and not {"onset", "value"} <= set(rows[0]): + raise ValueError( + f"{events_file} needs onset and value columns; it has {list(rows[0])}." + ) + events = [] + for row in rows: + try: + onset = float(row["onset"]) + except (TypeError, ValueError) as error: + raise ValueError( + f"{events_file}: onset {row['onset']!r} is not a number." + ) from error + if not math.isfinite(onset): + raise ValueError(f"{events_file}: onset {row['onset']!r} is not finite.") + events.append((onset, str(row["value"]).strip(), row.get("feedback"))) + # Python's sort is stable, as the mergesort used by EEGDash. + events.sort(key=lambda event: event[0]) + + starts = [onset for onset, value, _ in events if value == _TRIAL_START] + ends = [onset for onset, value, _ in events if value == _END] + bounds = list(zip(starts, starts[1:])) + if starts and ends and ends[-1] > starts[-1]: + bounds.append((starts[-1], ends[-1])) + + trials = [] + for start, stop in bounds: + stimulus = next( + (o for o, v, _ in events if v in _TARGETS and start <= o < stop), None + ) + since = start if stimulus is None else stimulus + response = next( + ((o, v, f) for o, v, f in events if v in _PRESSES and since <= o < stop), + None, + ) + feedback = None if response is None else response[2] + trials.append( + { + "trial_start": start, + "trial_stop": stop, + "stimulus_onset": stimulus, + "response_onset": None if response is None else response[0], + "response_time": ( + None + if stimulus is None or response is None + else response[0] - stimulus + ), + "response_type": None if response is None else response[1], + "correct": {"smiley_face": True, "sad_face": False}.get( + str(feedback).strip() + ), + } + ) + return trials + + +class HBNResponseTimeRegression(BaseTask): + """Predict the response time of a contrast change detection trial. + + Works with :class:`~pyhealth.datasets.HBNEEGDataset`; download the + recordings with ``download_tasks=("contrastChangeDetection",)``, which + also fetches the ``*_events.tsv`` files this task reads. + + For each ``contrastChangeDetection`` recording (all runs), the task + builds the trial table with :func:`read_ccd_trials`, keeps the trials + that have both a target stimulus and a button press, and cuts one window + per trial: from ``window_offset_sec`` after the stimulus, ``window_sec`` + long, rounded to the nearest sample. The defaults (0.5 s after the + stimulus, 2 s long, no other filter) are those of the challenge 1 starter + kit, so with them the targets and windows follow the challenge. The + signal is read in microvolts, without filtering or re-referencing: the + 100 Hz releases are already filtered to 0.5-50 Hz. + + Observed in the 60 ``events.tsv`` files of mini release 1 (20 + participants, 3 runs): 1,513 trials with a stimulus and a response, + median response time 1.62 s, maximum 2.40 s, and 17 responses under + 0.2 s, 12 of them with ``smiley_face`` feedback; the feedback does not + flag anticipations, hence ``min_response_time``. With the default window, + a response under 0.5 s falls before the window starts. + + Skipped, with counts logged once per patient: + + - recordings whose ``availability`` is not in ``allowed_availability``, + when it is given; + - recordings without an events file, or whose events file or signal + cannot be read (with a warning naming the file); + - trials without a stimulus, without a response, with a wrong-hand + response when ``correct_only`` is True, faster than + ``min_response_time``, or whose window does not fit in the recording. + + Each sample contains: + + - ``"signal"``: float32 array ``(n_channels, window_sec * sfreq)``, + 129 channels and 200 samples for the 100 Hz releases with the + defaults; + - ``"response_time"``: seconds from the stimulus to the press, float; + - ``"patient_id"``, ``"release"``, ``"record_id"`` (the file name), + ``"trial_index"`` (position in the trial table), + ``"stimulus_onset"`` (seconds), ``"correct"`` (1.0, 0.0, or NaN when + the feedback is neither ``smiley_face`` nor ``sad_face``), ``"age"`` + (float, NaN when unknown) and ``"sex"``, as context; they are not + model inputs. + + Trials of one participant are correlated, so split by patient (for + example with :class:`~pyhealth.datasets.PatientSplit`). + + Args: + window_offset_sec: Start of the window, in seconds after the + stimulus; may be negative. Default is 0.5. + window_sec: Window length in seconds. Default is 2. + min_response_time: Drop trials whose response time is below this + many seconds. Default is None (keep all, as the challenge). + correct_only: Keep only trials answered with the correct hand. + Default is False (keep both, as the challenge). + allowed_availability: Keep only recordings whose ``availability`` + in ``participants.tsv`` is in this collection, for example + ``("available",)``. Default is None (every recording on disk). + + Raises: + ValueError: If ``window_sec`` is not positive, ``window_offset_sec`` + is not finite or ``min_response_time`` is negative. + + Examples: + >>> from pyhealth.tasks import HBNResponseTimeRegression + >>> task = HBNResponseTimeRegression() + >>> task.output_schema + {'response_time': 'regression'} + >>> from pyhealth.datasets import HBNEEGDataset + >>> dataset = HBNEEGDataset( # doctest: +SKIP + ... root="/data/hbn", + ... download=True, + ... download_tasks=("contrastChangeDetection",), + ... ) + >>> samples = dataset.set_task(task) # doctest: +SKIP + """ + + task_name: str = "HBNResponseTimeRegression" + input_schema: ClassVar[dict[str, str]] = {"signal": "tensor"} + output_schema: ClassVar[dict[str, str]] = {"response_time": "regression"} + + def __init__( + self, + window_offset_sec: float = 0.5, + window_sec: float = 2.0, + min_response_time: float | None = None, + correct_only: bool = False, + allowed_availability: tuple[str, ...] | None = None, + ) -> None: + if not window_sec > 0: + raise ValueError(f"window_sec must be positive, got {window_sec}.") + if not math.isfinite(window_offset_sec): + raise ValueError( + f"window_offset_sec must be finite, got {window_offset_sec}." + ) + if min_response_time is not None and not min_response_time >= 0: + raise ValueError( + "min_response_time must be None or at least 0, got " + f"{min_response_time}." + ) + self.window_offset_sec = float(window_offset_sec) + self.window_sec = float(window_sec) + self.min_response_time = ( + None if min_response_time is None else float(min_response_time) + ) + self.correct_only = bool(correct_only) + self.allowed_availability = ( + None if allowed_availability is None else tuple(allowed_availability) + ) + # The cache key of set_task includes these attributes, so each setting + # gets its own cached samples. + super().__init__() + + def _keep(self, trial: dict[str, Any], skipped: dict[str, int]) -> bool: + """Apply the trial filters, counting each reason in ``skipped``.""" + if trial["stimulus_onset"] is None: + skipped["no stimulus"] += 1 + return False + if trial["response_onset"] is None: + skipped["no response"] += 1 + return False + if self.correct_only and trial["correct"] is not True: + skipped["not correct"] += 1 + return False + if ( + self.min_response_time is not None + and trial["response_time"] < self.min_response_time + ): + skipped["too fast"] += 1 + return False + return True + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Build the trial windows of one participant. + + Args: + patient: A patient of :class:`~pyhealth.datasets.HBNEEGDataset`. + + Returns: + One sample per kept trial, in recording then time order. + """ + samples: list[dict[str, Any]] = [] + skipped = { + "availability": 0, + "no events file": 0, + "unreadable": 0, + "no stimulus": 0, + "no response": 0, + "not correct": 0, + "too fast": 0, + "outside recording": 0, + } + events = [ + e + for e in patient.get_events(event_type="recordings") + if str(e.bids_task) == CCD_BIDS_TASK + ] + for event in sorted(events, key=lambda e: str(e.signal_file)): + if ( + self.allowed_availability is not None + and str(event.availability) not in self.allowed_availability + ): + skipped["availability"] += 1 + continue + signal_file = str(event.signal_file) + try: + events_file = events_file_for(signal_file) + except ValueError as error: + logger.warning("Skipping %s: %s", signal_file, error) + skipped["unreadable"] += 1 + continue + if not events_file.is_file(): + skipped["no events file"] += 1 + continue + try: + trials = read_ccd_trials(events_file) + except (OSError, ValueError, csv.Error) as error: + logger.warning("Skipping %s: %s", events_file, error) + skipped["unreadable"] += 1 + continue + kept = [(i, t) for i, t in enumerate(trials) if self._keep(t, skipped)] + if not kept: + continue + try: + data, _, sfreq = read_hbn_recording(signal_file) + except (OSError, ValueError) as error: + logger.warning("Skipping %s: %s", signal_file, error) + skipped["unreadable"] += 1 + continue + # At least one sample, so that a very short window is never empty. + length = max(1, round(self.window_sec * sfreq)) + age = _parse_factor(getattr(event, "age", None)) + record_id = signal_file.replace("\\", "/").rsplit("/", 1)[-1] + for index, trial in kept: + start = round( + (trial["stimulus_onset"] + self.window_offset_sec) * sfreq + ) + if start < 0 or start + length > data.shape[1]: + skipped["outside recording"] += 1 + continue + correct = trial["correct"] + samples.append( + { + "patient_id": patient.patient_id, + "release": str(event.release), + "record_id": record_id, + "trial_index": index, + "stimulus_onset": float(trial["stimulus_onset"]), + "correct": float("nan") if correct is None else float(correct), + "age": float("nan") if age is None else age, + "sex": str(event.sex), + "signal": data[:, start : start + length].astype(np.float32), + "response_time": float(trial["response_time"]), + } + ) + if any(skipped.values()): + logger.info( + "%s: skipped %s.", + patient.patient_id, + {k: v for k, v in skipped.items() if v}, + ) + return samples diff --git a/tests/core/test_hbn_response_time.py b/tests/core/test_hbn_response_time.py new file mode 100644 index 000000000..d5963aa2d --- /dev/null +++ b/tests/core/test_hbn_response_time.py @@ -0,0 +1,341 @@ +"""Tests for HBNResponseTimeRegression, on synthetic BDF and events files.""" + +import math +import tempfile +import unittest +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from pyhealth.datasets import HBNEEGDataset, PatientSplit +from pyhealth.tasks import HBNResponseTimeRegression +from pyhealth.tasks.hbn_response_time import events_file_for, read_ccd_trials +from tests.core.hbn_test_utils import signal, write_bdf, write_release + +CCD = "contrastChangeDetection" + +# Two complete trials closed by a third start: stimulus at 2.0 s answered at +# 3.2 s with the right hand, stimulus at 6.0 s answered at 6.9 s with the +# wrong hand. +TWO_TRIALS = [ + (0.0, "break cnt", "n/a"), + (1.0, "contrastTrial_start", "n/a"), + (2.0, "right_target", "n/a"), + (3.2, "right_buttonPress", "smiley_face"), + (5.0, "contrastTrial_start", "n/a"), + (6.0, "left_target", "n/a"), + (6.9, "right_buttonPress", "sad_face"), + (8.0, "contrastTrial_start", "n/a"), +] + + +def write_events(path: Path, rows) -> Path: + """Write ``(onset, value, feedback)`` rows as a BIDS events file.""" + lines = ["onset\tduration\tvalue\tevent_code\tfeedback"] + lines += [ + f"{onset}\tn/a\t{value}\t0\t{feedback}" for onset, value, feedback in rows + ] + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(lines) + "\n", encoding="utf-8") + return path + + +@dataclass +class _Event: + signal_file: str + bids_task: str = CCD + availability: str = "available" + release: str = "R1" + sex: str = "F" + age: str = "10.5" + + +class _Patient: + def __init__(self, patient_id, events): + self.patient_id = patient_id + self._events = events + + def get_events(self, event_type=None): + return self._events + + +class TestEventsAndTrials(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + + def test_events_file_for(self): + self.assertEqual( + events_file_for("/d/sub-A_task-x_run-2_eeg.bdf").name, + "sub-A_task-x_run-2_events.tsv", + ) + self.assertEqual( + events_file_for("sub-A_task-x_eeg.EDF").name, "sub-A_task-x_events.tsv" + ) + with self.assertRaisesRegex(ValueError, "_eeg.bdf"): + events_file_for("sub-A_task-x.bdf") + + def test_trial_table_follows_eegdash(self): + rows = [ + (1.0, "contrastTrial_start", "n/a"), + (2.0, "right_target", "n/a"), + (3.0, "right_buttonPress", "smiley_face"), + # Trial 2: a stimulus, no press before the next trial. + (5.0, "contrastTrial_start", "n/a"), + (6.0, "left_target", "n/a"), + # Trial 3: a late press before the stimulus is ignored; the first + # press after it counts, here with the wrong hand. + (8.4, "contrastTrial_start", "n/a"), + (8.45, "right_buttonPress", "non_target"), + (9.0, "left_target", "n/a"), + (10.0, "right_buttonPress", "sad_face"), + (10.2, "left_buttonPress", "smiley_face"), + # Trial 4: a press without stimulus, timed from the trial start. + (12.0, "contrastTrial_start", "n/a"), + (12.5, "left_buttonPress", "non_target"), + # Trial 5: the last start, without end_experiment, is dropped. + (14.0, "contrastTrial_start", "n/a"), + (15.0, "left_target", "n/a"), + ] + # Shuffled rows: the table sorts them by onset. + path = write_events(self.dir / "a_events.tsv", rows[::-1]) + trials = read_ccd_trials(path) + self.assertEqual(len(trials), 4) + first, second, third, fourth = trials + self.assertEqual((first["trial_start"], first["trial_stop"]), (1.0, 5.0)) + self.assertAlmostEqual(first["response_time"], 1.0) + self.assertIs(first["correct"], True) + self.assertEqual(first["response_type"], "right_buttonPress") + self.assertEqual(second["stimulus_onset"], 6.0) + self.assertIsNone(second["response_onset"]) + self.assertIsNone(second["response_time"]) + self.assertEqual(third["response_onset"], 10.0) + self.assertAlmostEqual(third["response_time"], 1.0) + self.assertIs(third["correct"], False) + self.assertIsNone(fourth["stimulus_onset"]) + self.assertEqual(fourth["response_onset"], 12.5) + self.assertIsNone(fourth["response_time"]) + self.assertIsNone(fourth["correct"]) + # end_experiment after the last start closes the last trial. + path = write_events( + self.dir / "b_events.tsv", rows + [(20.0, "end_experiment", "n/a")] + ) + trials = read_ccd_trials(path) + self.assertEqual(len(trials), 5) + self.assertEqual( + (trials[-1]["trial_start"], trials[-1]["trial_stop"]), (14.0, 20.0) + ) + + def test_bad_events_files_raise(self): + path = self.dir / "c_events.tsv" + path.write_text("onset\tduration\n1.0\tn/a\n", encoding="utf-8") + with self.assertRaisesRegex(ValueError, "onset and value"): + read_ccd_trials(path) + path = write_events( + self.dir / "d_events.tsv", [("soon", "contrastTrial_start", "n/a")] + ) + with self.assertRaisesRegex(ValueError, "not a number"): + read_ccd_trials(path) + path = write_events( + self.dir / "e_events.tsv", [("nan", "contrastTrial_start", "n/a")] + ) + with self.assertRaisesRegex(ValueError, "not finite"): + read_ccd_trials(path) + empty = self.dir / "f_events.tsv" + empty.write_text("", encoding="utf-8") + self.assertEqual(read_ccd_trials(empty), []) + + +class TestHBNResponseTimeRegression(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.dir = Path(self.tmp.name) + + def _recording(self, name, seconds, rows=TWO_TRIALS): + path = self.dir / f"{name}_eeg.bdf" + write_bdf(path, signal(seconds)) + if rows is not None: + write_events(events_file_for(path), rows) + return str(path) + + def test_schema_and_invalid_arguments(self): + task = HBNResponseTimeRegression() + self.assertEqual(task.input_schema, {"signal": "tensor"}) + self.assertEqual(task.output_schema, {"response_time": "regression"}) + with self.assertRaisesRegex(ValueError, "window_sec"): + HBNResponseTimeRegression(window_sec=0) + with self.assertRaisesRegex(ValueError, "window_sec"): + HBNResponseTimeRegression(window_sec=float("nan")) + with self.assertRaisesRegex(ValueError, "window_offset_sec"): + HBNResponseTimeRegression(window_offset_sec=float("inf")) + with self.assertRaisesRegex(ValueError, "min_response_time"): + HBNResponseTimeRegression(min_response_time=-0.1) + + def test_one_window_per_trial_after_the_stimulus(self): + events = [_Event(self._recording("ccd_run-1", 10))] + samples = HBNResponseTimeRegression()(_Patient("p1", events)) + self.assertEqual(len(samples), 2) + first, second = samples + self.assertEqual(first["signal"].shape, (3, 200)) + self.assertEqual(first["signal"].dtype, np.float32) + # The window starts 0.5 s after the stimulus at 2.0 s: samples 250 to + # 449, where channel c holds 1000 * c plus the second index. + np.testing.assert_allclose(first["signal"][0, [0, 49, 50, 199]], [2, 2, 3, 4]) + np.testing.assert_allclose(first["signal"][2, 0], 2002) + self.assertAlmostEqual(first["response_time"], 1.2) + self.assertEqual(first["trial_index"], 0) + self.assertEqual(first["stimulus_onset"], 2.0) + self.assertEqual(first["correct"], 1.0) + self.assertEqual(first["record_id"], "ccd_run-1_eeg.bdf") + self.assertEqual( + (first["patient_id"], first["release"], first["age"]), ("p1", "R1", 10.5) + ) + self.assertAlmostEqual(second["response_time"], 0.9) + self.assertEqual(second["correct"], 0.0) + np.testing.assert_allclose(second["signal"][0, 0], 6) + # Another window: 1 s from the stimulus itself. + task = HBNResponseTimeRegression(window_offset_sec=0.0, window_sec=1.0) + first = task(_Patient("p1", events))[0] + self.assertEqual(first["signal"].shape, (3, 100)) + np.testing.assert_allclose(first["signal"][0, [0, 99]], [2, 2]) + + def test_filters_are_counted(self): + events = [_Event(self._recording("ccd_run-1", 10))] + task = HBNResponseTimeRegression(min_response_time=1.0) + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + samples = task(_Patient("p1", events)) + self.assertEqual([s["trial_index"] for s in samples], [0]) + self.assertIn("'too fast': 1", logs.output[-1]) + task = HBNResponseTimeRegression(correct_only=True) + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + samples = task(_Patient("p1", events)) + self.assertEqual([s["trial_index"] for s in samples], [0]) + self.assertIn("'not correct': 1", logs.output[-1]) + + def test_trials_without_stimulus_or_response_are_counted(self): + rows = [ + (1.0, "contrastTrial_start", "n/a"), + (2.0, "left_target", "n/a"), + (4.0, "contrastTrial_start", "n/a"), + (4.5, "left_buttonPress", "non_target"), + (6.0, "contrastTrial_start", "n/a"), + ] + events = [_Event(self._recording("ccd_run-1", 10, rows))] + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + self.assertEqual(HBNResponseTimeRegression()(_Patient("p1", events)), []) + self.assertIn("'no stimulus': 1", logs.output[-1]) + self.assertIn("'no response': 1", logs.output[-1]) + + def test_windows_outside_the_recording_are_skipped(self): + # 8 s: the second window would end at 8.5 s. + events = [_Event(self._recording("ccd_run-1", 8))] + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + samples = HBNResponseTimeRegression()(_Patient("p1", events)) + self.assertEqual([s["trial_index"] for s in samples], [0]) + self.assertIn("'outside recording': 1", logs.output[-1]) + # A window that would start before the recording. + task = HBNResponseTimeRegression(window_offset_sec=-3.0) + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + samples = task(_Patient("p1", events)) + self.assertEqual([s["trial_index"] for s in samples], [1]) + self.assertIn("'outside recording': 1", logs.output[-1]) + + def test_recordings_skipped_and_order(self): + events = [ + _Event(self._recording("b_run-1", 10)), + _Event(self._recording("a_run-1", 10)), + _Event(self._recording("rest", 10), bids_task="RestingState"), + _Event(self._recording("noevents_run-1", 10, rows=None)), + _Event(self._recording("caution_run-1", 10), availability="caution"), + ] + task = HBNResponseTimeRegression(allowed_availability=("available",)) + with self.assertLogs("pyhealth.tasks.hbn_response_time", "INFO") as logs: + samples = task(_Patient("p1", events)) + self.assertEqual( + [s["record_id"] for s in samples], + ["a_run-1_eeg.bdf"] * 2 + ["b_run-1_eeg.bdf"] * 2, + ) + self.assertIn("'availability': 1", logs.output[-1]) + self.assertIn("'no events file': 1", logs.output[-1]) + + def test_unreadable_files_are_skipped_with_a_warning(self): + bad_signal = self.dir / "bad_run-1_eeg.bdf" + bad_signal.write_bytes(b"not a bdf") + write_events(events_file_for(bad_signal), TWO_TRIALS) + bad_events = self._recording("badevents_run-1", 10) + events_file_for(bad_events).write_text( + "onset\tvalue\nsoon\tx\n", encoding="utf-8" + ) + events = [ + _Event(str(bad_signal)), + _Event(bad_events), + _Event(self._recording("ok_run-1", 10)), + ] + with self.assertLogs("pyhealth.tasks.hbn_response_time", "WARNING") as logs: + samples = HBNResponseTimeRegression()(_Patient("p1", events)) + self.assertEqual({s["record_id"] for s in samples}, {"ok_run-1_eeg.bdf"}) + self.assertEqual(len(logs.output), 2) + self.assertTrue(any("bad_run-1_eeg.bdf" in line for line in logs.output)) + self.assertTrue( + any("badevents_run-1_events.tsv" in line for line in logs.output) + ) + + def test_unknown_feedback_and_age_are_nan(self): + rows = [ + r if r[1] != "right_buttonPress" else (r[0], r[1], "n/a") + for r in TWO_TRIALS + ] + events = [_Event(self._recording("ccd_run-1", 10, rows), age="n/a")] + sample = HBNResponseTimeRegression()(_Patient("p1", events))[0] + self.assertTrue(math.isnan(sample["correct"])) + self.assertTrue(math.isnan(sample["age"])) + + +class TestSetTask(unittest.TestCase): + """The full path through HBNEEGDataset.set_task, processors included.""" + + def test_set_task_with_patient_split(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + root = Path(tmp.name) + subjects = [f"sub-NDARX{i}" for i in range(4)] + folder = write_release( + root, + "R1", + [ + {"participant_id": s, "contrastChangeDetection_1": "available"} + for s in subjects + ], + [(s, CCD, 1, 10) for s in subjects] + + [(subjects[0], "RestingState", None, 4)], + ) + for s in subjects: + name = f"{s}_task-{CCD}_run-1_events.tsv" + write_events(folder / s / "eeg" / name, TWO_TRIALS) + # On Windows the sample chunks stay mapped until the datasets are + # garbage collected, so the cache gets its own lenient directory. + cache = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + self.addCleanup(cache.cleanup) + dataset = HBNEEGDataset(root=str(root), cache_dir=cache.name, num_workers=1) + task = HBNResponseTimeRegression() + samples = dataset.set_task(task) + self.addCleanup(samples.close) + # Two trials per recording, four recordings; the resting state is not used. + self.assertEqual(len(samples), 8) + first = samples[0] + self.assertEqual(tuple(first["signal"].shape), (3, 200)) + self.assertEqual(tuple(first["response_time"].shape), (1,)) + self.assertEqual(samples.output_schema, {"response_time": "regression"}) + parts = dataset.set_task(task, split=PatientSplit(ratios=(0.5, 0.5), seed=0)) + for part in parts: + self.addCleanup(part.close) + ids = [{s["patient_id"] for s in part} for part in parts] + self.assertFalse(ids[0] & ids[1]) + self.assertEqual(sum(len(part) for part in parts), 8) + + +if __name__ == "__main__": + unittest.main() From fe729c683595833cb8e28ef972e80d08834cf780 Mon Sep 17 00:00:00 2001 From: AxelNoun <150222552+AxelNoun@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:22:51 +0100 Subject: [PATCH 2/3] Add an HBN-EEG response time regression example The example trains EEGNet on one window per contrast change detection trial and scores it per test trial against the constant predictor, with the challenge nRMSE. Participants are split 60/20/20 by seed. --- .../eeg/hbn/hbn_response_time_regression.py | 168 ++++++++++++++++++ 1 file changed, 168 insertions(+) create mode 100644 examples/eeg/hbn/hbn_response_time_regression.py diff --git a/examples/eeg/hbn/hbn_response_time_regression.py b/examples/eeg/hbn/hbn_response_time_regression.py new file mode 100644 index 000000000..786c9f9fe --- /dev/null +++ b/examples/eeg/hbn/hbn_response_time_regression.py @@ -0,0 +1,168 @@ +"""Regress the response time of contrast change detection trials on HBN-EEG. + +Author: Axel Coiffard-Donaty +Paper: S. Y. Shirazi et al. "HBN-EEG: The FAIR implementation of the + Healthy Brain Network (HBN) electroencephalography dataset". bioRxiv, + 2024. https://doi.org/10.1101/2024.10.03.615261 +Description: ``HBNEEGDataset`` and ``HBNResponseTimeRegression`` cut one + window per trial of the contrast change detection recordings of the + chosen releases, 0.5 to 2.5 s after the target stimulus (129 channels at + 100 Hz), labelled with the response time in seconds, as in challenge 1 + of the EEG Foundation Challenge 2025. For each seed, participants are + split 60/20/20 with ``PatientSplit``, so no participant is in two parts. + ``EEGNet`` (sampling rate 100 Hz) is trained with the mean squared + error, the epoch with the lowest validation loss is kept, and the test + set is scored at that epoch. + + Scores are reported per trial, the unit the challenge scores: root mean + square error (RMSE), the RMSE divided by the standard deviation of the + true values (nRMSE, the challenge metric), mean absolute error and + Pearson's correlation. The constant predictor, the mean response time of + the training trials, is scored on the same test trials: a model is + useful only if it does better. + + The windows are used as read, in microvolts, without normalization, as + in the challenge starter kit. About 1% of the channel windows of mini + release 1 exceed 1000 uV (often a single channel), against a median + standard deviation of 14 uV; normalization is left to the user. + + This is a usage example, not a benchmark: a mini release has 20 + participants, and the spread over seeds says more than any single score. + +Data: the mini releases of the EEG Foundation Challenge 2025 (CC-BY-SA 4.0), + fetched from the public bucket with ``--download``; the contrast change + detection recordings are 0.68 to 1.06 GB per mini release (releases 1 to + 5). + +Usage: + python examples/eeg/hbn/hbn_response_time_regression.py \\ + --root /data/hbn --download --releases R1 R2 R3 R4 R5 --seeds 0 1 2 +""" + +from __future__ import annotations + +import argparse + +import numpy as np + +from pyhealth.datasets import HBNEEGDataset, PatientSplit, get_dataloader +from pyhealth.models import EEGNet +from pyhealth.tasks import HBNResponseTimeRegression +from pyhealth.trainer import Trainer + +SPLIT_RATIOS = (0.6, 0.2, 0.2) # train / validation / test, by participant +SAMPLING_RATE = 100 # Hz, the rate of the 100 Hz releases +BATCH_SIZE = 64 +LEARNING_RATE = 1e-3 + + +def parse_args() -> argparse.Namespace: + """Parse the command-line arguments. + + Returns: + The parsed arguments. + """ + parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) + parser.add_argument("--root", required=True, help="Folder of release folders.") + parser.add_argument("--download", action="store_true") + parser.add_argument("--releases", nargs="+", default=["R1"]) + parser.add_argument( + "--min-response-time", + type=float, + default=None, + help="Drop trials faster than this, in seconds. Default: keep all.", + ) + parser.add_argument("--seeds", type=int, nargs="+", default=[0]) + parser.add_argument("--epochs", type=int, default=20) + parser.add_argument("--device", default=None, help="Default: cuda if available.") + return parser.parse_args() + + +def scores(y_true: np.ndarray, y_pred: np.ndarray) -> dict[str, float]: + """RMSE, nRMSE, MAE and Pearson's r. + + Args: + y_true: True values. + y_pred: Predictions. + + Returns: + The four scores; ``r`` is NaN when the predictions are constant. + """ + rmse = float(np.sqrt(np.mean((y_true - y_pred) ** 2))) + # np.ptp is exactly 0 for constant values; in float32 np.std is not + # (about 1e-7), and np.corrcoef would then divide 0 by 0. + r = ( + float(np.corrcoef(y_true, y_pred)[0, 1]) + if np.ptp(y_pred) > 0 and np.ptp(y_true) > 0 + else float("nan") + ) + return { + "rmse": rmse, + "nrmse": rmse / float(np.std(y_true)), + "mae": float(np.mean(np.abs(y_true - y_pred))), + "r": r, + } + + +def main() -> None: + """Train and score EEGNet and the constant predictor over the seeds.""" + import torch # after pyhealth, as in the other EEG examples + + args = parse_args() + dataset = HBNEEGDataset( + root=args.root, + download=args.download, + releases=tuple(args.releases), + download_tasks=("contrastChangeDetection",), + ) + task = HBNResponseTimeRegression(min_response_time=args.min_response_time) + rows = [] + for seed in args.seeds: + torch.manual_seed(seed) + np.random.seed(seed) + train, val, test = dataset.set_task( + task, split=PatientSplit(ratios=SPLIT_RATIOS, seed=seed) + ) + model = EEGNet(dataset=train, sampling_rate=SAMPLING_RATE) + trainer = Trainer(model=model, device=args.device) + trainer.train( + train_dataloader=get_dataloader( + train, batch_size=BATCH_SIZE, shuffle=True, seed=seed + ), + val_dataloader=get_dataloader(val, batch_size=BATCH_SIZE), + epochs=args.epochs, + optimizer_params={"lr": LEARNING_RATE}, + monitor="loss", + monitor_criterion="min", + ) + y_true, y_pred, _ = trainer.inference( + get_dataloader(test, batch_size=BATCH_SIZE) + ) + y_true, y_pred = np.ravel(y_true), np.ravel(y_pred) + constant = float(np.mean([float(s["response_time"]) for s in train])) + result = { + "seed": seed, + "n_train_participants": len({s["patient_id"] for s in train}), + "n_test_participants": len({s["patient_id"] for s in test}), + "n_train_trials": len(train), + "n_test_trials": len(y_true), + "model": scores(y_true, y_pred), + "constant": scores(y_true, np.full_like(y_true, constant)), + } + print(f"seed {seed}: {result}") + rows.append(result) + + print(f"\nresponse time, releases {args.releases}, test trials:") + for name in ("model", "constant"): + for metric in ("rmse", "nrmse", "mae", "r"): + values = np.array([row[name][metric] for row in rows]) + values = values[~np.isnan(values)] # r of the constant is NaN + if len(values) == 0: + print(f" {name:9s} {metric:6s} n/a") + continue + std = np.std(values, ddof=1) if len(values) > 1 else 0.0 + print(f" {name:9s} {metric:6s} {np.mean(values):7.3f} +- {std:.3f}") + + +if __name__ == "__main__": + main() From e4ca9f81e1d620d9ce39d2fa6a4b450d24abc1f3 Mon Sep 17 00:00:00 2001 From: AxelNoun <150222552+AxelNoun@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:34:49 +0100 Subject: [PATCH 3/3] Use itertools.pairwise for the trial bounds Ruff 0.17 (RUF007) flags zip(starts, starts[1:]); the pairs are the same. --- pyhealth/tasks/hbn_response_time.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/pyhealth/tasks/hbn_response_time.py b/pyhealth/tasks/hbn_response_time.py index 1eb818368..48bfa3be9 100644 --- a/pyhealth/tasks/hbn_response_time.py +++ b/pyhealth/tasks/hbn_response_time.py @@ -14,6 +14,7 @@ import csv import logging import math +from itertools import pairwise from pathlib import Path from typing import Any, ClassVar @@ -122,7 +123,7 @@ def read_ccd_trials(events_file: str | Path) -> list[dict[str, Any]]: starts = [onset for onset, value, _ in events if value == _TRIAL_START] ends = [onset for onset, value, _ in events if value == _END] - bounds = list(zip(starts, starts[1:])) + bounds = list(pairwise(starts)) if starts and ends and ends[-1] > starts[-1]: bounds.append((starts[-1], ends[-1]))