diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst index 2a1db44afe..d996ba52c7 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -435,6 +435,11 @@ PyHealth does not ship any data: you download each dataset from its source and p - `PhysioNet `__ - Yes - — + * - :doc:`MIT-BIH Arrhythmia ` + - Open + - `PhysioNet `__ + - No + - — * - :doc:`PTB-XL ` - Open - `PhysioNet `__ @@ -689,6 +694,7 @@ Available Datasets datasets/pyhealth.datasets.EEGBCIDataset datasets/pyhealth.datasets.AHEPADementiaDataset datasets/pyhealth.datasets.BCICompetitionIV2aDataset + MIT-BIH Arrhythmia Dataset PTB-XL Dataset PhysioNet 2012 Dataset datasets/pyhealth.datasets.TUABDataset diff --git a/docs/api/datasets/pyhealth.datasets.MITBIHDataset.rst b/docs/api/datasets/pyhealth.datasets.MITBIHDataset.rst new file mode 100644 index 0000000000..169463b126 --- /dev/null +++ b/docs/api/datasets/pyhealth.datasets.MITBIHDataset.rst @@ -0,0 +1,32 @@ +pyhealth.datasets.MITBIHDataset +=============================== + +Overview +-------- + +The `MIT-BIH Arrhythmia Database `_ +contains 48 half-hour, two-lead ambulatory ECG recordings from 47 patients, +sampled at 360 Hz, with every heartbeat annotated by cardiologists. Each +recording is loaded as one patient; waveforms are read lazily with ``wfdb`` +(``pip install wfdb``). + +:class:`~pyhealth.datasets.MITBIHAnomalyRatioSplit` provides a deterministic +record-level split by abnormal-beat ratio. Its default ``"paper"`` mode +reproduces the anomaly-detection split of MedTsLLM +(`Chan et al., MLHC 2024 `_): the 6 least +and 4 most abnormal of the 33 MLII+V1 recordings that are not entirely +abnormal, which matches the paper's reported 1,354,170 training and 902,780 +test samples at 125 Hz. + +API Reference +------------- + +.. autoclass:: pyhealth.datasets.MITBIHDataset + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.datasets.MITBIHAnomalyRatioSplit + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 67464516bf..8df6747cf1 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -284,6 +284,7 @@ Available Tasks AHEPA Dementia Classification BCI Competition IV 2a Motor Imagery BCI Competition IV 2a Left vs Right Hand + MIT-BIH ECG Anomaly Detection PTB-XL Tasks Sleep Staging v2 Benchmark EHRShot diff --git a/docs/api/tasks/pyhealth.tasks.mitbih.rst b/docs/api/tasks/pyhealth.tasks.mitbih.rst new file mode 100644 index 0000000000..749e3084b6 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.mitbih.rst @@ -0,0 +1,23 @@ +pyhealth.tasks.mitbih +===================== + +Overview +-------- + +ECG anomaly detection on the MIT-BIH Arrhythmia Database, following MedTsLLM +(`Chan et al., MLHC 2024 `_). Each recording +is resampled from 360 Hz to 125 Hz and cut into 128-sample windows of the +two-lead signal. The label is a per-time-step binary mask in which every +abnormal beat annotation (any beat other than ``N``) is expanded to 150 ms +before and after the beat. + +Use with :meth:`pyhealth.datasets.MITBIHDataset.anomaly_ratio_split` to obtain +the paper's train/test split. + +API Reference +------------- + +.. automodule:: pyhealth.tasks.mitbih + :members: + :undoc-members: + :show-inheritance: diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 576e024737..35ae3e2f97 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -143,6 +143,8 @@ def __init__(self, *args, **kwargs): from .bciiv2a import BCICompetitionIV2aDataset as BCICompetitionIV2aDataset from .hup_ieeg import HUPiEEGDataset as HUPiEEGDataset from .iiic import IIICDataset as IIICDataset +from .mitbih import MITBIHAnomalyRatioSplit as MITBIHAnomalyRatioSplit +from .mitbih import MITBIHDataset as MITBIHDataset from .tuab import TUABDataset from .tuev import TUEVDataset from .chbmit import CHBMITDataset as CHBMITDataset diff --git a/pyhealth/datasets/configs/mitbih.yaml b/pyhealth/datasets/configs/mitbih.yaml new file mode 100644 index 0000000000..d9d87b6310 --- /dev/null +++ b/pyhealth/datasets/configs/mitbih.yaml @@ -0,0 +1,17 @@ +version: "1.0.0" # PhysioNet MIT-BIH Arrhythmia Database (mitdb) v1.0.0 +tables: + records: + # Written by MITBIHDataset.prepare_metadata from the WFDB headers and + # beat annotations, into metadata_cache_dir (not the data root). + file_path: "mitbih-pyhealth.csv" + patient_id: "patient_id" + # Recordings are de-identified and carry no acquisition dates. + timestamp: null + attributes: + - "record_id" + - "signal_file" + - "fs" + - "n_samples" + - "leads" # comma-separated, e.g. "MLII,V1" + - "anomaly_ratio" # fraction of beat annotations other than "N" + - "comments" # header comments: age, sex, medications, notes diff --git a/pyhealth/datasets/mitbih.py b/pyhealth/datasets/mitbih.py new file mode 100644 index 0000000000..a35a110f99 --- /dev/null +++ b/pyhealth/datasets/mitbih.py @@ -0,0 +1,445 @@ +"""MIT-BIH Arrhythmia dataset and MedTsLLM's record-level anomaly split. + +Contributors: Thi Van Trinh Tran and Zexi Li. +Task: reconstruction-based ECG anomaly detection on abnormal beats. +Reference: MedTsLLM, https://arxiv.org/abs/2408.07773. +Data: https://physionet.org/content/mitdb/1.0.0/ (Moody and Mark, IEEE Eng. +Med. Biol. Mag. 20(3):45-50, 2001). + +One patient per 30-minute, two-lead recording; a YAML-configured metadata +table; signals are read lazily with ``wfdb`` by the task. The split +reproduces MedTsLLM's 6/4 MLII+V1 record selection exactly. +""" + +from __future__ import annotations + +import hashlib +import logging +import os +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +import dask.dataframe as dd +import numpy as np +import pandas as pd + +from .base_dataset import BaseDataset +from .splitter import Split +from .utils import MODULE_CACHE_PATH + +if TYPE_CHECKING: + from pyhealth.tasks.mitbih import MITBIHAnomalyDetection + +logger = logging.getLogger(__name__) + +MITBIH_EVENT_TYPE = "records" +MITBIH_METADATA_FILE = "mitbih-pyhealth.csv" + +# WFDB beat annotation symbols. Everything except "N" counts as abnormal. +# Non-beat annotations (rhythm "+", noise "~", artifact "|", comments, ...) +# describe the recording rather than a heartbeat and are ignored. +MITBIH_BEAT_SYMBOLS = frozenset("NLRBAaJSVrFejnE/fQ?!x\\") +MITBIH_NORMAL_SYMBOL = "N" + + +def _require_wfdb(): + """Imports ``wfdb`` lazily with an actionable error message. + + Returns: + module: The imported ``wfdb`` module. + + Raises: + ImportError: If ``wfdb`` is not installed. + + Examples: + >>> wfdb = _require_wfdb() # doctest: +SKIP + """ + try: + import wfdb + except ImportError as exc: + raise ImportError( + "Reading MIT-BIH records requires the optional 'wfdb' dependency. " + "Install it with `pip install wfdb` (also provided by " + "`pip install pyhealth[ptbxl]`)." + ) from exc + return wfdb + + +def beat_anomaly_ratio(symbols: Sequence[str]) -> float: + """Fraction of beat annotations that are abnormal (not ``"N"``). + + Args: + symbols: WFDB annotation symbols of one record. + + Returns: + float: Abnormal beats divided by all beat annotations, or ``0.0`` if + the record has no beat annotations. + + Examples: + >>> beat_anomaly_ratio(["N", "N", "V", "+", "N"]) + 0.25 + """ + beats = [s for s in symbols if s in MITBIH_BEAT_SYMBOLS] + if not beats: + return 0.0 + return sum(s != MITBIH_NORMAL_SYMBOL for s in beats) / len(beats) + + +@dataclass(frozen=True) +class MITBIHAnomalyRatioSplit(Split): + """Deterministic record-level train/test split by anomalous-beat ratio. + + Records with the fewest abnormal beats go to training (approximating + access to mostly-normal, unlabeled data) and the most abnormal go to + testing. Records whose beats are 100% abnormal are excluded. Ties are + broken by record ID, so the split is fully deterministic. + + Two modes are supported: + + - ``"paper"`` (default): the selection used by MedTsLLM for anomaly + detection. Only records whose leads are exactly ``required_leads`` + (MLII + V1) are eligible (33 records), then the ``n_train`` least and + ``n_test`` most abnormal are used. With the defaults this yields + train = 101, 112, 115, 121, 122, 230 and test = 208, 212, 217, 231, + which reproduces the paper's reported sizes exactly (1,354,170 / + 902,780 samples at 125 Hz). + - ``"fraction"``: all eligible records regardless of leads; the least + abnormal ``train_frac`` go to training and the rest to testing. + + Construct it with :meth:`MITBIHDataset.anomaly_ratio_split`, which fills + in the per-record metadata. + + Args: + anomaly_ratios: Record ID to abnormal-beat ratio. + leads: Record ID to its lead names, e.g. ``("MLII", "V1")``. + mode: ``"paper"`` or ``"fraction"``. Defaults to ``"paper"``. + required_leads: Leads required in ``"paper"`` mode. + n_train: Number of training records in ``"paper"`` mode. + n_test: Number of test records in ``"paper"`` mode. + train_frac: Training fraction in ``"fraction"`` mode. + + Examples: + >>> split = MITBIHAnomalyRatioSplit( + ... anomaly_ratios={"a": 0.0, "b": 0.3, "c": 0.1}, + ... leads={"a": ("MLII", "V1"), "b": ("MLII", "V1"), + ... "c": ("MLII", "V1")}, + ... n_train=2, n_test=1, + ... ) + >>> split.select_records() + (['a', 'c'], ['b']) + """ + + anomaly_ratios: Mapping[str, float] = field(default_factory=dict) + leads: Mapping[str, tuple[str, ...]] = field(default_factory=dict) + mode: Literal["paper", "fraction"] = "paper" + required_leads: tuple[str, ...] = ("MLII", "V1") + n_train: int = 6 + n_test: int = 4 + train_frac: float = 0.8 + + def select_records(self) -> tuple[list[str], list[str]]: + """Computes the training and test record IDs. + + Returns: + tuple[list[str], list[str]]: Training and test record IDs, each + ordered by increasing anomaly ratio. + + Raises: + ValueError: If the mode is unknown or too few records are eligible. + + Examples: + >>> MITBIHAnomalyRatioSplit( + ... anomaly_ratios={"a": 0.0, "b": 0.5, "c": 1.0}, + ... mode="fraction", train_frac=0.5, + ... ).select_records() + (['a'], ['b']) + """ + eligible = {r: v for r, v in self.anomaly_ratios.items() if v < 1.0} + if self.mode == "paper": + required = tuple(self.required_leads) + eligible = { + r: v + for r, v in eligible.items() + if tuple(self.leads.get(r, ())) == required + } + elif self.mode != "fraction": + raise ValueError(f"Unknown mode {self.mode!r}; use 'paper' or 'fraction'.") + + ordered = sorted(eligible, key=lambda r: (eligible[r], r)) + if self.mode == "paper": + if len(ordered) < self.n_train + self.n_test: + raise ValueError( + f"Only {len(ordered)} eligible records for n_train=" + f"{self.n_train} + n_test={self.n_test}." + ) + return ordered[: self.n_train], ordered[len(ordered) - self.n_test :] + n_train = max(1, round(len(ordered) * self.train_frac)) + return ordered[:n_train], ordered[n_train:] + + def split_indices( + self, patient_to_index: Mapping[str, Sequence[int]] + ) -> list[np.ndarray]: + """Returns sample indices of the training and test parts. + + Args: + patient_to_index: Patient (record) ID to the indices of its samples. + + Returns: + list[np.ndarray]: Sorted ``int64`` sample indices for the training + part, then the test part. Samples of unselected records are left + out. + + Examples: + >>> split = MITBIHAnomalyRatioSplit( + ... anomaly_ratios={"a": 0.0, "b": 0.5}, mode="fraction", + ... train_frac=0.5, + ... ) + >>> split.split_indices({"a": [0, 1], "b": [2]}) + [array([0, 1]), array([2])] + """ + train_ids, test_ids = self.select_records() + part_of = {r: 0 for r in train_ids} | {r: 1 for r in test_ids} + parts: tuple[list[int], list[int]] = ([], []) + for pid, indices in patient_to_index.items(): + part = part_of.get(str(pid)) + if part is not None: + parts[part].extend(indices) + return [np.asarray(sorted(p), dtype=np.int64) for p in parts] + + def to_dict(self) -> dict[str, Any]: + """Serializable description of the split, used in the cache key. + + Returns: + dict[str, Any]: Mode, parameters, and the selected record IDs. + + Examples: + >>> MITBIHAnomalyRatioSplit( + ... anomaly_ratios={"a": 0.0, "b": 0.5}, mode="fraction", + ... train_frac=0.5, + ... ).to_dict()["test_records"] + ['b'] + """ + train_ids, test_ids = self.select_records() + return { + "kind": "mitbih_anomaly_ratio", + "mode": self.mode, + "required_leads": list(self.required_leads), + "n_train": self.n_train, + "n_test": self.n_test, + "train_frac": self.train_frac, + "train_records": train_ids, + "test_records": test_ids, + } + + +class MITBIHDataset(BaseDataset): + """MIT-BIH Arrhythmia Database (48 two-lead, 30-minute ECG recordings). + + Each recording is treated as one patient whose ID is the record name + (e.g. ``"100"``). On construction, the WFDB headers and beat annotations + are read once and summarized in a metadata CSV with one row per record, + loaded through the ``records`` table of ``configs/mitbih.yaml``. Each + patient therefore has one ``records`` event with the file path, sampling + rate, lead names, abnormal-beat ratio and header comments. Waveforms are + loaded lazily by the task. + + The CSV is written to ``metadata_cache_dir``, so the data directory may + be read-only. A hash of its content is part of the dataset name, so + changing the records in ``root`` never reuses a stale event cache. + + Args: + root: Directory containing the ``.hea``, ``.dat`` and ``.atr`` files of + the PhysioNet ``mitdb`` 1.0.0 release. + dataset_name: Name of the dataset. Defaults to ``"mitbih"``. + config_path: YAML config. Defaults to the packaged + ``configs/mitbih.yaml``. + metadata_cache_dir: Directory for the derived metadata CSV. Defaults + to a folder under the PyHealth cache, keyed by ``root``. + cache_dir: Cache directory, see :class:`BaseDataset`. + num_workers: Number of workers for task processing. + dev: Whether to run in dev mode (limits the number of patients). + + Raises: + FileNotFoundError: If ``root`` does not exist, has no ``.hea`` files, + or a record has no ``.atr`` beat annotation file. + + Examples: + >>> from pyhealth.datasets import MITBIHDataset # doctest: +SKIP + >>> ds = MITBIHDataset(root="/data/mitdb/1.0.0") # doctest: +SKIP + >>> train, test = ds.set_task(split=ds.anomaly_ratio_split()) # doctest: +SKIP + >>> train[0]["signal"].shape # doctest: +SKIP + torch.Size([128, 2]) + """ + + def __init__( + self, + root: str | Path, + dataset_name: str | None = None, + config_path: str | Path | None = None, + metadata_cache_dir: str | Path | None = None, + cache_dir: str | Path | None = None, + num_workers: int = 1, + dev: bool = False, + ) -> None: + root_path = Path(root).expanduser().resolve() + if not root_path.is_dir(): + raise FileNotFoundError(f"MIT-BIH directory not found: {root_path}") + self.record_ids = sorted(p.stem for p in root_path.glob("*.hea")) + if not self.record_ids: + raise FileNotFoundError(f"No .hea files found in {root_path}") + + root_key = hashlib.sha1(str(root_path).encode("utf-8")).hexdigest()[:10] + self.metadata_cache_dir = Path( + metadata_cache_dir + if metadata_cache_dir is not None + else Path(MODULE_CACHE_PATH) / "mitbih" / root_key + ) + self.record_metadata = self._read_metadata(root_path) + metadata_key = self.prepare_metadata() + if config_path is None: + config_path = Path(__file__).parent / "configs" / "mitbih.yaml" + + super().__init__( + root=str(root_path), + tables=["records"], + dataset_name=f"{dataset_name or 'mitbih'}_{metadata_key}", + config_path=str(config_path), + cache_dir=cache_dir, + num_workers=num_workers, + dev=dev, + ) + + def _read_metadata(self, root: Path) -> dict[str, dict[str, Any]]: + """Reads headers and beat annotations of every record. + + Args: + root: Dataset directory. + + Returns: + dict[str, dict[str, Any]]: Record ID to metadata. + + Raises: + FileNotFoundError: If a record has no ``.atr`` annotation file. + + Examples: + >>> meta = ds._read_metadata(Path("/data/mitdb")) # doctest: +SKIP + """ + wfdb = _require_wfdb() + metadata = {} + for rid in self.record_ids: + path = root / rid + if not path.with_suffix(".atr").is_file(): + raise FileNotFoundError( + f"Record {rid} has no beat annotation file {rid}.atr in {root}" + ) + header = wfdb.rdheader(str(path)) + ann = wfdb.rdann(str(path), "atr") + metadata[rid] = { + "signal_file": str(path), + "fs": float(header.fs), + "n_samples": int(header.sig_len), + "leads": tuple(header.sig_name), + "anomaly_ratio": beat_anomaly_ratio(ann.symbol), + "comments": "; ".join(c.strip() for c in header.comments or []), + } + return metadata + + def prepare_metadata(self) -> str: + """Writes the ``records`` table CSV to ``metadata_cache_dir``. + + The file is rewritten only when its content changes. + + Returns: + str: A 10-character content hash of the CSV, used in the cache key. + + Examples: + >>> ds.prepare_metadata() # doctest: +SKIP + '3f1c0a9b2e' + """ + rows = [ + { + "patient_id": rid, + "record_id": rid, + "signal_file": meta["signal_file"], + "fs": meta["fs"], + "n_samples": meta["n_samples"], + "leads": ",".join(meta["leads"]), + "anomaly_ratio": meta["anomaly_ratio"], + "comments": meta["comments"], + } + for rid, meta in self.record_metadata.items() + ] + content = pd.DataFrame(rows).to_csv(index=False, lineterminator="\n") + self.metadata_cache_dir.mkdir(parents=True, exist_ok=True) + csv_path = self.metadata_cache_dir / MITBIH_METADATA_FILE + if not csv_path.is_file() or csv_path.read_text(encoding="utf-8") != content: + tmp_path = csv_path.with_name(csv_path.name + ".tmp") + tmp_path.write_text(content, encoding="utf-8", newline="") + os.replace(tmp_path, csv_path) + return hashlib.sha1(content.encode("utf-8")).hexdigest()[:10] + + def load_table(self, table_name: str) -> dd.DataFrame: + """Loads a table from ``metadata_cache_dir`` instead of ``root``. + + Args: + table_name: Table name from the YAML config (``"records"``). + + Returns: + dd.DataFrame: The table loaded by :meth:`BaseDataset.load_table`. + + Examples: + >>> ds.load_table("records").compute() # doctest: +SKIP + """ + data_root = self.root + self.root = str(self.metadata_cache_dir) + try: + return super().load_table(table_name) + finally: + self.root = data_root + + @property + def default_task(self) -> MITBIHAnomalyDetection: + """Default task: :class:`~pyhealth.tasks.MITBIHAnomalyDetection`. + + Returns: + MITBIHAnomalyDetection: Task with MedTsLLM defaults (125 Hz, + 128-sample windows). + + Examples: + >>> task = ds.default_task # doctest: +SKIP + """ + from pyhealth.tasks.mitbih import MITBIHAnomalyDetection + + return MITBIHAnomalyDetection() + + def anomaly_ratio_split( + self, + mode: Literal["paper", "fraction"] = "paper", + **kwargs: Any, + ) -> MITBIHAnomalyRatioSplit: + """Creates a :class:`MITBIHAnomalyRatioSplit` for this dataset. + + Args: + mode: ``"paper"`` (MedTsLLM 6/4 MLII+V1 selection) or + ``"fraction"``. + **kwargs: Other :class:`MITBIHAnomalyRatioSplit` parameters, e.g. + ``train_frac=0.8``. + + Returns: + MITBIHAnomalyRatioSplit: Split with this dataset's record metadata. + + Examples: + >>> split = ds.anomaly_ratio_split() # doctest: +SKIP + >>> split.select_records() # doctest: +SKIP + (['115', '122', '230', '112', '121', '101'], ['208', '212', '231', '217']) + """ + return MITBIHAnomalyRatioSplit( + anomaly_ratios={ + r: m["anomaly_ratio"] for r, m in self.record_metadata.items() + }, + leads={r: m["leads"] for r, m in self.record_metadata.items()}, + mode=mode, + **kwargs, + ) diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index c96e1c31b3..cfc1549e8d 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -374,6 +374,10 @@ def __getattr__(name: str): from .mpf_clinical_prediction import MPFClinicalPredictionTask return MPFClinicalPredictionTask + if name == "MITBIHAnomalyDetection": + from .mitbih import MITBIHAnomalyDetection + + return MITBIHAnomalyDetection if name == "PTBXLSuperclassClassification": from .ptbxl import PTBXLSuperclassClassification diff --git a/pyhealth/tasks/mitbih.py b/pyhealth/tasks/mitbih.py new file mode 100644 index 0000000000..39642400be --- /dev/null +++ b/pyhealth/tasks/mitbih.py @@ -0,0 +1,224 @@ +"""MIT-BIH ECG anomaly detection windows with per-step abnormal-beat labels. + +Contributors: Thi Van Trinh Tran and Zexi Li. +Reference: MedTsLLM, https://arxiv.org/abs/2408.07773. +Data: https://physionet.org/content/mitdb/1.0.0/. + +Two-lead windows resampled from 360 Hz to 125 Hz; every abnormal beat is +labeled 150 ms before and after it, following MedTsLLM. +""" + +from __future__ import annotations + +from fractions import Fraction +from typing import Any, ClassVar, Literal + +import numpy as np + +from pyhealth.data import Patient +from pyhealth.datasets.mitbih import ( + MITBIH_BEAT_SYMBOLS, + MITBIH_EVENT_TYPE, + MITBIH_NORMAL_SYMBOL, + _require_wfdb, +) + +from .base_task import BaseTask + + +def anomaly_mask( + beat_samples: np.ndarray, + symbols: list[str], + n_samples: int, + fs: float, + half_window_ms: float = 150.0, +) -> np.ndarray: + """Builds a per-sample anomaly mask from beat annotations. + + Every abnormal beat (a beat annotation other than ``"N"``) marks the + samples within ``half_window_ms`` before and after it. Non-beat + annotations are ignored. + + Args: + beat_samples: Sample index of each annotation. + symbols: WFDB symbol of each annotation. + n_samples: Length of the signal. + fs: Sampling frequency of ``beat_samples`` in Hz. + half_window_ms: Window on each side of an abnormal beat, in ms. + + Returns: + np.ndarray: ``uint8`` array of shape ``(n_samples,)``, 1 = anomalous. + + Examples: + >>> anomaly_mask(np.array([2, 7]), ["N", "V"], 10, fs=1000, + ... half_window_ms=1).tolist() + [0, 0, 0, 0, 0, 0, 1, 1, 1, 0] + """ + mask = np.zeros(n_samples, dtype=np.uint8) + half = round(fs * half_window_ms / 1000.0) + for idx, sym in zip(beat_samples, symbols): + if sym in MITBIH_BEAT_SYMBOLS and sym != MITBIH_NORMAL_SYMBOL: + mask[max(0, int(idx) - half) : min(n_samples, int(idx) + half + 1)] = 1 + return mask + + +class MITBIHAnomalyDetection(BaseTask): + """Windowed ECG anomaly detection on MIT-BIH (MedTsLLM setup). + + For each recording, the two-lead signal (in mV) is resampled from 360 Hz + to ``target_fs`` with a polyphase filter and cut into windows of + ``window_len`` samples every ``step_size`` samples. By default the label + is a per-time-step binary anomaly mask aligned with the window, as in + MedTsLLM. With ``label_level="window"``, the label is instead one binary + value per window (1 if any time step is anomalous), so that standard + PyHealth classifiers can be trained on the task. + + Each sample contains: + + - ``signal``: ``float32`` array of shape ``(window_len, 2)`` + - ``label``: ``int64`` array of shape ``(window_len,)`` with + ``label_level="step"``, or an ``int`` with ``label_level="window"``; + 1 = anomalous + - ``patient_id`` / ``record_id``: record name, e.g. ``"208"`` + - ``window_start``: index of the first sample in the resampled signal + - ``description``: header comments (age, sex, medications, notes), usable + as a text prompt by multimodal models such as MedTsLLM + + The per-step labels are intended for evaluation: reconstruction-based + detectors such as GPT4TS or MedTsLLM train on the signal only. + + Args: + target_fs: Sampling frequency after resampling, in Hz. Defaults to + 125.0 (MedTsLLM). + window_len: Samples per window. Defaults to 128 (MedTsLLM). + step_size: Stride between windows. Defaults to ``window_len`` + (non-overlapping windows). + half_window_ms: Anomaly window on each side of an abnormal beat, in + ms. Defaults to 150.0 (MedTsLLM). + label_level: ``"step"`` for a per-time-step label (``"tensor"`` + output schema) or ``"window"`` for one label per window + (``"binary"`` output schema). Defaults to ``"step"``. + + Raises: + ValueError: If a length is not positive, ``half_window_ms`` is + negative, or ``label_level`` is unknown. + + Examples: + >>> from pyhealth.datasets import MITBIHDataset # doctest: +SKIP + >>> from pyhealth.tasks import MITBIHAnomalyDetection # doctest: +SKIP + >>> ds = MITBIHDataset(root="/data/mitdb/1.0.0") # doctest: +SKIP + >>> train, test = ds.set_task( # doctest: +SKIP + ... MITBIHAnomalyDetection(), split=ds.anomaly_ratio_split() + ... ) + >>> test[0]["label"].shape # doctest: +SKIP + torch.Size([128]) + """ + + task_name: str = "MITBIHAnomalyDetection" + input_schema: ClassVar[dict[str, str]] = {"signal": "tensor"} + # Set per instance from label_level ("tensor" or "binary"). + output_schema: dict[str, str] + + def __init__( + self, + target_fs: float = 125.0, + window_len: int = 128, + step_size: int | None = None, + half_window_ms: float = 150.0, + label_level: Literal["step", "window"] = "step", + ) -> None: + if target_fs <= 0: + raise ValueError("target_fs must be positive.") + if window_len <= 0 or (step_size is not None and step_size <= 0): + raise ValueError("window_len and step_size must be positive.") + if half_window_ms < 0: + raise ValueError("half_window_ms must be non-negative.") + if label_level not in ("step", "window"): + raise ValueError( + f"Unknown label_level {label_level!r}; use 'step' or 'window'." + ) + super().__init__() + self.target_fs = float(target_fs) + self.window_len = int(window_len) + self.step_size = int(step_size) if step_size is not None else self.window_len + self.half_window_ms = float(half_window_ms) + self.label_level = label_level + self.output_schema = {"label": "tensor" if label_level == "step" else "binary"} + + def _resample(self, signal: np.ndarray, fs: float) -> np.ndarray: + """Resamples ``signal`` along time from ``fs`` to ``target_fs``. + + Args: + signal: Array of shape ``(n_samples, n_leads)``. + fs: Original sampling frequency in Hz. + + Returns: + np.ndarray: ``float32`` array of shape ``(n_resampled, n_leads)``. + + Examples: + >>> MITBIHAnomalyDetection()._resample(np.zeros((360, 2)), 360).shape + (125, 2) + """ + if fs == self.target_fs: + return signal.astype(np.float32) + from scipy.signal import resample_poly + + ratio = Fraction(self.target_fs / fs).limit_denominator(10_000) + out = resample_poly(signal, ratio.numerator, ratio.denominator, axis=0) + return out.astype(np.float32) + + def __call__(self, patient: Patient) -> list[dict[str, Any]]: + """Generates windowed samples for one recording. + + Args: + patient: Patient with one ``records`` event. + + Returns: + list[dict[str, Any]]: One sample per window; empty if the patient + has no record event or the recording is shorter than a window. + + Examples: + >>> samples = MITBIHAnomalyDetection()(patient) # doctest: +SKIP + """ + events = patient.get_events(event_type=MITBIH_EVENT_TYPE) + if not events: + return [] + event = events[0] + wfdb = _require_wfdb() + + record = wfdb.rdrecord(event["signal_file"]) + ann = wfdb.rdann(event["signal_file"], "atr") + fs = float(record.fs) + raw = record.p_signal + signal = self._resample(raw, fs) + + # Label at the original rate, then map each resampled time step to the + # nearest original sample, so label and signal lengths always agree. + mask = anomaly_mask( + ann.sample, list(ann.symbol), len(raw), fs, self.half_window_ms + ) + nearest = np.round(np.linspace(0, len(raw) - 1, len(signal))).astype(int) + label = mask[nearest].astype(np.int64) + + record_id = str(event["record_id"]) + # Empty CSV fields are read back as missing values. + comments = event["comments"] + description = comments if isinstance(comments, str) else "" + samples = [] + for start in range(0, len(signal) - self.window_len + 1, self.step_size): + end = start + self.window_len + samples.append( + { + "patient_id": patient.patient_id, + "record_id": record_id, + "window_start": start, + "signal": signal[start:end], + "label": ( + label[start:end] + if self.label_level == "step" + else int(label[start:end].any()) + ), + "description": description, + } + ) + return samples diff --git a/tests/core/test_mitbih.py b/tests/core/test_mitbih.py new file mode 100644 index 0000000000..ffe91b5dc3 --- /dev/null +++ b/tests/core/test_mitbih.py @@ -0,0 +1,306 @@ +"""Offline synthetic MIT-BIH dataset, split and task tests; no real records. + +Contributors: Thi Van Trinh Tran and Zexi Li. +Five tiny synthetic WFDB records (3 s each) are written at test time. Covers +the abnormal-beat ratio, the paper split's exclusions, the YAML metadata +table, step- and window-level labels, and the end-to-end ``set_task`` path. +""" + +from __future__ import annotations + +import shutil +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import numpy as np +import pandas as pd +import yaml +from distributed import LocalCluster + +from pyhealth.datasets import MITBIHAnomalyRatioSplit, MITBIHDataset +from pyhealth.datasets.mitbih import MITBIH_METADATA_FILE, beat_anomaly_ratio +from pyhealth.tasks import MITBIHAnomalyDetection +from pyhealth.tasks.mitbih import anomaly_mask + +FS = 360 +N_SAMPLES = 3 * FS +BEATS = np.arange(90, N_SAMPLES, 180) # 6 beats, every 0.5 s + +# record -> (leads, beat symbols, extra non-beat annotations) +RECORDS = { + "100": (("MLII", "V1"), ["N"] * 6, [(10, "+"), (500, "~")]), + "101": (("MLII", "V1"), ["N", "N", "V", "N", "N", "N"], [(10, "+")]), + "102": (("MLII", "V1"), ["N", "V", "N", "V", "A", "N"], []), + "103": (("MLII", "V1"), ["V"] * 6, []), # 100% abnormal: always excluded + "104": (("V5", "V2"), ["N", "V", "N", "N", "N", "N"], []), # wrong leads +} + + +def _write_records(root: Path) -> None: + import wfdb + + t = np.arange(N_SAMPLES) / FS + for rid, (leads, beats, extra) in RECORDS.items(): + signal = np.stack([np.sin(2 * np.pi * t), 0.5 * np.cos(2 * np.pi * t)], 1) + wfdb.wrsamp( + rid, + fs=FS, + units=["mV", "mV"], + sig_name=list(leads), + p_signal=signal, + fmt=["212", "212"], + comments=["69 M", f"synthetic record {rid}"], + write_dir=str(root), + ) + ann = sorted([(int(s), b) for s, b in zip(BEATS, beats)] + extra) + wfdb.wrann( + rid, + "atr", + np.array([s for s, _ in ann]), + [b for _, b in ann], + write_dir=str(root), + ) + + +class TestMITBIHHelpers(unittest.TestCase): + def test_beat_anomaly_ratio_ignores_non_beat_annotations(self): + self.assertEqual(beat_anomaly_ratio(["N", "+", "V", "~", "|", "N"]), 1 / 3) + self.assertEqual(beat_anomaly_ratio(["+", "~"]), 0.0) + + def test_anomaly_mask_expands_abnormal_beats_only(self): + mask = anomaly_mask( + np.array([100, 300]), ["V", "N"], 400, fs=1000, half_window_ms=10 + ) + self.assertEqual(mask.sum(), 21) + self.assertTrue(mask[90:111].all()) + self.assertFalse(mask[280:321].any()) + + def test_anomaly_mask_clips_at_edges(self): + mask = anomaly_mask(np.array([2]), ["V"], 10, fs=1000, half_window_ms=5) + self.assertEqual(mask.tolist(), [1] * 8 + [0] * 2) + + def test_task_rejects_bad_config(self): + for kwargs in ( + {"window_len": 0}, + {"step_size": -1}, + {"target_fs": 0}, + {"half_window_ms": -1}, + {"label_level": "beat"}, + ): + with self.subTest(**kwargs), self.assertRaises(ValueError): + MITBIHAnomalyDetection(**kwargs) + + def test_output_schema_follows_label_level(self): + self.assertEqual(MITBIHAnomalyDetection().output_schema, {"label": "tensor"}) + self.assertEqual( + MITBIHAnomalyDetection(label_level="window").output_schema, + {"label": "binary"}, + ) + + +SPLIT_RATIOS = {"a": 0.0, "b": 0.2, "c": 0.5, "d": 1.0, "e": 0.1} +SPLIT_LEADS = {k: ("MLII", "V1") for k in "abcd"} | {"e": ("V5", "V2")} + + +class TestMITBIHAnomalyRatioSplit(unittest.TestCase): + def test_paper_mode_filters_leads_and_all_abnormal(self): + split = MITBIHAnomalyRatioSplit(SPLIT_RATIOS, SPLIT_LEADS, n_train=1, n_test=1) + self.assertEqual(split.select_records(), (["a"], ["c"])) + + def test_fraction_mode_uses_all_leads(self): + split = MITBIHAnomalyRatioSplit( + SPLIT_RATIOS, SPLIT_LEADS, mode="fraction", train_frac=0.5 + ) + self.assertEqual(split.select_records(), (["a", "e"], ["b", "c"])) + + def test_ties_broken_by_record_id(self): + split = MITBIHAnomalyRatioSplit( + {"z": 0.0, "y": 0.0, "x": 0.3}, mode="fraction", train_frac=0.67 + ) + self.assertEqual(split.select_records(), (["y", "z"], ["x"])) + + def test_split_indices_and_to_dict(self): + split = MITBIHAnomalyRatioSplit(SPLIT_RATIOS, SPLIT_LEADS, n_train=1, n_test=1) + parts = split.split_indices({"a": [0, 1], "c": [4], "d": [2], "e": [3]}) + self.assertEqual([p.tolist() for p in parts], [[0, 1], [4]]) + self.assertEqual(parts[0].dtype, np.int64) + info = split.to_dict() + self.assertEqual((info["train_records"], info["test_records"]), (["a"], ["c"])) + + def test_too_few_records_raises(self): + split = MITBIHAnomalyRatioSplit(SPLIT_RATIOS, SPLIT_LEADS) # needs 6 + 4 + with self.assertRaises(ValueError): + split.select_records() + + def test_unknown_mode_raises(self): + with self.assertRaises(ValueError): + MITBIHAnomalyRatioSplit(SPLIT_RATIOS, mode="random").select_records() + + +def _threaded_cluster(**kwargs): + # Same Dask work in worker threads instead of child processes, which take + # seconds to start; as in tests/core/survival_test_utils.py. + return LocalCluster(**{**kwargs, "processes": False}) + + +class TestMITBIHDatasetAndTask(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.cluster_patch = patch( + "pyhealth.datasets.base_dataset.DaskCluster", _threaded_cluster + ) + cls.cluster_patch.start() + cls.tmp = Path(tempfile.mkdtemp()) + cls.root = cls.tmp / "mitdb" + cls.meta_dir = cls.tmp / "meta" + cls.root.mkdir() + _write_records(cls.root) + cls.dataset = MITBIHDataset( + root=cls.root, metadata_cache_dir=cls.meta_dir, cache_dir=cls.tmp / "cache" + ) + # One-time costs (importing scipy.signal, indexing the patients) are + # paid here rather than by whichever task test happens to run first. + MITBIHAnomalyDetection()(cls.dataset.get_patient("100")) + + @classmethod + def tearDownClass(cls): + cls.cluster_patch.stop() + shutil.rmtree(cls.tmp, ignore_errors=True) + + def test_missing_root_raises(self): + with self.assertRaises(FileNotFoundError): + MITBIHDataset(root=self.root / "missing", metadata_cache_dir=self.meta_dir) + + def test_missing_annotations_raises(self): + partial = self.tmp / "partial" + partial.mkdir() + shutil.copy(self.root / "100.hea", partial) + shutil.copy(self.root / "100.dat", partial) + with self.assertRaises(FileNotFoundError): + MITBIHDataset(root=partial, metadata_cache_dir=self.tmp / "meta2") + + def test_changed_records_get_a_new_cache_name(self): + import wfdb + + root = self.tmp / "changed" + shutil.copytree(self.root, root) + dirs = {"metadata_cache_dir": self.tmp / "meta3", "cache_dir": self.tmp / "c3"} + before = MITBIHDataset(root=root, **dirs) + # Record 100 gets an abnormal beat in place of its first normal one. + ann = wfdb.rdann(str(root / "100"), "atr") + symbols = list(ann.symbol) + symbols[symbols.index("N")] = "V" + wfdb.wrann("100", "atr", ann.sample, symbols, write_dir=str(root)) + after = MITBIHDataset(root=root, **dirs) + self.assertNotEqual(before.dataset_name, after.dataset_name) + self.assertEqual(before.record_metadata["100"]["anomaly_ratio"], 0.0) + self.assertAlmostEqual(after.record_metadata["100"]["anomaly_ratio"], 1 / 6) + event = after.get_patient("100").get_events(event_type="records")[0] + self.assertAlmostEqual(float(event.anomaly_ratio), 1 / 6) + + def test_metadata_table_matches_yaml_config(self): + csv_path = self.meta_dir / MITBIH_METADATA_FILE + self.assertTrue(csv_path.is_file()) + self.assertFalse((self.root / MITBIH_METADATA_FILE).exists()) + config_path = ( + Path(__file__).parents[2] / "pyhealth/datasets/configs/mitbih.yaml" + ) + table = yaml.safe_load(config_path.read_text())["tables"]["records"] + self.assertEqual(table["file_path"], MITBIH_METADATA_FILE) + df = pd.read_csv(csv_path, dtype=str) + self.assertEqual(list(df.columns), [table["patient_id"]] + table["attributes"]) + self.assertEqual(sorted(df["record_id"]), sorted(RECORDS)) + + def test_record_metadata(self): + meta = self.dataset.record_metadata + self.assertEqual(sorted(meta), sorted(RECORDS)) + self.assertEqual(meta["104"]["leads"], ("V5", "V2")) + self.assertEqual(meta["100"]["anomaly_ratio"], 0.0) + self.assertAlmostEqual(meta["102"]["anomaly_ratio"], 0.5) + self.assertEqual(meta["100"]["n_samples"], N_SAMPLES) + self.assertIn("synthetic record 100", meta["100"]["comments"]) + + def test_patients_have_one_record_event(self): + self.assertEqual(sorted(self.dataset.unique_patient_ids), sorted(RECORDS)) + patient = self.dataset.get_patient("101") + events = patient.get_events(event_type="records") + self.assertEqual(len(events), 1) + self.assertEqual(events[0]["leads"], "MLII,V1") + self.assertEqual(float(events[0]["fs"]), FS) + self.assertIn("synthetic record 101", events[0]["comments"]) + + def test_anomaly_ratio_split_from_dataset(self): + split = self.dataset.anomaly_ratio_split(n_train=2, n_test=1) + self.assertEqual(split.select_records(), (["100", "101"], ["102"])) + + def test_task_windows_and_labels(self): + task = MITBIHAnomalyDetection() + samples = task(self.dataset.get_patient("101")) + n_resampled = N_SAMPLES * 125 // 360 # 375 + self.assertEqual(len(samples), n_resampled // 128) + first = samples[0] + self.assertEqual(first["signal"].shape, (128, 2)) + self.assertEqual(first["signal"].dtype, np.float32) + self.assertEqual(first["label"].dtype, np.int64) + self.assertEqual(first["record_id"], "101") + self.assertEqual([s["window_start"] for s in samples], [0, 128]) + + # The only abnormal beat (V at 450 / 360 Hz = 1.25 s) maps to step ~156 + # at 125 Hz, with +/-150 ms (~19 steps) labelled on each side. + label = np.concatenate([s["label"] for s in samples]) + self.assertTrue(label[140:172].all()) + self.assertEqual(label[:130].sum() + label[180:].sum(), 0) + self.assertEqual(first["description"], "69 M; synthetic record 101") + + def test_label_width_follows_half_window(self): + patient = self.dataset.get_patient("101") + widths = {} + for half_ms in (0.0, 50.0, 150.0): + samples = MITBIHAnomalyDetection(half_window_ms=half_ms)(patient) + widths[half_ms] = int(sum(s["label"].sum() for s in samples)) + # 2 * round(125 Hz * ms / 1000) + 1 steps, up to resampling rounding. + self.assertLessEqual(widths[0.0], 2) + self.assertAlmostEqual(widths[50.0], 13, delta=2) + self.assertAlmostEqual(widths[150.0], 39, delta=2) + + def test_window_level_labels(self): + task = MITBIHAnomalyDetection(label_level="window") + samples = task(self.dataset.get_patient("101")) + # The abnormal beat (step ~156) lies in the second window only. + self.assertEqual([s["label"] for s in samples], [0, 1]) + overlapping = MITBIHAnomalyDetection(label_level="window", step_size=64) + labels = [s["label"] for s in overlapping(self.dataset.get_patient("101"))] + # Windows start at 0, 64, 128, 192; steps ~137-175 are labelled. + self.assertEqual(labels, [0, 1, 1, 0]) + + def test_task_skips_patient_without_events(self): + class _Empty: + def get_events(self, event_type=None): + return [] + + self.assertEqual(MITBIHAnomalyDetection()(_Empty()), []) + + def test_set_task_with_paper_split(self): + split = self.dataset.anomaly_ratio_split(n_train=2, n_test=1) + train, test = self.dataset.set_task(split=split) + self.assertEqual( + {train[i]["record_id"] for i in range(len(train))}, {"100", "101"} + ) + self.assertEqual({test[i]["record_id"] for i in range(len(test))}, {"102"}) + self.assertEqual(tuple(train[0]["signal"].shape), (128, 2)) + self.assertEqual(tuple(test[0]["label"].shape), (128,)) + + def test_set_task_with_window_labels(self): + split = self.dataset.anomaly_ratio_split(n_train=2, n_test=1) + _, test = self.dataset.set_task( + MITBIHAnomalyDetection(label_level="window"), split=split + ) + labels = [int(test[i]["label"]) for i in range(len(test))] + self.assertEqual(len(labels), 2) + self.assertEqual(max(labels), 1) + + +if __name__ == "__main__": + unittest.main()