Repository navigation
Conversation
ptsoumaki
force-pushed
the
e3-shhs-base-dataset
branch
2 times, most recently
from
November 16, 2026 16:44
2eec754 to
156828d
Compare
Open
Test CoverageTotal: 86.31% (45607 / 52841 lines)
|
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
force-pushed
the
e3-shhs-base-dataset
branch
from
November 23, 2026 12:19
591f5ee to
4733c0f
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What this does
Ports
SHHSDatasetoff the legacyBaseSignalDatasetonto the 2.0BaseDataset(YAML config + metadata CSV), and adds a 2.0SleepStagingSHHS(BaseTask)so the sleep-staging task actually runs on it.TUEVwas the reference port;EESM23Dataset/SleepStagingSleepEDFwere used as the closer template because they are also sleep-staging.Claiming bounty BTY-23. Closes #1477.
Files
pyhealth/datasets/configs/shhs.yamlshhs1,shhs2),timestamp: nullpyhealth/datasets/shhs.pyBaseSignalDataset→BaseDatasetpyhealth/tasks/sleep_staging_shhs.pySleepStagingSHHS(BaseTask)pyhealth/tasks/sleep_staging.pysleep_staging_shhs_fnkept importable, docstring correctedpyhealth/tasks/__init__.pySleepStagingSHHS(one line)tests/core/test_shhs.pytests/core/test_sleep_staging_shhs.pytests/core/test_sleep_staging_shhs_legacy.pytest_sleep_staging_shhs.py, 5 tests, unchangedtests/core/test_removed_1x_classes.pySHHSDatasetfrom the "still a stub" list — see belowdocs/api/tasks/*.rst,docs/api/tasks.rstexamples/eeg/sleep_staging/sleep_staging_shhs_contrawr.pyBaseDataset,BaseModel,Trainerand shared processors are untouched.Why two tables, not one
The cache key in
BaseDataset._init_cache_dirhashestables, the config, and each source file's(size, mtime_ns)— but notvisits. With a single table, runningvisits=("shhs1","shhs2")and thenvisits=("shhs1",)would silently reuse aglobal_event_dfthat 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
EEG,EEG(sec)) with a positional[2, 7]fallback plus a warning. The 1.x code didraw.get_data()[2:4]; on the 14-channel SHHS montage rows 2–3 areEMGandRESP, 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.intin{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.tablesis filtered bymetadata_csv_exists, so asking for both visits on a shhs1-only release loads one table instead of raising._annotation_path()triesannotations-events-profusion/<visit>/and then the legacy.../label/, warning when it falls back, instead of hardcoding either layout.patient_idis the numeric participant id, so both visits are two events on onePatient.visitandrecord_idare kept as separate fields. Note this merges the ~3,295 participants re-studied in SHHS-2 —split_by_patientwill keep them together, which is the safe direction for leakage but is worth a second opinion.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 raiseNotImplementedError.SHHSDatasetwas one of them. That is precisely what this PR fixes, so it is removed from that list (and from the explanatory comment indatasets/__init__.py).ISRUCDatasetleft the list when Port ISRUCDataset to the PyHealth 2.0 dataset API (part of #340) #1468 merged andCardiologyDatasetleft it when it was ported upstream afterwards, so the loop is gone entirely and only theMIMICExtractDatasetassertion 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:
label/layout exists at all in the current release,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.pyonce 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:
epoch_secondslonger than 30 s mislabelled the signal. The old allow-list took1,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 indexedlabels[i]1:1. At 60 s a window covered scored epochs2iand2i+1and took onlylabels[i], so samples carried a stage that was not in their own window;90is not even a divisor of 30, despite the docstring. This now followsSleepStagingISRUC: one score labels30 / epoch_secondsconsecutive windows, validated with a modulo, and the option was renamedepoch_secondsto match. The old tests hid it because every one of them usedepoch_sec=1— the single value where the broken mapping is coincidentally correct.ET.ParseErrorescaped the error handling. It subclassesSyntaxError, notValueError, so a truncated annotation or an HTML error page aborted the wholeset_taskrun instead of dropping that one night.Plus, from the same pass: the EDF is read with
preload=Falseso only the requested channels are held in memory (the read failures thatpreload=Trueraised insideread_raw_edfare now caught where they actually surface); a file that is not 125 Hz warns instead of leavingSHHS_SAMPLE_RATEunused;subjectsis afrozenset; the requested channel names are normalized once; an emptychannelslist raises; and one unclear docstring was reworded.A second pass over the fixed code found four more, also fixed:
_channel_indicesended withsorted(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.fromkeysnow dedupes while keeping the requested order, and thechannelsdocs state the guarantee.Also: a channel requested twice, or a prefix matching several channels, now warns instead of quietly collapsing to one row.
Verification
Rebased four times while open —
03db82a0,0e691f86when #1486 (ISRUC) merged,b4f482d8, and now08533de0. The last one conflicted in thepyhealth/tasks/__init__.pyimport block and intest_removed_1x_classes.py, both resolved by keeping every upstream addition alongside the SHHS export. Diff against08533de0: 15 files, +1501 / −267.Coordination
SleepStagingISRUCwhile this PR was open, and the self-review fixes above broughtSleepStagingSHHSonto its epoch-slicing and channel-selection strategy rather than duplicating a divergent one. The remaining common code (channel resolution, sub-epoch expansion) is still a good candidate for a shared helper; I kept the task self-contained here rather than touching a file that landed the same hour, and would happily do the extraction as a follow-up.SHHSDatasetand the legacy task function, so they should compose, but the reviewer may want to check the annotation-path handling agrees.