From ea86bd4046f6eb4368094e24c6a7643216ff785c 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/8] 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 8b19949c70..40be5ca82d 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -668,6 +668,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 9796b94ed0..745f6622f6 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -266,6 +266,7 @@ Available Tasks LabTOP Lab Value Prediction (HiRID) 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 c82e00a02d..3429727c49 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -142,6 +142,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 abf5ac8258..8a3e680a78 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -420,6 +420,13 @@ ShortTermSurvivalMIMIC3 as ShortTermSurvivalMIMIC3, ) +# 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 3a7fb4ac0dd794718d56e4bb457e60635716c80f 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/8] 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 c0f7ba7fd6309922bf6de7413507720d2526a39f 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/8] 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 08519db110dea5f90d8cff360afa6790625bbc9b 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/8] 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 From 71846738a2609a0cde56befafc56c4afbdc9ae8a 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 5/8] Add MedMod image tools, synthetic data, MedSigLIP embeddings and examples Part 3 of 4 of sunlabuiuc/PyHealth#1609. Builds on parts 1 and 2. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- .../pyhealth.datasets.MedModMIMIC4Dataset.rst | 33 ++ ...health.tasks.MedModInHospitalMortality.rst | 7 +- examples/README.md | 2 + examples/mimic4_medmod_convirt.py | 362 ++++++++++++++ examples/mimic4_medmod_ihm_early_fusion.py | 292 +++++++++++ examples/mimic4_medmod_ihm_results.md | 357 ++++++++++++++ pyhealth/datasets/medmod/__init__.py | 5 + pyhealth/datasets/medmod/files/NOTICE | 7 +- pyhealth/datasets/medmod/image_presets.py | 274 ++++++++++ pyhealth/datasets/medmod/medsiglip.py | 446 +++++++++++++++++ pyhealth/datasets/medmod/pretraining.py | 288 +++++++++++ pyhealth/datasets/medmod/resize_cxr.py | 245 +++++++++ pyhealth/datasets/medmod/synthetic.py | 466 ++++++++++++++++++ pyhealth/datasets/medmod_mimic4.py | 6 +- pyhealth/tasks/medmod_mortality_mimic4.py | 4 +- tests/core/test_medmod_medsiglip.py | 86 ++++ tests/core/test_medmod_mimic4_images.py | 176 +++++++ tests/core/test_medmod_mimic4_synthetic.py | 180 +++++++ tests/core/test_medmod_pretraining.py | 135 +++++ 19 files changed, 3362 insertions(+), 9 deletions(-) create mode 100644 examples/mimic4_medmod_convirt.py create mode 100644 examples/mimic4_medmod_ihm_early_fusion.py create mode 100644 examples/mimic4_medmod_ihm_results.md create mode 100644 pyhealth/datasets/medmod/image_presets.py create mode 100644 pyhealth/datasets/medmod/medsiglip.py create mode 100644 pyhealth/datasets/medmod/pretraining.py create mode 100644 pyhealth/datasets/medmod/resize_cxr.py create mode 100644 pyhealth/datasets/medmod/synthetic.py create mode 100644 tests/core/test_medmod_medsiglip.py create mode 100644 tests/core/test_medmod_mimic4_images.py create mode 100644 tests/core/test_medmod_mimic4_synthetic.py create mode 100644 tests/core/test_medmod_pretraining.py diff --git a/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst b/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst index d1bda5191e..20804c69eb 100644 --- a/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst +++ b/docs/api/datasets/pyhealth.datasets.MedModMIMIC4Dataset.rst @@ -12,6 +12,8 @@ with MedMod's fixed train / val / test split. Use it with Access to `MIMIC-IV v1.0 `__ and `MIMIC-CXR-JPG 2.0.0 `__ needs PhysioNet credentialing. +Without it, ``pyhealth.datasets.medmod.synthetic.create_synthetic_samples`` +builds synthetic samples with the same contract. .. autoclass:: pyhealth.datasets.MedModMIMIC4Dataset :members: @@ -24,3 +26,34 @@ needs PhysioNet credentialing. :show-inheritance: .. autofunction:: pyhealth.datasets.split_by_medmod + +MedSigLIP image embeddings +-------------------------- + +For the extension, :mod:`pyhealth.datasets.medmod.medsiglip` replaces the +ResNet-34 image features with those of a frozen ``google/medsiglip-448`` +image encoder. Each image is embedded once and saved to one ``.npz`` file, +where the embeddings are looked up by image file name. + +MedSigLIP (`google/medsiglip-448 `__) +is introduced in Sellergren et al., "MedGemma Technical Report", Nature +Medicine 32, 3695-3704 (2026), https://doi.org/10.1038/s41591-026-04626-w +(preprint arXiv:2507.05201). Its weights are downloaded from the Hugging Face Hub +under the `Health AI Developer Foundations terms of use +`__. + +.. automodule:: pyhealth.datasets.medmod.medsiglip + :members: + +ConVIRT pretraining samples +--------------------------- + +ConVIRT is pretrained on MedMod's phenotyping train and validation stays, each +with its whole ICU stay of EHR and its latest AP chest X-ray. +:mod:`pyhealth.datasets.medmod.pretraining` builds these samples from the +output of MedMod's extraction scripts and the MIMIC-CXR-JPG metadata +(``load_pretraining_samples``) and turns them into a PyHealth dataset +(``create_pretraining_dataset``). + +.. automodule:: pyhealth.datasets.medmod.pretraining + :members: diff --git a/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst index a77e3539f0..44a525dfca 100644 --- a/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst +++ b/docs/api/tasks/pyhealth.tasks.MedModInHospitalMortality.rst @@ -34,17 +34,20 @@ what the model's own image loader applies. - Why * - Early Fusion - ``"keep"`` - - ImageNet-normalized + - ``get_preset("early_fusion", ...)`` (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] + - ``get_preset("convirt", ...)`` (pixels in [0, 1]) - MedMod's ``src/data/datasets.py:137-163`` keeps 0 < t only; the ConVIRT scripts pass ``--transforms_cxr simclrv2``. +``get_preset`` and ``load_cxr`` are in ``pyhealth.datasets.medmod.image_presets``; +``train=True`` adds the training augmentation. + Paper vs code ------------- diff --git a/examples/README.md b/examples/README.md index 63589e3129..12a00baf49 100644 --- a/examples/README.md +++ b/examples/README.md @@ -99,6 +99,8 @@ Older examples that no longer run, or that duplicated a maintained one, are in | `patient_linkage_mimic3_medlink.py` | MedLink record linkage (needs `pytrec_eval`) | | `physionet_deid_ner_transformer_deid.py` | Transformer de-identification (PhysioNet, credentialed) | | `mimic4_mortality_medfuse.py` | MedFuse ablation (synthetic data) | +| `mimic4_medmod_ihm_early_fusion.py` | MedMod Early Fusion for in-hospital mortality | +| `mimic4_medmod_convirt.py` | MedMod ConVIRT pretraining + linear probe for in-hospital mortality | | `mimic4_decompensation_daft.py` | DAFT on MedMod decompensation and mortality, with ablations (synthetic data by default) | | `physionet2012_mortality_stepwise_embedding.py` | Step-wise embedding ablation (backbone, raw, direct, grouped and grouped_shared encoders) on PhysioNet 2012 mortality (synthetic data with `--synthetic`) | | `support_survival_survival_mdn.py` (with `survival_mdn_data.py`, `survival_mdn_metrics.py`, results in `survival_mdn_results/`) | Survival mixture density network on SUPPORT | diff --git a/examples/mimic4_medmod_convirt.py b/examples/mimic4_medmod_convirt.py new file mode 100644 index 0000000000..15d1910686 --- /dev/null +++ b/examples/mimic4_medmod_convirt.py @@ -0,0 +1,362 @@ +"""MedMod ConVIRT on MIMIC-IV + MIMIC-CXR: contrastive pretraining of an EHR +LSTM and a chest X-ray ResNet-34, then a linear probe for in-hospital +mortality (MedMod, Elsharief et al., CHIL 2025; paper Table 4: AUROC 0.847). + +Synthetic data (no MIMIC access; a few minutes on CPU): + + python examples/mimic4_medmod_convirt.py --synthetic + +Real data, two steps: + + # 1. pretraining on MedMod's phenotyping train/val stays, whole ICU stay + python examples/mimic4_medmod_convirt.py pretrain \\ + --extracted-root /data/medmod_extracted \\ + --cxr-root /data/mimic-cxr-jpg/2.0.0 \\ + --image-dir /data/mimic-cxr-jpg/2.0.0/resized --out runs/convirt + # 2. linear probe on in-hospital mortality, from pretraining epoch NNN + python examples/mimic4_medmod_convirt.py probe \\ + --ehr-root /data/mimiciv/1.0 --cxr-root /data/mimic-cxr-jpg/2.0.0 \\ + --image-dir /data/mimic-cxr-jpg/2.0.0/resized \\ + --cache-dir /data/pyhealth_cache --checkpoint runs/convirt/epoch_NNN.pt + +As the paper describes, NNN is the pretraining epoch with the highest +validation AUROC. ``mimic4_medmod_ihm_colab_runs.ipynb`` chooses NNN among +every 10th epoch, with quick probes of +``medmod_runners/convirt_probe.py --no-augment`` (follow-up pull request). + +``--extracted-root`` is the output of MedMod's extraction scripts (MIMIC-IV +benchmark + ``create_phenotyping``); ``--image-dir`` holds the images resized +by ``pyhealth.datasets.medmod.resize_cxr``. + +Pretraining follows MedMod's released settings (src/scripts/pretrain/ +simclr.sh; src/models/selfsupervised/models/simclr_model.py): 300 epochs, +batch 256 with drop_last, temperature 0.01, LARS (lr 0.6044, momentum 0.9, +weight decay 1e-4) with a 10-epoch linear warmup then +CosineAnnealingWarmRestarts(T_0=500), both stepped once per epoch, seed 84305, +MedMod's simclrv2 augmentation; every epoch's weights are kept. MedMod's +early stopping (patience 30 on val loss) is not applied. The probe follows +MedMod's linear eval (src/scripts/lineareval/mortality/multimodal.sh; +models/finetune.py) with the encoders frozen, as in the paper's Table 4: +AdamW lr 0.001, batch 256, at most 200 epochs, early stopping on val AUROC +(patience 30), train augmentation; MedMod reports the final epoch. + +MedSigLIP extension. The option ``--embeddings FILE`` replaces the ResNet-34 +with stored embeddings from a frozen MedSigLIP image encoder, in both steps. +The file is written by ``python -m pyhealth.datasets.medmod.medsiglip``. +ConVIRT is built with ``cxr_backbone=nn.Identity()`` and +``cxr_feature_dim=1152``, and each batch's image input is looked up in the +file by image file name. The stored vectors are fixed, so there is no image +augmentation. Pass the same file to both steps: + + python examples/mimic4_medmod_convirt.py pretrain ... \\ + --embeddings /data/medsiglip_448.npz --out runs/convirt_medsiglip + python examples/mimic4_medmod_convirt.py probe ... \\ + --embeddings /data/medsiglip_448.npz \\ + --checkpoint runs/convirt_medsiglip/epoch_NNN.pt + +On synthetic data, ``--embeddings synthetic`` writes a random stand-in vector +of 1152 values for each image. The MedSigLIP code then runs as on real data, +without the gated MedSigLIP model: + + python examples/mimic4_medmod_convirt.py --synthetic --embeddings synthetic + +Results on the test set. Each value is the mean +- standard deviation over +MedMod's five seeds 1002, 2918, 5793, 7261 and 84305, each with its own +pretraining run and probe. Each probe uses the chosen pretraining epoch, and +the score is taken at the last probe epoch. The runs used +``medmod_runners/convirt_pretrain.py`` and ``medmod_runners/convirt_probe.py``, +which train these models with these settings. The Colab notebook +``mimic4_medmod_ihm_colab_runs.ipynb`` prints them in the cell "Summary of the +runner reports". With seed 84305 and the same pretraining epoch, this script +gives the same scores as the runner with the ResNet-34, AUROC 0.8207 and AUPRC +0.4685. With MedSigLIP, it gives AUROC 0.8159 and AUPRC 0.4640, and the runner +gives 0.8148 and 0.4589, because the runner shuffles the training batches in a +different order (cell "Result line of every job"). +``medmod_runners/`` and the Colab notebook come in a follow-up pull request. + + ResNet-34: AUROC 0.8206 +- 0.0049, AUPRC 0.4588 +- 0.0114 + MedSigLIP: AUROC 0.8200 +- 0.0037, AUPRC 0.4686 +- 0.0077 + Paper, Table 4 (linear probing): AUROC 0.847 +- 0.002, AUPRC 0.482 +- 0.016 + Paper, Table 8 (linear evaluation): AUROC 0.813 +- 0.010 +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import tempfile +from pathlib import Path + +import numpy as np +import torch +from sklearn.metrics import average_precision_score, roc_auc_score +from torch import nn +from torch.optim.optimizer import Optimizer, required + +from pyhealth.datasets import ( + MedModMIMIC4Dataset, + MedModSplit, + get_dataloader, + split_by_medmod, +) +from pyhealth.datasets.medmod.image_presets import get_preset, load_cxr +from pyhealth.datasets.medmod.medsiglip import load_embeddings, lookup_embeddings +from pyhealth.datasets.medmod.pretraining import ( + create_pretraining_dataset, + load_pretraining_samples, +) +from pyhealth.datasets.medmod.synthetic import ( + create_synthetic_pretraining_samples, + create_synthetic_samples, + write_synthetic_embeddings, +) +from pyhealth.models import ConVIRT, ConVIRTLinearProbe +from pyhealth.tasks import MedModInHospitalMortality + + +class LARS(Optimizer): + """LARS from lightning-flash 0.7.5 (flash/core/optimizers/lars.py, + Apache-2.0), the optimizer MedMod imports (simclr_model.py:16). Same + arithmetic; the zero-norm test is a ``torch.where`` (no device sync).""" + + def __init__(self, params, lr=required, momentum=0.0, dampening=0.0, + weight_decay=0.0, nesterov=False, trust_coefficient=0.001, + eps=1e-8): + defaults = {"lr": lr, "momentum": momentum, "dampening": dampening, + "weight_decay": weight_decay, "nesterov": nesterov} + self.eps = eps + self.trust_coefficient = trust_coefficient + super().__init__(params, defaults) + + @torch.no_grad() + def step(self, closure=None): + for group in self.param_groups: + wd, momentum = group["weight_decay"], group["momentum"] + for p in group["params"]: + if p.grad is None: + continue + d_p = p.grad + if wd != 0: + p_norm, g_norm = torch.norm(p), torch.norm(d_p) + lars_lr = (p_norm / (g_norm + p_norm * wd + self.eps) + * self.trust_coefficient) + scaled = d_p.add(p, alpha=wd) * lars_lr + d_p = torch.where((p_norm != 0) & (g_norm != 0), scaled, d_p) + if momentum != 0: + state = self.state[p] + if "momentum_buffer" not in state: + buf = state["momentum_buffer"] = torch.clone(d_p).detach() + else: + buf = state["momentum_buffer"] + buf.mul_(momentum).add_(d_p, alpha=1 - group["dampening"]) + d_p = d_p.add(buf, alpha=momentum) if group["nesterov"] else buf + p.add_(d_p, alpha=-group["lr"]) + + +def default_device() -> str: + """CUDA if available, else CPU; MPS only with ``--device mps``, since it + crashes on some macOS and torch versions.""" + return "cuda" if torch.cuda.is_available() else "cpu" + + +def with_images(batch: dict, transform, table=None) -> dict: + """Adds the image input: the loaded, transformed images or, with ``table`` + (``--embeddings``), their stored MedSigLIP embeddings.""" + if table is not None: + batch["cxr"] = lookup_embeddings(batch["image_path"], *table) + else: + images = [transform(load_cxr(p)) for p in batch["image_path"]] + batch["cxr"] = torch.stack(images) + return batch + + +def build_convirt(dataset, args) -> ConVIRT: + """ConVIRT with a ResNet, or reading stored embeddings (``--embeddings``).""" + if args.table is None: + return ConVIRT(dataset, cxr_backbone=args.backbone, + temperature=args.temperature) + return ConVIRT(dataset, cxr_backbone=nn.Identity(), + cxr_feature_dim=args.table[1].shape[1], + temperature=args.temperature) + + +def pretrain(dataset, out: Path, args) -> None: + """ConVIRT pretraining with MedMod's settings; resumes from out/last.pt.""" + train, val, _ = split_by_medmod(dataset) + print(f"pretraining stays: train {len(train)}, val {len(val)}", flush=True) + out.mkdir(parents=True, exist_ok=True) + dev = torch.device(args.device) + torch.manual_seed(args.seed) + np.random.seed(args.seed) # the presets draw from numpy's global RNG + model = build_convirt(dataset, args).to(dev) + opt = LARS(model.parameters(), lr=args.lr, momentum=0.9, weight_decay=1e-4) + # created in MedMod's order (simclr_model.py:88-93) + cosine = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(opt, 500) + warmup = torch.optim.lr_scheduler.LambdaLR(opt, lambda e: (e + 1) / 10) + history, start = [], 0 + if (out / "last.pt").exists(): + ck = torch.load(out / "last.pt", map_location="cpu", weights_only=True) + model.load_state_dict(ck["model"]) + opt.load_state_dict(ck["optimizer"]) + cosine.load_state_dict(ck["cosine"]) + warmup.load_state_dict(ck["warmup"]) + history, start = ck["history"], ck["epoch"] + 1 + print(f"resumed after epoch {ck['epoch']}", flush=True) + train_tf, eval_tf = get_preset("convirt", train=True), get_preset("convirt") + + def run(part, epoch, training): + model.train(training) + loader = get_dataloader(part, batch_size=args.batch_size, shuffle=training, + seed=args.seed, drop_last=training) + loader.epoch = epoch + 1 # shuffle order depends on (seed, epoch) + losses, sizes = [], [] + for batch in loader: + batch = with_images(batch, train_tf if training else eval_tf, args.table) + with torch.set_grad_enabled(training): + loss = model(**batch)["loss"] + if training: + opt.zero_grad(set_to_none=True) + loss.backward() + opt.step() + losses.append(loss.detach()) + sizes.append(len(batch["image_path"])) + per_batch = torch.stack(losses).float().cpu().numpy() + return float((per_batch * np.array(sizes)).sum() / sum(sizes)) + + for epoch in range(start, args.epochs): + lr = opt.param_groups[0]["lr"] + torch.manual_seed(args.seed + epoch) + np.random.seed(args.seed + epoch) + train_loss = run(train, epoch, True) + (warmup if epoch < 9 else cosine).step() # simclr_model.py:151-155 + with torch.no_grad(): + val_loss = run(val, epoch, False) + history.append({"epoch": epoch, "lr": lr, "train_loss": train_loss, + "val_loss": val_loss}) + print(json.dumps(history[-1]), flush=True) + torch.save({"epoch": epoch, "model": model.state_dict()}, + out / f"epoch_{epoch:03d}.pt") + tmp = out / "last.tmp" + torch.save({"epoch": epoch, "model": model.state_dict(), + "optimizer": opt.state_dict(), "cosine": cosine.state_dict(), + "warmup": warmup.state_dict(), "history": history}, tmp) + os.replace(tmp, out / "last.pt") + best = min(history, key=lambda h: h["val_loss"]) + print(f"done; lowest val loss {best['val_loss']:.4f} at epoch {best['epoch']}") + + +def probe(train, val, test, checkpoint: Path, args) -> dict: + """Linear probe on the frozen pretrained encoders, MedMod's linear eval.""" + dev = torch.device(args.device) + torch.manual_seed(args.seed) + np.random.seed(args.seed) + convirt = build_convirt(train, args) + convirt.load_state_dict( + torch.load(checkpoint, map_location="cpu", weights_only=True)["model"]) + model = ConVIRTLinearProbe(train, convirt).to(dev) + opt = torch.optim.AdamW([p for p in model.parameters() if p.requires_grad], + lr=0.001) + train_tf, eval_tf = get_preset("convirt", train=True), get_preset("convirt") + + @torch.no_grad() + def auroc_auprc(part): + model.eval() + ys, ps = [], [] + for batch in get_dataloader(part, batch_size=args.batch_size): + out = model(**with_images(batch, eval_tf, args.table)) + ys.append(out["y_true"].float().cpu().reshape(-1)) + ps.append(out["y_prob"].float().cpu().reshape(-1)) + y, p = torch.cat(ys).numpy(), torch.cat(ps).numpy() + return float(roc_auc_score(y, p)), float(average_precision_score(y, p)) + + best, waited = -math.inf, 0 + for epoch in range(args.probe_epochs): + torch.manual_seed(args.seed + epoch) + np.random.seed(args.seed + epoch) + model.train() + loader = get_dataloader(train, batch_size=args.batch_size, shuffle=True, + seed=args.seed, drop_last=True) + loader.epoch = epoch + 1 + for batch in loader: + loss = model(**with_images(batch, train_tf, args.table))["loss"] + opt.zero_grad() + loss.backward() + opt.step() + val_auroc, _ = auroc_auprc(val) + print(json.dumps({"epoch": epoch, "val_auroc": val_auroc}), flush=True) + if round(val_auroc, 4) > best + 0.001: # MedMod: EarlyStopping(0.001, 30) + best, waited = round(val_auroc, 4), 0 + else: + waited += 1 + if waited >= 30: + break + auroc, auprc = auroc_auprc(test) + result = {"test_auroc": auroc, "test_auprc": auprc, "epochs": epoch + 1} + print("TEST", json.dumps(result)) + return result + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("step", nargs="?", choices=["pretrain", "probe"]) + ap.add_argument("--synthetic", action="store_true", + help="both steps on small synthetic data (no MIMIC)") + ap.add_argument("--extracted-root") + ap.add_argument("--ehr-root") + ap.add_argument("--cxr-root") + ap.add_argument("--image-dir") + ap.add_argument("--cache-dir") + ap.add_argument("--out", default="runs/convirt") + ap.add_argument("--checkpoint") + ap.add_argument("--epochs", type=int, default=300) + ap.add_argument("--probe-epochs", type=int, default=200) + ap.add_argument("--batch-size", type=int, default=256) + ap.add_argument("--lr", type=float, default=0.6044) + ap.add_argument("--temperature", type=float, default=0.01) + ap.add_argument("--backbone", default="resnet34") + ap.add_argument("--embeddings", + help="MedSigLIP .npz file to use instead of a ResNet. " + "With --synthetic, 'synthetic' uses random stand-in vectors.") + ap.add_argument("--seed", type=int, default=84305) + ap.add_argument("--device", default=default_device()) + args = ap.parse_args() + synthetic_embeddings = args.embeddings == "synthetic" + if synthetic_embeddings and not args.synthetic: + ap.error("--embeddings synthetic needs --synthetic") + args.table = None + if args.embeddings and not synthetic_embeddings: + args.table = load_embeddings(args.embeddings)[:2] + + if args.synthetic: + args.epochs, args.probe_epochs, args.batch_size = 2, 2, 32 + out = Path(tempfile.mkdtemp(prefix="convirt_synthetic_")) + pretraining = create_synthetic_pretraining_samples(n_stays=96) + train, val, test = split_by_medmod(create_synthetic_samples("drop", 200)) + if synthetic_embeddings: + # Random stand-ins for MedSigLIP vectors of the synthetic images. + paths = [part[i]["image_path"] for part in (pretraining, train, val, test) + for i in range(len(part))] + emb = write_synthetic_embeddings(paths, out / "emb.npz", seed=args.seed) + args.table = load_embeddings(emb)[:2] + pretrain(pretraining, out, args) + probe(train, val, test, out / "epoch_001.pt", args) + elif args.step == "pretrain": + samples, funnel = load_pretraining_samples( + args.extracted_root, args.cxr_root, args.image_dir) + print("funnel:", json.dumps(funnel), flush=True) + pretrain(create_pretraining_dataset(samples), Path(args.out), args) + elif args.step == "probe": + dataset = MedModMIMIC4Dataset(ehr_root=args.ehr_root, cxr_root=args.cxr_root, + cache_dir=args.cache_dir) + task = MedModInHospitalMortality(hours_zero="drop", image_dir=args.image_dir) + train, val, test = dataset.set_task(task, split=MedModSplit()) + probe(train, val, test, Path(args.checkpoint), args) + else: + ap.error("give a step (pretrain or probe) or --synthetic") + + +if __name__ == "__main__": + main() diff --git a/examples/mimic4_medmod_ihm_early_fusion.py b/examples/mimic4_medmod_ihm_early_fusion.py new file mode 100644 index 0000000000..c27e975a00 --- /dev/null +++ b/examples/mimic4_medmod_ihm_early_fusion.py @@ -0,0 +1,292 @@ +"""Early Fusion on MedMod in-hospital mortality (MIMIC-IV + MIMIC-CXR). + +Authors: Yuqing Hu (yhu672@gatech.edu), Hanh Trang Do (hdo61@gatech.edu) + +Paper: + Elsharief et al. "MedMod: Multimodal Benchmark for Medical Prediction Tasks + with Electronic Health Records and Chest X-Ray Scans." CHIL 2025. + https://proceedings.mlr.press/v287/elsharief25a.html + +Trains :class:`~pyhealth.models.EHRCXREarlyFusion`: an EHR LSTM and a CXR +ResNet-34, both loaded from MedFuse's released checkpoints and frozen, so only +the projection and the classifier train. Training follows MedFuse +(``scripts/mortality/train/early.sh``, ``trainers/fusion_trainer.py``): Adam, +lr 9.515e-05, betas (0.9, 0.9), batch 16, up to 50 epochs, the learning rate +halved when the validation loss stops falling for 10 epochs, validation before +each epoch, the best epoch by validation AUROC, and early stopping after 15 +epochs without improvement. The data loader gives image paths, so the images +of each batch are loaded and transformed here, with augmentation in training. + +Smoke test on synthetic data (no MIMIC, no checkpoints; scores mean nothing): + + python examples/mimic4_medmod_ihm_early_fusion.py --synthetic 300 --epochs 2 + +Real data (credentialed MIMIC-IV v1.0 and MIMIC-CXR-JPG, plus the MedFuse +checkpoints from https://github.com/nyuad-cai/MedFuse, Git LFS): + + python examples/mimic4_medmod_ihm_early_fusion.py \\ + --ehr-root /data/mimiciv/1.0 --cxr-root /data/mimic-cxr-jpg/2.0.0 \\ + --image-dir /data/mimic-cxr-jpg/2.0.0/resized --cache-dir /data/cache \\ + --ehr-weights checkpoints/mortality/uni_ehr_all/best_checkpoint.pth.tar \\ + --cxr-weights checkpoints/cxr_rad_full/best_checkpoint.pth.tar + +MedSigLIP extension. The option ``--embeddings FILE`` replaces the CXR +ResNet-34 with stored embeddings from a frozen MedSigLIP image encoder. The +file is written by ``python -m pyhealth.datasets.medmod.medsiglip``. The model +is built with ``cxr_backbone=nn.Identity()`` and ``cxr_feature_dim=1152``, and +each batch's image input is looked up in the file by image file name. +``--cxr-weights`` is not used. The stored vectors are fixed, so there is no +image augmentation. + +On synthetic data, ``--embeddings synthetic`` writes a random stand-in vector +of 1152 values for each image. The MedSigLIP code then runs as on real data, +without the gated MedSigLIP model: + + python examples/mimic4_medmod_ihm_early_fusion.py --synthetic 300 \\ + --epochs 2 --embeddings synthetic + +Results on the test set. Each value is the mean +- standard deviation over +MedMod's five seeds 1002, 2918, 5793, 7261 and 84305. The five runs used +``medmod_runners/early_fusion_run.py``, which trains this model with these +settings. The Colab notebook ``mimic4_medmod_ihm_colab_runs.ipynb`` prints +them in the cell "Summary of the runner reports". With seed 0, this script and +the runner give the same scores, AUROC 0.8408 and AUPRC 0.5137 (cell "Result +line of every job"). +``medmod_runners/`` and the Colab notebook come in a follow-up pull request. + + ResNet-34: AUROC 0.8407 +- 0.0004, AUPRC 0.5140 +- 0.0007 + MedSigLIP: AUROC 0.8461 +- 0.0010, AUPRC 0.5367 +- 0.0035 + Paper: AUROC 0.842 +- 0.004, AUPRC 0.515 +- 0.020 + +Deviations. Our frozen encoders stay exactly as released during training, the +usual practice for frozen layers in PyTorch (evaluation mode). MedMod's and +MedFuse's code leave them in training mode, so their BatchNorm statistics and +dropout still change the features. Our project proposal described both +encoders as trained from scratch. The paper's Early Fusion uses pretrained +encoders, so we follow the paper. ``mimic4_medmod_ihm_results.md`` lists all +deviations. +""" + +from __future__ import annotations + +import argparse +import codecs +import hashlib +import json +import tempfile +from pathlib import Path + +import numpy as np +import torch +from numpy._core.multiarray import scalar +from sklearn.metrics import average_precision_score, roc_auc_score +from torch import nn + +from pyhealth.datasets import ( + MedModMIMIC4Dataset, + MedModSplit, + get_dataloader, + split_by_medmod, +) +from pyhealth.datasets.medmod.image_presets import get_preset, load_cxr +from pyhealth.datasets.medmod.medsiglip import load_embeddings, lookup_embeddings +from pyhealth.datasets.medmod.synthetic import ( + create_synthetic_samples, + write_synthetic_embeddings, +) +from pyhealth.models import EHRCXREarlyFusion +from pyhealth.tasks import MedModInHospitalMortality + +# sha256 of MedFuse's Git LFS checkpoint files. +EHR_SHA256 = "c545d8d536882948f25b4dd8a136c43da49fd10d4519e8b24b821109ad22f552" +CXR_SHA256 = "a02628fcec408cc59ac1464015ddcf87b98840e37812563ce648ddce11b3bf90" + + +def load_checkpoint(path: str, sha256: str) -> dict: + """Checks a MedFuse checkpoint file and returns its state dict. + + The file also stores numpy scalars, which torch's restricted loader + (``weights_only=True``) accepts once they are allowed explicitly. + """ + digest = hashlib.sha256(Path(path).read_bytes()).hexdigest() + if digest != sha256: + raise ValueError(f"{path}: not MedFuse's released checkpoint (sha256)") + allowed = [ + (scalar, "numpy.core.multiarray.scalar"), + np.dtype, + type(np.dtype("float64")), + codecs.encode, + ] + with torch.serialization.safe_globals(allowed): + checkpoint = torch.load(path, map_location="cpu", weights_only=True) + return checkpoint["state_dict"] + + +def ehr_state_dict(state: dict) -> dict: + """MedFuse's EHR LSTM is two 1-layer LSTMs, ``ehr_model.layer{k}.*_l0``. + + In one 2-layer ``nn.LSTM`` they are ``*_l{k}``. + """ + weights = {} + for key, value in state.items(): + if key.startswith("ehr_model.layer"): + layer, name = key[len("ehr_model.layer") :].split(".", 1) + weights[name.replace("_l0", f"_l{layer}")] = value + return weights + + +def cxr_state_dict(state: dict) -> dict: + """MedFuse's ``cxr_model.vision_backbone`` is a ResNet-34 without ``fc``.""" + prefix = "cxr_model.vision_backbone." + return {k[len(prefix) :]: v for k, v in state.items() if k.startswith(prefix)} + + +def load_data(args: argparse.Namespace): + """Returns the train, validation and test samples of the fixed MedMod split.""" + if args.synthetic: + samples = create_synthetic_samples( + hours_zero="keep", n_stays=args.synthetic, seed=args.seed + ) + return split_by_medmod(samples) + dataset = MedModMIMIC4Dataset( + ehr_root=args.ehr_root, cxr_root=args.cxr_root, cache_dir=args.cache_dir + ) + task = MedModInHospitalMortality(hours_zero="keep", image_dir=args.image_dir) + return dataset.set_task(task, split=MedModSplit()) + + +def add_images(batch: dict, transform, table=None) -> dict: + """Loads and transforms the images of a batch into ``batch["cxr"]``, or, + with ``table`` (``--embeddings``), looks up their stored embeddings.""" + if table is not None: + batch["cxr"] = lookup_embeddings(batch["image_path"], *table) + return batch + images = [transform(load_cxr(path)) for path in batch["image_path"]] + batch["cxr"] = torch.stack(images) + return batch + + +@torch.no_grad() +def evaluate(model, samples, transform, table=None) -> tuple[float, float, float]: + """Returns AUROC, AUPRC and the mean loss on ``samples``.""" + model.eval() + y_true, y_prob, losses = [], [], [] + for batch in get_dataloader(samples, batch_size=64): + output = model(**add_images(batch, transform, table)) + losses.append(float(output["loss"]) * len(batch["image_path"])) + y_true.append(output["y_true"].cpu().reshape(-1)) + y_prob.append(output["y_prob"].cpu().reshape(-1)) + y, p = torch.cat(y_true).numpy(), torch.cat(y_prob).numpy() + return roc_auc_score(y, p), average_precision_score(y, p), sum(losses) / len(y) + + +def parse_args() -> argparse.Namespace: + """Parses the command line.""" + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--synthetic", type=int, default=0, help="synthetic stays") + parser.add_argument("--ehr-root", help="MIMIC-IV v1.0 root") + parser.add_argument("--cxr-root", help="MIMIC-CXR-JPG root") + parser.add_argument("--image-dir", help="resized MIMIC-CXR images") + parser.add_argument("--cache-dir", help="PyHealth cache directory") + parser.add_argument("--ehr-weights", help="MedFuse uni_ehr_all checkpoint") + parser.add_argument("--cxr-weights", help="MedFuse cxr_rad_full checkpoint") + parser.add_argument( + "--embeddings", + help="MedSigLIP .npz file to use instead of a ResNet. With --synthetic, " + "'synthetic' uses random stand-in vectors.", + ) + parser.add_argument("--epochs", type=int, default=50) + parser.add_argument("--batch-size", type=int, default=16) + parser.add_argument("--lr", type=float, default=9.515e-05) + parser.add_argument("--patience", type=int, default=15) + parser.add_argument("--seed", type=int, default=0) + # MPS only with --device mps: it crashes on some macOS and torch versions. + parser.add_argument( + "--device", default="cuda" if torch.cuda.is_available() else "cpu" + ) + args = parser.parse_args() + real = (args.ehr_root, args.cxr_root, args.image_dir, args.cache_dir) + if not args.synthetic and not all(real): + parser.error( + "set --synthetic N, or all of --ehr-root, --cxr-root, " + "--image-dir and --cache-dir" + ) + if args.embeddings and args.cxr_weights: + parser.error("--cxr-weights is for the ResNet, not --embeddings") + if args.embeddings == "synthetic" and not args.synthetic: + parser.error("--embeddings synthetic needs --synthetic N") + return args + + +def main() -> None: + """Trains Early Fusion and prints the test AUROC and AUPRC.""" + args = parse_args() + torch.manual_seed(args.seed) + np.random.seed(args.seed) # the image presets draw from numpy's RNG + + train, val, test = load_data(args) + print(f"stays train/val/test: {len(train)}/{len(val)}/{len(test)}") + weights = {} + if args.ehr_weights: + state = load_checkpoint(args.ehr_weights, EHR_SHA256) + weights["ehr_state_dict"] = ehr_state_dict(state) + if args.cxr_weights: + state = load_checkpoint(args.cxr_weights, CXR_SHA256) + weights["cxr_state_dict"] = cxr_state_dict(state) + if args.embeddings == "synthetic": + # Random stand-ins for MedSigLIP vectors of the synthetic images. + paths = [part[i]["image_path"] for part in (train, val, test) + for i in range(len(part))] + out = Path(tempfile.mkdtemp(prefix="medsiglip_synthetic_")) / "emb.npz" + args.embeddings = str(write_synthetic_embeddings(paths, out, seed=args.seed)) + table, image_encoder = None, {} + if args.embeddings: + table = load_embeddings(args.embeddings)[:2] + image_encoder = { + "cxr_backbone": nn.Identity(), + "cxr_feature_dim": table[1].shape[1], + } + if len(weights) + bool(table) < 2: + print("Encoders without MedFuse weights are random: smoke test only.") + model = EHRCXREarlyFusion( + train, freeze_encoders=True, **weights, **image_encoder + ).to(args.device) + + trainable = [p for p in model.parameters() if p.requires_grad] + optimizer = torch.optim.Adam(trainable, lr=args.lr, betas=(0.9, 0.9)) + scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau( + optimizer, factor=0.5, patience=10 + ) + train_tf, eval_tf = ( + get_preset("early_fusion", train=True), + get_preset("early_fusion"), + ) + + best_auroc, best_state, waited = -1.0, None, 0 + for epoch in range(args.epochs + 1): + # As MedFuse: validate before each epoch; the last pass only validates. + val_auroc, _, val_loss = evaluate(model, val, eval_tf, table) + if val_auroc > best_auroc: + best_auroc, waited = val_auroc, 0 + best_state = {k: v.clone() for k, v in model.state_dict().items()} + else: + waited += 1 + print(f"epoch {epoch}: val AUROC {val_auroc:.4f}") + if epoch == args.epochs or waited >= args.patience: + break + model.train() + loader = get_dataloader(train, batch_size=args.batch_size, shuffle=True) + for batch in loader: + loss = model(**add_images(batch, train_tf, table))["loss"] + optimizer.zero_grad() + loss.backward() + optimizer.step() + scheduler.step(val_loss) + + model.load_state_dict(best_state) + auroc, auprc, _ = evaluate(model, test, eval_tf, table) + print("RESULT", json.dumps({"test_auroc": auroc, "test_auprc": auprc})) + + +if __name__ == "__main__": + main() diff --git a/examples/mimic4_medmod_ihm_results.md b/examples/mimic4_medmod_ihm_results.md new file mode 100644 index 0000000000..cc6a01ee01 --- /dev/null +++ b/examples/mimic4_medmod_ihm_results.md @@ -0,0 +1,357 @@ +# MedMod in-hospital mortality reproduction results + +This page reports our results for the two models in the MedMod example +scripts in this folder. The models were run on real MIMIC-IV v1.0 and +MIMIC-CXR-JPG 2.0.0 data, and the results are compared with the paper below. + +> Elsharief, S., et al. (2025). MedMod: Multimodal benchmark for medical +> prediction tasks with electronic health records and chest X-ray scans. +> CHIL 2025. https://proceedings.mlr.press/v287/elsharief25a.html + +The two scripts are: + +- `mimic4_medmod_ihm_early_fusion.py` trains Early Fusion. It uses MedFuse's + released pretrained encoders, the EHR LSTM `uni_ehr_all` and the ResNet-34 + `cxr_rad_full`. Both are frozen, so they stay exactly as released. Only the + projection layer and the classifier are trained. +- `mimic4_medmod_convirt.py` pretrains ConVIRT with a contrastive loss and then + trains a linear probe on the frozen encoders. + +Our extension replaces the ResNet-34 image encoder with a frozen MedSigLIP +image encoder in both models (option `--embeddings`). + +All numbers are measured on MedMod's fixed test split, which has 1,241 stays +and 187 deaths. This page reports only aggregate scores and no patient-level +data. + +The runner scripts in `medmod_runners/` and the Colab notebook come in a +follow-up pull request. + +The Google Colab notebook `mimic4_medmod_ihm_colab_runs.ipynb` goes with this +page. It holds our real-data runs, with the output each run printed. Both +scripts also run end to end on synthetic data, which needs no MIMIC access +(see Reproduce). + +The five-seed results come from the runner scripts in `medmod_runners/`. They +train the same models with the same settings as the example scripts. They also +compute bootstrap confidence intervals and write a report for every run. Each +runner saves checkpoints and continues from the last one after a disconnect. +The Early Fusion and probe runners save every 10 epochs, and the ConVIRT +pretraining runner saves after every epoch. Each example script was also run +once on real data, to check that it gives the same scores as its runner. + +The Colab notebook `mimic4_medmod_ihm_colab_runs.ipynb` shows all runs. Its +cell "Summary of the runner reports" prints the score of every seed, the means +and the differences. The cell "Result line of every job" prints the last line +of every run, including the example scripts. The sections below name the cell +that shows each number. + +## Our hypotheses + +Our project proposal stated two hypotheses. The sections below give the +details. + +**H1. Our PyHealth models reach a test AUROC close to the paper's.** + +Early Fusion confirms H1. Its mean AUROC over five seeds is 0.8407 ± 0.0004, +and the paper reports 0.842 ± 0.004. + +The ConVIRT linear probe does not confirm H1 for the target in our proposal, +Table 4's 0.847 ± 0.002 for linear probing. Its mean AUROC over five seeds is +0.8206 ± 0.0049, below 0.847 with every seed. It is close to Table 8's +0.813 ± 0.010 for linear evaluation. Our proposal chose Table 4 because Table +8 seems to swap the linear-probing and fine-tuning values. MedMod's released +linear-evaluation script also trains the encoders, which may explain the +higher 0.847 (see ConVIRT linear probe below). + +**H2. Replacing the ResNet-34 image encoder with frozen MedSigLIP changes the +test scores of both models.** + +For Early Fusion, MedSigLIP gives a small but consistent gain. Its AUROC is +higher with each of the five seeds, by 0.0054 on average. The 95% intervals of +the two encoders still overlap with every seed. + +For the ConVIRT linear probe, MedSigLIP does not change the AUROC. The mean +difference is -0.0006 ± 0.0049, and MedSigLIP is higher with 3 of the 5 seeds. +The AUPRC is higher by 0.0098 ± 0.0139 on average, with 4 of the 5 seeds. + +## Early Fusion + +Each score is the mean ± sample standard deviation over five runs. The runs +use MedMod's five seeds 1002, 2918, 5793, 7261 and 84305. The paper also +averages five runs, and the seed list comes from MedMod's code. + +The five runs used the runner `medmod_runners/early_fusion_run.py`. With +seed 0, the example script and the runner give the same scores, AUROC 0.8408 +and AUPRC 0.5137 (Colab cell "Result line of every job"). + +| Image encoder | AUROC | AUPRC | +|---|---|---| +| ResNet-34 (MedFuse `cxr_rad_full`), this reproduction | **0.8407 ± 0.0004** | **0.5140 ± 0.0007** | +| Paper | 0.842 ± 0.004 | 0.515 ± 0.020 | +| MedSigLIP (extension) | **0.8461 ± 0.0010** | **0.5367 ± 0.0035** | + +Across the five seeds, AUROC ranges from 0.8401 to 0.8410 with the ResNet-34 +and from 0.8447 to 0.8474 with MedSigLIP. MedSigLIP scores higher than the +ResNet-34 with every seed. The average difference per seed is +0.0054 ± 0.0009 +in AUROC and +0.0227 ± 0.0032 in AUPRC. + +This gain is small compared with the uncertainty that comes from the size of +the test set. For example, with seed 1002 the 95% bootstrap interval of the +AUROC is 0.8105 to 0.8678 for the ResNet-34 and 0.8180 to 0.8701 for +MedSigLIP. The two intervals overlap with every seed. So the gain is +consistent across seeds but small. + +Our scores vary much less between seeds than the paper's. A likely reason is +that our frozen encoders stay in evaluation mode, so they stay exactly as +released. MedMod's code leaves them in training mode (see Deviations and +caveats). + +## ConVIRT linear probe + +Each score is the mean ± sample standard deviation over MedMod's five seeds. +Each seed has its own pretraining run and its own probe. As the paper +describes, each probe uses the pretraining epoch with the highest validation +AUROC (see Pretraining below). The test score is taken at the last probe +epoch, as in MedMod's code. The runs used the runners +`medmod_runners/convirt_pretrain.py` and `medmod_runners/convirt_probe.py`. + +| Image encoder | AUROC | AUPRC | +|---|---|---| +| ResNet-34, this reproduction | **0.8206 ± 0.0049** | **0.4588 ± 0.0114** | +| Paper, Table 4 (linear probing) | 0.847 ± 0.002 | 0.482 ± 0.016 | +| Paper, Table 8 (linear evaluation) | 0.813 ± 0.010 | | +| MedSigLIP (extension) | **0.8200 ± 0.0037** | **0.4686 ± 0.0077** | + +Across the five seeds, AUROC ranges from 0.8134 to 0.8255 with the ResNet-34 +and from 0.8148 to 0.8252 with MedSigLIP. The paper's Table 4 value (0.847) is +above every seed's score. + +The 95% bootstrap intervals use 1,000 resamples of the test set. With seed +84305, they are AUROC 0.7874 to 0.8512 for the ResNet-34 and 0.7831 to 0.8468 +for MedSigLIP. The intervals of the two encoders overlap with every seed. + +The example script `mimic4_medmod_convirt.py` ran once with seed 84305, on the +same pretraining epoch as the runner. With the ResNet-34, it gives the same +scores as the runner, AUROC 0.8207 and AUPRC 0.4685. With MedSigLIP, it gives +AUROC 0.8159 and AUPRC 0.4640, and the runner gives 0.8148 and 0.4589. The +runner shuffles the MedSigLIP training batches in a different order. + +The paper's tables disagree about which value belongs to the linear probe. +Table 4 gives 0.847 for linear probing and 0.813 ± 0.010 (AUPRC 0.449 ± 0.018) +for fine-tuning. Table 8 gives 0.847 for fine-tuning and 0.813 for linear +evaluation, with 641 trainable parameters. Our ResNet-34 probe also has 641 +trainable parameters. + +MedMod's released linear-evaluation script for mortality +(`src/scripts/lineareval/mortality/multimodal.sh`) passes the option +`--finetune`. With this option the encoders process the inputs +(`forward_fused` in `src/models/fusion_models.py`), and all parameters except +the projection heads are trained (`freeze_weights` and `configure_optimizers` +in `src/models/selfsupervised/models/finetune.py`). So the 0.847 may come from +fine-tuning and not from a frozen linear probe. We report the frozen probe, +which is what Table 4 describes. + +With MedSigLIP, the probe's 1,152 image features are the fixed MedSigLIP +vectors, and pretraining changes only the 128 EHR features. So the MedSigLIP +probe result does not show the effect of contrastive pretraining by itself. + +### Pretraining (300 epochs, MedMod's settings) + +Every pretraining run keeps the weights of every 10th epoch (9, 19, ..., 299). +For each of these 30 epochs, a quick probe runs with the image features +computed once and no augmentation. The epoch whose quick probe reaches the +highest validation AUROC is chosen, and the normal probe then runs on it. The +test set is not used for this choice. + +The table comes from the Colab cells "Pretraining summary, both encoders and +all seeds" and "Summary of the runner reports". + +| Image encoder | Seed | Epoch with the lowest validation loss (loss) | Validation loss at the last epoch, 299 | Epoch chosen for the probe | +|---|---|---|---|---| +| ResNet-34 | 1002 | 135 (8.89) | 13.48 | 279 | +| ResNet-34 | 2918 | 110 (9.03) | 15.20 | 209 | +| ResNet-34 | 5793 | 125 (8.98) | 13.42 | 269 | +| ResNet-34 | 7261 | 127 (8.95) | 14.59 | 259 | +| ResNet-34 | 84305 | 138 (8.84) | 12.80 | 189 | +| MedSigLIP | 1002 | 17 (8.68) | 47.20 | 139 | +| MedSigLIP | 2918 | 27 (8.64) | 43.55 | 249 | +| MedSigLIP | 5793 | 21 (8.79) | 46.32 | 219 | +| MedSigLIP | 7261 | 21 (8.73) | 47.86 | 179 | +| MedSigLIP | 84305 | 15 (8.74) | 47.98 | 199 | + +Both encoders overfit the contrastive loss. The validation loss is lowest +early and then rises. A model that guesses at random would get about 10.9 on +these validation batches. MedMod's early stopping (patience 30) would stop 30 +epochs after the lowest validation loss. Still, the chosen epochs come much +later than the lowest validation loss. So for the probe, a low contrastive +validation loss does not mean the best features. + +MedMod's loss leaves the positive pair out of the denominator. For this reason +the training loss can go below zero. + +## Settings + +- Cohort. Early Fusion uses MedMod's fixed split with 4,485 training, 488 + validation and 1,241 test stays. The paper and our proposal have 1,242 test + stays. One test image is missing from PhysioNet, so we drop that stay. + ConVIRT pretraining uses MedMod's phenotyping stays, 7,755 for training and + 882 for validation, each with the EHR of the whole ICU stay, as in MedMod's + code. One training image is missing there too. +- EHR. We use 1-hour bins and MedMod's phenotyping normalizer, as in the + released code. The paper text says 2-hour bins and a normalizer fitted on the + dataset. Our proposal also said 2-hour bins. We follow the code because + MedFuse's released EHR encoder, which Early Fusion uses, matches the test + AUROC MedFuse reports for it (0.825, MedFuse Table 1) only with the code's + settings. In our check on our test split, the frozen encoder alone gave + 0.833 with the code's settings and 0.719 with the paper's. +- Early Fusion. The encoders are MedFuse's released `uni_ehr_all` LSTM and + `cxr_rad_full` ResNet-34, both frozen. Training uses Adam with learning rate + 9.515e-05 and betas (0.9, 0.9), batch size 16, up to 50 epochs, and + ReduceLROnPlateau with factor 0.5 and patience 10. The best epoch is chosen + by validation AUROC. Training stops after 15 epochs without improvement, + which is MedFuse's default. The paper text says 10 epochs. +- ConVIRT pretraining. LARS with learning rate 0.6044, batch size 256, + temperature 0.01, a 10-epoch warmup followed by cosine restarts, and 300 + epochs, as in MedMod's `simclr.sh`. +- ConVIRT linear probe. The probe uses the pretraining epoch with the highest + validation AUROC, as the paper describes. MedMod's linear-evaluation script + uses pretraining epoch 65 instead. The probe is trained with AdamW, learning + rate 0.001, batch size 256, for up to 200 epochs, and stops after 30 epochs + without improvement in validation AUROC. These settings come from MedMod's + linear-evaluation script. The paper text instead describes Adam, up to 300 + epochs, stopping after 10 epochs and a learning-rate search. +- MedSigLIP (Sellergren et al., 2026, see References). We use the vision + tower of `google/medsiglip-448` (revision `9cea28a1`), frozen, with its + pooled output and its own 448 × 448 image processor. The embeddings are + computed once for all 12,625 resized images (the Colab cell "Check the + MedSigLIP embeddings file"). There is no image augmentation. +- Confidence intervals. We use 1,000 bootstrap resamples of the test set and + the percentile method. MedFuse's code uses the basic method. On the same + resamples, the basic method would move the interval ends of our runs by + 0.016 or less. + +## Deviations and caveats + +- Our project proposal described Early Fusion with both encoders trained from + scratch. The paper's Early Fusion, which is the model we proposed to + reproduce (0.842 ± 0.004), uses pretrained encoders instead. Section 3.3.1 + says it pretrains the two encoders separately, and Table 3 lists it under + "Multimodal (Pretrained)". MedMod's and MedFuse's `fusion_trainer.py` also + freeze both encoders for Early Fusion. We follow the paper. One sentence in + the caption of the paper's Figure 1 says Early Fusion uses "randomly + initialized encoders". This conflicts with the rest of the paper. +- Early Fusion uses MedFuse's released encoder checkpoints. MedMod pretrains + its own encoders, the EHR LSTM on mortality and the ResNet-34 on the + radiology labels, but does not release them. MedFuse is from the same lab, + and its encoders were trained with the same patient split. So no test + patient is in the encoders' training data. +- Our frozen encoders stay exactly as released during training. This is the + usual practice for frozen layers in PyTorch (evaluation mode). MedMod's and + MedFuse's code leave the frozen encoders in training mode. There, the + ResNet's BatchNorm statistics still change during training, and dropout + still acts on the EHR features. This may explain part of the larger spread + between seeds in the paper. +- Our proposal planned to train with PyHealth's `Trainer`. The example + scripts use their own short training loops instead, because the `Trainer` + has no learning-rate scheduler. MedFuse's settings need ReduceLROnPlateau, + and MedMod's need LARS with a warmup and cosine restarts. +- We use MedFuse's released learning rate. We did not repeat the paper's + learning-rate search, which used 100 runs for mortality. +- ConVIRT pretraining runs all 300 epochs. MedMod's code stops it when the + validation loss has not improved for 30 epochs. That rule would have stopped + every run before its chosen epoch (see Pretraining above). +- To choose the pretraining epoch, we compare every 10th epoch, not every + epoch, and the quick probe for this choice runs without augmentation. This + keeps the cost down. One 300-epoch ResNet-34 pretraining run took about 6 + hours on Colab. +- During our run, our Google Drive filled up, so some ResNet-34 pretraining + checkpoints were not uploaded to it. Before the probes ran, we copied them + back to their folders from Colab's local Drive cache, where they had been + kept. Where a checkpoint was in both places, the two copies were identical. +- MedSigLIP's training data include MIMIC-CXR. So MedSigLIP may have seen + images of our test patients during its own training. + +## Reproduce + +The Colab notebook `mimic4_medmod_ihm_colab_runs.ipynb` shows every real-data +run, including the runner commands. + +Both scripts run on synthetic data with `--synthetic`. The MedSigLIP extension +also runs on synthetic data with `--synthetic ... --embeddings synthetic`. +This option uses random stand-in vectors, so the gated MedSigLIP model is not +needed. The scripts' docstrings have the details. The commands for real data +are: + +```bash +# Early Fusion, one seed (repeat with --seed 1002, 2918, 5793, 7261, 84305) +python examples/mimic4_medmod_ihm_early_fusion.py \ + --ehr-root /data/mimiciv/1.0 --cxr-root /data/mimic-cxr-jpg/2.0.0 \ + --image-dir /data/mimic-cxr-jpg/2.0.0/resized --cache-dir /data/cache \ + --ehr-weights checkpoints/mortality/uni_ehr_all/best_checkpoint.pth.tar \ + --cxr-weights checkpoints/cxr_rad_full/best_checkpoint.pth.tar --seed 1002 +# For MedSigLIP, pass --embeddings medsiglip_448.npz instead of --cxr-weights + +# ConVIRT pretraining, then the probe on the chosen epoch NNN +python examples/mimic4_medmod_convirt.py pretrain --extracted-root ... --out runs/convirt +python examples/mimic4_medmod_convirt.py probe ... --checkpoint runs/convirt/epoch_NNN.pt +# For MedSigLIP, add --embeddings medsiglip_448.npz to both steps +# The Colab notebook chooses NNN with quick probes of the runner +# medmod_runners/convirt_probe.py (option --no-augment) + +# Compute the MedSigLIP embeddings +python -m pyhealth.datasets.medmod.medsiglip --help +``` + +## References + +Paper we reproduce: + +- Elsharief, S., Shurrab, S., Al Jorf, B., Lechuga López, L. J., Geras, K. J., + and Shamout, F. E. (2025). MedMod: Multimodal benchmark for medical + prediction tasks with electronic health records and chest X-ray scans. + Proceedings of the Conference on Health, Inference, and Learning (CHIL), + PMLR 287. + https://proceedings.mlr.press/v287/elsharief25a.html + Code: https://github.com/nyuad-cai/MedMod + +Methods and models we use: + +- Hayat, N., Geras, K. J., and Shamout, F. E. (2022). MedFuse: Multi-modal + fusion with clinical time-series data and chest X-ray images. Machine + Learning for Healthcare (MLHC). Code and encoder checkpoints: + https://github.com/nyuad-cai/MedFuse +- Zhang, Y., Jiang, H., Miura, Y., Manning, C. D., and Langlotz, C. P. (2022). + Contrastive learning of medical visual representations from paired images + and text. Machine Learning for Healthcare (MLHC). +- Sellergren, A., et al. (2026). MedGemma Technical Report. Nature Medicine + 32, 3695–3704. https://doi.org/10.1038/s41591-026-04626-w (preprint + arXiv:2507.05201). This report introduces MedSigLIP. The model + `google/medsiglip-448` (https://huggingface.co/google/medsiglip-448) is used + under the Health AI Developer Foundations terms of use, + https://developers.google.com/health-ai-developer-foundations/terms + +Data: + +- Johnson, A., Bulgarelli, L., Pollard, T., Horng, S., Celi, L. A., and + Mark, R. (2021). MIMIC-IV (version 1.0). PhysioNet. + https://doi.org/10.13026/s6n6-xd98 +- Johnson, A., Lungren, M., Peng, Y., Lu, Z., Mark, R., Berkowitz, S., and + Horng, S. (2019). MIMIC-CXR-JPG - chest radiographs with structured labels + (version 2.0.0). PhysioNet. https://doi.org/10.13026/8360-t248 +- Johnson, A. E. W., Pollard, T. J., Berkowitz, S. J., Greenbaum, N. R., + Lungren, M. P., Deng, C., Mark, R. G., and Horng, S. (2019). MIMIC-CXR: A + large publicly available database of labeled chest radiographs. + arXiv:1901.07042. https://arxiv.org/abs/1901.07042 +- Johnson, A., Pollard, T., Mark, R., Berkowitz, S., and Horng, S. (2019). + MIMIC-CXR Database (version 2.0.0). PhysioNet. + https://doi.org/10.13026/C2JT1Q +- Johnson, A. E. W., Pollard, T. J., Berkowitz, S. J., Greenbaum, N. R., + Lungren, M. P., Deng, C., Mark, R. G., and Horng, S. (2019). MIMIC-CXR, a + de-identified publicly available database of chest radiographs with + free-text reports. Scientific Data 6, 317. + https://doi.org/10.1038/s41597-019-0322-0 +- Pollard, T., Moody, B. E., Lehman, L., Gow, B., Fernandes, C., Xie, C., + Johnson, A., Mark, R. G., and Heldt, T. (2026). PhysioNet as a global + platform for biomedical research. Nature Health. + https://doi.org/10.1038/s44360-026-00096-z diff --git a/pyhealth/datasets/medmod/__init__.py b/pyhealth/datasets/medmod/__init__.py index c2480cc72a..8b0b2870c7 100644 --- a/pyhealth/datasets/medmod/__init__.py +++ b/pyhealth/datasets/medmod/__init__.py @@ -4,6 +4,11 @@ * ``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. +* ``image_presets``: chest X-ray transforms per model (``get_preset``, + ``load_cxr``). +* ``resize_cxr``: MedFuse's 512-px resize of MIMIC-CXR-JPG images. +* ``synthetic``: synthetic samples with the task's contract + (``create_synthetic_samples``), for development without MIMIC access. * ``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 diff --git a/pyhealth/datasets/medmod/files/NOTICE b/pyhealth/datasets/medmod/files/NOTICE index d0b9d48ee8..5c7a3543c3 100644 --- a/pyhealth/datasets/medmod/files/NOTICE +++ b/pyhealth/datasets/medmod/files/NOTICE @@ -20,12 +20,13 @@ MedMod (Elsharief et al., 2025), https://github.com/nyuad-cai/MedMod 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). + (extraction.py); the simclrv2 transforms (image_presets.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). + behaviours are re-implemented and cited by file and line: the image resize + step (resize_cxr.py), the image transforms (image_presets.py) and 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 diff --git a/pyhealth/datasets/medmod/image_presets.py b/pyhealth/datasets/medmod/image_presets.py new file mode 100644 index 0000000000..7055d5e648 --- /dev/null +++ b/pyhealth/datasets/medmod/image_presets.py @@ -0,0 +1,274 @@ +"""Chest X-ray transforms per model: training and evaluation. + + get_preset("early_fusion") # Early Fusion, val/test + get_preset("early_fusion", train=True) # Early Fusion, train (augmented) + get_preset("convirt") # ConVIRT + linear eval, val/test + get_preset("convirt", train=True) # ConVIRT + linear eval, train + +Early Fusion uses the loaders of MedFuse's released code +(github.com/nyuad-cai/MedFuse, not PyHealth's ``MedFuse`` model) and ConVIRT +MedMod's ``simclrv2`` ones (see the MedModInHospitalMortality docs, +"Per-model settings"). +Training transforms: + +``early_fusion``, train (``medfuse_train``): MedFuse + datasets/cxr_dataset.py:65-72 (literal sizes, not --resize): Resize(256), + RandomHorizontalFlip(), RandomAffine(degrees=45, + scale=(.85, 1.15), shear=0, translate=(0.15, 0.15)), CenterCrop(224), + ToTensor(), ImageNet Normalize. Applied to the train split + (cxr_dataset.py:99). +``convirt``, train (``medmod_simclrv2_train``): MedMod src/data/utils.py:80-101 + (``simclrv2``, chosen by --transforms_cxr simclrv2 in the ConVIRT scripts, + utils.py:115-116): + Resize([256, 256]), RandomAffine(degrees=(-45, 45), translate=(0.1, 0.1), + scale=(0.7, 1.5), shear=(-25, 25)), ``RandomCrop`` (square, side drawn + from U(0.6 * 256, 256), lines 46-53), Resize([224, 224], bicubic), + RandomHorizontalFlip(), ``RandomColorDistortion`` (ColorJitter(0.8, 0.8, + 0.8, 0.2) with probability 0.8, then RandomGrayscale(0.2), lines 57-75), + ToTensor(), no Normalize. Applied to the train split (utils.py:127), in + pretraining and in linear eval / fine-tuning alike. As in MedMod, the two + random draws use numpy's global RNG (``np.random.uniform``); seed it in + each DataLoader worker for reproducible runs. + +Evaluation transforms: + +``early_fusion``, eval (``medfuse_eval``): MedFuse test transforms + (github.com/nyuad-cai/MedFuse datasets/cxr_dataset.py:75-82, with + --resize 256 / --crop 224 defaults + from arguments.py:10-11): Resize(256), CenterCrop(224), ToTensor(), + ImageNet Normalize. MedMod's own copy, src/data/utils.py:37-40, is the + same minus Normalize (it defines `normalize` at line 27 but never appends + it). +``convirt``, eval (``medmod_simclrv2_eval``): MedMod's `simclrv2` test transforms, + src/data/utils.py:99-107 with --resize 256 (src/parser.py:44): + Resize([256, 256]), CenterCrop([224, 224]) (int(0.875 * 256) = 224), + Resize([224, 224], interpolation=3 i.e. bicubic), ToTensor(), no Normalize. + +Both MedFuse and MedMod open images with ``.convert('RGB')`` +(MedMod src/data/datasets.py:64). They also read pre-resized copies: +MedMod globs ``{tmp_dir}/resized/**/*.jpg`` (src/data/utils.py:125), made by +MedFuse resize.py:27-37 (width -> 512, height scaled, saved as JPEG). +``pyhealth.datasets.medmod.resize_cxr`` reproduces that step on disk (settings and +sources +are listed there). ``load_cxr(..., medfuse_preresize=True)`` does the same +in memory for an original image: same resize, then a JPEG round trip with +Pillow's default quality. +""" + +from __future__ import annotations + +import io + +import numpy as np +from PIL import Image +from torchvision import transforms +from torchvision.transforms import InterpolationMode + +from .resize_cxr import medfuse_resize + +IMAGENET_MEAN = [0.485, 0.456, 0.406] +IMAGENET_STD = [0.229, 0.224, 0.225] + + +def medfuse_eval(resize: int = 256, crop: int = 224) -> transforms.Compose: + """MedFuse's eval transform: resize, center crop, ImageNet + normalization. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import medfuse_eval + >>> medfuse_eval()(Image.new("RGB", (512, 600))).shape + torch.Size([3, 224, 224]) + """ + return transforms.Compose( + [ + transforms.Resize(resize), + transforms.CenterCrop(crop), + transforms.ToTensor(), + transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD), + ] + ) + + +def medfuse_train() -> transforms.Compose: + """MedFuse's train transform: ``medfuse_eval`` plus flip and + affine augmentation. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import medfuse_train + >>> medfuse_train()(Image.new("RGB", (512, 600))).shape + torch.Size([3, 224, 224]) + """ + return transforms.Compose( + [ + transforms.Resize(256), + transforms.RandomHorizontalFlip(), + transforms.RandomAffine( + degrees=45, scale=(0.85, 1.15), shear=0, translate=(0.15, 0.15) + ), + transforms.CenterCrop(224), + transforms.ToTensor(), + transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD), + ] + ) + + +class RandomCrop: + """MedMod ``RandomCrop`` (src/data/utils.py:46-53): a square crop whose + side is drawn from U(0.6 * 256, 256), truncated to int. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import RandomCrop + >>> w, h = RandomCrop()(Image.new("RGB", (256, 256))).size + >>> w == h and 153 <= w <= 256 + True + """ + + def __call__(self, img: Image.Image) -> Image.Image: + """Crops a random square from ``img``. + + Args: + img: A PIL image (256 x 256 in MedMod's preset). + + Returns: + The crop, its side drawn from U(153.6, 256). + """ + resize = 256 + size = int(np.random.uniform(0.6 * resize, resize, 1)[0]) + return transforms.RandomCrop(size)(img) + + +class RandomColorDistortion: + """MedMod ``RandomColorDistortion`` (src/data/utils.py:57-75). + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import RandomColorDistortion + >>> RandomColorDistortion()(Image.new("RGB", (224, 224))).size + (224, 224) + """ + + def __call__(self, img: Image.Image) -> Image.Image: + """Randomly jitters the colours of ``img``, then may make it grey. + + Args: + img: A PIL image. + + Returns: + The image after colour jitter (probability 0.8) and greyscale + (probability 0.2). + """ + strength = 1.0 + if np.random.uniform(0, 1, 1)[0] < 0.8: + img = transforms.ColorJitter( + 0.8 * strength, 0.8 * strength, 0.8 * strength, 0.2 * strength + )(img) + return transforms.RandomGrayscale(p=0.2)(img) + + +def medmod_simclrv2_train(resize: int = 256) -> transforms.Compose: + """MedMod's simclrv2 train transform (pixels in [0, 1], + no normalization). As in MedMod, the random crop's side is drawn from + U(0.6 * 256, 256) whatever ``resize`` is. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import medmod_simclrv2_train + >>> medmod_simclrv2_train()(Image.new("RGB", (512, 600))).shape + torch.Size([3, 224, 224]) + """ + return transforms.Compose( + [ + transforms.Resize([resize, resize]), + transforms.RandomAffine( + degrees=(-45, 45), + translate=(0.1, 0.1), + scale=(0.7, 1.5), + shear=(-25, 25), + ), + RandomCrop(), + transforms.Resize([224, 224], interpolation=InterpolationMode.BICUBIC), + transforms.RandomHorizontalFlip(), + RandomColorDistortion(), + transforms.ToTensor(), + ] + ) + + +def medmod_simclrv2_eval(resize: int = 256) -> transforms.Compose: + """MedMod's simclrv2 eval transform: resize, center crop + 0.875, resize to 224 (pixels in [0, 1]). + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import medmod_simclrv2_eval + >>> medmod_simclrv2_eval()(Image.new("RGB", (512, 600))).shape + torch.Size([3, 224, 224]) + """ + c = int(0.875 * resize) + return transforms.Compose( + [ + transforms.Resize([resize, resize]), + transforms.CenterCrop([c, c]), + transforms.Resize([224, 224], interpolation=InterpolationMode.BICUBIC), + transforms.ToTensor(), + ] + ) + + +# name -> (train, eval) +PRESETS = { + "early_fusion": ( + medfuse_train, + medfuse_eval, + ), # MedFuse loaders, ImageNet-normalized + "convirt": (medmod_simclrv2_train, medmod_simclrv2_eval), # MedMod simclrv2, [0, 1] +} + + +def get_preset(name: str, train: bool = False) -> transforms.Compose: + """The image transform for a model: ``"early_fusion"`` (MedFuse's, + ImageNet-normalized) or ``"convirt"`` (MedMod's simclrv2, pixels in [0, 1]; + pretraining and linear eval). ``train=True`` adds the training augmentation; + use it for the train split only. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import get_preset + >>> get_preset("convirt", train=True)(Image.new("RGB", (512, 600))).shape + torch.Size([3, 224, 224]) + """ + if name not in PRESETS: + raise ValueError(f"unknown preset {name!r}; choose from {sorted(PRESETS)}") + train_fn, eval_fn = PRESETS[name] + return train_fn() if train else eval_fn() + + +def _medfuse_preresize(img: Image.Image) -> Image.Image: + """MedFuse resize.py:27-37 plus the JPEG save/load round trip.""" + buf = io.BytesIO() + medfuse_resize(img).save(buf, format="JPEG") # default quality, as resize.py:37 + buf.seek(0) + return Image.open(buf) + + +def load_cxr(path: str, medfuse_preresize: bool = False) -> Image.Image: + """Open a chest X-ray as RGB. ``medfuse_preresize=True`` first applies + MedFuse's 512-px resize and JPEG round trip (for originals). + + Examples: + >>> import os, tempfile + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.image_presets import load_cxr + >>> path = os.path.join(tempfile.mkdtemp(), "cxr.jpg") + >>> Image.new("L", (1024, 1200)).save(path) + >>> img = load_cxr(path, medfuse_preresize=True) + >>> img.size, img.mode + ((512, 600), 'RGB') + """ + img = Image.open(path) + if medfuse_preresize: + img = _medfuse_preresize(img) + return img.convert("RGB") diff --git a/pyhealth/datasets/medmod/medsiglip.py b/pyhealth/datasets/medmod/medsiglip.py new file mode 100644 index 0000000000..66bb2ce7f8 --- /dev/null +++ b/pyhealth/datasets/medmod/medsiglip.py @@ -0,0 +1,446 @@ +"""Frozen MedSigLIP image embeddings for the MedMod extension. + + python -m pyhealth.datasets.medmod.medsiglip \\ + --images /data/mimic-cxr-jpg/2.0.0/resized --out /data/medsiglip_448.npz + +The extension swaps the ResNet-34 image encoder of both models for a frozen +MedSigLIP image encoder (``google/medsiglip-448``). A frozen encoder gives the +same output for an image every time, so each image is embedded once here and +the models read the stored vectors: :func:`lookup_embeddings` gives a batch's +image input for a model built with ``cxr_backbone=nn.Identity()`` and +``cxr_feature_dim=1152`` (the ``--embeddings`` option of the MedMod examples). + +* Model: ``google/medsiglip-448`` at a pinned revision (``REVISION``); only the + vision tower is loaded (``SiglipVisionModel``), frozen and in eval mode. + transformers lists the text tower's weights as unused; that is expected. +* Images: ``Image.open(...).convert("RGB")`` (the model card's example), then + the checkpoint's own image processor, so size, resampling, rescaling, mean + and std all come from its ``preprocessor_config.json``. The inputs are the + 512-px-wide resized JPEGs. +* Embedding: the vision tower's pooled output, which is what + ``get_image_features`` returns; stored unnormalized (the model card's + ``image_embeds`` are the same vectors L2-normalized). +* Output: one ``.npz`` with ``keys`` (image file name without extension), + ``embeddings`` (float32, ``[n, dim]``) and ``meta`` (model, revision, + processor settings, as JSON). It is rewritten every ``save_every`` images, + and a rerun skips the images already in it. Prints counts only. + +Runs with transformers 4.x and 5.x, and also as a standalone script +(``python medsiglip.py ...``; needs numpy, Pillow, torch, transformers). + +MedSigLIP (``google/medsiglip-448``, https://huggingface.co/google/medsiglip-448) +is introduced in Sellergren, A., et al. MedGemma Technical Report. Nature +Medicine 32, 3695-3704 (2026). https://doi.org/10.1038/s41591-026-04626-w +(preprint arXiv:2507.05201). + +The model weights are not part of PyHealth. They are downloaded from the +Hugging Face Hub, which asks you to accept the Health AI Developer Foundations +terms of use first: +https://developers.google.com/health-ai-developer-foundations/terms +""" + +from __future__ import annotations + +import argparse +import json +import os +import tempfile +import time +from collections.abc import Sequence +from pathlib import Path +from typing import Any + +import numpy as np +import torch +import transformers +from PIL import Image +from transformers import AutoImageProcessor, SiglipVisionModel + +MODEL_ID = "google/medsiglip-448" +# ``main`` of google/medsiglip-448 on the Hugging Face Hub on 2026-11-19. +REVISION = "9cea28a1a1195f665105faa6e8544c112fd960a4" +IMAGE_SUFFIXES = (".jpg", ".jpeg", ".png") +PROCESSOR_KEYS = ( + "size", + "resample", + "do_resize", + "do_rescale", + "rescale_factor", + "do_normalize", + "image_mean", + "image_std", + "do_convert_rgb", +) + + +def default_device() -> str: + """CUDA if available, then MPS, else CPU. + + Returns: + The device name. + + Examples: + >>> from pyhealth.datasets.medmod.medsiglip import default_device + >>> default_device() in ("cuda", "mps", "cpu") + True + """ + if torch.cuda.is_available(): + return "cuda" + if torch.backends.mps.is_available(): + return "mps" + return "cpu" + + +def pooled(output: Any) -> torch.Tensor: + """The pooled image features, whether a model returned a tensor + (transformers 4.x ``get_image_features``) or an output object (5.x, and + the vision tower in both). + + Args: + output: A tensor, or an object with ``pooler_output``. + + Returns: + The tensor. + + Examples: + >>> import torch + >>> from pyhealth.datasets.medmod.medsiglip import pooled + >>> pooled(torch.ones(2, 3)).shape + torch.Size([2, 3]) + """ + return output if isinstance(output, torch.Tensor) else output.pooler_output + + +def load_medsiglip( + model_id: str = MODEL_ID, + revision: str | None = REVISION, + device: str | None = None, +) -> tuple[Any, Any]: + """The checkpoint's image processor and its frozen vision tower. + + Args: + model_id: Hub id, or a local folder (then ``revision`` is ignored). + revision: Hub revision. + device: Torch device; None picks :func:`default_device`. + + Returns: + ``(processor, model)``. + + Examples: + >>> from pyhealth.datasets.medmod.medsiglip import load_medsiglip + >>> processor, model = load_medsiglip() # doctest: +SKIP + """ + if Path(model_id).is_dir(): + revision = None + # transformers 5 renamed ``torch_dtype`` to ``dtype``. + major = int(transformers.__version__.split(".")[0]) + dtype_arg = {"dtype" if major >= 5 else "torch_dtype": torch.float32} + processor = AutoImageProcessor.from_pretrained(model_id, revision=revision) + model = SiglipVisionModel.from_pretrained(model_id, revision=revision, **dtype_arg) + model.requires_grad_(False) + model.eval().to(device or default_device()) + return processor, model + + +@torch.inference_mode() +def embed_images( + images: Sequence[Image.Image], processor: Any, model: Any +) -> np.ndarray: + """Embeddings of PIL images, float32 ``[n, dim]``. + + Args: + images: PIL images of any mode and size. + processor: From :func:`load_medsiglip`. + model: From :func:`load_medsiglip`. + + Returns: + The embeddings. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.medsiglip import ( + ... embed_images, load_medsiglip, + ... ) + >>> processor, model = load_medsiglip() # doctest: +SKIP + >>> pic = Image.new("L", (512, 600)) + >>> embed_images([pic], processor, model).shape # doctest: +SKIP + (1, 1152) + """ + rgb = [image.convert("RGB") for image in images] + pixels = processor(images=rgb, return_tensors="pt")["pixel_values"] + out = model(pixel_values=pixels.to(model.device, model.dtype)) + return pooled(out).float().cpu().numpy() + + +def processor_settings(processor: Any) -> dict[str, Any]: + """The processor values that shape the input, for the record. + + Args: + processor: A transformers image processor. + + Returns: + Size, resampling, rescaling and normalization settings. + + Examples: + >>> from transformers import SiglipImageProcessor + >>> from pyhealth.datasets.medmod.medsiglip import processor_settings + >>> p = SiglipImageProcessor(size={"height": 448, "width": 448}) + >>> processor_settings(p)["size"] + {'height': 448, 'width': 448} + """ + config = processor.to_dict() + settings = {k: config[k] for k in PROCESSOR_KEYS if k in config} + settings["type"] = type(processor).__name__ + return json.loads(json.dumps(settings, default=int)) + + +def image_key(path: str | Path) -> str: + """The key of an image: its file name without the extension. + + Args: + path: Image path. + + Returns: + The key. + + Examples: + >>> from pyhealth.datasets.medmod.medsiglip import image_key + >>> image_key("/data/resized/abc.jpg") + 'abc' + """ + return Path(path).stem + + +def list_images(images: str | Path) -> list[Path]: + """Image files in a folder (not recursive), or listed one per line in a + text file (so paths may contain spaces). + + Args: + images: A folder, or a list file. + + Returns: + Sorted paths. + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.medsiglip import list_images + >>> listing = os.path.join(tempfile.mkdtemp(), "list.txt") + >>> _ = open(listing, "w").write("/my data/b.jpg\\n\\n/my data/a.jpg\\n") + >>> [p.name for p in list_images(listing)] + ['a.jpg', 'b.jpg'] + """ + images = Path(images) + if images.is_dir(): + return sorted(p for p in images.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES) + with open(images) as f: + return sorted(Path(line.rstrip("\r\n")) for line in f if line.strip()) + + +def save_embeddings( + path: str | Path, keys: Sequence[str], embeddings: np.ndarray, meta: dict +) -> Path: + """Writes the ``.npz`` atomically (a temporary file, then a rename). + + Args: + path: Output file. + keys: One key per row. + embeddings: ``[n, dim]``, stored as float32. + meta: Settings, stored as JSON. + + Returns: + The path. + + Examples: + >>> import os, tempfile + >>> import numpy as np + >>> from pyhealth.datasets.medmod.medsiglip import save_embeddings + >>> out = os.path.join(tempfile.mkdtemp(), "emb.npz") + >>> save_embeddings(out, ["a"], np.zeros((1, 4)), {"model": "x"}).name + 'emb.npz' + """ + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-", suffix=".npz") + with os.fdopen(fd, "wb") as f: + np.savez( + f, + keys=np.array(list(keys), dtype=str), + embeddings=np.asarray(embeddings, dtype=np.float32), + meta=np.array(json.dumps(meta)), + ) + os.replace(tmp, path) + return path + + +def load_embeddings(path: str | Path) -> tuple[dict[str, int], np.ndarray, dict]: + """Reads a file written by :func:`save_embeddings`. + + Args: + path: The ``.npz``. + + Returns: + ``(index, embeddings, meta)``: ``index`` maps a key to its row. + + Examples: + >>> import os, tempfile + >>> import numpy as np + >>> from pyhealth.datasets.medmod.medsiglip import ( + ... load_embeddings, save_embeddings, + ... ) + >>> out = os.path.join(tempfile.mkdtemp(), "emb.npz") + >>> _ = save_embeddings(out, ["a", "b"], np.eye(2), {"model": "x"}) + >>> index, emb, meta = load_embeddings(out) + >>> index, emb.shape, meta + ({'a': 0, 'b': 1}, (2, 2), {'model': 'x'}) + """ + with np.load(path, allow_pickle=False) as data: + keys = [str(k) for k in data["keys"]] + return ( + {k: i for i, k in enumerate(keys)}, + data["embeddings"], + json.loads(str(data["meta"])), + ) + + +def lookup_embeddings( + paths: Sequence[str | Path], index: dict[str, int], embeddings: np.ndarray +) -> torch.Tensor: + """The stored embeddings of a batch of images, looked up by image path. + + Args: + paths: Image paths, e.g. a batch's ``image_path``. + index: Key to row, from :func:`load_embeddings`. + embeddings: ``[n, dim]``, from :func:`load_embeddings`. + + Returns: + A float32 tensor ``[len(paths), dim]``: the image input of a model + built with ``cxr_backbone=nn.Identity()`` and ``cxr_feature_dim=dim``. + + Raises: + KeyError: An image has no embedding (its name is not shown). + + Examples: + >>> import numpy as np + >>> from pyhealth.datasets.medmod.medsiglip import lookup_embeddings + >>> table = np.arange(6, dtype=np.float32).reshape(2, 3) + >>> lookup_embeddings(["/x/b.jpg", "/y/a.jpg"], {"a": 0, "b": 1}, table) + tensor([[3., 4., 5.], + [0., 1., 2.]]) + """ + try: + rows = [index[image_key(p)] for p in paths] + except KeyError: + raise KeyError("An image has no embedding in the file.") from None + return torch.from_numpy(embeddings[rows]) + + +def compute_embeddings( + paths: Sequence[str | Path], + out: str | Path, + processor: Any, + model: Any, + meta: dict, + batch_size: int = 16, + save_every: int = 256, +) -> dict[str, float]: + """Embeds the images not yet in ``out`` and saves as it goes. + + Args: + paths: Image files with unique file names. + out: The ``.npz``; extended if it exists and was made with ``meta``. + processor: From :func:`load_medsiglip`. + model: From :func:`load_medsiglip`. + meta: Settings recorded in the file (see :func:`main`). + batch_size: Images per forward pass. + save_every: Rewrite the file after about this many new images. + + Returns: + Counts: ``images``, ``already_done``, ``computed``, ``seconds``. + + Examples: + >>> from pyhealth.datasets.medmod.medsiglip import compute_embeddings + >>> out = "emb.npz" + >>> compute_embeddings(paths, out, processor, model, meta) # doctest: +SKIP + """ + keys = [image_key(p) for p in paths] + if len(set(keys)) != len(keys): + raise ValueError(f"{len(keys) - len(set(keys))} images share a file name.") + done_keys: list[str] = [] + rows: list[np.ndarray] = [] + if Path(out).exists(): + index, embeddings, old_meta = load_embeddings(out) + if old_meta != json.loads(json.dumps(meta)): + raise ValueError(f"{out} was made with other settings; use another file.") + done_keys, rows = list(index), [embeddings] + done = set(done_keys) + todo = [p for p, k in zip(paths, keys) if k not in done] + + start, since_save = time.time(), 0 + for i in range(0, len(todo), batch_size): + batch = todo[i : i + batch_size] + images = [] + for p in batch: + with Image.open(p) as image: + image.load() + images.append(image) + rows.append(embed_images(images, processor, model)) + done_keys.extend(image_key(p) for p in batch) + since_save += len(batch) + last = i + batch_size >= len(todo) + if since_save >= save_every or last: + save_embeddings(out, done_keys, np.concatenate(rows), meta) + rows, since_save = [np.concatenate(rows)], 0 + n = i + len(batch) + rate = n / (time.time() - start) + print(f" {n}/{len(todo)} new images saved, {rate:.2f} img/s", flush=True) + return { + "images": len(paths), + "already_done": len(paths) - len(todo), + "computed": len(todo), + "seconds": round(time.time() - start, 1), + } + + +def main(argv: Sequence[str] | None = None) -> None: + """Command line: embed a folder (or list file) of images. + + Args: + argv: Arguments; None reads ``sys.argv``. + + Examples: + >>> from pyhealth.datasets.medmod.medsiglip import main + >>> main(["--images", "resized", "--out", "emb.npz"]) # doctest: +SKIP + """ + ap = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + ap.add_argument("--images", required=True, help="folder, or a list file") + ap.add_argument("--out", required=True, help="output .npz") + ap.add_argument("--model", default=MODEL_ID, help="Hub id or local folder") + ap.add_argument("--revision", default=REVISION) + ap.add_argument("--device", default=None) + ap.add_argument("--batch-size", type=int, default=16) + ap.add_argument("--save-every", type=int, default=256) + ap.add_argument("--limit", type=int, default=0, help="first N images only") + args = ap.parse_args(argv) + + paths = list_images(args.images) + if args.limit: + paths = paths[: args.limit] + processor, model = load_medsiglip(args.model, args.revision, args.device) + meta = { + "model_id": args.model, + "revision": None if Path(args.model).is_dir() else args.revision, + "embedding": "vision tower pooler_output, float32, not L2-normalized", + "dim": int(model.config.hidden_size), + "processor": processor_settings(processor), + } + print(f"{len(paths)} images on {model.device}; {json.dumps(meta)}") + counts = compute_embeddings( + paths, args.out, processor, model, meta, args.batch_size, args.save_every + ) + print(f"done: {counts}") + + +if __name__ == "__main__": + main() diff --git a/pyhealth/datasets/medmod/pretraining.py b/pyhealth/datasets/medmod/pretraining.py new file mode 100644 index 0000000000..196aa354a5 --- /dev/null +++ b/pyhealth/datasets/medmod/pretraining.py @@ -0,0 +1,288 @@ +"""MedMod's ConVIRT pretraining set: phenotyping stays, whole ICU stay + CXR. + +MedMod pretrains ConVIRT with ``--task`` left at its default, phenotyping +(src/parser.py:13; scripts/pretrain/simclr.sh), on the paired train split, and +uses val for its early stopping. This module builds those samples from +MedMod's own extraction output (``extracted_root``: ``root/all_stays.csv`` and +``phenotyping/{train,val}_listfile.csv`` with the episode files, all in +``phenotyping/train/``) and the MIMIC-CXR-JPG metadata and CheXpert CSVs. + +Image pairing, as MedMod (src/data/utils.py): every image of the patient joined +to every stay (``get_all_metadata``), the latest AP image with +intime <= StudyDateTime <= outtime (``get_recent_cxr``, 200-211, 280-286), only +images whose study has a CheXpert row (``get_final_meta``, 342-365), stays on +the split's listfile. Stays whose resized image is missing are dropped. + +EHR, as MedMod's loader (src/data/datasets.py): + +* rows with 0 < Hours < full_stay_time, strict on both sides + (``_read_timeseries``, 137-160), where full_stay_time = + round((outtime - intime) in hours, 3) (utils.py:194-195); MedMod's two dummy + rows if none is left (155-160); +* discretized with end = the listfile's period_length (196, 201): 1-hour bins, + previous-value imputation, masks; ``bins = int(period_length + 1 - 1e-6)``, + so the length varies per stay; +* standardized by ``MedModEHRSequenceProcessor`` (the phenotyping normalizer + by default), whose collate zero-pads a batch and returns the true lengths. + +Real data: 7,755 train / 882 val stays (the paper's Table 2 has 7,756 / 882; +one train image is not served by PhysioNet). +""" + +from __future__ import annotations + +from collections.abc import Sequence +from pathlib import Path + +import numpy as np +import pandas as pd + +from ...processors.medmod_ehr_processor import MedModEHRSequenceProcessor +from ..sample_dataset import SampleDataset, create_sample_dataset +from .discretizer import PH_NORMALIZER, Discretizer +from .extraction import MEDMOD_DUMMY_ROWS + +PRETRAINING_SPLITS = ("train", "val") + + +def _read_table(path: Path) -> pd.DataFrame: + for p in (path, Path(f"{path}.gz")): + if p.exists(): + return pd.read_csv(p) + raise FileNotFoundError(f"{path}(.gz) not found") + + +def pretraining_cohort( + extracted_root: str | Path, + cxr_root: str | Path, + splits: Sequence[str] = PRETRAINING_SPLITS, +) -> pd.DataFrame: + """One row per paired stay: ``split, subject_id, stay_id, study_id, dicom_id``. + + Args: + extracted_root: MedMod's extraction output (``root/``, ``phenotyping/``). + cxr_root: folder with ``mimic-cxr-2.0.0-metadata.csv(.gz)`` and + ``mimic-cxr-2.0.0-chexpert.csv(.gz)``. + splits: listfiles to pair (MedMod pretrains on train, validates on val). + + Returns: + The paired stays, in MedMod's order (split, then the merges' order). + + Examples: + >>> from pyhealth.datasets.medmod.pretraining import pretraining_cohort + >>> cohort = pretraining_cohort("/data/medmod_extracted", + ... "/data/mimic-cxr-jpg/2.0.0") # doctest: +SKIP + >>> cohort["split"].value_counts().to_dict() # doctest: +SKIP + {'train': 7756, 'val': 882} + """ + extracted_root, cxr_root = Path(extracted_root), Path(cxr_root) + meta = _read_table(cxr_root / "mimic-cxr-2.0.0-metadata.csv") + stays = pd.read_csv(extracted_root / "root" / "all_stays.csv") + merged = meta.merge(stays[["subject_id", "stay_id", "intime", "outtime"]], + how="inner", on="subject_id") + merged["StudyTime"] = merged["StudyTime"].apply(lambda x: f"{int(float(x)):06}") + merged["StudyDateTime"] = pd.to_datetime( + merged["StudyDate"].astype(str) + " " + merged["StudyTime"], + format="%Y%m%d %H%M%S", + ) + merged["intime"] = pd.to_datetime(merged["intime"]) + merged["outtime"] = pd.to_datetime(merged["outtime"]) + during = merged[(merged["StudyDateTime"] >= merged["intime"]) + & (merged["StudyDateTime"] <= merged["outtime"])] + ap = during[during["ViewPosition"] == "AP"] + latest = ap.sort_values("StudyDateTime", kind="stable").groupby("stay_id").tail(1) + + chexpert = _read_table(cxr_root / "mimic-cxr-2.0.0-chexpert.csv") + labeled = meta.merge(chexpert[["study_id"]], how="inner", on="study_id") + labeled = labeled.drop_duplicates(subset=["dicom_id"])[["dicom_id"]] + parts = [] + for split in splits: + listfile = pd.read_csv(extracted_root / "phenotyping" / f"{split}_listfile.csv") + part = latest.merge(listfile, how="inner", on="stay_id") + part = part.merge(labeled, how="inner", on="dicom_id") + part.insert(0, "split", split) + parts.append(part) + cohort = pd.concat(parts, ignore_index=True) + return cohort[["split", "subject_id", "stay_id", "study_id", "dicom_id"]] + + +def read_timeseries( + path: str | Path, lower: float, upper: float +) -> tuple[np.ndarray, list[str], bool]: + """MedMod's ``_read_timeseries`` (datasets.py:137-160), line for line. + + Returns: + The rows ``lower < Hours < upper`` (strings), the header, and whether + MedMod's dummy rows replaced an empty window. + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.pretraining import read_timeseries + >>> path = os.path.join(tempfile.mkdtemp(), "episode.csv") + >>> _ = open(path, "w").write("Hours,HR\\n0.0,70\\n1.5,80\\n9.0,90\\n") + >>> rows, header, dummy = read_timeseries(path, 0, 5.0) + >>> rows.tolist(), header, dummy + ([['1.5', '80']], ['Hours', 'HR'], False) + """ + ret = [] + with open(path) as tsfile: + header = tsfile.readline().strip().split(",") + assert header[0] == "Hours" + for line in tsfile: + mas = line.strip().split(",") + t = float(mas[0]) + if t < lower: + continue + elif (t > lower) & (t < upper): + ret.append(np.array(mas)) + elif t > upper: + break + if ret: + return np.stack(ret), header, False + return np.stack([np.array(r) for r in MEDMOD_DUMMY_ROWS]), header, True + + +def read_listfile(path: str | Path) -> dict[str, tuple[str, float]]: + """``stay_id -> (episode file, period_length)``, parsed as MedMod does + (``line.split(',')``, ``float(mas[1])``; datasets.py:96-121). + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.pretraining import read_listfile + >>> path = os.path.join(tempfile.mkdtemp(), "train_listfile.csv") + >>> _ = open(path, "w").write("stay,period_length,stay_id\\n" + ... "1_episode1_timeseries.csv,30.5,201\\n") + >>> read_listfile(path) + {'201': ('1_episode1_timeseries.csv', 30.5)} + """ + out = {} + with open(path) as f: + f.readline() + for line in f: + mas = line.strip().split(",") + out[str(int(float(mas[2])))] = (mas[0], float(mas[1])) + return out + + +def full_stay_times(all_stays: str | Path) -> dict[str, float]: + """``stay_id -> round((outtime - intime) in hours, 3)`` (utils.py:194-195). + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.pretraining import full_stay_times + >>> path = os.path.join(tempfile.mkdtemp(), "all_stays.csv") + >>> _ = open(path, "w").write("stay_id,intime,outtime\\n" + ... "201,2150-01-01 00:00,2150-01-02 06:00\\n") + >>> full_stay_times(path) + {'201': 30.0} + """ + stays = pd.read_csv(all_stays, usecols=["stay_id", "intime", "outtime"]) + hours = (pd.to_datetime(stays["outtime"]) - pd.to_datetime(stays["intime"])).apply( + lambda x: np.round(x.total_seconds() / 60 / 60, 3) + ) + return dict(zip(stays["stay_id"].astype(str), hours)) + + +def load_pretraining_samples( + extracted_root: str | Path, + cxr_root: str | Path, + image_dir: str | Path, + cohort: pd.DataFrame | None = None, +) -> tuple[list[dict], dict]: + """Raw pretraining samples and a funnel of counts. + + Args: + extracted_root: MedMod's extraction output. + cxr_root: folder with the MIMIC-CXR-JPG metadata and CheXpert CSVs. + image_dir: resized images, ``/.jpg``. + cohort: ``pretraining_cohort(...)``; computed if None. + + Returns: + ``(samples, funnel)``. Each sample has ``patient_id``, ``visit_id``, + ``ehr`` (unnormalized float64, ``(bins, 76)``), ``image_path`` and + ``split``. ``funnel`` holds counts per split. + + Examples: + >>> from pyhealth.datasets.medmod.pretraining import ( + ... load_pretraining_samples, + ... ) + >>> samples, funnel = load_pretraining_samples( # doctest: +SKIP + ... "/data/medmod_extracted", "/data/mimic-cxr-jpg/2.0.0", + ... "/data/mimic-cxr-jpg/2.0.0/resized") + """ + extracted_root, image_dir = Path(extracted_root), Path(image_dir) + if cohort is None: + cohort = pretraining_cohort(extracted_root, cxr_root) + pheno = extracted_root / "phenotyping" + upper = full_stay_times(extracted_root / "root" / "all_stays.csv") + disc = Discretizer() + samples, funnel = [], {} + for split in dict.fromkeys(cohort["split"]): + listfile = read_listfile(pheno / f"{split}_listfile.csv") + part = cohort[cohort["split"] == split] + f = funnel[split] = {"listfile_stays": len(listfile), "paired": len(part), + "image_missing": 0, "dummy_rows": 0, "kept": 0} + for row in part.itertuples(index=False): + stay_id = str(row.stay_id) + image = image_dir / f"{row.dicom_id}.jpg" + if not image.is_file(): + f["image_missing"] += 1 + continue + name, period_length = listfile[stay_id] + X, header, dummy = read_timeseries( + pheno / "train" / name, 0, upper[stay_id] + ) + f["dummy_rows"] += int(dummy) + samples.append({ + "patient_id": str(row.subject_id), + "visit_id": stay_id, + "ehr": disc.transform(X, header=header, end=period_length), + "image_path": str(image), + "split": split, + }) + f["kept"] += 1 + return samples, funnel + + +def create_pretraining_dataset( + samples: list[dict], normalizer: str | Path | None = PH_NORMALIZER +) -> SampleDataset: + """A PyHealth ``SampleDataset``: ``ehr`` (varying length, standardized by + ``MedModEHRSequenceProcessor``), ``image_path`` and ``split``. + + Args: + samples: from ``load_pretraining_samples`` (or + ``make_synthetic_pretraining_samples``). + normalizer: a MedMod normalizer file (default: the phenotyping one + MedMod's code loads), or None to fit on the samples whose + ``split`` is ``"train"``. + + Examples: + >>> import tempfile + >>> from pyhealth.datasets.medmod.pretraining import ( + ... create_pretraining_dataset, + ... ) + >>> from pyhealth.datasets.medmod.synthetic import ( + ... make_synthetic_pretraining_samples, + ... ) + >>> raw = make_synthetic_pretraining_samples(tempfile.mkdtemp(), 4) + >>> len(create_pretraining_dataset(raw)) # doctest: +SKIP + 4 + """ + normalizer = None if normalizer is None else str(normalizer) + # create_sample_dataset has no split= (set_task does), so with + # normalizer=None the statistics are fitted on the train split here. + ehr = MedModEHRSequenceProcessor(normalizer) + ehr.fit([s for s in samples if s["split"] == "train"], "ehr") + return create_sample_dataset( + samples, + input_schema={ + "ehr": (MedModEHRSequenceProcessor, {"normalizer": normalizer}), + "image_path": "raw", + }, + output_schema={}, + input_processors={"ehr": ehr}, + dataset_name="medmod_pretraining", + task_name="MedModConVIRTPretraining", + in_memory=False, + ) diff --git a/pyhealth/datasets/medmod/resize_cxr.py b/pyhealth/datasets/medmod/resize_cxr.py new file mode 100644 index 0000000000..b60284ba27 --- /dev/null +++ b/pyhealth/datasets/medmod/resize_cxr.py @@ -0,0 +1,245 @@ +"""Resize MIMIC-CXR-JPG images the way MedFuse's resize.py does. + + from pyhealth.datasets.medmod.resize_cxr import paths_from_metadata, resize_cxr + + root = "/data/mimic-cxr-jpg/2.0.0" + report = resize_cxr(paths_from_metadata(root), f"{root}/resized") + print(report) # counts: resized, skipped, missing, failed + +``paths_from_metadata`` lists every image in the MIMIC-CXR metadata CSV. Any +list of original ``.jpg`` paths works too, for example only the cohort's. + +Settings, with sources (MedFuse = github.com/nyuad-cai/MedFuse, resize.py; +Pillow = github.com/python-pillow/Pillow at tag 8.0.0, the version MedFuse +and MedMod pin, MedFuse environment.yml:129, MedMod environment.yml:145): + +* width 512, height = int(h * 512 / w), aspect ratio kept: resize.py:28, 32-35 +* output: flat folder ``resized/.jpg`` (basename of the input): + resize.py:29, 37 +* resample: none passed (resize.py:35), so Pillow's default. In Pillow 8.0.0 + that is BICUBIC (src/PIL/Image.py:1831), NEAREST only for modes "1"/"P" + (Image.py:1895-1896). Passed explicitly here so newer Pillow gives the same. +* JPEG quality: none passed (resize.py:37), so ``quality=-1`` + (src/PIL/JpegImagePlugin.py:619) and Pillow skips jpeg_set_quality + (src/libImaging/JpegEncode.c:175-176), leaving libjpeg's default. That this + default is 75 is from memory. This module also passes no quality, so it + gets the same libjpeg default. +* format from the ``.jpg`` extension (resize.py:37); here format="JPEG" is + explicit because the file is first written under a temporary name. +* skip an input if a file with the same basename already exists anywhere + under the output folder (recursive glob): resize.py:14, 22-24 +* 10 threads: resize.py:40-47 (speed only, no effect on output) + +Differences from resize.py, none of which change the pixels: + +* writes to a temporary file and renames it, so an interrupted run cannot leave + a truncated JPEG that a later run would then skip; +* a failing image is counted as ``failed`` instead of crashing the pool; +* inputs can be a list of expected paths (e.g. only the cohort's images), so + files that are not on disk are reported as ``missing``. +""" + +from __future__ import annotations + +import os +import tempfile +from collections.abc import Iterable +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass, field +from pathlib import Path + +import pandas as pd +from PIL import Image + +try: # Pillow >= 9.1 + BICUBIC = Image.Resampling.BICUBIC + NEAREST = Image.Resampling.NEAREST +except AttributeError: # pragma: no cover + BICUBIC = Image.BICUBIC + NEAREST = Image.NEAREST + +BASEWIDTH = 512 # MedFuse resize.py:28 + + +def original_path( + cxr_root: str | Path, + subject_id: str | int, + study_id: str | int, + dicom_id: str, +) -> Path: + """files/p/p/s/.jpg + (the layout PyHealth builds in ``process_image_path``, pyhealth/datasets/mimic4.py). + + Examples: + >>> from pyhealth.datasets.medmod.resize_cxr import original_path + >>> str(original_path("/cxr", "123", "456", "abc")) + '/cxr/files/p12/p123/s456/abc.jpg' + """ + sid = str(subject_id) + return ( + Path(cxr_root) + / "files" + / f"p{sid[:2]}" + / f"p{sid}" + / f"s{study_id}" + / f"{dicom_id}.jpg" + ) + + +def medfuse_resize(img: Image.Image, basewidth: int = BASEWIDTH) -> Image.Image: + """resize.py:32-35 with Pillow 8.0.0's default resample made explicit. + + Examples: + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.resize_cxr import medfuse_resize + >>> medfuse_resize(Image.new("L", (1024, 1200))).size + (512, 600) + """ + wpercent = basewidth / float(img.size[0]) + hsize = int(float(img.size[1]) * float(wpercent)) + resample = NEAREST if img.mode in ("1", "P") else BICUBIC + return img.resize((basewidth, hsize), resample) + + +FAILED_FILE = "medmod_ihm_images_failed.txt" # in ; holds MIMIC IDs + + +@dataclass +class ResizeReport: + """Counts from ``resize_cxr``. Paths of missing or failed files are + kept apart (they contain MIMIC IDs); ``str()`` shows counts only. + + Examples: + >>> from pyhealth.datasets.medmod.resize_cxr import ResizeReport + >>> print(ResizeReport(resized=2, skipped=1)) + resized=2 skipped=1 missing=0 failed=0 + """ + resized: int = 0 + skipped: int = 0 + missing: int = 0 + failed: int = 0 + missing_paths: list[str] = field(default_factory=list) + failed_paths: list[str] = field(default_factory=list) + + def write_failed(self, folder: str | Path) -> Path | None: + """Failed paths contain MIMIC IDs, so they go to a file next to the + data (FAILED_FILE), never to the terminal. Returns the file, if any.""" + if not self.failed_paths: + return None + path = Path(folder) / FAILED_FILE + path.write_text("".join(f"{p}\n" for p in self.failed_paths)) + return path + + def __str__(self) -> str: + return ( + f"resized={self.resized} skipped={self.skipped} " + f"missing={self.missing} failed={self.failed}" + ) + + +def _resize_one(src: Path, out_dir: Path) -> None: + dst = out_dir / src.name # resize.py:29, 37 (flat folder, same basename) + with Image.open(src) as img: + small = medfuse_resize(img) + fd, tmp = tempfile.mkstemp(dir=out_dir, prefix=".tmp_", suffix=".jpg") + os.close(fd) + try: + small.save( + tmp, format="JPEG" + ) # no quality: Pillow/libjpeg default, as resize.py:37 + os.replace(tmp, dst) + except BaseException: + if os.path.exists(tmp): + os.remove(tmp) + raise + + +def existing_basenames(out_dir: Path) -> set: + """resize.py:14, 22: basenames of every .jpg under the output folder. + + Examples: + >>> import tempfile + >>> from pathlib import Path + >>> from pyhealth.datasets.medmod.resize_cxr import existing_basenames + >>> existing_basenames(Path(tempfile.mkdtemp())) + set() + """ + return {p.name for p in out_dir.glob("**/*.jpg") if not p.name.startswith(".tmp_")} + + +def resize_cxr( + paths: Iterable[str | Path], out_dir: str | Path, threads: int = 10 +) -> ResizeReport: + """MedFuse resize.py: each image to 512 px wide, saved flat as + ``out_dir/``; basenames already there are skipped. + + Examples: + >>> import tempfile + >>> from pathlib import Path + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.resize_cxr import resize_cxr + >>> src = Path(tempfile.mkdtemp()) / "abc.jpg" + >>> Image.new("L", (1024, 1200)).save(src) + >>> print(resize_cxr([src], src.parent / "resized", threads=1)) + resized=1 skipped=0 missing=0 failed=0 + """ + out_dir = Path(out_dir) + out_dir.mkdir(parents=True, exist_ok=True) + done = existing_basenames(out_dir) + report = ResizeReport() + todo: list[Path] = [] + seen: set = set() + for p in map(Path, paths): + if p.name in done or p.name in seen: # resize.py:24 + report.skipped += 1 + elif not p.is_file(): + report.missing += 1 + report.missing_paths.append(str(p)) + else: + todo.append(p) + seen.add(p.name) + + def work(p: Path) -> str | None: + try: + _resize_one(p, out_dir) + return None + except Exception as e: # noqa: BLE001 + return f"{p}: {e}" + + with ThreadPoolExecutor(max_workers=max(1, threads)) as pool: # resize.py:40-47 + for p, err in zip(todo, pool.map(work, todo)): + if err is None: + report.resized += 1 + else: + report.failed += 1 + report.failed_paths.append(err) + return report + + +def paths_from_metadata( + cxr_root: str | Path, metadata_csv: str | Path | None = None +) -> list[Path]: + """Expected original path of every dicom in the MIMIC-CXR metadata CSV. + + Examples: + >>> import tempfile + >>> from pathlib import Path + >>> from pyhealth.datasets.medmod.resize_cxr import paths_from_metadata + >>> root = Path(tempfile.mkdtemp()) + >>> meta = root / "meta.csv" + >>> _ = meta.write_text("dicom_id,subject_id,study_id\\nabc,123,456\\n") + >>> [str(p.relative_to(root)) for p in paths_from_metadata(root, meta)] + ['files/p12/p123/s456/abc.jpg'] + """ + + root = Path(cxr_root) + if metadata_csv is None: + gz = root / "mimic-cxr-2.0.0-metadata.csv.gz" + metadata_csv = gz if gz.exists() else root / "mimic-cxr-2.0.0-metadata.csv" + meta = pd.read_csv( + metadata_csv, dtype=str, usecols=["dicom_id", "subject_id", "study_id"] + ) + return [ + original_path(root, r.subject_id, r.study_id, r.dicom_id) + for r in meta.itertuples() + ] diff --git a/pyhealth/datasets/medmod/synthetic.py b/pyhealth/datasets/medmod/synthetic.py new file mode 100644 index 0000000000..071ce6adce --- /dev/null +++ b/pyhealth/datasets/medmod/synthetic.py @@ -0,0 +1,466 @@ +"""Synthetic MedMod IHM samples with the exact sample contract, no MIMIC needed. + +For writing and testing model code without MIMIC access. Works like PyHealth's +``create_sample_dataset``; everything after it is the same as on real data:: + + from pyhealth.datasets import get_dataloader + from pyhealth.datasets import split_by_medmod + from pyhealth.datasets.medmod.synthetic import create_synthetic_samples + + samples = create_synthetic_samples(hours_zero="keep", n_stays=300) + # real data instead: samples = dataset.set_task(MedModInHospitalMortality(...)) + train, val, test = split_by_medmod(samples) + train_loader = get_dataloader(train, batch_size=32, shuffle=True) + +Sample contract (identical to ``MedModInHospitalMortality``): + + patient_id str synthetic, prefixed "syn-" (never a MIMIC id) + visit_id str synthetic stay id, "syn-stay-…" + ehr float32 48x76 MedMod layout: 12 z-scored continuous columns, + 47 one-hot columns, 17 masks, in discretizer_config order + (task defaults; ``timestep=2.0`` gives 24x76) + image_path str a dummy grayscale JPG, 512 px wide like resized/ + label 0/1 (a float tensor [1] after PyHealth's binary processor) + split "train" | "val" | "test" + +How the EHR is made: synthetic hourly rows (plausible ICU values, GCS text +categories, random gaps, sometimes a row at Hours == 0) go through the SAME +loader (``medmod.extraction.loader_rows``), MedMod discretizer and +``MedModEHRProcessor`` as the real pipeline. So one-hot blocks, masks, +imputation and normalization behave like the real +data. The values are made up and carry no clinical signal, except +a weak link between label and a few vitals so a model has something to learn. +Real data also has occasional extreme values (MedMod does not clip outliers); +``extreme_rate`` adds a few to exercise that path. + +Split proportions follow the real cohort (4,485 / 488 / 1,241) and are assigned +per patient, like MedMod's subject lists. About 15% of stays are deaths, like the +real 14.9%. +""" + +from __future__ import annotations + +import tempfile +from collections.abc import Iterable, Sequence +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +from PIL import Image + +from ...processors.medmod_ehr_processor import ( + MedModEHRProcessor, + MedModEHRSequenceProcessor, +) +from ...tasks.medmod_mortality_mimic4 import MedModInHospitalMortality +from ..sample_dataset import SampleDataset, create_sample_dataset +from .discretizer import PH_NORMALIZER, Discretizer +from .extraction import DEFAULT_TIMESTEP, N_HOURS, loader_rows +from .medsiglip import image_key, save_embeddings + +SPLIT_FRACTIONS = {"train": 4485 / 6214, "val": 488 / 6214, "test": 1241 / 6214} +DEATH_RATE = 924 / 6214 + +# Continuous channels: (mean, sd, decimals, hours between measurements). +# Plausible adult ICU ranges in the units the pipeline produces after cleaning +# (FiO2 as a fraction, temperature in Celsius). +_CONT = { + "Diastolic blood pressure": (60.0, 12.0, 0, 1), + "Fraction inspired oxygen": (0.45, 0.15, 2, 6), + "Glucose": (135.0, 40.0, 0, 6), + "Heart Rate": (88.0, 16.0, 0, 1), + "Height": (170.0, 10.0, 0, 48), + "Mean blood pressure": (78.0, 12.0, 0, 1), + "Oxygen saturation": (96.5, 2.5, 0, 1), + "Respiratory rate": (19.0, 5.0, 0, 1), + "Systolic blood pressure": (120.0, 20.0, 0, 1), + "Temperature": (36.9, 0.6, 1, 4), + "Weight": (82.0, 18.0, 1, 48), + "pH": (7.38, 0.06, 2, 6), +} +_CAT_EVERY = { # categorical channels: hours between measurements + "Capillary refill rate": 12, + "Glascow coma scale eye opening": 4, + "Glascow coma scale motor response": 4, + "Glascow coma scale total": 8, + "Glascow coma scale verbal response": 4, +} + + +@dataclass +class SyntheticStay: + """One synthetic stay: IHM rows as MedMod's episode files hold them + (strings, '' = missing), label, split and stay length. + + Examples: + >>> from pyhealth.datasets.medmod.synthetic import make_synthetic_stays + >>> stay = make_synthetic_stays(n_stays=1)[0] + >>> len(stay.rows[0]) # Hours + 17 channels + 18 + """ + patient_id: str + visit_id: str + label: int + split: str + rows: list[list[str]] # IHM rows: [Hours, v_1..v_17] as strings ('' = missing) + full_stay_hours: float + + +def _make_rows( + rng: np.random.Generator, + channels: Sequence[str], + possible: dict[str, list[str]], + label: int, + extreme_rate: float, + hours: float = N_HOURS, +) -> list[list[str]]: + n_rows = max(1, int(rng.integers(30, 90) * hours / N_HOURS)) + times = np.sort(rng.uniform(0.05, hours, size=n_rows)) + if rng.random() < 0.3: + times = np.concatenate([[0.0], times]) # a row exactly at Hours == 0 + rows = [] + shift = ( + { + "Heart Rate": 12.0, + "Respiratory rate": 4.0, + "Oxygen saturation": -2.5, + "Systolic blood pressure": -12.0, + } + if label + else {} + ) + for t in times: + row = [repr(float(t))] + [""] * len(channels) + for j, ch in enumerate(channels, start=1): + if ch in _CONT: + mean, sd, dec, every = _CONT[ch] + if rng.random() > 1.0 / every: + continue + v = rng.normal(mean + shift.get(ch, 0.0), sd) + if rng.random() < extreme_rate: + v = mean * rng.choice( + [50.0, 1000.0] + ) # an absurd value, never clipped + row[j] = f"{v:.{dec}f}" if dec else str(int(round(v))) # noqa: RUF046 + else: + if rng.random() > 1.0 / _CAT_EVERY[ch]: + continue + row[j] = str(rng.choice(possible[ch])) + if all(v == "" for v in row[1:]): + # Real rows always hold >= 1 value: MedMod builds them by pivoting + # events per charttime (bench/subject.py:56-68). Keep the Hours == 0 + # row (so drop/keep differ) by giving it a heart rate; skip others. + if t != 0.0: + continue + hr = channels.index("Heart Rate") + 1 + hr_mean, hr_sd = _CONT["Heart Rate"][0], _CONT["Heart Rate"][1] + row[hr] = str(int(round(rng.normal(hr_mean, hr_sd)))) # noqa: RUF046 + rows.append(row) + return rows + + +def make_synthetic_stays( + n_stays: int = 300, seed: int = 0, extreme_rate: float = 0.001 +) -> list[SyntheticStay]: + """Synthetic stays: about 1.1 stays per patient, splits per patient. + + Examples: + >>> from pyhealth.datasets.medmod.synthetic import make_synthetic_stays + >>> stays = make_synthetic_stays(n_stays=10, seed=0) + >>> len(stays), sorted({s.split for s in stays}) <= ["test", "train", "val"] + (10, True) + """ + rng = np.random.default_rng(seed) + disc = Discretizer() + possible = disc._possible_values + stays: list[SyntheticStay] = [] + p = 0 + while len(stays) < n_stays: + p += 1 + split = rng.choice(list(SPLIT_FRACTIONS), p=list(SPLIT_FRACTIONS.values())) + for _ in range(1 if rng.random() < 0.9 else 2): + if len(stays) >= n_stays: + break + label = int(rng.random() < DEATH_RATE) + stays.append( + SyntheticStay( + patient_id=f"syn-{p:05d}", + visit_id=f"syn-stay-{len(stays) + 1:05d}", + label=label, + split=str(split), + rows=_make_rows(rng, disc.channels, possible, label, extreme_rate), + full_stay_hours=float(np.round(rng.uniform(N_HOURS, 240.0), 3)), + ) + ) + # PyHealth's binary label processor needs both classes; so do most metrics. + for split in ("train", "val", "test"): + idx = [i for i, s in enumerate(stays) if s.split == split] + if idx and len({stays[i].label for i in idx}) == 1: + stays[idx[0]].label = 1 - stays[idx[0]].label + return stays + + +def write_dummy_jpg(path: Path, rng: np.random.Generator) -> None: + """A grayscale JPG shaped like a resized portable chest X-ray (512 wide). + + Examples: + >>> import tempfile + >>> from pathlib import Path + >>> import numpy as np + >>> from PIL import Image + >>> from pyhealth.datasets.medmod.synthetic import write_dummy_jpg + >>> path = Path(tempfile.mkdtemp()) / "x.jpg" + >>> write_dummy_jpg(path, np.random.default_rng(0)) + >>> Image.open(path).size[0] + 512 + """ + h = int(rng.integers(560, 640)) + yy, xx = np.mgrid[0:h, 0:512] + base = 90 + 60 * np.exp(-(((xx - 256) / 150.0) ** 2 + ((yy - h / 2) / 220.0) ** 2)) + img = np.clip(base + rng.normal(0, 12, size=base.shape), 0, 255).astype(np.uint8) + path.parent.mkdir(parents=True, exist_ok=True) + Image.fromarray(img, "L").save(path, format="JPEG") + + +def write_synthetic_embeddings( + image_paths: Iterable[str | Path], + out: str | Path, + dim: int = 1152, + seed: int = 0, +) -> Path: + """Random stand-ins for MedSigLIP embeddings of synthetic images. + + Writes the same ``.npz`` format as ``python -m + pyhealth.datasets.medmod.medsiglip``, one random vector per image file + name, so the MedSigLIP extension (``--embeddings``) runs end to end + without the gated model or real images. The vectors carry no information + about the images. + + Args: + image_paths: Paths of the synthetic images, e.g. the samples' + ``image_path`` values. A file name that repeats gets one vector. + out: The ``.npz`` to write. + dim: Vector size. MedSigLIP-448's vectors have 1152 values. + seed: Seed of the random vectors. + + Returns: + The path of the written file. + + Examples: + >>> import os, tempfile + >>> from pyhealth.datasets.medmod.medsiglip import load_embeddings + >>> from pyhealth.datasets.medmod.synthetic import ( + ... write_synthetic_embeddings, + ... ) + >>> out = os.path.join(tempfile.mkdtemp(), "emb.npz") + >>> _ = write_synthetic_embeddings(["/x/a.jpg", "/y/b.jpg"], out, dim=4) + >>> index, emb, meta = load_embeddings(out) + >>> index, emb.shape, meta["model"] + ({'a': 0, 'b': 1}, (2, 4), 'synthetic (random vectors)') + """ + keys = list(dict.fromkeys(image_key(p) for p in image_paths)) + rng = np.random.default_rng(seed) + embeddings = rng.normal(size=(len(keys), dim)).astype(np.float32) + meta = {"model": "synthetic (random vectors)", "dim": dim, "seed": seed} + return save_embeddings(out, keys, embeddings, meta) + + +def make_synthetic_samples( + hours_zero: str, + out_dir: str | Path, + n_stays: int = 300, + seed: int = 0, + extreme_rate: float = 0.001, + timestep: float = DEFAULT_TIMESTEP, +) -> list[dict]: + """Raw sample dicts (what the task's ``__call__`` returns: ``ehr`` + unnormalized float64), plus dummy JPGs in ``out_dir/resized/``. No PyHealth + needed. ``hours_zero`` and ``timestep`` as in the task. + + Examples: + >>> import tempfile + >>> from pyhealth.datasets.medmod.synthetic import make_synthetic_samples + >>> samples = make_synthetic_samples("keep", tempfile.mkdtemp(), n_stays=5) + >>> samples[0]["ehr"].shape, sorted(samples[0]) + ((48, 76), ['ehr', 'image_path', 'label', 'patient_id', 'split', 'visit_id']) + """ + if hours_zero not in ("drop", "keep"): + raise ValueError('hours_zero must be "drop" or "keep"') + disc = Discretizer(timestep=timestep) + rng = np.random.default_rng(seed + 1) + out = [] + for s in make_synthetic_stays(n_stays, seed, extreme_rate): + rows, _ = loader_rows(s.rows, hours_zero, s.full_stay_hours) + ehr = disc.transform(rows, end=float(N_HOURS)) + img = Path(out_dir) / "resized" / f"{s.visit_id}.jpg" + if not img.exists(): + write_dummy_jpg(img, rng) + out.append( + { + "patient_id": s.patient_id, + "visit_id": s.visit_id, + "ehr": ehr, + "image_path": str(img), + "label": s.label, + "split": s.split, + } + ) + return out + + +def create_synthetic_samples( + hours_zero: str, + n_stays: int = 300, + seed: int = 0, + out_dir: str | Path | None = None, + extreme_rate: float = 0.001, + timestep: float = DEFAULT_TIMESTEP, + normalizer: str | Path | None = PH_NORMALIZER, +) -> SampleDataset: + """A PyHealth ``SampleDataset`` of synthetic stays, built with the task's own + schema and processor, so ``samples[i]`` has the same keys, types and shapes + as the real set. Split it with ``split_by_medmod(samples)``. + + Args: + hours_zero: "keep" (Early Fusion) or "drop" (ConVIRT), as in the task. + n_stays: number of stays; use 300+ so val (~8%) isn't tiny. + seed: makes the data reproducible. + out_dir: where the dummy JPGs go (``out_dir/resized``); a temp folder + if not given. + extreme_rate: share of values replaced by an absurd one (no clipping). + timestep: Bin width in hours, as in ``MedModInHospitalMortality``. + The default is 1 hour, as in the released code. + normalizer: As in ``MedModInHospitalMortality``. The default is the + phenotyping normalizer file that the released code uses. + + Returns: + The synthetic samples, with a ``split`` field for ``split_by_medmod``. + + Examples: + >>> from pyhealth.datasets import split_by_medmod + >>> from pyhealth.datasets.medmod.synthetic import create_synthetic_samples + >>> samples = create_synthetic_samples("keep", n_stays=50) # doctest: +SKIP + >>> train, val, test = split_by_medmod(samples) # doctest: +SKIP + """ + task = MedModInHospitalMortality( + hours_zero=hours_zero, timestep=timestep, normalizer=normalizer + ) + + out_dir = ( + Path(out_dir) if out_dir else Path(tempfile.mkdtemp(prefix="medmod_synthetic_")) + ) + raw = make_synthetic_samples( + hours_zero, out_dir, n_stays, seed, extreme_rate, timestep + ) + # create_sample_dataset has no split= (set_task does), so with + # normalizer=None the statistics are fitted on the train split here. + ehr = MedModEHRProcessor(normalizer) + ehr.fit([s for s in raw if s["split"] == "train"], "ehr") + return create_sample_dataset( + raw, + input_schema=task.input_schema, + output_schema=task.output_schema, + input_processors={"ehr": ehr}, + dataset_name="medmod_synthetic", + task_name="MedModInHospitalMortality", + in_memory=False, + ) + + +# ConVIRT pretraining (MedMod's phenotyping train/val stays, whole ICU stay). +PRETRAIN_SPLIT_FRACTIONS = {"train": 7755 / 8637, "val": 882 / 8637} + + +def make_synthetic_pretraining_samples( + out_dir: str | Path, + n_stays: int = 200, + seed: int = 0, + extreme_rate: float = 0.001, + max_hours: float = 480.0, +) -> list[dict]: + """Raw pretraining samples, as MedMod's loader builds them for the whole + ICU stay: rows with 0 < Hours < full_stay_time (src/data/datasets.py: + 137-160), discretized up to the listfile's period_length (datasets.py:196, + 201). ``ehr`` is unnormalized float64, ``(bins, 76)`` with + ``bins = int(period_length + 1 - 1e-6)``, so it varies per stay. Stay + lengths are log-normal (median 60 h, 6 h to ``max_hours``). Samples have + ``patient_id``, ``visit_id``, ``ehr``, ``image_path`` and ``split`` + (``"train"`` / ``"val"``, per patient). + + Examples: + >>> import tempfile + >>> from pyhealth.datasets.medmod.synthetic import ( + ... make_synthetic_pretraining_samples, + ... ) + >>> samples = make_synthetic_pretraining_samples(tempfile.mkdtemp(), n_stays=5) + >>> samples[0]["ehr"].shape[1], sorted(samples[0]) + (76, ['ehr', 'image_path', 'patient_id', 'split', 'visit_id']) + """ + disc = Discretizer() + rng = np.random.default_rng(seed) + img_rng = np.random.default_rng(seed + 1) + out = [] + p = 0 + while len(out) < n_stays: + p += 1 + names, probs = zip(*PRETRAIN_SPLIT_FRACTIONS.items()) + split = str(rng.choice(names, p=probs)) + for _ in range(1 if rng.random() < 0.9 else 2): + if len(out) >= n_stays: + break + hours = float(np.clip(rng.lognormal(np.log(60.0), 0.8), 6.0, max_hours)) + period_length = round(hours, 6) # the listfile's {:.6f} + full_stay_hours = float(np.round(hours, 3)) + rows = _make_rows( + rng, disc.channels, disc._possible_values, 0, extreme_rate, hours + ) + rows, _ = loader_rows(rows, "drop", full_stay_hours) + visit_id = f"syn-stay-{len(out) + 1:05d}" + img = Path(out_dir) / "resized" / f"{visit_id}.jpg" + if not img.exists(): + write_dummy_jpg(img, img_rng) + out.append( + { + "patient_id": f"syn-{p:05d}", + "visit_id": visit_id, + "ehr": disc.transform(rows, end=period_length), + "image_path": str(img), + "split": split, + } + ) + return out + + +def create_synthetic_pretraining_samples( + n_stays: int = 200, + seed: int = 0, + out_dir: str | Path | None = None, + extreme_rate: float = 0.001, +) -> SampleDataset: + """A PyHealth ``SampleDataset`` of synthetic ConVIRT pretraining stays with + the real pretraining set's contract: ``ehr`` of varying length, + standardized with MedMod's phenotyping normalizer; a batch's ``ehr`` is + ``(padded [B, max_bins, 76], lengths [B])`` (``MedModEHRSequenceProcessor``). + Split it with ``split_by_medmod(samples)`` (train, val; test is empty). + + Examples: + >>> from pyhealth.datasets.medmod.synthetic import ( + ... create_synthetic_pretraining_samples, + ... ) + >>> samples = create_synthetic_pretraining_samples(50) # doctest: +SKIP + """ + out_dir = ( + Path(out_dir) if out_dir else Path(tempfile.mkdtemp(prefix="medmod_pretrain_")) + ) + raw = make_synthetic_pretraining_samples(out_dir, n_stays, seed, extreme_rate) + return create_sample_dataset( + raw, + input_schema={ + "ehr": (MedModEHRSequenceProcessor, {"normalizer": str(PH_NORMALIZER)}), + "image_path": "raw", + }, + output_schema={}, + dataset_name="medmod_synthetic_pretraining", + task_name="MedModConVIRTPretraining", + in_memory=False, + ) diff --git a/pyhealth/datasets/medmod_mimic4.py b/pyhealth/datasets/medmod_mimic4.py index 76a644fd4d..d7b432de85 100644 --- a/pyhealth/datasets/medmod_mimic4.py +++ b/pyhealth/datasets/medmod_mimic4.py @@ -311,7 +311,8 @@ def split_by_medmod( """Split a MedMod ``SampleDataset`` by its ``split`` field. Args: - samples: a ``SampleDataset`` from ``set_task`` without ``split``. + samples: a ``SampleDataset`` from ``create_synthetic_samples(...)`` (or + ``set_task`` without ``split``). Returns: train, val, test: ``SampleDataset`` views (``samples.subset``), as @@ -319,7 +320,8 @@ def split_by_medmod( Examples: >>> from pyhealth.datasets import split_by_medmod - >>> samples = dataset.set_task(task) # doctest: +SKIP + >>> from pyhealth.datasets.medmod.synthetic import create_synthetic_samples + >>> samples = create_synthetic_samples("keep", n_stays=50) # doctest: +SKIP >>> train, val, test = split_by_medmod(samples) # doctest: +SKIP """ positions = split_positions(samples[i]["split"] for i in range(len(samples))) diff --git a/pyhealth/tasks/medmod_mortality_mimic4.py b/pyhealth/tasks/medmod_mortality_mimic4.py index e8c0779fcb..fd1877703e 100644 --- a/pyhealth/tasks/medmod_mortality_mimic4.py +++ b/pyhealth/tasks/medmod_mortality_mimic4.py @@ -92,8 +92,8 @@ class MedModInHospitalMortality(BaseTask): 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_dir: folder of resized images (``resized/.jpg``, as + written by ``pyhealth.datasets.medmod.resize_cxr``). 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 diff --git a/tests/core/test_medmod_medsiglip.py b/tests/core/test_medmod_medsiglip.py new file mode 100644 index 0000000000..8318698ecc --- /dev/null +++ b/tests/core/test_medmod_medsiglip.py @@ -0,0 +1,86 @@ +"""MedSigLIP image embeddings (MedMod extension): a tiny random SigLIP and +synthetic images, no download and no real data.""" + +from __future__ import annotations + +import numpy as np +import pytest +import torch +from PIL import Image +from transformers import SiglipConfig, SiglipImageProcessor, SiglipModel + +from pyhealth.datasets.medmod.medsiglip import ( + compute_embeddings, + embed_images, + list_images, + load_embeddings, + load_medsiglip, + main, + pooled, +) + + +@pytest.fixture(scope="module") +def checkpoint(tmp_path_factory): + torch.manual_seed(0) + small = {"hidden_size": 16, "intermediate_size": 24, "num_hidden_layers": 2, + "num_attention_heads": 2} + config = SiglipConfig( + text_config={"vocab_size": 50, "max_position_embeddings": 8, **small}, + vision_config={"image_size": 32, "patch_size": 8, **small}, + ) + path = tmp_path_factory.mktemp("tiny siglip") + SiglipModel(config).save_pretrained(path) + SiglipImageProcessor(size={"height": 32, "width": 32}).save_pretrained(path) + return path + + +@pytest.fixture(scope="module") +def images(tmp_path_factory): + folder = tmp_path_factory.mktemp("my images") # a space in the path + rng = np.random.default_rng(0) + paths = [] + for i in range(5): + path = folder / f"img{i}.jpg" + Image.fromarray(rng.integers(0, 256, (40 + i, 36), dtype=np.uint8)).save(path) + paths.append(path) + return paths + + +def test_embedding_matches_full_model_and_batching(checkpoint, images): + processor, model = load_medsiglip(str(checkpoint), device="cpu") + assert not model.training + assert not any(p.requires_grad for p in model.parameters()) + pics = [Image.open(p) for p in images] + together = embed_images(pics, processor, model) + assert together.shape == (5, 16) and together.dtype == np.float32 + one_by_one = np.concatenate([embed_images([p], processor, model) for p in pics]) + np.testing.assert_allclose(one_by_one, together, atol=1e-5) + full = SiglipModel.from_pretrained(checkpoint).eval() + pixels = processor(images=[p.convert("RGB") for p in pics], return_tensors="pt") + with torch.no_grad(): + ref = pooled(full.get_image_features(pixel_values=pixels["pixel_values"])) + np.testing.assert_allclose(together, ref.numpy(), atol=1e-6) + + +def test_resume_and_list_file(checkpoint, images, tmp_path, capsys): + out = tmp_path / "emb.npz" + listing = tmp_path / "list.txt" + listing.write_text("\n".join(str(p) for p in images[:3]) + "\n") + args = ["--out", str(out), "--model", str(checkpoint), "--device", "cpu", + "--batch-size", "2", "--save-every", "2"] + main(["--images", str(listing), *args]) + assert len(load_embeddings(out)[0]) == 3 + main(["--images", str(images[0].parent), *args]) # skips the 3 done + assert "'already_done': 3, 'computed': 2" in capsys.readouterr().out + + index, embeddings, meta = load_embeddings(out) + assert len(index) == 5 and embeddings.shape == (5, 16) + assert meta["processor"]["size"] == {"height": 32, "width": 32} + processor, model = load_medsiglip(str(checkpoint), device="cpu") + expected = embed_images([Image.open(images[4])], processor, model)[0] + np.testing.assert_allclose(embeddings[index["img4"]], expected, atol=1e-5) + with pytest.raises(ValueError, match="other settings"): + compute_embeddings(images, out, processor, model, {**meta, "dim": 1}) + listed = [p.name for p in list_images(listing)] + assert listed == ["img0.jpg", "img1.jpg", "img2.jpg"] diff --git a/tests/core/test_medmod_mimic4_images.py b/tests/core/test_medmod_mimic4_images.py new file mode 100644 index 0000000000..5522fad06c --- /dev/null +++ b/tests/core/test_medmod_mimic4_images.py @@ -0,0 +1,176 @@ +"""MedMod in-hospital mortality: chest X-ray presets and MedFuse's 512-px resize.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest +import torch +from PIL import Image +from torchvision.transforms import ( + CenterCrop, + InterpolationMode, + Normalize, + RandomAffine, + RandomHorizontalFlip, + Resize, + ToTensor, +) + +from pyhealth.datasets.medmod.image_presets import ( + IMAGENET_MEAN, + IMAGENET_STD, + RandomColorDistortion, + RandomCrop, + get_preset, +) +from pyhealth.datasets.medmod.resize_cxr import ( + BASEWIDTH, + FAILED_FILE, + ResizeReport, + medfuse_resize, + original_path, + resize_cxr, +) +from tests.core.medmod_test_utils import SID + + +def test_eval_presets(): + """MedFuse's Early Fusion and MedMod's ConVIRT evaluation presets.""" + a, b = get_preset("early_fusion"), get_preset("convirt") + assert [type(t) for t in a.transforms] == [Resize, CenterCrop, ToTensor, Normalize] + assert [type(t) for t in b.transforms] == [Resize, CenterCrop, Resize, ToTensor] + assert a.transforms[0].size == 256 and list(a.transforms[1].size) == [224, 224] + assert list(a.transforms[3].mean) == IMAGENET_MEAN + assert list(a.transforms[3].std) == IMAGENET_STD + assert list(b.transforms[0].size) == [256, 256] + assert list(b.transforms[1].size) == [224, 224] + assert list(b.transforms[2].size) == [224, 224] + assert b.transforms[2].interpolation == InterpolationMode.BICUBIC + + img = Image.new("RGB", (2544, 3056), (128, 128, 128)) # portrait CXR-sized + xa, xb = a(img), b(img) + assert tuple(xa.shape) == (3, 224, 224) and tuple(xb.shape) == (3, 224, 224) + assert 0.0 <= float(xb.min()) and float(xb.max()) <= 1.0 # (b): no Normalize + exp = (128 / 255 - IMAGENET_MEAN[0]) / IMAGENET_STD[0] + assert abs(float(xa[0].mean()) - exp) < 1e-3 # (a): ImageNet normalized + + +def test_train_presets(): + """Training presets: MedFuse cxr_dataset.py:65-71, MedMod utils.py:80-101.""" + at, bt = get_preset("early_fusion", train=True), get_preset("convirt", train=True) + with pytest.raises(ValueError, match="early_fusion"): + get_preset("a") + assert [type(t) for t in at.transforms] == [ + Resize, RandomHorizontalFlip, RandomAffine, CenterCrop, ToTensor, Normalize + ] + aff = at.transforms[2] + assert list(aff.degrees) == [-45.0, 45.0] and aff.scale == (0.85, 1.15) + assert aff.translate == (0.15, 0.15) and at.transforms[0].size == 256 + assert [type(t) for t in bt.transforms] == [ + Resize, RandomAffine, RandomCrop, Resize, RandomHorizontalFlip, + RandomColorDistortion, ToTensor, + ] + aff = bt.transforms[1] + assert aff.scale == (0.7, 1.5) and aff.translate == (0.1, 0.1) + assert list(aff.shear) == [-25.0, 25.0] + assert bt.transforms[3].interpolation == InterpolationMode.BICUBIC + + np.random.seed(0) + torch.manual_seed(0) + pixels = np.random.randint(0, 255, (600, 512), np.uint8) + noisy = Image.fromarray(pixels).convert("RGB") + xat, xbt1, xbt2 = at(noisy), bt(noisy), bt(noisy) + assert tuple(xat.shape) == (3, 224, 224) and tuple(xbt1.shape) == (3, 224, 224) + assert 0.0 <= float(xbt1.min()) and float(xbt1.max()) <= 1.0 # no Normalize + assert not torch.equal(xbt1, xbt2) # random augmentation + sizes = {RandomCrop()(Image.new("RGB", (256, 256))).size[0] for _ in range(200)} + assert min(sizes) >= 153 and max(sizes) <= 255 # int(U(153.6, 256)) + + +def _jpg(path: Path, size=(1000, 800), mode="L") -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + rng = np.random.default_rng(0) + arr = rng.integers( + 0, + 256, + size=(size[1], size[0]) + ((3,) if mode == "RGB" else ()), + dtype=np.uint8, + ) + Image.fromarray(arr, mode).save(path, format="JPEG") + return path + + +def test_original_path_layout(tmp_path): + p = original_path(tmp_path, "10000001", "50000001", "d1") # made-up ids + assert p == tmp_path / "files/p10/p10000001/s50000001/d1.jpg" + + +@pytest.mark.parametrize( + "size,mode", + [((1000, 800), "L"), ((2544, 3056), "L"), ((3056, 2544), "RGB"), ((300, 200), "L")], +) +def test_resize_width_512_keeps_aspect(tmp_path, size, mode): + src = _jpg(original_path(tmp_path / "cxr", SID, "50000001", "d1"), size, mode) + out = tmp_path / "resized" + report = resize_cxr([src], out) + assert (report.resized, report.skipped, report.missing, report.failed) == ( + 1, + 0, + 0, + 0, + ) + dst = out / "d1.jpg" # flat folder, same basename + with Image.open(dst) as img: + assert img.format == "JPEG" and img.mode == mode + w, h = img.size + assert w == BASEWIDTH + assert h == int(size[1] * BASEWIDTH / size[0]) # resize.py:32-34 (truncation) + assert abs(w / h - size[0] / size[1]) < 2 / h # aspect ratio kept to within a pixel + + +def test_resize_matches_medfuse_formula_and_bicubic(): + img = Image.fromarray( + np.arange(80 * 100, dtype=np.uint32).reshape(80, 100).astype(np.uint8), "L" + ) + out = medfuse_resize(img) + assert out.size == (512, int(80 * 512 / 100)) + expected = img.resize((512, int(80 * 512 / 100)), Image.Resampling.BICUBIC) + assert np.array_equal(np.asarray(out), np.asarray(expected)) + + +def test_resize_skip_missing_and_report(tmp_path): + root = tmp_path / "cxr" + a = _jpg(original_path(root, SID, "50000001", "a")) + b = _jpg(original_path(root, SID, "50000002", "b")) + gone = original_path(root, SID, "50000003", "gone") # never written + out = tmp_path / "resized" + # an existing file anywhere under resized/ counts as done (resize.py:14, 22-24) + _jpg(out / "old_batch" / "b.jpg", (512, 400)) + r = resize_cxr([a, b, gone], out) + assert (r.resized, r.skipped, r.missing, r.failed) == (1, 1, 1, 0) + assert r.missing_paths == [str(gone)] + assert not (out / "b.jpg").exists() # skipped, not rewritten + r2 = resize_cxr([a, b, gone], out) # second run: nothing left to do + assert (r2.resized, r2.skipped, r2.missing) == (0, 2, 1) + assert not list(out.glob(".tmp_*")) + assert str(r2) == "resized=0 skipped=2 missing=1 failed=0" + + +def test_resize_counts_unreadable_file_as_failed(tmp_path): + bad = original_path(tmp_path / "cxr", SID, "50000001", "bad") + bad.parent.mkdir(parents=True) + bad.write_bytes(b"not a jpeg") + r = resize_cxr([bad], tmp_path / "resized") + assert (r.resized, r.failed) == (0, 1) + assert not (tmp_path / "resized" / "bad.jpg").exists() + + +def test_failed_paths_go_to_a_file_not_the_terminal(tmp_path, capsys): + assert ResizeReport().write_failed(tmp_path) is None + report = ResizeReport(failed=1, failed_paths=["files/p1/s2/d3.jpg: bad"]) + path = report.write_failed(tmp_path) + assert path == tmp_path / FAILED_FILE + assert path.read_text() == "files/p1/s2/d3.jpg: bad\n" + assert "d3" not in str(report) and "d3" not in capsys.readouterr().out diff --git a/tests/core/test_medmod_mimic4_synthetic.py b/tests/core/test_medmod_mimic4_synthetic.py new file mode 100644 index 0000000000..8621b47492 --- /dev/null +++ b/tests/core/test_medmod_mimic4_synthetic.py @@ -0,0 +1,180 @@ +"""MedMod in-hospital mortality: synthetic samples with the task's contract.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest +import torch +from PIL import Image + +from pyhealth.datasets import get_dataloader, split_by_medmod +from pyhealth.datasets.medmod.discretizer import medmod_ehr_funcs +from pyhealth.datasets.medmod.extraction import StayResult +from pyhealth.datasets.medmod.medsiglip import load_embeddings, lookup_embeddings +from pyhealth.datasets.medmod.synthetic import ( + create_synthetic_pretraining_samples, + create_synthetic_samples, + make_synthetic_pretraining_samples, + make_synthetic_samples, + make_synthetic_stays, + write_synthetic_embeddings, +) + +DISC, _ = medmod_ehr_funcs() +HEADER = DISC.output_header() + + +@pytest.fixture(scope="module") +def keep(tmp_path_factory): + return make_synthetic_samples( + "keep", tmp_path_factory.mktemp("syn"), n_stays=8, seed=13 + ) + + +def test_keys_and_types_match_the_real_task(keep): + real_keys = set( + StayResult("p", "s", "h", passed=0, label=0, split="train").sample() + ) + for s in keep: + assert set(s) == real_keys + # what the task returns: unnormalized float64, 1-hour bins by default + assert s["ehr"].dtype == np.float64 and s["ehr"].shape == (48, 76) + assert isinstance(s["patient_id"], str) and s["patient_id"].startswith("syn-") + assert isinstance(s["visit_id"], str) and s["visit_id"].startswith("syn-stay-") + assert s["label"] in (0, 1) and s["split"] in ("train", "val", "test") + + +def test_ehr_layout_is_consistent(keep): + masks = [i for i, n in enumerate(HEADER) if n.startswith("mask->")] + assert len(masks) == 17 and len(DISC.continuous_columns()) == 12 + for s in keep: + x = s["ehr"] + assert np.isfinite(x).all() + assert set(np.unique(x[:, masks])) <= {0.0, 1.0} + for ch in DISC.channels: + cols = [i for i, n in enumerate(HEADER) if n.startswith(ch + "->")] + if cols: # categorical: exactly one hot per hour (observed or imputed) + assert (x[:, cols].sum(axis=1) == 1).all(), ch + observed = np.stack([s["ehr"][:, masks] for s in keep]).mean() + assert 0.05 < observed < 0.9 # some gaps, some observations + + +def test_splits_per_patient_both_labels_and_rates(keep): + by_patient = {} + for s in keep: + by_patient.setdefault(s["patient_id"], set()).add(s["split"]) + assert all(len(v) == 1 for v in by_patient.values()) + for split in ("train", "val", "test"): + labels = {s["label"] for s in keep if s["split"] == split} + assert labels == {0, 1}, split + assert sum(s["split"] == "train" for s in keep) > sum( + s["split"] == "test" for s in keep + ) + + +def test_dummy_images(keep): + for s in keep[:5]: + with Image.open(s["image_path"]) as img: + assert img.format == "JPEG" and img.mode == "L" and img.size[0] == 512 + + +def test_deterministic_and_drop_keep_differ_only_with_a_row_at_hour_zero(tmp_path): + keep_a = make_synthetic_samples("keep", tmp_path, n_stays=8, seed=7) + keep_b = make_synthetic_samples("keep", tmp_path, n_stays=8, seed=7) + drop = make_synthetic_samples("drop", tmp_path, n_stays=8, seed=7) + stays = make_synthetic_stays(8, seed=7) + assert all(np.array_equal(a["ehr"], b["ehr"]) for a, b in zip(keep_a, keep_b)) + for k, d, st in zip(keep_a, drop, stays): + assert (k["visit_id"], k["label"], k["split"]) == ( + d["visit_id"], + d["label"], + d["split"], + ) + has_zero = any(float(r[0]) == 0.0 for r in st.rows) + if not has_zero: # only a row at Hours == 0 can make drop and keep differ + assert np.array_equal(k["ehr"], d["ehr"]) + # ...and some stays with such a row do differ (others don't: a later value in + # the first hour overwrites it, "later value wins", as in real data) + differ = [not np.array_equal(k["ehr"], d["ehr"]) for k, d in zip(keep_a, drop)] + assert any(differ) and sum(differ) <= sum( + any(float(r[0]) == 0.0 for r in st.rows) for st in stays + ) + + +def test_hours_zero_is_required(tmp_path): + with pytest.raises(ValueError): + make_synthetic_samples("maybe", tmp_path, n_stays=5) + + +def test_create_synthetic_samples_works_like_the_real_pipeline(tmp_path): + samples = create_synthetic_samples("keep", n_stays=8, seed=13, out_dir=tmp_path) + train, val, test = split_by_medmod(samples) + assert len(train) + len(val) + len(test) == len(samples) == 8 + s = train[0] + assert s["split"] == "train" and tuple(s["ehr"].shape) == (48, 76) + assert s["ehr"].dtype == torch.float32 + proc = samples.input_processors["ehr"] # the released code's file + assert not proc.learns_statistics and proc.normalizer_file.endswith(".normalizer") + assert Path(s["image_path"]).exists() + assert set(s) >= {"patient_id", "visit_id", "ehr", "image_path", "label", "split"} + batch = next(iter(get_dataloader(train, batch_size=4, shuffle=True, seed=0))) + assert tuple(batch["ehr"].shape) == (4, 48, 76) + + # 2-hour bins, normalizer fitted on the train split only + other = create_synthetic_samples( + "keep", n_stays=8, seed=13, out_dir=tmp_path, timestep=2.0, normalizer=None + ) + ptrain, _, ptest = split_by_medmod(other) + assert tuple(ptrain[0]["ehr"].shape) == (24, 76) + assert other.input_processors["ehr"].learns_statistics + cont = DISC.continuous_columns() + x = np.concatenate([np.asarray(ptrain[i]["ehr"]) for i in range(len(ptrain))]) + np.testing.assert_allclose(x[:, cont].mean(axis=0), 0, atol=1e-4) + xt = np.concatenate([np.asarray(ptest[i]["ehr"]) for i in range(len(ptest))]) + assert np.abs(xt[:, cont].mean(axis=0)).max() > 1e-3 # not fitted on test + + +def test_rows_are_never_empty_like_real_pivot_rows(): + for st in make_synthetic_stays(8, seed=11): + assert all(any(v != "" for v in r[1:]) for r in st.rows) + + +def test_synthetic_pretraining_samples_vary_in_length(tmp_path): + raw = make_synthetic_pretraining_samples(tmp_path, n_stays=8, seed=2) + assert len(raw) == 8 + assert {s["split"] for s in raw} <= {"train", "val"} + bins = [s["ehr"].shape[0] for s in raw] + assert len(set(bins)) > 4 and min(bins) >= 6 and max(bins) <= 481 + assert all(s["ehr"].shape[1] == 76 for s in raw) + assert all(Path(s["image_path"]).exists() for s in raw) + again = make_synthetic_pretraining_samples(tmp_path, n_stays=8, seed=2) + assert all(np.array_equal(a["ehr"], b["ehr"]) for a, b in zip(raw, again)) + + +def test_synthetic_pretraining_batches_carry_true_lengths(tmp_path): + samples = create_synthetic_pretraining_samples(8, seed=1, out_dir=tmp_path) + train, val, test = split_by_medmod(samples) + assert len(train) + len(val) == 8 and len(test) == 0 + ehr, lengths = next(iter(get_dataloader(train, batch_size=4)))["ehr"] + assert ehr.shape[0] == len(lengths) == 4 and ehr.shape[2] == 76 + assert ehr.shape[1] == int(lengths.max()) + for i, n in enumerate(lengths.tolist()): + assert not ehr[i, n:].any() + + +def test_synthetic_embeddings_cover_every_image(keep, tmp_path): + """--embeddings synthetic: one stand-in vector per synthetic image, found + by the same lookup the MedSigLIP extension uses.""" + paths = [s["image_path"] for s in keep] + out = write_synthetic_embeddings(paths + paths[:3], tmp_path / "emb.npz", dim=8) + index, embeddings, meta = load_embeddings(out) + assert len(index) == len(set(paths)) and embeddings.shape == (len(index), 8) + assert meta["model"] == "synthetic (random vectors)" + batch = lookup_embeddings(paths[:4], index, embeddings) + assert tuple(batch.shape) == (4, 8) and str(batch.dtype) == "torch.float32" + again = load_embeddings( + write_synthetic_embeddings(paths, tmp_path / "b.npz", dim=8) + ) + np.testing.assert_array_equal(again[1], embeddings) # same seed, same vectors diff --git a/tests/core/test_medmod_pretraining.py b/tests/core/test_medmod_pretraining.py new file mode 100644 index 0000000000..dce6711f22 --- /dev/null +++ b/tests/core/test_medmod_pretraining.py @@ -0,0 +1,135 @@ +"""MedMod ConVIRT pretraining set, on a tiny fake MedMod extraction (no MIMIC).""" + +import numpy as np +import pandas as pd +import pytest +import torch + +from pyhealth.datasets import get_dataloader +from pyhealth.datasets.medmod.discretizer import Discretizer +from pyhealth.datasets.medmod.pretraining import ( + create_pretraining_dataset, + load_pretraining_samples, + pretraining_cohort, +) +from pyhealth.datasets.medmod.synthetic import ( + create_synthetic_pretraining_samples, + make_synthetic_pretraining_samples, + write_dummy_jpg, +) +from pyhealth.models import ConVIRT +from pyhealth.processors.medmod_ehr_processor import MedModEHRSequenceProcessor + +INTIME = pd.Timestamp("2150-01-01 00:00") + + +def _episode(path, hours_and_hr): + disc = Discretizer() + hr = 1 + disc.channels.index("Heart Rate") + lines = [",".join(disc.header)] + for t, v in hours_and_hr: + row = [repr(float(t))] + [""] * len(disc.channels) + row[hr] = v + lines.append(",".join(row)) + path.write_text("\n".join(lines) + "\n") + + +@pytest.fixture() +def fake(tmp_path): + ext, cxr, img = tmp_path / "ext", tmp_path / "cxr", tmp_path / "resized" + (ext / "root").mkdir(parents=True) + (ext / "phenotyping" / "train").mkdir(parents=True) + cxr.mkdir() + # stays 1-5 (subjects 11-15), 30 h each except stay 4 (10 h) + stays = [(11, 1, 30), (12, 2, 30), (13, 3, 30), (14, 4, 10), (15, 5, 30)] + pd.DataFrame( + [{"subject_id": s, "stay_id": st, "intime": str(INTIME), + "outtime": str(INTIME + pd.Timedelta(hours=float(h)))} for s, st, h in stays] + ).to_csv(ext / "root" / "all_stays.csv", index=False) + + def img_row(dicom, subject, study, hours, view="AP"): + t = INTIME + pd.Timedelta(hours=float(hours)) + return {"dicom_id": dicom, "subject_id": subject, "study_id": study, + "StudyDate": int(t.strftime("%Y%m%d")), + "StudyTime": float(t.strftime("%H%M%S")), "ViewPosition": view} + + pd.DataFrame([ + img_row("a_early", 11, 100, 2), img_row("a_late", 11, 101, 20), + img_row("a_pa", 11, 102, 25, view="PA"), img_row("a_after", 11, 103, 40), + img_row("b_nolabel", 12, 200, 5), # study without a CheXpert row + img_row("c", 13, 300, 5), # stay not on a listfile + img_row("d", 14, 400, 5), # val stay + img_row("e_missing", 15, 500, 5), # resized file missing + ]).to_csv(cxr / "mimic-cxr-2.0.0-metadata.csv", index=False) + pd.DataFrame({"study_id": [100, 101, 102, 103, 300, 400, 500]}).to_csv( + cxr / "mimic-cxr-2.0.0-chexpert.csv", index=False) + header = "stay,period_length,stay_id,label\n" + (ext / "phenotyping" / "train_listfile.csv").write_text( + header + "e1.csv,30.0,1,0\ne2.csv,30.0,2,0\ne5.csv,30.0,5,0\n") + (ext / "phenotyping" / "val_listfile.csv").write_text(header + "e4.csv,10.0,4,1\n") + # stay 1: Hours 0 is dropped (0 < t), 31 is beyond the stay; stay 4: no rows + _episode(ext / "phenotyping" / "train" / "e1.csv", + [(0.0, "60"), (1.5, "70"), (29.0, "80"), (31.0, "90")]) + _episode(ext / "phenotyping" / "train" / "e2.csv", [(1.0, "70")]) + _episode(ext / "phenotyping" / "train" / "e4.csv", [(0.0, "70")]) + _episode(ext / "phenotyping" / "train" / "e5.csv", [(1.0, "70")]) + rng = np.random.default_rng(0) + for dicom in ("a_early", "a_late", "a_pa", "a_after", "b_nolabel", "c", "d"): + write_dummy_jpg(img / f"{dicom}.jpg", rng) + return ext, cxr, img + + +def test_cohort_pairs_latest_ap_with_chexpert_on_listfiles(fake): + ext, cxr, _ = fake + cohort = pretraining_cohort(ext, cxr) + got = sorted(cohort[["split", "stay_id", "dicom_id"]].values.tolist()) + assert got == [["train", 1, "a_late"], ["train", 5, "e_missing"], ["val", 4, "d"]] + + +def test_samples_follow_medmods_loader(fake): + ext, cxr, img = fake + samples, funnel = load_pretraining_samples(ext, cxr, img) + assert funnel["train"]["image_missing"] == 1 + assert funnel["val"]["dummy_rows"] == 1 # stay 4 has only Hours == 0 + by_stay = {s["visit_id"]: s for s in samples} + assert sorted(by_stay) == ["1", "4"] + ehr = by_stay["1"]["ehr"] + assert ehr.shape == (30, 76) # int(30 + 1 - 1e-6) bins + hr = Discretizer().channels.index("Heart Rate") + col = Discretizer()._begin_pos[hr] + assert ehr[1, col] == 70.0 and ehr[29, col] == 80.0 # 1.5 h, 29 h + assert ehr[0, col] != 60.0 # the Hours == 0 row is dropped + assert by_stay["4"]["ehr"].shape == (10, 76) + assert by_stay["4"]["split"] == "val" + + +def test_dataset_batches_carry_lengths(fake): + ext, cxr, img = fake + samples, _ = load_pretraining_samples(ext, cxr, img) + dataset = create_pretraining_dataset(samples) + batch = next(iter(get_dataloader(dataset, batch_size=2, shuffle=False))) + ehr, lengths = batch["ehr"] + assert sorted(lengths.tolist()) == [10, 30] + assert ehr.shape == (2, 30, 76) + + +def test_fitted_normalizer_uses_the_train_split_only(tmp_path): + raw = make_synthetic_pretraining_samples(tmp_path, n_stays=30, seed=0) + assert {s["split"] for s in raw} == {"train", "val"} + dataset = create_pretraining_dataset(raw, normalizer=None) + expected = MedModEHRSequenceProcessor(None) + expected.fit([s for s in raw if s["split"] == "train"], "ehr") + got = dataset.input_processors["ehr"].normalizer + np.testing.assert_allclose(got._means, expected.normalizer._means) + np.testing.assert_allclose(got._stds, expected.normalizer._stds) + +def test_convirt_on_pretraining_batches_of_varying_length(): + dataset = create_synthetic_pretraining_samples(n_stays=6, seed=0) + batch = next(iter(get_dataloader(dataset, batch_size=6))) + _, lengths = batch["ehr"] + assert len(set(lengths.tolist())) > 1 + batch["cxr"] = torch.rand(6, 3, 32, 32) + model = ConVIRT( + dataset, ehr_hidden_dim=8, projection_dim=8, cxr_backbone="resnet18" + ) + assert torch.isfinite(model(**batch)["loss"]) From c04b28b6c400f5a0fcb189085402f644482c6a83 Mon Sep 17 00:00:00 2001 From: dhtrg <87437721+dhtrg@users.noreply.github.com> Date: Mon, 30 Nov 2026 18:09:59 -0500 Subject: [PATCH 6/8] Skip resize temp files when listing images for MedSigLIP resize_cxr leaves a .tmp_*.jpg file behind if it is killed while saving. list_images now skips it, as existing_basenames already does. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- pyhealth/datasets/medmod/medsiglip.py | 9 +++++++-- tests/core/test_medmod_medsiglip.py | 6 ++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/pyhealth/datasets/medmod/medsiglip.py b/pyhealth/datasets/medmod/medsiglip.py index 66bb2ce7f8..41167fdac7 100644 --- a/pyhealth/datasets/medmod/medsiglip.py +++ b/pyhealth/datasets/medmod/medsiglip.py @@ -213,7 +213,9 @@ def image_key(path: str | Path) -> str: def list_images(images: str | Path) -> list[Path]: """Image files in a folder (not recursive), or listed one per line in a - text file (so paths may contain spaces). + text file (so paths may contain spaces). In a folder, ``.tmp_*`` files + are skipped: ``resize_cxr`` leaves one behind if it is killed while + saving an image. Args: images: A folder, or a list file. @@ -231,7 +233,10 @@ def list_images(images: str | Path) -> list[Path]: """ images = Path(images) if images.is_dir(): - return sorted(p for p in images.iterdir() if p.suffix.lower() in IMAGE_SUFFIXES) + return sorted( + p for p in images.iterdir() + if p.suffix.lower() in IMAGE_SUFFIXES and not p.name.startswith(".tmp_") + ) with open(images) as f: return sorted(Path(line.rstrip("\r\n")) for line in f if line.strip()) diff --git a/tests/core/test_medmod_medsiglip.py b/tests/core/test_medmod_medsiglip.py index 8318698ecc..a6438fc7cd 100644 --- a/tests/core/test_medmod_medsiglip.py +++ b/tests/core/test_medmod_medsiglip.py @@ -84,3 +84,9 @@ def test_resume_and_list_file(checkpoint, images, tmp_path, capsys): compute_embeddings(images, out, processor, model, {**meta, "dim": 1}) listed = [p.name for p in list_images(listing)] assert listed == ["img0.jpg", "img1.jpg", "img2.jpg"] + + +def test_list_images_skips_resize_temp_files(tmp_path): + for name in ["b.jpg", "a.png", ".tmp_x1.jpg", "notes.txt"]: + (tmp_path / name).write_bytes(b"") + assert [p.name for p in list_images(tmp_path)] == ["a.png", "b.jpg"] From f92140d2c151b663230c486a383737955de398e7 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 7/8] Add the MedMod runner scripts and Colab notebook Part 4 of 4 of sunlabuiuc/PyHealth#1609. Builds on part 3. Co-authored-by: rainiehu <57816421+Rainie-Hu@users.noreply.github.com> --- examples/medmod_runners/README.md | 125 ++ examples/medmod_runners/__init__.py | 13 + examples/medmod_runners/colab_bundle.py | 144 ++ examples/medmod_runners/convirt_pretrain.py | 376 +++++ examples/medmod_runners/convirt_probe.py | 312 +++++ examples/medmod_runners/early_fusion_run.py | 326 +++++ examples/medmod_runners/pretrain_samples.py | 259 ++++ examples/medmod_runners/provenance.py | 129 ++ examples/medmod_runners/samples.py | 230 +++ examples/medmod_runners/slim_events.py | 253 ++++ examples/mimic4_medmod_convirt.py | 3 +- examples/mimic4_medmod_ihm_colab_runs.ipynb | 1391 +++++++++++++++++++ examples/mimic4_medmod_ihm_early_fusion.py | 1 - examples/mimic4_medmod_ihm_results.md | 3 - 14 files changed, 3559 insertions(+), 6 deletions(-) create mode 100644 examples/medmod_runners/README.md create mode 100644 examples/medmod_runners/__init__.py create mode 100644 examples/medmod_runners/colab_bundle.py create mode 100644 examples/medmod_runners/convirt_pretrain.py create mode 100644 examples/medmod_runners/convirt_probe.py create mode 100644 examples/medmod_runners/early_fusion_run.py create mode 100644 examples/medmod_runners/pretrain_samples.py create mode 100644 examples/medmod_runners/provenance.py create mode 100644 examples/medmod_runners/samples.py create mode 100644 examples/medmod_runners/slim_events.py create mode 100644 examples/mimic4_medmod_ihm_colab_runs.ipynb diff --git a/examples/medmod_runners/README.md b/examples/medmod_runners/README.md new file mode 100644 index 0000000000..d141c38d53 --- /dev/null +++ b/examples/medmod_runners/README.md @@ -0,0 +1,125 @@ +# MedMod runner scripts + +These scripts produced the real-data results in +[`../mimic4_medmod_ihm_results.md`](../mimic4_medmod_ihm_results.md). They +train the same models with the same settings as the example scripts +`mimic4_medmod_ihm_early_fusion.py` and `mimic4_medmod_convirt.py`. They also +compute bootstrap confidence intervals, write a JSON report for every run and +save checkpoints, so that a run continues after a disconnect. The Colab +notebook [`../mimic4_medmod_ihm_colab_runs.ipynb`](../mimic4_medmod_ihm_colab_runs.ipynb) +runs all of them. + +The runs need credentialed PhysioNet access to MIMIC-IV v1.0 and +MIMIC-CXR-JPG 2.0.0. Keep the data out of the code folder and out of git. The +scripts print only aggregates, such as counts, losses and scores. + +| Script | What it does | +|---|---| +| `slim_events.py` | Writes the slim copy of the MIMIC-IV event tables (once) | +| `samples.py` | Builds and checks an in-hospital mortality sample set | +| `early_fusion_run.py` | Trains and tests Early Fusion | +| `pretrain_samples.py` | Builds the ConVIRT pretraining samples | +| `convirt_pretrain.py` | Pretrains ConVIRT | +| `convirt_probe.py` | Trains and tests the linear probe on a pretraining checkpoint | +| `colab_bundle.py` | Zips the code and data for Google Colab | +| `provenance.py` | Records the code version in every report and checkpoint | + +Run each script from the repository root. This shows its options: +`python -m examples.medmod_runners.