Skip to content

[Standalone Task] Sleep/Wake Detection for DREAMT (SleepWakeDREAMT) - #1743

Open
allen0x2a wants to merge 1 commit into
sunlabuiuc:masterfrom
allen0x2a:dreamt-sleep-wake
Open

allen0x2a wants to merge 1 commit into
sunlabuiuc:masterfrom
allen0x2a:dreamt-sleep-wake

Conversation

@allen0x2a

Copy link
Copy Markdown

Contributors: Andrae Allen, Hita Pullur

Contribution Type: Standalone Task (new task for the existing DREAMTDataset)

Paper: Wang et al., "Addressing Wearable Sleep Tracking Inequity: A New Dataset and Novel Methods for a Population with Sleep Disorders", CHIL 2024 (PMLR 248:380-396). https://proceedings.mlr.press/v248/wang24a.html

Description: Adds SleepWakeDREAMT, an epoch-level sleep/wake detection task for DREAMT (Empatica E4 wristband + PSG, 100 adults from a sleep disorders clinic), reproducing the paper's wake (positive) vs sleep target. For each participant the task reads the 64 Hz recording (only the needed columns), cuts it into 30-second epochs aligned to the PSG scoring grid, and computes mean / SD / min / max per channel. (The recordings don't start on a PSG epoch boundary, and in 3 of 100 the grid shifts once after a gap. Cutting from row 0, 12,816 of 105,960 epochs (12.10%) contained more than one stage label and 5,979 (5.64%) contained both wake and sleep rows. With per-segment alignment, 0 of 105,957 do.) An optional context window concatenates the features of ±k neighbouring epochs, repeating the edge epoch past the ends of the recording. Labels are the most common class (plurality) of each epoch's rows: W → 1; N1/N2/N3/R → 0; epochs where P (preparation) or Missing is most common, or with a tie, are not emitted as targets but still serve as context. Each sample also carries the participant's apnea severity (from the AHI) and obesity flag (BMI ≥ 30 as defined in the paper, −1 if missing), the groups the paper uses as random effects. Features are z-scored with statistics fitted on the training patients (set_task(..., split=PatientSplit(...))). Missing, unreadable, empty or too-short recordings log a warning and yield no samples; stray non-numeric, infinite or out-of-range values are ignored like NaN. The class docstring walks through the steps and defines the feature layout; the task cites DREAMTDataset, so it appears on the dataset's docs page.

Files to Review:

File What to review
pyhealth/tasks/sleep_wake_dreamt.py The task: input/output schema, epoching, features, labels, context window, edge cases
pyhealth/tasks/__init__.py One import line (X as X form)
tests/core/test_sleep_wake_dreamt.py 15 tests on 5 synthetic patients (temp dir, ~0.3 s): sample counts, label mapping, P/Missing dropped, alignment to the PSG grid (including a one-row glitch and a mid-night grid shift), plurality labels and ties, non-finite readings, unlabelled epochs as context, edge padding, feature length, channel subset values, non-numeric values, invalid arguments, group attributes, missing file
docs/api/tasks/pyhealth.tasks.SleepWakeDREAMT.rst API page
docs/api/tasks.rst Toctree entry next to the other sleep tasks
examples/dreamt_sleep_wake_rnn.py 6-run ablation with pyhealth.models.RNN; runs on synthetic data by default

How to test:

pytest tests/core/test_sleep_wake_dreamt.py -v          # 15 tests, synthetic data only
python examples/dreamt_sleep_wake_rnn.py                 # synthetic DREAMT-style data, ~30 s on CPU
python examples/dreamt_sleep_wake_rnn.py --root /path/to/dreamt/2.1.0 --max-patients 20   # quick real-data check
python examples/dreamt_sleep_wake_rnn.py --root /path/to/dreamt/2.1.0 --num-workers 8 --results-md results.md   # the full 100-participant run below

Ablation: context_window k ∈ {0, 2, 5} × channels ∈ {ACC only, all 7 E4 channels}, same patient-level 70/10/20 split, seed and RNN for every run; test-set F1, AUROC and Cohen's κ for the wake class.

Results on DREAMT 2.1.0, all 100 participants (70/9/21 train/val/test patients, 16,223 test epochs, 21.4% of them wake), 5 training epochs, seed 42, --num-workers 8, CPU, about 7 minutes in total. The script checks that all six runs use identical samples.

k channels features F1 AUROC κ
0 ACC only 12 0.390 0.719 0.298
0 all 28 0.432 0.764 0.313
2 ACC only 60 0.507 0.780 0.397
2 all 140 0.517 0.805 0.397
5 ACC only 132 0.511 0.808 0.406
5 all 308 0.529 0.815 0.418
  • Context helps most: going from k=0 to k=5 adds 0.10–0.12 F1 and about 0.1 κ for both channel sets.
  • The AUROC advantage of all seven channels over the accelerometer shrinks as context grows: +0.045 at k=0, +0.025 at k=2, +0.007 at k=5.
  • At k=5 the two channel sets are within 0.02 on every metric. A rerun that changed only 0.2% of the labels (the alignment fix for 3 recordings) reversed two of the three gaps (AUROC and κ), so we read them as a tie, not as evidence that either set is better. The all-channel model also has 2.3× the inputs for the same model size and training budget.
  • RNN sees each flat feature vector as a length-1 sequence, so this measures a classifier on concatenated neighbouring-epoch features, not a GRU learning across epochs. Single split, 21 test participants, no confidence intervals.
  • All runs are below the paper's best (F1 0.823, AUROC 0.926, κ 0.694); see the differences below.

