Skip to content

Add wav2sleep model and multi-signal sleep staging task - #1727

Merged
solarsys merged 9 commits into
sunlabuiuc:masterfrom
fujiason:wav2sleep-mesa
Dec 4, 2026
Merged

solarsys merged 9 commits into
sunlabuiuc:masterfrom
fujiason:wav2sleep-mesa

Conversation

@fujiason

@fujiason fujiason commented Nov 29, 2026 •

Copy link
Copy Markdown
Contributor

Contributors:

University of Illinois Urbana-Champaign, CS 598 DL4H, Fall 2026, Team T20.

Contribution Type: New Task + new Model, built on the existing NSRRSleepDataset.

Paper: Jonathan F. Carter and Lionel Tarassenko. wav2sleep: A Unified Multi-Modal Approach to Sleep Stage Classification from Physiological Signals. Proceedings of the 4th Machine Learning for Health Symposium, PMLR 259:186–202 (2025). https://proceedings.mlr.press/v259/carter25a.html (authors' code: https://github.com/joncarter1/wav2sleep, MIT)

Description:
wav2sleep stages every 30 s epoch of a night from any subset of the cardio-respiratory signals ECG, PPG and abdominal and thoracic respiratory effort (ABD, THX). That lets one model be trained across sleep cohorts that recorded different signals. This PR adds the two pieces needed to reproduce it in PyHealth, on top of the existing NSRRSleepDataset (cohort="mesa"):

  • MultiSignalSleepStaging task: prepares each night as in the paper.
    • Reads only the needed EDF channels at their native rates.
    • Resamples ECG and PPG to 1024 samples per epoch and ABD and THX to 256.
    • Z-scores each signal over the night, then pads or cuts the night to 1,200 epochs (10 h).
    • Reads the stages from the profusion XML files that NSRRSleepDataset indexes (the NSRR-harmonized *-nsrr.xml format also works), and maps them to 4 classes (W, light, deep, REM) or 5 classes. Unscored and padded epochs are -1.
    • A missing or flat channel becomes all-NaN, which the model treats as unavailable.
    • Channel names are arguments, so the task also fits other NSRR cohorts.
    • A night whose EDF or XML file is missing, truncated or malformed, whose epochs aren't 30 s, or whose signals are all missing or flat is skipped with a warning, so one bad download doesn't stop set_task.
    • It has its own EDF reader (read_edf_channels) rather than the private _read_edf_channels in sleep_staging_nsrr.py. Ours keeps the exact channel labels so channel names can be passed per cohort, returns float64, and raises on a truncated file so the task can skip that night instead of training on part of it.
  • Wav2Sleep model (BaseModel), with the paper's defaults:
    • per-signal residual CNN encoders;
    • an EpochMixer transformer with a CLS token that attends only to the signals present in each night (key-padding mask);
    • a SequenceMixer of dilated convolutions (dilations 1–32, two blocks).
    • Stochastic signal masking in training (masking="fixed" with the paper's probabilities, or "subset" / "none"), plus random polarity inversion.
    • use_signals=[...] evaluates a trained model on any subset of its signals. An unknown signal name or a label >= n_classes raises a clear ValueError.
    • Labels are a per-epoch tensor (-1 ignored). The model supplies a multiclass label processor, as DeepSleepNet does, so Trainer scores every scored epoch (metrics=["accuracy", "cohen_kappa"]).

Uses the existing NSRRSleepDataset (intended): MESA is already covered by NSRRSleepDataset(cohort="mesa") from #1425, so this PR adds no dataset and doesn't change NSRRSleepDataset. The task only needs each event's signal_file (EDF) and label_file (XML), which NSRRSleepDataset provides. The example uses its prepare_metadata to build the MESA index, then writes a smaller copy of that index to train on a subset of nights.

Why a separate task from SleepStagingCardioRespiratory (#1425): both read NSRR EDF channels, resample them to 1024/256 points per 30 s and use the same 4 classes. The outputs differ in ways that would change the existing task's schema and behaviour, not just add an option:

SleepStagingCardioRespiratory MultiSignalSleepStaging
One sample is one 30 s epoch one whole night, (1200, points) per signal
Label one class (multiclass) one class per epoch, -1 for unscored or padding (tensor)
A requested signal is missing the night is skipped the night is kept and that signal is all-NaN

wav2sleep needs the second column. Its sequence mixer looks across the whole night, so it needs whole-night samples. And it's trained on nights that recorded different signals (e.g. SHHS has no PPG), so a missing signal must be marked unavailable rather than dropping the night. Adding this as an option would give SleepStagingCardioRespiratory two different input and output schemas, so we kept it as a separate task. And from SHHSMultimodalSleepStaging (#1688): that task also marks missing signals, but it makes one sample per epoch with one label, supports only ECG, ABD and THX (SHHS has no PPG), and uses fixed SHHS channel names. Ours makes one sample per whole night, adds PPG, and takes the channel names as arguments, so it fits MESA and other NSRR cohorts. A per-night mode there would change its schema in the same way. Neither #1425 nor #1688 adds the wav2sleep model. Our task lives in multi_signal_sleep_staging.py so it doesn't collide with sleep_staging_nsrr.py; no existing files are changed apart from index entries.

  • Example and ablations (examples/mesa_sleep_staging_wav2sleep.py): the full pipeline, from dataset to task to Trainer to evaluation on each input set. It adds three ablations that are not in the paper:

    1. masking schedule: fixed, uniform subset, increasing, or none;
    2. test-time ECG corruption: noise, flat-line blocks, or dropout after the first 5 hours;
    3. training-data fraction: joint model vs ECG-only model (trained and validated only on nights that recorded ECG).

    Without --root, it writes synthetic nights and runs all three ablations in a few minutes (about 2 with a GPU, about 5 on a CPU). Results on 500 MESA nights are in its module docstring and summarized below. They were produced with an earlier version of the script that read the NSRR-harmonized (*-nsrr.xml) stage annotations instead of the profusion files NSRRSleepDataset indexes; the task's preprocessing and the model are unchanged. The data has since been deleted under the NSRR data use agreement, so they can't be re-run with the current version.

Results (500 MESA nights, 350/49/101 train/val/test split by participant, one RTX 5070 Ti):

Cohen's κ on the test set, by the signals given to the model:

Training masking All ECG PPG ECG+THX ABD+THX
fixed (paper) 0.662 0.280 0.643 0.448 0.469
uniform subset 0.657 0.273 0.593 0.604 0.627
increasing 0.698 0.279 0.646 0.544 0.628
none 0.739 0.031 0.503 0.624 0.710
  • Masking:
    • Without it, ECG alone fails (κ 0.03) and PPG alone drops to 0.503, which matches the paper's claim that masking matters for single signals.
    • The paper's hand-picked probabilities trade the respiratory sets against PPG.
    • An increasing schedule matches them on ECG alone (0.279 vs 0.280) and beats them on every other input set.
  • ECG corruption: dropping the ECG after the first 5 hours halves ECG-only κ (0.280 → 0.144). With all signals, κ and accuracy are unchanged to three decimals under every corruption. Flat-line and dropout act on the padded 10-hour window, not on each night's recorded length: dropout removes the ECG after the first 5 hours (the last 3 hours of a typical 8-hour night), and flat-line zeroes a uniformly random 25% of the window's 5-minute blocks (on average 25% of each night).
  • Data fraction: on MESA alone, a model trained only on ECG beats the joint model's ECG-only score at every size (0.642 vs 0.293 at 350 nights). With the paper's probabilities, ECG is the only signal in fewer than 4% of training samples, and almost every MESA night has PPG (all 101 test nights do). So the paper's ECG gains likely come from pooling cohorts such as SHHS, where ECG is the only cardiac signal. One caveat: each model keeps its best validation κ on its own inputs (all signals for the joint model, ECG for the ECG-only one), which favours the ECG-only model on ECG.

Each number is one training run. Two runs of the same setting differed by 0.013 κ.

The paper trains on about 10,000 nights from seven cohorts with batch size 16. We use 350 MESA nights with batch size 2, which is the most that fits a 16 GB GPU at 10 h per night, so absolute κ is lower than the paper's.

Files to Review:

  • pyhealth/models/wav2sleep.py: the model (SignalEncoder, EpochMixer, SequenceMixer, Wav2Sleep)
  • pyhealth/tasks/multi_signal_sleep_staging.py: the task, plus the read_edf_channels and read_nsrr_stages helpers
  • tests/core/test_wav2sleep.py: model tests (shapes, gradients, masking, missing signals, input errors, state-dict round trip, Trainer)
  • tests/core/test_multi_signal_sleep_staging.py: task tests, including one through NSRRSleepDataset(cohort="mesa") and the skip paths for bad files, on tiny synthetic EDF and XML files written to a temporary directory
  • tests/core/test_mesa_sleep_staging_example.py: tests for the example's corrupt, evaluate and with_signal helpers, and for reusing or retraining the saved checkpoint
  • examples/mesa_sleep_staging_wav2sleep.py: the full pipeline and ablations. The corruption experiment reuses the saved model only if it was trained with the same settings, and logs which it did
  • docs/api/models/pyhealth.models.Wav2Sleep.rst, docs/api/tasks/pyhealth.tasks.MultiSignalSleepStaging.rst: new docs pages
  • docs/api/{models,tasks}.rst and pyhealth/{models,tasks}/__init__.py: index and import entries (one entry each)

Testing:

python -m pytest tests/core/test_wav2sleep.py tests/core/test_multi_signal_sleep_staging.py tests/core/test_mesa_sleep_staging_example.py
python examples/mesa_sleep_staging_wav2sleep.py            # synthetic, a few minutes
python examples/mesa_sleep_staging_wav2sleep.py --root /path/to/nsrr/mesa --max-nights 500

All tests use synthetic data. The three test files (50 tests) run in about 20 s on a CPU; the slowest test (the task through NSRRSleepDataset) takes about 2.5 s. No NSRR data is included in this PR. MESA requires an approved NSRR data use agreement.

@github-actions

github-actions Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 89.44% (69268 / 77448 lines)

Modified file Coverage Lines
pyhealth/autoimprove/__init__.py 100.00% 18 / 18
pyhealth/autoimprove/config.py 93.47% 186 / 199
pyhealth/autoimprove/evaluation/__init__.py 100.00% 1 / 1
pyhealth/autoimprove/evaluation/explain.py 92.13% 363 / 394
pyhealth/autoimprove/evaluation/guardrails.py 91.27% 230 / 252
pyhealth/autoimprove/evaluation/holdout.py 98.25% 56 / 57
pyhealth/autoimprove/evaluation/records.py 95.95% 71 / 74
pyhealth/autoimprove/evaluation/report.py 94.86% 664 / 700
pyhealth/autoimprove/evaluation/review.py 93.33% 70 / 75
pyhealth/autoimprove/evaluation/selection.py 91.57% 228 / 249
pyhealth/autoimprove/evaluation/training.py 86.94% 366 / 421
pyhealth/autoimprove/improver.py 92.06% 116 / 126
pyhealth/autoimprove/search/__init__.py 100.00% 1 / 1
pyhealth/autoimprove/search/analysis.py 84.82% 218 / 257
pyhealth/autoimprove/search/features.py 93.79% 589 / 628
pyhealth/autoimprove/search/literature.py 93.54% 536 / 573
pyhealth/autoimprove/search/prompts.py 82.38% 187 / 227
pyhealth/autoimprove/search/proposers.py 87.50% 168 / 192
pyhealth/autoimprove/search/space.py 98.39% 244 / 248
pyhealth/autoimprove/search/turns.py 86.29% 277 / 321
pyhealth/autoimprove/state.py 96.09% 491 / 511
pyhealth/autoimprove/utils/__init__.py 100.00% 1 / 1
pyhealth/autoimprove/utils/data.py 84.71% 72 / 85
pyhealth/autoimprove/utils/llm.py 97.09% 100 / 103
pyhealth/autoimprove/utils/sandbox.py 82.24% 412 / 501
pyhealth/autoimprove/utils/store.py 90.95% 201 / 221
pyhealth/benchmarks/__init__.py 100.00% 4 / 4
pyhealth/benchmarks/robustness.py 85.71% 30 / 35
pyhealth/calib/calibration/hb.py 88.60% 101 / 114
pyhealth/calib/calibration/temperature_scale.py 100.00% 45 / 45
pyhealth/datasets/__init__.py 100.00% 97 / 97
pyhealth/datasets/chestxray14.py 84.26% 91 / 108
pyhealth/datasets/gwas_proxy_sim.py 97.70% 85 / 87
pyhealth/datasets/gwas_simulator.py 96.67% 116 / 120
pyhealth/datasets/ham10000.py 94.48% 137 / 145
pyhealth/datasets/hbn_eeg.py 94.59% 140 / 148
pyhealth/datasets/physionet2012.py 96.64% 115 / 119
pyhealth/datasets/physionet2019.py 89.09% 196 / 220
pyhealth/datasets/risk_progression_sim.py 98.41% 124 / 126
pyhealth/datasets/seer.py 92.19% 59 / 64
pyhealth/graph/cooccurrence.py 100.00% 37 / 37
pyhealth/medcode/__init__.py 100.00% 16 / 16
pyhealth/medcode/codes/ndc.py 72.73% 16 / 22
pyhealth/medcode/omop/__init__.py 100.00% 4 / 4
pyhealth/medcode/omop/condition_hierarchy.py 97.39% 112 / 115
pyhealth/medcode/omop/icd_mapper.py 98.31% 58 / 59
pyhealth/medcode/omop/vocabulary.py 98.10% 103 / 105
pyhealth/medcode/pretrained_embeddings/lm_emb/openai_retriever.py 100.00% 13 / 13
pyhealth/metrics/__init__.py 100.00% 21 / 21
pyhealth/metrics/fairness_selection.py 100.00% 27 / 27
pyhealth/metrics/group_fairness.py 100.00% 97 / 97
pyhealth/metrics/gwas_discovery.py 98.39% 61 / 62
pyhealth/models/__init__.py 100.00% 141 / 141
pyhealth/models/apex_gp.py 95.96% 499 / 520
pyhealth/models/brain_network_transformer.py 98.20% 164 / 167
pyhealth/models/causal_gated_imputer.py 98.75% 79 / 80
pyhealth/models/cehrgpt.py 98.31% 116 / 118
pyhealth/models/deepcoxph.py 96.43% 108 / 112
pyhealth/models/diffmv.py 99.44% 358 / 360
pyhealth/models/dkaft.py 95.37% 371 / 389
pyhealth/models/duett.py 93.52% 101 / 108
pyhealth/models/fedweight.py 98.59% 279 / 283
pyhealth/models/generators/corgan.py 98.77% 241 / 244
pyhealth/models/generators/gpt2.py 86.01% 123 / 143
pyhealth/models/generators/halo.py 92.07% 325 / 353
pyhealth/models/generators/medgan.py 98.95% 189 / 191
pyhealth/models/generators/promptehr.py 88.89% 184 / 207
pyhealth/models/generators/synthea.py 95.96% 261 / 272
pyhealth/models/giantmed.py 96.69% 409 / 423
pyhealth/models/llm_code_transfer.py 94.61% 614 / 649
pyhealth/models/protoecgnet.py 98.18% 377 / 384
pyhealth/models/protoecgnet_h1.py 94.53% 259 / 274
pyhealth/models/protoecgnet_h1_checkpoint.py 87.71% 157 / 179
pyhealth/models/protoecgnet_h1_data.py 88.80% 111 / 125
pyhealth/models/protoecgnet_h1_reference.py 100.00% 153 / 153
pyhealth/models/robust_shy.py 91.67% 22 / 24
pyhealth/models/salientsleepnet.py 99.47% 189 / 190
pyhealth/models/shy.py 94.43% 339 / 359
pyhealth/models/stagenet_mha.py 94.33% 266 / 282
pyhealth/models/stepwise_embedding.py 95.58% 173 / 181
pyhealth/models/surgical_aggregation.py 96.30% 156 / 162
pyhealth/models/survival_mdn.py 94.93% 281 / 296
pyhealth/models/t3a.py 98.11% 104 / 106
pyhealth/models/temporalscl.py 87.63% 248 / 283
pyhealth/models/wav2sleep.py 99.44% 177 / 178
pyhealth/nlp/metrics.py 84.17% 218 / 259
pyhealth/processors/__init__.py 95.92% 47 / 49
pyhealth/processors/band_power_processor.py 98.80% 82 / 83
pyhealth/processors/seer_processor.py 95.40% 83 / 87
pyhealth/processors/vit_embedding_processor.py 89.60% 155 / 173
pyhealth/sampler/__init__.py 100.00% 5 / 5
pyhealth/sampler/group_sampler.py 100.00% 83 / 83
pyhealth/tasks/__init__.py 98.73% 155 / 157
pyhealth/tasks/barttender_chestxray14.py 94.00% 94 / 100
pyhealth/tasks/barttender_encoding.py 100.00% 126 / 126
pyhealth/tasks/barttender_giou.py 100.00% 60 / 60
pyhealth/tasks/cehrgpt_omop.py 97.16% 205 / 211
pyhealth/tasks/diffmv_eicu.py 100.00% 59 / 59
pyhealth/tasks/drug_recommendation.py 94.98% 265 / 279
pyhealth/tasks/fedweight_eicu.py 100.00% 91 / 91
pyhealth/tasks/fedweight_mimic3.py 96.32% 183 / 190
pyhealth/tasks/ham10000_malignancy.py 100.00% 42 / 42
pyhealth/tasks/hbn_psychopathology.py 98.67% 74 / 75
pyhealth/tasks/hbn_response_time.py 100.00% 134 / 134
pyhealth/tasks/in_icu_mortality_emdot_mimic4.py 95.82% 275 / 287
pyhealth/tasks/multi_signal_sleep_staging.py 97.53% 158 / 162
pyhealth/tasks/nutrisight.py 93.75% 15 / 16
pyhealth/tasks/phenotype_imputation.py 100.00% 29 / 29
pyhealth/tasks/physionet2012_stepwise_mortality.py 85.42% 41 / 48
pyhealth/tasks/ptbxl_reduced_lead_rhythm.py 100.00% 23 / 23
pyhealth/tasks/risk_progression_prediction.py 100.00% 70 / 70
pyhealth/tasks/seer_survival.py 96.97% 32 / 33
pyhealth/tasks/sleep_staging.py 93.48% 86 / 92
pyhealth/tasks/sleep_staging_v2.py 98.84% 85 / 86
pyhealth/tasks/temporal_outcome_prediction_mimic4.py 85.81% 248 / 289
pyhealth/tokenizer.py 79.75% 63 / 79

Workflow run · 375f18f

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 30, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: pyhealth/datasets/mesa.py adds a MESA dataset, but master's NSRRSleepDataset already covers MESA (cohort="mesa" in pyhealth/datasets/nsrr_sleep.py). PyHealth keeps one dataset per source.

To make it eligible: drop mesa.py and build your multi-signal task on NSRRSleepDataset. If it lacks something you need, propose that as a small, explained change in its own PR. The wav2sleep model and the task are otherwise new. Then we'll switch the label to status: automatic and request an AI review.

@fujiason fujiason changed the title Add wav2sleep model, MESA dataset and multi-signal sleep staging task Add wav2sleep model and multi-signal sleep staging task Nov 30, 2026
@fujiason

Copy link
Copy Markdown
Contributor Author

Why this PR has status: manual: pyhealth/datasets/mesa.py adds a MESA dataset, but master's NSRRSleepDataset already covers MESA (cohort="mesa" in pyhealth/datasets/nsrr_sleep.py). PyHealth keeps one dataset per source.

To make it eligible: drop mesa.py and build your multi-signal task on NSRRSleepDataset. If it lacks something you need, propose that as a small, explained change in its own PR. The wav2sleep model and the task are otherwise new. Then we'll switch the label to status: automatic and request an AI review.

Thanks, done. mesa.py is gone, along with its config, docs page and index entries, so the PR no longer touches pyhealth/datasets.

MultiSignalSleepStaging now runs on NSRRSleepDataset(cohort="mesa"). The only gap was the label format: NSRRSleepDataset points to the profusion XML, and our reader only handled the NSRR-harmonized XML. I updated read_nsrr_stages to read both, so NSRRSleepDataset didn't need any changes and there's no separate PR.

I also added a test that runs the task through NSRRSleepDataset on synthetic files.

@solarsys solarsys added status: automatic The PR will go through automatic review process. and removed status: manual Pending maintainer's review labels Nov 30, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Good news: the reasons this PR had status: manual are fixed, so it has moved to status: automatic. We've requested an AI review of the latest commit. If it approves, the PR merges; if it asks for changes, push a fix and comment /review yourself (on automatic PRs you can).

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit b9f54d5

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds a Wav2Sleep model, a whole-night multi-signal sleep staging task, and an example with three ablations. The model code looks careful and well tested. Coverage meets the bar: the repository total is 88.39%, wav2sleep.py is 99.42% and multi_signal_sleep_staging.py is 97.96%. The change is close, but the diff and the description don't match yet.

To get this merged:

  1. Missing dataset files. The description lists MESADataset, pyhealth/datasets/mesa.py, configs/mesa.yaml, tests/core/test_mesa.py and docs/api/datasets/pyhealth.datasets.MESADataset.rst. None of them are in the diff. The example and tests use the existing NSRRSleepDataset instead, and tests/core/test_multi_signal_sleep_staging.py is in the diff but isn't listed in the description. Please either add the MESA dataset files with tests, docs and a source link (https://sleepdata.org/datasets/mesa), or update the description, testing commands and file list to match what the diff contains.
  2. Use of NSRRSleepDataset. The example, the task docs and the tests depend on NSRRSleepDataset, including its prepare_metadata method. The description doesn't mention this. Please say in the description that the dependency is intended and why, or make the component self-contained. Both are fine.
  3. Overlap with the existing NSRR task. MultiSignalSleepStaging repeats much of the existing SleepStagingCardioRespiratory (NSRR channel reading, resampling, z-scoring, class mapping). The description mentions #1425 but doesn't explain why this separate task is needed. Please state the difference clearly, for example whole-night samples with native-rate EDF reading, and why it can't be an option of the existing task.
  4. Truncated EDF handling. read_edf_channels raises ValueError on a truncated file, and __call__ doesn't catch it. One bad night would abort set_task. This also contradicts the description's claim that partial downloads work. Please catch the error, log a warning and skip that night, and add a test.

Optional suggestions:

  • The example silently reuses an existing wav2sleep_fixed.pt from --out in the corruption experiment. A log message or a flag would avoid stale results.
  • The example's docstring says "a few minutes" on CPU, while the description says about a minute. Please make them agree.
  • The example helpers (corrupt, evaluate) have no tests. A small test would help.

Reviewed commit b9f54d5

@fujiason

fujiason commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor Author

The description now matches the diff. It lists no dataset files and does list the new tests. It also says the NSRRSleepDataset dependency is intended, and explains why this is a separate task from SleepStagingCardioRespiratory: it makes one sample per whole night with a label per epoch, and it keeps nights with a missing signal instead of skipping them. Adding that as an option would give the existing task two schemas.

A night with a missing, truncated or malformed file is now skipped with a warning, and there's a test for it through call.

I also did the optional ones. The corruption run only reuses a checkpoint trained with the same settings, the runtime says about 2 minutes in both places, and corrupt and evaluate have tests.

@fujiason

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 1c628c3

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this contribution. It adds a Wav2Sleep model and a whole-night MultiSignalSleepStaging task on top of NSRRSleepDataset. It also adds an example with three ablations, docs and tests. The PR is well organised. It explains why the task is separate from SleepStagingCardioRespiratory, and it says clearly how the example uses NSRRSleepDataset. Coverage is above the bar: wav2sleep.py is at 99.4%, multi_signal_sleep_staging.py at 98.0%, and the whole repository at 88.4%.

To get this merged:

  • In examples/mesa_sleep_staging_wav2sleep.py, corrupt(..., "dropout_second_half") zeroes x[:, n_epochs // 2:]. Here n_epochs = x.shape[1] is the padded length of 1200 epochs, not the length of the recorded night. For a night shorter than 10 h, this drops the ECG from epoch 600 onward. That is not the second half of the night (for a night of about 800 epochs it is only the last quarter). So the docstring text "ECG lost, second half", the 0.280 → 0.144 result and the PR description don't match what the code does. Please either compute the midpoint from the scored or recorded epochs of each night (for example from the labels, or from where the padding starts), or reword the experiment and its docs to say "ECG lost from epoch 600 of the padded night". If you change the code, please re-run or re-check the reported numbers. The flat-line corruption is also applied over the padded array. The docs should say whether that is intended.

Optional suggestions:

  • SingleSignalWav2Sleep with use_signals=["ecg"] raises a ValueError on any batch that contains a night with no ECG. This is fine for your 500 MESA nights, but a note or a filter would make the baseline more robust.
  • The checkpoint-reuse logic in corruption_experiment is untested. A small test could cover it.
  • The task docstring describes output_schema slightly differently from the actual ("tensor", {"dtype": torch.long}) tuple.
  • #1688 adds an SHHS multimodal sleep staging task. A one-line statement in the description of how this task differs from it, such as the MESA/NSRR scope and the whole-night samples, would help maintainers.

Reviewed commit 1c628c3

@solarsys

solarsys commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 375f18f

def setUp(self):
self._tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True)
out = Path(self._tmp.name)
self.dataset = TestEvaluate.dataset

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] TestCheckpointReuse depends on another test class's setUpClass

self.dataset = TestEvaluate.dataset only works if TestEvaluate.setUpClass has already run. Selecting this class alone (for example pytest ...::TestCheckpointReuse) or running it under a different order or parallel runner raises AttributeError. Build the small dataset inside this class's setUp, or move the shared dataset construction to a module-level helper that both classes call.

def __init__(
self,
signals: tuple[str, ...] = ("ecg", "ppg", "abd", "thx"),
channels: Mapping[str, str] | None = None,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] channels argument has no test

The description advertises channel names as arguments so the task fits other NSRR cohorts, but no test passes a channels mapping. Every test uses the MESA defaults. Add a test that writes an EDF with renamed channel labels, passes the matching channels mapping, and checks that the signal is read from the renamed channel.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for this contribution, and for the detailed description. It adds a Wav2Sleep model, a whole-night MultiSignalSleepStaging task, docs, tests and an example with three ablations. The model follows the paper's design. The task reads the EDF channels at their native rates, handles missing channels as all-NaN, and skips bad nights with a warning. The description also explains why this is a separate task from SleepStagingCardioRespiratory and SHHSMultimodalSleepStaging.

It looks ready to merge. The diff is complete and matches the description. The links to NSRRSleepDataset, BaseModel, BaseTask and the label processors are either named in the description or are shared base code. Coverage meets the bar:

  • wav2sleep.py: 99.4%
  • multi_signal_sleep_staging.py: 97.5%
  • whole repository: 89.4% (bar is 60%)

Optional suggestions:

  • TestCheckpointReuse in tests/core/test_mesa_sleep_staging_example.py uses TestEvaluate.dataset, which only exists after that class's setUpClass has run. Running it alone would fail. Building its own small dataset in setUp would fix this.
  • The channels override for other NSRR cohorts has no test. A short test with renamed channels would cover it.
  • The module docstring of the example is long. The results tables could move to the docs page, which would keep the script's header short.

Reviewed commit 375f18f

@solarsys
solarsys merged commit a494213 into sunlabuiuc:master Dec 4, 2026
3 checks passed
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.

2 participants