Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -268,6 +268,7 @@ Available Tasks
BCI Competition IV 2a Left vs Right Hand <tasks/pyhealth.tasks.BCIIV2aLeftRightImagery>
PTB-XL Tasks <tasks/pyhealth.tasks.ptbxl>
Sleep Staging v2 <tasks/pyhealth.tasks.sleep_staging_v2>
Sleep Staging (SHHS) <tasks/pyhealth.tasks.sleep_staging_shhs>
Benchmark EHRShot <tasks/pyhealth.tasks.benchmark_ehrshot>
EHR Text Serialization (LLM encoders) <tasks/pyhealth.tasks.ehr_text_serialization>
EHR Foundation Model Timelines <tasks/pyhealth.tasks.ehr_foundation_model>
Expand Down
7 changes: 7 additions & 0 deletions docs/api/tasks/pyhealth.tasks.sleep_staging_shhs.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
pyhealth.tasks.sleep_staging_shhs
================================

.. autoclass:: pyhealth.tasks.sleep_staging_shhs.SleepStagingSHHS
:members:
:undoc-members:
:show-inheritance:
94 changes: 94 additions & 0 deletions examples/eeg/sleep_staging/sleep_staging_shhs_contrawr.py
Original file line number Diff line number Diff line change
@@ -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()
1 change: 0 additions & 1 deletion examples/old/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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` |
Expand Down
50 changes: 0 additions & 50 deletions examples/old/eeg/sleep_staging/sleep_staging_shhs_contrawr.py

This file was deleted.

4 changes: 2 additions & 2 deletions pyhealth/datasets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 "
Expand Down
20 changes: 20 additions & 0 deletions pyhealth/datasets/configs/shhs.yaml
Original file line number Diff line number Diff line change
@@ -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"
Loading
Loading