Compute: CPU only, no GPU needed (Intel i9-14900K, 32 threads, 62 GB RAM, Docker). Per run: ~30 s set_task + ~35 s training; all six runs ~7 min. Peak memory 9.5 GB with --num-workers 8 (main process 1.4 GB). A same-seed rerun reproduced every number exactly. Data: DREAMT 2.1.0 from PhysioNet (credentialed access and a signed DUA, ~10 min); the 64 Hz files and participant table are 13 GB and took ~9 h to download at ~0.6 MB/s. The unit tests and the synthetic example need no data download.

Why it is novel: the paper trains every model on all E4 sensors and never compares sensor subsets (its motivation is that existing datasets are accelerometer-only), and its temporal context is fixed (Gaussian smoothing, moving-window variance, LSTM post-processing on/off). It never varies the input window size.

Differences from the paper: simple per-epoch statistics instead of engineered features, an RNN instead of boosted trees with random effects, one patient-level split instead of 5-fold CV, and no exclusion of participants with > 20% artifact epochs (we use all 100; the paper keeps 80). The numbers are not directly comparable to the paper's Table 2.

Future work: participant-level bootstrap confidence intervals for the paired differences, a sequence-shaped (2k+1, features) input so the RNN unrolls over epochs, and a raw-signal model (e.g. PyHealth's ContraWR) on the 64 Hz epochs.

🤖 Generated with Claude Code

Adds an epoch-level sleep/wake detection task for DREAMTDataset,
reproducing the wake vs sleep target of Wang et al., CHIL 2024
(https://proceedings.mlr.press/v248/wang24a.html).

- pyhealth/tasks/sleep_wake_dreamt.py: 30-s epochs aligned to the PSG
  scoring grid, per-channel mean/SD/min/max, plurality wake/sleep
  labels, optional context window, apnea severity and obesity groups.
- tests/core/test_sleep_wake_dreamt.py: 15 tests on 5 synthetic patients.
- docs: API page and tasks index entry.
- examples/dreamt_sleep_wake_rnn.py: 6-run ablation (context window x
  sensor channels) with PyHealth RNN; results on all 100 participants.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Test Coverage

Total: 88.21% (57530 / 65220 lines)

Modified file Coverage Lines
pyhealth/tasks/__init__.py 98.57% 138 / 140
pyhealth/tasks/sleep_wake_dreamt.py 95.73% 157 / 164

Workflow run · 18062aa

@solarsys solarsys added the status: automatic The PR will go through automatic review process. label Nov 30, 2026
@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.

Reviewed commit 18062aa

counts = row.pop("_counts")
# Paired comparison: a recording skipped by one configuration
# (e.g. a missing channel) would change the samples.
if reference is not None and counts != reference:

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

[medium] Pairing check compares counts only, not labels as documented

The module docstring (line 72) says every configuration must produce the same samples "(same counts and labels per split)" and that the script stops if they differ. The PR description says the script checks that all six runs use identical samples. The check here compares only (number of samples, number of wake samples) per split, so labels are never compared. Fix either by comparing the per-sample labels (for example, collecting the label arrays in label_counts and comparing them) or by rewording the docstring and PR description to say that sample and wake counts are compared.

logger = logging.getLogger(__name__)


class SleepWakeDREAMT(BaseTask):

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] Relation to existing SleepStagingDREAMT not explained

PyHealth already has SleepStagingDREAMT (pyhealth/tasks/sleep_staging_dreamt.py) on the same DREAMTDataset, with Wake/NREM/REM epoch labels from a majority vote. This task is not a duplicate: it has a binary target, uses raw channel statistics instead of IBI, adds a context window, and aligns epochs to the PSG grid, while the existing task cuts from row 0. The PR description should say this in a sentence, so the reader knows which task to use for which purpose.

@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: need change
decision: need change

Thank you for this contribution. SleepWakeDREAMT adds an epoch-level wake vs. sleep task for DREAMTDataset. It aligns epochs to the PSG scoring grid and offers an optional context window, channel selection, and apnea and obesity group attributes. The task is well documented, and the tests and ablation example are thorough. Coverage is 95.7% for sleep_wake_dreamt.py and 88.2% for the whole repository, so both meet the bar. You're close.

To get this merged:

  • In examples/dreamt_sleep_wake_rnn.py, the paired-run check in main() compares only each split's sample count and wake count ((n, n_wake)). The module docstring says "same counts and labels per split", and the PR description says the script "checks that all six runs use identical samples". Two runs could have the same counts and still differ in which epochs are included. Please either change the check to compare the actual (patient_id, epoch_index, label) sets, or reword the docstring and PR description to say it checks sample and wake counts per split.

Optional suggestions:

  • Briefly mention SleepStagingDREAMT in the task docstring or PR description, and say how this binary, feature-based task differs from it.
  • The example is about 500 lines. You could trim the synthetic-data generator or the long docstring if you want it shorter.

Reviewed commit 18062aa

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.

2 participants