diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index f681224253..174e52d10e 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -268,6 +268,7 @@ Available Tasks BCI Competition IV 2a Left vs Right Hand PTB-XL Tasks Sleep Staging v2 + Sleep Staging (SHHS) Benchmark EHRShot EHR Text Serialization (LLM encoders) EHR Foundation Model Timelines diff --git a/docs/api/tasks/pyhealth.tasks.sleep_staging_shhs.rst b/docs/api/tasks/pyhealth.tasks.sleep_staging_shhs.rst new file mode 100644 index 0000000000..a78e16b770 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.sleep_staging_shhs.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.sleep_staging_shhs +================================ + +.. autoclass:: pyhealth.tasks.sleep_staging_shhs.SleepStagingSHHS + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py b/examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py new file mode 100644 index 0000000000..129ab1e1d8 --- /dev/null +++ b/examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py @@ -0,0 +1,94 @@ +"""Sleep staging on SHHS with SparcNet (ContraWR is a drop-in swap). + +Loads the Sleep Heart Health Study polysomnography release with +``SHHSDataset``, cuts it into 30-second epochs labeled W/N1/N2/N3/N4/REM with +``SleepStagingSHHS``, splits by patient and trains ``SparcNet``. Despite the +file name, the model is SparcNet; replace it with +``ContraWR(dataset=sample_dataset)`` to train ContraWR instead. + +Data: SHHS visits 1 and 2, restricted. An NSRR account and an approved data +access request are required, and the data are not redistributable +(https://sleepdata.org/datasets/shhs). After approval, download with +``gem install nsrr`` then ``nsrr download shhs/polysomnography``, and set +``SHHS_ROOT`` to the resulting ``polysomnography`` folder, which holds +``edfs/`` and ``annotations-events-profusion/``. + +Run: ``python examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py``. +The full release is hundreds of GB, so the script passes ``dev=True`` and +defaults to visit 1 only; drop ``dev`` for a real run. +""" + +from pathlib import Path + +from pyhealth.datasets import SHHSDataset, get_dataloader, split_by_patient +from pyhealth.models import SparcNet +from pyhealth.tasks import SleepStagingSHHS +from pyhealth.trainer import Trainer + +#: The ``polysomnography`` folder of the NSRR SHHS release. +SHHS_ROOT = "/path/to/shhs/polysomnography" +#: Where to cache the tokenized samples and the fitted processors. +CACHE_DIR = Path.home() / ".cache" / "pyhealth" / "shhs_demo" + + +def main() -> None: + # STEP 1: build the metadata tables and load them. + # ``dev=True`` limits the event table to the first 1000 participants. + base_dataset = SHHSDataset( + root=SHHS_ROOT, + visits=("shhs1",), + cache_dir=CACHE_DIR, + dev=True, + ) + base_dataset.stats() + + # STEP 2: apply the sleep-staging task. + # 30 s epochs, the length the reading centre scored. Epochs labelled as + # movement are dropped, so the label space is 0-5. + task = SleepStagingSHHS(epoch_seconds=30) + print(f"Task: {task.task_name}") + print(f"Input schema: {list(task.input_schema)}") + print(f"Output schema: {list(task.output_schema)}") + + sample_dataset = base_dataset.set_task(task, num_workers=4) + print(f"Total epoch samples: {len(sample_dataset)}") + + sample = sample_dataset[0] + print(f" patient_id: {sample['patient_id']}") + print(f" record_id: {sample['record_id']}") + print(f" signal: {tuple(sample['signal'].shape)} (channels x samples)") + print(f" label: {int(sample['label'].item())}") + + # STEP 3: split by participant, so both nights of a person never straddle + # the train/test boundary. + train_dataset, val_dataset, test_dataset = split_by_patient( + sample_dataset, [0.8, 0.1, 0.1] + ) + print( + "samples train/val/test", + len(train_dataset), + len(val_dataset), + len(test_dataset), + ) + train_loader = get_dataloader(train_dataset, batch_size=32, shuffle=True) + val_loader = get_dataloader(val_dataset, batch_size=32, shuffle=False) + test_loader = get_dataloader(test_dataset, batch_size=32, shuffle=False) + + # STEP 4: define the model. + model = SparcNet(dataset=sample_dataset) + + # STEP 5: train. + trainer = Trainer(model=model, metrics=["accuracy", "f1_weighted"]) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=5, + monitor="accuracy", + ) + + # STEP 6: evaluate. + print(trainer.evaluate(test_loader)) + + +if __name__ == "__main__": + main() diff --git a/examples/old/README.md b/examples/old/README.md index ef9b15077a..fe5cc9fe49 100644 --- a/examples/old/README.md +++ b/examples/old/README.md @@ -11,7 +11,6 @@ or the [examples index](../README.md). |---|---|---| | `cardiology_detection_isAR_SparcNet.py` | 1.x task function `cardiology_isAR_fn` on the 1.x `CardiologyDataset` | `ecg/cardiology/cardiology_detection_sparcnet.py` | | `eeg/sleep_staging/sleep_staging_ISRUC_SparcNet.py` | 1.x task function `sleep_staging_isruc_fn` | `eeg/isruc/isruc_sleep_staging.py` | -| `eeg/sleep_staging/sleep_staging_shhs_contrawr.py` | `SHHSDataset` hasn't been ported to 2.x (no `set_task`) | `eeg/sleep_staging/contrawr_sleepedf.ipynb` | | `conformal_eeg/tuev_eeg_quickstart.ipynb` | duplicate with a stale layer size; fails on 2.x | `eeg/tuh_eeg/tuev_eeg_event_classification.ipynb`, `conformal_eeg/contrawr_tuev_eeg.ipynb` | | `conformal_eeg/test_tfm_tuev_inference.py`, `conformal_eeg/test_tfm_tuab_inference.py` | personal checkpoint checks; need unreleased weight files | `conformal_eeg/*_conformal.py --model tfm` | | `cxr/covid19cxr_tutorial_display.py` | near-copy of the COVID-19 CXR tutorial | `cxr/covid19cxr_tutorial.py` | diff --git a/examples/old/eeg/sleep_staging/sleep_staging_shhs_contrawr.py b/examples/old/eeg/sleep_staging/sleep_staging_shhs_contrawr.py deleted file mode 100644 index 891eea895e..0000000000 --- a/examples/old/eeg/sleep_staging/sleep_staging_shhs_contrawr.py +++ /dev/null @@ -1,50 +0,0 @@ -from pyhealth.datasets import SHHSDataset, get_dataloader, split_by_patient -from pyhealth.models import SparcNet -from pyhealth.tasks import sleep_staging_shhs_fn -from pyhealth.trainer import Trainer - -# step 1: load signal data -dataset = SHHSDataset( - root="/srv/local/data/SHHS/polysomnography", - dev=True, - refresh_cache=False, -) - -# step 2: set task -# epochs without a corresponding SleepStage annotation are skipped -sleep_staging_ds = dataset.set_task(sleep_staging_shhs_fn) -sleep_staging_ds.stat() - -# split dataset -train_dataset, val_dataset, test_dataset = split_by_patient( - sleep_staging_ds, [0.6, 0.2, 0.2] -) -train_dataloader = get_dataloader(train_dataset, batch_size=32, shuffle=True) -val_dataloader = get_dataloader(val_dataset, batch_size=32, shuffle=False) -test_dataloader = get_dataloader(test_dataset, batch_size=32, shuffle=False) -print( - "loader size: train/val/test", - len(train_dataset), - len(val_dataset), - len(test_dataset), -) - -# STEP 3: define model -model = SparcNet( - dataset=sleep_staging_ds, - feature_keys=["signal"], - label_key="label", - mode="multiclass", -) - -# STEP 4: define trainer -trainer = Trainer(model=model) -trainer.train( - train_dataloader=train_dataloader, - val_dataloader=val_dataloader, - epochs=5, - monitor="accuracy", -) - -# STEP 5: evaluate -print(trainer.evaluate(test_dataloader)) diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 42c8727c56..20273f5631 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -19,8 +19,8 @@ def __init__(self, *args, **kwargs): docs = "https://pyhealth.readthedocs.io/en/latest/api/datasets.html" cls = type(self).__name__ if cls != name: - # An in-tree or user dataset still built on the 1.x base class - # (e.g. SHHSDataset, MIMICExtractDataset). It never worked on 2.x: the stub set no + # A user dataset (or a still-unported in-tree one) that builds on + # the 1.x base class. It never worked on 2.x: the stub set no # attributes and provided no set_task. raise NotImplementedError( f"{cls} is built on {name}, which was removed in PyHealth " diff --git a/pyhealth/datasets/configs/shhs.yaml b/pyhealth/datasets/configs/shhs.yaml new file mode 100644 index 0000000000..77d6cea33e --- /dev/null +++ b/pyhealth/datasets/configs/shhs.yaml @@ -0,0 +1,20 @@ +version: "1.0" +tables: + shhs1: + file_path: "shhs1-pyhealth.csv" + patient_id: "patient_id" + timestamp: null + attributes: + - "visit" + - "record_id" + - "signal_file" + - "annotation_file" + shhs2: + file_path: "shhs2-pyhealth.csv" + patient_id: "patient_id" + timestamp: null + attributes: + - "visit" + - "record_id" + - "signal_file" + - "annotation_file" diff --git a/pyhealth/datasets/shhs.py b/pyhealth/datasets/shhs.py index aa6fbd68b1..c716c4d871 100644 --- a/pyhealth/datasets/shhs.py +++ b/pyhealth/datasets/shhs.py @@ -1,11 +1,170 @@ -import os +"""SHHS (Sleep Heart Health Study) polysomnography dataset. -import numpy as np +Reads the NSRR ``polysomnography`` release: one EDF recording per night under +``edfs/`` and one Profusion XML annotation per recording under +``annotations-events-profusion/``. -from pyhealth.datasets import BaseSignalDataset +``prepare_metadata`` writes one metadata CSV per visit +(``shhs1-pyhealth.csv``, ``shhs2-pyhealth.csv``) next to the release, or under +``~/.cache/pyhealth/shhs/`` when that directory is not writable. +The default task is +:class:`~pyhealth.tasks.sleep_staging_shhs.SleepStagingSHHS`. +""" -class SHHSDataset(BaseSignalDataset): +import logging +import xml.etree.ElementTree as ET +from pathlib import Path + +import pandas as pd + +from .base_dataset import BaseDataset +from .metadata_csv import ( + metadata_csv_exists, + resolve_metadata_root, + write_metadata_csv, +) + +logger = logging.getLogger(__name__) + +# Visits published in the NSRR polysomnography release. +_VALID_VISITS = ("shhs1", "shhs2") + +# Metadata CSV name for a single visit. The visit is part of the name, so the +# two tables never write to the same file even though they share a directory. +_CSV_TEMPLATE = "{visit}-pyhealth.csv" + +# Candidate parents of the Profusion XML inside +# ``annotations-events-profusion``. The released layout is one directory per +# visit; the legacy 1.x loader looked for shhs2 under ``label/``. Both are +# accepted, in this order, so either release works. +_ANNOTATION_SUBDIRS = ("{visit}", "label") + +# Stage codes written by the SHHS reading centre: wake, N1-N4 and REM. Code 9 +# marks movement/unscored epochs and is not a class, so it is dropped. +VALID_SLEEP_STAGES = frozenset({0, 1, 2, 3, 4, 5}) + + +def parse_patient_id(file_name: str | Path) -> str: + """Return the NSRR participant id encoded in a SHHS recording file name. + + SHHS names recordings ``shhs1-200001.edf``. The numeric part is the + participant, and it is shared by that person's visit 1 and visit 2 + recordings, so grouping on it keeps both nights under one + :class:`~pyhealth.data.Patient`. + + Args: + file_name: Recording file name or path, with or without a directory. + + Returns: + The participant id, for example ``"200001"``. + + Raises: + ValueError: If the name does not follow the ``-`` layout. + + Examples: + >>> from pyhealth.datasets.shhs import parse_patient_id + >>> parse_patient_id("shhs1-200001.edf") + '200001' + >>> parse_patient_id("/data/edfs/shhs2/shhs2-200001.edf") + '200001' + """ + stem = Path(file_name).name.split(".")[0] + parts = stem.split("-") + if len(parts) != 2 or not parts[1].isdigit(): + raise ValueError( + f"Unexpected SHHS recording name {Path(file_name).name!r}; " + "expected '-.edf'" + ) + return parts[1] + + +def read_sleep_stages(annotation_file: str | Path) -> list[int]: + """Read the per-epoch sleep-stage codes from a Profusion XML file. + + Each ``SleepStage`` element is one 30 s epoch, in recording order. + + Args: + annotation_file: Path to ``--profusion.xml``. + + Returns: + One integer stage code per scored epoch. + + Raises: + ValueError: If the document has no ``SleepStages`` element or a stage + is not an integer. + xml.etree.ElementTree.ParseError: If the file is not well-formed XML, + for example a truncated download or an HTML error page. Callers + that iterate a dataset should catch this alongside ``ValueError`` + to skip one broken night instead of aborting the run. + + Examples: + >>> from pyhealth.datasets.shhs import read_sleep_stages + >>> import tempfile, pathlib + >>> path = pathlib.Path(tempfile.mkdtemp()) / "shhs1-200001-profusion.xml" + >>> _ = path.write_text( + ... "" + ... "02" + ... "" + ... ) + >>> read_sleep_stages(path) + [0, 2] + """ + root = ET.parse(annotation_file).getroot() + stages = root.find("SleepStages") + if stages is None: + raise ValueError(f"No SleepStages element in {annotation_file}") + codes = [] + for element in stages.findall("SleepStage"): + text = (element.text or "").strip() + try: + codes.append(int(text)) + except ValueError as error: + raise ValueError( + f"Non-integer sleep stage {text!r} in {annotation_file}" + ) from error + return codes + + +def _normalize_visits(visits) -> list[str]: + """Validate a ``visits`` argument and return the visits in the order given.""" + if visits is None: + return list(_VALID_VISITS) + if isinstance(visits, str): + visits = (visits,) + normalized: list[str] = [] + for visit in visits: + key = str(visit).strip().lower() + if key not in _VALID_VISITS: + raise ValueError( + f"visits must be a subset of {_VALID_VISITS}, got {visit!r}" + ) + if key not in normalized: + normalized.append(key) + if not normalized: + raise ValueError("visits must name at least one visit") + return normalized + + +def _annotation_path(root: Path, visit: str, patient_id: str) -> Path | None: + """Return the Profusion XML for one recording, or None when absent.""" + name = f"{visit}-{patient_id}-profusion.xml" + base = root / "annotations-events-profusion" + for subdir in _ANNOTATION_SUBDIRS: + candidate = base / subdir.format(visit=visit) / name + if candidate.is_file(): + if subdir == "label": + logger.warning( + "Found %s under the legacy 'label/' directory; the released " + "NSRR layout uses '%s/'.", + name, + visit, + ) + return candidate + return None + + +class SHHSDataset(BaseDataset): """Base EEG dataset for Sleep Heart Health Study (SHHS) The Sleep Heart Health Study (SHHS) is a multi-center cohort study implemented by the National Heart Lung & Blood Institute to determine the cardiovascular and other consequences of sleep-disordered breathing. It tests whether sleep-related breathing is associated with an increased risk of coronary heart disease, stroke, all cause mortality, and hypertension. In all, 6,441 men and women aged 40 years and older were enrolled between November 1, 1995 and January 31, 1998 to take part in SHHS Visit 1. During exam cycle 3 (January 2001- June 2003), a second polysomnogram (SHHS Visit 2) was obtained in 3,295 of the participants. CVD Outcomes data were monitored and adjudicated by parent cohorts between baseline and 2011. More than 130 manuscripts have been published investigating predictors and outcomes of sleep disorders. @@ -20,104 +179,165 @@ class SHHSDataset(BaseSignalDataset): ``annotations-events-profusion/``. Args: - dataset_name: name of the dataset. root: the ``polysomnography`` folder (holds ``edfs/`` and ``annotations-events-profusion/``). - dev: whether to enable dev mode (only use a small subset of the data). - Default is False. - refresh_cache: whether to refresh the cache; if true, the dataset will - be processed from scratch and the cache will be updated. Default is False. - - Attributes: - task: Optional[str], name of the task (e.g., "sleep staging"). - Default is None. - samples: Optional[List[Dict]], a list of samples, each sample is a dict with - patient_id, record_id, and other task-specific attributes as key. - Default is None. - patient_to_index: Optional[Dict[str, List[int]]], a dict mapping patient_id to - a list of sample indices. Default is None. - visit_to_index: Optional[Dict[str, List[int]]], a dict mapping visit_id to a - list of sample indices. Default is None. + dataset_name: name of the dataset. Defaults to ``"shhs"``. + config_path: YAML config. Defaults to ``configs/shhs.yaml``. + visits: which visits to load, any subset of ``("shhs1", "shhs2")``. + Defaults to both. Each visit becomes its own table. + **kwargs: forwarded to :class:`~pyhealth.datasets.BaseDataset` + (``cache_dir``, ``num_workers``, ``dev``). + + The metadata CSV holds one row per recording: ``patient_id`` (the + participant, shared by both visits, for example ``"200001"``), ``visit`` + (``"shhs1"`` or ``"shhs2"``), ``record_id`` (``"-"``), + ``signal_file`` (absolute path to the EDF) and ``annotation_file`` + (absolute path to the Profusion XML). Examples: >>> from pyhealth.datasets import SHHSDataset - >>> dataset = SHHSDataset( - ... root="/srv/local/data/SHHS/", - ... ) - >>> dataset.stat() - >>> dataset.info() + >>> dataset = SHHSDataset( # doctest: +SKIP + ... root="/path/to/shhs/polysomnography", + ... ) + >>> dataset.stats() # doctest: +SKIP + >>> samples = dataset.set_task() # doctest: +SKIP + >>> samples[0]["signal"].shape # doctest: +SKIP + torch.Size([2, 3750]) """ - def parse_patient_id(self, file_name): - """ - Args: - file_name: the file name of the shhs datasets. e.g., shhs1-200001.edf + def __init__( + self, + root: str, + dataset_name: str | None = None, + config_path: str | None = None, + visits=None, + **kwargs, + ) -> None: + if config_path is None: + logger.debug("No config path provided, using default config") + config_path = Path(__file__).parent / "configs" / "shhs.yaml" + + self.root = str(root) + self.visits = _normalize_visits(visits) + self.prepare_metadata() + + root_path = Path(self.root) + tables = [] + for visit in self.visits: + csv_name = _CSV_TEMPLATE.format(visit=visit) + if metadata_csv_exists(root_path, "shhs", csv_name): + tables.append(visit) + if not tables: + raise FileNotFoundError( + f"No SHHS metadata for visits {self.visits} under {self.root}. " + "Expected edfs/shhs1 or edfs/shhs2 next to " + "annotations-events-profusion." + ) + + metadata_root = resolve_metadata_root( + root_path, "shhs", _CSV_TEMPLATE.format(visit=tables[0]) + ) + super().__init__( + root=metadata_root, + tables=tables, + dataset_name=dataset_name or "shhs", + config_path=config_path, + **kwargs, + ) + + def prepare_metadata(self) -> None: + """Write one metadata CSV per requested visit, if absent. + + The CSV is skipped when it already exists, either next to the release + or in ``~/.cache/pyhealth/shhs/``. A recording whose + Profusion annotation cannot be found is dropped and counted, so a + partially downloaded release still produces a usable table. + Returns: - patient_id: the patient id of the shhs datasets. e.g., 200001 + None. The CSV path is ``/-pyhealth.csv`` or the cache + equivalent. """ - return file_name.split("-")[1].split(".")[0] - - def process_EEG_data(self): - - # get shhs1 - shhs1 = [] - if os.path.exists(os.path.join(self.root, "edfs/shhs1")): - print("shhs1 exists and load shhs1") - shhs1 = os.listdir(os.path.join(self.root, "edfs/shhs1")) - else: - print("shhs1 does not exist") - - # get shhs2 - shhs2 = [] - if os.path.exists(os.path.join(self.root, "edfs/shhs2")): - print("shhs2 exists and load shhs2") - shhs2 = os.listdir(os.path.join(self.root, "edfs/shhs2")) - else: - print("shhs2 does not exist") - - # get all patient ids - patient_ids = np.unique([self.parse_patient_id(file) for file in shhs1 + shhs2]) - if self.dev: - patient_ids = patient_ids[:5] - # get patient to record maps - # - key: pid: - # - value: [{"load_from_path": None, "file": None, "save_to_path": None}, ...] - patients = {pid: [] for pid in patient_ids} - - # parse shhs1 - for file in shhs1: - pid = self.parse_patient_id(file) - if pid in patient_ids: - patients[pid].append( - { - "load_from_path": self.root, - "signal_file": os.path.join("edfs/shhs1", file), - "label_file": os.path.join("annotations-events-profusion/shhs1", f"shhs1-{pid}-profusion.xml"), - "save_to_path": os.path.join(self.filepath), - } + root = Path(self.root) + for visit in self.visits: + csv_name = _CSV_TEMPLATE.format(visit=visit) + if metadata_csv_exists(root, "shhs", csv_name): + continue + rows = self._metadata_rows(root, visit) + if not rows: + logger.warning( + "No SHHS %s recordings with annotations under %s", visit, root ) + continue + df = pd.DataFrame(rows) + df.sort_values( + ["patient_id", "record_id"], inplace=True, na_position="last" + ) + df.reset_index(drop=True, inplace=True) + write_metadata_csv(df, root, "shhs", csv_name) - # parse shhs2 - for file in shhs2: - pid = self.parse_patient_id(file) - if pid in patient_ids: - patients[pid].append( - { - "load_from_path": self.root, - "signal_file": os.path.join("edfs/shhs2", file), - "label_file": os.path.join("annotations-events-profusion/label", f"shhs2-{pid}-profusion.xml"), - "save_to_path": os.path.join(self.filepath), - } - ) - return patients + @staticmethod + def _metadata_rows(root: Path, visit: str) -> list[dict]: + """Build one metadata row per paired EDF/XML recording for a visit.""" + edf_dir = root / "edfs" / visit + if not edf_dir.is_dir(): + logger.debug("SHHS %s recordings not found: %s", visit, edf_dir) + return [] + + rows: list[dict] = [] + missing = 0 + skipped = 0 + for edf_path in sorted(edf_dir.glob("*.edf")): + try: + patient_id = parse_patient_id(edf_path.name) + except ValueError: + logger.warning("Skipping unparsable SHHS file name: %s", edf_path) + skipped += 1 + continue + annotation_file = _annotation_path(root, visit, patient_id) + if annotation_file is None: + missing += 1 + continue + rows.append( + { + "patient_id": patient_id, + "visit": visit, + "record_id": f"{visit}-{patient_id}", + "signal_file": str(edf_path.resolve()), + "annotation_file": str(annotation_file.resolve()), + } + ) + + if missing: + logger.warning( + "Skipped %d SHHS %s recordings with no Profusion annotation", + missing, + visit, + ) + if skipped: + logger.warning( + "Skipped %d files in %s that do not follow '-.edf'", + skipped, + edf_dir, + ) + return rows + + @property + def default_task(self): + """Return the default sleep-staging task for SHHS. + + Returns: + A :class:`~pyhealth.tasks.sleep_staging_shhs.SleepStagingSHHS` + instance with its default 30 s epochs. + """ + from pyhealth.tasks.sleep_staging_shhs import SleepStagingSHHS + + return SleepStagingSHHS() if __name__ == "__main__": dataset = SHHSDataset( root="/srv/local/data/SHHS/polysomnography", + visits=("shhs1",), dev=True, - refresh_cache=True, ) - dataset.stat() - dataset.info() - print(list(dataset.patients.items())[0]) + dataset.stats() diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 554aa3d8f5..54ec8a18c9 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -230,6 +230,7 @@ from .sleep_staging_isruc import ( SleepStagingSequenceISRUC as SleepStagingSequenceISRUC, ) +from .sleep_staging_shhs import SleepStagingSHHS as SleepStagingSHHS from .temple_university_EEG_tasks import ( EEGEventsTUEV, EEGAbnormalTUAB diff --git a/pyhealth/tasks/sleep_staging.py b/pyhealth/tasks/sleep_staging.py index b239604cd1..77e4f6b02d 100644 --- a/pyhealth/tasks/sleep_staging.py +++ b/pyhealth/tasks/sleep_staging.py @@ -240,21 +240,23 @@ def sleep_staging_shhs_fn(record, epoch_seconds=30): Note that we define the task as a multi-class classification task. + .. deprecated:: + This is the 1.x task function and it cannot be used through + :meth:`~pyhealth.datasets.BaseDataset.set_task`, which expects a + :class:`~pyhealth.tasks.BaseTask` instance. Use + :class:`~pyhealth.tasks.sleep_staging_shhs.SleepStagingSHHS` with + :class:`~pyhealth.datasets.SHHSDataset` instead. + Examples: >>> from pyhealth.datasets import SHHSDataset - >>> shhs = SHHSDataset( - ... root="/srv/local/data/SHHS/polysomnography", - ... dev=True, - ... ) - >>> from pyhealth.tasks import sleep_staging_shhs_fn - >>> shhs_ds = shhs.set_task(sleep_staging_shhs_fn) - >>> shhs_ds.samples[0] - { - 'record_id': 'shhs1-200001-0', - 'patient_id': 'shhs1-200001', - 'epoch_path': '/home/chaoqiy2/.cache/pyhealth/datasets/76c1ce8195a2e1a654e061cb5df4671a/shhs1-200001-0.pkl', - 'label': '0' - } + >>> from pyhealth.tasks import SleepStagingSHHS + >>> shhs = SHHSDataset( # doctest: +SKIP + ... root="/srv/local/data/SHHS/polysomnography", + ... dev=True, + ... ) + >>> shhs_ds = shhs.set_task(SleepStagingSHHS()) # doctest: +SKIP + >>> shhs_ds[0]["signal"].shape # doctest: +SKIP + torch.Size([2, 3750]) """ SAMPLE_RATE = 125 @@ -318,7 +320,8 @@ def sleep_staging_shhs_fn(record, epoch_seconds=30): if __name__ == "__main__": - from pyhealth.datasets import SleepEDFDataset, SHHSDataset, ISRUCDataset + # All demo blocks below are commented out: they need restricted datasets. + # from pyhealth.datasets import SleepEDFDataset, SHHSDataset, ISRUCDataset """ test sleep edf""" # dataset = SleepEDFDataset( @@ -346,17 +349,18 @@ def sleep_staging_shhs_fn(record, epoch_seconds=30): # # print(sleep_staging_ds.patient_to_index) # # print(sleep_staging_ds.record_to_index) # print(sleep_staging_ds.input_info) - - dataset = SHHSDataset( - root="/srv/local/data/SHHS/polysomnography", - dev=True, - refresh_cache=True, - ) - sleep_staging_ds = dataset.set_task(sleep_staging_shhs_fn) - print(sleep_staging_ds.samples[0]) - # print(sleep_staging_ds.patient_to_index) - # print(sleep_staging_ds.record_to_index) - print(sleep_staging_ds.input_info) + + # """ test SHHS""" + # The 1.x function below predates the 2.0 API: SHHSDataset is now a + # BaseDataset, so it takes no refresh_cache and set_task needs a BaseTask. + # Use pyhealth.tasks.SleepStagingSHHS instead. + # dataset = SHHSDataset( + # root="/srv/local/data/SHHS/polysomnography", + # dev=True, + # ) + # sleep_staging_ds = dataset.set_task(SleepStagingSHHS()) + # print(sleep_staging_ds[0]) + # print(sleep_staging_ds.input_info) diff --git a/pyhealth/tasks/sleep_staging_shhs.py b/pyhealth/tasks/sleep_staging_shhs.py new file mode 100644 index 0000000000..5f377a24d8 --- /dev/null +++ b/pyhealth/tasks/sleep_staging_shhs.py @@ -0,0 +1,390 @@ +"""Sleep staging on SHHS polysomnography. + +The SHHS reading centre scored every 30 s of the night: wake, N1, N2, N3, N4 or +REM, with code 9 for movement. By default one scored epoch of the two EEG +channels is one sample. A shorter epoch length cuts each score into several +samples, so ``epoch_seconds=10`` yields three 10 s samples per score. Movement +epochs are dropped because they are not a class. + +The paired dataset is :class:`~pyhealth.datasets.SHHSDataset`, which builds the +``shhs1`` and ``shhs2`` tables from the NSRR ``polysomnography`` release. + +Authors: + - PyHealth Contributors + +References: + - Quan, S. F. et al. The Sleep Heart Health Study: design, rationale, and + methods. Sleep 20, 1077-1085 (1997). + - NSRR: https://sleepdata.org/datasets/shhs +""" + +import logging +import math +from typing import Any, ClassVar +from xml.etree import ElementTree as ET + +import mne +import numpy as np +import torch + +from pyhealth.tasks import BaseTask +from pyhealth.tasks.eegbci import normalize_signal + +logger = logging.getLogger(__name__) + +#: Sampling rate of the released SHHS EDF files, in Hz. Epoch boundaries are +#: recomputed from each file's own ``sfreq``, so a recording is never cut in the +#: wrong place; anything other than this rate is unexpected enough to warn +#: about. +SHHS_SAMPLE_RATE = 125 + +#: Length of one epoch in the released annotations, in seconds. The reading +#: centre scored every 30 s, so ``epoch_seconds`` has to divide this evenly for +#: a score to line up with a whole number of signal windows. +_SCORED_EPOCH_SECONDS = 30 + +#: Channels the 1.x loader took positionally when it could not match names. +_LEGACY_CHANNEL_POSITIONS = (2, 7) + + +def _normalize_channel_name(name: str) -> str: + """Lowercase a channel name and strip the spacing EDF writers vary on.""" + return name.strip().lower().replace(" ", "") + + +def _read_sleep_stages(annotation_file: str) -> list[int]: + """Read the Profusion stage codes, reusing the dataset-level parser. + + Imported lazily because :mod:`pyhealth.datasets` imports + :mod:`pyhealth.tasks` at module load time. + """ + from pyhealth.datasets.shhs import read_sleep_stages + + return read_sleep_stages(annotation_file) + + +def _valid_sleep_stages() -> frozenset[int]: + """Return the stage codes that count as classes.""" + from pyhealth.datasets.shhs import VALID_SLEEP_STAGES + + return VALID_SLEEP_STAGES + + +class SleepStagingSHHS(BaseTask): + """Epoch-level sleep staging for the Sleep Heart Health Study. + + The reading centre scored one stage per 30 s of the night. With the default + ``epoch_seconds=30`` one sample is one scored epoch: ``signal`` holds the + selected EEG channels (in uV) and ``label`` is the stage code ``0``-``5``. + Epochs scored as movement (``9``) are dropped, as are epochs with no + matching signal window. + + A shorter ``epoch_seconds`` cuts each scored epoch into + ``30 / epoch_seconds`` samples that share its label, exactly as + :class:`~pyhealth.tasks.SleepStagingISRUC` does, so ``epoch_seconds=10`` + yields three 10 s samples per score. Lengths that do not divide 30 are + rejected: a score would otherwise cover a fractional number of windows and + the labels would drift out of step with the signal. + + Args: + epoch_seconds: Epoch length in whole seconds. Defaults to ``30``, the + length the reading centre scored. Must divide 30 so signal and + labels stay aligned. + channels: EEG channel names to keep, for example ``["EEG"]``. + Defaults to every channel whose name starts with ``EEG``. The rows + of ``signal`` follow the order given here, not the order the EDF + lists them, so a montage can be named directly. + normalization: Passed to + :func:`~pyhealth.tasks.eegbci.normalize_signal`, for example + ``"95th_percentile"``. Defaults to ``None`` (no normalization). + subjects: Patient ids to keep. Defaults to ``None`` (all of them). + + Raises: + ValueError: If ``epoch_seconds`` is not a positive whole number of + seconds that divides 30, if ``channels`` is empty, or if + ``normalization`` is not a mode + :func:`~pyhealth.tasks.eegbci.normalize_signal` knows. + + Attributes: + task_name (str): ``"SleepStagingSHHS"``. + input_schema (dict): ``{"signal": "tensor"}``. + output_schema (dict): ``{"label": "multiclass"}``. + + Examples: + >>> from pyhealth.datasets import SHHSDataset + >>> from pyhealth.tasks import SleepStagingSHHS + >>> dataset = SHHSDataset( # doctest: +SKIP + ... root="/path/to/shhs/polysomnography", + ... visits=("shhs1",), + ... ) + >>> sample_dataset = dataset.set_task(SleepStagingSHHS()) # doctest: +SKIP + >>> sample_dataset[0]["signal"].shape # doctest: +SKIP + torch.Size([2, 3750]) + """ + + task_name: str = "SleepStagingSHHS" + input_schema: ClassVar[dict[str, str]] = {"signal": "tensor"} + output_schema: ClassVar[dict[str, str]] = {"label": "multiclass"} + + def __init__( + self, + epoch_seconds: int = 30, + channels: list[str] | None = None, + normalization: str | None = None, + subjects: list[str] | None = None, + ) -> None: + super().__init__() + try: + seconds = float(epoch_seconds) + whole_seconds = int(seconds) + except (TypeError, ValueError, OverflowError) as exc: + raise ValueError( + "epoch_seconds must be a whole number of seconds that divides " + f"{_SCORED_EPOCH_SECONDS}, got {epoch_seconds!r}." + ) from exc + if ( + seconds <= 0 + or seconds != whole_seconds + or _SCORED_EPOCH_SECONDS % whole_seconds != 0 + ): + raise ValueError( + "epoch_seconds must be a whole number of seconds that divides " + f"{_SCORED_EPOCH_SECONDS}, got {epoch_seconds!r}." + ) + if channels is not None and not channels: + raise ValueError("channels must name at least one channel.") + normalize_signal(np.zeros((1, 2)), normalization) + self.epoch_seconds = whole_seconds + self.channels = None if channels is None else tuple(channels) + # Normalizing the requested names once keeps the per-recording loop to + # a single pass over the channels the file happens to carry. + self._channel_lookup = ( + None + if channels is None + else tuple((name, _normalize_channel_name(name)) for name in channels) + ) + if self._channel_lookup is not None: + requested = [key for _name, key in self._channel_lookup] + if len(set(requested)) != len(requested): + logger.warning( + "channels names a channel twice (%s); it is kept once, so " + "signal has fewer rows than channels.", + requested, + ) + self.normalization = normalization + # A set, because every participant is looked up once per pass. + self.subjects = ( + None if subjects is None else frozenset(str(s) for s in subjects) + ) + + def read_recording( + self, file_name: str + ) -> tuple[np.ndarray, float, list[str]] | None: + """Load one EDF recording and keep the requested EEG channels. + + The file is not preloaded: ``get_data`` reads only the requested + channels, so a fourteen channel night never has to sit in memory in + full. + + Args: + file_name: Path to a ``shhs1-.edf`` or ``shhs2-.edf``. + + Returns: + ``(data, sfreq, ch_names)`` with ``data`` in uV and shaped + ``(n_channels, n_samples)``, or ``None`` when the file cannot be + read or none of the requested channels are present. + """ + try: + raw = mne.io.read_raw_edf(file_name, preload=False, verbose="error") + except (OSError, RuntimeError, ValueError) as exc: + logger.warning("Failed to read %s: %s", file_name, exc) + return None + + ch_names = list(raw.ch_names) + picks = self._channel_indices(ch_names, file_name) + if picks is None: + raw.close() + return None + + sfreq = float(raw.info["sfreq"]) + try: + # Without preloading the data, a truncated or corrupt EDF surfaces + # here rather than inside read_raw_edf. + data = raw.get_data(picks=picks, units="uV") + except (OSError, RuntimeError, ValueError) as exc: + logger.warning("Failed to read %s: %s", file_name, exc) + return None + finally: + raw.close() + + if not math.isclose(sfreq, SHHS_SAMPLE_RATE, rel_tol=1e-6): + logger.warning( + "Expected %s Hz for %s, got %s Hz; cutting epochs at the " + "file's own sampling rate.", + SHHS_SAMPLE_RATE, + file_name, + sfreq, + ) + return data, sfreq, [ch_names[i] for i in picks] + + def _channel_indices(self, ch_names: list[str], source: str) -> list[int] | None: + """Resolve channel names to indices, falling back to 1.x positions. + + The result follows the order the channels were requested in, not the + order the file lists them, so ``signal`` rows line up with + ``channels``. Without that, a caller building a montage would silently + train on permuted rows. + """ + normalized = [_normalize_channel_name(name) for name in ch_names] + + if self._channel_lookup is None: + picks = [i for i, name in enumerate(normalized) if name.startswith("eeg")] + if not picks: + picks = [i for i in _LEGACY_CHANNEL_POSITIONS if i < len(ch_names)] + logger.warning( + "No EEG channels named in %s; falling back to positions %s.", + source, + picks, + ) + return picks or None + + picks = [] + for wanted, key in self._channel_lookup: + exact = [i for i, name in enumerate(normalized) if name == key] + match = exact or [i for i, n in enumerate(normalized) if n.startswith(key)] + if not match: + logger.warning("Channel %r not found in %s", wanted, source) + return None + if not exact and len(match) > 1: + logger.warning( + "Channel %r matches %s in %s; keeping the first.", + wanted, + [ch_names[i] for i in match], + source, + ) + picks.append(match[0]) + # dict.fromkeys dedupes while keeping the requested order; a sorted set + # would silently reorder the rows. + return list(dict.fromkeys(picks)) or None + + def _samples_from_event(self, patient_id: str, event: Any) -> list[dict[str, Any]]: + """Turn one scored night into epoch samples. + + Args: + patient_id: The participant id, for example ``"200001"``. + event: A ``shhs1`` or ``shhs2`` event carrying ``signal_file`` and + ``annotation_file``. + + Returns: + One sample dict per usable epoch, empty when the night is + unreadable or ``subjects`` excludes this participant. + """ + signal_file = str(getattr(event, "signal_file", "") or "").strip() + annotation_file = str(getattr(event, "annotation_file", "") or "").strip() + if not signal_file or not annotation_file: + return [] + + visit = ( + getattr(event, "visit", None) or getattr(event, "event_type", "") or "shhs" + ) + record_id = getattr(event, "record_id", "") or f"{visit}-{patient_id}" + + # Parse the annotation first: it is a small XML file, so a night that + # is going to be dropped never pays for reading its EDF. + try: + labels = _read_sleep_stages(annotation_file) + except (OSError, ValueError, ET.ParseError) as exc: + # ET.ParseError is a SyntaxError, so it is not covered by + # ValueError: a truncated download or an HTML error page would + # otherwise abort the whole run instead of dropping one night. + logger.warning("Failed to read %s: %s", annotation_file, exc) + return [] + if not labels: + logger.warning("No scored epochs in %s", annotation_file) + return [] + + loaded = self.read_recording(signal_file) + if loaded is None: + return [] + signal, sfreq, _ch_names = loaded + + valid = _valid_sleep_stages() + scored_len = round(_SCORED_EPOCH_SECONDS * sfreq) + epoch_len = round(self.epoch_seconds * sfreq) + if scored_len <= 0 or epoch_len <= 0: + return [] + # One score labels this many consecutive epochs of epoch_len samples. + per_score = _SCORED_EPOCH_SECONDS // self.epoch_seconds + + n_scored = min(len(labels), signal.shape[1] // scored_len) + if n_scored < len(labels): + logger.warning( + "%s has %d scored epochs but only %d complete %d s epochs of " + "signal, keeping the first %d.", + signal_file, + len(labels), + signal.shape[1] // scored_len, + _SCORED_EPOCH_SECONDS, + n_scored, + ) + + samples: list[dict[str, Any]] = [] + unscored = 0 + for scored_index in range(n_scored): + label = labels[scored_index] + if label not in valid: + unscored += 1 + continue + for sub_index in range(per_score): + epoch_index = scored_index * per_score + sub_index + start = scored_index * scored_len + sub_index * epoch_len + # Stop at the end of this score's window. Rounding a + # fractional sfreq can make the sub-epochs overshoot it, and an + # epoch reaching into the next window would carry that score's + # label. The length check below then drops the short remainder + # rather than returning a window with a borrowed label. + stop = min(start + epoch_len, (scored_index + 1) * scored_len) + epoch = signal[:, start:stop] + if epoch.shape[1] != epoch_len: + continue + if np.isnan(epoch).any(): + continue + epoch = normalize_signal(epoch, self.normalization) + samples.append( + { + "patient_id": patient_id, + "visit": visit, + "record_id": f"{record_id}-{epoch_index}", + "epoch_index": int(epoch_index), + "signal": torch.FloatTensor(np.ascontiguousarray(epoch)), + "label": int(label), + } + ) + + if unscored: + logger.debug( + "Dropped %d of %d scored epochs without a valid stage in %s", + unscored, + n_scored, + record_id, + ) + return samples + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Build epoch samples for one participant. + + Args: + patient: A PyHealth patient whose events are the rows of + ``shhs1-pyhealth.csv`` and ``shhs2-pyhealth.csv``. + + Returns: + Epoch samples for that participant. Empty when ``subjects`` was + set and this participant is not in it. + """ + patient_id = str(patient.patient_id) + if self.subjects is not None and patient_id not in self.subjects: + return [] + samples: list[dict[str, Any]] = [] + for event in patient.get_events(): + samples.extend(self._samples_from_event(patient_id, event)) + return samples diff --git a/tests/core/test_removed_1x_classes.py b/tests/core/test_removed_1x_classes.py index 0b2c6e79a6..1fd41c74f9 100644 --- a/tests/core/test_removed_1x_classes.py +++ b/tests/core/test_removed_1x_classes.py @@ -41,18 +41,8 @@ def test_subclass_raises_too(self): subclass() def test_in_tree_legacy_datasets_name_themselves(self): - from pyhealth.datasets import ( - MIMICExtractDataset, - SHHSDataset, - ) + from pyhealth.datasets import MIMICExtractDataset - for cls in (SHHSDataset,): - with self.subTest(cls=cls.__name__): - with self.assertRaises(NotImplementedError) as ctx: - cls(root="data") - message = str(ctx.exception) - self.assertIn(f"{cls.__name__} is built on", message) - self.assertIn("does not work yet", message) with self.assertRaises(NotImplementedError) as ctx: MIMICExtractDataset(root="data", tables=["C"]) self.assertIn( diff --git a/tests/core/test_shhs.py b/tests/core/test_shhs.py new file mode 100644 index 0000000000..9804a16d15 --- /dev/null +++ b/tests/core/test_shhs.py @@ -0,0 +1,185 @@ +"""SHHSDataset metadata, using a synthetic NSRR ``polysomnography`` tree.""" + +import tempfile +import unittest +from pathlib import Path + +import pandas as pd + +from pyhealth.datasets import SHHSDataset +from pyhealth.tasks import SleepStagingSHHS + + +def _write_recording(root: Path, visit: str, patient_id: str, *, annotation_dir=None): + """Create an empty EDF and its Profusion XML under the NSRR layout.""" + edf_dir = root / "edfs" / visit + edf_dir.mkdir(parents=True, exist_ok=True) + record = f"{visit}-{patient_id}" + (edf_dir / f"{record}.edf").write_bytes(b"") + + subdir = annotation_dir or visit + ann_dir = root / "annotations-events-profusion" / subdir + ann_dir.mkdir(parents=True, exist_ok=True) + (ann_dir / f"{record}-profusion.xml").write_text("") + + +class TestSHHSDatasetMetadata(unittest.TestCase): + def _prepare(self, root: Path, visits=None) -> Path: + """Run prepare_metadata without building the 2.0 event cache.""" + dataset = SHHSDataset.__new__(SHHSDataset) + dataset.root = str(root) + dataset.visits = list(visits or ("shhs1", "shhs2")) + dataset.prepare_metadata() + return root + + def test_pairs_edfs_with_profusion_annotations(self): + with tempfile.TemporaryDirectory() as tmp: + root = self._prepare(Path(tmp)) + csv_path = root / "shhs1-pyhealth.csv" + self.assertFalse(csv_path.exists()) + + _write_recording(root, "shhs1", "200001") + self._prepare(root) + + df = pd.read_csv(csv_path, dtype=str, keep_default_na=False) + self.assertEqual(len(df), 1) + row = df.iloc[0] + self.assertEqual(row["patient_id"], "200001") + self.assertEqual(row["visit"], "shhs1") + self.assertEqual(row["record_id"], "shhs1-200001") + self.assertTrue(row["signal_file"].endswith("shhs1-200001.edf")) + self.assertTrue( + row["annotation_file"].endswith("shhs1-200001-profusion.xml") + ) + + def test_shared_participant_id_across_visits(self): + """Both nights of one person share patient_id so they stay one Patient.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs1", "200001") + _write_recording(root, "shhs2", "200001") + self._prepare(root) + + df = pd.read_csv(root / "shhs1-pyhealth.csv", dtype=str) + df2 = pd.read_csv(root / "shhs2-pyhealth.csv", dtype=str) + self.assertEqual(set(df["patient_id"]), {"200001"}) + self.assertEqual(set(df2["patient_id"]), {"200001"}) + self.assertEqual(set(df["record_id"]), {"shhs1-200001"}) + self.assertEqual(set(df2["record_id"]), {"shhs2-200001"}) + + def test_shhs2_annotations_resolve_under_legacy_label_dir(self): + """The 1.x loader looked for shhs2 under ``label/``; both are accepted.""" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs2", "200002", annotation_dir="label") + with self.assertLogs("pyhealth.datasets.shhs", level="WARNING") as logs: + self._prepare(root, visits=("shhs2",)) + self.assertTrue(any("label/" in message for message in logs.output)) + + df = pd.read_csv(root / "shhs2-pyhealth.csv", dtype=str) + self.assertEqual(len(df), 1) + + def test_recordings_without_annotation_are_skipped(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs1", "200001") + (root / "edfs" / "shhs1" / "shhs1-200003.edf").write_bytes(b"") + self._prepare(root, visits=("shhs1",)) + + df = pd.read_csv(root / "shhs1-pyhealth.csv", dtype=str) + self.assertEqual(set(df["patient_id"]), {"200001"}) + + def test_unparsable_file_names_are_skipped(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs1", "200001") + (root / "edfs" / "shhs1" / "notes.edf").write_bytes(b"") + self._prepare(root, visits=("shhs1",)) + + df = pd.read_csv(root / "shhs1-pyhealth.csv", dtype=str) + self.assertEqual(len(df), 1) + + def test_prepare_metadata_is_idempotent(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs1", "200001") + self._prepare(root) + csv_path = root / "shhs1-pyhealth.csv" + first = csv_path.read_bytes() + + _write_recording(root, "shhs1", "200002") + self._prepare(root) + self.assertEqual(csv_path.read_bytes(), first) + + def test_only_requested_visits_are_written(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + _write_recording(root, "shhs1", "200001") + _write_recording(root, "shhs2", "200001") + self._prepare(root, visits=("shhs2",)) + + self.assertFalse((root / "shhs1-pyhealth.csv").exists()) + self.assertTrue((root / "shhs2-pyhealth.csv").exists()) + + def test_empty_root_writes_nothing(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + self._prepare(root) + self.assertEqual(list(root.glob("*.csv")), []) + + def test_unknown_visit_raises(self): + with tempfile.TemporaryDirectory() as tmp, self.assertRaises(ValueError): + SHHSDataset(root=tmp, visits=("shhs3",)) + + def test_empty_root_raises_file_not_found(self): + with tempfile.TemporaryDirectory() as tmp, self.assertRaises(FileNotFoundError): + SHHSDataset(root=tmp) + + def test_default_task_is_sleep_staging(self): + dataset = SHHSDataset.__new__(SHHSDataset) + self.assertIsInstance(dataset.default_task, SleepStagingSHHS) + self.assertEqual(dataset.default_task.epoch_seconds, 30) + + +class TestSHHSModuleHelpers(unittest.TestCase): + def test_parse_patient_id_reads_the_numeric_part(self): + from pyhealth.datasets.shhs import parse_patient_id + + self.assertEqual(parse_patient_id("shhs1-200001.edf"), "200001") + self.assertEqual( + parse_patient_id(Path("/data/edfs/shhs2/shhs2-200001.edf")), "200001" + ) + with self.assertRaises(ValueError): + parse_patient_id("notes.edf") + + def test_read_sleep_stages_returns_integer_codes(self): + from pyhealth.datasets.shhs import read_sleep_stages + + with tempfile.TemporaryDirectory() as tmp: + xml = Path(tmp) / "shhs1-200001-profusion.xml" + xml.write_text( + "" + "02" + "59" + "" + ) + self.assertEqual(read_sleep_stages(xml), [0, 2, 5, 9]) + + def test_read_sleep_stages_rejects_missing_stages(self): + from pyhealth.datasets.shhs import read_sleep_stages + + with tempfile.TemporaryDirectory() as tmp: + xml = Path(tmp) / "bad.xml" + xml.write_text("") + with self.assertRaises(ValueError): + read_sleep_stages(xml) + + def test_rem_is_a_valid_stage_and_movement_is_not(self): + from pyhealth.datasets.shhs import VALID_SLEEP_STAGES + + self.assertIn(5, VALID_SLEEP_STAGES) + self.assertNotIn(9, VALID_SLEEP_STAGES) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_sleep_staging_shhs.py b/tests/core/test_sleep_staging_shhs.py index 71dc0361ce..aae409ef92 100644 --- a/tests/core/test_sleep_staging_shhs.py +++ b/tests/core/test_sleep_staging_shhs.py @@ -1,14 +1,15 @@ -import os -import pickle +"""SleepStagingSHHS: epoch slicing, channel selection and label filtering.""" + import tempfile import unittest -import xml.etree.ElementTree as ET +from pathlib import Path +from types import SimpleNamespace from unittest import mock import numpy as np -from pyhealth.tasks import sleep_staging -from pyhealth.tasks.sleep_staging import sleep_staging_shhs_fn +from pyhealth.tasks import sleep_staging_shhs as task_module +from pyhealth.tasks.sleep_staging_shhs import SleepStagingSHHS SHHS_XML = """ @@ -22,111 +23,350 @@ """ +SHHS_CHANNELS = [ + "EEG", + "EEG(sec)", + "EMG", + "EOG(L)", + "EOG(R)", + "ECG", + "HR", + "RESP", + "THOR RES", + "ABDO RES", + "POSITION", + "LIGHT", + "SaO2", + "OX STAT", +] + +# Samples in one scored 30 s epoch at the released 125 Hz. +_SAMPLES_PER_SCORE = 30 * 125 + class _FakeRawEDF: - """Minimal stand-in for the object returned by mne.io.read_raw_edf.""" + """Minimal stand-in for the ``mne.io.Raw`` returned by read_raw_edf.""" - def __init__(self, data): + def __init__(self, data, ch_names, sfreq=125.0): self._data = data + self.ch_names = list(ch_names) + self.info = {"sfreq": sfreq} + self.closed = False - def get_data(self): - return self._data + def get_data(self, picks=None, units=None): + data = self._data + if picks is not None: + data = data[list(picks), :] + return data + def close(self): + self.closed = True -class TestSleepStagingSHHS(unittest.TestCase): - """Test cases for sleep_staging_shhs_fn.""" +class TestSleepStagingSHHS(unittest.TestCase): def setUp(self): - """Set up a fake SHHS recording (signal path + XML label file).""" self._tmp = tempfile.TemporaryDirectory() self.addCleanup(self._tmp.cleanup) - self.root = os.path.join(self._tmp.name, "shhs") - self.save_path = os.path.join(self._tmp.name, "epochs") - os.makedirs(self.root) - os.makedirs(self.save_path) - - self.signal_file = "shhs1-200001.edf" - self.label_file = "shhs1-200001.xml" - with open(os.path.join(self.root, self.label_file), "w") as f: - f.write(SHHS_XML) - - self.record = [ - { - "load_from_path": self.root, - "signal_file": self.signal_file, - "label_file": self.label_file, - "save_to_path": self.save_path, - } - ] - - def test_xml_parser_available_at_module_level(self): - """ET must be bound unconditionally so label parsing cannot NameError.""" - self.assertIs(sleep_staging.ET, ET) - - def test_parses_sleep_stage_labels_from_xml(self): - """The task reads SleepStage labels via ElementTree, with no extra deps.""" - num_epochs = 4 - # 14 channels: skips both missing-channel branches in the task fn. - signal = np.zeros((14, num_epochs * 125)) - with mock.patch.object( - sleep_staging.mne.io, - "read_raw_edf", - return_value=_FakeRawEDF(signal), - ): - samples = sleep_staging_shhs_fn(self.record, epoch_seconds=1) - - self.assertEqual(len(samples), num_epochs) - for i, sample in enumerate(samples): - self.assertEqual(sample["record_id"], f"shhs1-200001-{i}") - self.assertEqual(sample["patient_id"], "shhs1-200001") - self.assertEqual(sample["label"], ["0", "4", "2", "1"][i]) - self.assertTrue(os.path.exists(sample["epoch_path"])) - with open(sample["epoch_path"], "rb") as f: - epoch = pickle.load(f) - self.assertEqual(epoch["signal"].shape, (2, 125)) - self.assertEqual(epoch["label"], sample["label"]) - - def _run_epochs(self, num_epochs): - signal = np.zeros((14, num_epochs * 125)) - with mock.patch.object( - sleep_staging.mne.io, - "read_raw_edf", - return_value=_FakeRawEDF(signal), - ): - return sleep_staging_shhs_fn(self.record, epoch_seconds=1) + self.root = Path(self._tmp.name) + self.annotation_file = self.root / "shhs1-200001-profusion.xml" + self.annotation_file.write_text(SHHS_XML) - def test_skips_signal_epochs_beyond_available_labels(self): - """Six signal epochs and four labels yield the four labeled epochs.""" - samples = self._run_epochs(6) - self.assertEqual([s["label"] for s in samples], ["0", "4", "2", "1"]) + def _run(self, data, ch_names=None, label_file=None, sfreq=125.0, **options): + """Run the task on fake EDF data without touching the filesystem.""" + task = SleepStagingSHHS(**options) + channels = SHHS_CHANNELS[: data.shape[0]] if ch_names is None else ch_names + raw = _FakeRawEDF(data, channels, sfreq=sfreq) + event = SimpleNamespace( + visit="shhs1", + record_id="shhs1-200001", + signal_file="shhs1-200001.edf", + annotation_file=str(label_file or self.annotation_file), + ) + patient = SimpleNamespace(patient_id="200001", get_events=lambda: [event]) + with mock.patch.object(task_module.mne.io, "read_raw_edf", return_value=raw): + return task(patient) + + def _data(self, num_epochs, num_channels=14): + """Samples where the value encodes the channel index. + + ``num_epochs`` counts scored 30 s epochs, so the signal is exactly as + long as the annotations it gets paired with. + """ + return np.repeat( + np.arange(num_channels, dtype=float)[:, None], + num_epochs * _SAMPLES_PER_SCORE, + axis=1, + ) + + def _ramp(self, num_epochs, num_channels=14): + """Samples whose value encodes the absolute sample index.""" + return np.tile( + np.arange(num_epochs * _SAMPLES_PER_SCORE, dtype=float), + (num_channels, 1), + ) + + def test_epochs_are_labelled_from_the_xml(self): + samples = self._run(self._data(4)) + + self.assertEqual(len(samples), 4) + self.assertEqual([s["label"] for s in samples], [0, 4, 2, 1]) + self.assertEqual([s["epoch_index"] for s in samples], [0, 1, 2, 3]) self.assertEqual( [s["record_id"] for s in samples], [f"shhs1-200001-{i}" for i in range(4)], ) + self.assertTrue(all(s["patient_id"] == "200001" for s in samples)) + self.assertTrue(all(s["visit"] == "shhs1" for s in samples)) + + def test_default_channels_are_the_two_eeg_channels(self): + samples = self._run(self._data(4)) + signal = samples[0]["signal"] + self.assertEqual(tuple(signal.shape), (2, _SAMPLES_PER_SCORE)) + np.testing.assert_array_equal(signal[:, 0], [0, 1]) + + def test_epochs_cover_consecutive_thirty_second_windows(self): + samples = self._run(self._ramp(3)) + + starts = [int(s["signal"][0, 0]) for s in samples] + self.assertEqual(starts, [0, _SAMPLES_PER_SCORE, 2 * _SAMPLES_PER_SCORE]) + for sample in samples: + self.assertEqual(tuple(sample["signal"].shape), (2, _SAMPLES_PER_SCORE)) + + def test_named_channels_are_selected_by_name(self): + samples = self._run(self._data(4), channels=["EEG(sec)"]) + signal = samples[0]["signal"] + self.assertEqual(tuple(signal.shape), (1, _SAMPLES_PER_SCORE)) + np.testing.assert_array_equal(signal[:, 0], [1]) + + def test_signal_rows_follow_the_requested_channel_order(self): + # "EEG" is channel 0 and "EEG(sec)" is channel 1 in the file, so asking + # for them the other way round has to swap the rows. + samples = self._run(self._data(4), channels=["EEG(sec)", "EEG"]) + signal = samples[0]["signal"] + self.assertEqual(tuple(signal.shape), (2, _SAMPLES_PER_SCORE)) + np.testing.assert_array_equal(signal[:, 0], [1, 0]) + + def test_duplicate_channels_are_kept_once_and_warn(self): + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), channels=["EEG", "EEG"]) + self.assertTrue(any("twice" in message for message in logs.output)) + self.assertEqual(tuple(samples[0]["signal"].shape), (1, _SAMPLES_PER_SCORE)) + + def test_channel_lookup_ignores_case_and_spacing(self): + samples = self._run(self._data(4), channels=["eeg (sec)"]) + np.testing.assert_array_equal(samples[0]["signal"][:, 0], [1]) + + def test_ambiguous_prefix_warns_and_keeps_the_first_match(self): + channels = ["EOG(L)", "EOG(R)"] + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), ch_names=channels, channels=["EOG"]) + self.assertTrue(any("matches" in message for message in logs.output)) + np.testing.assert_array_equal(samples[0]["signal"][:, 0], [0]) + + def test_missing_channel_drops_the_recording(self): + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), channels=["iEEG"]) + self.assertEqual(samples, []) + self.assertTrue(any("iEEG" in message for message in logs.output)) + + def test_unnamed_channels_fall_back_to_legacy_positions(self): + channels = ["ch0", "ch1", "ch2", "ch3", "ch4", "ch5", "ch6", "ch7"] + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), ch_names=channels) + self.assertTrue(any("falling back" in message for message in logs.output)) + np.testing.assert_array_equal(samples[0]["signal"][:, 0], [2, 7]) + + def test_skips_signal_epochs_beyond_available_labels(self): + samples = self._run(self._data(6)) + self.assertEqual([s["label"] for s in samples], [0, 4, 2, 1]) def test_ignores_labels_without_a_complete_signal_epoch(self): - """Two signal epochs and four labels yield the first two labels.""" - samples = self._run_epochs(2) - self.assertEqual([s["label"] for s in samples], ["0", "4"]) - - def test_drops_missing_channel_rows_before_selecting_eeg(self): - """15- and 16-channel recordings still yield the two EEG channels.""" - for num_channels in (15, 16): - with self.subTest(num_channels=num_channels): - # each row holds its own channel index - signal = np.repeat( - np.arange(num_channels, dtype=float)[:, None], 4 * 125, axis=1 + samples = self._run(self._data(2)) + self.assertEqual([s["label"] for s in samples], [0, 4]) + + def test_ignores_labels_without_a_complete_signal_epoch_warns(self): + with self.assertLogs(task_module.logger, level="WARNING") as logs: + self._run(self._data(2)) + self.assertTrue(any("scored epochs" in m for m in logs.output)) + + def test_movement_epochs_are_dropped(self): + label_file = self.root / "with-movement.xml" + label_file.write_text( + "" + "09" + "5" + "" + ) + samples = self._run(self._data(3), label_file=label_file) + self.assertEqual([s["label"] for s in samples], [0, 5]) + self.assertEqual([s["epoch_index"] for s in samples], [0, 2]) + + def test_unreadable_annotation_drops_the_recording(self): + missing = self.root / "absent.xml" + with self.assertLogs(task_module.logger, level="WARNING"): + samples = self._run(self._data(4), label_file=missing) + self.assertEqual(samples, []) + + def test_corrupt_annotation_drops_the_recording(self): + # A truncated download is not well-formed XML, and ET.ParseError is a + # SyntaxError, so it has to be caught explicitly or one bad night + # aborts the whole run. + truncated = self.root / "truncated.xml" + truncated.write_text("0") + empty = self.root / "empty.xml" + empty.write_text("") + for label_file in (truncated, empty): + with self.subTest(label_file=label_file.name): + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), label_file=label_file) + self.assertEqual(samples, []) + self.assertTrue(any("Failed to read" in m for m in logs.output)) + + def test_empty_annotation_drops_the_recording(self): + label_file = self.root / "no-stages.xml" + label_file.write_text( + "" + ) + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), label_file=label_file) + self.assertEqual(samples, []) + self.assertTrue(any("No scored epochs" in m for m in logs.output)) + + def test_annotation_is_read_before_the_recording(self): + # A night that is going to be dropped should not pay for its EDF. + task = SleepStagingSHHS() + event = SimpleNamespace( + visit="shhs1", + record_id="shhs1-200001", + signal_file="shhs1-200001.edf", + annotation_file=str(self.root / "absent.xml"), + ) + with ( + mock.patch.object(task_module.mne.io, "read_raw_edf") as reader, + self.assertLogs(task_module.logger, level="WARNING"), + ): + samples = task._samples_from_event("200001", event) + self.assertEqual(samples, []) + reader.assert_not_called() + + def test_subjects_filter_excludes_other_participants(self): + samples = self._run(self._data(4), subjects=["200999"]) + self.assertEqual(samples, []) + + def test_subjects_filter_keeps_listed_participants(self): + samples = self._run(self._data(4), subjects=["200001"]) + self.assertEqual(len(samples), 4) + + def test_normalization_is_applied(self): + # Non-constant data: constant rows survive 95th-percentile scaling. + rng = np.random.default_rng(0) + data = rng.normal(50.0, 10.0, size=(14, 4 * _SAMPLES_PER_SCORE)) + plain = self._run(data)[0]["signal"] + scaled = self._run(data, normalization="95th_percentile")[0]["signal"] + self.assertFalse(np.allclose(plain.numpy(), scaled.numpy())) + + def test_short_epochs_share_the_score_of_their_window(self): + # 10 s windows: each 30 s score labels three consecutive samples. + samples = self._run(self._ramp(4), epoch_seconds=10) + + self.assertEqual(len(samples), 12) + self.assertEqual( + [s["label"] for s in samples], + [0, 0, 0, 4, 4, 4, 2, 2, 2, 1, 1, 1], + ) + self.assertEqual([s["epoch_index"] for s in samples], list(range(12))) + self.assertEqual( + [int(s["signal"][0, 0]) for s in samples], + [i * 1250 for i in range(12)], + ) + for sample in samples: + self.assertEqual(tuple(sample["signal"].shape), (2, 1250)) + + def test_movement_epochs_are_dropped_across_all_their_sub_epochs(self): + label_file = self.root / "movement.xml" + label_file.write_text( + "" + "09" + "5" + "" + ) + samples = self._run(self._ramp(3), label_file=label_file, epoch_seconds=10) + self.assertEqual([s["label"] for s in samples], [0, 0, 0, 5, 5, 5]) + self.assertEqual([s["epoch_index"] for s in samples], [0, 1, 2, 6, 7, 8]) + + def test_epoch_seconds_must_divide_thirty(self): + for epoch_seconds in (7, 20, 45, 60, 90, 120, 300, 0, -10, 12.5, "abc"): + with ( + self.subTest(epoch_seconds=epoch_seconds), + self.assertRaises(ValueError), + ): + SleepStagingSHHS(epoch_seconds=epoch_seconds) + + def test_epoch_seconds_accepts_divisors_of_thirty(self): + for epoch_seconds in (1, 2, 3, 5, 6, 10, 15, 30): + with self.subTest(epoch_seconds=epoch_seconds): + self.assertEqual( + SleepStagingSHHS(epoch_seconds=epoch_seconds).epoch_seconds, + epoch_seconds, ) - with mock.patch.object( - sleep_staging.mne.io, - "read_raw_edf", - return_value=_FakeRawEDF(signal), - ): - samples = sleep_staging_shhs_fn(self.record, epoch_seconds=1) - - with open(samples[0]["epoch_path"], "rb") as f: - epoch = pickle.load(f) - np.testing.assert_array_equal(epoch["signal"][:, 0], [2, 7]) + + def test_empty_channel_selection_is_rejected(self): + with self.assertRaises(ValueError): + SleepStagingSHHS(channels=[]) + + def test_recording_is_not_preloaded(self): + task = SleepStagingSHHS() + raw = _FakeRawEDF(self._data(4), SHHS_CHANNELS) + event = SimpleNamespace( + visit="shhs1", + record_id="shhs1-200001", + signal_file="shhs1-200001.edf", + annotation_file=str(self.annotation_file), + ) + patient = SimpleNamespace(patient_id="200001", get_events=lambda: [event]) + with mock.patch.object( + task_module.mne.io, "read_raw_edf", return_value=raw + ) as reader: + task(patient) + self.assertFalse(reader.call_args.kwargs["preload"]) + + def test_unexpected_sampling_rate_warns_and_still_slices(self): + with self.assertLogs(task_module.logger, level="WARNING") as logs: + samples = self._run(self._data(4), sfreq=100.0) + self.assertTrue(any("100.0 Hz" in m for m in logs.output)) + # Boundaries follow the file, so a 30 s epoch is 3000 samples here. + self.assertEqual(len(samples), 4) + self.assertEqual(tuple(samples[0]["signal"].shape), (2, 3000)) + + def test_short_epochs_never_read_into_the_next_scored_window(self): + # 133.33 Hz makes 30 s round to 4000 samples but 5 s to 667, so six + # sub-epochs no longer fit. The overflowing window has to be dropped + # rather than labelled with the following score. + scored_len = round(30 * 133.33) + signal = np.tile( + np.arange(scored_len * 2, dtype=float), + (2, 1), + ) + with self.assertLogs(task_module.logger, level="WARNING"): + samples = self._run( + signal, sfreq=133.33, epoch_seconds=5, ch_names=SHHS_CHANNELS[:2] + ) + + self.assertTrue(samples) + for sample in samples: + first = int(sample["signal"][0, 0]) + last = int(sample["signal"][0, -1]) + window = first // scored_len + self.assertEqual(last // scored_len, window) + self.assertLessEqual(last, (window + 1) * scored_len - 1) + # The score that ran out of room contributed fewer sub-epochs. + self.assertEqual(len(samples), 10) + + def test_task_schemas(self): + task = SleepStagingSHHS() + self.assertEqual(task.task_name, "SleepStagingSHHS") + self.assertEqual(task.input_schema, {"signal": "tensor"}) + self.assertEqual(task.output_schema, {"label": "multiclass"}) if __name__ == "__main__": diff --git a/tests/core/test_sleep_staging_shhs_legacy.py b/tests/core/test_sleep_staging_shhs_legacy.py new file mode 100644 index 0000000000..71dc0361ce --- /dev/null +++ b/tests/core/test_sleep_staging_shhs_legacy.py @@ -0,0 +1,133 @@ +import os +import pickle +import tempfile +import unittest +import xml.etree.ElementTree as ET +from unittest import mock + +import numpy as np + +from pyhealth.tasks import sleep_staging +from pyhealth.tasks.sleep_staging import sleep_staging_shhs_fn + +SHHS_XML = """ + + 30 + + 0 + 4 + 2 + 1 + + +""" + + +class _FakeRawEDF: + """Minimal stand-in for the object returned by mne.io.read_raw_edf.""" + + def __init__(self, data): + self._data = data + + def get_data(self): + return self._data + + +class TestSleepStagingSHHS(unittest.TestCase): + """Test cases for sleep_staging_shhs_fn.""" + + def setUp(self): + """Set up a fake SHHS recording (signal path + XML label file).""" + self._tmp = tempfile.TemporaryDirectory() + self.addCleanup(self._tmp.cleanup) + self.root = os.path.join(self._tmp.name, "shhs") + self.save_path = os.path.join(self._tmp.name, "epochs") + os.makedirs(self.root) + os.makedirs(self.save_path) + + self.signal_file = "shhs1-200001.edf" + self.label_file = "shhs1-200001.xml" + with open(os.path.join(self.root, self.label_file), "w") as f: + f.write(SHHS_XML) + + self.record = [ + { + "load_from_path": self.root, + "signal_file": self.signal_file, + "label_file": self.label_file, + "save_to_path": self.save_path, + } + ] + + def test_xml_parser_available_at_module_level(self): + """ET must be bound unconditionally so label parsing cannot NameError.""" + self.assertIs(sleep_staging.ET, ET) + + def test_parses_sleep_stage_labels_from_xml(self): + """The task reads SleepStage labels via ElementTree, with no extra deps.""" + num_epochs = 4 + # 14 channels: skips both missing-channel branches in the task fn. + signal = np.zeros((14, num_epochs * 125)) + with mock.patch.object( + sleep_staging.mne.io, + "read_raw_edf", + return_value=_FakeRawEDF(signal), + ): + samples = sleep_staging_shhs_fn(self.record, epoch_seconds=1) + + self.assertEqual(len(samples), num_epochs) + for i, sample in enumerate(samples): + self.assertEqual(sample["record_id"], f"shhs1-200001-{i}") + self.assertEqual(sample["patient_id"], "shhs1-200001") + self.assertEqual(sample["label"], ["0", "4", "2", "1"][i]) + self.assertTrue(os.path.exists(sample["epoch_path"])) + with open(sample["epoch_path"], "rb") as f: + epoch = pickle.load(f) + self.assertEqual(epoch["signal"].shape, (2, 125)) + self.assertEqual(epoch["label"], sample["label"]) + + def _run_epochs(self, num_epochs): + signal = np.zeros((14, num_epochs * 125)) + with mock.patch.object( + sleep_staging.mne.io, + "read_raw_edf", + return_value=_FakeRawEDF(signal), + ): + return sleep_staging_shhs_fn(self.record, epoch_seconds=1) + + def test_skips_signal_epochs_beyond_available_labels(self): + """Six signal epochs and four labels yield the four labeled epochs.""" + samples = self._run_epochs(6) + self.assertEqual([s["label"] for s in samples], ["0", "4", "2", "1"]) + self.assertEqual( + [s["record_id"] for s in samples], + [f"shhs1-200001-{i}" for i in range(4)], + ) + + def test_ignores_labels_without_a_complete_signal_epoch(self): + """Two signal epochs and four labels yield the first two labels.""" + samples = self._run_epochs(2) + self.assertEqual([s["label"] for s in samples], ["0", "4"]) + + def test_drops_missing_channel_rows_before_selecting_eeg(self): + """15- and 16-channel recordings still yield the two EEG channels.""" + for num_channels in (15, 16): + with self.subTest(num_channels=num_channels): + # each row holds its own channel index + signal = np.repeat( + np.arange(num_channels, dtype=float)[:, None], 4 * 125, axis=1 + ) + with mock.patch.object( + sleep_staging.mne.io, + "read_raw_edf", + return_value=_FakeRawEDF(signal), + ): + samples = sleep_staging_shhs_fn(self.record, epoch_seconds=1) + + with open(samples[0]["epoch_path"], "rb") as f: + epoch = pickle.load(f) + np.testing.assert_array_equal(epoch["signal"][:, 0], [2, 7]) + + +if __name__ == "__main__": + unittest.main()