Skip to content

[BTY-23] Port SHHSDataset to the PyHealth 2.0 BaseDataset - #1500

Draft
ptsoumaki wants to merge 6 commits into
sunlabuiuc:masterfrom
ptsoumaki:e3-shhs-base-dataset
Draft

ptsoumaki wants to merge 6 commits into
sunlabuiuc:masterfrom
ptsoumaki:e3-shhs-base-dataset

Conversation

@ptsoumaki

@ptsoumaki ptsoumaki commented Nov 16, 2026 •

Copy link
Copy Markdown

What this does

Ports SHHSDataset off the legacy BaseSignalDataset onto the 2.0 BaseDataset (YAML config + metadata CSV), and adds a 2.0 SleepStagingSHHS(BaseTask) so the sleep-staging task actually runs on it. TUEV was the reference port; EESM23Dataset/SleepStagingSleepEDF were used as the closer template because they are also sleep-staging.

Claiming bounty BTY-23. Closes #1477.

Files

File Change
pyhealth/datasets/configs/shhs.yaml new — one table per visit (shhs1, shhs2), timestamp: null
pyhealth/datasets/shhs.py rewritten: 122 → 389 changed lines; BaseSignalDataset → BaseDataset
pyhealth/tasks/sleep_staging_shhs.py new — SleepStagingSHHS(BaseTask)
pyhealth/tasks/sleep_staging.py 1.x sleep_staging_shhs_fn kept importable, docstring corrected
pyhealth/tasks/__init__.py exports SleepStagingSHHS (one line)
tests/core/test_shhs.py new, 15 tests
tests/core/test_sleep_staging_shhs.py new, 30 tests
tests/core/test_sleep_staging_shhs_legacy.py renamed from test_sleep_staging_shhs.py, 5 tests, unchanged
tests/core/test_removed_1x_classes.py drops SHHSDataset from the "still a stub" list — see below
docs/api/tasks/*.rst, docs/api/tasks.rst new task page + toctree entry
examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py rewritten to the 2.0 flow

BaseDataset, BaseModel, Trainer and shared processors are untouched.

Why two tables, not one

The cache key in BaseDataset._init_cache_dir hashes tables, the config, and each source file's (size, mtime_ns) — but not visits. With a single table, running visits=("shhs1","shhs2") and then visits=("shhs1",) would silently reuse a global_event_df that still contains shhs2 events. One table per visit makes that impossible and lets the loader pick whichever visits the release actually ships.

Behaviour changes worth reviewing

  1. Channel selection is now name-based (EEG, EEG(sec)) with a positional [2, 7] fallback plus a warning. The 1.x code did raw.get_data()[2:4]; on the 14-channel SHHS montage rows 2–3 are EMG and RESP, not EEG, so this is a bug fix rather than a behaviour change. This is the one change I could not confirm on real data — see the data-access status below.
  2. Labels are int in {0,1,2,3,4,5}. The 1.x code emitted strings and would drop REM if the valid set were {0..4}; code 5 is REM and 9 is movement/unscored, which is dropped and counted.
  3. tables is filtered by metadata_csv_exists, so asking for both visits on a shhs1-only release loads one table instead of raising.
  4. shhs2 annotation path: _annotation_path() tries annotations-events-profusion/<visit>/ and then the legacy .../label/, warning when it falls back, instead of hardcoding either layout.
  5. patient_id is the numeric participant id, so both visits are two events on one Patient. visit and record_id are kept as separate fields. Note this merges the ~3,295 participants re-studied in SHHS-2 — split_by_patient will keep them together, which is the safe direction for leakage but is worth a second opinion.
  6. test_removed_1x_classes.py: upstream added this while the PR was in flight, asserting that in-tree datasets still built on a removed 1.x base raise NotImplementedError. SHHSDataset was one of them. That is precisely what this PR fixes, so it is removed from that list (and from the explanatory comment in datasets/__init__.py). ISRUCDataset left the list when Port ISRUCDataset to the PyHealth 2.0 dataset API (part of #340) #1468 merged and CardiologyDataset left it when it was ported upstream afterwards, so the loop is gone entirely and only the MIMICExtractDataset assertion remains.

Status: waiting on NSRR data access

I have requested access to the SHHS release on NSRR and am waiting for the data use agreement to be approved. Until that comes through, everything here is validated against synthetic fixtures and these remain unverified on real recordings:

  • the actual channel names/order in the released EDFs (drives change 1),
  • whether the label/ layout exists at all in the current release,
  • the real sampling rate (assumed 125 Hz, from the 1.x code).

Once access is granted I will run the example end to end against a real release and fold the confirmed channel names, sampling rate and annotation layout back into this description — correcting changes 1–3 above if any of them turn out wrong. I am not marking this ready before then.

The code fails loudly rather than silently in the meantime: unnamed channels warn, a missing named channel drops the recording with a warning, the label/ fallback warns. The example script has not been executed yet for the same reason; it is import-checked only.

If a maintainer or anyone else with DUA access wants to check sooner, running examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py once against a real download would confirm or correct changes 1–3 cheaply — I would be glad to have that in review instead.

Self-review fixes

A pass over the implementation before marking this ready turned up two real bugs, both now fixed and regression-tested:

  1. epoch_seconds longer than 30 s mislabelled the signal. The old allow-list took 1,2,3,5,6,10,15,30,60,90,120,300, but labels are scored once per 30 s while the loop sliced the signal per window and indexed labels[i] 1:1. At 60 s a window covered scored epochs 2i and 2i+1 and took only labels[i], so samples carried a stage that was not in their own window; 90 is not even a divisor of 30, despite the docstring. This now follows SleepStagingISRUC: one score labels 30 / epoch_seconds consecutive windows, validated with a modulo, and the option was renamed epoch_seconds to match. The old tests hid it because every one of them used epoch_sec=1 — the single value where the broken mapping is coincidentally correct.
  2. ET.ParseError escaped the error handling. It subclasses SyntaxError, not ValueError, so a truncated annotation or an HTML error page aborted the whole set_task run instead of dropping that one night.

Plus, from the same pass: the EDF is read with preload=False so only the requested channels are held in memory (the read failures that preload=True raised inside read_raw_edf are now caught where they actually surface); a file that is not 125 Hz warns instead of leaving SHHS_SAMPLE_RATE unused; subjects is a frozenset; the requested channel names are normalized once; an empty channels list raises; and one unclear docstring was reworded.

A second pass over the fixed code found four more, also fixed:

  1. Channel order was silently reversed. _channel_indices ended with sorted(set(picks)), which is the order the EDF lists channels in, not the order they were requested in. channels=["EEG(sec)", "EEG"] returned rows [EEG, EEG(sec)], so a caller naming a montage would train on permuted channels without any error. dict.fromkeys now dedupes while keeping the requested order, and the channels docs state the guarantee.
  2. A sub-epoch could read into the next scored window. Starts were anchored to the score but ends were not, so at a fractional sampling rate where 30 s and its sub-epochs round differently, the last sub-epoch ran past the boundary and took the following score's label. The stop is now clamped to the window, and the existing length check drops the short remainder.
  3. An annotation with zero epochs was silent — indistinguishable from a night with no data. It now warns, like every other failure mode here.
  4. The EDF was read before the annotation was validated, so a night that was going to be dropped still paid for a full disk pass over its signal. The small XML is parsed first.

Also: a channel requested twice, or a prefix matching several channels, now warns instead of quietly collapsing to one row.

Verification

python -m unittest tests.core.test_shhs tests.core.test_sleep_staging_shhs \
  tests.core.test_sleep_staging_shhs_legacy tests.core.test_sleep_staging \
  tests.core.test_eesm23 tests.core.test_tuev tests.core.test_removed_1x_classes \
  tests.core.test_isruc
→ 107 tests, OK

python tools/check_pr_rules.py --base upstream/master --head HEAD
→ All PR contribution rules passed.

Rebased four times while open — 03db82a0, 0e691f86 when #1486 (ISRUC) merged, b4f482d8, and now 08533de0. The last one conflicted in the pyhealth/tasks/__init__.py import block and in test_removed_1x_classes.py, both resolved by keeping every upstream addition alongside the SHHS export. Diff against 08533de0: 15 files, +1501 / −267.

Coordination

@ptsoumaki
ptsoumaki force-pushed the e3-shhs-base-dataset branch 2 times, most recently from 2eec754 to 156828d Compare November 16, 2026 16:44
@github-actions github-actions Bot mentioned this pull request Nov 16, 2026
@github-actions

github-actions Bot commented Nov 18, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.31% (45607 / 52841 lines)

Modified file Coverage Lines
pyhealth/datasets/__init__.py 100.00% 80 / 80
pyhealth/datasets/shhs.py 89.17% 107 / 120
pyhealth/tasks/__init__.py 98.04% 100 / 102
pyhealth/tasks/sleep_staging.py 98.82% 84 / 85
pyhealth/tasks/sleep_staging_shhs.py 93.71% 134 / 143

Workflow run · 4733c0f

@jhnwu3 jhnwu3 added the status: automatic The PR will go through automatic review process. label Nov 19, 2026
SHHSDataset subclassed the 1.x BaseSignalDataset stub and had no __init__,
so process_EEG_data() read self.root/self.dev/self.filepath, none of which
were ever set. Replace it with a BaseDataset that builds its metadata from
the NSRR polysomnography release:

- configs/shhs.yaml declares one table per visit. Two fixed CSV names keep
  the source fingerprints stable, and putting the visit into the table name
  means visits= shows up in the cache key instead of silently reusing a
  table built from a different subset.
- prepare_metadata() writes one row per recording (patient_id, visit,
  record_id, signal_file, annotation_file) through metadata_csv, is
  idempotent, and drops recordings with no Profusion annotation.
- patient_id is the numeric participant, so a person's two nights stay one
  Patient and cannot straddle a patient-level split.
- The shhs2 annotation lookup accepted only annotations-events-profusion/
  shhs1|shhs2. Some releases nest them under label/, which the 1.x loader
  hardcoded for shhs2; both are now accepted and the fallback is logged.

Refs sunlabuiuc#1477
One 30 s epoch is one sample: two EEG channels in uV and an integer stage
0-5. Movement epochs (code 9) are dropped rather than emitted as a class.

Channels are selected by name (EEG, EEG(sec)) instead of the 1.x
X[[2, 7]], which on a 14-channel SHHS recording picks EMG and RESP, not
EEG. A positional fallback keeps unnamed montages working and logs that it
was used. epoch_sec is limited to divisors of 30 because the annotations
are scored every 30 s and any other value silently misaligned signal and
labels.

The legacy sleep_staging_shhs_fn stays importable but can no longer be
reached through set_task(), which needs a BaseTask; its docstring and the
module __main__ demo said otherwise and would now raise, so both are
updated.

Refs sunlabuiuc#1477
Dataset and task tests build their fixtures in tempfile, so they need
neither the NSRR data nor a network. They cover metadata pairing, the
shhs2 label/ fallback, the shared participant id, epoch truncation in both
directions, movement-epoch dropping, and the channel name/position rules.

The 1.x suite keeps its coverage as test_sleep_staging_shhs_legacy.py so
the conventional test_sleep_staging_shhs.py can name the new task module,
and it is deleted together with sleep_staging_shhs_fn when the 1.x API
goes.

The SHHS example moves back out of examples/old/: it was archived only
because SHHSDataset could not run through set_task(), which no longer
holds, so its manifest row goes too.

Refs sunlabuiuc#1477
tests/core/test_removed_1x_classes.py landed upstream while this port was in
flight and asserts that SHHSDataset still raises NotImplementedError because it
is built on the removed BaseSignalDataset. That is no longer true, so drop it
from the list and the example comment.
epoch_sec accepted 60, 90, 120 and 300 even though the annotations are scored every 30 s. A window longer than a score covered two or more scored epochs but took a single label, so samples were labelled with a stage that was not in their own window, and 90 is not even a divisor of 30. Follow SleepStagingISRUC instead: one score labels 30 / epoch_seconds consecutive windows, validated with a modulo so lengths that cannot align are rejected. Renamed to epoch_seconds to match that task.

ET.ParseError subclasses SyntaxError, so it was not caught where read_sleep_stages failures were handled and a truncated download or an HTML error page aborted the whole run instead of dropping one night.

Read the EDF without preloading so only the requested channels are held in memory, catching the read failures that preload=True used to raise inside read_raw_edf. Also: warn when a file is not 125 Hz instead of leaving SHHS_SAMPLE_RATE unused, look participants up in a frozenset, normalize the requested channel names once, reject an empty channel list, and fix the _normalize_visits docstring wording.
_channel_indices returned sorted(set(picks)), which is file order, not the order the channels were requested in. Asking for ['EEG(sec)', 'EEG'] therefore produced a tensor whose rows were swapped relative to task.channels, so a caller naming a montage would silently train on permuted channels. Use dict.fromkeys to dedupe while preserving the requested order.

Sub-epoch starts were anchored to the scored window but their ends were not, so at a fractional sampling rate a 30 s window rounding differently from its sub-epochs let the last sub-epoch read into the next window and take that score's label. Clamp the stop to the window; the existing length check drops the short remainder instead of mislabelling it.

Also: warn when an annotation has no scored epochs instead of returning nothing silently, read the small XML before the EDF so a dropped night does not pay for its signal, warn when a channel is requested twice or when a prefix matches several channels, and document the row order on the channels argument.
@ptsoumaki
ptsoumaki force-pushed the e3-shhs-base-dataset branch from 591f5ee to 4733c0f Compare November 23, 2026 12:19

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Port SHHSDataset to the PyHealth 2.0 dataset API (part of #340)

2 participants