diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst index 2a1db44afe..5976a5610a 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -485,6 +485,11 @@ PyHealth does not ship any data: you download each dataset from its source and p - `ISRUC `__ - No - — + * - :doc:`Sleep-Accel ` + - Open + - `PhysioNet `__ + - No + - — * - :doc:`EESM23 (ear-EEG) ` - Open - `OpenNeuro `__ @@ -670,6 +675,7 @@ Available Datasets datasets/pyhealth.datasets.DREAMTDataset datasets/pyhealth.datasets.SHHSDataset datasets/pyhealth.datasets.SleepEDFDataset + datasets/pyhealth.datasets.SleepAccelDataset datasets/pyhealth.datasets.NSRRSleepDataset datasets/pyhealth.datasets.EHRShotDataset datasets/pyhealth.datasets.Support2Dataset diff --git a/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst b/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst new file mode 100644 index 0000000000..b8155d5ed9 --- /dev/null +++ b/docs/api/datasets/pyhealth.datasets.SleepAccelDataset.rst @@ -0,0 +1,17 @@ +pyhealth.datasets.SleepAccelDataset +=================================== + +PhysioNet Sleep-Accel contains wrist heart rate, acceleration, step counts and +30 s sleep-stage labels from a night of polysomnography. The PyHealth loader +writes ``sleep_accel-pyhealth.csv`` with absolute paths for each complete +subject and exposes the four modalities as one event per recording. + +Because the dataset has no raw PPG or ECG waveform, IBI staging derives +``60 / bpm`` samples from the heart-rate stream. Use +:class:`~pyhealth.tasks.SleepStagingIBISleepAccel` to build the shared +``(T, 750)`` IBI tensors and three-class labels. + +.. autoclass:: pyhealth.datasets.SleepAccelDataset + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/models.rst b/docs/api/models.rst index 64f0694c24..c2a219e66b 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -48,6 +48,9 @@ routes each feature type automatically. * - :doc:`models/pyhealth.models.UNet` - Your task is pixel/voxel-level segmentation with an image and a mask - ``UNet2D``/``UNet3D``; pair with ``PatchDataset``, ``PatchSampler`` and Dice/IoU metrics + * - :doc:`models/pyhealth.models.WatchSleepNet` + - You have whole-night IBI sequences and want one sleep-stage label per 30 s epoch + - CNN + TCN + BiLSTM + attention; masks padded and unknown epochs from loss/metrics * - :doc:`models/pyhealth.models.GNN` - Features include graph-structured data - Works with ``GraphProcessor``; see :doc:`graph` for setup @@ -328,6 +331,7 @@ API Reference models/pyhealth.models.CLIPStress models/pyhealth.models.EEGNet models/pyhealth.models.DeepSleepNet + models/pyhealth.models.WatchSleepNet models/pyhealth.models.SleepKD models/pyhealth.models.SparcNet models/pyhealth.models.StageNet diff --git a/docs/api/models/pyhealth.models.WatchSleepNet.rst b/docs/api/models/pyhealth.models.WatchSleepNet.rst new file mode 100644 index 0000000000..ff20dbd4fc --- /dev/null +++ b/docs/api/models/pyhealth.models.WatchSleepNet.rst @@ -0,0 +1,19 @@ +pyhealth.models.WatchSleepNet +=================================== + +WatchSleepNet, a CNN + TCN + BiLSTM + attention model that stages every 30 s epoch of an IBI sequence. + +This module is a PyHealth implementation of the original WatchSleepNet paper: + +Wang, W.K., Chen, B., Yang, J., Jeong, H., Hershkovich, L., Islam, S.M.M., +Liu, M., Roghanizad, A.R., Shandhi, M.M.H., Spector, A.R. & Dunn, J. (2025). +`WatchSleepNet: A Novel Model and Pretraining Approach for Advancing Sleep +Staging with Smartwatches +`_. Proceedings of the sixth +Conference on Health, Inference, and Learning (CHIL 2025), Proceedings of +Machine Learning Research 287:145-165. + +.. autoclass:: pyhealth.models.WatchSleepNet + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index b81e204464..6ba465fe3a 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -268,6 +268,11 @@ Available Tasks Sleep Staging (SleepEDF) Sleep-EDF Forecasting Sleep Staging (Cardio-Respiratory, NSRR) + IBI Sleep Staging (DREAMT) + IBI Sleep Staging (NSRR SHHS) + IBI Sleep Staging (NSRR MESA) + IBI Sleep Staging (ISRUC) + IBI Sleep Staging (Sleep-Accel) Sleep Staging Sequences (SleepEDF) Sleep Staging (ISRUC) Sleep Staging Sequences (ISRUC) diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst new file mode 100644 index 0000000000..b705c79196 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIDREAMT.rst @@ -0,0 +1,11 @@ +pyhealth.tasks.SleepStagingIBIDREAMT +===================================== + +Per-recording inter-beat-interval sleep staging for DREAMT. Reads the +``data_100Hz`` BVP signal by default, recovers the 30 s epoch grid from stage +changes, and emits ``(T, 750)`` IBI tensors with three-class labels. + +.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIDREAMT + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst new file mode 100644 index 0000000000..e8f4bdbdec --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIISRUC.rst @@ -0,0 +1,13 @@ +pyhealth.tasks.SleepStagingIBIISRUC +=================================== + +ECG-derived inter-beat-interval sleep staging for ISRUC-Sleep. By default the +task reads the ``X2`` ECG channel at its native 200 Hz rate, strides the IBI +signal by eight, and emits ``(T, 750)`` tensors with three-class labels. Choose +``scorer="expert2"`` to use the second expert's hypnogram instead of the +first. + +.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIISRUC + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst new file mode 100644 index 0000000000..1e697aeec2 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBIMESA.rst @@ -0,0 +1,11 @@ +pyhealth.tasks.SleepStagingIBIMESA +=================================== + +Per-recording inter-beat-interval sleep staging for NSRR MESA. Resamples the +Pleth channel from 256 Hz to 100 Hz, strides IBI by four, and emits +``(T, 750)`` tensors with three-class labels. + +.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBIMESA + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst new file mode 100644 index 0000000000..d935b17131 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISHHS.rst @@ -0,0 +1,11 @@ +pyhealth.tasks.SleepStagingIBISHHS +=================================== + +Per-recording inter-beat-interval sleep staging for NSRR SHHS. Reads the ECG +channel at 125 Hz, strides IBI by five, and emits ``(T, 750)`` tensors with +three-class labels. + +.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISHHS + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst new file mode 100644 index 0000000000..134a8f63ff --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.SleepStagingIBISleepAccel.rst @@ -0,0 +1,12 @@ +pyhealth.tasks.SleepStagingIBISleepAccel +======================================== + +Heart-rate-derived inter-beat-interval sleep staging for Sleep-Accel. The task +interpolates ``60 / bpm`` onto a 25 Hz grid and emits ``(T, 750)`` tensors with +three-class labels. It maps R&K stages to Wake ``0``, NREM ``1``, REM ``2`` and +unknown ``-1``, and caps each recording at 1100 epochs by default. + +.. autoclass:: pyhealth.tasks.sleep_staging_ibi.SleepStagingIBISleepAccel + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/watchsleepnet/readme.md b/examples/watchsleepnet/readme.md new file mode 100644 index 0000000000..ade3571e9e --- /dev/null +++ b/examples/watchsleepnet/readme.md @@ -0,0 +1,135 @@ +# WatchSleepNet Examples + +WatchSleepNet is a sleep-stage classification algorithm that uses inter-beat interval (IBI) signals derived from polysomnography (PSG) data (ECG, PPG, heart rate). The original paper utilized a two-stage pre-training process, where the model was pre-trained on a large corpus of high quality PSG data like the Sleep Heart Health Study (SHHS) and the Multi-Ethnic Study of Atherosclerosis (MESA) and then fine-tuned on a smaller set of data collected from wearable devices like the Dataset for Real-time sleep stage EstimAtion using Multisensor wearable Technology (DREAMT). + +These examples run an end-to-end pipeline for processing datasets to extract IBI from signals, pre-training a model, fine-tuning, and then performing evaluation of a trained model. + +Run the commands from the PyHealth repository root with the environment where PyHealth is installed. + +## Synthetic Data Generation + +If you do not have access to the restricted datasets (SHHS, MESA, DREAMT), the synthetic data generator script can be used to generate datasets for testing. Run the command and pass in the desired dataset to generate (`dreamt`, `mesa`, `shhs`), the number of samples, and the output folder path. + +```bash +python examples/watchsleepnet/watchsleepnet_synthetic_data.py \ + --dataset shhs --num-samples 5 --output-dir synthetic/shhs +``` + +The script will create a folder with the same structure and simulated PSG files as the target dataset. Since the PSG files are randomly generated, they will likely result in poor model training results compared to real data but they can be used to validate the pipeline works. + +Generate enough samples for a 60/20/20 train/test/validate split. Each recording defaults to 20 epochs of 30 seconds; use `--epochs` to change this, `--seed` for deterministic output, and `--overwrite` to replace a non-empty output directory. If `--output-dir` is omitted, the dataset is written to `synthetic_data/`. + +## Training Model + +To train the model, specify paths to the SHHS and MESA dataset, output path, and number of epochs. + +The script will perform data transformation to IBI and train the model on the extracted IBI. `--loss` accepts `ce` (default), `weighted_ce`, `focal`, or `inverse_focal`. + +```bash +python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \ + --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \ + --output-dir output/watchsleepnet-pretrain +``` + +The output directory contains `pretrained.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable PyHealth cache under `cache/shhs` and `cache/mesa`. + +### Ablations + +Use `--quantization` to train with `fp32` (default), `bf16`, or `fp16` compute: + +```bash +python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \ + --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \ + --output-dir output/watchsleepnet-pretrain-bf16 --quantization bf16 +``` + +Architecture flags override the defaults for one run. For example, to disable the TCN and self-attention and shrink the model: + +```bash +python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \ + --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \ + --output-dir output/watchsleepnet-no-tcn-attn \ + --use-tcn false --use-attention false \ + --hidden-dim 128 --num-heads 8 --num-layers 2 --tcn-layers 1 +``` + +## Fine Tuning Model + +After a model is trained, a `pretrained.pt` model checkpoint will be saved in the output folder. This checkpoint is used for reloading the model for further training or evaluation. + +To fine tune the model, specify the checkpoint model path, the dataset, path to the fine tune dataset, number of epochs to fine tune, and the output folder for the trained model. `--loss` and the architecture flags from the pretraining section can also be overridden here. + +```bash +python examples/watchsleepnet/watchsleepnet_finetune.py --dataset dreamt \ + --root /path/to/dreamt \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --epochs 5 --output-dir output/watchsleepnet-finetune +``` + +The output directory contains `finetuned.pt`, `training_history.csv`, `results.csv`, `results.json`, and a reusable cache under `cache`. + +## Quantizing Model + +A model trained at full precision `fp32` can be quantized to a lower precision `bf16` or `fp16`. + +```bash +python examples/watchsleepnet/watchsleepnet_quantize.py \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --output output/watchsleepnet-pretrain/pretrained_bf16.pt \ + --quantization bf16 +``` + +The quantized model will be saved to a separate `.pt` file that can be loaded for further fine tuning or evaluation. A `quantization.json` report (or the path passed to `--report`) records the resulting tensor dtype counts. + +## Evaluating Performance + +To evaluate a trained model checkpoint, specify the dataset, path to the dataset, the trained model checkpoint, and the output folder. + +To avoid reprocessing the dataset, pass `--cache-dir` pointing to the PyHealth cache generated during training or fine tuning. + +```bash +python examples/watchsleepnet/watchsleepnet_evaluate.py \ + --checkpoint output/watchsleepnet-finetune/finetuned.pt \ + --dataset dreamt --root /path/to/dreamt \ + --cache-dir output/watchsleepnet-finetune/cache \ + --output-dir output/watchsleepnet-evaluate +``` + +Evaluation reuses the task settings stored in the checkpoint (`points_per_epoch`, `max_epochs`, `signal_source`, and `scorer`); the matching CLI flags override them. The output folder saves `results.csv`, `results.json`, and `confusion_matrix.png` with overall metrics (Accuracy, macro/weighted F1, AUROC, Cohen's Kappa) and per-class Wake/NREM/REM F1. + +All real-data training and evaluation scripts accept `--peak-backend`; it defaults to `scipy` so IBI extraction is reproducible. Pass `--peak-backend auto`, `neurokit`, or `biosppy` to opt into the reference detectors, which require optional packages that PyHealth does not install. + +## Additional Datasets + +Two additional datasets that were not used by the original model were implemented: Sleep-Accel and ISRUC. For ISRUC, IBI signals are extracted from the ECG channel; for Sleep-Accel, they are extracted from heart rate. + +For ISRUC, point `--root` at one extracted subgroup folder. Each subject folder contains `/.rec` plus the expert hypnograms `_1.txt` and `_2.txt`. The ECG channel may be named (`X2`, `ECG`, `EKG`, etc.) or, in some exports, numerically labelled; in the latter case the EDF transducer field (`EKG_Channel`) is used to locate it. Use `--scorer expert1` (default) or `expert2`. + +```bash +python examples/watchsleepnet/watchsleepnet_finetune.py --dataset isruc \ + --root /path/to/ISRUC-Sleep-I \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --epochs 10 --output-dir output/watchsleepnet-finetune-isruc +``` + +For Sleep-Accel, point `--root` at a directory containing `heart_rate/`, `labels/`, `motion/`, and `steps/` subdirectories. + +```bash +python examples/watchsleepnet/watchsleepnet_finetune.py --dataset sleep_accel \ + --root /path/to/sleep-accel \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --epochs 10 --output-dir output/watchsleepnet-finetune-sleep-accel +``` + +To evaluate a trained model on either dataset, use the same `--dataset` and `--root` pattern (plus `--cache-dir` to reuse the training cache). + +```bash +python examples/watchsleepnet/watchsleepnet_evaluate.py \ + --checkpoint output/watchsleepnet-finetune-sleep-accel/finetuned.pt \ + --dataset sleep_accel --root /path/to/sleep-accel \ + --cache-dir output/watchsleepnet-finetune-sleep-accel/cache \ + --output-dir output/watchsleepnet-evaluate-sleep-accel +``` + +`sleep-accel` is not a valid dataset name; use `sleep_accel`. + diff --git a/examples/watchsleepnet/watchsleepnet_common.py b/examples/watchsleepnet/watchsleepnet_common.py new file mode 100644 index 0000000000..12d48720c3 --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_common.py @@ -0,0 +1,889 @@ +"""Shared helpers for the WatchSleepNet real-data examples. + +Every training example requires an explicit root to a real dataset directory; +there is no synthetic-data fallback. The same functions build datasets, tasks, +models, checkpoints, and report tables for DREAMT, SHHS, MESA, ISRUC and +Sleep-Accel cohorts. + +Examples: + >>> from watchsleepnet_common import CLASS_NAMES, LOSS_MODES + >>> from watchsleepnet_common import QUANTIZATION_MODES + >>> CLASS_NAMES + ('Wake', 'NREM', 'REM') + >>> QUANTIZATION_MODES + ('fp32', 'bf16', 'fp16') + >>> LOSS_MODES + ('ce', 'weighted_ce', 'focal', 'inverse_focal') +""" + +from __future__ import annotations + +import argparse +import json +import os +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any + +import numpy as np +import pandas as pd +import torch +from scipy.signal import resample +from sklearn.metrics import accuracy_score, f1_score + +from pyhealth.datasets import ( + DREAMTDataset, + ISRUCDataset, + NSRRSleepDataset, + SleepAccelDataset, + create_sample_dataset, + get_dataloader, + split_by_patient, +) +from pyhealth.models import WatchSleepNet +from pyhealth.tasks import ( + SleepStagingIBIDREAMT, + SleepStagingIBIISRUC, + SleepStagingIBIMESA, + SleepStagingIBISHHS, + SleepStagingIBISleepAccel, +) +from pyhealth.trainer import Trainer + +CLASS_NAMES = ("Wake", "NREM", "REM") +QUANTIZATION_MODES = ("fp32", "bf16", "fp16") +LOSS_MODES = ("ce", "weighted_ce", "focal", "inverse_focal") +PEAK_BACKENDS = ("scipy", "auto", "neurokit", "biosppy") +DEFAULT_PEAK_BACKEND = "scipy" +QUANTIZATION_DTYPES = { + "fp32": torch.float32, + "bf16": torch.bfloat16, + "fp16": torch.float16, +} +DEFAULT_MODEL_KWARGS = { + "num_channels": 256, + "kernel_size": 5, + "hidden_dim": 256, + "num_heads": 16, + "num_layers": 4, + "tcn_layers": 3, +} +TRAINER_METRICS = ["accuracy", "f1_macro", "cohen_kappa"] +CHECKPOINT_FORMAT = "watchsleepnet-pyhealth-v1" + + +def existing_dir(value: str) -> Path: + """Returns an existing directory supplied on the command line. + + Args: + value: User-supplied dataset path. + + Returns: + The expanded path. + + Raises: + argparse.ArgumentTypeError: If the path is not an existing directory. + + Examples: + >>> existing_dir(".").is_dir() + True + """ + path = Path(value).expanduser() + if not path.is_dir(): + raise argparse.ArgumentTypeError( + f"{value!r} does not point to an existing dataset directory" + ) + return path + + +def add_peak_backend_arg( + parser: argparse.ArgumentParser, +) -> argparse.ArgumentParser: + """Adds the shared IBI peak-detector flag to an example CLI. + + Args: + parser: Parser to extend. + + Returns: + The same parser. + + Examples: + >>> args = add_peak_backend_arg(argparse.ArgumentParser()).parse_args([]) + >>> args.peak_backend + 'scipy' + """ + parser.add_argument( + "--peak-backend", + choices=PEAK_BACKENDS, + default=DEFAULT_PEAK_BACKEND, + help="IBI beat detector; the others require optional packages", + ) + return parser + + +def build_dataset( + name: str, + root: str | os.PathLike[str], + cohort: str | None = None, + cache_dir: str | None = None, +) -> Any: + """Builds a PyHealth dataset for one of the supported IBI sources. + + Args: + name: ``"dreamt"``, ``"shhs"``, ``"mesa"``, ``"isruc"`` or + ``"sleep_accel"``. + root: Dataset directory. + cohort: NSRR cohort; defaults to ``name``. + cache_dir: Optional writable cache for PyHealth metadata. + + Returns: + A fitted PyHealth dataset. + + Raises: + ValueError: For an unknown name. + + Examples: + >>> build_dataset("dreamt", "unused-root") if False else "ready" + 'ready' + """ + if name == "dreamt": + return DREAMTDataset(root=str(root)) + if name in ("shhs", "mesa"): + return NSRRSleepDataset( + root=str(root), + cohort=cohort or name, + cache_dir=cache_dir, + ) + if name == "isruc": + return ISRUCDataset(root=str(root), cache_dir=cache_dir) + if name == "sleep_accel": + return SleepAccelDataset(root=str(root), cache_dir=cache_dir) + raise ValueError(f"unknown dataset {name!r}") + + +def build_task( + name: str, + points_per_epoch: int = 750, + max_epochs: int = 1100, + signal_source: str = "psg_100hz", + signal_channel: str | None = None, + peak_backend: str = "scipy", + scorer: str = "expert1", +) -> Any: + """Builds the three-class IBI task for a dataset. + + Args: + name: ``"dreamt"``, ``"shhs"``, ``"mesa"``, ``"isruc"`` or + ``"sleep_accel"``. + points_per_epoch: IBI samples per 30 s epoch. + max_epochs: Maximum epochs per recording. + signal_source: ``"psg_100hz"`` or ``"wearable_64hz"`` for DREAMT. + signal_channel: Waveform column or EDF channel. + peak_backend: Beat detector. Defaults to ``"scipy"`` so samples + do not depend on optional packages. ``"auto"`` is an opt-in that + prefers the installed biosppy/neurokit backends with a scipy + fallback. + scorer: ``"expert1"`` or ``"expert2"`` hypnogram for ISRUC. + + Returns: + A task whose samples use the shared signal/lengths/label contract. + + Raises: + ValueError: For an unknown name. + + Examples: + >>> build_task("dreamt", points_per_epoch=375).points_per_epoch + 375 + >>> build_task("isruc", scorer="expert2").scorer + 'expert2' + """ + if name == "dreamt": + return SleepStagingIBIDREAMT( + signal_source=signal_source, + signal_channel=signal_channel or "BVP", + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + peak_backend=peak_backend, + ) + if name == "shhs": + return SleepStagingIBISHHS( + signal_channel=signal_channel or "ECG", + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + peak_backend=peak_backend, + ) + if name == "mesa": + return SleepStagingIBIMESA( + signal_channel=signal_channel or "Pleth", + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + peak_backend=peak_backend, + ) + if name == "isruc": + return SleepStagingIBIISRUC( + scorer=scorer, + channel=signal_channel, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + peak_backend=peak_backend, + ) + if name == "sleep_accel": + return SleepStagingIBISleepAccel( + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + ) + raise ValueError(f"unknown dataset {name!r}") + + +def build_samples(dataset: Any, task: Any, num_workers: int = 1) -> Any: + """Applies a task to a base dataset with a bounded worker count. + + Args: + dataset: A fitted PyHealth dataset. + task: A task from :func:`build_task`. + num_workers: Number of PyHealth task workers. One avoids spawning a + process pool in CI and gives deterministic sample order. + + Returns: + A PyHealth ``SampleDataset`` with the shared IBI contract. + + Examples: + >>> build_samples(None, None) if False else "ready" + 'ready' + """ + return dataset.set_task(task, num_workers=num_workers) + + +def _rebuild(samples: list[dict[str, Any]], source: Any, name: str = "") -> Any: + return create_sample_dataset( + samples=samples, + input_schema=dict(source.input_schema), + output_schema=dict(source.output_schema), + dataset_name=name or getattr(source, "dataset_name", ""), + task_name=getattr(source, "task_name", ""), + ) + + +def pool_datasets(datasets: Sequence[Any]) -> Any: + """Pools sample datasets into one ``SampleDataset``. + + Patient IDs are prefixed with the source index when more than one dataset + is pooled, so SHHS and MESA IDs cannot collide. + + Args: + datasets: Sample datasets with identical schemas. + + Returns: + A single in-memory sample dataset. + + Examples: + >>> import numpy as np, torch + >>> from pyhealth.datasets import create_sample_dataset + >>> def ds(pid): + ... return create_sample_dataset( + ... [{"patient_id": pid, "signal": np.zeros((1, 750), "float32"), + ... "label": np.array([0]), "lengths": 1}], + ... {"signal": "tensor", "lengths": "raw"}, + ... {"label": ("tensor", {"dtype": torch.long})}) + >>> len(pool_datasets([ds("p1"), ds("p2")])) + 2 + """ + samples: list[dict[str, Any]] = [] + for index, dataset in enumerate(datasets): + for sample in dataset: + item = dict(sample) + if len(datasets) > 1: + item["patient_id"] = f"d{index}-{item['patient_id']}" + samples.append(item) + return _rebuild(samples, datasets[0], "pooled") + + +def resample_dataset(dataset: Any, points: int = 750) -> Any: + """Resamples each IBI row to ``points`` without changing labels or schema. + + This is used for the ``points_per_epoch`` ablation: the task computes IBI + at a lower rate, then every epoch row is brought back to the 750 samples + the model requires so only the information bandwidth changes. + + Args: + dataset: A sample dataset with ``(T, S)`` signal tensors. + points: Target width for each epoch row. + + Returns: + A rebuilt sample dataset. + + Examples: + >>> import numpy as np, torch + >>> from pyhealth.datasets import create_sample_dataset + >>> ds = create_sample_dataset( + ... [{"patient_id": "p1", "signal": np.zeros((2, 375), "float32"), + ... "label": np.array([0, 1]), "lengths": 2}], + ... {"signal": "tensor", "lengths": "raw"}, + ... {"label": ("tensor", {"dtype": torch.long})}) + >>> tuple(resample_dataset(ds, 750)[0]["signal"].shape) + (2, 750) + """ + samples = [] + for sample in dataset: + item = dict(sample) + signal = np.asarray(item["signal"]) + item["signal"] = resample(signal, points, axis=-1).astype(np.float32) + samples.append(item) + return _rebuild(samples, dataset, "resampled") + + +def split_dataset(dataset: Any, seed: int = 0) -> tuple[Any, Any, Any]: + """Splits a sample dataset by patient into 60/20/20 parts. + + Args: + dataset: A sample dataset with at least three patients. + seed: Seed used by :func:`pyhealth.datasets.split_by_patient`. + + Returns: + Train, validation, and test sample datasets. + + Raises: + ValueError: If any split is empty. + + Examples: + >>> import numpy as np, torch + >>> from pyhealth.datasets import create_sample_dataset + >>> samples = [ + ... {"patient_id": f"p{i}", "signal": np.zeros((1, 750), "float32"), + ... "label": np.array([0]), "lengths": 1} for i in range(5)] + >>> parts = split_dataset(create_sample_dataset( + ... samples, {"signal": "tensor", "lengths": "raw"}, + ... {"label": ("tensor", {"dtype": torch.long})})) + >>> [len(part) for part in parts] + [3, 1, 1] + """ + parts = split_by_patient(dataset, [0.6, 0.2, 0.2], seed=seed) + if any(len(part) == 0 for part in parts): + raise ValueError( + "patient split produced an empty part; use at least three patients " + "with 5 or more for a stable 60/20/20 split" + ) + return parts + + +def build_model( + dataset: Any, + seed: int = 0, + model_kwargs: Mapping[str, Any] | None = None, + quantization: str = "fp32", + loss: str = "ce", +) -> WatchSleepNet: + """Builds a WatchSleepNet with a fixed seed for reproducible ablations. + + Args: + dataset: The fitted sample dataset. + seed: Seed applied to PyTorch before model construction. + model_kwargs: Overrides of :data:`DEFAULT_MODEL_KWARGS`. + quantization: One of :data:`QUANTIZATION_MODES`. + loss: One of :data:`LOSS_MODES`; ``"ce"`` is the reference default. + + Returns: + An untrained model with a three-class classifier. + + Examples: + >>> import numpy as np, torch + >>> from pyhealth.datasets import create_sample_dataset + >>> ds = create_sample_dataset( + ... [{"patient_id": "p1", "signal": np.zeros((1, 750), "float32"), + ... "label": np.array([0]), "lengths": 1}], + ... {"signal": "tensor", "lengths": "raw"}, + ... {"label": ("tensor", {"dtype": torch.long})}) + >>> build_model(ds).n_classes + 3 + """ + params = dict(DEFAULT_MODEL_KWARGS) + params.update(model_kwargs or {}) + torch.manual_seed(seed) + return WatchSleepNet( + dataset=dataset, + n_classes=len(CLASS_NAMES), + quantization=quantization, + loss=loss, + **params, + ) + + +def get_loaders( + parts: Sequence[Any], batch_size: int = 16, seed: int = 0 +) -> list[Any]: + """Creates train/validation/test loaders with a deterministic shuffle. + + Args: + parts: Train, validation, and test sample datasets. + batch_size: Batch size for all loaders. + seed: Shuffle seed, applied only to the training loader. + + Returns: + A list of three data loaders. + + Examples: + >>> import numpy as np, torch + >>> from pyhealth.datasets import create_sample_dataset + >>> samples = [ + ... {"patient_id": f"p{i}", "signal": np.zeros((1, 750), "float32"), + ... "label": np.array([0]), "lengths": 1} for i in range(5)] + >>> ds = create_sample_dataset( + ... samples, {"signal": "tensor", "lengths": "raw"}, + ... {"label": ("tensor", {"dtype": torch.long})}) + >>> [len(loader.dataset) for loader in get_loaders(split_dataset(ds))] + [3, 1, 1] + """ + return [ + get_dataloader(part, batch_size=batch_size, shuffle=(i == 0), seed=seed) + for i, part in enumerate(parts) + ] + + +def fit( + model: WatchSleepNet, + loaders: Sequence[Any], + epochs: int = 5, + lr: float = 5e-5, + weight_decay: float = 1e-4, + device: str | None = None, + quantization: str = "fp32", +) -> tuple[Trainer, list[dict[str, float]]]: + """Trains with ``Trainer.train`` and records one validation row per epoch. + + Args: + model: The model to train in place. + loaders: Train and validation data loaders. + epochs: Number of training epochs. + lr: Adam learning rate. + weight_decay: Adam weight decay. + device: Torch device; ``None`` lets Trainer choose it. + quantization: Used to raise Adam's epsilon for fp16 stability. + + Returns: + The trainer and a list of per-epoch validation score dicts. + + Examples: + >>> fit(model=None, loaders=[]) if False else "ready" + 'ready' + """ + trainer = Trainer(model=model, metrics=TRAINER_METRICS, enable_logging=False, + device=device) + optimizer_params: dict[str, float] = {"lr": lr} + if quantization == "fp16": + optimizer_params["eps"] = 1e-4 + history: list[dict[str, float]] = [] + for epoch in range(int(epochs)): + trainer.train( + train_dataloader=loaders[0], + val_dataloader=loaders[1] if len(loaders) > 1 else None, + epochs=1, + optimizer_params=optimizer_params, + weight_decay=weight_decay, + monitor="accuracy" if len(loaders) > 1 else None, + ) + scores = trainer.evaluate(loaders[1]) if len(loaders) > 1 else {} + history.append({"epoch": epoch + 1, **{k: float(v) for k, v in scores.items()}}) + return trainer, history + + +def predict( + model: WatchSleepNet, + loader: Any, + device: str | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Collects flattened true labels and class probabilities from a loader. + + Args: + model: A trained model. + loader: Data loader for the evaluation split. + device: Torch device; ``None`` uses the model's parameter device. + + Returns: + ``(y_true, y_prob)`` arrays over valid, non-padded epochs. + + Examples: + >>> predict(model=None, loader=None) if False else "ready" + 'ready' + """ + target = device or str(model.device) + model.eval() + true_parts, prob_parts = [], [] + with torch.no_grad(): + for batch in loader: + batch = {k: v.to(target) if isinstance(v, torch.Tensor) else v + for k, v in batch.items()} + output = model(**batch) + true_parts.append(output["y_true"].detach().cpu().numpy()) + prob_parts.append(output["y_prob"].detach().cpu().numpy()) + if not true_parts: + return np.empty(0, dtype=np.int64), np.empty((0, len(CLASS_NAMES))) + return np.concatenate(true_parts), np.concatenate(prob_parts) + + +def summarize_predictions( + y_true: np.ndarray, y_prob: np.ndarray +) -> dict[str, float]: + """Computes accuracy, per-class F1, and predicted-class distribution. + + Args: + y_true: Flattened integer labels in ``0..2``. + y_prob: Class probabilities with shape ``(n, 3)``. + + Returns: + A flat dictionary of scalar metrics. Per-class F1 values expose + NREM-majority collapse even when accuracy looks reasonable. + + Examples: + >>> import numpy as np + >>> row = summarize_predictions(np.array([0, 1]), np.eye(3)[:2]) + >>> row["accuracy"], row["f1_rem"] + (1.0, 0.0) + """ + y_true = np.asarray(y_true, dtype=np.int64) + y_prob = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES)) + labels = list(range(len(CLASS_NAMES))) + y_pred = y_prob.argmax(axis=1) if y_prob.size else np.empty(0, dtype=np.int64) + f1 = f1_score(y_true, y_pred, labels=labels, average=None, zero_division=0) + counts = np.bincount(y_pred, minlength=len(CLASS_NAMES)).astype(float) + distribution = counts / max(len(y_pred), 1) + result = { + "accuracy": float(accuracy_score(y_true, y_pred)) if y_true.size else 0.0, + "f1_macro": float(np.mean(f1)), + "n_epochs": int(y_true.size), + } + for name, value in zip(CLASS_NAMES, f1, strict=True): + result[f"f1_{name.lower()}"] = float(value) + for name, value in zip(CLASS_NAMES, distribution, strict=True): + result[f"pred_{name.lower()}"] = float(value) + return result + + +def save_checkpoint( + path: str | os.PathLike[str], + model: WatchSleepNet, + config: Mapping[str, Any], + metrics: Mapping[str, Any] | None = None, +) -> Path: + """Saves a self-describing checkpoint with a bare state dict inside. + + Args: + path: Output ``.pt`` path. + model: Model whose state dict is saved. + config: Dataset, task, model, and training configuration. + metrics: Optional final evaluation metrics. + + Returns: + The output path. + + Examples: + >>> save_checkpoint("unused.pt", None, {}) if False else "ready" + 'ready' + """ + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + torch.save( + { + "format": CHECKPOINT_FORMAT, + "state_dict": {k: v.detach().cpu() for k, v in model.state_dict().items()}, + "config": dict(config), + "metrics": dict(metrics or {}), + }, + path, + ) + return path + + +def load_checkpoint( + path: str | os.PathLike[str], +) -> tuple[dict[str, torch.Tensor], dict[str, Any]]: + """Loads either a self-describing bundle or a bare ``.pt`` state dict. + + Args: + path: Checkpoint path produced by this helper or ``Trainer.save_ckpt``. + + Returns: + The state dict and any bundled metadata (empty for bare checkpoints). + + Examples: + >>> load_checkpoint("unused.pt") if False else "ready" + 'ready' + """ + payload = torch.load(path, map_location="cpu", weights_only=True) + if isinstance(payload, Mapping) and "state_dict" in payload: + state = dict(payload["state_dict"]) + metadata = {k: v for k, v in payload.items() if k != "state_dict"} + else: + state = dict(payload) + metadata = {} + cleaned = {} + for key, value in state.items(): + name = key + for prefix in ("module.", "model."): + name = name.removeprefix(prefix) + cleaned[name] = value + return cleaned, metadata + + +def build_model_from_checkpoint( + path: str | os.PathLike[str], + dataset: Any, + seed: int = 0, + overrides: Mapping[str, Any] | None = None, +) -> tuple[WatchSleepNet, dict[str, Any]]: + """Rebuilds a model from a self-describing bundle or a bare ``.pt`` file. + + Values in ``overrides`` win over the checkpoint config. Bare checkpoints use + :data:`DEFAULT_MODEL_KWARGS` and ``fp32``; the original bare checkpoint + layout is therefore accepted without extra metadata. + + Args: + path: Checkpoint produced by :func:`save_checkpoint`, + :func:`quantize_checkpoint`, or ``Trainer.save_ckpt``. + dataset: The fitted sample dataset used to build the classifier. + seed: Seed applied before model construction. + overrides: Optional model kwargs, quantization, loss, or dataset name. + + Returns: + The loaded model and the checkpoint metadata. + + Examples: + >>> build_model_from_checkpoint("unused.pt", None) if False else "ready" + 'ready' + """ + state, metadata = load_checkpoint(path) + config = dict(metadata.get("config", {})) + options = dict(overrides or {}) + model_kwargs = dict(DEFAULT_MODEL_KWARGS) + model_kwargs.update(config.get("model", config.get("model_kwargs", {}))) + model_kwargs.update(options.get("model_kwargs", {})) + for key in DEFAULT_MODEL_KWARGS: + if key in options: + model_kwargs[key] = options[key] + for key in ("use_attention", "use_tcn"): + if key in config: + model_kwargs[key] = config[key] + if key in options: + model_kwargs[key] = options[key] + quantization = options.get( + "quantization", config.get("quantization", "fp32") + ) + loss = options.get("loss", config.get("loss", "ce")) + model = build_model(dataset, seed=seed, model_kwargs=model_kwargs, + quantization=quantization, loss=loss) + model.load_state_dict(state, strict=True) + return model, metadata + + +def add_model_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + """Adds optional architecture flags that override model defaults. + + Args: + parser: Argument parser to update. + + Returns: + The same parser, for chaining. + + Examples: + >>> import argparse + >>> args = add_model_args(argparse.ArgumentParser()).parse_args([]) + >>> args.hidden_dim, args.use_attention + (None, None) + """ + parser.add_argument("--hidden-dim", type=int, default=None) + parser.add_argument("--num-channels", type=int, default=None) + parser.add_argument("--num-heads", type=int, default=None) + parser.add_argument("--num-layers", type=int, default=None) + parser.add_argument("--tcn-layers", type=int, default=None) + parser.add_argument( + "--use-attention", choices=("true", "false"), default=None + ) + parser.add_argument("--use-tcn", choices=("true", "false"), default=None) + return parser + + +def model_kwargs_from_args(args: argparse.Namespace) -> dict[str, Any]: + """Converts architecture CLI flags into ``WatchSleepNet`` kwargs. + + Args: + args: Namespace populated by :func:`add_model_args`. + + Returns: + Only the architecture options the caller explicitly set. + + Examples: + >>> import argparse + >>> parser = add_model_args(argparse.ArgumentParser()) + >>> model_kwargs_from_args(parser.parse_args(["--hidden-dim", "8"])) + {'hidden_dim': 8} + """ + names = { + "hidden_dim": "hidden_dim", + "num_channels": "num_channels", + "num_heads": "num_heads", + "num_layers": "num_layers", + "tcn_layers": "tcn_layers", + } + kwargs: dict[str, Any] = {} + for flag, key in names.items(): + value = getattr(args, flag, None) + if value is not None: + kwargs[key] = value + for flag, key in (("use_attention", "use_attention"), ("use_tcn", "use_tcn")): + value = getattr(args, flag, None) + if value is not None: + kwargs[key] = value == "true" + return kwargs + + +def quantize_checkpoint( + source: str | os.PathLike[str], + target: str | os.PathLike[str], + quantization: str, +) -> Path: + """Casts every floating-point checkpoint tensor to a compute dtype. + + Args: + source: Input bundle or bare ``.pt`` checkpoint. + target: Output ``.pt`` path. + quantization: One of :data:`QUANTIZATION_MODES`. + + Returns: + The output path. + + Raises: + ValueError: If ``quantization`` is unsupported. + + Examples: + >>> quantize_checkpoint("a.pt", "b.pt", "fp8") if False else "ready" + 'ready' + """ + if quantization not in QUANTIZATION_DTYPES: + raise ValueError( + f"quantization must be one of {QUANTIZATION_MODES}, got {quantization!r}" + ) + state, metadata = load_checkpoint(source) + source_format = metadata.get("format", "bare-state-dict") + dtype = QUANTIZATION_DTYPES[quantization] + cast = { + key: value.to(dtype) if torch.is_floating_point(value) else value.clone() + for key, value in state.items() + } + metadata["format"] = CHECKPOINT_FORMAT + metadata["quantization"] = quantization + target = Path(target) + target.parent.mkdir(parents=True, exist_ok=True) + torch.save( + { + "format": CHECKPOINT_FORMAT, + "state_dict": cast, + "config": metadata.get("config", {}), + "metrics": metadata.get("metrics", {}), + "quantization": quantization, + "source_format": source_format, + }, + target, + ) + return target + + +def write_results( + output_dir: str | os.PathLike[str], + rows: Sequence[Mapping[str, Any]], + metadata: Mapping[str, Any] | None = None, +) -> tuple[Path, Path]: + """Writes ``results.csv`` and ``results.json`` with one row per condition. + + Args: + output_dir: Directory to create or overwrite the result files in. + rows: Metric dictionaries, one per experiment condition. + metadata: Extra JSON metadata such as seeds and dataset roots. + + Returns: + The CSV and JSON paths. + + Examples: + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... csv_path, json_path = write_results(tmp, [{"accuracy": 1.0}]) + ... csv_path.name, json_path.name + ('results.csv', 'results.json') + """ + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + frame = pd.DataFrame(list(rows)) + csv_path = output_dir / "results.csv" + frame.to_csv(csv_path, index=False) + + def plain(value: Any) -> Any: + return value.item() if hasattr(value, "item") else value + + payload = { + "metadata": {k: plain(v) for k, v in (metadata or {}).items()}, + "results": [ + {k: plain(v) for k, v in row.items()} for row in rows + ], + } + json_path = output_dir / "results.json" + json_path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n") + return csv_path, json_path + + +def print_table(rows: Sequence[Mapping[str, Any]], columns: Sequence[str]) -> None: + """Prints an aligned table of the requested columns. + + Args: + rows: Metric dictionaries. + columns: Column names to print in order. + + Returns: + None. The table is written to standard output. + + Examples: + >>> print_table([{"accuracy": 1.0}], ["accuracy"]) + accuracy + 1.0000 + """ + widths = [max(len(c), 8) for c in columns] + print(" ".join(c.ljust(w).rstrip() for c, w in zip(columns, widths, strict=True))) + for row in rows: + cells = [] + for column, width in zip(columns, widths, strict=True): + value = row.get(column, "") + if isinstance(value, float): + cells.append(f"{value:.4f}".ljust(width)) + else: + cells.append(str(value).ljust(width)) + print(" ".join(cell.rstrip() for cell in cells)) + + +def add_training_args(parser: argparse.ArgumentParser) -> argparse.ArgumentParser: + """Adds the shared training, seed, device, and quantization CLI flags. + + Args: + parser: Argument parser to update. + + Returns: + The same parser, for chaining. + + Examples: + >>> import argparse + >>> args = add_training_args(argparse.ArgumentParser()).parse_args([]) + >>> args.quantization, args.seed, args.loss + ('fp32', 0, 'ce') + """ + parser.add_argument("--epochs", type=int, default=5) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument("--lr", type=float, default=5e-5) + parser.add_argument("--weight-decay", type=float, default=1e-4) + parser.add_argument("--seed", type=int, default=0) + parser.add_argument("--device", default=None, help="torch device; default auto") + parser.add_argument("--quantization", choices=QUANTIZATION_MODES, default="fp32") + parser.add_argument( + "--loss", + choices=LOSS_MODES, + default="ce", + help="training loss; ce is the reference default", + ) + parser.add_argument("--output-dir", default="output/watchsleepnet") + return parser diff --git a/examples/watchsleepnet/watchsleepnet_evaluate.py b/examples/watchsleepnet/watchsleepnet_evaluate.py new file mode 100644 index 0000000000..431cf17ac5 --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_evaluate.py @@ -0,0 +1,411 @@ +"""Evaluates a trained WatchSleepNet checkpoint on a real staging cohort. + +The script rebuilds the IBI task from a real dataset root, loads a +bare ``.pt`` state dict or a self-describing checkpoint, evaluates on the +held-out patient split, prints the metric table, and writes ``results.csv``, +``results.json``, and a three-class ``confusion_matrix.png`` to ``--output-dir``. +DREAMT, SHHS, MESA, ISRUC and Sleep-Accel roots are supported; ISRUC uses the +checkpoint's scorer unless ``--scorer`` overrides it. + +Command: + python examples/watchsleepnet/watchsleepnet_evaluate.py \ + --checkpoint output/watchsleepnet-finetune/finetuned.pt \ + --dataset dreamt --root /path/to/dreamt \ + --output-dir output/watchsleepnet-evaluate + +Metrics include accuracy, macro one-vs-rest AUROC, Cohen's kappa, macro F1, +weighted F1, and Wake/NREM/REM F1. Classes with no positive examples are skipped +when averaging AUROC, so a small held-out split remains scorable. +""" + +from __future__ import annotations + +import argparse +import random +import warnings +from pathlib import Path +from typing import Any + +import numpy as np +import torch +from sklearn.metrics import ( + cohen_kappa_score, + confusion_matrix, + f1_score, + roc_auc_score, +) + +try: + from .watchsleepnet_common import ( + CLASS_NAMES, + add_peak_backend_arg, + build_dataset, + build_model_from_checkpoint, + build_samples, + build_task, + existing_dir, + get_loaders, + load_checkpoint, + predict, + print_table, + resample_dataset, + split_dataset, + summarize_predictions, + write_results, + ) +except ImportError: + from watchsleepnet_common import ( + CLASS_NAMES, + add_peak_backend_arg, + build_dataset, + build_model_from_checkpoint, + build_samples, + build_task, + existing_dir, + get_loaders, + load_checkpoint, + predict, + print_table, + resample_dataset, + split_dataset, + summarize_predictions, + write_results, + ) + +REPORT_COLUMNS = ( + "dataset", + "n_epochs", + "accuracy", + "auroc", + "cohen_kappa", + "f1_macro", + "f1_weighted", + "f1_wake", + "f1_nrem", + "f1_rem", +) + + +def existing_file(value: str) -> Path: + """Returns an existing checkpoint file supplied on the command line. + + Args: + value: User-supplied checkpoint path. + + Returns: + The expanded path. + + Raises: + argparse.ArgumentTypeError: If the path is not an existing file. + + Examples: + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... path = Path(tmp) / "model.pt" + ... _ = path.write_bytes(b"") + ... existing_file(str(path)).name + 'model.pt' + """ + path = Path(value).expanduser() + if not path.is_file(): + raise argparse.ArgumentTypeError( + f"{value!r} does not point to an existing checkpoint file" + ) + return path + + +def macro_ovr_auroc(y_true: np.ndarray, y_prob: np.ndarray) -> float: + """Computes macro one-vs-rest AUROC over the three staging classes. + + Args: + y_true: Integer labels in ``0..2``. + y_prob: Class probabilities with shape ``(n, 3)``. + + Returns: + The mean AUROC over classes with both positive and negative examples, + or ``0.0`` when no such class exists. + + Examples: + >>> import numpy as np + >>> probs = np.array([[0.9, 0.1, 0.0], [0.2, 0.8, 0.0]]) + >>> macro_ovr_auroc(np.array([0, 1]), probs) + 1.0 + """ + truth = np.asarray(y_true, dtype=np.int64) + scores = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES)) + if not truth.size: + return 0.0 + values = [] + for index in range(len(CLASS_NAMES)): + binary = (truth == index).astype(np.int64) + if np.unique(binary).size < 2: + continue + values.append(float(roc_auc_score(binary, scores[:, index]))) + return float(np.mean(values)) if values else 0.0 + + +def evaluation_metrics(y_true: np.ndarray, y_prob: np.ndarray) -> dict[str, Any]: + """Computes the full evaluation table from flattened predictions. + + Args: + y_true: Integer labels in ``0..2``. + y_prob: Class probabilities with shape ``(n, 3)``. + + Returns: + A flat dictionary with accuracy, AUROC, kappa, macro/weighted F1, and + per-class F1. Empty inputs produce zeros. + + Examples: + >>> import numpy as np + >>> row = evaluation_metrics(np.array([0, 1, 2]), np.eye(3)) + >>> row["accuracy"], row["auroc"], row["cohen_kappa"] + (1.0, 1.0, 1.0) + >>> row["f1_macro"], row["f1_weighted"] + (1.0, 1.0) + >>> row["f1_wake"], row["f1_nrem"], row["f1_rem"] + (1.0, 1.0, 1.0) + """ + metrics = dict(summarize_predictions(y_true, y_prob)) + truth = np.asarray(y_true, dtype=np.int64) + scores = np.asarray(y_prob, dtype=np.float64).reshape(-1, len(CLASS_NAMES)) + predicted = ( + scores.argmax(axis=1) if scores.size else np.empty(0, dtype=np.int64) + ) + labels = list(range(len(CLASS_NAMES))) + if not truth.size: + metrics.update( + auroc=0.0, + cohen_kappa=0.0, + f1_weighted=0.0, + ) + return metrics + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + kappa = cohen_kappa_score(truth, predicted, labels=labels) + metrics["auroc"] = macro_ovr_auroc(truth, scores) + metrics["cohen_kappa"] = float(kappa) if np.isfinite(kappa) else 0.0 + metrics["f1_weighted"] = float( + f1_score(truth, predicted, labels=labels, average="weighted", + zero_division=0) + ) + return metrics + + +def save_confusion_matrix( + y_true: np.ndarray, y_pred: np.ndarray, output_dir: str | Path +) -> Path: + """Saves a labeled three-class confusion matrix as a PNG. + + Args: + y_true: Integer labels in ``0..2``. + y_pred: Predicted labels in ``0..2``. + output_dir: Report directory to write ``confusion_matrix.png`` into. + + Returns: + The saved image path. + + Examples: + >>> import numpy as np + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... path = save_confusion_matrix( + ... np.array([0, 1]), np.array([0, 2]), tmp + ... ) + ... path.name + 'confusion_matrix.png' + """ + import matplotlib + + matplotlib.use("Agg") + import matplotlib.pyplot as plt + + output_dir = Path(output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + matrix = confusion_matrix( + np.asarray(y_true, dtype=np.int64), + np.asarray(y_pred, dtype=np.int64), + labels=list(range(len(CLASS_NAMES))), + ) + figure, axis = plt.subplots(figsize=(5.5, 4.5)) + image = axis.imshow(matrix, cmap="Blues") + axis.set_xticks(range(len(CLASS_NAMES)), CLASS_NAMES) + axis.set_yticks(range(len(CLASS_NAMES)), CLASS_NAMES) + axis.set_xlabel("Predicted") + axis.set_ylabel("True") + axis.set_title("WatchSleepNet confusion matrix") + for row in range(len(CLASS_NAMES)): + for column in range(len(CLASS_NAMES)): + axis.text( + column, + row, + str(int(matrix[row, column])), + ha="center", + va="center", + color="white" if matrix[row, column] > matrix.max() / 2 else "black", + ) + figure.colorbar(image, ax=axis) + figure.tight_layout() + path = output_dir / "confusion_matrix.png" + figure.savefig(path, dpi=150) + plt.close(figure) + return path + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parses command-line arguments for checkpoint evaluation. + + Args: + argv: Optional argument list. Defaults to ``sys.argv[1:]``. + + Returns: + The parsed namespace. ``seed`` defaults to the checkpoint's split seed. + + Examples: + >>> args = parse_args([ + ... "--checkpoint", __file__, "--root", ".", + ... "--output-dir", "out", + ... ]) + >>> args.dataset, args.batch_size + ('dreamt', 16) + >>> args.peak_backend + 'scipy' + """ + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--checkpoint", required=True, type=existing_file, + help="trained .pt state dict or bundled checkpoint", + ) + parser.add_argument( + "--dataset", + choices=("dreamt", "shhs", "mesa", "isruc", "sleep_accel"), + default="dreamt", + ) + parser.add_argument( + "--root", required=True, type=existing_dir, help="real dataset root" + ) + parser.add_argument( + "--cache-dir", + default=None, + help="reuse a PyHealth cache from training (e.g. /cache)", + ) + parser.add_argument( + "--output-dir", required=True, type=Path, help="report directory" + ) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument("--seed", type=int, default=None) + parser.add_argument("--device", default=None, help="torch device; default auto") + parser.add_argument("--signal-source", default=None) + parser.add_argument("--signal-channel", default=None) + parser.add_argument( + "--scorer", choices=("expert1", "expert2"), default=None + ) + parser.add_argument("--points-per-epoch", type=int, default=None) + parser.add_argument("--task-max-epochs", type=int, default=None) + add_peak_backend_arg(parser) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + """Evaluates one checkpoint and writes a complete report folder. + + Args: + argv: Optional argument list. + + Returns: + Process exit code, ``0`` on success. + + Examples: + >>> main([ + ... "--checkpoint", __file__, "--root", ".", + ... "--output-dir", "out", + ... ]) if False else "ready" + 'ready' + """ + args = parse_args(argv) + _, metadata = load_checkpoint(args.checkpoint) + config: dict[str, Any] = dict(metadata.get("config", {})) + task_config: dict[str, Any] = dict(config.get("task", {})) + seed = args.seed if args.seed is not None else int(config.get("split_seed", 0)) + points = ( + args.points_per_epoch + if args.points_per_epoch is not None + else int(task_config.get("points_per_epoch", 750)) + ) + max_epochs = ( + args.task_max_epochs + if args.task_max_epochs is not None + else int(task_config.get("max_epochs", 1100)) + ) + signal_source = args.signal_source or str( + task_config.get("signal_source", "psg_100hz") + ) + scorer = args.scorer or str(task_config.get("scorer", "expert1")) + + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + + dataset = build_dataset( + args.dataset, args.root, cache_dir=args.cache_dir + ) + task = build_task( + args.dataset, + points_per_epoch=points, + max_epochs=max_epochs, + signal_source=signal_source, + signal_channel=args.signal_channel, + scorer=scorer, + peak_backend=args.peak_backend, + ) + samples = build_samples(dataset, task, num_workers=args.num_workers) + if points != 750: + samples = resample_dataset(samples, 750) + parts = split_dataset(samples, seed=seed) + loader = get_loaders(parts, batch_size=args.batch_size, seed=seed)[2] + + model, _ = build_model_from_checkpoint( + args.checkpoint, parts[0], seed=seed + ) + target = args.device or str(model.device) + model.to(target) + y_true, y_prob = predict(model, loader, device=target) + y_pred = ( + y_prob.argmax(axis=1) if y_prob.size else np.empty(0, dtype=np.int64) + ) + + row = {"dataset": args.dataset, **evaluation_metrics(y_true, y_prob)} + image_path = save_confusion_matrix(y_true, y_pred, args.output_dir) + matrix = confusion_matrix( + y_true, + y_pred, + labels=list(range(len(CLASS_NAMES))), + ).tolist() + write_results( + args.output_dir, + [row], + { + "checkpoint": str(args.checkpoint), + "root": str(args.root), + "split": "test", + "seed": seed, + "task": { + "signal_source": signal_source, + "points_per_epoch": points, + "max_epochs": max_epochs, + "scorer": scorer, + }, + "confusion_matrix": matrix, + "confusion_matrix_image": image_path.name, + }, + ) + print_table([row], REPORT_COLUMNS) + print(f"confusion matrix: {image_path}") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/watchsleepnet/watchsleepnet_finetune.py b/examples/watchsleepnet/watchsleepnet_finetune.py new file mode 100644 index 0000000000..53677fb07d --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_finetune.py @@ -0,0 +1,286 @@ +"""WatchSleepNet fine-tuning from a bare or bundled checkpoint. + +The script requires a real dataset root, optionally loads an existing ``.pt`` +checkpoint, fine-tunes with ``Trainer.train``, evaluates with +``Trainer.evaluate``, and saves a self-describing fine-tuned checkpoint. +DREAMT, SHHS, MESA, ISRUC and Sleep-Accel roots are supported. There is no +synthetic-data fallback. ``--loss`` selects the training objective; ``ce`` is +the reference default. + +Command: + python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \ + --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \ + --output-dir output/watchsleepnet-pretrain + python examples/watchsleepnet/watchsleepnet_finetune.py --dataset dreamt \ + --root /path/to/dreamt \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --epochs 5 --output-dir output/watchsleepnet-finetune + +Example output table:: + + dataset status checkpoint_loaded accuracy f1_wake f1_nrem f1_rem + dreamt ok True 0.6364 0.0000 0.7778 0.0000 + +Per-class F1 and the predicted-class distribution are written to +``results.csv``/``results.json``; they expose NREM-majority collapse. +""" + +from __future__ import annotations + +import argparse +import random +from pathlib import Path + +import numpy as np +import pandas as pd + +try: + from .watchsleepnet_common import ( + DEFAULT_MODEL_KWARGS, + add_model_args, + add_peak_backend_arg, + add_training_args, + build_dataset, + build_model, + build_model_from_checkpoint, + build_samples, + build_task, + existing_dir, + fit, + get_loaders, + load_checkpoint, + model_kwargs_from_args, + predict, + print_table, + save_checkpoint, + split_dataset, + summarize_predictions, + write_results, + ) +except ImportError: + from watchsleepnet_common import ( + DEFAULT_MODEL_KWARGS, + add_model_args, + add_peak_backend_arg, + add_training_args, + build_dataset, + build_model, + build_model_from_checkpoint, + build_samples, + build_task, + existing_dir, + fit, + get_loaders, + load_checkpoint, + model_kwargs_from_args, + predict, + print_table, + save_checkpoint, + split_dataset, + summarize_predictions, + write_results, + ) + +TABLE_COLUMNS = ( + "dataset", + "status", + "loss", + "checkpoint_loaded", + "pre_accuracy", + "accuracy", + "f1_wake", + "f1_nrem", + "f1_rem", + "pred_nrem", +) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parses command-line arguments for the fine-tuning example. + + Args: + argv: Optional argument list. + + Returns: + The parsed namespace. ``quantization`` is ``None`` unless explicitly + set, so a loaded checkpoint's own mode is preserved. + + Examples: + >>> args = parse_args(["--root", "."]) + >>> args.quantization is None, args.loss + (True, 'ce') + >>> args.peak_backend + 'scipy' + >>> parse_args(["--root", ".", "--peak-backend", "auto"]).peak_backend + 'auto' + """ + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--dataset", + choices=("dreamt", "shhs", "mesa", "isruc", "sleep_accel"), + default="dreamt", + ) + parser.add_argument( + "--root", required=True, type=existing_dir, help="real dataset root" + ) + parser.add_argument("--checkpoint", default=None, help=".pt to fine-tune") + parser.add_argument("--points-per-epoch", type=int, default=750) + parser.add_argument("--task-max-epochs", type=int, default=None) + parser.add_argument( + "--signal-source", + choices=("psg_100hz", "wearable_64hz"), + default="psg_100hz", + ) + parser.add_argument( + "--scorer", choices=("expert1", "expert2"), default="expert1" + ) + add_peak_backend_arg(parser) + add_training_args(parser) + add_model_args(parser) + parser.set_defaults(quantization=None) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + """Fine-tunes from an optional checkpoint and writes model and result files. + + Args: + argv: Optional argument list. + + Returns: + Zero after a completed run. + + Examples: + >>> main(["--root", ".", "--epochs", "0"]) if False else "ready" + 'ready' + """ + args = parse_args(argv) + random.seed(args.seed) + np.random.seed(args.seed) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + root = Path(args.root) + cache_dir = output_dir / "cache" + dataset = build_dataset( + args.dataset, root, cache_dir=str(cache_dir) + ) + task = build_task( + args.dataset, + points_per_epoch=args.points_per_epoch, + max_epochs=args.task_max_epochs or 1100, + signal_source=args.signal_source, + scorer=args.scorer, + peak_backend=args.peak_backend, + ) + samples = build_samples(dataset, task, num_workers=args.num_workers) + parts = split_dataset(samples, seed=args.seed) + loaders = get_loaders( + parts, batch_size=args.batch_size, seed=args.seed + ) + + cli_kwargs = model_kwargs_from_args(args) + checkpoint_config: dict[str, object] = {} + if args.checkpoint: + _, metadata = load_checkpoint(args.checkpoint) + checkpoint_config = dict(metadata.get("config", {})) + overrides: dict[str, object] = {} + if args.quantization is not None: + overrides["quantization"] = args.quantization + overrides["loss"] = args.loss + if cli_kwargs: + overrides["model_kwargs"] = cli_kwargs + model, _ = build_model_from_checkpoint( + args.checkpoint, parts[0], seed=args.seed, overrides=overrides + ) + else: + model = build_model( + parts[0], seed=args.seed, model_kwargs=cli_kwargs, + quantization=args.quantization or "fp32", loss=args.loss, + ) + quantization = str( + args.quantization + or checkpoint_config.get("quantization", "fp32") + ) + model_kwargs = dict(DEFAULT_MODEL_KWARGS) + model_kwargs.update(checkpoint_config.get("model", {})) + model_kwargs.update(cli_kwargs) + + pre_metrics = {} + if args.checkpoint: + pre_true, pre_prob = predict(model, loaders[2], + device=args.device) + pre_metrics = summarize_predictions(pre_true, pre_prob) + + trainer, history = fit( + model, + loaders, + epochs=args.epochs, + lr=args.lr, + weight_decay=args.weight_decay, + device=args.device, + quantization=quantization, + ) + val_scores = trainer.evaluate(loaders[1]) + y_true, y_prob = predict(model, loaders[2], device=args.device) + metrics = summarize_predictions(y_true, y_prob) + + checkpoint = save_checkpoint( + output_dir / "finetuned.pt", + model, + { + "stage": "finetune", + "dataset": args.dataset, + "root": str(root), + "source_checkpoint": args.checkpoint, + "task": { + "signal_source": args.signal_source, + "points_per_epoch": args.points_per_epoch, + "max_epochs": args.task_max_epochs or 1100, + "scorer": args.scorer, + }, + "model": model_kwargs, + "quantization": quantization, + "loss": args.loss, + "split_seed": args.seed, + "training": { + "epochs": args.epochs, + "batch_size": args.batch_size, + "lr": args.lr, + "weight_decay": args.weight_decay, + }, + }, + metrics, + ) + pd.DataFrame(history).to_csv( + output_dir / "training_history.csv", index=False + ) + row = { + "dataset": args.dataset, + "status": "ok", + "loss": args.loss, + "checkpoint_loaded": bool(args.checkpoint), + "pre_accuracy": pre_metrics.get("accuracy", ""), + "val_accuracy": float(val_scores.get("accuracy", 0.0)), + "checkpoint": str(checkpoint), + **metrics, + } + write_results( + output_dir, + [row], + { + "root": str(root), + "loss": args.loss, + "seed": args.seed, + "source_checkpoint": args.checkpoint, + }, + ) + print_table([row], TABLE_COLUMNS) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py b/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py new file mode 100644 index 0000000000..bfdfe9f495 --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py @@ -0,0 +1,236 @@ +"""SHHS+MESA WatchSleepNet pretraining on real cohorts. + +The script requires real SHHS and MESA roots, builds the three-class +IBI tasks, pools the recordings, splits by patient, trains +:class:`~pyhealth.models.WatchSleepNet` with ``Trainer.train``, and saves a +self-describing checkpoint plus ``training_history.csv``. There is no +synthetic-data fallback. + +Command: + python examples/watchsleepnet/watchsleepnet_pretrain_shhs_mesa.py \ + --shhs-root /path/to/shhs --mesa-root /path/to/mesa --epochs 200 \ + --output-dir output/watchsleepnet-pretrain + +A 1100-epoch cap is used by default. ``--loss`` selects the +training objective; ``ce`` is the reference default. Example output table:: + + cohort status accuracy f1_wake f1_nrem f1_rem + shhs+mesa ok 0.6364 0.0000 0.7778 0.0000 + +The predicted-class distribution is also reported in ``results.csv`` so that +NREM-majority collapse remains visible even when accuracy looks reasonable. +""" + +from __future__ import annotations + +import argparse +import random +from pathlib import Path + +import numpy as np +import pandas as pd + +try: + from .watchsleepnet_common import ( + add_model_args, + add_peak_backend_arg, + add_training_args, + build_dataset, + build_model, + build_samples, + build_task, + existing_dir, + fit, + get_loaders, + model_kwargs_from_args, + pool_datasets, + predict, + print_table, + save_checkpoint, + split_dataset, + summarize_predictions, + write_results, + ) +except ImportError: + from watchsleepnet_common import ( + add_model_args, + add_peak_backend_arg, + add_training_args, + build_dataset, + build_model, + build_samples, + build_task, + existing_dir, + fit, + get_loaders, + model_kwargs_from_args, + pool_datasets, + predict, + print_table, + save_checkpoint, + split_dataset, + summarize_predictions, + write_results, + ) + +TABLE_COLUMNS = ( + "cohort", + "status", + "loss", + "accuracy", + "f1_wake", + "f1_nrem", + "f1_rem", + "pred_wake", + "pred_nrem", + "pred_rem", +) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parses command-line arguments for the pretraining example. + + Args: + argv: Optional argument list. + + Returns: + The parsed namespace. + + Examples: + >>> args = parse_args(["--shhs-root", ".", "--mesa-root", ".", + ... "--epochs", "2"]) + >>> args.epochs, args.peak_backend + (2, 'scipy') + """ + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--shhs-root", required=True, type=existing_dir, help="real SHHS root" + ) + parser.add_argument( + "--mesa-root", required=True, type=existing_dir, help="real MESA root" + ) + parser.add_argument("--points-per-epoch", type=int, default=750) + parser.add_argument("--task-max-epochs", type=int, default=None) + add_peak_backend_arg(parser) + add_training_args(parser) + add_model_args(parser) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + """Runs pretraining and writes the checkpoint, history, and result files. + + Args: + argv: Optional argument list. + + Returns: + Zero after a completed run. + + Examples: + >>> main(["--shhs-root", ".", "--mesa-root", ".", + ... "--epochs", "0"]) if False else "ready" + 'ready' + """ + args = parse_args(argv) + random.seed(args.seed) + np.random.seed(args.seed) + output_dir = Path(args.output_dir) + output_dir.mkdir(parents=True, exist_ok=True) + + cache_root = output_dir / "cache" + cohorts = [("shhs", Path(args.shhs_root)), ("mesa", Path(args.mesa_root))] + + sample_sets = [] + for name, root in cohorts: + dataset = build_dataset( + name, root, cache_dir=str(cache_root / name) + ) + task = build_task( + name, + points_per_epoch=args.points_per_epoch, + max_epochs=( + args.task_max_epochs + if args.task_max_epochs is not None + else 1100 + ), + peak_backend=args.peak_backend, + ) + sample_sets.append( + build_samples(dataset, task, num_workers=args.num_workers) + ) + samples = pool_datasets(sample_sets) + parts = split_dataset(samples, seed=args.seed) + loaders = get_loaders( + parts, batch_size=args.batch_size, seed=args.seed + ) + model_kwargs = model_kwargs_from_args(args) + model = build_model( + parts[0], seed=args.seed, model_kwargs=model_kwargs, + quantization=args.quantization, loss=args.loss, + ) + trainer, history = fit( + model, + loaders, + epochs=args.epochs, + lr=args.lr, + weight_decay=args.weight_decay, + device=args.device, + quantization=args.quantization, + ) + val_scores = trainer.evaluate(loaders[1]) + y_true, y_prob = predict(model, loaders[2], device=args.device) + metrics = summarize_predictions(y_true, y_prob) + + checkpoint = save_checkpoint( + output_dir / "pretrained.pt", + model, + { + "stage": "pretrain", + "cohorts": [name for name, _ in cohorts], + "roots": {name: str(root) for name, root in cohorts}, + "task": { + "points_per_epoch": args.points_per_epoch, + "max_epochs": args.task_max_epochs or 1100, + }, + "model": model_kwargs, + "quantization": args.quantization, + "loss": args.loss, + "split_seed": args.seed, + "training": { + "epochs": args.epochs, + "batch_size": args.batch_size, + "lr": args.lr, + "weight_decay": args.weight_decay, + }, + }, + metrics, + ) + pd.DataFrame(history).to_csv( + output_dir / "training_history.csv", index=False + ) + row = { + "cohort": "+".join(name for name, _ in cohorts), + "status": "ok", + "loss": args.loss, + "val_accuracy": float(val_scores.get("accuracy", 0.0)), + "checkpoint": str(checkpoint), + **metrics, + } + write_results( + output_dir, + [row], + { + "roots": {name: str(root) for name, root in cohorts}, + "loss": args.loss, + "seed": args.seed, + }, + ) + print_table([row], TABLE_COLUMNS) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/watchsleepnet/watchsleepnet_quantize.py b/examples/watchsleepnet/watchsleepnet_quantize.py new file mode 100644 index 0000000000..e79c138f62 --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_quantize.py @@ -0,0 +1,136 @@ +"""Casts a WatchSleepNet checkpoint to fp32, bf16, or fp16 without training. + +This example needs no dataset: it loads a bare ``.pt`` state dict or a +self-describing bundle, casts floating-point tensors, and saves the result. +Unsupported dtype/device behavior is left to PyTorch; the script reports the +dtype counts it actually wrote rather than pre-labeling any mode. + +Casting a checkpoint does not train a model; it only checks that the PyHealth +checkpoint path preserves the requested compute dtype. + +Command: + python examples/watchsleepnet/watchsleepnet_quantize.py \ + --checkpoint output/watchsleepnet-pretrain/pretrained.pt \ + --output output/watchsleepnet-pretrain/pretrained_fp16.pt \ + --quantization fp16 + +Example output table:: + + tensor_dtype count + torch.float16 135 + torch.int64 0 + +``quantization.csv`` and ``quantization.json`` are written next to ``--output``. +""" + +from __future__ import annotations + +import argparse +import json +from collections import Counter +from pathlib import Path + +try: + from .watchsleepnet_common import ( + QUANTIZATION_MODES, + load_checkpoint, + print_table, + quantize_checkpoint, + ) +except ImportError: + from watchsleepnet_common import ( + QUANTIZATION_MODES, + load_checkpoint, + print_table, + quantize_checkpoint, + ) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + """Parses command-line arguments for checkpoint quantization. + + Args: + argv: Optional argument list. + + Returns: + The parsed namespace. + + Examples: + >>> args = parse_args(["--checkpoint", "a.pt", "--output", "b.pt", + ... "--quantization", "bf16"]) + >>> args.quantization + 'bf16' + """ + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument("--checkpoint", required=True, help="input .pt file") + parser.add_argument("--output", required=True, help="output .pt file") + parser.add_argument("--quantization", required=True, + choices=QUANTIZATION_MODES) + parser.add_argument("--report", default=None, + help="report path; defaults next to --output") + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + """Loads, casts, saves, and reports a checkpoint. + + Args: + argv: Optional argument list. + + Returns: + Zero after the cast completes. + + Examples: + >>> main(["--checkpoint", "unused.pt", "--output", "out.pt", + ... "--quantization", "fp32"]) if False else "ready" + 'ready' + """ + args = parse_args(argv) + source = Path(args.checkpoint) + target = Path(args.output) + _, metadata = load_checkpoint(source) + quantize_checkpoint(source, target, args.quantization) + state, output_metadata = load_checkpoint(target) + counts = Counter(str(tensor.dtype) for tensor in state.values()) + rows = [ + {"tensor_dtype": dtype, "count": count} + for dtype, count in sorted(counts.items()) + ] + + report = ( + Path(args.report) if args.report else target.parent / "quantization.json" + ) + report.parent.mkdir(parents=True, exist_ok=True) + report.write_text( + json.dumps( + { + "source": str(source), + "target": str(target), + "quantization": args.quantization, + "source_format": output_metadata.get( + "source_format", metadata.get("format", "bare-state-dict") + ), + "dtype_counts": dict(counts), + "config": output_metadata.get("config", {}), + }, + indent=2, + sort_keys=True, + default=str, + ) + + "\n" + ) + csv_path = report.with_suffix(".csv") + with open(csv_path, "w") as handle: + handle.write("tensor_dtype,count\n") + handle.writelines( + f"{row['tensor_dtype']},{row['count']}\n" for row in rows + ) + print_table(rows, ("tensor_dtype", "count")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/watchsleepnet/watchsleepnet_synthetic_data.py b/examples/watchsleepnet/watchsleepnet_synthetic_data.py new file mode 100644 index 0000000000..6c22f0e526 --- /dev/null +++ b/examples/watchsleepnet/watchsleepnet_synthetic_data.py @@ -0,0 +1,551 @@ +"""Generate synthetic DREAMT, SHHS, or MESA recordings. + +The generated tree mirrors the folder and file layout expected by +:class:`~pyhealth.datasets.DREAMTDataset` and +:class:`~pyhealth.datasets.NSRRSleepDataset`, but contains deterministic mock +waveforms and hypnograms. It lets reviewers run the WatchSleepNet pipeline +without access to the protected source datasets. + +DREAMT output:: + + / + participant_info.csv + dreamt-metadata.csv + data_100Hz/S001_PSG_df.csv + data_64Hz/S001_whole_df.csv + +SHHS output:: + + / + nsrr-shhs-pyhealth.csv + edfs/shhs1/shhs1-200001.edf + annotations-events-profusion/shhs1/shhs1-200001-profusion.xml + +MESA output:: + + / + nsrr-mesa-pyhealth.csv + edfs/mesa-sleep-0001.edf + annotations-events-profusion/mesa-sleep-0001-profusion.xml + +Command: + python examples/watchsleepnet/watchsleepnet_synthetic_data.py \ + --dataset shhs --num-samples 5 --output-dir synthetic/shhs + python examples/watchsleepnet/watchsleepnet_synthetic_data.py \ + --dataset dreamt --num-samples 5 --output-dir synthetic/dreamt +""" + +from __future__ import annotations + +import argparse +import shutil +import sys +import xml.etree.ElementTree as ET +from pathlib import Path + +import numpy as np +import pandas as pd + +_RECORD_SECONDS = 30.0 +_STAGE_CYCLES: dict[str, tuple[object, ...]] = { + "shhs": (0, 0, 1, 1, 2, 2, 2, 3, 2, 2, 5, 5, 2, 1, 0), + "mesa": (0, 0, 1, 1, 2, 2, 2, 3, 2, 2, 5, 5, 2, 1, 0), + "dreamt": ( + "W", "W", "N1", "N2", "N2", "N3", "N2", "R", "R", "N2", "N1", "W", + ), +} +_DREAMT_100HZ_COLUMNS = ( + "TIMESTAMP", "C4-M1", "F4-M1", "O2-M1", "Fp1-O2", "T3 - CZ", "CZ - T4", + "CHIN", "E1", "E2", "ECG", "LAT", "RAT", "SNORE", "PTAF", "FLOW", + "THORAX", "ABDOMEN", "SAO2", "BVP", "ACC_X", "ACC_Y", "ACC_Z", "TEMP", + "EDA", "HR", "IBI", "Sleep_Stage", "Obstructive_Apnea", "Central_Apnea", + "Hypopnea", "Multiple_Events", +) +_DREAMT_64HZ_COLUMNS = ( + "TIMESTAMP", "BVP", "ACC_X", "ACC_Y", "ACC_Z", "TEMP", "EDA", "HR", "IBI", + "Sleep_Stage", "Obstructive_Apnea", "Central_Apnea", "Hypopnea", + "Multiple_Events", +) + + +def build_parser() -> argparse.ArgumentParser: + """Builds the command-line parser. + + Returns: + A parser with ``--dataset`` and ``--num-samples`` required and the + shape controls optional. + """ + parser = argparse.ArgumentParser( + description=__doc__.splitlines()[0], + formatter_class=argparse.ArgumentDefaultsHelpFormatter, + ) + parser.add_argument( + "--dataset", + required=True, + choices=("shhs", "mesa", "dreamt"), + help="dataset layout to simulate", + ) + parser.add_argument( + "--num-samples", + required=True, + type=int, + help="number of synthetic recordings (one per patient)", + ) + parser.add_argument( + "--epochs", + type=int, + default=20, + help="number of 30 s epochs per recording", + ) + parser.add_argument( + "--output-dir", + type=Path, + default=None, + help="destination; defaults to synthetic_data/", + ) + parser.add_argument( + "--seed", + type=int, + default=0, + help="random seed for waveform and hypnogram generation", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="replace a non-empty output directory", + ) + return parser + + +def _stage_sequence(dataset: str, epochs: int, seed: int) -> list[object]: + """Returns a deterministic hypnogram containing every target class.""" + cycle = _STAGE_CYCLES[dataset] + offset = seed % len(cycle) + rotated = cycle[offset:] + cycle[:offset] + return [rotated[i % len(rotated)] for i in range(epochs)] + + +def _heart_rate( + n: int, fs: float, seed: int, bpm: float = 60.0 +) -> tuple[np.ndarray, np.ndarray]: + """Returns a smooth heart-rate trace and its sample times.""" + rng = np.random.default_rng(seed) + times = np.arange(n, dtype=np.float64) / fs + rate = bpm + 4.0 * np.sin( + 2.0 * np.pi * times / 300.0 + rng.uniform(0.0, 2.0 * np.pi) + ) + rate += 0.6 * np.sin( + 2.0 * np.pi * times / 41.0 + rng.uniform(0.0, 2.0 * np.pi) + ) + return rate, times + + +def _beat_phase(rate: np.ndarray, fs: float) -> np.ndarray: + """Converts an instantaneous heart rate into a wrapped beat phase.""" + return np.mod(np.cumsum(rate / 60.0) / fs, 1.0) + + +def _cardiac_signal( + n: int, fs: float, seed: int, kind: str, bpm: float = 60.0 +) -> tuple[np.ndarray, np.ndarray]: + """Returns a clean ECG or PPG waveform and its heart-rate trace. + + The signals have exactly one positive peak per cardiac cycle, which keeps + the scipy peak-detector fallback stable without needing optional packages. + """ + rate, _ = _heart_rate(n, fs, seed, bpm) + phase = _beat_phase(rate, fs) + if kind == "ecg": + r_peak = np.exp(-0.5 * ((phase - 0.25) / 0.012) ** 2) + q_wave = -0.15 * np.exp(-0.5 * ((phase - 0.22) / 0.020) ** 2) + s_wave = -0.25 * np.exp(-0.5 * ((phase - 0.28) / 0.020) ** 2) + return r_peak + q_wave + s_wave, rate + if kind == "ppg": + return np.exp(-0.5 * ((phase - 0.20) / 0.075) ** 2), rate + raise ValueError(f"unknown cardiac signal {kind!r}") + + +def _respiratory_signal(n: int, fs: float, seed: int) -> np.ndarray: + """Returns a slow respiratory-effort waveform.""" + rng = np.random.default_rng(seed) + times = np.arange(n, dtype=np.float64) / fs + phase = rng.uniform(0.0, 2.0 * np.pi) + return np.sin(2.0 * np.pi * 0.25 * times + phase) + + +def _normalize(signal: np.ndarray) -> np.ndarray: + """Centers a signal and scales it to ``[-0.9, 0.9]``.""" + array = np.asarray(signal, dtype=np.float64) + array = array - array.mean() + peak = float(np.max(np.abs(array))) + if peak > 0.0: + array = 0.9 * array / peak + return array + + +def _pad(value: object, width: int, align: str = "<") -> str: + """Pads or truncates an ASCII field to an EDF header width.""" + text = str(value) + if len(text) > width: + text = text[:width] + return f"{text:{align}{width}}" + + +def _write_edf( + path: Path, + channels: list[tuple[str, np.ndarray, float]], + n_records: int, +) -> None: + """Writes a minimal EDF+C file readable by PyHealth's NSRR loader. + + Args: + path: Destination ``.edf`` file. + channels: ``(label, signal, sampling_rate_hz)`` triples. Each signal + must contain ``n_records * sampling_rate * 30`` samples. + n_records: Number of 30 s data records. + """ + record_samples = [ + int(round(rate * _RECORD_SECONDS)) for _, _, rate in channels + ] + for (label, signal, _), count in zip(channels, record_samples): + expected = n_records * count + if signal.size != expected: + raise ValueError( + f"{label} has {signal.size} samples, expected {expected}" + ) + n_signals = len(channels) + header_bytes = 256 + 256 * n_signals + per_record = sum(record_samples) + + header = "".join( + ( + _pad("0", 8), + _pad("Synthetic WatchSleepNet", 80), + _pad("Synthetic recording", 80), + _pad("01.01.00", 8), + _pad("00.00.00", 8), + _pad(header_bytes, 8, ">"), + _pad("EDF+C", 44), + _pad(n_records, 8, ">"), + _pad(f"{_RECORD_SECONDS:g}", 8, ">"), + _pad(n_signals, 4, ">"), + ) + ) + # EDF signal headers are column-major: every label, then every + # transducer, and so on. This is the layout PyHealth's reader expects. + for label, _, _ in channels: + header += _pad(label, 16) + for _ in channels: + header += _pad("synthetic", 80) + for _ in channels: + header += _pad("mV", 8) + for value in ("-1", "1", "-32768", "32767"): + for _ in channels: + header += _pad(value, 8, ">") + for _ in channels: + header += _pad("", 80) + for count in record_samples: + header += _pad(count, 8, ">") + for _ in channels: + header += _pad("", 32) + + data = np.empty((n_records, per_record), dtype=" None: + """Writes a minimal NSRR profusion XML with one stage per epoch.""" + root = ET.Element("CMPStudyConfig") + ET.SubElement(root, "EpochLength").text = str(int(_RECORD_SECONDS)) + sleep_stages = ET.SubElement(root, "SleepStages") + for stage in stages: + ET.SubElement(sleep_stages, "SleepStage").text = str(int(stage)) + ET.indent(root, space=" ") + ET.ElementTree(root).write(path, encoding="utf-8", xml_declaration=True) + + +def _write_nsrr_metadata( + path: Path, + rows: list[dict[str, str]], +) -> None: + """Writes the metadata CSV that NSRRSleepDataset normally builds.""" + frame = pd.DataFrame( + rows, + columns=("patient_id", "visit", "signal_file", "label_file"), + ) + frame.to_csv(path, index=False) + + +def generate_shhs( + output: Path, num_samples: int, epochs: int, seed: int +) -> list[Path]: + """Generates SHHS-shaped EDF, XML, and metadata files.""" + edf_dir = output / "edfs" / "shhs1" + xml_dir = output / "annotations-events-profusion" / "shhs1" + edf_dir.mkdir(parents=True, exist_ok=True) + xml_dir.mkdir(parents=True, exist_ok=True) + + rows: list[dict[str, str]] = [] + files: list[Path] = [] + for index in range(num_samples): + patient_id = f"{200001 + index:06d}" + run_seed = seed + index + ecg, _ = _cardiac_signal(epochs * 125 * 30, 125.0, run_seed, "ecg") + thorax = _respiratory_signal(epochs * 32 * 30, 32.0, run_seed + 1) + abdomen = _respiratory_signal(epochs * 32 * 30, 32.0, run_seed + 2) + + edf_path = edf_dir / f"shhs1-{patient_id}.edf" + _write_edf( + edf_path, + [ + ("ECG", ecg, 125.0), + ("THOR RES", thorax, 32.0), + ("ABDO RES", abdomen, 32.0), + ], + epochs, + ) + stages = _stage_sequence("shhs", epochs, run_seed) + xml_path = xml_dir / f"shhs1-{patient_id}-profusion.xml" + _write_profusion_xml(xml_path, stages) + rows.append( + { + "patient_id": patient_id, + "visit": "shhs1", + "signal_file": str(edf_path.resolve()), + "label_file": str(xml_path.resolve()), + } + ) + files.extend((edf_path, xml_path)) + + _write_nsrr_metadata( + output / "nsrr-shhs-pyhealth.csv", rows + ) + return files + + +def generate_mesa( + output: Path, num_samples: int, epochs: int, seed: int +) -> list[Path]: + """Generates MESA-shaped EDF, XML, and metadata files.""" + edf_dir = output / "edfs" + xml_dir = output / "annotations-events-profusion" + edf_dir.mkdir(parents=True, exist_ok=True) + xml_dir.mkdir(parents=True, exist_ok=True) + + rows: list[dict[str, str]] = [] + files: list[Path] = [] + for index in range(num_samples): + patient_id = f"{1 + index:04d}" + run_seed = seed + index + pleth, _ = _cardiac_signal( + epochs * 256 * 30, 256.0, run_seed, "ppg" + ) + ekg, _ = _cardiac_signal( + epochs * 256 * 30, 256.0, run_seed + 1, "ecg" + ) + thorax = _respiratory_signal(epochs * 32 * 30, 32.0, run_seed + 2) + abdomen = _respiratory_signal(epochs * 32 * 30, 32.0, run_seed + 3) + + edf_path = edf_dir / f"mesa-sleep-{patient_id}.edf" + _write_edf( + edf_path, + [ + ("Pleth", pleth, 256.0), + ("EKG", ekg, 256.0), + ("Thor", thorax, 32.0), + ("Abdo", abdomen, 32.0), + ], + epochs, + ) + stages = _stage_sequence("mesa", epochs, run_seed) + xml_path = ( + xml_dir / f"mesa-sleep-{patient_id}-profusion.xml" + ) + _write_profusion_xml(xml_path, stages) + rows.append( + { + "patient_id": patient_id, + "visit": "mesa", + "signal_file": str(edf_path.resolve()), + "label_file": str(xml_path.resolve()), + } + ) + files.extend((edf_path, xml_path)) + + _write_nsrr_metadata( + output / "nsrr-mesa-pyhealth.csv", rows + ) + return files + + +def _dreamt_frame( + columns: tuple[str, ...], + signal: np.ndarray, + rate: np.ndarray, + stages: list[object], + samples_per_epoch: int, +) -> pd.DataFrame: + """Builds one DREAMT-style frame with mock values in unused columns.""" + n = signal.size + values: dict[str, np.ndarray] = { + column: np.zeros(n, dtype=np.float64) for column in columns + } + values["TIMESTAMP"] = np.arange(n, dtype=np.float64) / ( + samples_per_epoch / _RECORD_SECONDS + ) + values["BVP"] = signal + values["HR"] = rate + values["IBI"] = np.divide( + 60.0, rate, out=np.zeros_like(rate), where=rate > 0 + ) + frame = pd.DataFrame(values, columns=list(columns)) + frame["Sleep_Stage"] = np.repeat( + np.asarray(stages, dtype=object), samples_per_epoch + ) + return frame + + +def generate_dreamt( + output: Path, num_samples: int, epochs: int, seed: int +) -> list[Path]: + """Generates DREAMT-shaped 100 Hz and 64 Hz CSV files.""" + data_100 = output / "data_100Hz" + data_64 = output / "data_64Hz" + data_100.mkdir(parents=True, exist_ok=True) + data_64.mkdir(parents=True, exist_ok=True) + + participant_rows: list[dict[str, object]] = [] + metadata_rows: list[dict[str, object]] = [] + files: list[Path] = [] + for index in range(num_samples): + patient_id = f"S{1 + index:03d}" + run_seed = seed + index + stages = _stage_sequence("dreamt", epochs, run_seed) + + bvp_100, rate_100 = _cardiac_signal( + epochs * 100 * 30, 100.0, run_seed, "ppg" + ) + frame_100 = _dreamt_frame( + _DREAMT_100HZ_COLUMNS, bvp_100, rate_100, stages, 100 * 30 + ) + ecg_100, _ = _cardiac_signal( + epochs * 100 * 30, 100.0, run_seed + 1, "ecg" + ) + frame_100["ECG"] = ecg_100 + frame_100["SAO2"] = 95.0 + frame_100["TEMP"] = 32.0 + frame_100["EDA"] = 1.0 + path_100 = data_100 / f"{patient_id}_PSG_df.csv" + frame_100.to_csv(path_100, index=False, float_format="%.4f") + + bvp_64, rate_64 = _cardiac_signal( + epochs * 64 * 30, 64.0, run_seed + 2, "ppg" + ) + frame_64 = _dreamt_frame( + _DREAMT_64HZ_COLUMNS, bvp_64, rate_64, stages, 64 * 30 + ) + path_64 = data_64 / f"{patient_id}_whole_df.csv" + frame_64.to_csv(path_64, index=False, float_format="%.4f") + + participant_rows.append( + { + "SID": patient_id, + "AGE": 50.0 + index, + "GENDER": "M" if index % 2 == 0 else "F", + "BMI": 25.0 + index, + "OAHI": 5.0 + index, + "AHI": 6.0 + index, + "Mean_SaO2": "95%", + "Arousal Index": 10.0 + index, + "MEDICAL_HISTORY": "None", + "Sleep_Disorders": "None", + } + ) + metadata_rows.append( + { + "patient_id": patient_id, + "age": 50.0 + index, + "gender": "M" if index % 2 == 0 else "F", + "bmi": 25.0 + index, + "oahi": 5.0 + index, + "ahi": 6.0 + index, + "mean_sao2": 95.0, + "arousal_index": 10.0 + index, + "medical_history": "None", + "sleep_disorders": "None", + "file_64hz": str(path_64.resolve()), + "file_100hz": str(path_100.resolve()), + } + ) + files.extend((path_100, path_64)) + + pd.DataFrame(participant_rows).to_csv( + output / "participant_info.csv", index=False + ) + pd.DataFrame(metadata_rows).to_csv( + output / "dreamt-metadata.csv", index=False + ) + return files + + +def _prepare_output( + path: Path, overwrite: bool +) -> Path: + """Creates the destination, optionally replacing existing contents.""" + if path.exists(): + if not path.is_dir(): + raise SystemExit(f"{path} exists and is not a directory") + if any(path.iterdir()): + if not overwrite: + raise SystemExit( + f"{path} is not empty; pass --overwrite to replace it" + ) + shutil.rmtree(path) + path.mkdir(parents=True, exist_ok=True) + return path + + +def main(argv: list[str] | None = None) -> int: + """Generates the requested synthetic dataset tree.""" + args = build_parser().parse_args(argv) + if args.num_samples < 1: + raise SystemExit("--num-samples must be positive") + if args.epochs < 1: + raise SystemExit("--epochs must be positive") + + output = args.output_dir or ( + Path("synthetic_data") / args.dataset + ) + output = _prepare_output(output, args.overwrite) + generators = { + "shhs": generate_shhs, + "mesa": generate_mesa, + "dreamt": generate_dreamt, + } + files = generators[args.dataset]( + output, args.num_samples, args.epochs, args.seed + ) + + print( + f"Generated {args.num_samples} {args.dataset} recording(s) " + f"with {args.epochs} epochs each" + ) + print(f"Output: {output.resolve()}") + print(f"Files: {len(files)}") + print("Run the pipeline with:") + print( + " python examples/watchsleepnet/watchsleepnet_finetune.py " + f"--dataset {args.dataset} --root {output} --epochs 2 " + f"--output-dir {output / 'output'}" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 576e024737..a993731b86 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -112,6 +112,7 @@ def __init__(self, *args, **kwargs): from .abide import ABIDEDataset as ABIDEDataset from .shhs import SHHSDataset from .sleepedf import SleepEDFDataset +from .sleep_accel import SleepAccelDataset as SleepAccelDataset from .nsrr_sleep import NSRRSleepDataset as NSRRSleepDataset from .bmd_hs import BMDHSDataset from .support2 import Support2Dataset diff --git a/pyhealth/datasets/configs/sleep_accel.yaml b/pyhealth/datasets/configs/sleep_accel.yaml new file mode 100644 index 0000000000..823559ebed --- /dev/null +++ b/pyhealth/datasets/configs/sleep_accel.yaml @@ -0,0 +1,12 @@ +version: "1.0" +tables: + sleep_accel: + file_path: "sleep_accel-pyhealth.csv" + patient_id: "patient_id" + timestamp: null + attributes: + - "record_name" + - "heart_rate_file" + - "label_file" + - "motion_file" + - "steps_file" diff --git a/pyhealth/datasets/dreamt.py b/pyhealth/datasets/dreamt.py index 8cab1f26f1..e9f3c49e43 100644 --- a/pyhealth/datasets/dreamt.py +++ b/pyhealth/datasets/dreamt.py @@ -1,13 +1,15 @@ import logging import os from pathlib import Path -from typing import Optional, Union +from typing import Optional, Union import pandas as pd + from pyhealth.datasets import BaseDataset logger = logging.getLogger(__name__) + class DREAMTDataset(BaseDataset): """ Base Dataset for Real-time sleep stage EstimAtion using Multisensor wearable Technology (DREAMT) @@ -109,31 +111,35 @@ def __init__( config_path=config_path ) - def get_patient_file(self, patient_id: str, root: str, file_path: str) -> Union[str | None]: - """ - Returns file path of 64Hz and 100Hz data for a patient, or None if no file found + def get_patient_file( + self, patient_id: str, root: str, file_path: str + ) -> Union[str | None]: + """Returns the 64 Hz or 100 Hz CSV for a patient, or ``None``. Args: - patient_id: patient identifier - root: root directory containing the dataset files - file_path: path to location of 64Hz or 100Hz file - - Returns: - file: path to file location or None if no file found - """ - - if file_path == "data_64Hz" or file_path == "data": - file = Path(root) / f"{file_path}" / f"{patient_id}_whole_df.csv" - - if file_path == "data_100Hz": - file = Path(root) / f"{file_path}" / f"{patient_id}_PSG_df.csv" + patient_id: Patient identifier. + root: Root directory containing the dataset files. + file_path: Folder name for the requested sampling rate. - if not os.path.exists(str(file)): - logger.info(f"{file} not found") - file = None - - return file + Returns: + Absolute path string to the CSV, or ``None`` when the folder or + file is missing. + Examples: + >>> dataset.get_patient_file("S001", root, "data_100Hz") + """ + file = None + if file_path in ("data_64Hz", "data"): + # Original legacy data directory: https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L172 + file = Path(root) / file_path / f"{patient_id}_whole_df.csv" + elif file_path == "data_100Hz": + # Original 100 Hz directory: https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L202 + file = Path(root) / file_path / f"{patient_id}_PSG_df.csv" + + if file is None or not file.exists(): + logger.info("%s not found", file) + return None + return str(file) def prepare_metadata(self, root: str) -> None: """ diff --git a/pyhealth/datasets/sleep_accel.py b/pyhealth/datasets/sleep_accel.py new file mode 100644 index 0000000000..14e5363d78 --- /dev/null +++ b/pyhealth/datasets/sleep_accel.py @@ -0,0 +1,265 @@ +"""PhysioNet Sleep-Accel heart-rate dataset. + +Sleep-Accel contains wrist Apple Watch recordings from 31 subjects during a +night of polysomnography. The dataset ships irregular heart rate in bpm, +three-axis acceleration, step counts and 30 s R&K stage labels. There is no +raw ECG or PPG waveform, so WatchSleepNet IBI features are derived from heart +rate with ``60 / bpm``. + +Layout:: + + / + heart_rate/_heartrate.txt # "," + labels/_labeled_sleep.txt # " " + motion/_acceleration.txt # ",,," + steps/_steps.txt # "," +""" + +import logging +from pathlib import Path + +import numpy as np +import pandas as pd + +from .base_dataset import BaseDataset +from .metadata_csv import ( + metadata_cache_dir, + metadata_csv_exists, + resolve_metadata_root, + write_metadata_csv, +) + +logger = logging.getLogger(__name__) + +_CSV_NAME = "sleep_accel-pyhealth.csv" +_DATASET_KEY = "sleep_accel" + +#: Raw R&K stage codes -> canonical five-class stages. +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation +# /public_datasets/utils.py#L48 +# Original 4 -> 3: +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation +# /public_datasets/utils.py#L49 +# Original 5 -> 4: +SLEEP_ACCEL_STAGE_MAP: dict[int, int] = { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 3, + 5: 4, + -1: -1, +} + + +def load_sleep_accel_stages(path: str | Path) -> tuple[np.ndarray, np.ndarray]: + """Reads one Sleep-Accel scoring file. + + Args: + path: Path to ``_labeled_sleep.txt``. + + Returns: + A pair of arrays containing canonical stages and epoch start times + in seconds relative to polysomnography start. + + Examples: + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... path = Path(tmp) / "1_labeled_sleep.txt" + ... _ = path.write_text("0 0\\n30 5\\n60 -1\\n") + ... stages, starts = load_sleep_accel_stages(path) + >>> stages.tolist(), starts.tolist() + ([0, 4, -1], [0.0, 30.0, 60.0]) + """ + data = np.loadtxt(path, dtype=np.float64, ndmin=2) + starts = data[:, 0].astype(np.float64) + codes = data[:, 1].astype(np.int64) + stages = np.asarray( + [SLEEP_ACCEL_STAGE_MAP.get(int(code), -1) for code in codes], + dtype=np.int64, + ) + return stages, starts + + +def load_sleep_accel_heart_rate( + path: str | Path, + t_start: float | None = None, + t_end: float | None = None, +) -> tuple[np.ndarray, np.ndarray]: + """Reads sorted, de-duplicated heart-rate samples. + + Args: + path: Path to ``_heartrate.txt``. + t_start: Optional inclusive lower time bound in seconds. + t_end: Optional exclusive upper time bound in seconds. + + Returns: + A pair of arrays containing times in seconds and heart rate in bpm. + Non-finite times, non-positive rates and duplicate times are dropped. + + Examples: + >>> import tempfile + >>> with tempfile.TemporaryDirectory() as tmp: + ... path = Path(tmp) / "1_heartrate.txt" + ... _ = path.write_text("5,60\\n0,50\\n5,60\\n") + ... times, bpm = load_sleep_accel_heart_rate(path) + >>> times.tolist(), bpm.tolist() + ([0.0, 5.0], [50.0, 60.0]) + """ + data = np.loadtxt(path, dtype=np.float64, delimiter=",", ndmin=2) + times, bpm = data[:, 0], data[:, 1] + keep = np.isfinite(times) & np.isfinite(bpm) & (bpm > 0) + times, bpm = times[keep], bpm[keep] + order = np.argsort(times, kind="stable") + times, bpm = times[order], bpm[order] + times, first = np.unique(times, return_index=True) + bpm = bpm[first] + if t_start is not None: + mask = times >= t_start + times, bpm = times[mask], bpm[mask] + if t_end is not None: + mask = times < t_end + times, bpm = times[mask], bpm[mask] + return times, bpm + + +class SleepAccelDataset(BaseDataset): + """PyHealth dataset for the PhysioNet Sleep-Accel cohort. + + ``root`` holds one subject directory worth of files in each of the four + modality folders. The dataset writes ``sleep_accel-pyhealth.csv`` on first + use and exposes absolute file paths as event attributes so tasks do not + need the dataset object when reading a recording. + + Args: + root: Directory containing ``heart_rate``, ``labels``, ``motion`` and + ``steps`` subdirectories. + dataset_name: Optional dataset name. Defaults to ``"sleep_accel"``. + config_path: Optional YAML config. Defaults to the bundled config. + cache_dir: Optional PyHealth sample cache directory. + num_workers: Worker count for PyHealth task processing. + dev: If True, limits the event table with PyHealth's dev cache key. + refresh_cache: Rebuild the metadata CSV before fitting. + + Raises: + ValueError: If the root is missing or no usable records are found. + + Examples: + >>> from pyhealth.datasets import SleepAccelDataset + >>> SleepAccelDataset.__name__ + 'SleepAccelDataset' + """ + + def __init__( + self, + root: str, + dataset_name: str | None = None, + config_path: str | None = None, + cache_dir: str | Path | None = None, + num_workers: int = 1, + dev: bool = False, + refresh_cache: bool = False, + ) -> None: + root_path = Path(root).expanduser() + if not root_path.is_dir(): + raise ValueError(f"sleep-accel root is not a directory: {root}") + self.root = str(root_path.resolve()) + if config_path is None: + config_path = Path(__file__).parent / "configs" / "sleep_accel.yaml" + if refresh_cache: + for path in ( + root_path / _CSV_NAME, + metadata_cache_dir(root_path, _DATASET_KEY) / _CSV_NAME, + ): + if path.is_file(): + path.unlink() + if not metadata_csv_exists(root_path, _DATASET_KEY, _CSV_NAME): + self.prepare_metadata(self.root) + super().__init__( + root=resolve_metadata_root(root_path, _DATASET_KEY, _CSV_NAME), + tables=["sleep_accel"], + dataset_name=dataset_name or "sleep_accel", + config_path=config_path, + cache_dir=cache_dir, + num_workers=num_workers, + dev=dev, + ) + + def prepare_metadata(self, root: str) -> str: + """Writes one metadata row per complete Sleep-Accel subject. + + Args: + root: Directory containing the four modality folders. + + Returns: + The path of the written CSV. + + Raises: + ValueError: If no record has all four required files. + """ + root_path = Path(root).resolve() + label_dir = root_path / "labels" + if not label_dir.is_dir(): + raise ValueError(f"missing labels directory under {root}") + rows: list[dict[str, str]] = [] + for label_file in sorted(label_dir.glob("*_labeled_sleep.txt")): + subject_id = label_file.name.split("_", 1)[0] + files = { + "heart_rate_file": root_path + / "heart_rate" + / f"{subject_id}_heartrate.txt", + "label_file": label_file, + "motion_file": root_path + / "motion" + / f"{subject_id}_acceleration.txt", + "steps_file": root_path / "steps" / f"{subject_id}_steps.txt", + } + missing = [name for name, path in files.items() if not path.is_file()] + if missing: + logger.warning( + "Skipping Sleep-Accel subject %s: missing %s", + subject_id, + ", ".join(missing), + ) + continue + try: + stages, starts = load_sleep_accel_stages(files["label_file"]) + heart_times, _ = load_sleep_accel_heart_rate( + files["heart_rate_file"] + ) + except (OSError, ValueError) as err: + logger.warning( + "Skipping Sleep-Accel subject %s: %s", subject_id, err + ) + continue + if stages.size == 0 or np.any(np.diff(starts) < 0): + logger.warning( + "Skipping Sleep-Accel subject %s: empty or unsorted labels", + subject_id, + ) + continue + if heart_times.size == 0: + logger.warning( + "Skipping Sleep-Accel subject %s: no heart-rate samples", + subject_id, + ) + continue + rows.append( + { + "patient_id": subject_id, + "record_name": subject_id, + **{key: str(path) for key, path in files.items()}, + } + ) + if not rows: + raise ValueError(f"no usable sleep-accel records found under {root}") + frame = pd.DataFrame(rows) + path = write_metadata_csv(frame, root_path, _DATASET_KEY, _CSV_NAME) + return str(path) + + @property + def default_task(self): + """Returns a fresh heart-rate-derived IBI staging task.""" + from pyhealth.tasks.sleep_staging_ibi import SleepStagingIBISleepAccel + + return SleepStagingIBISleepAccel() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 74bbc82d27..a54fdac01a 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -200,6 +200,7 @@ load_game_embeddings as load_game_embeddings, normalize_game_code as normalize_game_code, ) +from .watchsleepnet import WatchSleepNet as WatchSleepNet from .medtok import ( MedTokEmbedding as MedTokEmbedding, apply_medtok as apply_medtok, diff --git a/pyhealth/models/watchsleepnet.py b/pyhealth/models/watchsleepnet.py new file mode 100644 index 0000000000..af26e4d12c --- /dev/null +++ b/pyhealth/models/watchsleepnet.py @@ -0,0 +1,714 @@ +"""WatchSleepNet: per-epoch sleep staging from inter-beat-interval sequences. + +Ported from WatchSleepNet; keep in sync with the reference implementation: +https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models +/watchsleepnet.py#L225 + +The optional ``loss`` switch changes only the training objective. Inverse +weights are inferred from the fitted dataset and cached as plain attributes, +so the bare checkpoint state dict stays identical to the reference layout. +""" + +from typing import Any, Literal + +import torch +import torch.nn.functional as F +from torch import nn + +from ..datasets import SampleDataset +from ..processors import LabelProcessor, MultiClassLabelProcessor +from .base_model import BaseModel + +_QUANTIZATION_DTYPES = { + "fp32": torch.float32, + "fp16": torch.float16, + "bf16": torch.bfloat16, +} +_LOSS_MODES = ("ce", "weighted_ce", "focal", "inverse_focal") + + +def _inverse_frequency_weights(counts: torch.Tensor) -> torch.Tensor: + """Returns inverse-frequency class weights with a mean of one.""" + present = counts > 0 + weights = torch.zeros_like(counts) + if bool(present.any()): + weights[present] = counts.sum() / ( + present.sum().to(dtype=counts.dtype) * counts[present] + ) + return weights + + +class _ResBlock(nn.Module): + """Reference ResBlock (ported verbatim; keep in sync).""" + + def __init__(self, in_channels: int, out_channels: int, stride: int = 1): + super().__init__() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L8 + self.conv1 = nn.Conv1d( + in_channels, + out_channels, + kernel_size=3, + stride=stride, + padding=1, + bias=False, + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L16 + self.bn1 = nn.BatchNorm1d(out_channels) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L17 + self.relu1 = nn.ReLU(inplace=True) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L18 + self.dropout1 = nn.Dropout(0.2) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L20 + self.conv2 = nn.Conv1d( + out_channels, + out_channels, + kernel_size=3, + stride=1, + padding=1, + bias=False, + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L28 + self.bn2 = nn.BatchNorm1d(out_channels) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L29 + self.relu2 = nn.ReLU(inplace=True) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L30 + self.dropout2 = nn.Dropout(0.2) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L32 + self.downsample = nn.Sequential() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L33 + if stride != 1 or in_channels != out_channels: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L34 + self.downsample = nn.Sequential( + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L35 + nn.Conv1d( + in_channels, out_channels, kernel_size=1, stride=stride, bias=False + ), + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L38 + nn.BatchNorm1d(out_channels), + ) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L42 + residual = self.downsample(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L43 + x = self.conv1(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L44 + # BN -> ReLU -> dropout: + x = self.dropout1(self.relu1(self.bn1(x))) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L47 + x = self.conv2(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L48 + # BN -> ReLU -> dropout: + x = self.dropout2(self.relu2(self.bn2(x))) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L51 + return x + residual + + +class _DeepFeatureExtractor(nn.Module): + """Reference per-epoch feature extractor (ported; keep in sync).""" + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L56 + def __init__(self, initial_channels: int = 1): + super().__init__() + layers: list[nn.Module] = [ + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L64 + nn.Conv1d(initial_channels, 16, kernel_size=7, stride=1, padding=3), + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L70 + nn.ReLU(inplace=True), + ] + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L71 + current_channels = 16 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L73 + for i in range(4): + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L74 + out_channels = 32 * (2**i) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L73 + # Four stride-4 ResBlocks: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L76 + layers.append(_ResBlock(current_channels, out_channels, stride=4)) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L77 + current_channels = out_channels + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L79 + self.layers = nn.Sequential(*layers) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L80 + self.final_conv = nn.Conv1d(256, 256, kernel_size=3, stride=4) + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L82 + def forward(self, x: torch.Tensor) -> torch.Tensor: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L83 + for layer in self.layers: + x = layer(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L86 + # Final convolution: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L88 + # Flatten to 256 features: + return self.final_conv(x).view(x.size(0), -1) + + +class _DeepTCNBlock(nn.Module): + """Reference dilated TCN (ported verbatim; keep in sync).""" + + def __init__( + self, + in_channels: int, + out_channels: int, + kernel_size: int, + num_layers: int, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L93 + ): + super().__init__() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L95 + self.layers = nn.ModuleList() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L96 + current_channels = in_channels + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L97 + dilation = 1 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L99 + for _ in range(num_layers): + self.layers.append( + nn.Sequential( + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L102 + nn.Conv1d( + current_channels, + out_channels, + kernel_size, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L106 + padding=(kernel_size - 1) * dilation // 2, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L107 + dilation=dilation, + ), + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L109 + nn.BatchNorm1d(out_channels), + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L110 + nn.ReLU(), + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /modeling/models/watchsleepnet.py#L111 + nn.Dropout(0.2), + ) + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L114 + current_channels = out_channels + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L115 + dilation *= 2 + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L117 + def forward(self, x: torch.Tensor) -> torch.Tensor: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L118 + for layer in self.layers: + x = layer(x) + return x + + +class _LSTMLayer(nn.Module): + """Reference BiLSTM layer with optional self-attention (ported).""" + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L123 + # Attention variant: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L185 + # No-attention variant: + + def __init__( + self, + input_size: int, + hidden_size: int, + num_heads: int, + num_layers: int, + use_attention: bool, + ): + super().__init__() + self.use_attention = use_attention + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L134 + self.lstm = nn.LSTM( + input_size, + hidden_size, + num_layers, + batch_first=True, + bidirectional=True, + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L142 + feature_size = hidden_size * 2 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L252 + if use_attention: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L143 + self.attention = nn.MultiheadAttention( + feature_size, num_heads, batch_first=True + ) + + def forward( + self, x: torch.Tensor, lengths: torch.Tensor + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L147 + ) -> tuple[torch.Tensor, torch.Tensor | None]: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L148 + # Packing needs CPU int64 lengths: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L155 + lengths_cpu = lengths.detach().to(device="cpu", dtype=torch.int64) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L158 + packed = nn.utils.rnn.pack_padded_sequence( + x, lengths_cpu, batch_first=True, enforce_sorted=False + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L163 + output, _ = self.lstm(packed) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L166 + output, _ = nn.utils.rnn.pad_packed_sequence(output, batch_first=True) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L222 + weights = None + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L179 + if self.use_attention: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L173 + # Ignore positions beyond each night's true length: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L172 + max_seq_len = output.size(1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L173 + key_padding_mask = torch.arange( + max_seq_len, device=output.device + ).unsqueeze(0) >= lengths.to(output.device).unsqueeze(1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L179 + output, weights = self.attention( + output, output, output, key_padding_mask=key_padding_mask + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L182 + return output, weights + + +class WatchSleepNet(BaseModel): + """WatchSleepNet for per-epoch sleep staging of IBI sequences. + + This is a simplified PyHealth port of the paper's model. The convolution, + TCN, BiLSTM, attention, and classifier math matches the reference, while + the forward method consumes PyHealth batches and handles padding, unknown + labels, and low-precision dtypes. The model expects one ``"signal"`` + feature of shape ``(epochs, 750)`` per sample and a matching ``"label"`` + tensor; batches may have shape ``(batch, epochs, 750)`` or + ``(batch, 750)`` for a single epoch per sample. An optional raw + ``"lengths"`` field overrides lengths inferred from trailing zero rows. + + Checkpoints are bare state dictionaries, identical in layout to the + reference checkpoint, so ``Trainer.save_ckpt`` / ``load_ckpt`` work with + original ``.pt`` files. + + Args: + dataset: The fitted :class:`~pyhealth.datasets.SampleDataset`. + n_classes: Number of output classes. Default is 3 (W / N / R). + num_channels: TCN output width. Default is 256. + kernel_size: TCN convolution kernel. Default is 5. + hidden_dim: Hidden size of each BiLSTM direction. Default is 256. + num_heads: Self-attention heads. Default is 16. + num_layers: Number of stacked BiLSTM layers. Default is 4. + tcn_layers: Number of dilated TCN blocks. Default is 3. + use_tcn: Whether to apply the TCN. Default is True. + use_attention: Whether to apply self-attention. Default is True. + quantization: Compute dtype, one of ``"fp32"``, ``"fp16"``, or + ``"bf16"``. Default is ``"fp32"``. Logits are upcast to float32 + for loss and probabilities. + loss: Training objective. ``"ce"`` is the paper's reference default. + ``"weighted_ce"`` is cross-entropy with inverse-frequency class + weights; ``"focal"`` is gamma-2 focal loss; ``"inverse_focal"`` + adds inverse-frequency alpha weights. Default is ``"ce"``. + + Examples: + >>> import numpy as np + >>> import torch + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import WatchSleepNet + >>> samples = [ + ... { + ... "patient_id": str(i), + ... "signal": np.random.randn(3, 750).astype("float32"), + ... "label": np.array([0, 1, 2]), + ... "lengths": 3, + ... } + ... for i in range(2) + ... ] + >>> dataset = create_sample_dataset( + ... samples=samples, + ... input_schema={"signal": "tensor", "lengths": "raw"}, + ... output_schema={"label": ("tensor", {"dtype": torch.long})}, + ... ) + >>> model = WatchSleepNet(dataset, hidden_dim=8, num_heads=2, + ... num_channels=8, num_layers=1, tcn_layers=1) + >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) + >>> out = model(**batch) + >>> out["logit"].shape + torch.Size([2, 3, 3]) + >>> weighted = WatchSleepNet( + ... dataset, hidden_dim=8, num_heads=2, num_channels=8, + ... num_layers=1, tcn_layers=1, loss="weighted_ce" + ... ) + >>> weighted.loss + 'weighted_ce' + >>> set(model.state_dict()) == set(weighted.state_dict()) + True + """ + + def __init__( + self, + dataset: SampleDataset, + n_classes: int = 3, + num_channels: int = 256, + kernel_size: int = 5, + hidden_dim: int = 256, + num_heads: int = 16, + num_layers: int = 4, + tcn_layers: int = 3, + use_tcn: bool = True, + use_attention: bool = True, + quantization: Literal["fp32", "fp16", "bf16"] = "fp32", + loss: Literal["ce", "weighted_ce", "focal", "inverse_focal"] = "ce", + ): + super().__init__(dataset=dataset) + # Keep the state dict identical to the reference bare checkpoint. + del self._dummy_param + if "signal" not in self.feature_keys or any( + key not in {"signal", "lengths"} for key in self.feature_keys + ): + raise ValueError( + "WatchSleepNet needs a 'signal' feature and an optional raw " + f"'lengths' field, got inputs {self.feature_keys}." + ) + if len(self.label_keys) != 1 or self.label_keys[0] != "label": + raise ValueError( + "WatchSleepNet needs exactly one 'label' target, got " + f"{self.label_keys}." + ) + for name, value in ( + ("n_classes", n_classes), + ("num_channels", num_channels), + ("kernel_size", kernel_size), + ("hidden_dim", hidden_dim), + ("num_heads", num_heads), + ("num_layers", num_layers), + ("tcn_layers", tcn_layers), + ): + if value < 1: + raise ValueError(f"{name} must be positive, got {value}.") + if n_classes < 2: + raise ValueError(f"n_classes must be at least 2, got {n_classes}.") + if hidden_dim % num_heads != 0: + raise ValueError( + f"hidden_dim ({hidden_dim}) must be divisible by num_heads " + f"({num_heads})." + ) + if quantization not in _QUANTIZATION_DTYPES: + raise ValueError( + f"quantization must be one of {sorted(_QUANTIZATION_DTYPES)}, " + f"got {quantization!r}." + ) + if loss not in _LOSS_MODES: + raise ValueError(f"loss must be one of {_LOSS_MODES}, got {loss!r}.") + + self.feature_key = "signal" + self.label_key = "label" + self.n_classes = n_classes + self.quantization = quantization + self.loss = loss + self._class_counts: torch.Tensor | None = None + self._weight_cache: dict[tuple[torch.device, torch.dtype], torch.Tensor] = {} + self._label_processor = MultiClassLabelProcessor(labels=n_classes) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L240 + self.use_tcn = use_tcn + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L251 + self.use_attention = use_attention + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L242 + self.feature_extractor = _DeepFeatureExtractor(initial_channels=1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L243 + feature_dim = 256 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L245 + if use_tcn: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L246 + self.tcn = _DeepTCNBlock(feature_dim, num_channels, kernel_size, tcn_layers) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L247 + lstm_input_dim = num_channels + else: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L249 + lstm_input_dim = feature_dim + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L253 + # Attention variant: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L262 + # Plain-LSTM variant: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L253 + self.lstm_layer = _LSTMLayer( + input_size=lstm_input_dim, + hidden_size=hidden_dim, + num_heads=num_heads, + num_layers=num_layers, + use_attention=use_attention, + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L271 + self.classifier = nn.Linear(hidden_dim * 2, n_classes) + # No capability checks: PyTorch reports unsupported dtype/device combinations. + self.to(dtype=_QUANTIZATION_DTYPES[quantization]) + + @property + def device(self) -> torch.device: + """Returns the device of the model parameters.""" + return self.classifier.weight.device + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """Exposes the flattened per-epoch multiclass label to the Trainer.""" + return {self.label_key: self._label_processor} + + forward_from_embedding = None + + def _resolve_class_counts(self) -> torch.Tensor: + """Counts valid training labels once for weighted loss presets.""" + if self._class_counts is not None: + return self._class_counts + counts = torch.zeros(self.n_classes, dtype=torch.float32) + for sample in self.dataset: + values = sample.get(self.label_key) if hasattr(sample, "get") else None + if values is None: + continue + labels = torch.as_tensor(values).detach().reshape(-1) + valid = (labels >= 0) & (labels < self.n_classes) + if bool(valid.any()): + binned = torch.bincount( + labels[valid].to(device=counts.device, dtype=torch.int64), + minlength=self.n_classes, + ) + counts += binned[:self.n_classes].to(dtype=counts.dtype) + if counts.sum() == 0: + raise ValueError( + f"loss={self.loss!r} needs labeled samples to infer class weights" + ) + self._class_counts = counts + return counts + + def _loss_weights(self, logits: torch.Tensor) -> torch.Tensor | None: + """Returns cached inverse-frequency weights for weighted presets.""" + if self.loss not in ("weighted_ce", "inverse_focal"): + return None + device, dtype = logits.device, logits.dtype + weights = self._weight_cache.get((device, dtype)) + if weights is None: + weights = _inverse_frequency_weights(self._resolve_class_counts()).to( + device=device, dtype=dtype + ) + self._weight_cache[(device, dtype)] = weights + return weights + + def _training_loss( + self, logits: torch.Tensor, targets: torch.Tensor + ) -> torch.Tensor: + """Computes the configured loss over valid, flattened epochs.""" + if self.loss == "ce": + return self._label_processor.loss(logits, targets) + weights = self._loss_weights(logits) + if self.loss == "weighted_ce": + return F.cross_entropy(logits, targets, weight=weights) + ce = F.cross_entropy(logits, targets, reduction="none") + pt = torch.exp(-ce).clamp(max=1.0) + loss = (1.0 - pt) ** 2.0 * ce + if weights is not None: + loss = loss * weights[targets] + return loss.mean() + + @staticmethod + def _resolve_lengths( + signal: torch.Tensor, value: Any, batch_size: int, seq_len: int + ) -> torch.Tensor: + if value is None: + if seq_len == 1 or signal.ndim == 2: + return torch.full((batch_size,), 1, dtype=torch.int64) + nonzero = signal.detach().abs().sum(dim=-1) != 0 + trailing = nonzero.flip(dims=[1]).int().argmax(dim=1) + lengths = torch.where( + nonzero.any(dim=1), seq_len - trailing, torch.ones_like(trailing) + ) + elif isinstance(value, torch.Tensor): + lengths = value.reshape(-1) + elif isinstance(value, (list, tuple)): + values = [ + int(v) if not isinstance(v, torch.Tensor) else int(v.item()) + for v in value + ] + lengths = torch.as_tensor(values) + else: + lengths = torch.full((batch_size,), int(value)) + return lengths.to(dtype=torch.int64).clamp(min=1, max=seq_len) + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L273 + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Runs WatchSleepNet and returns masked, flattened multiclass outputs. + + The returned ``logit`` has shape ``(batch, epochs, n_classes)``; + ``y_prob`` and ``y_true`` are flattened over valid, non-padded epochs + only so that PyHealth's Trainer scores exactly those positions. + + Returns: + A dict with ``loss``, ``logit``, ``y_prob``, and ``y_true``. + """ + signal = kwargs[self.feature_key] + if not isinstance(signal, torch.Tensor): + signal = torch.as_tensor(signal) + dtype = self.classifier.weight.dtype + signal = signal.to(device=self.device, dtype=dtype) + if signal.ndim == 2: + signal = signal.unsqueeze(1) + if signal.ndim != 3: + raise ValueError( + f"'{self.feature_key}' must have shape (batch, epochs, 750) or " + f"(batch, 750), got {tuple(signal.shape)}." + ) + if signal.size(-1) != 750: + raise ValueError( + f"WatchSleepNet needs 750 samples per epoch, got {signal.size(-1)}." + ) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L274 + batch_size, seq_len, _ = signal.shape + lengths = self._resolve_lengths( + signal, kwargs.get("lengths"), batch_size, seq_len + ) + + labels = kwargs[self.label_key] + if not isinstance(labels, torch.Tensor): + labels = torch.as_tensor(labels) + labels = labels.to(device=self.device, dtype=torch.long) + if labels.ndim == 1 and seq_len == 1: + labels = labels.unsqueeze(1) + labels = labels[:, :seq_len] + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L277 + x = signal.reshape(batch_size * seq_len, 1, -1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L278 + x = self.feature_extractor(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L279 + x = x.view(batch_size, seq_len, -1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L282 + if self.use_tcn: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L283 + x = x.permute(0, 2, 1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L284 + x = self.tcn(x) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /models/watchsleepnet.py#L285 + x = x.permute(0, 2, 1).contiguous() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L288 + x, _ = self.lstm_layer(x, lengths) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling/models + # /watchsleepnet.py#L291 + logits = self.classifier(x) + if logits.size(1) < seq_len: + # pad_packed_sequence returns max(lengths); restore the batch grid. + logits = F.pad(logits, (0, 0, 0, seq_len - logits.size(1))) + logits = logits[:, :seq_len, :].to(torch.float32) + + epoch_index = torch.arange(seq_len, device=self.device).unsqueeze(0) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /engine.py#L266 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /config.py#L142 + valid = (epoch_index < lengths.to(self.device).unsqueeze(1)) & (labels >= 0) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /engine.py#L271 + flat_logits = logits.reshape(-1, self.n_classes) + flat_valid = valid.reshape(-1) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /engine.py#L272 + y_true = labels.reshape(-1)[flat_valid] + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /engine.py#L276 + y_prob = self._label_processor.activation(flat_logits)[flat_valid] + if y_true.numel(): + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /engine.py#L319 + loss = self._training_loss(flat_logits[flat_valid], y_true) + else: + loss = flat_logits.sum() * 0 + return { + "loss": loss, + "logit": logits, + "y_prob": y_prob, + "y_true": y_true, + } + + +WatchSleepNet.forward_from_embedding = WatchSleepNet.forward diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 313f13d7a7..12235e64d5 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -283,6 +283,13 @@ ) from .sleep_staging_v2 import SleepStagingSleepEDF from .sleep_staging_nsrr import SleepStagingCardioRespiratory # noqa: F401 +from .sleep_staging_ibi import ( + SleepStagingIBIDREAMT as SleepStagingIBIDREAMT, + SleepStagingIBIISRUC as SleepStagingIBIISRUC, + SleepStagingIBISHHS as SleepStagingIBISHHS, + SleepStagingIBIMESA as SleepStagingIBIMESA, + SleepStagingIBISleepAccel as SleepStagingIBISleepAccel, +) from .sleep_staging_isruc import SleepStagingISRUC as SleepStagingISRUC from .sleep_staging_isruc import ( SleepStagingSequenceISRUC as SleepStagingSequenceISRUC, diff --git a/pyhealth/tasks/sleep_staging_ibi.py b/pyhealth/tasks/sleep_staging_ibi.py new file mode 100644 index 0000000000..4e4fd34760 --- /dev/null +++ b/pyhealth/tasks/sleep_staging_ibi.py @@ -0,0 +1,1566 @@ +"""Per-recording inter-beat-interval (IBI) sleep-staging tasks. + +The tasks in this module turn 30 s waveform epochs into a fixed-size IBI +sequence with shape ``(T, points_per_epoch)``. Each row is derived by detecting +beats in a waveform epoch, expanding the beat intervals with sample-and-hold, +and striding (or resampling) to ``points_per_epoch`` samples. Labels are +retrieved as three classes with ``-1`` reserved for unknown epochs: + +.. code-block:: text + + W -> 0, N1/N2/N3/N4 -> 1, R/REM -> 2, unknown -> -1 + +No NPZ cache, custom task cache, feature processor, or class-remapping +machinery is involved; the tasks emit the final tensors directly. + +Examples: + >>> task = SleepStagingIBIDREAMT() + >>> task.task_name + 'SleepStagingIBIDREAMT' +""" + +import logging +import warnings +import xml.etree.ElementTree as ET +from collections.abc import Sequence +from fractions import Fraction +from itertools import pairwise +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd +import torch +from scipy.signal import detrend, find_peaks, resample, resample_poly + +from pyhealth.tasks.base_task import BaseTask +from pyhealth.tasks.sleep_staging_nsrr import ( + CHANNEL_ALIASES, + LABEL_SCHEMES, + _read_edf_channels, + _read_stage_codes, +) + +logger = logging.getLogger(__name__) + +#: NSRR profusion codes -> canonical five-class stages. +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation +# /public_datasets/utils.py#L48 +# Original 4 -> 3: +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation +# /public_datasets/utils.py#L49 +# Original 5 -> 4: +PROFUSION_STAGE_MAP: dict[int, int] = LABEL_SCHEMES["five_class"] + +#: Canonical five-class stages -> retrieved three-class labels. +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling +# /data_setup.py#L85 +# Original three-class map: +CANONICAL_TO_THREE: dict[int, int] = {0: 0, 1: 1, 2: 1, 3: 1, 4: 2, -1: -1} + +_AASM_STRING_MAP: dict[str, int] = { + "W": 0, + "WAKE": 0, + "N1": 1, + "N2": 2, + "N3": 3, + "N4": 3, + "R": 4, + "REM": 4, + "MISSING": -1, + "UNKNOWN": -1, +} + +_RK_STRING_MAP: dict[str, int] = { + "W": 0, + "WAKE": 0, + "S1": 1, + "N1": 1, + "S2": 2, + "N2": 2, + "S3": 3, + "N3": 3, + "S4": 3, + "N4": 3, + "REM": 4, + "R": 4, + "MISSING": -1, + "UNKNOWN": -1, +} + +_PEAK_BACKENDS = ("auto", "scipy", "neurokit", "biosppy") + +#: ISRUC channel names that carry ECG in the released recordings. +_ISRUC_ECG_CHANNELS = ( + "X2", + "ECG II", + "ECG I", + "ECG", + "EKG II", + "EKG I", + "EKG", +) + +#: ISRUC score codes -> canonical five-class stages. +_ISRUC_SCORE_MAP = {0: 0, 1: 1, 2: 2, 3: 3, 5: 4, -1: -1} + +#: DREAMT sleep-stage strings mapped to canonical five-class integers. +# Original stage map: +# https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation +# /dreamt/dreamt_extract_ibi_se.py#L42 +DREAMT_STAGE_MAPPING: dict[str, int] = { + "W": 0, + "N1": 1, + "N2": 2, + "N3": 3, + "R": 4, + "Missing": -1, +} + + +def map_dreamt_stages(values: Any) -> np.ndarray: + """Maps DREAMT sleep stages to canonical integers. + + Args: + values: Iterable of stage strings or already-numeric stages. + + Returns: + ``int64`` array. ``"Missing"``, unrecognized tokens such as ``"P"``, + and out-of-range numbers become ``-1``. + + Examples: + >>> map_dreamt_stages(["W", "N3", "Missing", "P"]).tolist() + [0, 3, -1, -1] + """ + values = list(values) + if values and isinstance(values[0], str): + # Original unknown-stage fallback: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L43 + return np.asarray( + [DREAMT_STAGE_MAPPING.get(str(v).strip(), -1) for v in values], + dtype=np.int64, + ) + return np.asarray(values, dtype=np.int64) + + +def load_dreamt_frame( + file_path: str, + # Original wearable channel: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L183 + signal_cols: tuple[str, ...] = ("BVP",), + epoch_duration: float = 30.0, +) -> pd.DataFrame: + """Reads the signal and stage columns of one DREAMT recording. + + The frame is returned at its native sampling rate; epoch construction and + IBI extraction belong to the task layer. Non-finite signal samples are + preserved so the task can interpolate them consistently. + + Args: + file_path: Path to ``*_whole_df.csv`` or ``*_PSG_df.csv``. + signal_cols: Waveform columns to read. Defaults to ``BVP``, the + reference DREAMT wearable channel. + epoch_duration: Epoch length in seconds, used only for validation. + + Returns: + DataFrame containing the requested signal columns and a canonical + integer ``Sleep_Stage`` column. + + Raises: + FileNotFoundError: If ``file_path`` does not exist. + ValueError: If no signal column or no stage column is present, or if + ``epoch_duration`` is not positive. + + Examples: + >>> frame = load_dreamt_frame("S001_PSG_df.csv", ("BVP",)) # doctest: +SKIP + """ + if epoch_duration <= 0: + raise ValueError("epoch_duration must be positive") + path = Path(file_path) + if not path.is_file(): + raise FileNotFoundError(str(path)) + header = pd.read_csv(path, nrows=0) + wanted = [col for col in signal_cols if col in header.columns] + if not wanted: + raise ValueError(f"none of {signal_cols} found in {path}") + if "Sleep_Stage" not in header.columns: + raise ValueError(f"Sleep_Stage not found in {path}") + frame = pd.read_csv(path, usecols=[*wanted, "Sleep_Stage"]) + for col in wanted: + frame[col] = pd.to_numeric(frame[col], errors="coerce").astype(np.float64) + # Original Sleep_Stage column: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L35 + frame["Sleep_Stage"] = map_dreamt_stages(frame["Sleep_Stage"].values) + return frame + + +def _edf_transducer_labels(path: str | Path) -> list[str]: + """Returns the per-channel EDF transducer labels without reading data. + + Some ISRUC exports label the ECG channel numerically (for example ``25``) + rather than with a name such as ``X2``. In those recordings the EDF + ``transducer`` header field is authoritative: the ECG channel is marked + ``EKG_Channel``. + + Args: + path: Path to the EDF/``.rec`` recording. + + Returns: + One transducer label per EDF signal, in channel order. + + Raises: + ValueError: If the file does not have a valid EDF header. + """ + with open(path, "rb") as file: + head = file.read(256) + if len(head) < 256 or not head[:8].startswith(b"0"): + raise ValueError(f"{path} is not a valid EDF file") + n_signals = int(head[252:256]) + fields = file.read(n_signals * 96) + if n_signals <= 0 or len(fields) < n_signals * 96: + raise ValueError(f"{path} has an invalid EDF header") + return [ + fields[n_signals * 16 + i * 80 : n_signals * 16 + (i + 1) * 80] + .decode("ascii", "ignore") + .strip() + for i in range(n_signals) + ] + + +def _clean_signal(waveform: Sequence[float]) -> np.ndarray: + """Interpolates non-finite samples in a 1-D waveform. + + Args: + waveform: One-dimensional signal samples. + + Returns: + Float64 array with no NaN or infinite values. An all-non-finite input + becomes an all-zero array. + + Examples: + >>> _clean_signal([0.0, np.nan, 2.0]).tolist() + [0.0, 1.0, 2.0] + """ + signal = np.asarray(waveform, dtype=np.float64).reshape(-1) + if signal.size == 0: + return signal + good = np.isfinite(signal) + if good.all(): + return signal + if not good.any(): + return np.zeros_like(signal) + x = np.arange(signal.size) + return np.interp(x, x[good], signal[good]).astype(np.float64) + + +def _peaks_to_ibi( + peaks: Sequence[int], + fs: float, + max_ibi: float, + length: int | None = None, +) -> np.ndarray: + """Expands beat positions into a sample-and-hold IBI signal. + + Args: + peaks: Beat sample indices. + fs: Sampling rate in Hz. + max_ibi: Intervals at or above this many seconds become zero. + length: Desired output length. Defaults to the last peak plus one. + + Returns: + Float64 IBI array of shape ``(length,)``. Fewer than two in-range + peaks yields an all-zero array. + + Examples: + >>> _peaks_to_ibi([0, 100, 250], 100, 2.0, 300)[:2].tolist() + [1.0, 1.0] + """ + if fs <= 0: + raise ValueError("fs must be positive") + if max_ibi <= 0: + raise ValueError("max_ibi must be positive") + peak_array = np.asarray(peaks, dtype=np.int64).reshape(-1) + out_len = int(length) if length is not None else ( + int(peak_array[-1]) + 1 if peak_array.size else 0 + ) + ibi = np.zeros(max(out_len, 0), dtype=np.float64) + in_range = peak_array[(peak_array >= 0) & (peak_array < ibi.size)] + if in_range.size < 2: + return ibi + in_range = np.sort(in_range) + for start, end in pairwise(in_range): + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L24 + # Original np.diff(peaks) / fs: + interval = float(end - start) / float(fs) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L34 + # Original 2 s outlier zeroing: + if end > start and interval < max_ibi: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L31 + # Original sample-and-hold fill: + ibi[int(start) : int(end)] = interval + return ibi + + +def _beat_annotations_to_ibi( + samples: Sequence[int], + fs: float, + max_ibi: float, + length: int | None = None, +) -> np.ndarray: + """Builds an IBI signal from externally supplied beat annotations. + + Args: + samples: Annotated beat sample indices. + fs: Sampling rate in Hz. + max_ibi: Intervals at or above this many seconds become zero. + length: Desired output length. + + Returns: + Float64 sample-and-hold IBI array. + + Examples: + >>> float(_beat_annotations_to_ibi([0, 50], 50, 2.0, 60)[0]) + 1.0 + """ + return _peaks_to_ibi(samples, fs, max_ibi, length) + + +def _heart_rate_to_ibi( + times: Sequence[float], + bpm: Sequence[float], + max_ibi: float = 2.0, + length: int | None = None, +) -> np.ndarray: + """Interpolates instantaneous heart rate into an IBI signal. + + Args: + times: Heart-rate sample times in seconds. + bpm: Heart rate in beats per minute at each time. + max_ibi: Intervals at or above this many seconds become zero. + length: Optional output length; defaults to the time span at the + median heart-rate sample rate. + + Returns: + Float64 IBI array with one value per output sample. + + Examples: + >>> _heart_rate_to_ibi([0.0, 1.0], [60.0, 60.0], 2.0).tolist() + [1.0, 1.0] + """ + time_array = np.asarray(times, dtype=np.float64).reshape(-1) + rate_array = np.asarray(bpm, dtype=np.float64).reshape(-1) + if time_array.size != rate_array.size: + raise ValueError("times and bpm must have the same length") + if time_array.size < 2: + out_len = int(length) if length is not None else 0 + return np.zeros(max(out_len, 0), dtype=np.float64) + + order = np.argsort(time_array) + time_array, rate_array = time_array[order], rate_array[order] + with np.errstate(divide="ignore", invalid="ignore"): + values = np.where(rate_array > 0, 60.0 / rate_array, 0.0) + values[~np.isfinite(values)] = 0.0 + values[values >= max_ibi] = 0.0 + + deltas = np.diff(time_array) + deltas = deltas[deltas > 0] + fs = 1.0 / float(np.median(deltas)) if deltas.size else 1.0 + span = float(time_array[-1] - time_array[0]) + out_len = int(length) if length is not None else max(int(span * fs) + 1, 2) + out_times = np.arange(out_len, dtype=np.float64) / fs + ibi = np.interp(out_times, time_array - time_array[0], values) + ibi[ibi >= max_ibi] = 0.0 + return ibi.astype(np.float64) + + +def _heart_rate_to_grid( + times: Sequence[float], + bpm: Sequence[float], + points: int, + epoch_seconds: float, + max_ibi: float = 2.0, + min_ibi: float = 0.3, +) -> np.ndarray: + """Interpolates ``60 / bpm`` onto one fixed-size epoch grid. + + Args: + times: Heart-rate times relative to the epoch start, in seconds. + bpm: Heart rate in beats per minute at each time. + points: Number of samples in the returned IBI row. + epoch_seconds: Epoch duration in seconds. + max_ibi: Intervals at or above this many seconds become zero. + min_ibi: Intervals below this many seconds become zero. + + Returns: + Float32 IBI row of shape ``(points,)``. Values outside the observed + heart-rate span and outside ``[min_ibi, max_ibi)`` are zero. + + Examples: + >>> row = _heart_rate_to_grid([0.0, 30.0], [60.0, 60.0], 4, 30.0) + >>> row.tolist() + [1.0, 1.0, 1.0, 1.0] + """ + time_array = np.asarray(times, dtype=np.float64).reshape(-1) + rate_array = np.asarray(bpm, dtype=np.float64).reshape(-1) + zeros = np.zeros(max(int(points), 0), dtype=np.float32) + if time_array.size != rate_array.size or time_array.size < 2: + return zeros + finite = np.isfinite(time_array) & np.isfinite(rate_array) & (rate_array > 0) + time_array, rate_array = time_array[finite], rate_array[finite] + if time_array.size < 2: + return zeros + order = np.argsort(time_array, kind="stable") + time_array, rate_array = time_array[order], rate_array[order] + time_array, first = np.unique(time_array, return_index=True) + rate_array = rate_array[first] + with np.errstate(divide="ignore", invalid="ignore"): + values = 60.0 / rate_array + values[~np.isfinite(values)] = 0.0 + values[(values < min_ibi) | (values >= max_ibi)] = 0.0 + rate = points / epoch_seconds + grid = np.arange(int(points), dtype=np.float64) / rate + ibi = np.interp(grid, time_array, values) + outside = (grid < time_array[0]) | (grid > time_array[-1]) + ibi[outside] = 0.0 + return ibi.astype(np.float32) + + +def _resample_rows(signal: np.ndarray, points: int) -> np.ndarray: + """Resamples each row of a 2-D array to ``points`` columns.""" + signal = np.asarray(signal, dtype=np.float64) + if signal.shape[1] == points: + return signal + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation + # /public_datasets/extract_and_save_ibi.py#L128 + # Original resample_poly fallback: + ratio = Fraction(points, signal.shape[1]) + return resample_poly( + signal, ratio.numerator, ratio.denominator, axis=1 + ).astype(np.float64) + + +def _ibi_to_epoch_grid( + ibi: Sequence[float], + epoch_seconds: float, + points_per_epoch: int, + n_epochs: int, + downsample_factor: int | None = None, +) -> np.ndarray: + """Reshapes an IBI signal into one fixed-size row per epoch. + + An integer stride is used when ``downsample_factor`` divides the source + epoch length exactly into ``points_per_epoch``; otherwise each epoch is + resampled to ``points_per_epoch`` samples. + + Args: + ibi: Continuous IBI samples at the source sampling rate. + epoch_seconds: Seconds per epoch. + points_per_epoch: Target number of samples per epoch. + n_epochs: Number of epochs to emit. + downsample_factor: Optional integer stride. + + Returns: + Float32 array of shape ``(n_epochs, points_per_epoch)``. + + Examples: + >>> ibi = np.ones(4 * 100) + >>> _ibi_to_epoch_grid(ibi, 30.0, 100, 4, 1).shape + (4, 100) + """ + samples = np.asarray(ibi, dtype=np.float64).reshape(-1) + if n_epochs <= 0: + return np.zeros((0, points_per_epoch), dtype=np.float32) + if samples.size < n_epochs: + raise ValueError("IBI signal is shorter than n_epochs") + native = samples.size // n_epochs + if native <= 0: + raise ValueError("IBI signal is too short for the requested epochs") + epochs = samples[: n_epochs * native].reshape(n_epochs, native) + if ( + downsample_factor is not None + and downsample_factor > 1 + and native % downsample_factor == 0 + and native // downsample_factor == points_per_epoch + ): + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L124 + # Original integer-stride decimation: + grid = epochs[:, ::downsample_factor] + else: + grid = _resample_rows(epochs, points_per_epoch) + return grid.astype(np.float32) + + +def _stage_to_canonical(stage: Any, scheme: str = "aasm") -> int: + """Maps a stage label to the canonical five-class space. + + Args: + stage: String or integer stage label. + scheme: ``"aasm"`` or ``"rk"`` string vocabulary. + + Returns: + Canonical stage in ``{-1, 0, 1, 2, 3, 4}``; unknown values map to + ``-1``. + + Examples: + >>> _stage_to_canonical("N4"), _stage_to_canonical("S4", "rk") + (3, 3) + """ + if scheme not in ("aasm", "rk"): + raise ValueError("scheme must be 'aasm' or 'rk'") + if stage is None: + return -1 + mapping = _AASM_STRING_MAP if scheme == "aasm" else _RK_STRING_MAP + if isinstance(stage, str): + return mapping.get(stage.strip().upper(), -1) + try: + value = int(stage) + except (TypeError, ValueError): + return -1 + return value if value == -1 or 0 <= value <= 4 else -1 + + +def _to_three_class(stage: Any, scheme: str = "aasm") -> Any: + """Maps canonical stages to the retrieved three-class space. + + Args: + stage: Scalar or array of stage labels. + scheme: String vocabulary passed to :func:`_stage_to_canonical`. + + Returns: + An integer for scalar input, otherwise an ``int64`` array with the + same shape. ``-1`` is preserved for unknown stages. + + Examples: + >>> _to_three_class([0, 1, 2, 3, 4, -1]).tolist() + [0, 1, 1, 1, 2, -1] + """ + if isinstance(stage, (list, tuple, np.ndarray)): + array = np.asarray(stage) + values = [_to_three_class(value, scheme) for value in array.ravel()] + return np.asarray(values, dtype=np.int64).reshape(array.shape) + canonical = _stage_to_canonical(stage, scheme) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /data_setup.py#L91 + # Original unmapped -> -1: + return CANONICAL_TO_THREE.get(canonical, -1) + + +def _truncate_epochs( + signal: np.ndarray, label: np.ndarray, max_epochs: int +) -> tuple[np.ndarray, np.ndarray]: + """Truncates aligned signal rows and labels to ``max_epochs``. + + Args: + signal: Float array of shape ``(T, points)``. + label: Integer array of shape ``(T,)``. + max_epochs: Maximum number of rows to keep. + + Returns: + The truncated ``(signal, label)`` pair. + + Examples: + >>> x, y = _truncate_epochs(np.ones((5, 2)), np.arange(5), 3) + >>> x.shape, y.tolist() + ((3, 2), [0, 1, 2]) + """ + rows = np.asarray(signal) + labels = np.asarray(label) + if rows.ndim != 2 or labels.ndim != 1 or rows.shape[0] != labels.shape[0]: + raise ValueError("signal and label must be aligned (T, points) and (T,)") + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/modeling + # /data_setup.py#L68 + # Original 1100-segment cap: + n = min(rows.shape[0], labels.shape[0], int(max_epochs)) + return rows[:n], labels[:n] + + +def _detect_peaks( + waveform: Sequence[float], + fs: float, + signal_type: str, + backend: str = "scipy", +) -> np.ndarray: + """Detects beats in a waveform epoch. + + ``scipy`` is the default so IBI extraction does not depend on optional + packages. Opting in to ``"auto"`` prefers biosppy for ECG and neurokit for + PPG when installed, falls back to :func:`scipy.signal.find_peaks` when they + are missing, and treats degenerate epochs (including NeuroKit's "too few + peaks" warning) as having no beats. + + Args: + waveform: One epoch of a PPG or ECG waveform. + fs: Sampling rate in Hz. + signal_type: ``"ecg"`` or ``"ppg"``. + backend: One of ``"scipy"``, ``"auto"``, ``"neurokit"``, ``"biosppy"``. + + Returns: + Integer array of peak sample indices. + + Examples: + >>> x = np.zeros(100); x[20] = x[60] = 1.0 + >>> _detect_peaks(x, 100, "ecg", backend="scipy").tolist() + [20, 60] + """ + if signal_type not in ("ecg", "ppg"): + raise ValueError("signal_type must be 'ecg' or 'ppg'") + if backend not in _PEAK_BACKENDS: + raise ValueError(f"unknown peak backend {backend!r}") + signal = _clean_signal(waveform) + if signal.size < 3: + return np.empty(0, dtype=np.int64) + + def empty() -> np.ndarray: + return np.empty(0, dtype=np.int64) + + def scipy_peaks() -> np.ndarray: + cleaned = detrend(signal, type="linear") if signal.size > 3 else signal + distance = max(1, round(0.35 * float(fs))) + peaks, _ = find_peaks(cleaned, distance=distance) + return peaks.astype(np.int64) + + detector_errors = ( + AttributeError, + IndexError, + KeyError, + RuntimeError, + TypeError, + ValueError, + ZeroDivisionError, + ) + + if backend == "scipy": + return scipy_peaks() + + if backend == "biosppy": + if signal_type != "ecg": + raise ValueError("biosppy backend supports ECG only") + try: + from biosppy.signals import ecg as biosppy_ecg + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L22 + # Original biosppy ECG detector: + result = biosppy_ecg.ecg( + signal=signal, sampling_rate=float(fs), show=False + ) + except detector_errors as err: + logger.debug("biosppy peak detection failed: %s", err) + return empty() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L23 + # Original rpeaks key: + return np.asarray(result["rpeaks"], dtype=np.int64) + + if backend == "neurokit": + try: + import neurokit2 as nk + + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + if signal_type == "ecg": + _, info = nk.ecg_process(signal, sampling_rate=float(fs)) + key = "ECG_R_Peaks" + else: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L46 + # Original neurokit PPG processor: + _, info = nk.ppg_process(signal, sampling_rate=float(fs)) + key = "PPG_Peaks" + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L131 + # Original too-few-peaks guard: + if any( + "Too few peaks detected to compute the rate" in str(w.message) + for w in caught + ): + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L133 + # Original all-zero degenerate epoch: + return empty() + except detector_errors as err: + logger.debug("neurokit peak detection failed: %s", err) + return empty() + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L135 + # Original PPG peak key: + return np.asarray(info.get(key, []), dtype=np.int64) + + candidates = ["biosppy", "neurokit"] if signal_type == "ecg" else ["neurokit"] + for candidate in candidates: + try: + return _detect_peaks(signal, fs, signal_type, backend=candidate) + except ImportError as err: + logger.debug("Peak backend %s is unavailable: %s", candidate, err) + return scipy_peaks() + + +def _resample_to_rate(signal: np.ndarray, fs: float, target_fs: float) -> tuple[ + np.ndarray, float +]: + """Fourier-resamples a waveform to ``target_fs`` when needed. + + The target length is truncated with ``int`` to match the NSRR/MESA + reference readers, which call :func:`scipy.signal.resample` with + ``int(len(signal) * target_fs / fs)`` samples. + + Args: + signal: One-dimensional waveform. + fs: Current sampling rate in Hz. + target_fs: Desired sampling rate in Hz. + + Returns: + The resampled waveform and its effective sampling rate. + + Examples: + >>> out, rate = _resample_to_rate(np.ones(256), 256.0, 100.0) + >>> out.shape, rate + ((100,), 100.0) + """ + array = np.asarray(signal, dtype=np.float64).reshape(-1) + if fs <= 0 or target_fs <= 0: + raise ValueError("sampling rates must be positive") + if abs(fs - target_fs) < 1e-9: + return array, float(fs) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main/dataset_preparation + # /public_datasets/utils.py#L40 + # Original int-truncated Fourier resample: + target_length = int(array.size * float(target_fs) / float(fs)) + if target_length <= 0: + return np.empty(0, dtype=np.float64), float(target_fs) + return resample(array, target_length), float(target_fs) + + +class _SleepStagingIBIBase(BaseTask): + """Shared argument validation and sample emission for IBI tasks.""" + + task_name = "SleepStagingIBIBase" + input_schema = {"signal": "tensor", "lengths": "raw"} # noqa: RUF012 + output_schema = {"label": ("tensor", {"dtype": torch.long})} # noqa: RUF012 + + signal_type: str = "ppg" + source_fs: float = 100.0 + downsample_factor: int = 4 + + def __init__( + self, + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + peak_backend: str = "scipy", + ) -> None: + if not np.isfinite(epoch_seconds) or epoch_seconds <= 0: + raise ValueError("epoch_seconds must be positive and finite") + if points_per_epoch <= 0: + raise ValueError("points_per_epoch must be positive") + if max_epochs <= 0: + raise ValueError("max_epochs must be positive") + if min_epochs <= 0: + raise ValueError("min_epochs must be positive") + if not np.isfinite(max_ibi) or max_ibi <= 0: + raise ValueError("max_ibi must be positive and finite") + if peak_backend not in _PEAK_BACKENDS: + raise ValueError(f"unknown peak backend {peak_backend!r}") + self.epoch_seconds = float(epoch_seconds) + self.points_per_epoch = int(points_per_epoch) + self.max_epochs = int(max_epochs) + self.min_epochs = int(min_epochs) + self.max_ibi = float(max_ibi) + self.peak_backend = peak_backend + super().__init__() + + def _waveforms_to_rows(self, waveforms: np.ndarray) -> np.ndarray: + """Converts ``(T, native)`` waveform epochs into IBI rows.""" + waveforms = np.asarray(waveforms, dtype=np.float64) + rows = np.empty((waveforms.shape[0], self.points_per_epoch), np.float32) + for i, waveform in enumerate(waveforms): + peaks = _detect_peaks( + waveform, self.source_fs, self.signal_type, self.peak_backend + ) + ibi = _peaks_to_ibi( + peaks, self.source_fs, self.max_ibi, length=len(waveform) + ) + rows[i] = _ibi_to_epoch_grid( + ibi, + self.epoch_seconds, + self.points_per_epoch, + 1, + self.downsample_factor, + )[0] + return rows + + def _finalize( + self, + signal: np.ndarray, + label: np.ndarray, + patient_id: str, + record_id: str, + ) -> list[dict[str, Any]]: + """Truncates and wraps rows in the shared sample schema.""" + rows = np.asarray(signal, dtype=np.float32) + labels = _to_three_class(label) + labels = np.asarray(labels, dtype=np.int64) + rows, labels = _truncate_epochs(rows, labels, self.max_epochs) + n_epochs = int(labels.shape[0]) + if n_epochs < self.min_epochs: + return [] + return [ + { + "patient_id": str(patient_id), + "record_id": str(record_id), + "signal": rows, + "label": labels, + "lengths": n_epochs, + } + ] + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + raise NotImplementedError + + +def _nsrr_samples(task: _SleepStagingIBIBase, patient: Any) -> list[dict[str, Any]]: + """Builds one IBI sample per NSRR EDF/XML recording of a patient.""" + samples: list[dict[str, Any]] = [] + for event in patient.get_events(): + try: + channels = _read_edf_channels(event.signal_file, task.channel_aliases) + channel = next( + (a for a in task.channel_aliases if a in channels), None + ) + if channel is None: + raise ValueError(f"no IBI channel in {event.signal_file}") + signal, fs = channels[channel] + stages = _read_stage_codes(event.label_file) + signal, fs = _resample_to_rate(signal, fs, task.source_fs) + native = round(task.source_fs * task.epoch_seconds) + n_epochs = min(len(stages), int(len(signal) // native)) + if n_epochs <= 0: + continue + canonical = np.asarray( + [ + PROFUSION_STAGE_MAP.get(int(stage), -1) + for stage in stages[:n_epochs] + ], + dtype=np.int64, + ) + labels = canonical + waveforms = signal[: n_epochs * native].reshape(n_epochs, native) + rows = task._waveforms_to_rows(waveforms) + record_id = getattr(event, "record_name", None) or Path( + str(event.signal_file) + ).stem + samples.extend( + task._finalize(rows, labels, patient.patient_id, str(record_id)) + ) + except (ValueError, OSError, ET.ParseError) as err: + logger.warning( + "Skipping recording of patient %s: %s", patient.patient_id, err + ) + return samples + + +def _isruc_samples(task: "_SleepStagingIBIBase", patient: Any) -> list[dict]: + """Builds one IBI sample per ISRUC recording of a patient. + + Args: + task: A configured :class:`SleepStagingIBIISRUC`. + patient: A patient from :class:`~pyhealth.datasets.ISRUCDataset`. + + Returns: + Samples with final three-class IBI tensors. Recordings without a + resolvable ECG channel are skipped with a warning. + """ + import mne + + from pyhealth.tasks.sleep_staging_isruc import ( + base_channel_name, + read_isruc_scores, + ) + + samples: list[dict] = [] + label_attr = f"label_file_{task.scorer_index}" + channels = task.channel_aliases + for event in patient.get_events(): + label_file = str(getattr(event, label_attr, "") or "") + if not label_file.strip() or label_file.lower() in {"nan", "none"}: + logger.warning( + "Skipping ISRUC recording of patient %s: missing %s", + patient.patient_id, + label_attr, + ) + continue + try: + raw = mne.io.read_raw_edf( + str(event.signal_file), preload=True, verbose="error" + ) + by_base: dict[str, str] = {} + for name in raw.ch_names: + by_base.setdefault(base_channel_name(name), name) + channel = next((c for c in channels if c in by_base), None) + if channel is None: + # Name-based resolution failed (some ISRUC exports use + # numeric channel labels). Fall back to the EDF transducer + # field, which marks the ECG channel as EKG_Channel. + try: + transducers = _edf_transducer_labels(event.signal_file) + except (OSError, ValueError): + transducers = [] + matches = [ + i + for i, transducer in enumerate(transducers) + if "EKG" in transducer.upper() or "ECG" in transducer.upper() + ] + if matches and matches[0] < len(raw.ch_names): + channel = raw.ch_names[matches[0]] + logger.info( + "Using EDF transducer-labelled ECG channel %r for %s", + channel, + event.signal_file, + ) + if channel is None: + logger.warning( + "Skipping %s: no ECG channel among %s; channels are %s", + event.signal_file, + channels, + raw.ch_names, + ) + raw.close() + continue + signal = raw.get_data(picks=[by_base[channel]])[0] + fs = float(raw.info["sfreq"]) + raw.close() + signal, fs = _resample_to_rate(signal, fs, task.source_fs) + scores = read_isruc_scores(label_file) + native = round(task.source_fs * task.epoch_seconds) + n_epochs = min(len(scores), int(len(signal) // native)) + if n_epochs <= 0: + continue + labels = np.asarray( + [_ISRUC_SCORE_MAP.get(int(score), -1) for score in scores], + dtype=np.int64, + )[:n_epochs] + waveforms = signal[: n_epochs * native].reshape(n_epochs, native) + rows = task._waveforms_to_rows(waveforms) + record_id = str( + getattr(event, "session_id", None) + or Path(str(event.signal_file)).stem + ) + samples.extend( + task._finalize( + rows, labels, patient.patient_id, record_id + ) + ) + except (OSError, RuntimeError, ValueError) as err: + logger.warning( + "Skipping ISRUC recording of patient %s: %s", + patient.patient_id, + err, + ) + return samples + + +class SleepStagingIBIDREAMT(_SleepStagingIBIBase): + """Per-recording IBI sleep staging for :class:`~pyhealth.datasets.DREAMTDataset`. + + The default ``psg_100hz`` source mirrors the reference DREAMT pipeline: + the ``data_100Hz`` BVP column is sampled at 100 Hz, the 30 s epoch grid + is recovered from stage changes, and IBI is strided by four to produce + 750 samples per epoch at 25 Hz. The full anchored night is kept, including + leading and trailing wake epochs. The optional ``wearable_64hz`` source + reads ``data_64Hz`` (or legacy ``data``) files instead. + + Attributes: + task_name: ``"SleepStagingIBIDREAMT"``. + input_schema: ``{"signal": "tensor", "lengths": "raw"}``. + output_schema: ``{"label": ("tensor", {"dtype": torch.long})}``. + + Args: + signal_source: ``"psg_100hz"`` or ``"wearable_64hz"``. + signal_channel: Waveform column, normally ``"BVP"``. + epoch_seconds: Seconds per epoch. + points_per_epoch: Number of IBI samples per epoch. + max_epochs: Maximum epochs per recording. + min_epochs: Drop recordings with fewer epochs than this. + max_ibi: Intervals at or above this many seconds become zero. + peak_backend: Peak detector. Defaults to ``"scipy"`` so results do + not depend on optional packages. ``"auto"`` is an opt-in that + prefers the installed backend with a scipy fallback. + + Examples: + >>> from pyhealth.tasks import SleepStagingIBIDREAMT + >>> task = SleepStagingIBIDREAMT() + >>> task.downsample_factor + 4 + """ + + task_name = "SleepStagingIBIDREAMT" + signal_type = "ppg" + + def __init__( + self, + signal_source: str = "psg_100hz", + signal_channel: str = "BVP", + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + peak_backend: str = "scipy", + ) -> None: + if signal_source not in ("psg_100hz", "wearable_64hz"): + raise ValueError(f"unknown DREAMT signal source {signal_source!r}") + if not signal_channel: + raise ValueError("signal_channel must not be empty") + self.signal_source = signal_source + self.signal_channel = str(signal_channel) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L184 + # Original 100 Hz extraction: + self.source_fs = 100.0 if signal_source == "psg_100hz" else 64.0 + super().__init__( + epoch_seconds=epoch_seconds, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + min_epochs=min_epochs, + max_ibi=max_ibi, + peak_backend=peak_backend, + ) + target_rate = self.points_per_epoch / self.epoch_seconds + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L115 + # Original 25 Hz target: + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L113 + # Original ::4 decimation: + self.downsample_factor = max(1, round(self.source_fs / target_rate)) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds one IBI sample per DREAMT recording of a patient. + + Args: + patient: A patient from :class:`~pyhealth.datasets.DREAMTDataset`. + + Returns: + Samples with ``signal`` of shape ``(T, 750)``, three-class + ``label`` of shape ``(T,)`` and ``lengths == T``. + + Examples: + >>> task = SleepStagingIBIDREAMT() + >>> task.points_per_epoch + 750 + """ + events = patient.get_events(event_type="dreamt_sleep") + if not events: + events = patient.get_events() + file_attr = ( + "file_100hz" if self.signal_source == "psg_100hz" else "file_64hz" + ) + samples: list[dict[str, Any]] = [] + for event in events: + file_path = getattr(event, file_attr, None) + if not file_path or not Path(str(file_path)).is_file(): + logger.warning( + "Skipping DREAMT recording of patient %s: missing %s", + patient.patient_id, + file_attr, + ) + continue + try: + frame = load_dreamt_frame( + str(file_path), signal_cols=(self.signal_channel,) + ) + signal = _clean_signal(frame[self.signal_channel].to_numpy()) + stages = frame["Sleep_Stage"].to_numpy(dtype=np.int64) + + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L55 + # Original epoch size: + samples_per_epoch = round(self.source_fs * self.epoch_seconds) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L100 + # Reference offset-correction loop (conceptual): + changes = np.where(np.diff(stages) != 0)[0] + 1 + if changes.size: + counts = np.bincount( + changes % samples_per_epoch, minlength=samples_per_epoch + ) + anchor = int(np.argmax(counts)) + else: + anchor = 0 + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L62 + # Reference leading wake trim (PyHealth keeps full night): + n_epochs = max((len(stages) - anchor) // samples_per_epoch, 0) + if n_epochs == 0: + continue + + end = anchor + n_epochs * samples_per_epoch + grid = stages[anchor:end].reshape(n_epochs, samples_per_epoch) + first = grid[:, 0] + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L91 + # Original consistent-stage check: + consistent = np.all(grid == first[:, None], axis=1) + known = first >= 0 + epoch_stages = np.full(n_epochs, -1, dtype=np.int64) + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L97 + # Original full-epoch stage repeat: + epoch_stages[consistent & known] = first[consistent & known] + waveforms = signal[anchor:end].reshape( + n_epochs, samples_per_epoch + ) + rows = self._waveforms_to_rows(waveforms) + samples.extend( + self._finalize( + rows, + epoch_stages, + patient.patient_id, + Path(str(file_path)).stem, + ) + ) + except (ValueError, OSError) as err: + logger.warning( + "Skipping DREAMT recording of patient %s: %s", + patient.patient_id, + err, + ) + return samples + + +class SleepStagingIBISHHS(_SleepStagingIBIBase): + """Per-recording IBI sleep staging for NSRR SHHS recordings. + + Uses :class:`~pyhealth.datasets.NSRRSleepDataset` EDF/XML events. The + default ECG channel is read at its native 125 Hz, IBI is strided by five, + and profusion stages are mapped to ``{W: 0, NREM: 1, REM: 2}`` with + ``-1`` for unknown epochs. + + Attributes: + task_name: ``"SleepStagingIBISHHS"``. + input_schema: Shared ``signal``/``lengths`` schema. + output_schema: Long-tensor ``label`` schema. + + Args: + signal_channel: EDF channel name, normally ``"ECG"``. + source_fs: Sampling rate used for the epoch grid. + downsample_factor: Integer stride from ``source_fs`` to 25 Hz. + epoch_seconds: Seconds per epoch. + points_per_epoch: Number of IBI samples per epoch. + max_epochs: Maximum epochs per recording. + min_epochs: Drop recordings with fewer epochs than this. + max_ibi: Intervals at or above this many seconds become zero. + peak_backend: Peak detector. Defaults to ``"scipy"`` so results do + not depend on optional packages. ``"auto"`` is an opt-in that + prefers the installed backend with a scipy fallback. + + Examples: + >>> from pyhealth.tasks import SleepStagingIBISHHS + >>> task = SleepStagingIBISHHS() + >>> task.signal_type + 'ecg' + """ + + task_name = "SleepStagingIBISHHS" + + def __init__( + self, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/shhs_extract_ecg.py#L23 + # Original SHHS ECG channel: + signal_channel: str = "ECG", + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/utils.py#L35 + # Original native EDF rate: + source_fs: float = 125.0, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L123 + # Original 25 Hz stride: + downsample_factor: int = 5, + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + peak_backend: str = "scipy", + ) -> None: + if source_fs <= 0 or not np.isfinite(source_fs): + raise ValueError("source_fs must be positive and finite") + if downsample_factor <= 0: + raise ValueError("downsample_factor must be positive") + self.source_fs = float(source_fs) + self.downsample_factor = int(downsample_factor) + self.signal_channel = str(signal_channel) + self.signal_type = ( + "ecg" if self.signal_channel.lower() in CHANNEL_ALIASES["ecg"] else "ppg" + ) + aliases = CHANNEL_ALIASES[self.signal_type] + aliases = (*aliases, self.signal_channel.lower()) + self.channel_aliases = tuple(dict.fromkeys(aliases)) + super().__init__( + epoch_seconds=epoch_seconds, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + min_epochs=min_epochs, + max_ibi=max_ibi, + peak_backend=peak_backend, + ) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds one IBI sample per SHHS recording of a patient. + + Args: + patient: A patient from + :class:`~pyhealth.datasets.NSRRSleepDataset`. + + Returns: + Samples with ``signal`` of shape ``(T, 750)``, three-class + ``label`` of shape ``(T,)`` and ``lengths == T``. + + Examples: + >>> task = SleepStagingIBISHHS() + >>> task.task_name + 'SleepStagingIBISHHS' + """ + return _nsrr_samples(self, patient) + + +class SleepStagingIBIMESA(_SleepStagingIBIBase): + """Per-recording IBI sleep staging for NSRR MESA recordings. + + Uses :class:`~pyhealth.datasets.NSRRSleepDataset` EDF/XML events. The + default ``Pleth`` signal is Fourier-resampled from its native 256 Hz to + 100 Hz, IBI is strided by four to 750 samples per epoch, and profusion + stages are mapped to ``{W: 0, NREM: 1, REM: 2}`` with ``-1`` unknown. + + Attributes: + task_name: ``"SleepStagingIBIMESA"``. + input_schema: Shared ``signal``/``lengths`` schema. + output_schema: Long-tensor ``label`` schema. + + Args: + signal_channel: EDF channel name, normally ``"Pleth"``. + source_fs: Sampling rate used for the epoch grid. + downsample_factor: Integer stride from ``source_fs`` to 25 Hz. + epoch_seconds: Seconds per epoch. + points_per_epoch: Number of IBI samples per epoch. + max_epochs: Maximum epochs per recording. + min_epochs: Drop recordings with fewer epochs than this. + max_ibi: Intervals at or above this many seconds become zero. + peak_backend: Peak detector. Defaults to ``"scipy"`` so results do + not depend on optional packages. ``"auto"`` is an opt-in that + prefers the installed backend with a scipy fallback. + + Examples: + >>> from pyhealth.tasks import SleepStagingIBIMESA + >>> task = SleepStagingIBIMESA() + >>> task.signal_type + 'ppg' + """ + + task_name = "SleepStagingIBIMESA" + + def __init__( + self, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/mesa_extract_ppg.py#L16 + # Original MESA Pleth channel: + signal_channel: str = "Pleth", + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/preprocess_mesa_ppg.py#L14 + # Original MESA native rate: + source_fs: float = 100.0, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/dreamt/dreamt_extract_ibi_se.py#L113 + # Original ::4 decimation: + downsample_factor: int = 4, + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + peak_backend: str = "scipy", + ) -> None: + if source_fs <= 0 or not np.isfinite(source_fs): + raise ValueError("source_fs must be positive and finite") + if downsample_factor <= 0: + raise ValueError("downsample_factor must be positive") + self.source_fs = float(source_fs) + self.downsample_factor = int(downsample_factor) + self.signal_channel = str(signal_channel) + self.signal_type = ( + "ecg" if self.signal_channel.lower() in CHANNEL_ALIASES["ecg"] else "ppg" + ) + aliases = CHANNEL_ALIASES[self.signal_type] + aliases = (*aliases, self.signal_channel.lower()) + self.channel_aliases = tuple(dict.fromkeys(aliases)) + super().__init__( + epoch_seconds=epoch_seconds, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + min_epochs=min_epochs, + max_ibi=max_ibi, + peak_backend=peak_backend, + ) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds one IBI sample per MESA recording of a patient. + + Args: + patient: A patient from + :class:`~pyhealth.datasets.NSRRSleepDataset`. + + Returns: + Samples with ``signal`` of shape ``(T, 750)``, three-class + ``label`` of shape ``(T,)`` and ``lengths == T``. + + Examples: + >>> task = SleepStagingIBIMESA() + >>> task.task_name + 'SleepStagingIBIMESA' + """ + return _nsrr_samples(self, patient) + + +class SleepStagingIBISleepAccel(_SleepStagingIBIBase): + """Heart-rate-derived IBI staging for Sleep-Accel recordings. + + Sleep-Accel has no raw ECG or PPG waveform. Each 30 s epoch is converted + by interpolating ``60 / bpm`` onto a uniform 25 Hz grid, producing 750 + samples by default. Labels are Wake ``0``, NREM ``1``, REM ``2`` and + unknown ``-1``. + + Args: + epoch_seconds: Seconds per epoch. + points_per_epoch: Number of IBI samples per epoch. + max_epochs: Maximum epochs per recording. + min_epochs: Drop recordings with fewer epochs than this. + max_ibi: Intervals at or above this many seconds become zero. + min_ibi: Intervals below this many seconds become zero. + heart_rate_padding: Seconds of neighbouring heart-rate samples + included on each side of an epoch for edge interpolation. + require_signal: Drop epochs with no heart-rate sample inside the + epoch window. Defaults to False so the 30 s grid is preserved + with zero IBI rows, matching whole-night reference behavior. + + Attributes: + task_name: ``"SleepStagingIBISleepAccel"``. + input_schema: Shared ``signal``/``lengths`` schema. + output_schema: Long-tensor ``label`` schema. + + Examples: + >>> from pyhealth.tasks import SleepStagingIBISleepAccel + >>> task = SleepStagingIBISleepAccel() + >>> task.task_name, task.points_per_epoch + ('SleepStagingIBISleepAccel', 750) + """ + + task_name = "SleepStagingIBISleepAccel" + signal_type = "hr" + + def __init__( + self, + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + min_ibi: float = 0.3, + heart_rate_padding: float = 60.0, + require_signal: bool = False, + ) -> None: + if max_ibi <= 0 or min_ibi <= 0 or min_ibi >= max_ibi: + raise ValueError("require 0 < min_ibi < max_ibi") + if heart_rate_padding < 0 or not np.isfinite(heart_rate_padding): + raise ValueError("heart_rate_padding must be finite and non-negative") + self.min_ibi = float(min_ibi) + self.heart_rate_padding = float(heart_rate_padding) + self.require_signal = bool(require_signal) + super().__init__( + epoch_seconds=epoch_seconds, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + min_epochs=min_epochs, + max_ibi=max_ibi, + ) + self.source_fs = self.points_per_epoch / self.epoch_seconds + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds one heart-rate-derived IBI sample per recording. + + Args: + patient: A patient from a PyHealth Sleep-Accel dataset. + + Returns: + Samples with ``signal`` of shape ``(T, 750)``, three-class + ``label`` of shape ``(T,)`` and ``lengths == T``. + + Examples: + >>> SleepStagingIBISleepAccel().max_epochs + 1100 + """ + from pyhealth.datasets.sleep_accel import ( + load_sleep_accel_heart_rate, + load_sleep_accel_stages, + ) + + events = patient.get_events(event_type="sleep_accel") + if not events: + events = patient.get_events() + samples: list[dict[str, Any]] = [] + for event in events: + try: + stages, starts = load_sleep_accel_stages(event.label_file) + times, bpm = load_sleep_accel_heart_rate(event.heart_rate_file) + n_epochs = min(len(stages), len(starts)) + if n_epochs <= 0: + continue + rows: list[np.ndarray] = [] + labels: list[int] = [] + for index in range(n_epochs): + start = float(starts[index]) + end = start + self.epoch_seconds + core = (times >= start) & (times < end) + if self.require_signal and not core.any(): + continue + selected = ( + (times >= start - self.heart_rate_padding) + & (times < end + self.heart_rate_padding) + ) + rows.append( + _heart_rate_to_grid( + times[selected] - start, + bpm[selected], + self.points_per_epoch, + self.epoch_seconds, + self.max_ibi, + self.min_ibi, + ) + ) + labels.append(int(stages[index])) + if not rows: + continue + record_id = str( + getattr(event, "record_name", None) + or Path(str(event.label_file)).name.split("_", 1)[0] + ) + samples.extend( + self._finalize( + np.asarray(rows, dtype=np.float32), + np.asarray(labels, dtype=np.int64), + patient.patient_id, + record_id, + ) + ) + except (OSError, ValueError) as err: + logger.warning( + "Skipping Sleep-Accel recording of patient %s: %s", + patient.patient_id, + err, + ) + return samples + + +class SleepStagingIBIISRUC(_SleepStagingIBIBase): + """ECG-derived IBI staging for ISRUC-Sleep recordings. + + The task reads one expert's hypnogram and the ECG channel of each ISRUC + recording, detects beats at the native 200 Hz rate, and strides the IBI + signal by eight to produce 750 samples per 30 s epoch. Labels are Wake + ``0``, NREM ``1``, REM ``2`` and unknown ``-1``. + + Args: + scorer: ``"expert1"`` or ``"expert2"`` hypnogram. + channel: Optional ECG channel override. Defaults to the released + candidates, beginning with ``"X2"``. When a recording uses + numeric channel labels, the EDF transducer field (``EKG_Channel``) + is used to locate the ECG channel. + source_fs: Sampling rate used for the epoch grid. + downsample_factor: Integer stride from ``source_fs`` to 25 Hz. + epoch_seconds: Seconds per epoch. + points_per_epoch: Number of IBI samples per epoch. + max_epochs: Maximum epochs per recording. + min_epochs: Drop recordings with fewer epochs than this. + max_ibi: Intervals at or above this many seconds become zero. + peak_backend: Peak detector. Defaults to ``"scipy"`` so results do + not depend on optional packages. ``"auto"`` is an opt-in that + prefers the installed backend with a scipy fallback. + + Attributes: + task_name: ``"SleepStagingIBIISRUC"``. + input_schema: Shared ``signal``/``lengths`` schema. + output_schema: Long-tensor ``label`` schema. + + Examples: + >>> from pyhealth.tasks import SleepStagingIBIISRUC + >>> task = SleepStagingIBIISRUC(scorer="expert2") + >>> task.scorer, task.downsample_factor + ('expert2', 8) + """ + + task_name = "SleepStagingIBIISRUC" + signal_type = "ecg" + + def __init__( + self, + scorer: Literal["expert1", "expert2"] = "expert1", + channel: str | None = None, + source_fs: float = 200.0, + # https://github.com/WillKeWang/WatchSleepNet_public/blob/main + # /dataset_preparation/public_datasets/extract_and_save_ibi.py#L123 + # Original stride: + downsample_factor: int = 8, + epoch_seconds: float = 30.0, + points_per_epoch: int = 750, + max_epochs: int = 1100, + min_epochs: int = 1, + max_ibi: float = 2.0, + peak_backend: str = "scipy", + ) -> None: + if scorer not in ("expert1", "expert2"): + raise ValueError("scorer must be 'expert1' or 'expert2'") + if source_fs <= 0 or not np.isfinite(source_fs): + raise ValueError("source_fs must be positive and finite") + if downsample_factor <= 0: + raise ValueError("downsample_factor must be positive") + self.scorer = scorer + self.scorer_index = 1 if scorer == "expert1" else 2 + candidates = _ISRUC_ECG_CHANNELS + if channel: + candidates = (str(channel), *_ISRUC_ECG_CHANNELS) + self.channel_aliases = tuple(dict.fromkeys(candidates)) + self.source_fs = float(source_fs) + self.downsample_factor = int(downsample_factor) + super().__init__( + epoch_seconds=epoch_seconds, + points_per_epoch=points_per_epoch, + max_epochs=max_epochs, + min_epochs=min_epochs, + max_ibi=max_ibi, + peak_backend=peak_backend, + ) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Builds one IBI sample per ISRUC recording of a patient. + + Args: + patient: A patient from a PyHealth ISRUC dataset. + + Returns: + Samples with ``signal`` of shape ``(T, 750)``, three-class + ``label`` of shape ``(T,)`` and ``lengths == T``. + + Examples: + >>> SleepStagingIBIISRUC().task_name + 'SleepStagingIBIISRUC' + """ + return _isruc_samples(self, patient) diff --git a/tests/core/test_dreamt_ibi.py b/tests/core/test_dreamt_ibi.py new file mode 100644 index 0000000000..8a683e36bc --- /dev/null +++ b/tests/core/test_dreamt_ibi.py @@ -0,0 +1,142 @@ +"""Tests for the DREAMT IBI sleep-staging task and DREAMT loading helpers. + +All data are synthetic; no real DREAMT recordings are required. +""" + +import shutil +import tempfile +import unittest +from pathlib import Path + +import numpy as np +import pandas as pd + +from pyhealth.datasets import DREAMTDataset +from pyhealth.tasks import SleepStagingIBIDREAMT +from pyhealth.tasks.sleep_staging_ibi import ( + load_dreamt_frame, + map_dreamt_stages, +) + + +def participant_info(num_patients: int) -> pd.DataFrame: + rng = np.random.default_rng(0) + return pd.DataFrame( + { + "SID": [f"S{i:03d}" for i in range(1, num_patients + 1)], + "AGE": rng.uniform(25, 65, num_patients), + "GENDER": rng.choice(["M", "F"], num_patients), + "BMI": rng.integers(20, 50, num_patients), + "OAHI": rng.integers(0, 50, num_patients), + "AHI": rng.integers(0, 50, num_patients), + "Mean_SaO2": [f"{v}%" for v in rng.integers(85, 99, num_patients)], + "Arousal Index": rng.integers(1, 100, num_patients), + "MEDICAL_HISTORY": ["Medical History"] * num_patients, + "Sleep_Disorders": ["Sleep Disorder"] * num_patients, + } + ) + + +def synthetic_bvp(n_samples: int, fs: int = 100, period: int = 100) -> np.ndarray: + t = np.arange(n_samples) / fs + waveform = np.sin(2 * np.pi * t / period) + 0.5 * np.sin( + 4 * np.pi * t / period + ) + waveform[::period] += 2.0 + return waveform.astype(np.float64) + + +class TestDREAMTIBILoadingHelpers(unittest.TestCase): + """Checks the task-side DREAMT loading helpers used by IBI staging.""" + + def setUp(self): + self.temp_dir = tempfile.mkdtemp() + self.root = Path(self.temp_dir) + (self.root / "data_64Hz").mkdir() + (self.root / "data_100Hz").mkdir() + participant_info(1).to_csv(self.root / "participant_info.csv", index=False) + for folder in ("data_64Hz", "data_100Hz"): + pd.DataFrame({"BVP": [1.0], "Sleep_Stage": ["W"]}).to_csv( + self.root / folder / "S001_PSG_df.csv", index=False + ) + + def tearDown(self): + shutil.rmtree(self.temp_dir) + + def test_missing_and_unexpected_file_folder(self): + dataset = DREAMTDataset(root=str(self.root)) + self.assertIsNone(dataset.get_patient_file("S001", str(self.root), "nope")) + self.assertIsNone(dataset.get_patient_file("S222", str(self.root), "data")) + path = dataset.get_patient_file("S001", str(self.root), "data_100Hz") + self.assertTrue(Path(path).is_file()) + + def test_stage_map(self): + self.assertEqual( + map_dreamt_stages(["W", "N1", "N2", "N3", "R", "Missing", "P"]).tolist(), + [0, 1, 2, 3, 4, -1, -1], + ) + + def test_load_dreamt_frame(self): + path = self.root / "data_100Hz" / "S001_PSG_df.csv" + frame = load_dreamt_frame(str(path), signal_cols=("BVP",)) + self.assertEqual(set(frame.columns), {"BVP", "Sleep_Stage"}) + self.assertEqual(frame["BVP"].dtype, np.float64) + with self.assertRaises(ValueError): + load_dreamt_frame(str(path), signal_cols=("missing",)) + with self.assertRaises(FileNotFoundError): + load_dreamt_frame(str(self.root / "absent.csv")) + + +class TestDREAMTIBITask(unittest.TestCase): + """Checks IBI emission on a deterministic synthetic DREAMT night.""" + + def setUp(self): + self.temp_dir = tempfile.mkdtemp() + self.root = Path(self.temp_dir) + (self.root / "data_100Hz").mkdir() + participant_info(1).to_csv(self.root / "participant_info.csv", index=False) + + samples_per_epoch = 100 * 30 + stages = ["W", "N2", "Missing", "R", "W"] + self.labels = [0, 1, -1, 2, 0] + frame = pd.DataFrame( + { + "BVP": synthetic_bvp(samples_per_epoch * len(stages)), + "Sleep_Stage": np.repeat(stages, samples_per_epoch), + } + ) + frame.to_csv(self.root / "data_100Hz" / "S001_PSG_df.csv", index=False) + self.dataset = DREAMTDataset(root=str(self.root)) + + def tearDown(self): + shutil.rmtree(self.temp_dir) + + def test_direct_task_call(self): + task = SleepStagingIBIDREAMT(peak_backend="scipy", max_epochs=5) + patient = self.dataset.get_patient("S001") + samples = task(patient) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["signal"].shape, (5, 750)) + self.assertEqual(sample["signal"].dtype, np.float32) + self.assertEqual(sample["label"].tolist(), self.labels) + self.assertEqual(sample["lengths"], 5) + self.assertEqual(sample["record_id"], "S001_PSG_df") + self.assertAlmostEqual(float(np.median(sample["signal"])), 1.0, delta=0.01) + + def test_set_task_integration(self): + import torch + + task = SleepStagingIBIDREAMT(peak_backend="scipy", max_epochs=5) + samples = self.dataset.set_task(task, num_workers=1) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(tuple(sample["signal"].shape), (5, 750)) + self.assertEqual(sample["signal"].dtype, torch.float32) + self.assertEqual(tuple(sample["label"].shape), (5,)) + self.assertEqual(sample["label"].dtype, torch.long) + self.assertEqual(sample["lengths"], 5) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_isruc_ibi.py b/tests/core/test_isruc_ibi.py new file mode 100644 index 0000000000..6ed2244cce --- /dev/null +++ b/tests/core/test_isruc_ibi.py @@ -0,0 +1,228 @@ +"""Tests for the ISRUC IBI sleep-staging task, using synthetic EDF files.""" + +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import torch + +from pyhealth.datasets import ISRUCDataset +from pyhealth.tasks import SleepStagingIBIISRUC + +SFREQ = 200 + + +def _write_edf( + path: Path, + channels: list[str], + data: np.ndarray, + fs: int = SFREQ, + transducers: list[str] | None = None, +) -> None: + """Write ``data`` (microvolts, one row per channel) as a minimal EDF file. + + Each data record is one second. Physical and digital ranges match, so + a stored integer is the value in microvolts. + """ + n_channels = len(channels) + n_records = data.shape[1] // fs + transducers = transducers or [""] * n_channels + + def field(value, width): + return f"{value:<{width}}"[:width] + + header = ( + field("0", 8) + + field("X X X X", 80) + + field("Startdate 01-JAN-2000 X X X", 80) + + "01.01.00" + + "00.00.00" + + field(256 * (n_channels + 1), 8) + + field("", 44) + + field(n_records, 8) + + field(1, 8) + + field(n_channels, 4) + ) + for width, values in [ + (16, channels), + (80, transducers), + (8, ["uV"] * n_channels), + (8, ["-32768"] * n_channels), + (8, ["32767"] * n_channels), + (8, ["-32768"] * n_channels), + (8, ["32767"] * n_channels), + (80, [""] * n_channels), + (8, [fs] * n_channels), + (32, [""] * n_channels), + ]: + header += "".join(field(v, width) for v in values) + records = data[:, : n_records * fs].astype(" np.ndarray: + """A regular ECG-like spike train at 75 beats per minute.""" + data = np.zeros((1, seconds * fs), dtype=np.float64) + spacing = round(0.8 * fs) + data[0, ::spacing] = 10.0 + return data + + +def _write_recording( + folder: Path, + stem: str, + scores: list[int], + suffix: str = ".rec", + channels: list[str] | None = None, +) -> None: + """Write an ISRUC style recording (at 200 Hz) and its scoring files.""" + channels = channels or ["X2"] + seconds = 30 * len(scores) + second = np.arange(seconds * SFREQ) // SFREQ + data = np.stack([100 * i + second for i in range(len(channels))]) + _write_edf(folder / f"{stem}{suffix}", channels, data) + for annotator in (1, 2): + (folder / f"{stem}_{annotator}.txt").write_text( + "".join(f"{score}\n" for score in scores) + ) + + +def _event(folder: Path, stem: str, suffix: str = ".edf", **overrides): + """A ``recordings`` event like the rows of ``isruc-pyhealth.csv``.""" + fields = { + "session_id": "1", + "signal_file": str(folder / f"{stem}{suffix}"), + "label_file_1": str(folder / f"{stem}_1.txt"), + "label_file_2": str(folder / f"{stem}_2.txt"), + } + fields.update(overrides) + return SimpleNamespace(**fields) + + +def _patient(patient_id: str, events: list) -> SimpleNamespace: + return SimpleNamespace( + patient_id=patient_id, + get_events=lambda event_type=None: events, + ) + + +class TestSleepStagingIBIISRUC(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.folder = Path(tmp.name) / "1" + + def _write( + self, + scores: list[int], + scores2: list[int] | None = None, + channels: list[str] | None = None, + transducers: list[str] | None = None, + ) -> None: + self.folder.mkdir(parents=True, exist_ok=True) + channels = channels or ["X2"] + _write_edf( + self.folder / "1.edf", + channels, + _ecg_signal(30 * len(scores)), + transducers=transducers, + ) + (self.folder / "1_1.txt").write_text( + "".join(f"{score}\n" for score in scores) + ) + second = scores if scores2 is None else scores2 + (self.folder / "1_2.txt").write_text( + "".join(f"{score}\n" for score in second) + ) + + def test_labels_shape_and_expert_selection(self) -> None: + self._write( + [0, 1, 2, 3, 5, -1], + [2, 2, 2, 2, 2, 2], + ) + patient = _patient("1", [_event(self.folder, "1")]) + + first = SleepStagingIBIISRUC(peak_backend="scipy")(patient) + second = SleepStagingIBIISRUC( + scorer="expert2", peak_backend="scipy" + )(patient) + + self.assertEqual(first[0]["label"].tolist(), [0, 1, 1, 1, 2, -1]) + self.assertEqual(second[0]["label"].tolist(), [1] * 6) + self.assertEqual(first[0]["signal"].shape, (6, 750)) + self.assertEqual(first[0]["signal"].dtype, np.float32) + self.assertEqual(first[0]["label"].dtype, np.int64) + self.assertEqual(first[0]["lengths"], 6) + self.assertEqual(first[0]["record_id"], "1") + + def test_max_epochs_truncates(self) -> None: + self._write([0, 2, 5, 0]) + + samples = SleepStagingIBIISRUC( + max_epochs=2, peak_backend="scipy" + )(_patient("1", [_event(self.folder, "1")])) + + self.assertEqual(len(samples), 1) + self.assertEqual(samples[0]["signal"].shape, (2, 750)) + self.assertEqual(samples[0]["label"].tolist(), [0, 1]) + + def test_missing_ecg_channel_skips_recording(self) -> None: + self._write([0], channels=["C3"]) + + with self.assertLogs("pyhealth.tasks.sleep_staging_ibi", "WARNING") as logs: + samples = SleepStagingIBIISRUC(peak_backend="scipy")( + _patient("1", [_event(self.folder, "1")]) + ) + + self.assertEqual(samples, []) + self.assertIn("no ECG channel", logs.output[0]) + + def test_numeric_ecg_channel_uses_edf_transducer(self) -> None: + self._write( + [0, 2], + channels=["25"], + transducers=["EKG_Channel"], + ) + + samples = SleepStagingIBIISRUC(peak_backend="scipy")( + _patient("1", [_event(self.folder, "1")]) + ) + + self.assertEqual(len(samples), 1) + self.assertEqual(samples[0]["signal"].shape, (2, 750)) + + def test_invalid_arguments(self) -> None: + for kwargs in ( + {"scorer": "expert3"}, + {"source_fs": 0}, + {"downsample_factor": 0}, + {"peak_backend": "nope"}, + ): + with self.subTest(**kwargs), self.assertRaises(ValueError): + SleepStagingIBIISRUC(**kwargs) + + def test_set_task_integration(self) -> None: + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + root = Path(tmp) / "ISRUC-Sleep-I" + for subject, scores in (("1", [0, 5]), ("2", [1, 3])): + _write_recording(root / subject, subject, scores) + dataset = ISRUCDataset( + root=str(root), cache_dir=str(Path(tmp) / "cache"), num_workers=1 + ) + + samples = dataset.set_task( + SleepStagingIBIISRUC(peak_backend="scipy"), num_workers=1 + ) + + self.assertEqual(len(samples), 2) + for sample in samples: + self.assertEqual(sample["signal"].shape, (2, 750)) + self.assertEqual(sample["label"].dtype, torch.int64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_nsrr_sleep_ibi.py b/tests/core/test_nsrr_sleep_ibi.py new file mode 100644 index 0000000000..365fe7da1e --- /dev/null +++ b/tests/core/test_nsrr_sleep_ibi.py @@ -0,0 +1,176 @@ +"""Tests for the SHHS/MESA IBI sleep-staging tasks. + +All data are synthetic: tiny EDF and profusion XML files written to a +temporary directory. No real NSRR data is used. +""" + +import os +import tempfile +import unittest + +import numpy as np + +from pyhealth.datasets import NSRRSleepDataset +from pyhealth.tasks import SleepStagingIBIMESA, SleepStagingIBISHHS + +# Stage codes of the synthetic night; 9 marks an unscored epoch. +STAGES = [0, 0, 1, 2, 2, 3, 4, 5, 5, 9] + + +def periodic_signal(n_seconds, rate, period_samples): + """Deterministic pulsatile waveform with a beat every ``period_samples``.""" + t = np.arange(n_seconds * rate) + wave = np.sin(2 * np.pi * t / period_samples) + wave += 0.5 * np.sin(4 * np.pi * t / period_samples) + wave[::period_samples] += 2.0 + return (np.clip(wave, -3.0, 3.0) * 10000).astype("{s}" for s in stages) + with open(path, "w") as f: + f.write( + "30" + f"{body}" + ) + + +class TestSleepStagingIBI(unittest.TestCase): + """Checks SHHS/MESA IBI tasks on deterministic synthetic EDF/XML files.""" + + @classmethod + def setUpClass(cls): + cls.tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + root = cls.tmp.name + cls.shhs_root = os.path.join(root, "shhs_ibi") + cls.mesa_root = os.path.join(root, "mesa_ibi") + shhs_edfs = os.path.join(cls.shhs_root, "edfs") + mesa_edfs = os.path.join(cls.mesa_root, "edfs") + os.makedirs(shhs_edfs) + os.makedirs(mesa_edfs) + + n_seconds = 30 * len(STAGES) + write_edf_array( + os.path.join(shhs_edfs, "shhs1-300001.edf"), + [("ECG", 125)], + {"ECG": periodic_signal(n_seconds, 125, 125)}, + ) + write_xml( + os.path.join(shhs_edfs, "shhs1-300001-profusion.xml"), STAGES + ) + write_edf_array( + os.path.join(mesa_edfs, "mesa-sleep-0002.edf"), + [("Pleth", 256)], + {"Pleth": periodic_signal(n_seconds, 256, 256)}, + ) + write_xml( + os.path.join(mesa_edfs, "mesa-sleep-0002-profusion.xml"), STAGES + ) + + cache = os.path.join(root, "ibi_cache") + cls.shhs_ds = NSRRSleepDataset( + cls.shhs_root, cohort="shhs", cache_dir=cache + ) + cls.mesa_ds = NSRRSleepDataset( + cls.mesa_root, cohort="mesa", cache_dir=cache + ) + cls.shhs_patient = cls.shhs_ds.get_patient("300001") + cls.mesa_patient = cls.mesa_ds.get_patient("0002") + cls.expected_labels = [0, 0, 1, 1, 1, 1, 1, 2, 2, -1] + + @classmethod + def tearDownClass(cls): + cls.tmp.cleanup() + + def test_shhs_samples(self): + samples = SleepStagingIBISHHS(peak_backend="scipy")(self.shhs_patient) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["signal"].shape, (len(STAGES), 750)) + self.assertEqual(sample["signal"].dtype, np.float32) + self.assertEqual(sample["label"].tolist(), self.expected_labels) + self.assertEqual(sample["lengths"], len(STAGES)) + self.assertEqual(sample["record_id"], "shhs1-300001") + + def test_mesa_samples(self): + samples = SleepStagingIBIMESA(peak_backend="scipy")(self.mesa_patient) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["signal"].shape, (len(STAGES), 750)) + self.assertEqual(sample["signal"].dtype, np.float32) + self.assertEqual(sample["label"].tolist(), self.expected_labels) + self.assertEqual(sample["lengths"], len(STAGES)) + + def test_pooled_schemas_match(self): + shhs = SleepStagingIBISHHS(peak_backend="scipy") + mesa = SleepStagingIBIMESA(peak_backend="scipy") + self.assertEqual(shhs.input_schema, mesa.input_schema) + self.assertEqual(shhs.output_schema, mesa.output_schema) + shhs_sample = shhs(self.shhs_patient)[0] + mesa_sample = mesa(self.mesa_patient)[0] + self.assertEqual(shhs_sample["signal"].shape, mesa_sample["signal"].shape) + self.assertEqual(shhs_sample["label"].dtype, mesa_sample["label"].dtype) + + def test_max_epochs_truncates(self): + task = SleepStagingIBISHHS(peak_backend="scipy", max_epochs=4) + sample = task(self.shhs_patient)[0] + self.assertEqual(sample["signal"].shape, (4, 750)) + self.assertEqual(sample["label"].tolist(), self.expected_labels[:4]) + self.assertEqual(sample["lengths"], 4) + + def test_set_task_integration(self): + import torch + + task = SleepStagingIBISHHS(peak_backend="scipy", max_epochs=4) + samples = self.shhs_ds.set_task(task, num_workers=1) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(tuple(sample["signal"].shape), (4, 750)) + self.assertEqual(sample["signal"].dtype, torch.float32) + self.assertEqual(tuple(sample["label"].shape), (4,)) + self.assertEqual(sample["label"].dtype, torch.long) + self.assertEqual(sample["lengths"], 4) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_sleep_accel.py b/tests/core/test_sleep_accel.py new file mode 100644 index 0000000000..8ed1c03343 --- /dev/null +++ b/tests/core/test_sleep_accel.py @@ -0,0 +1,223 @@ +"""Tests for the Sleep-Accel dataset and heart-rate IBI task.""" + +import tempfile +import unittest +from pathlib import Path +from types import SimpleNamespace + +import numpy as np +import pandas as pd +import torch + +from pyhealth.datasets import SleepAccelDataset +from pyhealth.datasets.sleep_accel import ( + SLEEP_ACCEL_STAGE_MAP, + load_sleep_accel_heart_rate, + load_sleep_accel_stages, +) +from pyhealth.tasks import SleepStagingIBISleepAccel +from pyhealth.tasks.sleep_staging_ibi import _heart_rate_to_grid + + +def _write_subject( + root: Path, + subject: str, + scores: list[int], + rates: list[float] | None = None, +) -> None: + """Writes one synthetic Sleep-Accel subject with all four modalities.""" + for folder in ("heart_rate", "labels", "motion", "steps"): + (root / folder).mkdir(parents=True, exist_ok=True) + labels = "".join(f"{i * 30} {score}\n" for i, score in enumerate(scores)) + (root / "labels" / f"{subject}_labeled_sleep.txt").write_text(labels) + if rates is None: + rates = [60.0] * (len(scores) + 2) + times = list(range(-30, 30 * (len(scores) + 1), 30)) + rows = "".join( + f"{time},{rate}\n" for time, rate in zip(times, rates, strict=False) + ) + (root / "heart_rate" / f"{subject}_heartrate.txt").write_text(rows) + (root / "motion" / f"{subject}_acceleration.txt").write_text("0,0,0,0\n") + (root / "steps" / f"{subject}_steps.txt").write_text("0,0\n") + + +def _event(root: Path, subject: str) -> SimpleNamespace: + """Builds one event like the rows of the Sleep-Accel metadata CSV.""" + return SimpleNamespace( + patient_id=subject, + record_name=subject, + label_file=str(root / "labels" / f"{subject}_labeled_sleep.txt"), + heart_rate_file=str( + root / "heart_rate" / f"{subject}_heartrate.txt" + ), + ) + + +def _patient(subject: str, events: list) -> SimpleNamespace: + return SimpleNamespace( + patient_id=subject, + get_events=lambda event_type=None: events, + ) + + +class TestSleepAccelDataset(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) / "sleep-accel" + self.root.mkdir() + + def test_metadata_columns_and_absolute_paths(self) -> None: + _write_subject(self.root, "101", [0, 5]) + + dataset = SleepAccelDataset( + root=str(self.root), cache_dir=str(self.root / "cache"), num_workers=1 + ) + frame = pd.read_csv( + self.root / "sleep_accel-pyhealth.csv", dtype=str, keep_default_na=False + ) + + self.assertEqual(list(frame.columns)[:2], ["patient_id", "record_name"]) + self.assertEqual(frame["patient_id"].tolist(), ["101"]) + row = frame.iloc[0] + for column in frame.columns[2:]: + self.assertTrue(Path(row[column]).is_absolute()) + self.assertTrue(Path(row[column]).is_file()) + self.assertEqual(dataset.dataset_name, "sleep_accel") + + def test_incomplete_record_is_skipped_with_warning(self) -> None: + _write_subject(self.root, "101", [0]) + _write_subject(self.root, "102", [0]) + (self.root / "steps" / "102_steps.txt").unlink() + + with self.assertLogs("pyhealth.datasets.sleep_accel", "WARNING") as logs: + dataset = SleepAccelDataset( + root=str(self.root), + cache_dir=str(self.root / "cache"), + num_workers=1, + ) + + frame = pd.read_csv(self.root / "sleep_accel-pyhealth.csv", dtype=str) + self.assertEqual(frame["patient_id"].tolist(), ["101"]) + self.assertIn("missing steps_file", logs.output[0]) + self.assertEqual(len(dataset.unique_patient_ids), 1) + + def test_invalid_root_raises(self) -> None: + with self.assertRaisesRegex(ValueError, "not a directory"): + SleepAccelDataset(root=str(self.root / "missing")) + + def test_dev_uses_isolated_cache_key(self) -> None: + _write_subject(self.root, "101", [0]) + cache_dir = str(self.root / "cache") + dev = SleepAccelDataset( + root=str(self.root), cache_dir=cache_dir, dev=True, num_workers=1 + ) + full = SleepAccelDataset( + root=str(self.root), cache_dir=cache_dir, dev=False, num_workers=1 + ) + + self.assertTrue(dev.dev) + self.assertFalse(full.dev) + self.assertNotEqual(dev.cache_dir, full.cache_dir) + + +class TestSleepAccelHelpers(unittest.TestCase): + def test_stage_map_and_loaders(self) -> None: + self.assertEqual( + SLEEP_ACCEL_STAGE_MAP, + {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 4, -1: -1}, + ) + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_subject(root, "1", [0, 5, -1]) + stages, starts = load_sleep_accel_stages( + root / "labels" / "1_labeled_sleep.txt" + ) + times, bpm = load_sleep_accel_heart_rate( + root / "heart_rate" / "1_heartrate.txt" + ) + self.assertEqual(stages.tolist(), [0, 4, -1]) + self.assertEqual(starts.tolist(), [0.0, 30.0, 60.0]) + self.assertEqual(times[0], -30.0) + self.assertTrue(np.all(bpm == 60.0)) + + def test_heart_rate_grid_validation(self) -> None: + row = _heart_rate_to_grid([0.0, 30.0], [60.0, 120.0], 4, 30.0) + np.testing.assert_allclose(row, [1.0, 0.875, 0.75, 0.625], atol=1e-6) + self.assertEqual(row.dtype, np.float32) + zeroed = _heart_rate_to_grid([0.0, 30.0], [30.0, 300.0], 4, 30.0) + np.testing.assert_array_equal(zeroed, np.zeros(4)) + + +class TestSleepStagingIBISleepAccel(unittest.TestCase): + def setUp(self) -> None: + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) / "sleep-accel" + self.root.mkdir() + + def test_label_map_shape_and_unknown(self) -> None: + _write_subject(self.root, "1", [0, 1, 2, 3, 4, 5, -1]) + + samples = SleepStagingIBISleepAccel()( + _patient("1", [_event(self.root, "1")]) + ) + + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["label"].tolist(), [0, 1, 1, 1, 1, 2, -1]) + self.assertEqual(sample["label"].dtype, np.int64) + self.assertEqual(sample["signal"].shape, (7, 750)) + self.assertEqual(sample["signal"].dtype, np.float32) + self.assertEqual(sample["lengths"], 7) + self.assertEqual(sample["record_id"], "1") + np.testing.assert_allclose(sample["signal"][0], 1.0) + + def test_default_keeps_epochs_without_heart_rate(self) -> None: + _write_subject(self.root, "1", [0, 1, 5]) + ( + self.root / "heart_rate" / "1_heartrate.txt" + ).write_text("-15,60\n15,60\n75,60\n105,60\n") + patient = _patient("1", [_event(self.root, "1")]) + + kept = SleepStagingIBISleepAccel()(patient)[0] + dropped = SleepStagingIBISleepAccel(require_signal=True)(patient)[0] + + self.assertEqual(kept["signal"].shape, (3, 750)) + self.assertEqual(kept["label"].tolist(), [0, 1, 2]) + self.assertEqual(dropped["signal"].shape, (2, 750)) + self.assertEqual(dropped["label"].tolist(), [0, 2]) + + def test_max_epochs_truncates(self) -> None: + _write_subject(self.root, "1", [0, 5, 0, 5]) + + samples = SleepStagingIBISleepAccel(max_epochs=2)( + _patient("1", [_event(self.root, "1")]) + ) + + self.assertEqual(len(samples), 1) + self.assertEqual(samples[0]["signal"].shape, (2, 750)) + self.assertEqual(samples[0]["label"].tolist(), [0, 2]) + + def test_set_task_integration(self) -> None: + _write_subject(self.root, "1", [0, 5]) + _write_subject(self.root, "2", [1, -1]) + + dataset = SleepAccelDataset( + root=str(self.root), cache_dir=str(self.root / "cache"), num_workers=1 + ) + samples = dataset.set_task( + SleepStagingIBISleepAccel(), num_workers=1 + ) + + self.assertEqual(len(samples), 2) + self.assertEqual( + sorted(sample["patient_id"] for sample in samples), ["1", "2"] + ) + for sample in samples: + self.assertEqual(sample["signal"].shape, (2, 750)) + self.assertEqual(sample["label"].dtype, torch.int64) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_sleep_staging_ibi.py b/tests/core/test_sleep_staging_ibi.py new file mode 100644 index 0000000000..c36a43b4b2 --- /dev/null +++ b/tests/core/test_sleep_staging_ibi.py @@ -0,0 +1,163 @@ +"""Tests for the shared per-recording IBI sleep-staging helpers. + +All waveforms and beat times are synthetic; no real dataset is required. +""" + +import unittest + +import numpy as np + +from pyhealth.tasks.sleep_staging_ibi import ( + SleepStagingIBIDREAMT, + SleepStagingIBIISRUC, + SleepStagingIBIMESA, + SleepStagingIBISHHS, + SleepStagingIBISleepAccel, + _beat_annotations_to_ibi, + _detect_peaks, + _heart_rate_to_grid, + _heart_rate_to_ibi, + _ibi_to_epoch_grid, + _peaks_to_ibi, + _to_three_class, + _truncate_epochs, +) + + +class TestIBIHelpers(unittest.TestCase): + def test_peaks_to_ibi_sample_and_hold(self): + ibi = _peaks_to_ibi([0, 100, 250], 100, 2.0, length=300) + self.assertEqual(ibi.shape, (300,)) + np.testing.assert_allclose(ibi[:100], 1.0) + np.testing.assert_allclose(ibi[100:250], 1.5) + np.testing.assert_allclose(ibi[250:], 0.0) + + def test_peaks_to_ibi_long_interval_and_few_peaks(self): + ibi = _peaks_to_ibi([0, 300], 100, 2.0, length=400) + np.testing.assert_allclose(ibi, 0.0) + np.testing.assert_allclose(_peaks_to_ibi([10], 100, 2.0, 20), 0.0) + + def test_beat_annotations_delegate_to_peak_expansion(self): + left = _beat_annotations_to_ibi([0, 50, 110], 50, 1.5, 120) + right = _peaks_to_ibi([0, 50, 110], 50, 1.5, 120) + np.testing.assert_array_equal(left, right) + + def test_heart_rate_to_ibi(self): + ibi = _heart_rate_to_ibi([0.0, 1.0, 2.0], [60.0, 60.0, 120.0], 2.0) + self.assertEqual(ibi.shape, (3,)) + np.testing.assert_allclose(ibi[:2], [1.0, 1.0], atol=1e-6) + self.assertAlmostEqual(float(ibi[2]), 0.5) + + def test_ibi_to_epoch_grid_stride(self): + ibi = np.arange(4 * 100, dtype=np.float64) + grid = _ibi_to_epoch_grid(ibi, 30.0, 100, 4, downsample_factor=1) + self.assertEqual(grid.shape, (4, 100)) + self.assertEqual(grid.dtype, np.float32) + np.testing.assert_allclose(grid[0], ibi[:100]) + + def test_ibi_to_epoch_grid_resamples_when_stride_mismatches(self): + ibi = np.ones(4 * 120) + grid = _ibi_to_epoch_grid(ibi, 30.0, 100, 4, downsample_factor=7) + self.assertEqual(grid.shape, (4, 100)) + np.testing.assert_allclose(grid, 1.0, atol=0.1) + + def test_stage_maps(self): + self.assertEqual(_to_three_class("W"), 0) + self.assertEqual(_to_three_class("N1"), 1) + self.assertEqual(_to_three_class("N4"), 1) + self.assertEqual(_to_three_class("R"), 2) + self.assertEqual(_to_three_class("Missing"), -1) + self.assertEqual(_to_three_class("P"), -1) + self.assertEqual(_to_three_class("S4", scheme="rk"), 1) + labels = _to_three_class([0, 1, 2, 3, 4, -1]) + self.assertEqual(labels.tolist(), [0, 1, 1, 1, 2, -1]) + self.assertEqual(labels.dtype, np.int64) + + def test_truncate_epochs(self): + signal, label = _truncate_epochs(np.ones((5, 750)), np.arange(5), 3) + self.assertEqual(signal.shape, (3, 750)) + self.assertEqual(label.tolist(), [0, 1, 2]) + + def test_detect_peaks_scipy_fallback(self): + waveform = np.zeros(300) + waveform[50] = waveform[150] = waveform[250] = 10.0 + peaks = _detect_peaks(waveform, 100, "ecg", backend="scipy") + self.assertEqual(peaks.tolist(), [50, 150, 250]) + + def test_detect_peaks_defaults_to_scipy(self): + waveform = np.zeros(100) + waveform[20] = waveform[60] = 1.0 + self.assertEqual(_detect_peaks(waveform, 100, "ecg").tolist(), [20, 60]) + + def test_task_peak_backend_defaults_to_scipy(self): + tasks = ( + SleepStagingIBIDREAMT(), + SleepStagingIBISHHS(), + SleepStagingIBIMESA(), + SleepStagingIBIISRUC(), + SleepStagingIBISleepAccel(), + ) + for task in tasks: + with self.subTest(task=task.task_name): + self.assertEqual(task.peak_backend, "scipy") + + def test_peak_backend_opt_in(self): + for backend in ("auto", "neurokit", "biosppy"): + with self.subTest(backend=backend): + task = SleepStagingIBIDREAMT(peak_backend=backend) + self.assertEqual(task.peak_backend, backend) + + def test_heart_rate_grid_zeroes_unobserved_and_outliers(self): + row = _heart_rate_to_grid([1.0, 2.0], [60.0, 300.0], 4, 4.0) + self.assertEqual(row.dtype, np.float32) + self.assertEqual(row[0], 0.0) + self.assertEqual(row[1], 1.0) + self.assertEqual(row[2], 0.0) + self.assertEqual(row[3], 0.0) + + def test_new_task_defaults(self): + accel = SleepStagingIBISleepAccel() + isruc = SleepStagingIBIISRUC(scorer="expert2") + self.assertEqual(accel.task_name, "SleepStagingIBISleepAccel") + self.assertEqual(accel.max_epochs, 1100) + self.assertEqual(accel.points_per_epoch, 750) + self.assertEqual(isruc.task_name, "SleepStagingIBIISRUC") + self.assertEqual(isruc.scorer, "expert2") + self.assertEqual(isruc.scorer_index, 2) + self.assertEqual(isruc.downsample_factor, 8) + + def test_invalid_constructor_arguments(self): + with self.assertRaises(ValueError): + SleepStagingIBIDREAMT(epoch_seconds=0) + with self.assertRaises(ValueError): + SleepStagingIBIDREAMT(points_per_epoch=0) + with self.assertRaises(ValueError): + SleepStagingIBIDREAMT(max_epochs=0) + with self.assertRaises(ValueError): + SleepStagingIBIDREAMT(peak_backend="nope") + with self.assertRaises(ValueError): + SleepStagingIBIDREAMT(signal_source="nope") + with self.assertRaises(ValueError): + SleepStagingIBISHHS(source_fs=0) + with self.assertRaises(ValueError): + SleepStagingIBIMESA(downsample_factor=0) + with self.assertRaises(ValueError): + SleepStagingIBISleepAccel(min_ibi=0) + with self.assertRaises(ValueError): + SleepStagingIBISleepAccel(min_ibi=2.0) + with self.assertRaises(ValueError): + SleepStagingIBISleepAccel(heart_rate_padding=-1) + with self.assertRaises(ValueError): + SleepStagingIBISleepAccel(points_per_epoch=0) + with self.assertRaises(ValueError): + SleepStagingIBIISRUC(scorer="expert3") + with self.assertRaises(ValueError): + SleepStagingIBIISRUC(source_fs=0) + with self.assertRaises(ValueError): + SleepStagingIBIISRUC(downsample_factor=0) + with self.assertRaises(ValueError): + SleepStagingIBIISRUC(peak_backend="nope") + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_watchsleepnet.py b/tests/core/test_watchsleepnet.py new file mode 100644 index 0000000000..f91a96e27f --- /dev/null +++ b/tests/core/test_watchsleepnet.py @@ -0,0 +1,207 @@ +"""Tests for the simplified WatchSleepNet model. All data is synthetic.""" + +import tempfile +import unittest +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +from pyhealth.datasets import create_sample_dataset +from pyhealth.models import WatchSleepNet +from pyhealth.trainer import Trainer + +SEQ_LEN = 3 +EPOCH_LEN = 750 + + +def _dataset(n_samples=2, include_lengths=True, single_epoch=False, seed=0): + rng = np.random.default_rng(seed) + shape = (EPOCH_LEN,) if single_epoch else (SEQ_LEN, EPOCH_LEN) + samples = [] + for i in range(n_samples): + sample = { + "patient_id": str(i), + "signal": rng.standard_normal(shape).astype(np.float32), + "label": rng.integers(0, 3, size=1 if single_epoch else SEQ_LEN).astype( + np.int64 + ), + } + if include_lengths: + sample["lengths"] = 1 if single_epoch else SEQ_LEN + samples.append(sample) + schema = {"signal": "tensor"} + if include_lengths: + schema["lengths"] = "raw" + return create_sample_dataset( + samples=samples, + input_schema=schema, + output_schema={"label": ("tensor", {"dtype": torch.long})}, + ) + + +def _labeled_dataset(labels_per_sample): + samples = [] + for i, labels in enumerate(labels_per_sample): + samples.append({ + "patient_id": str(i), + "signal": np.zeros((len(labels), EPOCH_LEN), dtype=np.float32), + "label": np.asarray(labels, dtype=np.int64), + "lengths": len(labels), + }) + return create_sample_dataset( + samples=samples, + input_schema={"signal": "tensor", "lengths": "raw"}, + output_schema={"label": ("tensor", {"dtype": torch.long})}, + ) + + +def _tiny_model(dataset, **kwargs): + params = { + "num_channels": 16, + "kernel_size": 3, + "hidden_dim": 32, + "num_heads": 8, + "num_layers": 1, + "tcn_layers": 1, + } + params.update(kwargs) + return WatchSleepNet(dataset, **params) + + +class TestWatchSleepNet(unittest.TestCase): + def test_construction_and_label_processor(self): + model = _tiny_model(_dataset(), n_classes=4) + self.assertEqual(model.loss, "ce") + self.assertEqual(model.n_classes, 4) + self.assertEqual(model.label_processors["label"].size(), 4) + self.assertEqual(model.label_processor.size(), 4) + self.assertIs(model.forward_from_embedding.__func__, model.forward.__func__) + self.assertNotIn("_dummy_param", model.state_dict()) + + def test_loss_modes_match_reference_formulas(self): + dataset = _labeled_dataset([[0, 1, -1], [1, 2, 2]]) + logits = torch.tensor( + [[2.0, 0.5, -1.0], [0.0, 1.0, 3.0]], requires_grad=True + ) + plain = logits.detach() + targets = torch.tensor([0, 2]) + weights = torch.tensor([5.0 / 3.0, 5.0 / 6.0, 5.0 / 6.0]) + per_class_ce = F.cross_entropy(plain, targets, reduction="none") + pt = torch.exp(-per_class_ce).clamp(max=1.0) + focal = ((1.0 - pt) ** 2.0 * per_class_ce).mean() + cases = ( + ("ce", F.cross_entropy(plain, targets)), + ("weighted_ce", F.cross_entropy(plain, targets, weight=weights)), + ("focal", focal), + ("inverse_focal", ((1.0 - pt) ** 2.0 * per_class_ce + * weights[targets]).mean()), + ) + baseline_keys = set(_tiny_model(dataset).state_dict()) + for loss, expected in cases: + with self.subTest(loss=loss): + model = _tiny_model(dataset, loss=loss) + actual = model._training_loss(logits, targets) + self.assertTrue( + torch.allclose(actual, expected, atol=1e-6), + msg=f"{loss}: {actual.item()} != {expected.item()}", + ) + self.assertEqual(set(model.state_dict()), baseline_keys) + actual.backward() + self.assertIsNotNone(logits.grad) + self.assertTrue(torch.isfinite(logits.grad).all()) + + def test_forward_shapes_gradients_and_masking(self): + dataset = _dataset() + model = _tiny_model(dataset) + x = torch.randn(2, SEQ_LEN, EPOCH_LEN) + y = torch.tensor([[0, 1, -1], [1, 2, -1]]) + out = model(signal=x, label=y, lengths=[2, 2]) + self.assertEqual(out["logit"].shape, (2, SEQ_LEN, 3)) + self.assertEqual(out["y_prob"].shape, (4, 3)) + self.assertEqual(out["y_true"].tolist(), [0, 1, 1, 2]) + self.assertTrue(torch.isfinite(out["loss"])) + self.assertTrue(torch.allclose(out["y_prob"].sum(dim=1), torch.ones(4))) + # Padded positions are zeroed in the returned logit grid. + self.assertTrue(torch.equal(out["logit"][0, 2], torch.zeros(3))) + out["loss"].backward() + for name in ( + "feature_extractor.layers.2.conv1.weight", + "tcn.layers.0.0.weight", + "lstm_layer.lstm.weight_ih_l0", + "lstm_layer.attention.in_proj_weight", + "classifier.weight", + ): + param = dict(model.named_parameters())[name] + self.assertIsNotNone(param.grad, name) + + def test_derived_lengths_and_single_epoch(self): + dataset = _dataset(include_lengths=False) + model = _tiny_model(dataset) + x = torch.stack( + [torch.randn(SEQ_LEN, EPOCH_LEN), torch.zeros(SEQ_LEN, EPOCH_LEN)] + ) + x[0, 1:] = 0 + y = torch.tensor([[0, -1, 2], [1, 2, 0]]) + out = model(signal=x, label=y) + self.assertEqual(out["y_true"].tolist(), [0, 1]) + self.assertTrue(torch.equal(out["logit"][1, 1:], torch.zeros(2, 3))) + + single = _tiny_model(_dataset(single_epoch=True)) + out = single( + signal=torch.randn(2, EPOCH_LEN), label=torch.tensor([0, -1]) + ) + self.assertEqual(out["logit"].shape, (2, 1, 3)) + self.assertEqual(out["y_true"].tolist(), [0]) + + def test_quantization_and_checkpoint_roundtrip(self): + dataset = _dataset() + fp32 = _tiny_model(dataset) + bf16 = _tiny_model(dataset, quantization="bf16") + self.assertEqual(bf16.classifier.weight.dtype, torch.bfloat16) + args = { + "signal": torch.randn(2, SEQ_LEN, EPOCH_LEN), + "label": torch.tensor([[0, 1, 2], [2, 0, 1]]), + "lengths": [2, 3], + } + fp32.eval() + bf16.eval() + for model in (fp32, bf16): + out = model(**args) + self.assertEqual(out["logit"].dtype, torch.float32) + self.assertTrue(torch.isfinite(out["loss"])) + try: + fp16 = _tiny_model(dataset, quantization="fp16") + except (RuntimeError, NotImplementedError) as exc: + self.skipTest(f"PyTorch cannot run fp16 here: {exc}") + fp16.eval() + self.assertTrue(torch.isfinite(fp16(**args)["loss"])) + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "watchsleepnet.pt" + Trainer(model=fp32, device="cpu", enable_logging=False).save_ckpt(str(path)) + state = torch.load(path, weights_only=True) + self.assertEqual(len(state), len(fp32.state_dict())) + reloaded = _tiny_model(dataset, quantization="fp16") + Trainer(model=reloaded, device="cpu", enable_logging=False).load_ckpt( + str(path) + ) + reloaded.eval() + self.assertTrue(torch.isfinite(reloaded(**args)["loss"])) + + def test_invalid_arguments(self): + dataset = _dataset() + for kwargs in ( + {"n_classes": 1}, + {"num_layers": 0}, + {"hidden_dim": 30, "num_heads": 8}, + {"quantization": "fp8"}, + {"loss": "focal_inverse"}, + ): + with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): + _tiny_model(dataset, **kwargs) + + +if __name__ == "__main__": + unittest.main()