From 4401bfaee3c079053daa266e6449fb7429415324 Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Fri, 27 Nov 2026 00:42:40 -0500 Subject: [PATCH 1/4] Add the MedMod in-hospital mortality dataset, task and EHR processor Part 1 of 4 of sunlabuiuc/PyHealth#1609. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- docs/api/datasets.rst | 1 + .../pyhealth.datasets.MedModMIMIC4Dataset.rst | 26 + docs/api/tasks.rst | 1 + ...health.tasks.MedModInHospitalMortality.rst | 84 ++ pyhealth/datasets/__init__.py | 5 + .../datasets/configs/mimic4_ehr_v1.0.yaml | 99 ++ pyhealth/datasets/medmod/__init__.py | 11 + pyhealth/datasets/medmod/discretizer.py | 342 +++++ pyhealth/datasets/medmod/downloads.py | 111 ++ pyhealth/datasets/medmod/extraction.py | 1117 +++++++++++++++++ pyhealth/datasets/medmod/files/MEDMOD_COMMIT | 1 + pyhealth/datasets/medmod/files/MEDMOD_LICENSE | 201 +++ pyhealth/datasets/medmod/files/NOTICE | 35 + .../medmod/files/discretizer_config.json | 154 +++ .../datasets/medmod/files/ph_ts1.0.normalizer | Bin 0 -> 1400 bytes pyhealth/datasets/medmod_mimic4.py | 279 ++++ pyhealth/processors/medmod_ehr_processor.py | 146 +++ pyhealth/tasks/__init__.py | 7 + pyhealth/tasks/medmod_mortality_mimic4.py | 246 ++++ .../medmod/itemid_to_variable_map.csv | 11 + tests/core/medmod_test_utils.py | 385 ++++++ tests/core/test_medmod_mimic4_dataset.py | 177 +++ tests/core/test_medmod_mimic4_extraction.py | 537 ++++++++ tests/core/test_medmod_mimic4_processor.py | 183 +++ 24 files changed, 4159 insertions(+) create mode 100644 docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst create mode 100644 docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst create mode 100644 pyhealth/datasets/configs/mimic4_ehr_v1.0.yaml create mode 100644 pyhealth/datasets/medmod/__init__.py create mode 100644 pyhealth/datasets/medmod/discretizer.py create mode 100644 pyhealth/datasets/medmod/downloads.py create mode 100644 pyhealth/datasets/medmod/extraction.py create mode 100644 pyhealth/datasets/medmod/files/MEDMOD_COMMIT create mode 100644 pyhealth/datasets/medmod/files/MEDMOD_LICENSE create mode 100644 pyhealth/datasets/medmod/files/NOTICE create mode 100755 pyhealth/datasets/medmod/files/discretizer_config.json create mode 100755 pyhealth/datasets/medmod/files/ph_ts1.0.normalizer create mode 100644 pyhealth/datasets/medmod_mimic4.py create mode 100644 pyhealth/processors/medmod_ehr_processor.py create mode 100644 pyhealth/tasks/medmod_mortality_mimic4.py create mode 100644 test-resources/medmod/itemid_to_variable_map.csv create mode 100644 tests/core/medmod_test_utils.py create mode 100644 tests/core/test_medmod_mimic4_dataset.py create mode 100644 tests/core/test_medmod_mimic4_extraction.py create mode 100644 tests/core/test_medmod_mimic4_processor.py diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst index 7b95e009a8..80ab1a1ef3 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -643,6 +643,7 @@ Available Datasets datasets/pyhealth.datasets.MIMIC4EDDataset datasets/pyhealth.datasets.KiTS23Dataset datasets/pyhealth.datasets.MIMIC4ImaGenomeDataset + datasets/pyhealth.datasets.MedModMIMIC4Dataset datasets/pyhealth.datasets.BrainTumorMRIDataset datasets/pyhealth.datasets.FHIRDataset datasets/pyhealth.datasets.MEDSDataset diff --git a/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst b/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst new file mode 100644 index 0000000000..d1bda5191e --- /dev/null +++ b/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst @@ -0,0 +1,26 @@ +pyhealth.datasets.MedModMIMIC4Dataset +===================================== + +MIMIC-IV v1.0 and MIMIC-CXR-JPG 2.0.0 as used by MedMod (Elsharief et al., +"MedMod: Multimodal Benchmark for Medical Prediction Tasks with Electronic +Health Records and Chest X-Ray Scans", CHIL 2025, PMLR 287; +`paper `__, +`code `__) for in-hospital mortality, +with MedMod's fixed train / val / test split. Use it with +:class:`~pyhealth.tasks.MedModInHospitalMortality`. + +Access to `MIMIC-IV v1.0 `__ +and `MIMIC-CXR-JPG 2.0.0 `__ +needs PhysioNet credentialing. + +.. autoclass:: pyhealth.datasets.MedModMIMIC4Dataset + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.datasets.MedModSplit + :members: + :undoc-members: + :show-inheritance: + +.. autofunction:: pyhealth.datasets.split_by_medmod diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 00149a96e0..5f36698eb8 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -252,6 +252,7 @@ Available Tasks EHR Generation Length of Stay Prediction Length of Stay Prediction (StageNet MIMIC-IV) + MedMod In-Hospital Mortality (MIMIC-IV + CXR) Medical Transcriptions Classification MPF Clinical Prediction (FHIR) Mortality Prediction (Next Visit) diff --git a/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst new file mode 100644 index 0000000000..f3f58ed3b4 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst @@ -0,0 +1,84 @@ +pyhealth.tasks.MedModInHospitalMortality +======================================== + +In-hospital mortality from the first 48 hours of an ICU stay and the latest +chest X-ray in that window, reproducing MedMod (Elsharief et al., 2025) and its +released code: one sample per ICU stay with ``ehr`` (48 x 76), ``image_path`` +and ``label``. Use it with :class:`~pyhealth.datasets.MedModMIMIC4Dataset`. + +.. autoclass:: pyhealth.tasks.MedModInHospitalMortality + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.processors.medmod_ehr_processor.MedModEHRProcessor + :members: + :undoc-members: + :show-inheritance: + +Per-model settings +------------------ + +MedMod's models read their data through two code paths, and the task +reproduces each. Both use the same cohort, labels and split; only the EHR rows +at Hours == 0 and the image transform differ. + +.. list-table:: + :header-rows: 1 + + * - Model + - ``hours_zero`` + - Image transform + - Why + * - Early Fusion + - ``"keep"`` + - ImageNet-normalized + - MedMod's supervised ``fusion_main.py:13-16`` imports ``datasets.*`` and + ``ehr_utils.*``, which exist only in MedFuse; MedFuse's + ``datasets/ehr_dataset.py`` keeps every row and + ``datasets/cxr_dataset.py`` normalizes. + * - ConVIRT (pretraining, linear evaluation) + - ``"drop"`` + - pixels in [0, 1] + - MedMod's ``src/data/datasets.py:137-163`` keeps 0 < t only; the ConVIRT + scripts pass ``--transforms_cxr simclrv2``. + +Paper vs code +------------- + +Where MedMod's paper and released code disagree, the task follows the code, +which produced the reported numbers. The bin width and the normalizer remain +settings of the task (``timestep``, ``normalizer``). + +.. list-table:: + :header-rows: 1 + + * - Rule + - MedMod paper + - Released code + - Default here + * - Bin width + - §3.2.2 "every two hours" (MedFuse §4.1.1 too) + - 1 h (``--timestep`` default 1.0, ``src/parser.py:30``) + - 1 h (``timestep``) + * - Normalizer + - §3.2.2 "task-specific", computed on the dataset + - the phenotyping file ``ph_ts1.0`` (an ``is`` comparison in ``ehr_funcs``) + - ``ph_ts1.0``; ``normalizer=None`` fits one on the train split + * - Split + - §3.2.4 random 70/10/20 by patient + - fixed subject lists + - the fixed lists, which reproduce Table 2 + +Two checks on the real data (image-paired test set, 1,241 stays): + +- MedFuse's released EHR checkpoint (``checkpoints/mortality/uni_ehr_all``), + evaluated frozen: test AUROC 0.833 (95% CI 0.802-0.860) with 1 h + + ``ph_ts1.0``, against 0.735 with 1 h + a normalizer fitted on the train split + and 0.719 with 2 h + fitted; MedFuse reports 0.825 (0.793-0.852). So a model + that uses MedFuse's encoders frozen needs the code's settings. MedFuse split + with the same subject lists, so its training data holds none of these test + patients. +- MedMod's EHR LSTM trained from scratch (5 seeds): 1 h vs 2 h with the same + normalizer makes no difference (Δ AUROC +0.000 ± 0.006); ``ph_ts1.0`` scores + 0.009 higher than a fitted normalizer (0.816 vs 0.807; paper Table 3: 0.829). diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 17043a7c6b..eae3a84f8d 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -133,6 +133,11 @@ def __init__(self, *args, **kwargs): ) from .gold_test_split import GoldTestSplit as GoldTestSplit from .mimic4_imagenome import MIMIC4ImaGenomeDataset as MIMIC4ImaGenomeDataset +from .medmod_mimic4 import ( + MedModMIMIC4Dataset as MedModMIMIC4Dataset, + MedModSplit as MedModSplit, + split_by_medmod as split_by_medmod, +) from .eegbci import EEGBCIDataset as EEGBCIDataset # noqa: E402 from .ahepa_dementia import AHEPADementiaDataset as AHEPADementiaDataset from .bciiv2a import BCICompetitionIV2aDataset as BCICompetitionIV2aDataset diff --git a/pyhealth/datasets/configs/mimic4_ehr_v1.0.yaml b/pyhealth/datasets/configs/mimic4_ehr_v1.0.yaml new file mode 100644 index 0000000000..a6ea5db411 --- /dev/null +++ b/pyhealth/datasets/configs/mimic4_ehr_v1.0.yaml @@ -0,0 +1,99 @@ +# PyHealth table config for MIMIC-IV v1.0 (core/ + hosp/ + icu/, `ethnicity`). +# +# Adapted from PyHealth's v2.2 config (pyhealth/datasets/configs/mimic4_ehr.yaml) +# for the tables the MedMod IHM task reads. Changes from v2.2: +# * patients, admissions: hosp/ -> core/ (v1.0 layout) +# * admissions: `race` -> `ethnicity` (MedMod reads `ethnicity`, mimic3csv.py:27) +# * icustays: add `los` (create_ihm.py:34 uses icustays.los, in days) +# * diagnoses_icd: extra inner join with hosp/d_icd_diagnoses on icd_code +# only (not icd_version), as MedMod does in mimic3csv.py:44-48; a diagnosis +# with no match is dropped +# * labevents: no join with d_labitems (the task needs only itemid/value) +# * chartevents, labevents: no valueuom (see the note at the end) +# PyHealth tries both .csv and .csv.gz (_csv_tsv_gz_path in base_dataset.py), so +# either works. +# Column lists were written from memory of the v1.0 schema and confirmed by a +# full run on the real v1.0 files (2026-11-09): PyHealth selects every listed +# attribute, so a missing column would have failed the load. +version: "1.0" +tables: + patients: + file_path: "core/patients.csv.gz" + patient_id: "subject_id" + timestamp: null + attributes: + - "gender" + - "anchor_age" + - "anchor_year" + - "anchor_year_group" + - "dod" + + admissions: + file_path: "core/admissions.csv.gz" + patient_id: "subject_id" + timestamp: "admittime" + attributes: + - "hadm_id" + - "admission_type" + - "dischtime" + - "deathtime" + - "ethnicity" + - "hospital_expire_flag" + + icustays: + file_path: "icu/icustays.csv.gz" + patient_id: "subject_id" + timestamp: "intime" + attributes: + - "hadm_id" + - "stay_id" + - "first_careunit" + - "last_careunit" + - "outtime" + - "los" + + diagnoses_icd: + file_path: "hosp/diagnoses_icd.csv.gz" + patient_id: "subject_id" + join: + - file_path: "core/admissions.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + - file_path: "hosp/d_icd_diagnoses.csv.gz" + "on": "icd_code" + how: "inner" + columns: + - "long_title" + timestamp: "dischtime" + attributes: + - "hadm_id" + - "icd_code" + - "icd_version" + - "seq_num" + - "long_title" + + labevents: + file_path: "hosp/labevents.csv.gz" + patient_id: "subject_id" + timestamp: "charttime" + attributes: + - "hadm_id" + - "itemid" + - "value" + - "valuenum" + + chartevents: + file_path: "icu/chartevents.csv.gz" + patient_id: "subject_id" + timestamp: "charttime" + attributes: + - "hadm_id" + - "stay_id" + - "itemid" + - "value" + - "valuenum" +# valueuom is left out of both event tables: MedMod never reads units for +# chartevents/labevents (it stores valuenum in that slot, mimic3csv.py:220), and +# every column kept here is carried through PyHealth's disk-heavy sort. diff --git a/pyhealth/datasets/medmod/__init__.py b/pyhealth/datasets/medmod/__init__.py new file mode 100644 index 0000000000..c2480cc72a --- /dev/null +++ b/pyhealth/datasets/medmod/__init__.py @@ -0,0 +1,11 @@ +"""MedMod (Elsharief et al., 2025) in-hospital mortality: the parts behind +``MedModMIMIC4Dataset`` and ``MedModInHospitalMortality``. + +* ``extraction``: cohort, labels, value cleaning, time series and CXR pairing, + one subject at a time, following MedMod's code line by line. +* ``discretizer``: MedMod's Discretizer and Normalizer. +* ``downloads``: MedMod's subject lists and item map, downloaded from MedMod's + GitHub (pinned commit, SHA-256 checked) on first use. +* ``files/``: MedMod's discretizer config and normalizer (Apache-2.0, see + ``files/NOTICE``). +""" diff --git a/pyhealth/datasets/medmod/discretizer.py b/pyhealth/datasets/medmod/discretizer.py new file mode 100644 index 0000000000..fa09741951 --- /dev/null +++ b/pyhealth/datasets/medmod/discretizer.py @@ -0,0 +1,342 @@ +"""MedMod discretizer and normalizer, ported for the PyHealth IHM task. + +Source: MedMod repo (github.com/nyuad-cai/MedMod, commit in +``files/MEDMOD_COMMIT``), file ``src/data/preprocessing.py``. Line numbers +below refer to that file. The algorithm is unchanged; the port only + +* fixes the settings MedMod calls it with (``ehr_funcs``, lines 247-252): + ``store_masks=True``, ``impute_strategy='previous'``, ``start_time='zero'``, + and drops the branches for the other values; the bin width stays a setting + (default 1.0, the ``--timestep`` default), +* drops the statistics counters (lines 29-32, 147-150), which do not affect output, +* loads the normalizer pickle with a restricted unpickler instead of + ``pickle.load`` (line 220), so a tampered file cannot run code. +""" + +from __future__ import annotations + +import copy +import hashlib +import json +import pickle +import warnings +from collections.abc import Iterable, Sequence +from pathlib import Path +from typing import ClassVar + +import numpy as np + +# MedMod's own files (Apache-2.0, see files/NOTICE), bundled with this package. +MEDMOD_FILES = Path(__file__).resolve().parent / "files" +DEFAULT_CONFIG = MEDMOD_FILES / "discretizer_config.json" +# The normalizer MedMod's released code loads for IHM: the *phenotyping* one. +# ehr_funcs tests `args.task is 'mortality'` (preprocessing.py:259), an identity +# check on an argparse string that is False in practice, so it falls through to +# the `else` branch at line 265-266 (ph_ts{timestep}...normalizer). +# MedMod's ph_ts1.0.input_str:previous.start_time:zero.normalizer, renamed +# because Windows does not allow colons in file names. +PH_NORMALIZER = MEDMOD_FILES / "ph_ts1.0.normalizer" + +EPS = 1e-6 # preprocessing.py:38 + + +def _check_timestep(timestep: float) -> float: + if not timestep > 0: + raise ValueError(f"timestep must be > 0 hours, got {timestep}") + return float(timestep) + + +class Discretizer: + """Port of ``Discretizer`` (preprocessing.py:11-172) with the settings + MedMod calls it with (``ehr_funcs``, lines 247-252): masks stored, + previous-value imputation, time measured from ICU admission. + + Args: + timestep: bin width in hours (MedMod's default 1.0). + + Examples: + >>> from pyhealth.datasets.medmod.discretizer import Discretizer + >>> disc = Discretizer() + >>> row = ["0.5"] + [""] * len(disc.channels) # [Hours, 17 channels] + >>> row[1 + disc.channels.index("Heart Rate")] = "80" + >>> disc.transform([row], end=48.0).shape + (48, 76) + """ + + def __init__(self, timestep: float = 1.0): + with open(DEFAULT_CONFIG) as f: # lines 15-21 + config = json.load(f) + self._id_to_channel: list[str] = config["id_to_channel"] + self._channel_to_id = {c: i for i, c in enumerate(self._id_to_channel)} + self._is_categorical_channel = config["is_categorical_channel"] + self._possible_values = config["possible_values"] + self._normal_values = config["normal_values"] + + self._header = ["Hours"] + self._id_to_channel # line 23 + self._timestep = _check_timestep(timestep) + + # Column layout, lines 59-69: channels in config order, a categorical + # channel takes len(possible_values) one-hot columns. + self._begin_pos: list[int] = [] + cur_len = 0 + for channel in self._id_to_channel: + self._begin_pos.append(cur_len) + if self._is_categorical_channel[channel]: + cur_len += len(self._possible_values[channel]) + else: + cur_len += 1 + self._n_data_cols = cur_len + + @property + def channels(self) -> list[str]: + """The 17 variable names, in the discretizer's column order.""" + return list(self._id_to_channel) + + @property + def header(self) -> list[str]: + """Input header: ``Hours`` + the 17 channels in config order.""" + return list(self._header) + + def output_header(self) -> list[str]: + """Output column names, built as in lines 156-168.""" + out = [] + for channel in self._id_to_channel: + if self._is_categorical_channel[channel]: + out += [f"{channel}->{v}" for v in self._possible_values[channel]] + else: + out.append(channel) + return out + [f"mask->{c}" for c in self._id_to_channel] + + def continuous_columns(self) -> list[int]: + """Columns MedMod z-scores: header names without ``->`` (line 254).""" + return [i for i, name in enumerate(self.output_header()) if "->" not in name] + + def with_timestep(self, timestep: float) -> Discretizer: + """The same discretizer with another bin width (hours). The column + layout does not depend on it, so the config is not read again.""" + other = copy.copy(self) + other._timestep = _check_timestep(timestep) + return other + + def _write(self, data: np.ndarray, bin_id: int, channel: str, value: str) -> None: + # lines 77-88. `list.index` raises ValueError for a categorical value + # that is not in possible_values, exactly like MedMod. + channel_id = self._channel_to_id[channel] + begin = self._begin_pos[channel_id] + if self._is_categorical_channel[channel]: + values = self._possible_values[channel] + category_id = values.index(value) + data[bin_id, begin : begin + len(values)] = 0.0 + data[bin_id, begin + category_id] = 1.0 + else: + data[bin_id, begin] = float(value) + + def transform( + self, + X: Sequence[Sequence[str]], + header: Sequence[str] | None = None, + end: float | None = None, + ) -> np.ndarray: + """Bin rows ``[Hours, v_1, ..., v_17]`` (strings, '' = missing). + + Returns the (N_bins, 76) float64 array (MedMod returns ``(data, + header)``; use :meth:`output_header` for the names). + """ + header = list(self._header if header is None else header) + assert header[0] == "Hours" # line 37 + n_channels = len(self._id_to_channel) + + ts = [float(row[0]) for row in X] # lines 41-43 + for i in range(len(ts) - 1): + assert ts[i] < ts[i + 1] + EPS + + first_time = 0.0 # start_time='zero', lines 45-50 + + max_hours = (max(ts) if end is None else end) - first_time # lines 52-55 + n_bins = int(max_hours / self._timestep + 1.0 - EPS) # line 57 + + data = np.zeros((n_bins, self._n_data_cols), dtype=float) # line 71 + mask = np.zeros((n_bins, n_channels), dtype=int) # line 72 + original_value = [["" for _ in range(n_channels)] for _ in range(n_bins)] + + # lines 90-109: rows in time order; a later value in the same bin + # overwrites an earlier one and the mask is set to 1. + for row in X: + t = float(row[0]) - first_time + if t > max_hours + EPS: + continue + bin_id = int(t / self._timestep - EPS) + assert 0 <= bin_id < n_bins + for j in range(1, len(row)): + if row[j] == "": + continue + channel = header[j] + channel_id = self._channel_to_id[channel] + mask[bin_id][channel_id] = 1 + self._write(data, bin_id, channel, row[j]) + original_value[bin_id][channel_id] = row[j] + + # impute_strategy='previous', lines 116-131: an unobserved bin takes the + # channel's last observed value, or its normal value before the first. + prev_values: list[list[str]] = [[] for _ in range(n_channels)] + for bin_id in range(n_bins): + for channel in self._id_to_channel: + channel_id = self._channel_to_id[channel] + if mask[bin_id][channel_id] == 1: + prev_values[channel_id].append(original_value[bin_id][channel_id]) + continue + if prev_values[channel_id]: + imputed_value = prev_values[channel_id][-1] + else: + imputed_value = self._normal_values[channel] + self._write(data, bin_id, channel, imputed_value) + + # store_masks=True, lines 152-153 + return np.hstack([data, mask.astype(np.float32)]) + + +class _NumpyOnlyUnpickler(pickle.Unpickler): + """Allows only the globals a pickled ``{'means', 'stds'}`` dict of numpy + arrays needs (checked with ``python -m pickletools`` on the MedMod file: + ``numpy.core.multiarray._reconstruct``, ``numpy.ndarray``, ``numpy.dtype``).""" + + _ALLOWED: ClassVar[frozenset[tuple[str, str]]] = frozenset({ + ("numpy.core.multiarray", "_reconstruct"), + ("numpy._core.multiarray", "_reconstruct"), + ("numpy", "ndarray"), + ("numpy", "dtype"), + ("numpy.core.multiarray", "scalar"), + ("numpy._core.multiarray", "scalar"), + }) + + def find_class(self, module: str, name: str) -> type: + if (module, name) not in self._ALLOWED: + raise pickle.UnpicklingError(f"global {module}.{name} is not allowed") + if module.startswith("numpy.core") and int(np.__version__.split(".")[0]) >= 2: + module = module.replace("numpy.core", "numpy._core", 1) + return super().find_class(module, name) + + +class Normalizer: + """Port of ``Normalizer`` (preprocessing.py:181-232). + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets.medmod.discretizer import Normalizer + >>> norm = Normalizer().fit([np.array([[1.0, 10.0], [3.0, 30.0]])]) + >>> norm.transform(np.array([[2.0, 20.0]])).tolist() + [[0.0, 0.0]] + """ + + def __init__(self, fields: Sequence[int] | None = None): + self._fields = None if fields is None else list(fields) + self._means: np.ndarray | None = None + self._stds: np.ndarray | None = None + + def __repr__(self) -> str: + # Stable across runs (no object address): PyHealth puts str() of + # pre-fitted processors into its cache key (BaseDataset.set_task). + if self._means is None: + state = "unfitted" + else: + digest = hashlib.sha256( + np.ascontiguousarray(self._means).tobytes() + + np.ascontiguousarray(self._stds).tobytes() + ).hexdigest()[:12] + state = f"sha256:{digest}" + n = "all" if self._fields is None else len(self._fields) + return f"Normalizer(fields={n}, {state})" + + def fit(self, arrays: Iterable[np.ndarray]) -> Normalizer: + """Means and stds over every bin of every array, all columns, as + ``_feed_data`` + ``_save_params`` (lines 193-215) compute them; MedMod's + create_normalizer_state.py:87-93 feeds each training stay's discretized, + unnormalized array.""" + count, sum_x, sum_sq_x = 0, None, None + for x in arrays: + x = np.asarray(x, dtype=float) + count += x.shape[0] + if sum_x is None: + sum_x, sum_sq_x = x.sum(axis=0), (x**2).sum(axis=0) + else: + sum_x += x.sum(axis=0) + sum_sq_x += (x**2).sum(axis=0) + if count < 2: + raise ValueError("need at least 2 rows to fit a normalizer") + means = 1.0 / count * sum_x + var = 1.0 / (count - 1) * (sum_sq_x - 2.0 * sum_x * means + count * means**2) + # For a constant column, rounding can make var a tiny negative number; + # MedMod's sqrt then gives NaN and the 1e-7 floor misses it. Clamp at 0 + # so it gets the floor; every other column is unchanged. + stds = np.sqrt(np.maximum(var, 0.0)) + stds[stds < 1e-7] = 1e-7 + self._means, self._stds = means, stds + return self + + def load_params(self, path: str | Path = PH_NORMALIZER) -> Normalizer: + """Loads the means and standard deviations from a MedMod normalizer. + + Only numpy arrays are unpickled. Any other object is refused. + + Args: + path: A MedMod ``.normalizer`` file. The default is the + phenotyping file that MedMod's code loads. + + Returns: + This normalizer, ready to ``transform``. + """ + # line 220: pickle.load(..., encoding='latin1') + with open(path, "rb") as f, warnings.catch_warnings(): + # numpy >= 2.4 warns about the py2-era `align=0` in the pickled dtype. + warnings.simplefilter( + "ignore", + category=getattr(np, "exceptions", np).VisibleDeprecationWarning, + ) + dct = _NumpyOnlyUnpickler(f, encoding="latin1").load() + self._means = np.asarray(dct["means"], dtype=float) + self._stds = np.asarray(dct["stds"], dtype=float) + return self + + @property + def means(self) -> np.ndarray: + """Per-column means (after ``load_params`` or fitting).""" + assert self._means is not None + return self._means + + @property + def stds(self) -> np.ndarray: + """Per-column standard deviations, at least 1e-7.""" + assert self._stds is not None + return self._stds + + def transform(self, X: np.ndarray) -> np.ndarray: + """Standardizes the normalizer's columns of ``X``. + + Args: + X: Binned EHR, shape (time steps, 76). + + Returns: + A copy with the listed (continuous) columns z-scored. + """ + # lines 224-232: only the listed columns are z-scored. + fields = range(X.shape[1]) if self._fields is None else self._fields + ret = 1.0 * X + for col in fields: + ret[:, col] = (X[:, col] - self.means[col]) / self.stds[col] + return ret + + +def medmod_ehr_funcs(timestep: float = 1.0) -> tuple[Discretizer, Normalizer]: + """Equivalent of ``ehr_funcs`` (preprocessing.py:247-269): MedMod's + discretizer and the normalizer its released code loads (``PH_NORMALIZER``). + + Examples: + >>> from pyhealth.datasets.medmod.discretizer import medmod_ehr_funcs + >>> discretizer, normalizer = medmod_ehr_funcs() + >>> len(discretizer.output_header()) + 76 + """ + discretizer = Discretizer(timestep=timestep) + normalizer = Normalizer(fields=discretizer.continuous_columns()) + normalizer.load_params(PH_NORMALIZER) + return discretizer, normalizer diff --git a/pyhealth/datasets/medmod/downloads.py b/pyhealth/datasets/medmod/downloads.py new file mode 100644 index 0000000000..e2fba6f876 --- /dev/null +++ b/pyhealth/datasets/medmod/downloads.py @@ -0,0 +1,111 @@ +"""MedMod's resource files, downloaded from MedMod's GitHub on first use. + +* ``testset_iv.csv`` and ``valset_iv.csv`` define MedMod's train / val / test + split (test list first, then the validation list among the rest). +* ``itemid_to_variable_map.csv`` maps MIMIC item ids to MedMod's 17 EHR + variables. + +They are published in MedMod's repository and, byte-identical, in MedFuse's, so +PyHealth does not ship a copy. The first use downloads each file from a pinned +commit (MedMod first, then MedFuse), checks its SHA-256, and caches it under +``~/.cache/pyhealth/medmod/``; later uses read the cache. To work offline, put +the files in that folder, or pass their paths to ``MedModSplit`` / +``MedModResources.load`` / ``MedModMIMIC4Dataset``. +""" + +from __future__ import annotations + +import hashlib +import logging +import os +import tempfile +import urllib.request +from pathlib import Path + +from pyhealth import BASE_CACHE_PATH + +logger = logging.getLogger(__name__) + +#: Pinned commits: the download can't change under us. +MEDMOD_COMMIT = "7a47c0b909ffbd36370ff69dd023c34f71d9528a" +MEDFUSE_COMMIT = "3f8b54ec555ac9b8e84ebf98c4854aa6fbd0e4fa" +SOURCES: tuple[str, ...] = ( + f"https://raw.githubusercontent.com/nyuad-cai/MedMod/{MEDMOD_COMMIT}", + f"https://raw.githubusercontent.com/nyuad-cai/MedFuse/{MEDFUSE_COMMIT}", +) +#: Path of each file inside both repositories. +REPO_PATHS: dict[str, str] = { + "testset_iv.csv": "mimic4extract/mimic3benchmark/resources/testset_iv.csv", + "valset_iv.csv": "mimic4extract/mimic3models/resources/valset_iv.csv", + "itemid_to_variable_map.csv": ( + "mimic4extract/mimic3benchmark/resources/itemid_to_variable_map.csv" + ), +} +SHA256: dict[str, str] = { + "testset_iv.csv": ( + "9fe512f5feade04158a08eb2ff7aca90476e9d54ab5a45db658abc1dd3ce5b68" + ), + "valset_iv.csv": ( + "563917e13e65ab1974152ecda546a398e30b8f7cea378b51dc7fe4bff41b8594" + ), + "itemid_to_variable_map.csv": ( + "86ca1228eabd4731449740916bad5f7b03e9b8bc84c0648e49bab9e72ba5397e" + ), +} +CACHE_DIR = Path(BASE_CACHE_PATH) / "medmod" + + +def _sha256(data: bytes) -> str: + return hashlib.sha256(data).hexdigest() + + +def medmod_file_path(name: str, cache_dir: str | Path | None = None) -> Path: + """Local path of one of MedMod's resource files, downloaded on first use. + + Args: + name: ``"testset_iv.csv"``, ``"valset_iv.csv"`` or + ``"itemid_to_variable_map.csv"``. + cache_dir: where to keep it (default ``~/.cache/pyhealth/medmod``). + + Returns: + The path of the cached, checksum-verified file. + + Raises: + OSError: if the file is not cached and no source can be downloaded. + + Examples: + >>> from pyhealth.datasets.medmod.downloads import medmod_file_path + >>> medmod_file_path("testset_iv.csv").name # doctest: +SKIP + 'testset_iv.csv' + """ + if name not in REPO_PATHS: + raise ValueError(f"unknown file {name!r}; expected one of {sorted(REPO_PATHS)}") + folder = Path(cache_dir) if cache_dir is not None else CACHE_DIR + path = folder / name + if path.is_file() and _sha256(path.read_bytes()) == SHA256[name]: + return path + errors = [] + for base in SOURCES: + url = f"{base}/{REPO_PATHS[name]}" + try: + logger.info("Downloading %s", url) + with urllib.request.urlopen(url, timeout=60) as response: + data = response.read() + except OSError as error: # URLError and HTTPError are OSErrors + logger.warning("Could not download %s: %s", url, error) + errors.append(f"{url}: {error}") + continue + if _sha256(data) != SHA256[name]: + errors.append(f"{url}: unexpected SHA-256") + continue + folder.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=folder, suffix=".partial") + with os.fdopen(fd, "wb") as f: + f.write(data) + os.replace(tmp, path) # never leaves a half-written file + return path + raise OSError( + f"Could not download MedMod's {name} from any source:\n " + + "\n ".join(errors) + + f"\nDownload it manually into {folder}, or pass its path explicitly." + ) diff --git a/pyhealth/datasets/medmod/extraction.py b/pyhealth/datasets/medmod/extraction.py new file mode 100644 index 0000000000..b50c95fceb --- /dev/null +++ b/pyhealth/datasets/medmod/extraction.py @@ -0,0 +1,1117 @@ +"""MedMod in-hospital-mortality extraction, one subject at a time. + +Pure pandas, no PyHealth import, so every rule can be unit-tested on tiny +synthetic tables. ``pyhealth.tasks.medmod_mortality_mimic4`` adapts a PyHealth +``Patient`` to these inputs. + +References are ``file:line`` in the MedMod repo (github.com/nyuad-cai/MedMod, +commit in ``files/MEDMOD_COMMIT``): + +* ``mimic3csv.py`` = mimic4extract/mimic3benchmark/mimic3csv.py +* ``subject.py`` = mimic4extract/mimic3benchmark/subject.py +* ``bench_prep.py`` = mimic4extract/mimic3benchmark/preprocessing.py +* ``extract_subj.py`` = mimic4extract/mimic3benchmark/scripts/extract_subjects_iv.py +* ``validate.py`` = mimic4extract/mimic3benchmark/scripts/validate_events.py +* ``extract_ep.py`` = mimic4extract/mimic3benchmark/scripts/ + extract_episodes_from_subjects.py +* ``create_ihm.py`` = mimic4extract/mimic3benchmark/scripts/ + create_in_hospital_mortality.py +* ``split_test.py`` = mimic4extract/mimic3benchmark/scripts/split_train_and_test.py +* ``split_val.py`` = mimic4extract/mimic3models/split_train_val.py +* ``datasets.py`` / ``utils.py`` = src/data/datasets.py, src/data/utils.py +* MedFuse ``ehr_dataset.py`` = github.com/nyuad-cai/MedFuse datasets/ehr_dataset.py +""" + +from __future__ import annotations + +import re +from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import pandas as pd + +from .discretizer import Discretizer +from .downloads import MEDMOD_COMMIT, medmod_file_path + +EPS = 1e-6 # create_ihm.py:12 +N_HOURS = 48 # create_ihm.py:12 +# Default bin width in hours: MedMod's released code, --timestep default 1.0 +# (src/parser.py:30), never overridden. (The papers say "every two hours", +# MedMod §3.2.2, MedFuse §4.1.1; the task's ``timestep`` setting changes it.) +DEFAULT_TIMESTEP = 1.0 + +# Strings pandas 1.1.5 (MedMod pins pandas==1.1.5, environment.yml:248) reads +# as NaN: pandas/_libs/parsers.pyx:1354-1373 at tag v1.1.5. Note "None" is NOT +# in this set (it was added in pandas 2.0, parsers.pyx:1382 at v2.0.0), so the +# GCS eye-opening value "None" survives MedMod's read_csv round trips. +PANDAS_115_NA = frozenset( + { + "-1.#IND", + "1.#QNAN", + "1.#IND", + "-1.#QNAN", + "#N/A N/A", + "#N/A", + "N/A", + "n/a", + "NA", + "", + "#NA", + "NULL", + "null", + "NaN", + "-NaN", + "nan", + "-nan", + "", + } +) + +HoursZero = Literal["keep", "drop"] + +# Funnel stages, in the order of the filters. A stay "passes" a +# stage if it survives that filter and every earlier one. +STAGES = ( + "icustays", # all rows of icu/icustays for the subject + "same_careunit", # mimic3csv.py:77-81 + "has_admission_and_patient", # inner merges, extract_subj.py:48-49 + "one_stay_per_admission", # mimic3csv.py:120-125 (extract_subj.py:50) + "age_ge_18", # mimic3csv.py:93-98, 128-131 -> all_stays.csv + "los_ge_48h", # create_ihm.py:34-40 + "event_in_48h", # extract_ep.py:73-76 + create_ihm.py:45-52 + "has_diagnosis", # bench_prep.py:59 + create_ihm.py:28-30 + "ap_cxr_in_48h", # utils.py:269-277 + "cxr_has_chexpert", # utils.py:357-363 + # image_dir/.jpg exists (only checked when image_dir is set) + "resized_image_found", +) + + +# -------------------------------------------------------------------------- +# Resources +# -------------------------------------------------------------------------- + + +def read_itemid_to_variable_map(path: str | Path | None = None) -> pd.DataFrame: + """bench_prep.py:141-156: keep rows with LEVEL2 != '', COUNT > 0, + STATUS == 'ready'. Returns columns ``variable, itemid (int), mimic_label``. + + Without ``path``, MedMod's file is downloaded on first use + (``downloads.medmod_file_path``). + + Examples: + >>> from pyhealth.datasets.medmod.extraction import read_itemid_to_variable_map + >>> var_map = read_itemid_to_variable_map() # doctest: +SKIP + >>> list(var_map.columns), var_map["variable"].nunique() # doctest: +SKIP + (['variable', 'itemid', 'mimic_label'], 17) + """ + if path is None: + path = medmod_file_path("itemid_to_variable_map.csv") + var_map = pd.read_csv(path).fillna("").astype(str) + var_map["COUNT"] = var_map["COUNT"].astype(int) + var_map = var_map[(var_map["LEVEL2"] != "") & (var_map["COUNT"] > 0)] + var_map = var_map[var_map["STATUS"] == "ready"] + var_map["ITEMID"] = var_map["ITEMID"].astype(int) + var_map = var_map[["LEVEL2", "ITEMID", "MIMIC LABEL"]] + var_map = var_map.rename( + columns={"LEVEL2": "variable", "ITEMID": "itemid", "MIMIC LABEL": "mimic_label"} + ) + return var_map.reset_index(drop=True) + + +def split_of(subject_id: str, test_subjects: set[str], val_subjects: set[str]) -> str: + """MedMod's split of a subject: test list first, then the val list among + the rest, else train (split_test.py:33-34, split_val.py:27-28). + + Examples: + >>> from pyhealth.datasets.medmod.extraction import split_of + >>> split_of("101", test_subjects={"101"}, val_subjects={"101"}) + 'test' + >>> split_of("102", test_subjects=set(), val_subjects=set()) + 'train' + """ + if subject_id in test_subjects: + return "test" + if subject_id in val_subjects: + return "val" + return "train" + + +def read_split_file(path: str | Path) -> set[str]: + """split_test.py:25-29 / split_val.py:15-19: lines ``subject_id,flag``; + subjects with ``int(flag) == 1`` are in the set (compared as strings). + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.extraction import read_split_file + >>> path = os.path.join(tempfile.mkdtemp(), "testset.csv") + >>> _ = open(path, "w").write("101,1\\n102,0\\n") + >>> read_split_file(path) + {'101'} + """ + out: set[str] = set() + with open(path) as f: + for line in f: + x, y = line.split(",") + if int(y) == 1: + out.add(x) + return out + + +def _source_name(path: str | Path) -> str: + """A file given by the user, by its absolute path.""" + return str(Path(path).resolve()) + + +@dataclass +class MedModResources: + """MedMod's files: item map, split lists, discretizer config. + + The discretizer is MedMod's (previous-value imputation, masks, start at + intime; preprocessing.py:247-252); ``process_subject`` sets the bin width. + Standardizing is not done here but by ``MedModEHRProcessor`` + (medmod_ehr_processor.py): a MedMod normalizer file, or fitted on the + train split. + + The item map and the split lists are read on first use (``var_map``, + ``test_subjects``, ``val_subjects``); by default they are MedMod's, + downloaded from MedMod's GitHub on first use + (``downloads.medmod_file_path``), so building a task, its schema or + synthetic samples needs no network. + + ``repr`` shows only the source paths (``sources``), so it is short and the + same in every run. PyHealth puts ``str()`` of each task attribute into the + task's cache key (``BaseDataset._task_cache_dir``), so this matters. + + Examples: + >>> from pyhealth.datasets.medmod.extraction import MedModResources + >>> res = MedModResources.load() # no download until a file is used + >>> res.sources["itemid_map"], len(res.discretizer.channels) + ('medmod@7a47c0b:itemid_to_variable_map.csv', 17) + """ + + sources: dict[str, str] + discretizer: Discretizer = field(repr=False) + itemid_map: Path | None = field(default=None, repr=False) + testset: Path | None = field(default=None, repr=False) + valset: Path | None = field(default=None, repr=False) + _test_subjects: set[str] | None = field(default=None, repr=False) + _val_subjects: set[str] | None = field(default=None, repr=False) + _var_map: pd.DataFrame | None = field(default=None, repr=False) + + @classmethod + def load( + cls, + itemid_map: str | Path | None = None, + testset: str | Path | None = None, + valset: str | Path | None = None, + ) -> MedModResources: + """Defaults: MedMod's item map and split lists (downloaded on first + use). Pass ``itemid_map`` / ``testset`` / ``valset`` to use other + files.""" + sources = { + "itemid_map": ( + f"medmod@{MEDMOD_COMMIT[:7]}:itemid_to_variable_map.csv" + if itemid_map is None + else _source_name(itemid_map) + ), + "testset": ( + f"medmod@{MEDMOD_COMMIT[:7]}:testset_iv.csv" + if testset is None + else _source_name(testset) + ), + "valset": ( + f"medmod@{MEDMOD_COMMIT[:7]}:valset_iv.csv" + if valset is None + else _source_name(valset) + ), + } + return cls( + sources=sources, + discretizer=Discretizer(), + itemid_map=None if itemid_map is None else Path(itemid_map), + testset=None if testset is None else Path(testset), + valset=None if valset is None else Path(valset), + ) + + @property + def test_subjects(self) -> set[str]: + """Subjects on MedMod's test list (read, or downloaded, on first use).""" + if self._test_subjects is None: + path = self.testset or medmod_file_path("testset_iv.csv") + self._test_subjects = read_split_file(path) + return self._test_subjects + + @test_subjects.setter + def test_subjects(self, subjects: set[str]) -> None: + self._test_subjects = set(subjects) + + @property + def val_subjects(self) -> set[str]: + """Subjects on MedMod's validation list (read, or downloaded, on first use).""" + if self._val_subjects is None: + path = self.valset or medmod_file_path("valset_iv.csv") + self._val_subjects = read_split_file(path) + return self._val_subjects + + @val_subjects.setter + def val_subjects(self, subjects: set[str]) -> None: + self._val_subjects = set(subjects) + + @property + def var_map(self) -> pd.DataFrame: + """MedMod's item map, ready rows only (read, or downloaded, on first use).""" + if self._var_map is None: + self._var_map = read_itemid_to_variable_map(self.itemid_map) + return self._var_map + + @property + def itemids(self) -> set[int]: + """The MIMIC-IV item ids mapped to MedMod's 17 variables.""" + return {int(i) for i in self.var_map["itemid"]} + + +# -------------------------------------------------------------------------- +# Value cleaning, bench_prep.py:193-335 (applied per variable, in clean_fns order) +# -------------------------------------------------------------------------- + +_NUM_RE = r"^(\d+(\.\d*)?|\.\d+)$" + + +def clean_sbp(df: pd.DataFrame) -> pd.Series: # bench_prep.py:194-198 + """Systolic blood pressure: the first number of ``120/80``. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_sbp + >>> clean_sbp(pd.DataFrame({"value": ["120/80", "110"]})).tolist() + [120.0, 110.0] + """ + v = df.value.astype(str).copy() + idx = v.apply(lambda s: "/" in s) + v.loc[idx] = v[idx].apply(lambda s: re.match(r"^(\d+)/(\d+)$", s).group(1)) + return v.astype(float) + + +def clean_dbp(df: pd.DataFrame) -> pd.Series: # bench_prep.py:201-205 + """Diastolic blood pressure: the second number of ``120/80``. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_dbp + >>> clean_dbp(pd.DataFrame({"value": ["120/80", "70"]})).tolist() + [80.0, 70.0] + """ + v = df.value.astype(str).copy() + idx = v.apply(lambda s: "/" in s) + v.loc[idx] = v[idx].apply(lambda s: re.match(r"^(\d+)/(\d+)$", s).group(2)) + return v.astype(float) + + +def clean_crr(df: pd.DataFrame) -> pd.Series: # bench_prep.py:209-219 + """Capillary refill rate: normal/brisk -> 0, abnormal/delayed -> 1. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_crr + >>> clean_crr(pd.DataFrame({"value": ["Brisk", "Delayed", "other"]})).tolist() + [0.0, 1.0, nan] + """ + v = pd.Series(np.nan, index=df.index, dtype=float) + s = df.value.astype(str) + v.loc[(s == "Normal <3 secs") | (s == "Brisk")] = 0 + v.loc[(s == "Abnormal >3 secs") | (s == "Delayed")] = 1 + return v + + +def clean_fio2(df: pd.DataFrame) -> pd.Series: # bench_prep.py:223-244 + """Fraction inspired oxygen: divided by 100 (see the comment). + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_fio2 + >>> clean_fio2(pd.DataFrame({"value": ["40"], "valuenum": ["40"]})).tolist() + [0.4] + """ + v = df.value.astype(float).copy() + # Line 240 builds `is_str` with np.array(map(...), dtype=np.bool). Under + # Python 3 a map object is not a sequence, so numpy makes a 0-d array whose + # value is bool(map_object) == True; `is_str | (...)` is then True for every + # row. `valuenum` holds the numeric valuenum as a string for chartevents and + # labevents (mimic3csv.py:220, subject.py:34), so 'torr' is never in it. + # Net effect: every FiO2 value is divided by 100. (The ph normalizer's FiO2 + # mean, 0.294, is consistent with this.) + is_str = True + idx = ( + df.valuenum.fillna("").astype(str).apply(lambda s: "torr" not in s.lower()) + & is_str + ) + v.loc[idx] = v[idx] / 100.0 + return v + + +def clean_lab(df: pd.DataFrame) -> pd.Series: # bench_prep.py:248-252 + """Glucose and pH: non-numeric strings become NaN. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_lab + >>> clean_lab(pd.DataFrame({"value": ["7.4", "ERROR"]})).tolist() + [7.4, nan] + """ + v = df.value.copy() + idx = v.apply(lambda s: type(s) is str and not re.match(_NUM_RE, s)) + v.loc[idx] = np.nan + return v.astype(float) + + +def clean_o2sat(df: pd.DataFrame) -> pd.Series: # bench_prep.py:256-265 + """Oxygen saturation: fractions (<= 1) become percentages. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_o2sat + >>> clean_o2sat(pd.DataFrame({"value": ["0.95", "98"]})).tolist() + [95.0, 98.0] + """ + v = df.value.copy() + idx = v.apply(lambda s: type(s) is str and not re.match(_NUM_RE, s)) + v.loc[idx] = np.nan + v = v.astype(float) + idx = v <= 1 + v.loc[idx] = v[idx] * 100.0 + return v + + +def clean_temperature(df: pd.DataFrame) -> pd.Series: # bench_prep.py:269-273 + """Temperature: values >= 79 are Fahrenheit, converted to Celsius. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_temperature + >>> df = pd.DataFrame( + ... {"value": ["212", "37.5"], "valuenum": ["", ""], + ... "mimic_label": ["", ""]} + ... ) + >>> clean_temperature(df).tolist() + [100.0, 37.5] + """ + v = df.value.astype(float).copy() + # Faithful to MedMod: `'F' in s.lower()` can never be True, so only the + # `v >= 79` rule converts Fahrenheit to Celsius. + idx = ( + df.valuenum.fillna("").astype(str).apply(lambda s: "F" in s.lower()) + | df.mimic_label.apply(lambda s: "F" in s.lower()) + | (v >= 79) + ) + v.loc[idx] = (v[idx] - 32) * 5.0 / 9 + return v + + +def clean_weight(df: pd.DataFrame) -> pd.Series: # bench_prep.py:278-286 + """Weight: ounces and pounds converted to kg. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_weight + >>> df = pd.DataFrame( + ... {"value": ["70", "10"], "valuenum": ["", ""], + ... "mimic_label": ["Daily Weight", "Weight (lb)"]} + ... ) + >>> [round(v, 2) for v in clean_weight(df)] + [70.0, 4.54] + """ + v = df.value.astype(float).copy() + idx = df.valuenum.fillna("").astype(str).apply( + lambda s: "oz" in s.lower() + ) | df.mimic_label.apply(lambda s: "oz" in s.lower()) + v.loc[idx] = v[idx] / 16.0 + idx = ( + idx + | df.valuenum.fillna("").astype(str).apply(lambda s: "lb" in s.lower()) + | df.mimic_label.apply(lambda s: "lb" in s.lower()) + ) + v.loc[idx] = v[idx] * 0.453592 + return v + + +def clean_height(df: pd.DataFrame) -> pd.Series: # bench_prep.py:291-295 + """Height: inches converted to cm, rounded. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_height + >>> df = pd.DataFrame( + ... {"value": ["70", "180"], "valuenum": ["", ""], + ... "mimic_label": ["Height (in)", "Height (cm)"]} + ... ) + >>> clean_height(df).tolist() + [178.0, 180.0] + """ + v = df.value.astype(float).copy() + # Faithful: itemid 226707 ("Height", unit Inch) is NOT converted because + # neither its label nor valuenum contains "in". + idx = df.valuenum.fillna("").astype(str).apply( + lambda s: "in" in s.lower() + ) | df.mimic_label.apply(lambda s: "in" in s.lower()) + v.loc[idx] = np.round(v[idx] * 2.54) + return v + + +CLEAN_FNS = { # bench_prep.py:308-319 (same order) + "Capillary refill rate": clean_crr, + "Diastolic blood pressure": clean_dbp, + "Systolic blood pressure": clean_sbp, + "Fraction inspired oxygen": clean_fio2, + "Oxygen saturation": clean_o2sat, + "Glucose": clean_lab, + "pH": clean_lab, + "Temperature": clean_temperature, + "Weight": clean_weight, + "Height": clean_height, +} + + +def clean_events(events: pd.DataFrame) -> pd.DataFrame: + """bench_prep.py:322-335. MedMod calls exit() if a cleaner raises; here + the exception propagates. Rows whose cleaned value is NaN are dropped. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import clean_events + >>> ev = pd.DataFrame({ + ... "variable": ["Systolic blood pressure", "Glucose"], + ... "value": ["120/80", "ERROR"], + ... "valuenum": ["", ""], + ... "mimic_label": ["", ""], + ... }) + >>> clean_events(ev)["value"].tolist() + [120.0] + """ + events = events.copy() + events["value"] = events["value"].astype(object) + for var_name, fn in CLEAN_FNS.items(): + idx = events["variable"] == var_name + if idx.any(): + events.loc[idx, "value"] = fn(events[idx]).astype(object) + return events.loc[events["value"].notnull()] + + +# -------------------------------------------------------------------------- +# Inputs / outputs +# -------------------------------------------------------------------------- + + +@dataclass +class SubjectTables: + """One subject's rows. ID and value columns are raw strings (as PyHealth + stores them); timestamp columns are pandas datetimes. + + * patients: anchor_age, dod (0 or 1 row) + * admissions: hadm_id, admittime, dischtime, deathtime + * icustays: stay_id, hadm_id, first_careunit, last_careunit, intime, outtime, los + * events: charttime, hadm_id, stay_id (NA for labevents), itemid, value, + valuenum + * diagnoses: hadm_id (diagnoses_icd rows that matched d_icd_diagnoses) + * cxr: studydatetime, dicom_id, study_id, viewposition, image_path + * chexpert_study_ids: study_ids with a row in mimic-cxr-2.0.0-chexpert + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import ( + ... MedModResources, SubjectTables, process_subject, + ... ) + >>> e = pd.DataFrame() + >>> st = SubjectTables("101", e, e, e, e, e, e) # a subject with no rows + >>> process_subject(st, MedModResources.load()) + [] + """ + + subject_id: str + patients: pd.DataFrame + admissions: pd.DataFrame + icustays: pd.DataFrame + events: pd.DataFrame + diagnoses: pd.DataFrame + cxr: pd.DataFrame + chexpert_study_ids: set[str] = field(default_factory=set) + + +@dataclass +class StayResult: + """One ICU stay in ``process_subject``: the last stage it passed + and, for kept stays, the sample's fields (``sample()``). + + Examples: + >>> from pyhealth.datasets.medmod.extraction import StayResult + >>> r = StayResult(subject_id="101", stay_id="201", hadm_id="301", passed=0) + >>> r.kept + False + """ + subject_id: str + stay_id: str + hadm_id: str | None + passed: int # index into STAGES of the last stage this stay survived + label: int | None = None + split: str | None = None + image_path: str | None = None + dicom_id: str | None = None + original_image_path: str | None = ( + None # files/p../p../s../.jpg, set even if image_dir lacks it + ) + ehr: np.ndarray | None = None + used_dummy_rows: bool = False # MedMod empty-window fallback fired + + @property + def kept(self) -> bool: + """Whether the stay passed every cohort stage (is in the cohort).""" + return self.passed == len(STAGES) - 1 + + def sample(self) -> dict: + """Returns the stay as a PyHealth sample. + + Returns: + A dict with ``patient_id``, ``visit_id``, ``ehr``, ``image_path``, + ``label`` and ``split``. Use it only for a stay in the cohort. + """ + return { + "patient_id": self.subject_id, + "visit_id": self.stay_id, + "ehr": self.ehr, + "image_path": self.image_path, + "label": int(self.label), + "split": self.split, + } + + +# -------------------------------------------------------------------------- +# Helpers +# -------------------------------------------------------------------------- + + +def _to_num(s: pd.Series) -> pd.Series: + return pd.to_numeric(s.where(~s.astype(str).isin(PANDAS_115_NA)), errors="coerce") + + +def _id_str(x: Any) -> str: + return str(int(x)) + + +def _pandas_like_values(values: pd.Series) -> pd.Series: + """Mimic pandas' per-file dtype inference in subject.py:28 (read_events): + if every non-null value parses as a number the column is float, otherwise + every value stays a string. Only matters for the same-timestamp tie-break + in convert_events_to_timeseries and for clean_lab's string check. + Approximation: MedMod infers over the subject's whole events.csv (all + itemids in the full item map); this uses the 17-variable events only.""" + try: + return values.astype(float).astype(object) + except (TypeError, ValueError): + return values.astype(str).astype(object) + + +def in_hospital_mortality( + admittime: pd.Timestamp, + dischtime: pd.Timestamp, + deathtime: pd.Timestamp | None, + dod: pd.Timestamp | None, +) -> int: + """mimic3csv.py:101-108. dod or deathtime within [admittime, dischtime]. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import in_hospital_mortality + >>> t = pd.Timestamp + >>> admit, disch, death = t("2150-01-01"), t("2150-01-10"), t("2150-01-05") + >>> in_hospital_mortality(admit, disch, death, pd.NaT) + 1 + """ + + def within(t: pd.Timestamp | None) -> bool: + return pd.notnull(t) and admittime <= t <= dischtime + + return int(within(dod) or within(deathtime)) + + +# -------------------------------------------------------------------------- +# Time series (subject.py:56-68, extract_ep.py:53-89) +# -------------------------------------------------------------------------- + + +def cleaned_subject_events(events: pd.DataFrame, var_map: pd.DataFrame) -> pd.DataFrame: + """Validated raw events -> mapped to variables, typed like pandas, cleaned. + One row per raw event (before the per-charttime pick). + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import ( + ... cleaned_subject_events, read_itemid_to_variable_map, + ... ) + >>> ev = pd.DataFrame({"charttime": [pd.Timestamp("2150-01-01 01:00")], + ... "stay_id": [201], "itemid": [220045], # Heart Rate + ... "value": ["80"], "valuenum": ["80"]}) + >>> out = cleaned_subject_events(ev, read_itemid_to_variable_map()) + >>> out[["variable", "value"]].values.tolist() + [['Heart Rate', 80.0]] + """ + ev = events.merge(var_map, on="itemid") # bench_prep.py:159-164 (inner) + if ev.empty: + return ev + ev = ev.copy() + ev["value"] = _pandas_like_values(ev["value"]) + return clean_events(ev) # extract_ep.py:55 + + +def subject_timeseries(events: pd.DataFrame, var_map: pd.DataFrame) -> pd.DataFrame: + """Validated raw events -> one row per charttime. + + Returns columns ``charttime``, ``stay_ids`` (set of stay_ids of the events + at that time) and one column per variable (object; NaN = missing). + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import ( + ... read_itemid_to_variable_map, subject_timeseries, + ... ) + >>> ev = pd.DataFrame({"charttime": [pd.Timestamp("2150-01-01 01:00")], + ... "stay_id": [201], "itemid": [220045], # Heart Rate + ... "value": ["80"], "valuenum": ["80"]}) + >>> ts = subject_timeseries(ev, read_itemid_to_variable_map()) + >>> float(ts.loc[0, "Heart Rate"]), ts.loc[0, "stay_ids"] + (80.0, {201}) + """ + ev = cleaned_subject_events(events, var_map) + if ev.empty: # extract_ep.py:57-59 + return pd.DataFrame(columns=["charttime", "stay_ids"]) + + # subject.py:59-61: sort by (charttime, variable, value) and keep the LAST + # row per (charttime, variable), i.e. the largest value. Each variable's + # values share one type (float if cleaned / numeric file, else str). + picked = ev.groupby(["charttime", "variable"], sort=True)["value"].agg( + lambda s: sorted(s.tolist())[-1] # noqa: FURB192 (MedMod's sort, keep last) + ) + wide = picked.unstack("variable") + stays_at = ev.groupby("charttime")["stay_id"].agg(lambda s: {int(x) for x in s}) + return wide.join(stays_at.rename("stay_ids")).sort_index().reset_index() + + +def _fmt(v: Any) -> str: + """Value as it would appear in MedMod's episode CSV ('' = missing).""" + if v is None or (isinstance(v, float) and np.isnan(v)): + return "" + return str(v) # floats: str(float) == repr in Python 3, as pandas.to_csv writes + + +def stay_rows( + ts: pd.DataFrame, + stay_id: int, + intime: pd.Timestamp, + outtime: pd.Timestamp, + channels: Sequence[str], +) -> list[list]: + """Rows of one stay, ``[hours(float), v_1(str), ..., v_17(str)]``, sorted. + + subject.py:39-45: a row belongs to the stay if one of its events has that + stay_id OR its charttime is within [intime, outtime]. + subject.py:48-53: Hours = (charttime - intime) in hours. + Columns follow extract_ep.py:85-87 (alphabetical), which equals the + discretizer config order. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.discretizer import Discretizer + >>> from pyhealth.datasets.medmod.extraction import stay_rows + >>> ts = pd.DataFrame({"charttime": [pd.Timestamp("2150-01-01 01:30")], + ... "stay_ids": [{201}], "Heart Rate": [80.0]}) + >>> channels = Discretizer().channels + >>> intime, outtime = pd.Timestamp("2150-01-01"), pd.Timestamp("2150-01-03") + >>> rows = stay_rows(ts, 201, intime, outtime, channels) + >>> rows[0][0], rows[0][1 + channels.index("Heart Rate")] + (1.5, '80.0') + """ + if ts.empty: + return [] + sel = ts["stay_ids"].apply(lambda s: stay_id in s) | ( + (ts["charttime"] >= intime) & (ts["charttime"] <= outtime) + ) + sub = ts[sel] + out = [] + for _, r in sub.iterrows(): + hours = (r["charttime"] - intime).total_seconds() / 60.0 / 60 + out.append([hours] + [_fmt(r[c]) if c in sub.columns else "" for c in channels]) + out.sort(key=lambda x: x[0]) + return out + + +def ihm_window(rows: list[list]) -> list[list]: + """create_ihm.py:47-48: keep -eps < t < 48 + eps. + + Examples: + >>> from pyhealth.datasets.medmod.extraction import ihm_window + >>> ihm_window([[-1.0, "a"], [0.0, "b"], [47.5, "c"], [60.0, "d"]]) + [[0.0, 'b'], [47.5, 'c']] + """ + return [r for r in rows if -EPS < r[0] < N_HOURS + EPS] + + +# MedMod's fallback when the loader window is empty, datasets.py:156-163 +# (columns: Hours + 17 channels; '109' = Heart Rate, '30' = Respiratory rate...). +MEDMOD_DUMMY_ROWS = [ + [ + "0.11666666666666667", + "", + "", + "", + "", + "", + "", + "", + "", + "109", + "", + "", + "", + "30", + "", + "", + "", + "", + ], + [ + "0.16666666666666666", + "", + "61.0", + "", + "", + "", + "", + "", + "", + "109", + "", + "64", + "97.0", + "29", + "74.0", + "", + "", + "", + ], +] + + +def loader_rows( + rows: list[list], hours_zero: HoursZero, full_stay_hours: float +) -> tuple[list[list], bool]: + """Rows the training loader feeds to the discretizer. + + * ``keep`` (MedFuse, datasets/ehr_dataset.py:47-60): every row of the IHM + file, i.e. -eps < t < 48 + eps, Hours == 0 included. + * ``drop`` (MedMod, datasets.py:137-163 with lower=0 and + upper=full_stay_time from get_recent_cxr, utils.py:195-196, 208-209): + keep 0 < t < upper. Because the IHM file already stops at 48 + eps and + upper >= 48 for every LOS >= 48 h stay, this is 0 < t <= 48 in practice; + a row at exactly t == upper is dropped. If nothing is left, MedMod + substitutes hard-coded dummy rows; the second return value flags that. + + Examples: + >>> from pyhealth.datasets.medmod.extraction import loader_rows + >>> rows = [[0.0, "80"], [1.5, "82"]] + >>> loader_rows(rows, "keep", full_stay_hours=72.0) + ([['0.0', '80'], ['1.5', '82']], False) + >>> loader_rows(rows, "drop", full_stay_hours=72.0) + ([['1.5', '82']], False) + """ + if hours_zero == "keep": + return [[repr(float(r[0]))] + list(r[1:]) for r in rows], False + if hours_zero != "drop": + raise ValueError(f"hours_zero must be 'keep' or 'drop', got {hours_zero!r}") + lower, upper = 0.0, full_stay_hours + kept = [] + for r in rows: + t = float(r[0]) + if t < lower: + continue + elif (t > lower) and (t < upper): + kept.append([repr(t)] + list(r[1:])) + elif t > upper: + break + if not kept: + return [list(r) for r in MEDMOD_DUMMY_ROWS], True + return kept, False + + +def build_ehr(rows: list[list], discretizer: Discretizer) -> np.ndarray: + """datasets.py:196-201: discretize with end = period_length = 48 (the IHM + listfile writes period_length 0, create_ihm.py:72). Returns the + unnormalized float64 array, (48 / timestep) x 76. Standardizing (line + 202-203) is ``MedModEHRProcessor``'s job, so its statistics can come from + the train split. + + Examples: + >>> from pyhealth.datasets.medmod.discretizer import Discretizer + >>> from pyhealth.datasets.medmod.extraction import build_ehr + >>> disc = Discretizer() + >>> row = ["1.5"] + [""] * len(disc.channels) + >>> row[1 + disc.channels.index("Heart Rate")] = "80" + >>> build_ehr([row], disc).shape + (48, 76) + """ + return discretizer.transform(rows, end=float(N_HOURS)) + + +# -------------------------------------------------------------------------- +# Main per-subject routine +# -------------------------------------------------------------------------- + + +def resolve_image_path( + pyhealth_path: str, dicom_id: str, image_dir: str | Path | None +) -> str | None: + """Without ``image_dir``: PyHealth's original path (files/p../p../s../.jpg, + not checked on disk). With ``image_dir``: ``image_dir/.jpg``, the flat + layout of MedFuse resize.py:29, 37; None if that file does not exist. + + Examples: + >>> import tempfile + >>> from pyhealth.datasets.medmod.extraction import resolve_image_path + >>> resolve_image_path("files/p12/p123/s456/abc.jpg", "abc", None) + 'files/p12/p123/s456/abc.jpg' + >>> resolve_image_path("files/p12/p123/s456/abc.jpg", "abc", tempfile.mkdtemp()) + """ + if image_dir is None: + return pyhealth_path + p = Path(image_dir) / f"{dicom_id}.jpg" + return str(p) if p.is_file() else None + + +def validated_events( + st: SubjectTables, all_stays: pd.DataFrame, res: MedModResources +) -> pd.DataFrame: + """validate_events.py logic (validate.py:54-80) on the subject's raw events. + ``all_stays`` needs columns ``stay_int`` and ``hadm_int``. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import ( + ... MedModResources, SubjectTables, validated_events, + ... ) + >>> events = pd.DataFrame({"charttime": [pd.Timestamp("2150-01-01 01:00")], + ... "hadm_id": ["301"], "stay_id": ["201"], + ... "itemid": ["220045"], "value": ["80"], + ... "valuenum": ["80"]}) + >>> e = pd.DataFrame() + >>> st = SubjectTables("101", e, e, e, events, e, e) + >>> all_stays = pd.DataFrame({"stay_int": [201], "hadm_int": [301]}) + >>> out = validated_events(st, all_stays, MedModResources.load()) + >>> out[["stay_id", "itemid", "value"]].values.tolist() + [[201, 220045, '80']] + """ + ev = st.events.copy() + for col in ("stay_id", "valuenum"): + if col not in ev.columns: + ev[col] = pd.NA + if ev.empty: + return ev + ev["itemid"] = _to_num(ev["itemid"]) + ev = ev[ev["itemid"].isin(res.itemids)] # extract_subj.py:91-96 (superset filter) + ev["itemid"] = ev["itemid"].astype(int) + # subject.py:30: drop null values (pandas 1.1.5 NA strings) + ev = ev[ev["value"].notna() & ~ev["value"].astype(str).isin(PANDAS_115_NA)] + ev["hadm_num"] = _to_num(ev["hadm_id"]) + ev = ev[ev["hadm_num"].notna()] # validate.py:56-57 + hadm_to_stay = dict(zip(all_stays["hadm_int"], all_stays["stay_int"])) + ev = ev[ev["hadm_num"].isin(hadm_to_stay.keys())] # validate.py:59-65 + stay_r = ev["hadm_num"].map(hadm_to_stay) + stay_ev = _to_num(ev["stay_id"]).fillna( + stay_r + ) # validate.py:71 (labevents get the admission's stay) + same = stay_ev == stay_r # validate.py:79-80 + ev = ev[same].assign(stay_id=stay_r[same].astype(int)) + return ev[["charttime", "stay_id", "itemid", "value", "valuenum"]] + + +def process_subject( + st: SubjectTables, + res: MedModResources, + hours_zero: HoursZero = "keep", + image_dir: str | Path | None = None, + timestep: float = DEFAULT_TIMESTEP, +) -> list[StayResult]: + """Every ICU stay of one subject with the last stage it survived; kept + stays carry the unnormalized ``ehr`` at ``timestep``-hour bins. + + Examples: + >>> import pandas as pd + >>> from pyhealth.datasets.medmod.extraction import ( + ... MedModResources, SubjectTables, process_subject, + ... ) + >>> e = pd.DataFrame() + >>> st = SubjectTables("101", e, e, e, e, e, e) # a subject with no rows + >>> process_subject(st, MedModResources.load()) + [] + >>> # In the task: process_subject(task.subject_tables(patient), task.resources) + """ + disc = res.discretizer.with_timestep(timestep) + sid = st.subject_id + stays = st.icustays.copy() + if stays.empty: + return [] + results: dict[int, StayResult] = {} + for _, s in stays.iterrows(): + results[int(s["stay_id"])] = StayResult( + sid, _id_str(s["stay_id"]), _id_str(s["hadm_id"]), passed=0 + ) + + def bump(stay_ids: Iterable[Any], stage: str) -> None: + k = STAGES.index(stage) + for x in stay_ids: + results[int(x)].passed = k + + # 1. first_careunit == last_careunit (mimic3csv.py:79) + stays = stays[stays["first_careunit"] == stays["last_careunit"]] + bump(stays["stay_id"], "same_careunit") + + # Label for every stay that has an admission row (used for funnel death + # rates before the admissions merge; mimic3csv.py:101-108). + adm = st.admissions.copy() + adm["hadm_int"] = _to_num(adm["hadm_id"]) + adm = adm.drop_duplicates("hadm_int").set_index("hadm_int") + dod = pd.NaT + if ( + not st.patients.empty + and "dod" in st.patients + and pd.notnull(st.patients["dod"].iloc[0]) + ): + dod = pd.to_datetime(st.patients["dod"].iloc[0]) + for r in results.values(): + h = int(r.hadm_id) + if h in adm.index: + a = adm.loc[h] + r.label = in_hospital_mortality( + pd.to_datetime(a["admittime"]), + pd.to_datetime(a["dischtime"]), + pd.to_datetime(a["deathtime"]), + dod, + ) + + # 2. inner merges with admissions (subject, hadm) and patients (subject) + # (extract_subj.py:48-49) + if st.patients.empty: + stays = stays.iloc[0:0] + stays = stays[_to_num(stays["hadm_id"]).isin(adm.index)] + bump(stays["stay_id"], "has_admission_and_patient") + + # 3. exactly one remaining ICU stay per admission (mimic3csv.py:120-125). + # Counted AFTER the transfer filter, so an admission whose other stay + # was a transfer still qualifies. + counts = stays.groupby("hadm_id")["stay_id"].transform("count") + stays = stays[counts == 1] + bump(stays["stay_id"], "one_stay_per_admission") + + # 4. age = anchor_age (negative -> 90), keep >= 18 (mimic3csv.py:93-98, 128-131) + if not stays.empty: + age = float(_to_num(st.patients["anchor_age"]).iloc[0]) + age = 90.0 if age < 0 else age + if not age >= 18: + stays = stays.iloc[0:0] + bump(stays["stay_id"], "age_ge_18") + all_stays = stays.copy() # == this subject's rows of root/all_stays.csv + if all_stays.empty: + return list(results.values()) + all_stays["stay_int"] = _to_num(all_stays["stay_id"]).astype(int) + all_stays["hadm_int"] = _to_num(all_stays["hadm_id"]).astype(int) + + ev = validated_events(st, all_stays, res) + ts = ( + subject_timeseries(ev, res.var_map) + if not ev.empty + else pd.DataFrame(columns=["charttime", "stay_ids"]) + ) + + channels = res.discretizer.channels + diag_hadms = ( + set(_to_num(st.diagnoses["hadm_id"]).dropna().astype(int)) + if not st.diagnoses.empty + else set() + ) + + cxr = st.cxr.copy() + if not cxr.empty: + cxr = cxr[cxr["viewposition"] == "AP"] # utils.py:274 + + for _, s in all_stays.iterrows(): + r = results[int(s["stay_int"])] + intime, outtime = s["intime"], s["outtime"] + + # 5. LOS >= 48 h from icustays.los (days): create_ihm.py:34-40 + los = float(_to_num(pd.Series([s["los"]])).iloc[0]) + if pd.isnull(los) or 24.0 * los < N_HOURS - EPS: + continue + r.passed = STAGES.index("los_ge_48h") + + # 6. at least one time-series row with -eps < t < 48 + eps + rows = ihm_window(stay_rows(ts, int(s["stay_int"]), intime, outtime, channels)) + if not rows: + continue + r.passed = STAGES.index("event_in_48h") + + # 7. at least one diagnosis for the admission (inner merge in + # assemble_episodic_data, bench_prep.py:59, leaves an empty episode + # file that create_ihm.py:28-30 skips). + if int(s["hadm_int"]) not in diag_hadms: + continue + r.passed = STAGES.index("has_diagnosis") + + r.split = split_of(sid, res.test_subjects, res.val_subjects) + + # 8. latest AP CXR with intime <= StudyDateTime <= intime + 48 h + # (utils.py:269-277, get_recent_cxr utils.py:200-211). + # Ties at the same StudyDateTime: MedMod sorts with pandas' default + # quicksort and takes tail(1). Under its pinned numpy 1.19 that sort + # is stable for small groups, so the LAST tied row in metadata-file + # order wins (the merge in utils.py:184 keeps the metadata order). + # mimic-cxr-2.0.0-metadata.csv is sorted by (subject_id, study_id, + # dicom_id) (checked on the real file, 2026-11-09), so for one + # subject that is the largest (StudyDateTime, study_id, dicom_id). + # Computed from the row itself, never from PyHealth's event order: + # PyHealth 2.1.0 sorts a patient's events by timestamp only, so its + # order of tied images is arbitrary (pyhealth/data/data.py). + if cxr.empty: + continue + end = intime + pd.DateOffset(hours=N_HOURS) + win = cxr[(cxr["studydatetime"] >= intime) & (cxr["studydatetime"] <= end)] + if win.empty: + continue + r.passed = STAGES.index("ap_cxr_in_48h") + win = win.assign( + _study=_to_num(win["study_id"].astype(str)), + _dicom=win["dicom_id"].astype(str), + ) + latest = win.sort_values( + ["studydatetime", "_study", "_dicom"], kind="mergesort" + ).iloc[-1] + + # 9. its study must have a CheXpert row (utils.py:357-363) + if str(latest["study_id"]) not in st.chexpert_study_ids: + continue + r.passed = STAGES.index("cxr_has_chexpert") + r.dicom_id = str(latest["dicom_id"]) + r.original_image_path = latest["image_path"] + + # 10. optional: the resized copy must exist (no fallback to another image) + r.image_path = resolve_image_path(latest["image_path"], r.dicom_id, image_dir) + if r.image_path is None: + continue + r.passed = STAGES.index("resized_image_found") + + full_stay_hours = float( + np.round((outtime - intime).total_seconds() / 60 / 60, 3) + ) # utils.py:195-196 + lrows, r.used_dummy_rows = loader_rows(rows, hours_zero, full_stay_hours) + r.ehr = build_ehr(lrows, disc) + + return list(results.values()) diff --git a/pyhealth/datasets/medmod/files/MEDMOD_COMMIT b/pyhealth/datasets/medmod/files/MEDMOD_COMMIT new file mode 100644 index 0000000000..69d7fbb244 --- /dev/null +++ b/pyhealth/datasets/medmod/files/MEDMOD_COMMIT @@ -0,0 +1 @@ +7a47c0b909ffbd36370ff69dd023c34f71d9528a diff --git a/pyhealth/datasets/medmod/files/MEDMOD_LICENSE b/pyhealth/datasets/medmod/files/MEDMOD_LICENSE new file mode 100644 index 0000000000..261eeb9e9f --- /dev/null +++ b/pyhealth/datasets/medmod/files/MEDMOD_LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/pyhealth/datasets/medmod/files/NOTICE b/pyhealth/datasets/medmod/files/NOTICE new file mode 100644 index 0000000000..d0b9d48ee8 --- /dev/null +++ b/pyhealth/datasets/medmod/files/NOTICE @@ -0,0 +1,35 @@ +pyhealth.datasets.medmod: MedMod in-hospital mortality for PyHealth + +This package reproduces the data processing of MedMod and contains material +derived from the following projects. + +MedMod (Elsharief et al., 2025), https://github.com/nyuad-cai/MedMod + Licensed under the Apache License, Version 2.0 (files/MEDMOD_LICENSE). + Pinned commit: files/MEDMOD_COMMIT. + - Bundled unmodified: files/discretizer_config.json and + files/ph_ts1.0.normalizer. The latter is MedMod's + ph_ts1.0.input_str:previous.start_time:zero.normalizer, renamed because + Windows does not allow colons in file names; its content is unchanged. + - Not bundled: the split lists testset_iv.csv and valset_iv.csv and the item + map itemid_to_variable_map.csv are downloaded from this repository (or + MedFuse's byte-identical copy) at a pinned commit on first use, checked by + SHA-256 (downloads.py). The tests use 10 of the item map's rows, + unmodified, in test-resources/medmod/itemid_to_variable_map.csv. + - Ported with changes (cited by file and line in the code): the Discretizer + and Normalizer (discretizer.py: statistics counters dropped, restricted + unpickler instead of pickle.load); the cohort, cleaning, time-series and + split rules of mimic4extract (extraction.py, re-implemented on pandas for a + PyHealth task); the training loaders' time-window and CXR-pairing rules + (extraction.py). + +MedFuse (Hayat et al., 2022), https://github.com/nyuad-cai/MedFuse + The repository has no license file. No MedFuse code is bundled. Settings and + behaviours are re-implemented and cited by file and line: the EHR loader's + time window (extraction.py). + +PyHealth, https://github.com/sunlabuiuc/PyHealth, MIT License. + configs/mimic4_ehr_v1.0.yaml is adapted from PyHealth's + pyhealth/datasets/configs/mimic4_ehr.yaml (v2.2). + +pandas: the set of strings pandas 1.1.5 reads as NA (extraction.PANDAS_115_NA) + is taken from pandas/_libs/parsers.pyx at tag v1.1.5 (BSD-3-Clause). diff --git a/pyhealth/datasets/medmod/files/discretizer_config.json b/pyhealth/datasets/medmod/files/discretizer_config.json new file mode 100755 index 0000000000..e4186b0169 --- /dev/null +++ b/pyhealth/datasets/medmod/files/discretizer_config.json @@ -0,0 +1,154 @@ +{ + "id_to_channel": [ + "Capillary refill rate", + "Diastolic blood pressure", + "Fraction inspired oxygen", + "Glascow coma scale eye opening", + "Glascow coma scale motor response", + "Glascow coma scale total", + "Glascow coma scale verbal response", + "Glucose", + "Heart Rate", + "Height", + "Mean blood pressure", + "Oxygen saturation", + "Respiratory rate", + "Systolic blood pressure", + "Temperature", + "Weight", + "pH" + ], + "is_categorical_channel": { + "Capillary refill rate": true, + "Diastolic blood pressure": false, + "Fraction inspired oxygen": false, + "Glascow coma scale eye opening": true, + "Glascow coma scale motor response": true, + "Glascow coma scale total": true, + "Glascow coma scale verbal response": true, + "Glucose": false, + "Heart Rate": false, + "Height": false, + "Mean blood pressure": false, + "Oxygen saturation": false, + "Respiratory rate": false, + "Systolic blood pressure": false, + "Temperature": false, + "Weight": false, + "pH": false + }, + "possible_values": { + "Capillary refill rate": [ + "0.0", + "1.0" + ], + "Diastolic blood pressure": [ + + ], + "Fraction inspired oxygen": [ + + ], + "Glascow coma scale eye opening": [ + "To Pain", + "3 To speech", + "1 No Response", + "4 Spontaneously", + "None", + "To Speech", + "Spontaneously", + "2 To pain" + ], + "Glascow coma scale motor response": [ + "1 No Response", + "3 Abnorm flexion", + "Abnormal extension", + "No response", + "4 Flex-withdraws", + "Localizes Pain", + "Flex-withdraws", + "Obeys Commands", + "Abnormal Flexion", + "6 Obeys Commands", + "5 Localizes Pain", + "2 Abnorm extensn" + ], + "Glascow coma scale total": [ + "11", + "10", + "13", + "12", + "15", + "14", + "3", + "5", + "4", + "7", + "6", + "9", + "8" + ], + "Glascow coma scale verbal response": [ + "1 No Response", + "No Response", + "Confused", + "Inappropriate Words", + "Oriented", + "No Response-ETT", + "5 Oriented", + "Incomprehensible sounds", + "1.0 ET/Trach", + "4 Confused", + "2 Incomp sounds", + "3 Inapprop words" + ], + "Glucose": [ + + ], + "Heart Rate": [ + + ], + "Height": [ + + ], + "Mean blood pressure": [ + + ], + "Oxygen saturation": [ + + ], + "Respiratory rate": [ + + ], + "Systolic blood pressure": [ + + ], + "Temperature": [ + + ], + "Weight": [ + + ], + "pH": [ + + ] + }, + "normal_values": { + "Capillary refill rate": "0.0", + "Diastolic blood pressure": "59.0", + "Fraction inspired oxygen": "0.21", + "Glascow coma scale eye opening": "4 Spontaneously", + "Glascow coma scale motor response": "6 Obeys Commands", + "Glascow coma scale total": "15", + "Glascow coma scale verbal response": "5 Oriented", + "Glucose": "128.0", + "Heart Rate": "86", + "Height": "170.0", + "Mean blood pressure": "77.0", + "Oxygen saturation": "98.0", + "Respiratory rate": "19", + "Systolic blood pressure": "118.0", + "Temperature": "36.6", + "Weight": "81.0", + "pH": "7.4" + } +} \ No newline at end of file diff --git a/pyhealth/datasets/medmod/files/ph_ts1.0.normalizer b/pyhealth/datasets/medmod/files/ph_ts1.0.normalizer new file mode 100755 index 0000000000000000000000000000000000000000..db0fa964493014189a4b19784f0ddc5eaeaca94e GIT binary patch literal 1400 zcmYL{X*kpg0LEuVRx2e*IXftck|Ziy@1H_zq+=RKsm+)P$uN!_8`|AcD3PR4IYS{= zqMC|vho&*sHOQSzv2s@Xv^{H|XWtL+`{Dh4{GFo&amZTqdEP!uZw|$Y?d$FtpzGw} z#nN^6J?-P_=;h@YApMIM%gKZ7?c?R^DO z$NpNFT^QGqS;q&z@am?x`VJf@Jn15Hv<5cUOxFfC)uB^P(_-t9Y%DmKRzLYE4a-uS z9{Me=gd$PSf7wujcUx!-ZdM)gYI|Pfq*lNt&a9@gLWJ^N8@RL7Y^=_&vDf8xqffjd zK3!ITbekM2HY*Eu-1G)<`D?g^8Z!R2Z$wGA1?_+_7eSBvD{{mW_)gG z3^e~Jf|+tzgXzIX@IBB^P9E++>i8!~hxM={1E8?ct${VwNibPa-ao1E7g9tXcuC`OQh&XRG$ddk9jTo?LcIRa~5{_0oa${8$ zh-R~o_79AWiJ2Boufy-3VSY-yQM2tntoDscsdNb8`o(!tJ+}c*o*OF8^o!6JWpq49 zB*Gg-?oi(5R%~)pUKrOU!bp14iQdt6>~CAYIIvuRS;mbkdW~7|SuzazRNQB?bAr|?`p!V-5(T+-x&-cu-4+?|SmMWP6D zOa@pgR&E9Qt|+`~WM_Q#C_bn~)1QPUf^vOL`Zzfa_s&k7-ejJE%psvvukN>@*7M&WTzoi>yZ74%uSxeelngAK$6lXYYXu#Dd#EY)^Xxgg4-jZzbWxAB2l-W-8$uy~-=O+1Z=(QY1=~`tY89xDLoTn=7hsh`%iT2Z1_TCv=sq+h zhSC&Yc1pyA=X?2dLQ;&aCasl>_7NQ8sqqrS#i(E6KK`eM7#7ouZs+m@=#lU)$k-T< QOrc<#{MnN48v5$~1E=|$Pyhe` literal 0 HcmV?d00001 diff --git a/pyhealth/datasets/medmod_mimic4.py b/pyhealth/datasets/medmod_mimic4.py new file mode 100644 index 0000000000..f81101bac6 --- /dev/null +++ b/pyhealth/datasets/medmod_mimic4.py @@ -0,0 +1,279 @@ +"""MedMod in-hospital mortality (Elsharief et al., 2025) on MIMIC-IV v1.0 and +MIMIC-CXR-JPG 2.0.0: the dataset and MedMod's fixed train / val / test split. + +Usage:: + + from pyhealth.datasets import MedModMIMIC4Dataset, MedModSplit + from pyhealth.tasks import MedModInHospitalMortality + + dataset = MedModMIMIC4Dataset(ehr_root=..., cxr_root=..., cache_dir=...) + task = MedModInHospitalMortality(hours_zero="keep", image_dir=...) + train, val, test = dataset.set_task(task, split=MedModSplit()) + +``MedModMIMIC4Dataset`` is ``MIMIC4Dataset`` with a MIMIC-IV v1.0 config, the +tables the task reads, and MedMod's row filters applied before PyHealth caches +the events. PyHealth sorts the whole concatenated event table by patient +(base_dataset.py), which with all of chartevents + labevents needs tens of GB +of scratch space; the ``preprocess_`` hooks drop rows first. Every row +dropped is one MedMod drops anyway, so the cohort and the samples are +unchanged: + +* itemid not among the 114 ready itemids: extract_subjects_iv.py:91-96 and the + inner merge in preprocessing.py:159-164 (MedMod mimic4extract) +* hadm_id empty: validate_events.py:56-57 +* value empty: subject.py:30 (the task still applies MedMod's full pandas-1.1.5 + NA rule afterwards; this only removes true empties) + +MedMod's split comes from fixed subject lists (testset_iv.csv, then +valset_iv.csv among the rest; split_train_and_test.py, split_train_val.py): +the paper's random 70/10/20 patient split (§3.2.4) as MedMod drew it, giving +Table 2's 4,485 / 488 / 1,242. + +* ``MedModSplit``: a PyHealth ``Split`` for ``set_task``; processors are + fitted on its training part only. +* ``split_by_medmod(samples)``: splits a built ``SampleDataset`` by its + ``split`` field, like ``split_by_patient``; for synthetic samples, whose + patients are not on MedMod's lists. +""" + +from __future__ import annotations + +import hashlib +import os +import warnings +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass +from pathlib import Path + +import narwhals as nw +import numpy as np + +from .medmod.downloads import SHA256, medmod_file_path +from .medmod.extraction import ( + read_itemid_to_variable_map, + read_split_file, + split_of, +) +from .mimic4 import MIMIC4Dataset, MIMIC4EHRDataset +from .sample_dataset import SampleDataset +from .splitter import Split + +EHR_V10_CONFIG = Path(__file__).resolve().parent / "configs" / "mimic4_ehr_v1.0.yaml" +EHR_TABLES = ("chartevents", "labevents", "diagnoses_icd") +CXR_TABLES = ("metadata", "chexpert") + + +def _ready_itemids(itemid_map: str | Path | None = None) -> list[str]: + return sorted(str(i) for i in read_itemid_to_variable_map(itemid_map)["itemid"]) + + +def _keep_medmod_rows(frame: nw.LazyFrame, itemids: list[str]) -> nw.LazyFrame: + return frame.filter( + nw.col("itemid").is_in(itemids) + & ~nw.col("hadm_id").is_null() + & ~nw.col("value").is_null() + ) + + +class MedModEHRDataset(MIMIC4EHRDataset): + """MIMIC-IV EHR sub-dataset with MedMod's row filters as PyHealth hooks. + + Examples: + >>> from pyhealth.datasets.medmod_mimic4 import MedModEHRDataset + >>> MedModEHRDataset.itemid_map is None # MedMod's map, downloaded + True + >>> # Built for you by MedModMIMIC4Dataset (sub_datasets["ehr"]). + """ + + #: MedMod's item map; None downloads it on first use. + itemid_map: str | None = None + + def preprocess_chartevents(self, frame: nw.LazyFrame) -> nw.LazyFrame: + """Keeps only chartevents rows of MedMod's mapped item ids. + + Args: + frame: The raw chartevents table. + + Returns: + The rows whose ``itemid`` maps to one of the 17 variables. + """ + return _keep_medmod_rows(frame, _ready_itemids(self.itemid_map)) + + def preprocess_labevents(self, frame: nw.LazyFrame) -> nw.LazyFrame: + """Keeps only labevents rows of MedMod's mapped item ids. + + Args: + frame: The raw labevents table. + + Returns: + The rows whose ``itemid`` maps to one of the 17 variables. + """ + return _keep_medmod_rows(frame, _ready_itemids(self.itemid_map)) + + +class MedModMIMIC4Dataset(MIMIC4Dataset): + """``MIMIC4Dataset`` with the v1.0 config, the tables the task reads, and + the row filters above. + + ``dataset_name`` is part of PyHealth's cache key + (``BaseDataset._init_cache_dir``), so this cache never mixes with an + unfiltered ``MIMIC4Dataset`` cache. + + Args: + ehr_root: folder holding ``core/``, ``hosp/``, ``icu/`` (MIMIC-IV v1.0). + cxr_root: folder holding the MIMIC-CXR-JPG CSVs. + cache_dir: where PyHealth writes its processed copy of the data. Put it + next to the data; without it PyHealth uses its default cache folder. + itemid_map: MedMod's ``itemid_to_variable_map.csv``. Without it, the + file is downloaded from MedMod's GitHub on first use. + + Examples: + >>> from pyhealth.datasets import MedModMIMIC4Dataset + >>> dataset = MedModMIMIC4Dataset( # doctest: +SKIP + ... ehr_root="/data/mimiciv/1.0", + ... cxr_root="/data/mimic-cxr-jpg/2.0.0", + ... cache_dir="/data/pyhealth_cache", + ... ) + """ + + def __init__( + self, + ehr_root: str | Path, + cxr_root: str | Path, + cache_dir: str | Path | None = None, + dev: bool = False, + num_workers: int = 1, + ehr_config_path: str | Path = EHR_V10_CONFIG, + itemid_map: str | Path | None = None, + ): + ehr_root, cxr_root = os.fspath(ehr_root), os.fspath(cxr_root) + cfg = os.fspath(ehr_config_path) + super().__init__( + ehr_root=ehr_root, + cxr_root=cxr_root, + ehr_tables=list(EHR_TABLES), + cxr_tables=list(CXR_TABLES), + ehr_config_path=cfg, + dataset_name="medmod_mimic4", + dev=dev, + cache_dir=None if cache_dir is None else os.fspath(cache_dir), + num_workers=num_workers, + ) + # Swap in the filtering EHR sub-dataset (built the same way as + # MIMIC4Dataset.__init__). Nothing is loaded until global_event_df is used. + self.sub_datasets["ehr"] = MedModEHRDataset( + root=ehr_root, + tables=list(EHR_TABLES), + config_path=cfg, + cache_dir=str(self.cache_dir), + dev=dev, + num_workers=num_workers, + ) + if itemid_map is not None: + self.sub_datasets["ehr"].itemid_map = os.fspath(itemid_map) + + +SPLITS = ("train", "val", "test") + + +def _digest(path: str | Path) -> str: + return hashlib.sha256(Path(path).read_bytes()).hexdigest()[:16] + + +@dataclass(frozen=True) +class MedModSplit(Split): + """MedMod's subject lists as a PyHealth ``Split`` (train, val, test). + + Args: + testset: path of a test subject list (default: MedMod's + ``testset_iv.csv``, downloaded from MedMod's GitHub on first use). + valset: path of a validation subject list (default: MedMod's + ``valset_iv.csv``, the same way). + + Examples: + >>> from pyhealth.datasets import MedModSplit + >>> MedModSplit().to_dict()["kind"] + 'medmod' + >>> # train, val, test = dataset.set_task(task, split=MedModSplit()) + """ + + testset: str | None = None + valset: str | None = None + + def split_indices( + self, patient_to_index: Mapping[str, Sequence[int]] + ) -> list[np.ndarray]: + """Assigns samples to MedMod's fixed train, validation and test split. + + Args: + patient_to_index: Sample positions of each patient. + + Returns: + The sorted sample positions of train, val and test. + """ + test = read_split_file(self.testset or medmod_file_path("testset_iv.csv")) + val = read_split_file(self.valset or medmod_file_path("valset_iv.csv")) + parts: dict[str, list[int]] = {name: [] for name in SPLITS} + for pid, indices in patient_to_index.items(): + parts[split_of(str(pid), test, val)].extend(indices) + empty = [name for name in SPLITS if not parts[name]] + if empty: # normal for PyHealth dev mode or tiny test data + warnings.warn(f"MedModSplit: no samples in split(s) {empty}", stacklevel=2) + return [np.array(sorted(parts[name]), dtype=np.int64) for name in SPLITS] + + def to_dict(self) -> dict: + """Describes the split for PyHealth's cache key. + + Returns: + The split kind and the digests of the test and val lists, so the + cache changes whenever a list's content does. + """ + return { + "kind": "medmod", + "testset_sha256": ( + _digest(self.testset) if self.testset else SHA256["testset_iv.csv"][:16] + ), + "valset_sha256": ( + _digest(self.valset) if self.valset else SHA256["valset_iv.csv"][:16] + ), + } + + +def split_positions(splits: Iterable[str]) -> dict[str, list[int]]: + """Positions of each split value, in sample order. + + Examples: + >>> from pyhealth.datasets.medmod_mimic4 import split_positions + >>> split_positions(["train", "test", "train"]) + {'train': [0, 2], 'val': [], 'test': [1]} + """ + out: dict[str, list[int]] = {name: [] for name in SPLITS} + for i, name in enumerate(splits): + if name not in out: + raise ValueError(f"unknown split {name!r}; expected one of {SPLITS}") + out[name].append(i) + return out + + +def split_by_medmod( + samples: SampleDataset, +) -> tuple[SampleDataset, SampleDataset, SampleDataset]: + """Split a MedMod ``SampleDataset`` by its ``split`` field. + + Args: + samples: a ``SampleDataset`` from ``set_task`` without ``split``. + + Returns: + train, val, test: ``SampleDataset`` views (``samples.subset``), as + returned by PyHealth's ``split_by_patient``. + + Examples: + >>> from pyhealth.datasets import split_by_medmod + >>> samples = dataset.set_task(task) # doctest: +SKIP + >>> train, val, test = split_by_medmod(samples) # doctest: +SKIP + """ + positions = split_positions(samples[i]["split"] for i in range(len(samples))) + empty = [name for name, idx in positions.items() if not idx] + if empty: # normal for PyHealth dev mode or tiny test data; worth a heads-up + warnings.warn(f"split_by_medmod: no samples in split(s) {empty}", stacklevel=2) + return tuple(samples.subset(positions[name]) for name in SPLITS) diff --git a/pyhealth/processors/medmod_ehr_processor.py b/pyhealth/processors/medmod_ehr_processor.py new file mode 100644 index 0000000000..a1f0f6d556 --- /dev/null +++ b/pyhealth/processors/medmod_ehr_processor.py @@ -0,0 +1,146 @@ +"""PyHealth processor for MedMod's EHR tensor: standardize, then float32. + +``normalizer=`` loads a fixed MedMod normalizer file and learns nothing. +``PH_NORMALIZER``, the task's default, is the file MedMod's released code loads +for this task (the phenotyping one, via the ``is`` bug in ehr_funcs; see +discretizer.py). + +``normalizer=None`` learns the statistics (``learns_statistics``), and PyHealth +fits them on the training part only when the task is set with MedMod's split:: + + train, val, test = dataset.set_task(task, split=MedModSplit()) + +The statistics follow MedMod's create_normalizer_state.py:87-93 and +preprocessing.py:193-215: means and stds over every bin of every training stay, +all 76 columns. Either way only the 12 continuous columns are standardized +(preprocessing.py:224-232, 254). MedMod computes in float64 and its trainers +cast to float32 (``torch.from_numpy(x).float()``); so do we. +""" + +from __future__ import annotations + +from collections.abc import Iterable +from pathlib import Path +from typing import Any + +import numpy as np +import torch + +from .base_processor import FeatureProcessor + + +class MedModEHRProcessor(FeatureProcessor): + """Standardizes the task's unnormalized ``ehr`` (bins x 76) to float32. + + Args: + normalizer: a MedMod normalizer file, used as is (the task passes + ``PH_NORMALIZER`` by default). ``None``: learn means and stds in + ``fit``, which PyHealth calls on the training part when the task is + set with ``split=MedModSplit()``. + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets.medmod.discretizer import PH_NORMALIZER + >>> from pyhealth.processors.medmod_ehr_processor import MedModEHRProcessor + >>> processor = MedModEHRProcessor(PH_NORMALIZER) + >>> processor.process(np.zeros((48, 76))).dtype + torch.float32 + """ + + learns_statistics = True + stores_tensor = True + + def __init__(self, normalizer: str | Path | None = None): + # Imported here, not at the top. The discretizer is in pyhealth.datasets, + # which imports the tasks, and the MedMod task imports this module. A + # top-level import would fail when this module is imported first. + from ..datasets.medmod.discretizer import Discretizer, Normalizer + + self.normalizer_file = None if normalizer is None else str(normalizer) + # An instance attribute: PyHealth reads it to warn about fitting on + # all samples, which only matters when statistics are learned. + self.learns_statistics = normalizer is None + fields = Discretizer().continuous_columns() + self.normalizer = Normalizer(fields=fields) + if normalizer is not None: + self.normalizer.load_params(normalizer) + + def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: + """Fits the normalizer on the samples, unless a file was given. + + Args: + samples: The task's samples. + field: The EHR key of each sample. + """ + if self.normalizer_file is not None: + return + self.normalizer.fit(np.asarray(s[field], dtype=float) for s in samples) + + def process(self, value: Any) -> torch.Tensor: + """Standardizes one stay's binned EHR. + + Args: + value: The stay's EHR, shape (time steps, 76). + + Returns: + A float32 tensor of the same shape, continuous columns z-scored. + """ + x = self.normalizer.transform(np.asarray(value, dtype=float)) + return torch.from_numpy(x.astype(np.float32)) + + def is_token(self) -> bool: + """False: the EHR is continuous values, not token ids.""" + return False + + def schema(self) -> tuple[str, ...]: + """The processed output: one tensor, ``value``.""" + return ("value",) + + def dim(self) -> tuple[int, ...]: + """The tensor has 2 dimensions per sample: time steps x 76.""" + return (2,) + + def spatial(self) -> tuple[bool, ...]: + """Which dimensions are ordered: time steps yes, features no.""" + return (True, False) # time bins, then features + + +class MedModEHRSequenceProcessor(MedModEHRProcessor): + """``MedModEHRProcessor`` for EHR of varying length (bins x 76 per stay). + + Each sample is standardized as in :class:`MedModEHRProcessor`. A batch is + zero-padded at the end to its longest stay and comes with the true + lengths, as MedMod's ``pad_zeros`` / ``my_collate_fusion`` + (src/data/utils.py:160-170, 399-406) feed its LSTM, which packs them + (src/models/encoders.py:44-45). The batch value is ``(ehr, lengths)``: + ``ehr`` is ``[batch, max_bins, 76]`` float32, ``lengths`` int64. + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets.medmod.discretizer import PH_NORMALIZER + >>> from pyhealth.processors.medmod_ehr_processor import ( + ... MedModEHRSequenceProcessor, + ... ) + >>> processor = MedModEHRSequenceProcessor(PH_NORMALIZER) + >>> x = [processor.process(np.zeros((n, 76))) for n in (3, 5)] + >>> ehr, lengths = processor.collate(x) + >>> tuple(ehr.shape), lengths.tolist() + ((2, 5, 76), [3, 5]) + """ + + def collate(self, values: list[torch.Tensor]) -> tuple[torch.Tensor, torch.Tensor]: + """Zero-pads a batch of stays to the longest one. + + Args: + values: Processed stays, each (time steps, 76). + + Returns: + The padded batch (batch, longest, 76) and each stay's length. + """ + lengths = torch.tensor([v.shape[0] for v in values], dtype=torch.long) + ehr = torch.nn.utils.rnn.pad_sequence(values, batch_first=True, padding_value=0) + return ehr, lengths + + def schema(self) -> tuple[str, ...]: + """The processed output: the padded ``value`` and its ``lengths``.""" + return ("value", "lengths") diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index e01d41b267..4659c45e6c 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -342,6 +342,13 @@ from .tcga_survival_prediction import TCGASurvivalPrediction as TCGASurvivalPrediction from .query_focused_ehr import QueryFocusedEHRTask as QueryFocusedEHRTask +# Imported last: this task imports pyhealth.datasets, which imports the tasks +# above, so they must already be defined. +from .medmod_mortality_mimic4 import ( + MedModInHospitalMortality as MedModInHospitalMortality, +) + + def __getattr__(name: str): if name == "MPFClinicalPredictionTask": from .mpf_clinical_prediction import MPFClinicalPredictionTask diff --git a/pyhealth/tasks/medmod_mortality_mimic4.py b/pyhealth/tasks/medmod_mortality_mimic4.py new file mode 100644 index 0000000000..e8c0779fcb --- /dev/null +++ b/pyhealth/tasks/medmod_mortality_mimic4.py @@ -0,0 +1,246 @@ +"""PyHealth task: MedMod in-hospital mortality (EHR + latest AP chest X-ray). + +Used like any PyHealth task:: + + from pyhealth.datasets import get_dataloader + from pyhealth.datasets import MedModMIMIC4Dataset, MedModSplit + from pyhealth.tasks import MedModInHospitalMortality + + dataset = MedModMIMIC4Dataset( + ehr_root="/data/mimiciv_medmod_slim/1.0", + cxr_root="/data/mimic-cxr-jpg/2.0.0", + cache_dir="/data/pyhealth_cache", + ) + task = MedModInHospitalMortality( + hours_zero="keep", image_dir="/data/mimic-cxr-jpg/2.0.0/resized" + ) + train, val, test = dataset.set_task(task, split=MedModSplit(), num_workers=4) + train_loader = get_dataloader(train, batch_size=32, shuffle=True) + +Every rule follows MedMod's released code, which produced the paper's numbers +(where the paper says otherwise, see the docs page, "Paper vs code"). Two EHR +settings can be changed: ``timestep`` (bin width, default 1 h) and +``normalizer`` (default: the file MedMod's code loads; ``None`` fits one on the +train split). The defaults reproduce MedMod's own extraction bit for bit and +match MedFuse's released encoders (the frozen Early Fusion encoders). + +``MedModMIMIC4Dataset`` (pyhealth/datasets/medmod_mimic4.py) is a +``MIMIC4Dataset`` with the v1.0 +config and MedMod's row filters applied before PyHealth's disk-heavy sort. + +PyHealth references are ``file:line`` in github.com/sunlabuiuc/PyHealth +(pyhealth/...), MedMod references as in ``pyhealth/datasets/medmod/extraction.py``. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any, ClassVar + +import pandas as pd +import polars as pl + +from ..data import Patient +from ..datasets.medmod.discretizer import PH_NORMALIZER +from ..datasets.medmod.extraction import ( + DEFAULT_TIMESTEP, + N_HOURS, + HoursZero, + MedModResources, + StayResult, + SubjectTables, + process_subject, +) +from ..processors.medmod_ehr_processor import MedModEHRProcessor +from .base_task import BaseTask + + +def _table(patient: Patient, event_type: str, ts_name: str) -> pd.DataFrame: + """One event type as pandas, with the ``/`` prefix removed + (attribute naming from ``BaseDataset.load_table``) and ``timestamp`` + renamed to ``ts_name``.""" + df: pl.DataFrame = patient.get_events(event_type=event_type, return_df=True) + prefix = f"{event_type}/" + keep = ["timestamp"] + [c for c in df.columns if c.startswith(prefix)] + df = df.select(keep).rename( + {c: c[len(prefix) :] for c in keep if c.startswith(prefix)} + ) + out = df.to_pandas() + return out.rename(columns={"timestamp": ts_name}) + + +class MedModInHospitalMortality(BaseTask): + """One sample per ICU stay that survives MedMod's IHM pipeline. + + Sample: ``patient_id`` (subject_id), ``visit_id`` (stay_id), ``ehr`` + (float32, (48 / timestep) x 76: 48 x 76 by default), ``image_path`` + (latest AP CXR within 48 h of intime), ``label`` (1 = died in hospital), + ``split`` (train / val / test from MedMod's subject lists). + + Set it with ``split=MedModSplit()``: MedMod's fixed lists, and with + ``normalizer=None`` the normalizer is fitted on the train split only. + + Args: + hours_zero: required. ``"keep"`` rows at Hours == 0 (MedFuse loader, + Early Fusion) or ``"drop"`` them, i.e. 0 < Hours <= 48 (MedMod loader, + ConVIRT). The cohort + is the same either way; only ``ehr`` changes. (The paper is silent.) + timestep: bin width in hours; 48 must be a multiple. Default 1.0, the + released code's (--timestep default); e.g. 2.0 gives 24 x 76. + normalizer: a MedMod normalizer file, used as is. Default + ``PH_NORMALIZER``, the one the released code loads (and MedFuse's + checkpoints were trained with; its statistics are over 1-hour + bins). ``None``: means and stds fitted on the train split by + ``MedModEHRProcessor``. + image_dir: folder of resized images (``resized/.jpg``, + MedFuse's 512-px resize). If set, + ``image_path`` points + there and stays whose file is missing are dropped (funnel stage + ``resized_image_found``). If None, ``image_path`` is PyHealth's + original ``files/...`` path, not checked on disk. set_task caches by + the task's arguments, not by the folder's contents: after adding + images, use a fresh cache_dir or delete the task cache. + resources: MedMod's item map, split lists and discretizer config. + Defaults to ``MedModResources.load()``, which downloads the item + map and split lists from MedMod's GitHub on first use and reads + the discretizer config bundled in ``pyhealth/datasets/medmod/files``. + Pass your own ``MedModResources`` only to use different files. + + Examples: + >>> from pyhealth.tasks import MedModInHospitalMortality + >>> task = MedModInHospitalMortality(hours_zero="keep") + >>> task.task_name, task.output_schema + ('MedModInHospitalMortality', {'label': 'binary'}) + >>> # train, val, test = dataset.set_task(task, split=MedModSplit()) + """ + + task_name: str = "MedModInHospitalMortality" + input_schema: ClassVar[dict[str, Any]] = { + "ehr": MedModEHRProcessor, + "image_path": "raw", + } + output_schema: ClassVar[dict[str, str]] = {"label": "binary"} + + def __init__( + self, + *, + hours_zero: HoursZero, + timestep: float = DEFAULT_TIMESTEP, + normalizer: str | Path | None = PH_NORMALIZER, + image_dir: str | Path | None = None, + resources: MedModResources | None = None, + ): + super().__init__() + if hours_zero not in ("keep", "drop"): + raise ValueError( + f'hours_zero must be "keep" (Early Fusion) or "drop" (ConVIRT), ' + f"got {hours_zero!r}" + ) + bins = N_HOURS / timestep if timestep > 0 else 0 + if bins < 1 or abs(bins - round(bins)) > 1e-9: + raise ValueError(f"timestep must divide {N_HOURS} h, got {timestep}") + if normalizer is not None and not Path(normalizer).is_file(): + raise FileNotFoundError(f"normalizer file not found: {normalizer}") + if image_dir is not None and not Path(image_dir).is_dir(): + raise FileNotFoundError(f"image_dir does not exist: {image_dir}") + # set_task builds its cache key from vars(task) with json.dumps(default=str) + # (BaseDataset._task_cache_dir): plain values, and a resources object whose + # str() is its source paths. + self.hours_zero = hours_zero + self.timestep = float(timestep) + self.image_dir = None if image_dir is None else str(Path(image_dir).resolve()) + self.resources = resources if resources is not None else MedModResources.load() + # The processor spec carries the normalizer choice, so PyHealth's cache + # key (which includes input_schema) changes with it. + norm = None if normalizer is None else str(Path(normalizer).resolve()) + self.input_schema = { + "ehr": (MedModEHRProcessor, {"normalizer": norm}), + "image_path": "raw", + } + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Drop chartevents/labevents rows outside the 114 ready itemids before + patients are materialised (hook called in BaseDataset._task_transform). This + matches MedMod, which keeps only mapped itemids (extract_subj.py:91-96, + bench_prep.py:159-164).""" + names = df.collect_schema().names() + ids = [str(i) for i in sorted(self.resources.itemids)] + expr = pl.lit(True) + for et in ("chartevents", "labevents"): + col = f"{et}/itemid" + if col in names: + expr = expr & ((pl.col("event_type") != et) | pl.col(col).is_in(ids)) + return df.filter(expr) + + def subject_tables(self, patient: Patient) -> SubjectTables: + """Collects one patient's PyHealth events into MedMod's tables. + + Args: + patient: A PyHealth patient of ``MedModMIMIC4Dataset``. + + Returns: + The patient's admissions, ICU stays, chart and lab events, + diagnoses and chest X-ray metadata, in the form MedMod's + extraction (``process_subject``) reads. + """ + ce = _table(patient, "chartevents", "charttime") + le = _table(patient, "labevents", "charttime") + events = pd.concat([ce, le], ignore_index=True, sort=False) + for col in ("hadm_id", "stay_id", "itemid", "value", "valuenum"): + if col not in events.columns: + events[col] = pd.NA + + icu = _table(patient, "icustays", "intime") + if not icu.empty: + # MIMIC times are ISO 8601 ("2150-03-05 14:10:00"); naming the format + # avoids pandas' per-element dateutil fallback (and its warning) when + # it cannot guess, e.g. if a value is missing. Same parsed values. + icu["outtime"] = pd.to_datetime(icu["outtime"], format="ISO8601") + + cxr = _table(patient, "metadata", "studydatetime") + chex = _table(patient, "chexpert", "studydatetime") + return SubjectTables( + subject_id=str(patient.patient_id), + patients=_table(patient, "patients", "timestamp"), + admissions=_table(patient, "admissions", "admittime"), + icustays=icu, + events=events, + diagnoses=_table(patient, "diagnoses_icd", "dischtime"), + cxr=cxr, + chexpert_study_ids=( + set(chex["study_id"].astype(str)) if "study_id" in chex else set() + ), + ) + + def process_patient(self, patient: Patient) -> list[StayResult]: + """Runs MedMod's extraction on every ICU stay of a patient. + + Args: + patient: A PyHealth patient of ``MedModMIMIC4Dataset``. + + Returns: + One result per ICU stay, with the last cohort stage it passed + and, for stays in the cohort, its sample. + """ + return process_subject( + self.subject_tables(patient), + self.resources, + self.hours_zero, + self.image_dir, + self.timestep, + ) + + def __call__(self, patient: Patient) -> list[dict]: + """Returns the patient's in-hospital mortality samples. + + Args: + patient: A PyHealth patient of ``MedModMIMIC4Dataset``. + + Returns: + One sample per ICU stay in MedMod's cohort, with keys + ``patient_id``, ``visit_id``, ``ehr`` (the binned first 48 hours), + ``image_path`` (the latest AP chest X-ray), ``label`` (1 if the + patient died in hospital) and ``split`` (MedMod's fixed split). + Empty if no stay qualifies. + """ + return [r.sample() for r in self.process_patient(patient) if r.kept] diff --git a/test-resources/medmod/itemid_to_variable_map.csv b/test-resources/medmod/itemid_to_variable_map.csv new file mode 100644 index 0000000000..65109ff4aa --- /dev/null +++ b/test-resources/medmod/itemid_to_variable_map.csv @@ -0,0 +1,11 @@ +LEVEL2,LEVEL1,ALTERNATIVE,STATUS,STATUS NOTE,ITEMID,MIMIC LABEL,UNITNAME,LINKSTO,COUNT,CATEGORY,CONCEPTID,FLUID,LOINC_CODE,DBSOURCE,,PARAM_TYPE,NOTE +Capillary refill rate,Capillary refill rate,CRR,ready,,3348,Capillary Refill,,chartevents,440467,,,,,carevue,,Binary, +Fraction inspired oxygen,Fraction inspired oxygen,FiO2,ready,requires unit conversion or checking,223835,Inspired O2 Fraction,None,chartevents,558061,Respiratory,,,,metavision,,Numeric, +Glascow coma scale eye opening,Glascow coma scale eye opening,GCS eye,ready,should we just add these up?,220739,GCS - Eye Opening,,chartevents,571383,Neurological,,,,metavision,,Text, +Glucose,Glucose,,ready,,50931,GLUCOSE,,labevents,748981,CHEMISTRY,,BLOOD,7/1/2345,,,, +Heart Rate,Heart Rate,HR,ready,,220045,Heart Rate,bpm,chartevents,2762225,Routine Vital Signs,,,,metavision,,Numeric, +Height,Height,Height,ready,requires unit conversion or checking,226707,Height,Inch,chartevents,12015,General,,,,metavision,,Numeric, +Mean blood pressure,Mean blood pressure (arterial),ABPm,ready,,224,IABP Mean,,chartevents,30020,,,,,carevue,,, +Oxygen saturation,Pulse oximetry,SpO2,ready,,220277,O2 saturation pulseoxymetry,%,chartevents,2671816,Respiratory,,,,metavision,,Numeric, +pH,pH,,ready,,50820,PH,,labevents,530795,BLOOD GAS,,BLOOD,11558-4,,,, +Temperature,Temperature (F),,ready,requires unit conversion or checking,223761,Temperature Fahrenheit,?F,chartevents,522143,Routine Vital Signs,,,,metavision,,Numeric, diff --git a/tests/core/medmod_test_utils.py b/tests/core/medmod_test_utils.py new file mode 100644 index 0000000000..b46997312b --- /dev/null +++ b/tests/core/medmod_test_utils.py @@ -0,0 +1,385 @@ +"""Test helpers for the MedMod in-hospital mortality dataset and task: tiny +synthetic MIMIC-IV v1.0 + MIMIC-CXR subjects. + +Default subject: one admission, one 96 h MICU stay (intime 2150-03-01 22:00), +anchor_age 60, one diagnosis, one AP chest X-ray at intime + 10 h with a +CheXpert row. Event tuples are (hours after intime, itemid, value[, table, +stay_id, hadm_id]). +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pandas as pd + +from pyhealth.datasets.medmod.extraction import ( + MedModResources, + SubjectTables, + process_subject, +) +from pyhealth.datasets.medmod_mimic4 import MedModMIMIC4Dataset + +INTIME = pd.Timestamp("2150-03-01 22:00:00") +SID, HADM, STAY = "10000001", "20000001", "30000001" + +# MedMod's item map, only the rows of the item ids these tests use (so the +# tests need no download); copied unchanged from itemid_to_variable_map.csv +TEST_ITEMID_MAP = ( + Path(__file__).resolve().parents[2] + / "test-resources" + / "medmod" + / "itemid_to_variable_map.csv" +) + +# itemids from MedMod's itemid_to_variable_map.csv (STATUS == ready) +HR, GCS_EYE, CRR, TEMP_F, FIO2, HEIGHT_IN, SPO2, GLUCOSE_LAB, PH_LAB = ( + "220045", + "220739", + "3348", + "223761", + "223835", + "226707", + "220277", + "50931", + "50820", +) + + +def load_test_resources() -> MedModResources: + """MedMod's files: the test item map and synthetic subject lists.""" + r = MedModResources.load(itemid_map=TEST_ITEMID_MAP) + r.test_subjects = {"10000002"} + r.val_subjects = {"10000003"} + return r + + +def stay_row( + stay=STAY, hadm=HADM, intime=INTIME, hours=96.0, first="MICU", last="MICU", los=None +): + return { + "stay_id": stay, + "hadm_id": hadm, + "first_careunit": first, + "last_careunit": last, + "intime": intime, + "outtime": intime + pd.Timedelta(hours=hours), + "los": str(hours / 24.0 if los is None else los), + } + + +def make_subject( + sid=SID, + events=(), + stays=None, + admissions=None, + anchor_age="60", + dod=None, + diagnoses=(HADM,), + cxr=None, + chexpert=("50000001",), +) -> SubjectTables: + stays = [stay_row()] if stays is None else stays + if admissions is None: + admissions = [ + { + "hadm_id": HADM, + "admittime": INTIME - pd.Timedelta(hours=2), + "dischtime": str(INTIME + pd.Timedelta(days=8)), + "deathtime": None, + } + ] + if cxr is None: + cxr = [cxr_row(10.0)] + ev_rows = [] + for e in events: + hours, itemid, value = e[:3] + table = e[3] if len(e) > 3 else "chartevents" + stay = e[4] if len(e) > 4 else (STAY if table == "chartevents" else None) + hadm = e[5] if len(e) > 5 else HADM + ev_rows.append( + { + "charttime": INTIME + pd.Timedelta(hours=hours), + "hadm_id": hadm, + "stay_id": stay, + "itemid": itemid, + "value": value, + "valuenum": None, + } + ) + return SubjectTables( + subject_id=sid, + patients=pd.DataFrame([{"anchor_age": anchor_age, "dod": dod}]), + admissions=pd.DataFrame(admissions), + icustays=pd.DataFrame(stays), + events=pd.DataFrame( + ev_rows, + columns=["charttime", "hadm_id", "stay_id", "itemid", "value", "valuenum"], + ), + diagnoses=pd.DataFrame({"hadm_id": list(diagnoses)}), + cxr=pd.DataFrame( + cxr, + columns=[ + "studydatetime", + "dicom_id", + "study_id", + "viewposition", + "image_path", + ], + ), + chexpert_study_ids=set(chexpert), + ) + + +def cxr_row(hours, dicom="d1", study="50000001", view="AP", intime=INTIME): + return { + "studydatetime": intime + pd.Timedelta(hours=hours), + "dicom_id": dicom, + "study_id": study, + "viewposition": view, + "image_path": f"/cxr/files/p10/p{SID}/s{study}/{dicom}.jpg", + } + + +def run(st, res, hours_zero="keep", image_dir=None, timestep=1.0): + """Rule tests use 1-hour bins (the default), so bin i is hour i.""" + return { + r.stay_id: r for r in process_subject(st, res, hours_zero, image_dir, timestep) + } + + +def raw(ehr: np.ndarray) -> np.ndarray: + """``ehr`` as values. The extraction returns it unnormalized (the processor + standardizes later), so this is just a float copy.""" + return np.asarray(ehr, dtype=float).copy() + + +def col(res, name: str) -> int: + return res.discretizer.output_header().index(name) + + +# --------------------------------------------- whole-dataset fixtures + + +def _w(path, rows): + path.parent.mkdir(parents=True, exist_ok=True) + pd.DataFrame(rows).to_csv(path, index=False, compression="gzip") + + +def write_fake_mimic(tmp_path: Path): + """Three subjects as MIMIC-IV v1.0 + MIMIC-CXR CSVs; returns (ehr, cxr, cache).""" + ehr, cxr = tmp_path / "mimiciv" / "1.0", tmp_path / "cxr" + # subject 1: survives; subject 2: dies (deathtime); subject 3: ICU transfer + _w( + ehr / "core/patients.csv.gz", + [ + { + "subject_id": s, + "gender": "F", + "anchor_age": 60, + "anchor_year": 2150, + "anchor_year_group": "2008 - 2010", + "dod": d, + } + for s, d in [(10000001, ""), (10000002, "2150-03-04"), (10000003, "")] + ], + ) + _w( + ehr / "core/admissions.csv.gz", + [ + { + "subject_id": s, + "hadm_id": h, + "admittime": "2150-03-01 20:00:00", + "dischtime": "2150-03-09 12:00:00", + "deathtime": dt, + "admission_type": "EW EMER.", + "ethnicity": "WHITE", + "hospital_expire_flag": int(bool(dt)), + } + for s, h, dt in [ + (10000001, 20000001, ""), + (10000002, 20000002, "2150-03-04 10:00:00"), + (10000003, 20000003, ""), + ] + ], + ) + _w( + ehr / "icu/icustays.csv.gz", + [ + { + "subject_id": s, + "hadm_id": h, + "stay_id": st, + "first_careunit": "MICU", + "last_careunit": last, + "intime": "2150-03-01 22:00:00", + "outtime": "2150-03-05 22:00:00", + "los": 4.0, + } + for s, h, st, last in [ + (10000001, 20000001, 30000001, "MICU"), + (10000002, 20000002, 30000002, "MICU"), + (10000003, 20000003, 30000003, "SICU"), + ] + ], + ) + ce = [] + for s, h, st in [ + (10000001, 20000001, 30000001), + (10000002, 20000002, 30000002), + (10000003, 20000003, 30000003), + ]: + ce += [ + { + "subject_id": s, + "hadm_id": h, + "stay_id": st, + "charttime": "2150-03-01 22:00:00", + "storetime": "", + "itemid": 220045, + "value": "120", + "valuenum": 120.0, + "valueuom": "bpm", + "warning": 0, + }, + { + "subject_id": s, + "hadm_id": h, + "stay_id": st, + "charttime": "2150-03-02 01:30:00", + "storetime": "", + "itemid": 220045, + "value": "88", + "valuenum": 88.0, + "valueuom": "bpm", + "warning": 0, + }, + { + "subject_id": s, + "hadm_id": h, + "stay_id": st, + "charttime": "2150-03-02 01:30:00", + "storetime": "", + "itemid": 220739, + "value": "To Speech", + "valuenum": 3.0, + "valueuom": "", + "warning": 0, + }, + { + "subject_id": s, + "hadm_id": h, + "stay_id": st, + "charttime": "2150-03-02 01:30:00", + "storetime": "", + "itemid": 999999, + "value": "1", + "valuenum": 1.0, + "valueuom": "", + "warning": 0, + }, + ] + _w(ehr / "icu/chartevents.csv.gz", ce) + _w( + ehr / "hosp/labevents.csv.gz", + [ + { + "labevent_id": 1, + "subject_id": 10000001, + "hadm_id": 20000001, + "specimen_id": 1, + "itemid": 50931, + "charttime": "2150-03-02 03:10:00", + "storetime": "", + "value": "140", + "valuenum": 140.0, + "valueuom": "mg/dL", + "ref_range_lower": "", + "ref_range_upper": "", + "flag": "", + "priority": "", + "comments": "", + } + ], + ) + _w( + ehr / "hosp/diagnoses_icd.csv.gz", + [ + { + "subject_id": s, + "hadm_id": h, + "seq_num": 1, + "icd_code": "4019", + "icd_version": 9, + } + for s, h in [ + (10000001, 20000001), + (10000002, 20000002), + (10000003, 20000003), + ] + ], + ) + _w( + ehr / "hosp/d_icd_diagnoses.csv.gz", + [{"icd_code": "4019", "icd_version": 9, "long_title": "HTN"}], + ) + + meta = [ + { + "dicom_id": f"d{i}", + "subject_id": s, + "study_id": 50000000 + i, + "PerformedProcedureStepDescription": "CHEST (PORTABLE AP)", + "ViewPosition": "AP", + "Rows": 3056, + "Columns": 2544, + "StudyDate": 21500302, + "StudyTime": 81400.0, + "ProcedureCodeSequence_CodeMeaning": "CHEST (PORTABLE AP)", + "ViewCodeSequence_CodeMeaning": "antero-posterior", + "PatientOrientationCodeSequence_CodeMeaning": "Erect", + } + for i, s in [(1, 10000001), (2, 10000002), (3, 10000003)] + ] + _w(cxr / "mimic-cxr-2.0.0-metadata.csv.gz", meta) + labels = [ + "Atelectasis", + "Cardiomegaly", + "Consolidation", + "Edema", + "Enlarged Cardiomediastinum", + "Fracture", + "Lung Lesion", + "Lung Opacity", + "No Finding", + "Pleural Effusion", + "Pleural Other", + "Pneumonia", + "Pneumothorax", + "Support Devices", + ] + _w( + cxr / "mimic-cxr-2.0.0-chexpert.csv.gz", + [ + { + "subject_id": m["subject_id"], + "study_id": m["study_id"], + **{c: "" for c in labels}, + } + for m in meta + ], + ) + return ehr, cxr, tmp_path / "cache" + + +def make_dataset(roots): + ehr, cxr, cache = roots + return MedModMIMIC4Dataset( + ehr_root=ehr, + cxr_root=cxr, + cache_dir=cache, + num_workers=1, + itemid_map=TEST_ITEMID_MAP, + ) diff --git a/tests/core/test_medmod_mimic4_dataset.py b/tests/core/test_medmod_mimic4_dataset.py new file mode 100644 index 0000000000..e01a6eaf24 --- /dev/null +++ b/tests/core/test_medmod_mimic4_dataset.py @@ -0,0 +1,177 @@ +"""MedMod in-hospital mortality end to end in PyHealth: synthetic MIMIC-IV v1.0 + +MIMIC-CXR folders -> MedModMIMIC4Dataset -> set_task(split=MedModSplit()).""" + +from __future__ import annotations + +import numpy as np +import polars as pl +import pytest +import torch + +from pyhealth.datasets import MedModSplit, PatientSplit +from pyhealth.datasets.medmod.discretizer import PH_NORMALIZER, medmod_ehr_funcs +from pyhealth.datasets.medmod.extraction import STAGES, MedModResources +from pyhealth.tasks import MedModInHospitalMortality +from tests.core.medmod_test_utils import ( + TEST_ITEMID_MAP, + load_test_resources, + make_dataset, + write_fake_mimic, +) + + +@pytest.fixture(scope="module") +def roots(tmp_path_factory): + """One fake MIMIC folder and PyHealth cache for the whole module. + + Building the event table starts PyHealth's Dask worker processes. That + takes about 3 s, whatever the data size, so the table is built once here. + Each test then makes its own dataset object and task on this cache, which + takes milliseconds. + """ + roots = write_fake_mimic(tmp_path_factory.mktemp("fake_mimic")) + make_dataset(roots).global_event_df.collect() + return roots + + +def test_rows_filtered_before_cache(roots): + df = make_dataset(roots).global_event_df.collect() + items = ( + df.filter(pl.col("event_type") == "chartevents")["chartevents/itemid"] + .unique() + .to_list() + ) + assert "999999" not in items and set(items) == { + "220045", + "220739", + } # non-MedMod itemid dropped early + assert "chartevents/valueuom" not in df.columns + assert df.filter(pl.col("event_type") == "labevents").height == 1 + + +def _lists(tmp_path, test=(), val=()): + """MedMod-style subject lists: "subject_id,1" marks a member.""" + paths = [] + for name, ids in (("test", test), ("val", val)): + f = tmp_path / f"{name}set.csv" + f.write_text("".join(f"{i},1\n" for i in ids) + "99999999,0\n") + paths.append(str(f)) + return paths + + +@pytest.mark.parametrize("hours_zero", ["keep", "drop"]) +def test_set_task_end_to_end_2h_fitted_normalizer(roots, tmp_path, hours_zero): + # Both stays in train: PyHealth fits the binary label processor on the + # training part too, which needs both labels. Train-only fitting with a + # held-out part is tested in test_medmod_mimic4_processor.py. + testset, valset = _lists(tmp_path) + res = MedModResources.load( + itemid_map=TEST_ITEMID_MAP, testset=testset, valset=valset + ) + task = MedModInHospitalMortality( + hours_zero=hours_zero, timestep=2.0, normalizer=None, resources=res + ) + with pytest.warns(UserWarning, match="no samples in split"): # no val, test + train, val, test = make_dataset(roots).set_task( + task, split=MedModSplit(testset=testset, valset=valset), num_workers=1 + ) + assert (len(train), len(val), len(test)) == (2, 0, 0) + got = {train[i]["visit_id"]: train[i] for i in range(2)} + assert set(got) == {"30000001", "30000002"} # 30000003 is a transfer + for stay, label in [("30000001", 0), ("30000002", 1)]: + s = got[stay] + assert tuple(s["ehr"].shape) == (24, 76) and s["ehr"].dtype == torch.float32 + assert float(s["label"].reshape(-1)[0]) == label and s["split"] == "train" + assert s["image_path"].endswith(".jpg") and "/files/p10/" in s["image_path"] + + # The normalizer was learned from these (train) stays: over their bins, + # every standardized column has mean 0. + proc = train.input_processors["ehr"] + assert proc.learns_statistics and proc.normalizer_file is None + cont = task.resources.discretizer.continuous_columns() + x = np.concatenate([np.asarray(s["ehr"], dtype=float) for s in got.values()]) + np.testing.assert_allclose(x[:, cont].mean(axis=0), 0, atol=1e-5) + assert train.fit_split["kind"] == "medmod" + + # Hours == 0 row (HR 120 at intime): mask set only when kept + mask_hr = task.resources.discretizer.output_header().index("mask->Heart Rate") + assert float(got["30000001"]["ehr"][0, mask_hr]) == ( + 1.0 if hours_zero == "keep" else 0.0 + ) + + +def test_set_task_default_is_released_code_settings(roots, tmp_path): + testset, valset = _lists(tmp_path) + task = MedModInHospitalMortality(hours_zero="keep", resources=load_test_resources()) + ds = make_dataset(roots) + with pytest.warns(UserWarning, match="no samples in split"): + train, val, test = ds.set_task( + task, split=MedModSplit(testset=testset, valset=valset), num_workers=1 + ) + samples = [p[i] for p in (train, val, test) for i in range(len(p))] + assert {s["visit_id"] for s in samples} == {"30000001", "30000002"} + proc = train.input_processors["ehr"] + assert not proc.learns_statistics and proc.normalizer_file == str( + PH_NORMALIZER.resolve() + ) + # same numbers as MedMod's own pipeline: the task's raw 1-hour tensor, ph + # normalizer in float64, then float32 + _, ph = medmod_ehr_funcs() + for s in samples: + assert tuple(s["ehr"].shape) == (48, 76) + raws = {r["visit_id"]: r["ehr"] for r in task(ds.get_patient(s["patient_id"]))} + np.testing.assert_array_equal( + np.asarray(s["ehr"]), ph.transform(raws[s["visit_id"]]).astype(np.float32) + ) + + +def test_image_dir_end_to_end(roots, tmp_path): + img_dir = tmp_path / "resized" + img_dir.mkdir() + for d in ("d1", "d2"): + (img_dir / f"{d}.jpg").write_bytes(b"x") + parts = make_dataset(roots).set_task( + MedModInHospitalMortality( + hours_zero="keep", image_dir=img_dir, resources=load_test_resources() + ), + split=PatientSplit(ratios=(1.0, 0.0)), # every stay in train + num_workers=1, + ) + paths = sorted(p[i]["image_path"] for p in parts for i in range(len(p))) + assert paths == [ + str(img_dir.resolve() / "d1.jpg"), + str(img_dir.resolve() / "d2.jpg"), + ] + + (img_dir / "d2.jpg").unlink() + ds = make_dataset(roots) + task = MedModInHospitalMortality( + hours_zero="keep", image_dir=img_dir, resources=load_test_resources() + ) + results = [ + r + for pid in ds.unique_patient_ids + for r in task.process_patient(ds.get_patient(pid)) + ] + chexpert = STAGES.index("cxr_has_chexpert") + assert sum(r.passed >= chexpert for r in results) == 2 + assert sum(r.kept for r in results) == 1 # the stay whose image is gone drops + + +def test_task_validates_its_arguments(tmp_path): + with pytest.raises(ValueError, match="keep"): + MedModInHospitalMortality(hours_zero="maybe") + with pytest.raises(FileNotFoundError, match="image_dir"): + MedModInHospitalMortality(hours_zero="keep", image_dir=tmp_path / "missing") + with pytest.raises(TypeError): + MedModInHospitalMortality("keep") # keyword-only, so the choice is explicit + with pytest.raises(ValueError, match="divide"): + MedModInHospitalMortality(hours_zero="keep", timestep=5.0) + with pytest.raises(FileNotFoundError, match="normalizer"): + MedModInHospitalMortality(hours_zero="keep", normalizer=tmp_path / "none") + t = MedModInHospitalMortality(hours_zero="keep") + assert t.timestep == 1.0 + assert t.input_schema["ehr"][1]["normalizer"].endswith(".normalizer") + t2 = MedModInHospitalMortality(hours_zero="drop", timestep=2.0, normalizer=None) + assert t2.timestep == 2.0 and t2.input_schema["ehr"][1] == {"normalizer": None} + assert t2.hours_zero == "drop" diff --git a/tests/core/test_medmod_mimic4_extraction.py b/tests/core/test_medmod_mimic4_extraction.py new file mode 100644 index 0000000000..dc1bdf8431 --- /dev/null +++ b/tests/core/test_medmod_mimic4_extraction.py @@ -0,0 +1,537 @@ +"""MedMod in-hospital mortality: cohort, labels, cleaning, time series, CXR +pairing and split, on tiny synthetic subjects (no PyHealth dataset build).""" + +from __future__ import annotations + +import numpy as np +import pandas as pd +import pytest + +from pyhealth.datasets.medmod import downloads +from pyhealth.datasets.medmod.discretizer import PH_NORMALIZER, Normalizer +from pyhealth.datasets.medmod.extraction import ( + MEDMOD_DUMMY_ROWS, + STAGES, + MedModResources, + loader_rows, + process_subject, + read_split_file, +) +from pyhealth.datasets.medmod_mimic4 import split_by_medmod, split_positions +from pyhealth.processors.medmod_ehr_processor import MedModEHRProcessor +from tests.core.medmod_test_utils import ( + CRR, + FIO2, + GCS_EYE, + GLUCOSE_LAB, + HADM, + HEIGHT_IN, + HR, + INTIME, + PH_LAB, + SID, + SPO2, + STAY, + TEMP_F, + TEST_ITEMID_MAP, + col, + cxr_row, + load_test_resources, + make_subject, + raw, + run, + stay_row, +) + + +@pytest.fixture(scope="module") +def res(): + return load_test_resources() + + + + +NORMAL_HR = 86.0 # discretizer_config.json normal_values["Heart Rate"] + + +def kept(st, res, hours_zero="keep"): + r = run(st, res, hours_zero)[STAY] + assert r.kept, f"stay dropped after stage {STAGES[r.passed]}" + return r + + +def hr_raw(r, res): + return raw(r.ehr)[:, col(res, "Heart Rate")] + + +def hr_mask(r, res): + return r.ehr[:, col(res, "mask->Heart Rate")] + + +def test_sample_format(res): + r = kept(make_subject(events=[(5.0, HR, "90")]), res) + s = r.sample() + assert set(s) == {"patient_id", "visit_id", "ehr", "image_path", "label", "split"} + # unnormalized float64; MedModEHRProcessor standardizes and casts later + assert s["ehr"].dtype == np.float64 and s["ehr"].shape == (48, 76) + default = process_subject(make_subject(events=[(5.0, HR, "90")]), res)[0] + assert default.ehr.shape == (48, 76) # the released code's 1-hour bins + # 2-hour bins: hour 5.0 lands in bin int(5 / 2 - eps) = 2 + two_hour = run(make_subject(events=[(5.0, HR, "90")]), res, timestep=2.0)[STAY] + assert two_hour.ehr.shape == (24, 76) + assert hr_mask(two_hour, res).nonzero()[0].tolist() == [2] + assert hr_raw(two_hour, res)[2] == 90.0 + assert s["patient_id"] == "10000001" and s["visit_id"] == STAY + assert s["label"] == 0 and s["split"] == "train" + assert s["image_path"].endswith("/s50000001/d1.jpg") + + +def test_event_window_edges(res): + # create_ihm.py:47-48 keeps -eps < t < 48 + eps + r = kept( + make_subject( + events=[(-1 / 60, HR, "50"), (48.0, HR, "120"), (48 + 1 / 60, HR, "130")] + ), + res, + ) + hr, m = hr_raw(r, res), hr_mask(r, res) + assert m[47] == 1 and hr[47] == pytest.approx(120, abs=1e-3) # t == 48 -> last bin + assert m[:47].sum() == 0 # t < 0 dropped + assert hr[0] == pytest.approx( + NORMAL_HR, abs=1e-3 + ) # imputed normal, not the t<0 value + + +def test_stay_with_events_only_outside_window_is_dropped(res): + r = run(make_subject(events=[(-0.5, HR, "80"), (49.0, HR, "80")]), res)[STAY] + assert STAGES[r.passed] == "los_ge_48h" + + +def test_los_edges(res): + ev = [(5.0, HR, "90")] + assert run(make_subject(events=ev, stays=[stay_row(los=2.0)]), res)[STAY].kept + assert run(make_subject(events=ev, stays=[stay_row(los=(48 - 1e-7) / 24)]), res)[ + STAY + ].kept # eps + r = run(make_subject(events=ev, stays=[stay_row(los=47.9 / 24)]), res)[STAY] + assert STAGES[r.passed] == "age_ge_18" + + +def test_cxr_window_edges(res): + ev = [(5.0, HR, "90")] + for hours, ok in [ + (0.0, True), + (48.0, True), + (48 + 1 / 3600, False), + (-1 / 3600, False), + ]: + r = run(make_subject(events=ev, cxr=[cxr_row(hours)]), res)[STAY] + assert r.kept is ok, hours + if not ok: + assert STAGES[r.passed] == "has_diagnosis" + + +def test_cxr_latest_ap_and_chexpert(res): + ev = [(5.0, HR, "90")] + cxr = [ + cxr_row(2, "early", "50000001"), + cxr_row(30, "late", "50000002"), + cxr_row(40, "pa", "50000003", view="PA"), + ] + r = kept(make_subject(events=ev, cxr=cxr, chexpert=("50000001", "50000002")), res) + assert r.dicom_id == "late" # latest AP; the later PA is ignored + # latest AP has no CheXpert row -> stay dropped (no fallback to an earlier image) + r = run(make_subject(events=ev, cxr=cxr, chexpert=("50000001",)), res)[STAY] + assert STAGES[r.passed] == "ap_cxr_in_48h" + + +def test_cxr_tie_takes_last_metadata_row(res): + # Same study, same time: the metadata file lists a study's images in + # ascending dicom_id, so MedMod's tail(1) takes the largest dicom_id, + # whatever order the rows arrive in (PyHealth 2.1.0 does not keep file order). + ev = [(5.0, HR, "90")] + for rows in ( + [cxr_row(10, "aaa"), cxr_row(10, "bbb")], + [cxr_row(10, "bbb"), cxr_row(10, "aaa")], + ): + assert kept(make_subject(events=ev, cxr=rows), res).dicom_id == "bbb" + # Two studies at the same time: the file is sorted by study_id (numeric), + # so the larger one wins. + rows = [cxr_row(10, "zzz", "50000009"), cxr_row(10, "aaa", "50000010")] + st = make_subject(events=ev, cxr=rows, chexpert=("50000009", "50000010")) + assert kept(st, res).dicom_id == "aaa" + # A later image still beats a larger dicom_id. + rows = [cxr_row(11, "aaa"), cxr_row(10, "zzz")] + assert kept(make_subject(events=ev, cxr=rows), res).dicom_id == "aaa" + + +def test_hours_zero_keep_vs_drop(res): + st = make_subject(events=[(0.0, HR, "140"), (1.5, HR, "100")]) + k = kept(st, res, "keep") + d = kept(st, res, "drop") + assert hr_mask(k, res)[0] == 1 and hr_raw(k, res)[0] == pytest.approx(140, abs=1e-3) + assert hr_mask(d, res)[0] == 0 and hr_raw(d, res)[0] == pytest.approx( + NORMAL_HR, abs=1e-3 + ) + assert hr_raw(d, res)[1] == pytest.approx(100, abs=1e-3) + assert not k.used_dummy_rows and not d.used_dummy_rows + + +def test_hours_zero_drop_only_row_at_zero_uses_medmod_dummy(res): + st = make_subject(events=[(0.0, HR, "140")]) + d = kept(st, res, "drop") # cohort unchanged: stay still kept + assert d.used_dummy_rows + expected = res.discretizer.transform(MEDMOD_DUMMY_ROWS, end=48.0) + np.testing.assert_array_equal(d.ehr, expected) + assert hr_raw(d, res)[0] == pytest.approx(109, abs=1e-3) # dummy HR + + +def test_drop_mode_upper_bound_is_full_stay_time(): + rows = [[0.0] + [""] * 17, [10.0] + ["1"] * 17, [48.0] + ["2"] * 17] + out, dummy = loader_rows(rows, "drop", full_stay_hours=96.0) + assert [float(r[0]) for r in out] == [10.0, 48.0] and not dummy + out, _ = loader_rows(rows, "drop", full_stay_hours=48.0) # t == upper is dropped + assert [float(r[0]) for r in out] == [10.0] + out, _ = loader_rows(rows, "keep", full_stay_hours=48.0) + assert [float(r[0]) for r in out] == [0.0, 10.0, 48.0] + + +def test_binning_edges_and_last_value_wins(res): + ev = [ + (0.5, HR, "61"), + (1.0, HR, "62"), # both bin 0 (int(1 - 1e-6) = 0); later wins + (1.0 + 1 / 60, HR, "63"), # bin 1 + (2.1, HR, "70"), + (2.9, HR, "75"), # bin 2, later wins + (47.5, HR, "99"), + ] # bin 47 + r = kept(make_subject(events=ev), res) + hr, m = hr_raw(r, res), hr_mask(r, res) + assert hr[0] == pytest.approx(62, abs=1e-3) + assert hr[1] == pytest.approx(63, abs=1e-3) + assert hr[2] == pytest.approx(75, abs=1e-3) + assert hr[47] == pytest.approx(99, abs=1e-3) + assert m[[0, 1, 2, 47]].tolist() == [1, 1, 1, 1] and m.sum() == 4 + + +def test_same_timestamp_duplicates_keep_medmod_sort_max(res): + # subject.py:59-61 keeps the last value after sorting; values are strings + # here (the GCS text makes pandas read the column as str), so "99" > "100". + ev = [(3.0, HR, "100"), (3.0, HR, "99"), (4.0, GCS_EYE, "To Speech")] + assert hr_raw(kept(make_subject(events=ev), res), res)[3] == pytest.approx( + 99, abs=1e-3 + ) + # all-numeric subject: numeric sort, so 100 wins + ev = [(3.0, HR, "100"), (3.0, HR, "99")] + assert hr_raw(kept(make_subject(events=ev), res), res)[3] == pytest.approx( + 100, abs=1e-3 + ) + + +def test_imputation_normal_then_carry_forward(res): + r = kept(make_subject(events=[(10.5, HR, "120"), (20.5, HR, "80")]), res) + hr, m = hr_raw(r, res), hr_mask(r, res) + np.testing.assert_allclose(hr[:10], NORMAL_HR, atol=1e-3) + np.testing.assert_allclose(hr[10:20], 120, atol=1e-3) + np.testing.assert_allclose(hr[20:], 80, atol=1e-3) + assert np.flatnonzero(m).tolist() == [10, 20] + + +def test_categorical_imputation_carries_one_hot(res): + r = kept(make_subject(events=[(5.5, GCS_EYE, "To Speech")]), res) + eye_cols = [ + col(res, f"Glascow coma scale eye opening->{v}") + for v in res.discretizer._possible_values["Glascow coma scale eye opening"] + ] + block = r.ehr[:, eye_cols] + normal = eye_cols.index(col(res, "Glascow coma scale eye opening->4 Spontaneously")) + speech = eye_cols.index(col(res, "Glascow coma scale eye opening->To Speech")) + assert (block[:5, normal] == 1).all() and block[:5].sum() == 5 + assert (block[5:, speech] == 1).all() and block[5:].sum() == 43 + assert ( + r.ehr[:, col(res, "mask->Glascow coma scale eye opening")].tolist() + == [0] * 5 + [1] + [0] * 42 + ) + + +def test_one_hot_layout_and_masks(res): + h = res.discretizer.output_header() + assert len(h) == 76 + assert len(res.discretizer.continuous_columns()) == 12 + assert sum("->" in x and not x.startswith("mask->") for x in h) == 47 + assert h[59:] == [f"mask->{c}" for c in res.discretizer.channels] + r = kept( + make_subject( + events=[(2.5, GCS_EYE, "None"), (2.5, CRR, "Delayed"), (2.5, HR, "90")] + ), + res, + ) + assert ( + r.ehr[2, col(res, "Glascow coma scale eye opening->None")] == 1 + ) # "None" kept (pandas 1.1.5) + assert r.ehr[2, col(res, "Capillary refill rate->1.0")] == 1 + assert r.ehr[2, col(res, "Capillary refill rate->0.0")] == 0 + onehot = [i for i, x in enumerate(h) if "->" in x and not x.startswith("mask->")] + assert set(np.unique(r.ehr[:, onehot])) <= {0.0, 1.0} + masks = r.ehr[:, 59:] + assert set(np.unique(masks)) <= {0.0, 1.0} + observed = {res.discretizer.channels[j] for j in np.flatnonzero(masks[2])} + assert observed == { + "Glascow coma scale eye opening", + "Capillary refill rate", + "Heart Rate", + } + assert masks[[0, 1, 3]].sum() == 0 + + +def test_unknown_categorical_value_raises_like_medmod(res): + with pytest.raises(ValueError): + run(make_subject(events=[(2.5, GCS_EYE, "Eyes closed")]), res) + + +def test_ehr_is_unnormalized_the_processor_zscores(res): + r = kept(make_subject(events=[(2.5, HR, "90")]), res) + c = col(res, "Heart Rate") + assert r.ehr[2, c] == 90.0 # raw value in the task output + proc = MedModEHRProcessor(PH_NORMALIZER) + z = proc.process(r.ehr).numpy() + expected = (90 - proc.normalizer.means[c]) / proc.normalizer.stds[c] + assert z.dtype == np.float32 and z[2, c] == pytest.approx(expected, rel=1e-5) + assert z[2, col(res, "mask->Heart Rate")] == 1 # masks not normalized + + +def test_value_cleaning_quirks(res): + ev = [ + (2.5, TEMP_F, "98.6"), + (3.5, TEMP_F, "78"), # >= 79 -> Celsius; 78 left alone + (2.5, FIO2, "50"), # every FiO2 / 100 + (2.5, HEIGHT_IN, "70"), # itemid 226707 not converted + (2.5, SPO2, "0.95"), # <= 1 -> * 100 + (2.5, GLUCOSE_LAB, "ERROR", "labevents"), # non-numeric lab -> dropped + (3.5, GLUCOSE_LAB, "130", "labevents"), + (2.5, PH_LAB, "7.31", "labevents"), + ] + r = kept(make_subject(events=ev), res) + x = raw(r.ehr) + assert x[2, col(res, "Temperature")] == pytest.approx(37.0, abs=1e-3) + assert x[3, col(res, "Temperature")] == pytest.approx(78.0, abs=1e-3) + assert x[2, col(res, "Fraction inspired oxygen")] == pytest.approx(0.5, abs=1e-4) + assert x[2, col(res, "Height")] == pytest.approx(70.0, abs=1e-3) + assert x[2, col(res, "Oxygen saturation")] == pytest.approx(95.0, abs=1e-2) + assert r.ehr[2, col(res, "mask->Glucose")] == 0 + assert x[3, col(res, "Glucose")] == pytest.approx(130, abs=1e-2) + assert x[2, col(res, "pH")] == pytest.approx(7.31, abs=1e-4) + + +def test_na_strings_dropped_but_none_kept(res): + r = kept(make_subject(events=[(2.5, HR, "NA"), (3.5, HR, "88")]), res) + assert hr_mask(r, res)[2] == 0 and hr_mask(r, res)[3] == 1 + + +def test_event_assignment(res): + ev = [ + (2.5, HR, "70", "chartevents", STAY), + (3.5, GLUCOSE_LAB, "150", "labevents", None), # no stay_id: recovered from hadm + (4.5, HR, "71", "chartevents", "39999999"), # other stay_id -> dropped + (5.5, GLUCOSE_LAB, "160", "labevents", None, None), + ] # no hadm_id -> dropped + r = kept(make_subject(events=ev), res) + assert r.ehr[3, col(res, "mask->Glucose")] == 1 + assert r.ehr[4, col(res, "mask->Heart Rate")] == 0 + assert r.ehr[5, col(res, "mask->Glucose")] == 0 + + +def test_cohort_filters(res): + ev = [(5.0, HR, "90")] + r = run(make_subject(events=ev, stays=[stay_row(first="MICU", last="SICU")]), res)[ + STAY + ] + assert STAGES[r.passed] == "icustays" + r = run(make_subject(events=ev, anchor_age="17"), res)[STAY] + assert STAGES[r.passed] == "one_stay_per_admission" + r = run(make_subject(events=ev, diagnoses=()), res)[STAY] + assert STAGES[r.passed] == "event_in_48h" + + +def test_one_stay_per_admission_counted_after_transfer_filter(res): + ev = [(5.0, HR, "90")] + second = stay_row( + stay="30000002", intime=INTIME + pd.Timedelta(days=5), first="CCU", last="SICU" + ) + out = run(make_subject(events=ev, stays=[stay_row(), second]), res) + assert out[STAY].kept # the other stay was a transfer, removed first + third = stay_row(stay="30000003", intime=INTIME + pd.Timedelta(days=5)) + out = run(make_subject(events=ev, stays=[stay_row(), third]), res) + assert STAGES[out[STAY].passed] == "has_admission_and_patient" + assert STAGES[out["30000003"].passed] == "has_admission_and_patient" + + +def test_labels(res): + ev = [(5.0, HR, "90")] + + def adm(death): + return [ + { + "hadm_id": HADM, + "admittime": INTIME - pd.Timedelta(hours=2), + "dischtime": str(INTIME + pd.Timedelta(days=8)), + "deathtime": death, + } + ] + + assert ( + kept( + make_subject(events=ev, admissions=adm(str(INTIME + pd.Timedelta(days=8)))), + res, + ).label + == 1 + ) + assert ( + kept(make_subject(events=ev, dod=str(INTIME + pd.Timedelta(days=3))), res).label + == 1 + ) + assert ( + kept( + make_subject(events=ev, dod=str(INTIME + pd.Timedelta(days=30))), res + ).label + == 0 + ) + + +def test_split_assignment(res): + ev = [(5.0, HR, "90")] + assert kept(make_subject(sid="10000002", events=ev), res).split == "test" + assert kept(make_subject(sid="10000003", events=ev), res).split == "val" + assert kept(make_subject(sid="10000004", events=ev), res).split == "train" + + +def test_split_file_parsing(tmp_path): + p = tmp_path / "t.csv" + p.write_text("111,0\n222,1\n333,1\n") + assert read_split_file(p) == {"222", "333"} + + +def test_resources_read_files_lazily(tmp_path, monkeypatch): + def no_network(*args, **kwargs): + raise AssertionError("downloaded") + + monkeypatch.setattr(downloads.urllib.request, "urlopen", no_network) + r = MedModResources.load() # no file needed yet: no download + assert r.sources["testset"].startswith("medmod@") + assert r.sources["itemid_map"].startswith("medmod@") + r = MedModResources.load(itemid_map=TEST_ITEMID_MAP) + assert len(r.itemids) == 10 and int(HR) in r.itemids # the test copy's rows + (tmp_path / "t.csv").write_text("111,1\n222,0\n") + (tmp_path / "v.csv").write_text("333,1\n") + r = MedModResources.load(testset=tmp_path / "t.csv", valset=tmp_path / "v.csv") + assert r.test_subjects == {"111"} and r.val_subjects == {"333"} + + +def test_normalizer_fit_matches_medmod_formula(): + rng = np.random.default_rng(0) + arrays = [rng.normal(3, 2, size=(int(rng.integers(1, 9)), 5)) for _ in range(30)] + arrays[0][:, 4] = 7.0 + norm = Normalizer(fields=[0, 1, 4]).fit(iter(arrays)) # streamed, like PyHealth + stacked = np.concatenate(arrays) + np.testing.assert_allclose(norm.means, stacked.mean(axis=0)) + np.testing.assert_allclose(norm.stds[:4], stacked.std(axis=0, ddof=1)[:4]) + x = arrays[1] + assert np.array_equal(norm.transform(x)[:, 2:4], x[:, 2:4]) # not in fields + assert " at 0x" not in repr(norm) and "sha256:" in repr(norm) + + +def test_normalizer_fit_constant_column_gets_the_floor_not_nan(): + x = np.full((7, 2), 0.1) # 0.1 is inexact in binary: var rounds below 0 + x[:, 1] = 97.3 + norm = Normalizer().fit([x[:3], x[3:]]) + assert np.all(np.isfinite(norm.stds)) and norm.stds[0] == 1e-7 + + +# --------------------------------------------------------- image_dir + + +def test_image_path_without_image_dir_is_pyhealth_path(res): + r = run(make_subject(events=[(5.0, HR, "90")]), res)[STAY] + assert r.kept + assert r.image_path == f"/cxr/files/p10/p{SID}/s50000001/d1.jpg" + + +def test_image_path_with_image_dir(res, tmp_path): + (tmp_path / "d1.jpg").write_bytes(b"x") + r = run(make_subject(events=[(5.0, HR, "90")]), res, image_dir=tmp_path)[STAY] + assert r.kept + assert r.image_path == str(tmp_path / "d1.jpg") + assert r.sample()["image_path"] == str(tmp_path / "d1.jpg") + + +def test_missing_resized_file_drops_stay_and_is_counted(res, tmp_path): + ev = [(5.0, HR, "90")] + (tmp_path / "d1.jpg").write_bytes(b"x") # only subject 1's image was resized + results = [] + for sid, dicom in [("10000001", "d1"), ("10000004", "d4")]: + st = make_subject(sid=sid, events=ev, cxr=[cxr_row(10.0, dicom)]) + results += list(run(st, res, image_dir=tmp_path).values()) + by_sid = {r.subject_id: r for r in results} + assert by_sid["10000001"].kept + missing = by_sid["10000004"] + assert not missing.kept and missing.image_path is None and missing.ehr is None + assert ( + STAGES[missing.passed] == "cxr_has_chexpert" + ) # dropped at resized_image_found + chexpert = STAGES.index("cxr_has_chexpert") + assert sum(r.passed >= chexpert for r in results) == 2 + assert sum(r.kept for r in results) == 1 # passed resized_image_found + + +def test_no_fallback_to_older_resized_image(res, tmp_path): + (tmp_path / "early.jpg").write_bytes(b"x") # only the older image exists + cxr = [cxr_row(2.0, "early", "50000001"), cxr_row(30.0, "late", "50000002")] + st = make_subject( + events=[(5.0, HR, "90")], cxr=cxr, chexpert=("50000001", "50000002") + ) + r = run(st, res, image_dir=tmp_path)[STAY] + assert not r.kept and r.dicom_id == "late" + + +def test_without_image_dir_new_stage_is_passed_automatically(res): + results = list(run(make_subject(events=[(5.0, HR, "90")]), res).values()) + assert len(results) == 1 and results[0].kept + assert results[0].passed == STAGES.index("resized_image_found") + + +# ------------------------------------------------------------- split + + +def test_split_positions_keep_sample_order_and_reject_unknown_splits(): + out = split_positions(["train", "test", "train", "val", "test"]) + assert out == {"train": [0, 2], "val": [3], "test": [1, 4]} + assert split_positions([]) == {"train": [], "val": [], "test": []} + with pytest.raises(ValueError, match="unknown split"): + split_positions(["train", "holdout"]) + + +def test_split_by_medmod_returns_subset_views_like_pyhealth(): + class FakeSamples: # the two methods split_by_medmod uses + def __init__(self, splits): + self.splits = splits + + def __len__(self): + return len(self.splits) + + def __getitem__(self, i): + return {"split": self.splits[i]} + + def subset(self, indices): + return [self.splits[i] for i in indices] + + train, val, test = split_by_medmod(FakeSamples(["test", "train", "val", "train"])) + assert (train, val, test) == (["train", "train"], ["val"], ["test"]) + with pytest.warns(UserWarning, match="no samples"): + train, val, test = split_by_medmod(FakeSamples(["train", "train"])) + assert (len(train), len(val), len(test)) == (2, 0, 0) + + +def test_resources_repr_is_short_and_stable(): + a, b = repr(MedModResources.load()), repr(MedModResources.load()) + assert a == b and "medmod@7a47c0b:itemid_to_variable_map.csv" in a + assert "DataFrame" not in a and " at 0x" not in a and len(a) < 600 diff --git a/tests/core/test_medmod_mimic4_processor.py b/tests/core/test_medmod_mimic4_processor.py new file mode 100644 index 0000000000..333d517395 --- /dev/null +++ b/tests/core/test_medmod_mimic4_processor.py @@ -0,0 +1,183 @@ +"""MedMod in-hospital mortality: MedModSplit (a PyHealth Split) and +MedModEHRProcessor (MedMod's normalizer file, or one fitted on the train split).""" + +from __future__ import annotations + +import hashlib +import json +from pathlib import Path + +import numpy as np +import pytest +import torch + +from pyhealth.datasets.medmod import downloads as sl +from pyhealth.datasets.medmod.discretizer import ( + PH_NORMALIZER, + Normalizer, + medmod_ehr_funcs, +) +from pyhealth.datasets.medmod_mimic4 import MedModSplit +from pyhealth.datasets.sample_dataset import SampleBuilder +from pyhealth.processors.medmod_ehr_processor import ( + MedModEHRProcessor, + MedModEHRSequenceProcessor, +) + +DISC, PH = medmod_ehr_funcs() +CONT = DISC.continuous_columns() + + +def lists(tmp_path, test=(), val=()): + out = [] + for name, ids in (("test", test), ("val", val)): + f = tmp_path / f"{name}set.csv" + f.write_text("".join(f"{i},1\n" for i in ids) + "99999999,0\n") + out.append(str(f)) + return out + + +def raw_ehr(rng, bins=24, shift=0.0): + x = np.zeros((bins, 76)) + x[:, CONT] = rng.normal(50 + shift, 10, size=(bins, len(CONT))) + return x + + +def test_medmod_split_follows_the_lists(tmp_path): + testset, valset = lists(tmp_path, test=["2"], val=["3", "2"]) + split = MedModSplit(testset=testset, valset=valset) + parts = split.split_indices({"1": [0, 4], "2": [1], "3": [3], "5": [2]}) + # test wins over val, like MedMod (test list first, then val among the rest) + assert [p.tolist() for p in parts] == [[0, 2, 4], [3], [1]] + assert all(p.dtype == np.int64 for p in parts) + + before = split.to_dict() + Path(valset).write_text("3,1\n") + assert split.to_dict() != before # cache key follows the list contents + assert before["kind"] == "medmod" + + +class _Response: + def __init__(self, data: bytes): + self.data = data + + def read(self) -> bytes: + return self.data + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + +def test_split_list_download_checksum_cache_and_fallback(tmp_path, monkeypatch): + good = b"111,1\n222,0\n" + monkeypatch.setitem(sl.SHA256, "testset_iv.csv", hashlib.sha256(good).hexdigest()) + calls = [] + + def fake_urlopen(url, timeout): + calls.append(url) + if "/MedMod/" in url: + raise OSError("offline") # first source fails: falls back to MedFuse + return _Response(good) + + monkeypatch.setattr(sl.urllib.request, "urlopen", fake_urlopen) + path = sl.medmod_file_path("testset_iv.csv", cache_dir=tmp_path) + assert path.read_bytes() == good and len(calls) == 2 + assert all(sl.MEDMOD_COMMIT in u or sl.MEDFUSE_COMMIT in u for u in calls) + sl.medmod_file_path("testset_iv.csv", cache_dir=tmp_path) # cached + assert len(calls) == 2 + + path.write_bytes(b"tampered") # a bad cache is fetched again, and checked + monkeypatch.setattr( + sl.urllib.request, "urlopen", lambda url, timeout: _Response(b"wrong") + ) + with pytest.raises(OSError, match="SHA-256"): + sl.medmod_file_path("testset_iv.csv", cache_dir=tmp_path) + assert not list(tmp_path.glob("*.partial")) + + +def test_default_medmod_split_cache_key_needs_no_download(monkeypatch): + def no_network(*args, **kwargs): + raise AssertionError("downloaded") + + monkeypatch.setattr(sl.urllib.request, "urlopen", no_network) + key = MedModSplit().to_dict() + assert key["testset_sha256"] == sl.SHA256["testset_iv.csv"][:16] + assert key["valset_sha256"] == sl.SHA256["valset_iv.csv"][:16] + + +def test_processor_is_fitted_on_the_train_split_only(tmp_path): + """PyHealth's SampleBuilder with MedModSplit, as set_task does it.""" + rng = np.random.default_rng(0) + testset, valset = lists(tmp_path, test=["t1", "t2"], val=["v1"]) + samples, train_arrays = [], [] + for pid, split, shift, label in [ + ("a", "train", 0, 0), ("b", "train", 0, 1), ("c", "train", 0, 0), + ("v1", "val", 30, 1), ("t1", "test", 60, 0), ("t2", "test", 60, 1), + ]: # fmt: skip + x = raw_ehr(rng, shift=shift) + samples.append({"patient_id": pid, "ehr": x, "label": label, "split": split}) + if split == "train": + train_arrays.append(x) + + builder = SampleBuilder( + input_schema={"ehr": (MedModEHRProcessor, {"normalizer": None})}, + output_schema={"label": "binary"}, + ) + builder.fit(samples, split=MedModSplit(testset=testset, valset=valset)) + proc = builder.input_processors["ehr"] + want = Normalizer(fields=CONT).fit(train_arrays) + np.testing.assert_array_equal(proc.normalizer.means, want.means) + np.testing.assert_array_equal(proc.normalizer.stds, want.stds) + everyone = Normalizer(fields=CONT).fit(s["ehr"] for s in samples) + assert not np.allclose(proc.normalizer.means[CONT], everyone.means[CONT]) + assert [p.tolist() for p in builder.split_indices] == [[0, 1, 2], [3], [4, 5]] + + +def test_processor_output_matches_medmods_arithmetic(): + """float64 z-score, then float32 (MedMod's .float()): what the released-code + samples always were, so they still match MedMod's own extraction.""" + rng = np.random.default_rng(1) + x = raw_ehr(rng, bins=48) + proc = MedModEHRProcessor(PH_NORMALIZER) + got = proc.process(x) + assert got.dtype.is_floating_point and got.dtype.itemsize == 4 + np.testing.assert_array_equal(got.numpy(), PH.transform(x).astype(np.float32)) + assert not proc.learns_statistics # a fixed file learns nothing + proc.fit([{"ehr": raw_ehr(rng)}], "ehr") # no-op + np.testing.assert_array_equal(proc.process(x).numpy(), got.numpy()) + + +def test_processor_cache_key_is_stable(): + """With pre-fitted processors PyHealth keys its cache on + json.dumps(vars(processor), default=str) (BaseDataset.set_task).""" + def key(p): + return json.dumps(vars(p), default=str, sort_keys=True) + + a, b = MedModEHRProcessor(PH_NORMALIZER), MedModEHRProcessor(PH_NORMALIZER) + assert key(a) == key(b) and " at 0x" not in key(a) + fitted = MedModEHRProcessor() + fitted.fit([{"ehr": raw_ehr(np.random.default_rng(2))}], "ehr") + assert "sha256:" in key(fitted) and " at 0x" not in key(fitted) + assert fitted.schema() == ("value",) and fitted.dim() == (2,) + assert fitted.is_token() is False + + +def test_sequence_processor_pads_at_the_end_and_returns_lengths(): + rng = np.random.default_rng(3) + seq = MedModEHRSequenceProcessor(PH_NORMALIZER) + raw = [rng.normal(size=(n, 76)) for n in (4, 9, 1)] + values = [seq.process(x) for x in raw] + # each stay standardized exactly as the fixed-length processor does + fixed = MedModEHRProcessor(PH_NORMALIZER) + for v, x in zip(values, raw): + assert torch.equal(v, fixed.process(x)) + ehr, lengths = seq.collate(values) + assert lengths.tolist() == [4, 9, 1] and lengths.dtype == torch.long + assert tuple(ehr.shape) == (3, 9, 76) and ehr.dtype == torch.float32 + for i, n in enumerate((4, 9, 1)): # MedMod pad_zeros: zeros after the stay + assert torch.equal(ehr[i, :n], values[i]) + assert not ehr[i, n:].any() + assert seq.schema() == ("value", "lengths") From bd7661804f2a4f32fe615cb3cb1fc62b542060cf Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:33:33 -0500 Subject: [PATCH 2/4] Address the AI review of part 1: task docs and item-map cache The task page now says the image transform belongs to the model's image loader; the task returns image_path only. A custom itemid_map adds a digest of its file to dataset_name, so each map gets its own PyHealth cache, with a test that builds two maps on one cache_dir. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- ...health.tasks.MedModInHospitalMortality.rst | 8 +++++--- pyhealth/datasets/medmod_mimic4.py | 13 +++++++++--- tests/core/test_medmod_mimic4_dataset.py | 20 ++++++++++++++++++- 3 files changed, 34 insertions(+), 7 deletions(-) diff --git a/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst index f3f58ed3b4..a77e3539f0 100644 --- a/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst +++ b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst @@ -19,9 +19,11 @@ and ``label``. Use it with :class:`~pyhealth.datasets.MedModMIMIC4Dataset`. Per-model settings ------------------ -MedMod's models read their data through two code paths, and the task -reproduces each. Both use the same cohort, labels and split; only the EHR rows -at Hours == 0 and the image transform differ. +MedMod's models read their data through two code paths. Both use the same +cohort, labels and split. They differ in the EHR rows at Hours == 0, which the +task sets with ``hours_zero``, and in the image transform. The task returns +``image_path`` and applies no image transform: the "Image transform" column is +what the model's own image loader applies. .. list-table:: :header-rows: 1 diff --git a/pyhealth/datasets/medmod_mimic4.py b/pyhealth/datasets/medmod_mimic4.py index f81101bac6..696b14548a 100644 --- a/pyhealth/datasets/medmod_mimic4.py +++ b/pyhealth/datasets/medmod_mimic4.py @@ -117,7 +117,9 @@ class MedModMIMIC4Dataset(MIMIC4Dataset): ``dataset_name`` is part of PyHealth's cache key (``BaseDataset._init_cache_dir``), so this cache never mixes with an - unfiltered ``MIMIC4Dataset`` cache. + unfiltered ``MIMIC4Dataset`` cache. The key does not cover the item map, + so a custom ``itemid_map`` adds a digest of its file to ``dataset_name``: + each map gets its own cache. Args: ehr_root: folder holding ``core/``, ``hosp/``, ``icu/`` (MIMIC-IV v1.0). @@ -125,7 +127,8 @@ class MedModMIMIC4Dataset(MIMIC4Dataset): cache_dir: where PyHealth writes its processed copy of the data. Put it next to the data; without it PyHealth uses its default cache folder. itemid_map: MedMod's ``itemid_to_variable_map.csv``. Without it, the - file is downloaded from MedMod's GitHub on first use. + file is downloaded from MedMod's GitHub on first use. A custom map + gets its own cache. Examples: >>> from pyhealth.datasets import MedModMIMIC4Dataset @@ -148,13 +151,17 @@ def __init__( ): ehr_root, cxr_root = os.fspath(ehr_root), os.fspath(cxr_root) cfg = os.fspath(ehr_config_path) + # The default map is pinned and SHA-256 checked, so it needs no digest. + dataset_name = "medmod_mimic4" + if itemid_map is not None: + dataset_name += f"_{_digest(itemid_map)}" super().__init__( ehr_root=ehr_root, cxr_root=cxr_root, ehr_tables=list(EHR_TABLES), cxr_tables=list(CXR_TABLES), ehr_config_path=cfg, - dataset_name="medmod_mimic4", + dataset_name=dataset_name, dev=dev, cache_dir=None if cache_dir is None else os.fspath(cache_dir), num_workers=num_workers, diff --git a/tests/core/test_medmod_mimic4_dataset.py b/tests/core/test_medmod_mimic4_dataset.py index e01a6eaf24..9537f9efd1 100644 --- a/tests/core/test_medmod_mimic4_dataset.py +++ b/tests/core/test_medmod_mimic4_dataset.py @@ -8,7 +8,7 @@ import pytest import torch -from pyhealth.datasets import MedModSplit, PatientSplit +from pyhealth.datasets import MedModMIMIC4Dataset, MedModSplit, PatientSplit from pyhealth.datasets.medmod.discretizer import PH_NORMALIZER, medmod_ehr_funcs from pyhealth.datasets.medmod.extraction import STAGES, MedModResources from pyhealth.tasks import MedModInHospitalMortality @@ -49,6 +49,24 @@ def test_rows_filtered_before_cache(roots): assert df.filter(pl.col("event_type") == "labevents").height == 1 +def test_custom_item_map_gets_its_own_cache(roots, tmp_path): + # PyHealth's cache key has no item map, so a dataset with another map must + # not reuse the table the first map filtered. + ehr, cxr, cache = roots + lines = TEST_ITEMID_MAP.read_text().splitlines(keepends=True) + smaller = tmp_path / "itemid_map_without_220739.csv" + smaller.write_text("".join(line for line in lines if ",220739," not in line)) + other = MedModMIMIC4Dataset( + ehr_root=ehr, cxr_root=cxr, cache_dir=cache, num_workers=1, itemid_map=smaller + ) + assert other.cache_dir != make_dataset(roots).cache_dir + df = other.global_event_df.collect() + items = df.filter(pl.col("event_type") == "chartevents")["chartevents/itemid"] + assert set(items.unique().to_list()) == {"220045"} + default = MedModMIMIC4Dataset(ehr_root=ehr, cxr_root=cxr, cache_dir=cache) + assert default.dataset_name == "medmod_mimic4" # pinned map, no digest + + def _lists(tmp_path, test=(), val=()): """MedMod-style subject lists: "subject_id,1" marks a member.""" paths = [] From f6d0cfc56148d250dbff9311c0e2e76d59e2e636 Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:51:15 -0500 Subject: [PATCH 3/4] Check that the task's item ids are in the dataset's item map The dataset drops events outside its item map before caching, so a task whose item map has other ids would silently miss their events. set_task now raises a ValueError naming them, with a test. This is the second half of the AI review's item-map comment. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- pyhealth/datasets/medmod_mimic4.py | 43 ++++++++++++++++++++++++ tests/core/test_medmod_mimic4_dataset.py | 28 +++++++++++++-- 2 files changed, 68 insertions(+), 3 deletions(-) diff --git a/pyhealth/datasets/medmod_mimic4.py b/pyhealth/datasets/medmod_mimic4.py index 696b14548a..76a644fd4d 100644 --- a/pyhealth/datasets/medmod_mimic4.py +++ b/pyhealth/datasets/medmod_mimic4.py @@ -44,6 +44,7 @@ from collections.abc import Iterable, Mapping, Sequence from dataclasses import dataclass from pathlib import Path +from typing import TYPE_CHECKING, Any import narwhals as nw import numpy as np @@ -58,6 +59,9 @@ from .sample_dataset import SampleDataset from .splitter import Split +if TYPE_CHECKING: + from ..tasks.base_task import BaseTask + EHR_V10_CONFIG = Path(__file__).resolve().parent / "configs" / "mimic4_ehr_v1.0.yaml" EHR_TABLES = ("chartevents", "labevents", "diagnoses_icd") CXR_TABLES = ("metadata", "chexpert") @@ -179,6 +183,45 @@ def __init__( if itemid_map is not None: self.sub_datasets["ehr"].itemid_map = os.fspath(itemid_map) + def set_task( + self, task: BaseTask | None = None, *args: Any, **kwargs: Any + ) -> SampleDataset | tuple[SampleDataset, ...]: + """Runs PyHealth's ``set_task`` after checking the task's item map. + + The dataset drops events outside its own item map before caching, so a + MedMod task with item ids outside that map would silently miss their + events. This raises an error instead. + + Args: + task: The task, usually ``MedModInHospitalMortality``. + *args: Passed on to ``BaseDataset.set_task``. + **kwargs: Passed on to ``BaseDataset.set_task``. + + Returns: + What ``BaseDataset.set_task`` returns. + + Raises: + ValueError: If some of the task's item ids are not in the dataset's + item map. + + Examples: + >>> train, val, test = dataset.set_task( # doctest: +SKIP + ... task, split=MedModSplit() + ... ) + """ + resources = getattr(task, "resources", None) + if resources is not None: + kept = set(_ready_itemids(self.sub_datasets["ehr"].itemid_map)) + missing = sorted({str(i) for i in resources.itemids} - kept) + if missing: + raise ValueError( + f"{len(missing)} item ids of the task are not in this " + f"dataset's itemid_map, so their events were dropped before " + f"caching (first: {missing[:5]}). Use the same item map for " + "the dataset and the task." + ) + return super().set_task(task, *args, **kwargs) + SPLITS = ("train", "val", "test") diff --git a/tests/core/test_medmod_mimic4_dataset.py b/tests/core/test_medmod_mimic4_dataset.py index 9537f9efd1..b6a0b88fb0 100644 --- a/tests/core/test_medmod_mimic4_dataset.py +++ b/tests/core/test_medmod_mimic4_dataset.py @@ -49,13 +49,19 @@ def test_rows_filtered_before_cache(roots): assert df.filter(pl.col("event_type") == "labevents").height == 1 +def _map_without_220739(tmp_path): + """The test item map without item 220739.""" + lines = TEST_ITEMID_MAP.read_text().splitlines(keepends=True) + smaller = tmp_path / "itemid_map_without_220739.csv" + smaller.write_text("".join(line for line in lines if ",220739," not in line)) + return smaller + + def test_custom_item_map_gets_its_own_cache(roots, tmp_path): # PyHealth's cache key has no item map, so a dataset with another map must # not reuse the table the first map filtered. ehr, cxr, cache = roots - lines = TEST_ITEMID_MAP.read_text().splitlines(keepends=True) - smaller = tmp_path / "itemid_map_without_220739.csv" - smaller.write_text("".join(line for line in lines if ",220739," not in line)) + smaller = _map_without_220739(tmp_path) other = MedModMIMIC4Dataset( ehr_root=ehr, cxr_root=cxr, cache_dir=cache, num_workers=1, itemid_map=smaller ) @@ -67,6 +73,22 @@ def test_custom_item_map_gets_its_own_cache(roots, tmp_path): assert default.dataset_name == "medmod_mimic4" # pinned map, no digest +def test_task_item_ids_must_be_in_the_dataset_map(roots, tmp_path): + # The dataset dropped item 220739 before caching, so a task that reads it + # would silently miss its events. + ehr, cxr, cache = roots + dataset = MedModMIMIC4Dataset( + ehr_root=ehr, + cxr_root=cxr, + cache_dir=cache, + num_workers=1, + itemid_map=_map_without_220739(tmp_path), + ) + task = MedModInHospitalMortality(hours_zero="keep", resources=load_test_resources()) + with pytest.raises(ValueError, match=r"\['220739'\]"): + dataset.set_task(task) + + def _lists(tmp_path, test=(), val=()): """MedMod-style subject lists: "subject_id,1" marks a member.""" paths = [] From cfbc18fa8b1c49587b8b6d4867400f1c78e89708 Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:52:59 -0500 Subject: [PATCH 4/4] Build the MedMod test event table without a Dask cluster Starting and stopping PyHealth's local Dask cluster took about 5 s per event-table build on 28 fake rows. The dataset tests now run the same Dask graph in the test process, and the custom item map test checks its cache key and row filter without a second build. The slowest step is now the module's one shared build (about 1.7 s); every test takes under 0.5 s. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- tests/core/medmod_test_utils.py | 44 ++++++++++++++++++++++++ tests/core/test_medmod_mimic4_dataset.py | 24 ++++++++----- 2 files changed, 60 insertions(+), 8 deletions(-) diff --git a/tests/core/medmod_test_utils.py b/tests/core/medmod_test_utils.py index b46997312b..708a0bc13c 100644 --- a/tests/core/medmod_test_utils.py +++ b/tests/core/medmod_test_utils.py @@ -9,8 +9,11 @@ from __future__ import annotations +from contextlib import contextmanager from pathlib import Path +from unittest.mock import patch +import dask import numpy as np import pandas as pd @@ -383,3 +386,44 @@ def make_dataset(roots): num_workers=1, itemid_map=TEST_ITEMID_MAP, ) + + +class _SynchronousClient: + """Stands in for ``distributed.Client``: runs the Dask graph in this + process with Dask's synchronous scheduler.""" + + def __init__(self, cluster): + pass + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def compute(self, collection): + dask.compute(collection, scheduler="synchronous") + return self + + def result(self): + return None + + +@contextmanager +def synchronous_dask(): + """Builds PyHealth's event table without a Dask cluster. + + Starting and stopping PyHealth's local Dask cluster takes about 5 s per + build, whatever the data size; the fake tables here have 28 rows. The + same Dask graph (CSV reading, the MedMod row filters, sorting and the + Parquet cache) still runs, only in this process. + """ + with patch("pyhealth.datasets.base_dataset.DaskCluster", lambda **kwargs: _null()), \ + patch("pyhealth.datasets.base_dataset.DaskClient", _SynchronousClient), \ + patch("pyhealth.datasets.base_dataset.dask_progress", lambda *a, **k: None): + yield + + +@contextmanager +def _null(): + yield None diff --git a/tests/core/test_medmod_mimic4_dataset.py b/tests/core/test_medmod_mimic4_dataset.py index b6a0b88fb0..79a9342f1a 100644 --- a/tests/core/test_medmod_mimic4_dataset.py +++ b/tests/core/test_medmod_mimic4_dataset.py @@ -3,6 +3,7 @@ from __future__ import annotations +import narwhals as nw import numpy as np import polars as pl import pytest @@ -16,6 +17,7 @@ TEST_ITEMID_MAP, load_test_resources, make_dataset, + synchronous_dask, write_fake_mimic, ) @@ -24,13 +26,13 @@ def roots(tmp_path_factory): """One fake MIMIC folder and PyHealth cache for the whole module. - Building the event table starts PyHealth's Dask worker processes. That - takes about 3 s, whatever the data size, so the table is built once here. - Each test then makes its own dataset object and task on this cache, which - takes milliseconds. + The event table is built once here, without a Dask cluster (see + ``synchronous_dask``). Each test then makes its own dataset object and + task on this cache, which takes milliseconds. """ roots = write_fake_mimic(tmp_path_factory.mktemp("fake_mimic")) - make_dataset(roots).global_event_df.collect() + with synchronous_dask(): + make_dataset(roots).global_event_df.collect() return roots @@ -66,9 +68,15 @@ def test_custom_item_map_gets_its_own_cache(roots, tmp_path): ehr_root=ehr, cxr_root=cxr, cache_dir=cache, num_workers=1, itemid_map=smaller ) assert other.cache_dir != make_dataset(roots).cache_dir - df = other.global_event_df.collect() - items = df.filter(pl.col("event_type") == "chartevents")["chartevents/itemid"] - assert set(items.unique().to_list()) == {"220045"} + # Its own row filter drops 220739 (checked on a small frame, so no second + # event table is built). + rows = nw.from_native(pl.LazyFrame({ + "itemid": ["220045", "220739", "999999"], + "hadm_id": ["1", "1", "1"], + "value": ["80", "4", "1"], + })) + kept = other.sub_datasets["ehr"].preprocess_chartevents(rows).collect() + assert kept["itemid"].to_list() == ["220045"] default = MedModMIMIC4Dataset(ehr_root=ehr, cxr_root=cxr, cache_dir=cache) assert default.dataset_name == "medmod_mimic4" # pinned map, no digest