From 992886f3e07d2949ace1b889018c2038ef24fa66 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Thu, 5 Nov 2026 12:50:06 -0600 Subject: [PATCH 01/10] Add EthosProcessor, the ETHOS timeline tokenizer for MEDS Turns a patient's MEDS rows into ETHOS tokens: per-code quantile tokens for numeric values, fitted on the training split, and 19 time-interval tokens for gaps between events. Co-Authored-By: Claude Opus 5.5 --- docs/api/processors.rst | 2 + .../pyhealth.processors.EthosProcessor.rst | 11 + examples/ethos_timeline_tokenizer.py | 127 +++++ pyhealth/processors/__init__.py | 2 + pyhealth/processors/ethos_processor.py | 437 ++++++++++++++++++ tests/core/test_ethos_processor.py | 379 +++++++++++++++ 6 files changed, 958 insertions(+) create mode 100644 docs/api/processors/pyhealth.processors.EthosProcessor.rst create mode 100644 examples/ethos_timeline_tokenizer.py create mode 100644 pyhealth/processors/ethos_processor.py create mode 100644 tests/core/test_ethos_processor.py diff --git a/docs/api/processors.rst b/docs/api/processors.rst index 64a4c2215b..de3fecb269 100644 --- a/docs/api/processors.rst +++ b/docs/api/processors.rst @@ -29,6 +29,7 @@ Available Processors - ``NestedSequenceProcessor``: For nested categorical sequences (e.g., drug recommendation with visit history) - ``NestedMultiHotProcessor``: For nested categorical sequences as per-visit multi-hot vectors (e.g., generative EHR models) - ``NestedFloatsProcessor``: For nested numerical sequences with optional forward-fill +- :doc:`EthosProcessor `: Tokenizes MEDS patient timelines the way ETHOS does, with quantile tokens for numeric values and time-interval tokens (``"ethos"``, fitted on the training split) **Label Processors:** @@ -564,6 +565,7 @@ API Reference processors/pyhealth.processors.ImageProcessor processors/pyhealth.processors.TextProcessor processors/pyhealth.processors.TupleTimeTextProcessor + processors/pyhealth.processors.EthosProcessor processors/pyhealth.processors.AudioProcessor processors/pyhealth.processors.SignalProcessor processors/pyhealth.processors.TimeseriesProcessor diff --git a/docs/api/processors/pyhealth.processors.EthosProcessor.rst b/docs/api/processors/pyhealth.processors.EthosProcessor.rst new file mode 100644 index 0000000000..8bce898167 --- /dev/null +++ b/docs/api/processors/pyhealth.processors.EthosProcessor.rst @@ -0,0 +1,11 @@ +pyhealth.processors.EthosProcessor +================================== + +Tokenizes a MEDS patient timeline the way ETHOS does: numeric values become +per-code quantile tokens and gaps between events become time-interval tokens. +Registered as ``"ethos"``. + +.. autoclass:: pyhealth.processors.EthosProcessor + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/ethos_timeline_tokenizer.py b/examples/ethos_timeline_tokenizer.py new file mode 100644 index 0000000000..7db0a84e16 --- /dev/null +++ b/examples/ethos_timeline_tokenizer.py @@ -0,0 +1,127 @@ +"""Tokenize MEDS patient timelines the way ETHOS does. + +Smoke test on synthetic data: this writes a five-patient MEDS directory to a +temporary folder, so it needs no credentials and no download. The numbers mean +nothing clinically and nothing here reproduces a result from the paper. + +The steps are the same on a real MEDS export: point ``MEDSDataset`` at it, +keep the task below, and fit on the training patients only. + +Usage: + python examples/ethos_timeline_tokenizer.py +""" + +import tempfile +from datetime import datetime, timedelta +from pathlib import Path +from typing import ClassVar + +import pyarrow as pa +import pyarrow.parquet as pq + +from pyhealth.datasets import MEDSDataset, PatientSplit, get_dataloader +from pyhealth.tasks.base_task import BaseTask + + +class EthosTimeline(BaseTask): + """One sample per patient: the whole MEDS timeline. + + The label only makes the task complete; nothing is trained here. + """ + + task_name = "EthosTimeline" + input_schema: ClassVar[dict[str, str]] = {"timeline": "ethos"} + output_schema: ClassVar[dict[str, str]] = {"label": "binary"} + + def __call__(self, patient): + events = patient.get_events(event_type="meds", return_df=True) + if events.height == 0: + return [] + return [ + { + "patient_id": patient.patient_id, + "timeline": { + "time": events["timestamp"].to_list(), + "code": events["meds/code"].to_list(), + "numeric_value": events["meds/numeric_value"].to_list(), + }, + "label": int(patient.patient_id) % 2, + } + ] + + +def write_synthetic_meds(root: Path) -> None: + """Writes five patients in the MEDS layout.""" + start = datetime.fromisoformat("2024-01-01T08:00:00") # MEDS times are naive + rows = [] + for patient in range(5): + hemoglobin = 10.0 + patient + rows += [ + (patient, None, "GENDER//F", None), + (patient, start, "HOSPITAL_ADMISSION//EMERGENCY", None), + (patient, start, "LAB//HEMOGLOBIN", hemoglobin), + (patient, start, "LAB//LACTATE", 1.0 + patient / 2), + (patient, start + timedelta(minutes=3), "MEDICATION//ASPIRIN", None), + (patient, start + timedelta(hours=6), "LAB//HEMOGLOBIN", hemoglobin + 1), + (patient, start + timedelta(days=2), "HOSPITAL_DISCHARGE//HOME", None), + (patient, start + timedelta(days=400), "HOSPITAL_ADMISSION//ELECTIVE", None), + ] + subject_id, time, code, numeric_value = map(list, zip(*rows)) + (root / "data" / "train").mkdir(parents=True) + (root / "metadata").mkdir() + pq.write_table( + pa.table( + { + "subject_id": pa.array(subject_id, type=pa.int64()), + "time": pa.array(time, type=pa.timestamp("us")), + "code": pa.array(code, type=pa.string()), + "numeric_value": pa.array(numeric_value, type=pa.float32()), + } + ), + root / "data" / "train" / "0.parquet", + ) + patients = sorted(set(subject_id)) + pq.write_table( + pa.table( + { + "subject_id": pa.array(patients, type=pa.int64()), + "split": pa.array(["train"] * len(patients), type=pa.string()), + } + ), + root / "metadata" / "subject_splits.parquet", + ) + + +def main() -> None: + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "meds" + write_synthetic_meds(root) + + dataset = MEDSDataset(root=str(root), cache_dir=str(Path(tmp) / "cache")) + # The split makes fit() see the training patients only, so the code + # vocabulary and quantile breaks do not depend on test patients. + train, test = dataset.set_task( + EthosTimeline(), + split=PatientSplit(ratios=(0.6, 0.4), seed=0), + num_workers=1, + ) + print("train and test samples:", len(train), len(test)) + processor = train.input_processors["timeline"] + print(processor) + print("quantile breaks:", processor.quantiles) + + time, tokens = test[0]["timeline"] + print("hours token") + for hours, token in zip(time.tolist(), processor.decode(tokens)): + print(f"{hours:7.2f} {token}") + + batch = next(iter(get_dataloader(train, batch_size=5))) + print("batched tokens:", batch["timeline"][1].shape) + + path = str(Path(tmp) / "ethos_processor.json") + processor.save(path) + print("saved fitted state:", Path(path).stat().st_size, "bytes") + + +if __name__ == "__main__": + main() diff --git a/pyhealth/processors/__init__.py b/pyhealth/processors/__init__.py index 507fb0ffa6..c1e99d4a23 100644 --- a/pyhealth/processors/__init__.py +++ b/pyhealth/processors/__init__.py @@ -65,6 +65,7 @@ def get_processor(name: str): from .temporal_timeseries_processor import TemporalTimeseriesProcessor from .tuple_time_text_processor import TupleTimeTextProcessor from .cehr_processor import CehrProcessor, ConceptVocab +from .ethos_processor import EthosProcessor # Expose public API from .base_processor import ( @@ -106,4 +107,5 @@ def get_processor(name: str): "TupleTimeTextProcessor", "CehrProcessor", "ConceptVocab", + "EthosProcessor", ] diff --git a/pyhealth/processors/ethos_processor.py b/pyhealth/processors/ethos_processor.py new file mode 100644 index 0000000000..ae84ae4078 --- /dev/null +++ b/pyhealth/processors/ethos_processor.py @@ -0,0 +1,437 @@ +"""ETHOS timeline tokenizer for MEDS patient timelines. + +Turns a patient's MEDS rows into an ETHOS Patient Health Timeline: a flat +token sequence where each code is followed by a quantile token (``Q1`` ... +``Q10``) when it has a numeric value, and gaps between events are written as +time-interval tokens. + +Paper: + Renc et al. Foundation Model of Electronic Medical Records for Adaptive + Risk Estimation. https://arxiv.org/abs/2502.06124 + +Adapted from ethos-ares (commit 2d54383), ``src/ethos/tokenize/common``: +https://github.com/ipolharvard/ethos-ares + +MIT License. Copyright (c) 2024 Paweł Renc. +""" + +from __future__ import annotations + +import bisect +import math +from collections import defaultdict +from collections.abc import Iterable, Sequence +from datetime import timedelta +from pathlib import Path +from typing import Any + +import numpy as np +import orjson +import pandas as pd +import torch + +from . import register_processor +from .base_processor import FeatureProcessor +from .cehr_processor import ConceptVocab + +DEATH_CODE = "MEDS_DEATH" +DISCHARGE_PREFIX = "HOSPITAL_DISCHARGE" +TIMELINE_END_TOKEN = "TIMELINE_END" + +#: Codes ETHOS moves into the static patient context, away from the timeline. +STATIC_CODE_PREFIXES: tuple[str, ...] = ( + "MEDS_BIRTH", + "GENDER", + "MARITAL", + "RACE", +) + +#: Interval tokens and their inclusive lower bounds. A gap under the first +#: bound gets no token; a gap past the last repeats its token. +TIME_INTERVALS: tuple[tuple[str, timedelta], ...] = ( + ("5m-15m", timedelta(minutes=5)), + ("15m-45m", timedelta(minutes=15)), + ("45m-1h15m", timedelta(minutes=45)), + ("1h15m-2h", timedelta(hours=1, minutes=15)), + ("2h-3h", timedelta(hours=2)), + ("3h-5h", timedelta(hours=3)), + ("5h-8h", timedelta(hours=5)), + ("8h-12h", timedelta(hours=8)), + ("12h-18h", timedelta(hours=12)), + ("18h-1d", timedelta(hours=18)), + ("1d-2d", timedelta(days=1)), + ("2d-4d", timedelta(days=2)), + ("4d-7d", timedelta(days=4)), + ("7d-12d", timedelta(days=7)), + ("12d-20d", timedelta(days=12)), + ("20d-30d", timedelta(days=20)), + ("30d-2mt", timedelta(days=30)), + ("2mt-6mt", timedelta(days=60)), + ("=6mt", timedelta(days=180)), +) + +_MICROSECONDS = timedelta(microseconds=1) +_INTERVAL_LABELS = [label for label, _ in TIME_INTERVALS] +_INTERVAL_BOUNDS = [bound // _MICROSECONDS for _, bound in TIME_INTERVALS] +_MICROSECONDS_PER_HOUR = timedelta(hours=1) // _MICROSECONDS + + +def _interval_tokens(gap: int) -> list[str]: + """Returns the interval tokens for a gap given in microseconds.""" + if gap >= _INTERVAL_BOUNDS[-1]: + # Half away from zero, as polars rounds; Python's round() would not. + repeats = math.floor(gap / _INTERVAL_BOUNDS[-1] + 0.5) + return [_INTERVAL_LABELS[-1]] * repeats + index = bisect.bisect_right(_INTERVAL_BOUNDS, gap) - 1 + return [] if index < 0 else [_INTERVAL_LABELS[index]] + + +def _quantile_breaks(values: list[float], num_quantiles: int) -> list[float]: + """Returns one code's sorted, deduplicated inner quantile breaks. + + Quantiles use the nearest observation, with ties in the position rounded + up, which is how polars' default ``quantile`` picks them. + """ + ordered = np.sort(np.asarray(values, dtype=np.float64)) + levels = np.linspace(0, 1, num_quantiles + 1)[1:-1] + positions = np.floor((len(ordered) - 1) * levels + 0.5).astype(np.int64) + return np.unique(ordered[positions]).tolist() + + +def _timestamps(times: Sequence[Any]) -> np.ndarray: + """Returns the times as ``datetime64[us]``, with NaT for missing ones. + + MIMIC dates are shifted past 2100 and birth dates can be far earlier, so + this avoids pandas' nanosecond range, which ends in 2262. + """ + if pd.api.types.infer_dtype(times, skipna=True) in ( + "integer", + "floating", + "mixed-integer-float", + ): + raise TypeError( + "EthosProcessor needs datetimes in 'time', got numbers. MEDS times " + "are timestamps; a bare number has no unit to bin gaps with." + ) + return np.array( + [None if pd.isna(time) else time for time in times], dtype="datetime64[us]" + ) + + +def _place_death_before_discharge( + order: list[int], times: np.ndarray, codes: Sequence[str] +) -> list[int]: + """Puts a death ahead of a discharge recorded at the same time. + + Both move to the slot of the later of the two, as in ETHOS, so the rest of + the rows sharing that timestamp keep their order. + + Args: + order: Row indices sorted by time. + times: Time of each row. + codes: Code of each row. + + Returns: + ``order`` with the affected rows moved. + """ + death_times = {times[i] for i in order if codes[i] == DEATH_CODE} + for time in death_times: + slots = [ + slot + for slot, i in enumerate(order) + if times[i] == time + and (codes[i] == DEATH_CODE or codes[i].startswith(DISCHARGE_PREFIX)) + ] + rows = [order[slot] for slot in slots] + deaths = [i for i in rows if codes[i] == DEATH_CODE] + discharges = [i for i in rows if codes[i] != DEATH_CODE] + first = next(s for s, i in enumerate(order) if times[i] == time) + others = [i for i in order[first : slots[-1] + 1] if i not in rows] + order[first : slots[-1] + 1] = others + deaths + discharges + return order + + +@register_processor("ethos") +class EthosProcessor(FeatureProcessor): + """Tokenizes a MEDS patient timeline the way ETHOS does. + + The input is one patient's rows as columns, named as in MEDS: + + * ``time``: a timestamp per row. Rows without one are static and dropped. + * ``code``: a string per row. Rows without one are dropped. + * ``numeric_value``: a number or ``None`` per row. May be left out. + + Rows are sorted by time, and rows sharing a timestamp keep their input + order, except that ``MEDS_DEATH`` goes ahead of a same-time discharge. + Each row then becomes its code, followed by a quantile token if it has a + value. ETHOS has no marker for a shared timestamp: such rows are told + apart only by having no interval token between them. + + A gap between neighboring rows of at least 5 minutes puts one of 19 + interval tokens before the later row. Gaps are measured row to row, so + rows 4 minutes apart never get a token however long the run is. A gap of + 6 months or more repeats ``=6mt``, rounded to the nearest count. Timelines + end with ``TIMELINE_END``. + + :meth:`fit` learns the code vocabulary and, per code, the quantile breaks + of its values. ``Qk`` means ``k - 1`` breaks are strictly below the value, + so a value equal to a break takes the lower bin. Values outside the range + seen in training fall in the first or last bin. Breaks are deduplicated, + so a code with repeated values has fewer bins, and ``Qk`` is then a rank + among its bins and not a true decile. Quantile tokens are shared across + codes. Fit on the training split only: + ``set_task(task, split=PatientSplit(...))``, or reuse this processor for + test data through ``input_processors``. + + An unseen code becomes ```` with no quantile token. All quantile and + interval tokens are in the vocabulary, whether or not training saw them. + + Args: + num_quantiles: Number of bins per code. ETHOS uses 10. + quantize_prefixes: Quantize only codes with one of these prefixes. By + default every code with a value is quantized. + exclude_prefixes: Drop codes with one of these prefixes. By default + the codes that ETHOS keeps as static context, which this processor + does not emit. + add_timeline_end: Whether to append ``TIMELINE_END``. Turn this off if + the timeline is cut at a prediction time and does not end there. + + Examples: + >>> from datetime import datetime + >>> from pyhealth.processors import EthosProcessor + >>> timeline = { + ... "time": [datetime(2024, 1, 1, h) for h in (8, 9, 11)], + ... "code": ["LAB//HGB"] * 3, + ... "numeric_value": [10.0, 12.0, 14.0], + ... } + >>> processor = EthosProcessor(num_quantiles=2) + >>> processor.fit([{"timeline": timeline}], "timeline") + >>> time, tokens = processor.process(timeline) + >>> processor.decode(tokens) + ['LAB//HGB', 'Q1', '45m-1h15m', 'LAB//HGB', 'Q1', '2h-3h', 'LAB//HGB', 'Q2', 'TIMELINE_END'] + >>> time.tolist() + [0.0, 0.0, 1.0, 1.0, 1.0, 3.0, 3.0, 3.0, 3.0] + """ + + learns_statistics = True + stores_tensor = True + + def __init__( + self, + num_quantiles: int = 10, + quantize_prefixes: Sequence[str] | None = None, + exclude_prefixes: Sequence[str] = STATIC_CODE_PREFIXES, + add_timeline_end: bool = True, + ) -> None: + if num_quantiles < 2: + raise ValueError(f"num_quantiles must be at least 2, got {num_quantiles}.") + self.num_quantiles = num_quantiles + self.quantize_prefixes = ( + None if quantize_prefixes is None else tuple(quantize_prefixes) + ) + self.exclude_prefixes = tuple(exclude_prefixes) + self.add_timeline_end = add_timeline_end + self.vocab: ConceptVocab | None = None + self.quantiles: dict[str, list[float]] = {} + + def _read( + self, timeline: dict[str, Any] | None + ) -> tuple[np.ndarray, list[str], np.ndarray]: + """Returns the timeline's kept rows in token order. + + Args: + timeline: Raw timeline, as in the class docstring. + + Returns: + Times in microseconds, codes, and values with ``nan`` where a row + has no usable value. + + Raises: + ValueError: If the columns differ in length. + """ + empty = (np.empty(0, dtype=np.int64), [], np.empty(0)) + if not timeline or len(timeline["code"]) == 0: + return empty + + times, codes = timeline["time"], timeline["code"] + numbers = timeline.get("numeric_value") + if numbers is None: + numbers = [None] * len(codes) + if not len(times) == len(codes) == len(numbers): + raise ValueError( + "EthosProcessor needs time, code and numeric_value of one length, " + f"got {len(times)}, {len(codes)} and {len(numbers)}." + ) + + parsed = _timestamps(times) + stamps, missing = parsed.astype(np.int64), np.isnat(parsed) + values = np.array(numbers, dtype=np.float64) + values[~np.isfinite(values)] = np.nan + kept = [ + i + for i, code in enumerate(codes) + if not missing[i] + and code is not None + and not code.startswith(self.exclude_prefixes) + ] + if not kept: + return empty + + # A stable sort keeps the input order of rows sharing a timestamp. + order = [kept[i] for i in np.argsort(stamps[kept], kind="stable")] + order = _place_death_before_discharge(order, stamps, codes) + return stamps[order], [codes[i] for i in order], values[order] + + def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: + """Learns the vocabulary and quantile breaks. + + Args: + samples: Sample dictionaries. Pass the training split only. + field: Key of the raw timeline in each sample. + """ + observed: dict[str, list[float]] = defaultdict(list) + codes: set[str] = set() + for sample in samples: + _, sample_codes, values = self._read(sample.get(field)) + codes.update(sample_codes) + for code, value in zip(sample_codes, values.tolist()): + if math.isnan(value): + continue + if self.quantize_prefixes is None or code.startswith( + self.quantize_prefixes + ): + observed[code].append(value) + + self.quantiles = { + code: _quantile_breaks(values, self.num_quantiles) + for code, values in observed.items() + } + self.vocab = ConceptVocab() + for k in range(1, self.num_quantiles + 1): + self.vocab.add_token(f"Q{k}") + for label in _INTERVAL_LABELS: + self.vocab.add_token(label) + self.vocab.add_token(TIMELINE_END_TOKEN) + for code in sorted(codes): + self.vocab.add_token(code) + + def process(self, value: dict[str, Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Tokenizes one timeline. + + Args: + value: Raw timeline, as in the class docstring. + + Returns: + ``(time, tokens)``, both 1-D and of the same length. ``time`` is + ``float64`` hours since the first kept row, per token; an interval + token has the time of the row after it. ``tokens`` is ``long``. + Both are empty for a timeline with no kept rows, which gets no + ``TIMELINE_END`` either. + + Raises: + RuntimeError: If called before :meth:`fit` or :meth:`load`. + """ + if self.vocab is None: + raise RuntimeError("EthosProcessor must be fitted or loaded first.") + + stamps, codes, values = self._read(value) + tokens: list[int] = [] + times: list[int] = [] + previous = None + for time, code, number in zip(stamps.tolist(), codes, values.tolist()): + if previous is not None: + for interval in _interval_tokens(time - previous): + tokens.append(self.vocab[interval]) + times.append(time) + tokens.append(self.vocab[code]) + times.append(time) + breaks = self.quantiles.get(code) + if breaks is not None and not math.isnan(number): + tokens.append(self.vocab[f"Q{bisect.bisect_left(breaks, number) + 1}"]) + times.append(time) + previous = time + + if tokens and self.add_timeline_end: + tokens.append(self.vocab[TIMELINE_END_TOKEN]) + times.append(previous) + + hours = np.asarray(times, dtype=np.int64) - (times[0] if times else 0) + return ( + torch.from_numpy(hours / _MICROSECONDS_PER_HOUR), + torch.tensor(tokens, dtype=torch.long), + ) + + def decode(self, tokens: torch.Tensor | Iterable[int]) -> list[str]: + """Maps token ids back to token strings. + + Args: + tokens: Token ids, such as the output of :meth:`process`. + + Returns: + The token strings. + + Examples: + >>> from pyhealth.processors import EthosProcessor + >>> processor = EthosProcessor() + >>> processor.fit([], "timeline") + >>> processor.decode([0, 1, 2]) + ['', '', 'Q1'] + """ + by_id = {index: token for token, index in self.vocab.token_to_id.items()} + return [by_id[int(token)] for token in tokens] + + def save(self, path: str) -> None: + """Saves the configuration and fitted state as JSON. + + Args: + path: File to write. + """ + state = { + "num_quantiles": self.num_quantiles, + "quantize_prefixes": self.quantize_prefixes, + "exclude_prefixes": self.exclude_prefixes, + "add_timeline_end": self.add_timeline_end, + "vocab": None if self.vocab is None else self.vocab.to_json(), + "quantiles": self.quantiles, + } + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_bytes(orjson.dumps(state, option=orjson.OPT_SORT_KEYS)) + + def load(self, path: str) -> None: + """Restores what :meth:`save` wrote, replacing the current state. + + Args: + path: File to read. + """ + state = orjson.loads(Path(path).read_bytes()) + self.num_quantiles = state["num_quantiles"] + prefixes = state["quantize_prefixes"] + self.quantize_prefixes = None if prefixes is None else tuple(prefixes) + self.exclude_prefixes = tuple(state["exclude_prefixes"]) + self.add_timeline_end = state["add_timeline_end"] + vocab = state["vocab"] + self.vocab = None if vocab is None else ConceptVocab.from_json(vocab) + self.quantiles = state["quantiles"] + + def size(self) -> int: + """Returns the vocabulary size.""" + return 0 if self.vocab is None else self.vocab.vocab_size + + def is_token(self) -> bool: + """Output tokens are discrete indices.""" + return True + + def schema(self) -> tuple[str, ...]: + return ("time", "value") + + def dim(self) -> tuple[int, ...]: + return (1, 1) + + def spatial(self) -> tuple[bool, ...]: + return (True,) + + def __repr__(self) -> str: + return ( + f"EthosProcessor(num_quantiles={self.num_quantiles}, " + f"vocab_size={self.size()})" + ) diff --git a/tests/core/test_ethos_processor.py b/tests/core/test_ethos_processor.py new file mode 100644 index 0000000000..faff7c7dc6 --- /dev/null +++ b/tests/core/test_ethos_processor.py @@ -0,0 +1,379 @@ +"""Tests for EthosProcessor, on synthetic timelines only.""" + +import math +import os +import tempfile +import unittest +from datetime import datetime, timedelta + +import numpy as np +import pandas as pd +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.processors import EthosProcessor, get_processor +from pyhealth.processors.ethos_processor import TIME_INTERVALS + +T0 = datetime.fromisoformat("2024-01-01T08:00:00") # MEDS times are naive + + +def timeline(*rows): + """Builds a timeline from ``(minutes after T0, code, value)`` rows.""" + return { + "time": [T0 + timedelta(minutes=row[0]) for row in rows], + "code": [row[1] for row in rows], + "numeric_value": [row[2] for row in rows], + } + + +def fitted(*rows, **kwargs): + processor = EthosProcessor(**kwargs) + processor.fit([{"x": timeline(*rows)}], "x") + return processor + + +def tokens_of(processor, value): + return processor.decode(processor.process(value)[1]) + + +class TestQuantiles(unittest.TestCase): + def test_ten_quantile_fit_on_uniform_values(self): + rows = [(i, "LAB", float(i)) for i in range(1, 101)] + processor = fitted(*rows) + # Nine breaks: (n - 1) * q rounded, so 0.1 lands on sorted[10]. + self.assertEqual( + processor.quantiles["LAB"], + [11.0, 21.0, 31.0, 41.0, 51.0, 60.0, 70.0, 80.0, 90.0], + ) + + def test_value_on_a_break_takes_the_lower_bin(self): + processor = fitted(*[(i, "LAB", float(i)) for i in range(1, 101)]) + for value, expected in [(11.0, "Q1"), (11.5, "Q2"), (90.0, "Q9"), (90.5, "Q10")]: + out = tokens_of(processor, timeline((0, "LAB", value))) + self.assertEqual(out, ["LAB", expected, "TIMELINE_END"]) + + def test_unseen_values_fall_in_the_outer_bins(self): + processor = fitted(*[(i, "LAB", float(i)) for i in range(1, 101)]) + low = tokens_of(processor, timeline((0, "LAB", -1e6))) + high = tokens_of(processor, timeline((0, "LAB", 1e6))) + self.assertEqual(low[1], "Q1") + self.assertEqual(high[1], "Q10") + + def test_repeated_values_collapse_the_bins(self): + rows = [(i, "LAB", 5.0) for i in range(8)] + [(9, "LAB", 7.0), (10, "LAB", 9.0)] + processor = fitted(*rows) + self.assertEqual(processor.quantiles["LAB"], [5.0, 7.0]) + out = tokens_of(processor, timeline((0, "LAB", 8.0))) + self.assertEqual(out[1], "Q3") + + def test_breaks_are_per_code_and_tokens_shared(self): + processor = fitted( + *[(i, "A", float(i)) for i in range(10)], + *[(i, "B", 100.0 + i) for i in range(10)], + ) + self.assertNotEqual(processor.quantiles["A"], processor.quantiles["B"]) + out = tokens_of(processor, timeline((0, "A", 3.0), (0, "B", 103.0))) + self.assertEqual(out[1], out[3]) + + def test_fit_on_train_only(self): + self.assertTrue(EthosProcessor.learns_statistics) + processor = fitted(*[(i, "LAB", float(i)) for i in range(10)], num_quantiles=4) + breaks = dict(processor.quantiles) + size = processor.size() + processor.process(timeline((0, "LAB", 1e6), (1, "OTHER", 3.0))) + self.assertEqual(processor.quantiles, breaks) + self.assertEqual(processor.size(), size) + + def test_unseen_code_is_unk_without_a_quantile(self): + processor = fitted((0, "LAB", 1.0)) + out = tokens_of(processor, timeline((0, "NEW", 1.0))) + self.assertEqual(out, ["", "TIMELINE_END"]) + + def test_code_without_a_value_gets_no_quantile(self): + processor = fitted((0, "LAB", 1.0), (1, "LAB", 2.0)) + for missing in (None, math.nan, math.inf): + out = tokens_of(processor, timeline((0, "LAB", missing))) + self.assertEqual(out, ["LAB", "TIMELINE_END"]) + + def test_quantize_prefixes(self): + processor = fitted( + (0, "LAB//A", 1.0), (1, "AGE", 2.0), quantize_prefixes=["LAB//"] + ) + self.assertEqual(list(processor.quantiles), ["LAB//A"]) + out = tokens_of(processor, timeline((0, "AGE", 2.0))) + self.assertEqual(out, ["AGE", "TIMELINE_END"]) + + def test_num_quantiles_must_allow_a_break(self): + with self.assertRaises(ValueError): + EthosProcessor(num_quantiles=1) + + +class TestTimeIntervals(unittest.TestCase): + def gap_tokens(self, gap): + processor = fitted((0, "A", None)) + value = {"time": [T0, T0 + gap], "code": ["A", "A"]} + return tokens_of(processor, value)[1:-2] + + def test_nineteen_bins_as_in_the_paper(self): + self.assertEqual(len(TIME_INTERVALS), 19) + + def test_lower_bounds_are_inclusive(self): + for (label, bound), (previous, _) in zip( + TIME_INTERVALS[1:], TIME_INTERVALS + ): + self.assertEqual(self.gap_tokens(bound), [label]) + self.assertEqual( + self.gap_tokens(bound - timedelta(microseconds=1)), [previous] + ) + + def test_gap_under_five_minutes_has_no_token(self): + self.assertEqual(self.gap_tokens(timedelta(minutes=5, microseconds=-1)), []) + self.assertEqual(self.gap_tokens(timedelta(minutes=5)), ["5m-15m"]) + + def test_six_months_repeat_rounded_half_up(self): + for days, repeats in [(180, 1), (269, 1), (270, 2), (450, 3), (630, 4)]: + self.assertEqual(self.gap_tokens(timedelta(days=days)), ["=6mt"] * repeats) + + def test_short_gaps_do_not_accumulate(self): + processor = fitted((0, "A", None)) + rows = [(minute, "A", None) for minute in range(0, 40, 4)] + out = tokens_of(processor, timeline(*rows)) + self.assertEqual(out, ["A"] * 10 + ["TIMELINE_END"]) + + def test_interval_precedes_later_event_and_has_its_time(self): + processor = fitted((0, "A", None), (1, "B", 1.0)) + time, tokens = processor.process(timeline((0, "A", None), (120, "B", 1.0))) + self.assertEqual( + processor.decode(tokens), ["A", "2h-3h", "B", "Q1", "TIMELINE_END"] + ) + self.assertEqual(time.tolist(), [0.0, 2.0, 2.0, 2.0, 2.0]) + self.assertEqual(time.dtype, torch.float64) + self.assertEqual(tokens.dtype, torch.long) + + +class TestOrdering(unittest.TestCase): + def test_rows_are_sorted_and_ties_keep_input_order(self): + rows = [(60, "D", None), (0, "C", None), (0, "A", None), (0, "B", None)] + processor = fitted(*rows) + self.assertEqual( + tokens_of(processor, timeline(*rows)), + ["C", "A", "B", "45m-1h15m", "D", "TIMELINE_END"], + ) + + def test_shared_timestamp_has_no_marker(self): + rows = [(0, "A", 1.0), (0, "B", 1.0), (0, "C", 1.0)] + processor = fitted(*rows) + time, tokens = processor.process(timeline(*rows)) + self.assertEqual( + processor.decode(tokens), + ["A", "Q1", "B", "Q1", "C", "Q1", "TIMELINE_END"], + ) + self.assertEqual(set(time.tolist()), {0.0}) + + def test_death_goes_before_same_time_discharge(self): + rows = [ + (0, "HOSPITAL_DISCHARGE//HOME", None), + (0, "LAB", None), + (0, "MEDS_DEATH", None), + (0, "DRG//1", None), + ] + processor = fitted(*rows) + self.assertEqual( + tokens_of(processor, timeline(*rows)), + ["LAB", "MEDS_DEATH", "HOSPITAL_DISCHARGE//HOME", "DRG//1", "TIMELINE_END"], + ) + + def test_death_at_another_time_stays(self): + rows = [(0, "HOSPITAL_DISCHARGE", None), (1, "MEDS_DEATH", None)] + processor = fitted(*rows) + self.assertEqual( + tokens_of(processor, timeline(*rows)), + ["HOSPITAL_DISCHARGE", "MEDS_DEATH", "TIMELINE_END"], + ) + + +class TestInputs(unittest.TestCase): + def test_empty_timelines(self): + processor = fitted((0, "A", 1.0)) + for empty in ( + {"time": [], "code": [], "numeric_value": []}, + {"time": [], "code": []}, + {}, + None, + timeline((0, "MEDS_BIRTH", None)), + ): + time, tokens = processor.process(empty) + self.assertEqual((time.numel(), tokens.numel()), (0, 0)) + + def test_fit_skips_empty_and_missing_timelines(self): + processor = EthosProcessor() + processor.fit( + [{"x": {"time": [], "code": []}}, {"x": None}, {"x": timeline((0, "A", 1.0))}], + "x", + ) + self.assertIn("A", processor.vocab.token_to_id) + + def test_static_rows_are_dropped(self): + value = timeline((0, "GENDER//F", None), (0, "A", None)) + value["time"].append(None) + value["code"].append("HEIGHT") + value["numeric_value"].append(170.0) + processor = EthosProcessor() + processor.fit([{"x": value}], "x") + self.assertEqual(tokens_of(processor, value), ["A", "TIMELINE_END"]) + self.assertNotIn("GENDER//F", processor.vocab.token_to_id) + self.assertNotIn("HEIGHT", processor.quantiles) + + def test_numeric_value_column_is_optional(self): + processor = fitted((0, "A", None)) + value = {"time": [T0], "code": ["A"]} + self.assertEqual(tokens_of(processor, value), ["A", "TIMELINE_END"]) + + def test_timeline_end_can_be_left_out(self): + processor = fitted((0, "A", None), add_timeline_end=False) + self.assertEqual(tokens_of(processor, timeline((0, "A", None))), ["A"]) + + def test_time_column_types(self): + processor = fitted((0, "A", None)) + stamps = pd.to_datetime([T0, T0 + timedelta(minutes=5)]) + for times in (list(stamps), stamps.to_numpy(), [str(t) for t in stamps]): + value = {"time": times, "code": ["A", "A"]} + self.assertEqual( + tokens_of(processor, value), ["A", "5m-15m", "A", "TIMELINE_END"] + ) + + def test_dates_past_the_pandas_nanosecond_range(self): + processor = fitted((0, "A", None)) + value = { + "time": [ + datetime.fromisoformat("2500-01-01T08:00:00"), + datetime.fromisoformat("2500-01-01T09:00:00"), + pd.NaT, + ], + "code": ["A", "A", "A"], + } + self.assertEqual( + tokens_of(processor, value), ["A", "45m-1h15m", "A", "TIMELINE_END"] + ) + + def test_numeric_times_are_rejected(self): + processor = fitted((0, "A", None)) + for times in ([0, 5], [0.0, 5.0], np.array([0, 5])): + with self.assertRaises(TypeError): + processor.process({"time": times, "code": ["A", "A"]}) + + def test_mismatched_columns_are_rejected(self): + processor = fitted((0, "A", None)) + with self.assertRaises(ValueError): + processor.process({"time": [T0], "code": ["A", "A"]}) + + def test_process_before_fit_is_rejected(self): + with self.assertRaises(RuntimeError): + EthosProcessor().process(timeline((0, "A", None))) + + def test_input_is_not_modified(self): + value = timeline((60, "A", math.inf), (0, "B", None)) + processor = fitted((0, "A", 1.0)) + processor.process(value) + self.assertEqual(value, timeline((60, "A", math.inf), (0, "B", None))) + + +class TestVocabulary(unittest.TestCase): + def test_every_quantile_and_interval_token_is_reserved(self): + processor = EthosProcessor(num_quantiles=4) + processor.fit([], "x") + vocab = processor.vocab.token_to_id + self.assertEqual((vocab[""], vocab[""]), (0, 1)) + for token in ["Q1", "Q4", "TIMELINE_END", *[t for t, _ in TIME_INTERVALS]]: + self.assertIn(token, vocab) + self.assertEqual(processor.size(), 2 + 4 + 19 + 1) + + def test_ids_do_not_depend_on_sample_order(self): + first = fitted((0, "B", None), (1, "A", None)) + second = fitted((0, "A", None), (1, "B", None)) + self.assertEqual(first.vocab.token_to_id, second.vocab.token_to_id) + + def test_refit_replaces_state(self): + processor = fitted((0, "OLD", 1.0)) + processor.fit([{"x": timeline((0, "NEW", 1.0))}], "x") + self.assertNotIn("OLD", processor.vocab.token_to_id) + self.assertNotIn("OLD", processor.quantiles) + + +class TestSaveLoad(unittest.TestCase): + def test_round_trip(self): + rows = [(i * 10, "LAB", i / 3) for i in range(30)] + processor = fitted( + *rows, + num_quantiles=5, + quantize_prefixes=["LAB"], + exclude_prefixes=["X"], + add_timeline_end=False, + ) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "nested", "ethos.json") + processor.save(path) + loaded = EthosProcessor() + loaded.load(path) + + self.assertEqual(loaded.quantiles, processor.quantiles) + self.assertEqual(loaded.vocab.token_to_id, processor.vocab.token_to_id) + self.assertEqual(loaded.num_quantiles, 5) + self.assertEqual(loaded.quantize_prefixes, ("LAB",)) + self.assertEqual(loaded.exclude_prefixes, ("X",)) + self.assertFalse(loaded.add_timeline_end) + for out, expected in zip( + loaded.process(timeline(*rows)), processor.process(timeline(*rows)) + ): + self.assertTrue(torch.equal(out, expected)) + + def test_unfitted_round_trip(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "ethos.json") + EthosProcessor().save(path) + loaded = EthosProcessor() + loaded.load(path) + self.assertIsNone(loaded.vocab) + self.assertIsNone(loaded.quantize_prefixes) + + +class TestPipeline(unittest.TestCase): + def test_registered_and_contract(self): + self.assertIs(get_processor("ethos"), EthosProcessor) + processor = EthosProcessor() + self.assertTrue(processor.is_token()) + self.assertEqual(processor.schema(), ("time", "value")) + self.assertEqual(processor.dim(), (1, 1)) + self.assertEqual(processor.spatial(), (True,)) + self.assertIn("num_quantiles=10", repr(processor)) + + def test_sample_dataset_and_batching(self): + samples = [ + { + "patient_id": "p0", + "timeline": timeline((0, "A", 1.0), (120, "B", None)), + "label": 0, + }, + {"patient_id": "p1", "timeline": timeline((0, "A", 2.0)), "label": 1}, + { + "patient_id": "p2", + "timeline": {"time": [], "code": [], "numeric_value": []}, + "label": 1, + }, + ] + dataset = create_sample_dataset( + samples, + input_schema={"timeline": "ethos"}, + output_schema={"label": "binary"}, + dataset_name="ethos_test", + in_memory=True, + ) + batch = next(iter(get_dataloader(dataset, batch_size=3))) + time, tokens = batch["timeline"] + self.assertEqual(tokens.shape, (3, 5)) + self.assertEqual(time.shape, (3, 5)) + self.assertEqual(int((tokens == 0).sum()), 7) + + +if __name__ == "__main__": + unittest.main() From f50e69838187e26bed3b641edb5324ad9541a9d3 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Thu, 5 Nov 2026 12:57:01 -0600 Subject: [PATCH 02/10] Add MEDS ICU admission, readmission and prolonged stay tasks Add ICUAdmissionMEDS, HospitalReadmissionMEDS and ProlongedLengthOfStayMEDS, BaseTask classes on MEDSDataset that follow the ETHOS-ARES cohorts and labels (arXiv:2502.06124). They only need a code sequence, so any PyHealth sequence model can use them. Co-Authored-By: Claude Opus 5.5 --- docs/api/tasks.rst | 3 + ...pyhealth.tasks.HospitalReadmissionMEDS.rst | 7 + .../tasks/pyhealth.tasks.ICUAdmissionMEDS.rst | 7 + ...health.tasks.ProlongedLengthOfStayMEDS.rst | 7 + examples/meds_outcome_tasks.py | 161 ++++++ pyhealth/tasks/__init__.py | 5 + pyhealth/tasks/meds_outcome_tasks.py | 489 ++++++++++++++++++ tests/core/test_meds_outcome_tasks.py | 400 ++++++++++++++ 8 files changed, 1079 insertions(+) create mode 100644 docs/api/tasks/pyhealth.tasks.HospitalReadmissionMEDS.rst create mode 100644 docs/api/tasks/pyhealth.tasks.ICUAdmissionMEDS.rst create mode 100644 docs/api/tasks/pyhealth.tasks.ProlongedLengthOfStayMEDS.rst create mode 100644 examples/meds_outcome_tasks.py create mode 100644 pyhealth/tasks/meds_outcome_tasks.py create mode 100644 tests/core/test_meds_outcome_tasks.py diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index ddee0af7f2..659398a422 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -211,6 +211,9 @@ Available Tasks Base Task In-Hospital Mortality (MIMIC-IV) In-Hospital Mortality (MEDS) + ICU Admission (MEDS) + Hospital Readmission (MEDS) + Prolonged Length of Stay (MEDS) MIMIC-III ICD-9 Coding Cardiology Detection COVID-19 CXR Classification diff --git a/docs/api/tasks/pyhealth.tasks.HospitalReadmissionMEDS.rst b/docs/api/tasks/pyhealth.tasks.HospitalReadmissionMEDS.rst new file mode 100644 index 0000000000..75cc512357 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.HospitalReadmissionMEDS.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.HospitalReadmissionMEDS +====================================== + +.. autoclass:: pyhealth.tasks.meds_outcome_tasks.HospitalReadmissionMEDS + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.ICUAdmissionMEDS.rst b/docs/api/tasks/pyhealth.tasks.ICUAdmissionMEDS.rst new file mode 100644 index 0000000000..47aa8266c6 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.ICUAdmissionMEDS.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.ICUAdmissionMEDS +=============================== + +.. autoclass:: pyhealth.tasks.meds_outcome_tasks.ICUAdmissionMEDS + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.ProlongedLengthOfStayMEDS.rst b/docs/api/tasks/pyhealth.tasks.ProlongedLengthOfStayMEDS.rst new file mode 100644 index 0000000000..4edee1e9a8 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.ProlongedLengthOfStayMEDS.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.ProlongedLengthOfStayMEDS +======================================== + +.. autoclass:: pyhealth.tasks.meds_outcome_tasks.ProlongedLengthOfStayMEDS + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/meds_outcome_tasks.py b/examples/meds_outcome_tasks.py new file mode 100644 index 0000000000..848451bf56 --- /dev/null +++ b/examples/meds_outcome_tasks.py @@ -0,0 +1,161 @@ +"""ICU admission, readmission and prolonged stay tasks on MEDS data. + +Runs ``ICUAdmissionMEDS``, ``HospitalReadmissionMEDS`` and +``ProlongedLengthOfStayMEDS`` through ``set_task``, prints each cohort, and +runs one training step of a small RNN on each task. These tasks only need a +code sequence, so any PyHealth sequence model works the same way. + +With no arguments the script writes a small **synthetic** MEDS dataset to a +temporary folder. No data access is needed, and its numbers are a smoke test +with no clinical meaning: + + python examples/meds_outcome_tasks.py + +To use a real MEDS dataset, such as the open-access MIMIC-IV demo in MEDS +(https://physionet.org/content/mimic-iv-demo-meds/0.0.1/): + + python examples/meds_outcome_tasks.py \\ + --root physionet.org/files/mimic-iv-demo-meds/0.0.1 + +For reference, Renc et al. (arXiv:2502.06124) report these AUROCs for ETHOS on +all of MIMIC-IV 2.2: ICU admission 0.932 and prolonged stay 0.853. This script +does not reproduce them. +""" + +import argparse +import random +import tempfile +from datetime import datetime, timedelta +from pathlib import Path + +import polars as pl + +import pyhealth.datasets.configs as meds_configs +from pyhealth.datasets import MEDSDataset, get_dataloader +from pyhealth.models import RNN +from pyhealth.tasks import ( + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, +) + +LAB_CODES = ["LAB//51221//%", "LAB//50912//mg/dL", "LAB//50971//mEq/L"] +DIAGNOSIS_CODES = ["DIAGNOSIS//ICD//10//I10", "DIAGNOSIS//ICD//10//E119"] + + +def write_synthetic_meds(root: Path, n_subjects: int = 30, seed: int = 0) -> None: + """Writes a small synthetic MEDS dataset with one to three stays per subject. + + Args: + root (Path): Output directory. ``data/0.parquet`` is created inside. + n_subjects (int): Number of synthetic subjects. + seed (int): Random seed. + """ + rng = random.Random(seed) + rows = [] + for subject_id in range(1, n_subjects + 1): + start = datetime(2024, 1, 1, 8) # noqa: DTZ001 (MEDS times are tz-naive) + now = start + timedelta(days=rng.randint(0, 60)) + rows.append((subject_id, None, "GENDER//" + rng.choice("FM"), None)) + for stay in range(rng.randint(1, 3)): + hadm_id = subject_id * 100 + stay + length = timedelta(days=rng.uniform(1, 18)) + died = rng.random() < 0.1 + rows.append((subject_id, now, "HOSPITAL_ADMISSION//EW EMER.//ER", hadm_id)) + for _ in range(rng.randint(1, 6)): + when = now + length * rng.random() + rows.append((subject_id, when, rng.choice(LAB_CODES), hadm_id)) + if rng.random() < 0.3: + when = now + length * 0.2 + rows.append((subject_id, when, "ICU_ADMISSION//MICU", hadm_id)) + when = now + length * 0.6 + rows.append((subject_id, when, "ICU_DISCHARGE//MICU", hadm_id)) + + discharge = now + length + location = "DIED" if died else "HOME" + rows.append( + (subject_id, discharge, f"HOSPITAL_DISCHARGE//{location}", hadm_id) + ) + rows.append((subject_id, discharge, rng.choice(DIAGNOSIS_CODES), hadm_id)) + if died: + rows.append( + (subject_id, discharge + timedelta(hours=2), "MEDS_DEATH", None) + ) + break + now = discharge + timedelta(days=rng.choice([5, 15, 25, 60, 120])) + + (root / "data").mkdir(parents=True) + pl.DataFrame( + { + "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), + "time": pl.Series([r[1] for r in rows], dtype=pl.Datetime("us")), + "code": pl.Series([r[2] for r in rows], dtype=pl.String), + "numeric_value": pl.Series([None] * len(rows), dtype=pl.Float32), + "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), + } + ).write_parquet(root / "data" / "0.parquet") + + +def run_task(dataset, task, label_key: str) -> None: + """Prints a task's cohort and runs one training step of a small RNN. + + Args: + dataset (MEDSDataset): The dataset. + task (BaseTask): The task to apply. + label_key (str): The task's output key. + """ + samples = dataset.set_task(task, num_workers=1) + labels = [int(samples[i][label_key]) for i in range(len(samples))] + subjects = {samples[i]["patient_id"] for i in range(len(samples))} + rate = sum(labels) / len(labels) if labels else 0.0 + print( + f"{task.task_name}: samples={len(labels)} subjects={len(subjects)} " + f"positive={sum(labels)} rate={rate:.3f}" + ) + if len(set(labels)) < 2: + print(" skipping the RNN step: only one label value in this cohort") + return + + model = RNN(dataset=samples, embedding_dim=16, hidden_dim=16) + batch = next(iter(get_dataloader(samples, batch_size=16, shuffle=True))) + output = model(**batch) + output["loss"].backward() + print(f" one RNN step: loss={output['loss'].item():.4f}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", + default=None, + help="MEDS dataset root. Omit to use generated synthetic data.", + ) + args = parser.parse_args() + + config = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + if args.root is None: + print("Using synthetic MEDS data: a smoke test, not a result.") + root = temp_path / "synthetic_meds" + write_synthetic_meds(root) + else: + root = Path(args.root) + + dataset = MEDSDataset( + root=str(root), + config_path=str(config), + cache_dir=temp_path / "cache", + num_workers=1, + ) + tasks = [ + (ICUAdmissionMEDS(), "icu_admission"), + (HospitalReadmissionMEDS(), "readmission"), + (ProlongedLengthOfStayMEDS(), "prolonged_los"), + ] + for task, label_key in tasks: + run_task(dataset, task, label_key) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 423a64aefc..2413545f8e 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -52,6 +52,11 @@ ) from .length_of_stay_stagenet_mimic4 import LengthOfStayStageNetMIMIC4 from .medical_coding import MIMIC3ICD9Coding +from .meds_outcome_tasks import ( + HospitalReadmissionMEDS as HospitalReadmissionMEDS, + ICUAdmissionMEDS as ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS as ProlongedLengthOfStayMEDS, +) from .medical_transcriptions_classification import MedicalTranscriptionsClassification from .mortality_prediction import ( MortalityPredictionEICU, diff --git a/pyhealth/tasks/meds_outcome_tasks.py b/pyhealth/tasks/meds_outcome_tasks.py new file mode 100644 index 0000000000..3e763198b9 --- /dev/null +++ b/pyhealth/tasks/meds_outcome_tasks.py @@ -0,0 +1,489 @@ +"""Hospital outcome prediction tasks for the Medical Event Data Standard (MEDS). + +This module provides three MEDS-native outcome tasks that work with any +PyHealth model taking a code sequence: + +* :class:`ICUAdmissionMEDS`: ICU admission during a hospital stay. +* :class:`HospitalReadmissionMEDS`: readmission or death within 30 days of + discharge. +* :class:`ProlongedLengthOfStayMEDS`: a stay of at least 10 days. + +The cohorts and labels follow the ETHOS-ARES reference code. In-hospital +mortality already exists as +:class:`~pyhealth.tasks.in_hospital_mortality_meds.InHospitalMortalityMEDS`, +which observes the stay itself rather than predicting at admission. + +Task definitions +---------------- +As in ``InHospitalMortalityMEDS``, a *stay* is the set of events sharing one +``hadm_id``, with admission time ``t_a`` (earliest ``HOSPITAL_ADMISSION//*``) +and discharge time ``t_d`` (latest ``HOSPITAL_DISCHARGE//*``). Stays without +both events, or with ``t_d <= t_a``, produce no sample. A stay *ended in death* +if its discharge code is ``HOSPITAL_DISCHARGE//DIED`` or a ``MEDS_DEATH`` event +falls in ``[t_a, t_d]``. + +ICU admission and prolonged stay predict **at hospital admission**: + +* **Features.** Static events (null timestamp), every event strictly before + ``t_a`` (including earlier stays), then this stay's admission event. Other + events stamped exactly ``t_a`` are dropped because their order relative to + the admission is unknown: a direct ICU admission shares that timestamp. +* **ICU label.** 1 if an ``ICU_ADMISSION//*`` event carries this ``hadm_id`` or + falls in ``[t_a, t_d]``. By default a death in the stay is also positive + (``death_as_positive``), on the reasoning that the patient should have been + admitted to the ICU. +* **Prolonged stay label.** 1 if the time from ``t_a`` to the end of the stay + is at least ``threshold_days``. The stay ends at ``t_d`` or at an earlier + ``MEDS_DEATH``. Stays that ended in death are kept. + +Readmission predicts **at discharge**: + +* **Cohort.** Stays that did not end in death. +* **Features.** Static events, every event strictly before ``t_d``, and the + events stamped ``t_d`` that carry this ``hadm_id`` (the discharge, + diagnoses and DRG codes). Events stamped ``t_d`` from any other stay are + dropped, so a same-instant readmission cannot reach the input. +* **Label.** 1 if the next ``HOSPITAL_ADMISSION//*`` of another stay or the next + ``MEDS_DEATH`` falls within ``window_days`` of ``t_d`` (inclusive). + ``require_full_followup=True`` also drops negatives whose timeline ends + less than ``window_days`` after discharge (the "reduced" cohort). + +``MEDS_DEATH`` never enters the input of any task, and neither do events after +the prediction time. ``ICU_ADMISSION//*`` and ``ICU_DISCHARGE//*`` events of the +current stay are also dropped from admission-time input: MIMIC-IV can stamp an +ICU entry before the hospital admission it belongs to, which would otherwise +place the label in the history. ICU events of earlier stays remain. + +Admission-time input also drops events of the current stay stamped at exactly +midnight before ``t_a``. These are date-resolution records such as HCPCS billing +codes, which sort before the admission on the same day but describe care given +during the stay. Timed events of the current stay before ``t_a``, such as +emergency department labs and transfers, are kept. + +Configuration +------------- +These tasks read ``hadm_id``, which is not part of the core MEDS schema, so +pass the bundled ``configs/meds_with_hadm.yaml`` (or your own config listing +it). ``ICUAdmissionMEDS`` also needs ``ICU_ADMISSION//*`` codes, as produced by +the MIMIC-IV MEDS event configs. On a dataset without them every label is +driven by deaths alone. + +The ``ICU_ADMISSION``, ``HOSPITAL_ADMISSION`` and ``HOSPITAL_DISCHARGE`` tokens, +the prediction times and the labels are adapted from ETHOS-ARES +(``src/ethos/datasets/{mimic_icu,readmission,hospital_mortality}.py`` and +``notebooks/{icu_admission,hosp_readmission,all_task_label_dump}.ipynb``, +commit 2d54383). Copyright (c) 2024 Pawel Renc, MIT License. + +References: + Renc P., Grzeszczyk M. K., Oufattole N., et al. Foundation Model of + Electronic Medical Records for Adaptive Risk Estimation. arXiv:2502.06124. + https://arxiv.org/abs/2502.06124 + + Source code: https://github.com/ipolharvard/ethos-ares +""" + +from datetime import datetime, timedelta +from typing import Any, ClassVar + +import polars as pl + +from .base_task import BaseTask +from .in_hospital_mortality_meds import ( + ADMISSION_PREFIX, + DEATH_CODE, + DIED_CODE, + DISCHARGE_PREFIX, +) + +ICU_ADMISSION_PREFIX = "ICU_ADMISSION" +ICU_DISCHARGE_PREFIX = "ICU_DISCHARGE" + + +def _load_events(patient: Any) -> pl.DataFrame | None: + """Returns a patient's MEDS events with an integer ``_hadm`` column. + + Args: + patient (Any): A PyHealth ``Patient``. + + Returns: + pl.DataFrame | None: The events, or ``None`` if there are none. + """ + events = patient.get_events(event_type="meds", return_df=True) + if events.height == 0: + return None + # Nulls promote hadm_id to float through the Dask/pandas pipeline; cast it + # back so stays join cleanly and emitted ids stay integral. + return events.with_columns( + pl.col("meds/hadm_id").cast(pl.Int64, strict=False).alias("_hadm") + ) + + +def _completed_stays(events: pl.DataFrame) -> list[dict[str, Any]]: + """Builds one record per completed stay, in admission order. + + Args: + events (pl.DataFrame): Output of :func:`_load_events`. + + Returns: + list[dict[str, Any]]: Records with ``hadm_id``, ``admit``, + ``discharge``, ``died`` (the stay ended in death) and ``end`` (the + earliest in-stay ``MEDS_DEATH``, otherwise ``discharge``). + """ + code = pl.col("meds/code") + has_hadm = pl.col("_hadm").is_not_null() + admissions = ( + events.filter(code.str.starts_with(ADMISSION_PREFIX) & has_hadm) + .group_by("_hadm") + .agg(pl.col("timestamp").min().alias("admit")) + ) + discharges = ( + events.filter(code.str.starts_with(DISCHARGE_PREFIX) & has_hadm) + .group_by("_hadm") + .agg( + pl.col("timestamp").max().alias("discharge"), + code.sort_by("timestamp").last().alias("discharge_code"), + ) + ) + stays = ( + admissions.join(discharges, on="_hadm", how="inner") + .filter(pl.col("discharge") > pl.col("admit")) + .sort("admit") + ) + deaths = events.filter(code == DEATH_CODE)["timestamp"].drop_nulls().to_list() + + records = [] + for stay in stays.iter_rows(named=True): + admit, discharge = stay["admit"], stay["discharge"] + in_stay_deaths = [t for t in deaths if admit <= t <= discharge] + records.append( + { + "hadm_id": stay["_hadm"], + "admit": admit, + "discharge": discharge, + "died": stay["discharge_code"] == DIED_CODE or bool(in_stay_deaths), + "end": min(in_stay_deaths, default=discharge), + } + ) + return records + + +def _is_this_stay(hadm_id: int) -> pl.Expr: + """Selects events carrying ``hadm_id``; null ids count as other stays.""" + return (pl.col("_hadm") == hadm_id).fill_null(False) + + +def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the input of an admission-time prediction. + + Args: + events (pl.DataFrame): Output of :func:`_load_events`. + stay (dict[str, Any]): A record from :func:`_completed_stays`. + + Returns: + list[str]: Static codes, history before admission, then the admission + event itself. See the module docstring for the exclusions. + """ + code = pl.col("meds/code") + time = pl.col("timestamp") + this_stay = _is_this_stay(stay["hadm_id"]) + this_stay_icu = this_stay & ( + code.str.starts_with(ICU_ADMISSION_PREFIX) + | code.str.starts_with(ICU_DISCHARGE_PREFIX) + ) + this_stay_dated = this_stay & (time.dt.time() == pl.time(0)) + admission_event = ( + (time == stay["admit"]) & this_stay & code.str.starts_with(ADMISSION_PREFIX) + ) + history = (time < stay["admit"]) & ~this_stay_icu & ~this_stay_dated + window = time.is_null() | history + return events.filter((window | admission_event) & (code != DEATH_CODE))[ + "meds/code" + ].to_list() + + +def _codes_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the input of a discharge-time prediction. + + Args: + events (pl.DataFrame): Output of :func:`_load_events`. + stay (dict[str, Any]): A record from :func:`_completed_stays`. + + Returns: + list[str]: Static codes, everything before discharge, then the events + of this stay stamped at discharge. + """ + time = pl.col("timestamp") + at_discharge = (time == stay["discharge"]) & _is_this_stay(stay["hadm_id"]) + window = time.is_null() | (time < stay["discharge"]) | at_discharge + return events.filter(window & (pl.col("meds/code") != DEATH_CODE))[ + "meds/code" + ].to_list() + + +def _next_outcome_time( + events: pl.DataFrame, stay: dict[str, Any] +) -> datetime | None: + """Returns the time of the next admission or death after a discharge. + + Args: + events (pl.DataFrame): Output of :func:`_load_events`. + stay (dict[str, Any]): A record from :func:`_completed_stays`. + + Returns: + datetime | None: The earliest outcome time, or ``None`` if neither + event follows the discharge. + """ + code = pl.col("meds/code") + time = pl.col("timestamp") + readmission = ( + code.str.starts_with(ADMISSION_PREFIX) + & (time >= stay["discharge"]) + & ~_is_this_stay(stay["hadm_id"]) + ) + death = (code == DEATH_CODE) & (time > stay["discharge"]) + return events.filter(readmission | death)["timestamp"].min() + + +class ICUAdmissionMEDS(BaseTask): + """ICU admission prediction at hospital admission for MEDS datasets. + + One sample per completed stay. The input is the patient's history up to + and including the admission event, and the binary label is whether the + patient reached the ICU during the stay. By default a death during the + stay also counts as positive, following the ETHOS-ARES reference code. See + the module docstring for the full definition. + + Args: + death_as_positive (bool): Treat a death during the stay as positive + even without an ICU admission. Defaults to ``True``, matching + ``notebooks/icu_admission.ipynb``. ``False`` gives the ICU-only + label of ``notebooks/all_task_label_dump.ipynb``. + code_mapping (Optional[Dict[str, Tuple[str, str]]]): Optional vocab + mapping forwarded to :class:`BaseTask`. + + Attributes: + task_name (str): The name of the task. + input_schema (Dict[str, str]): ``codes``, the observed MEDS codes. + output_schema (Dict[str, str]): ``icu_admission``, a binary label. + + Examples: + >>> from pathlib import Path + >>> import pyhealth.datasets.configs as meds_configs + >>> from pyhealth.datasets import MEDSDataset + >>> from pyhealth.tasks import ICUAdmissionMEDS + >>> cfg = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" + >>> dataset = MEDSDataset( + ... root="/path/to/mimic-iv-demo-meds/0.0.1", + ... config_path=str(cfg), + ... ) + >>> samples = dataset.set_task(ICUAdmissionMEDS()) + >>> icu_only = ICUAdmissionMEDS(death_as_positive=False) + """ + + task_name: str = "ICUAdmissionMEDS" + input_schema: ClassVar[dict[str, str]] = {"codes": "sequence"} + output_schema: ClassVar[dict[str, str]] = {"icu_admission": "binary"} + + def __init__( + self, + death_as_positive: bool = True, + code_mapping: dict[str, tuple[str, str]] | None = None, + ) -> None: + super().__init__(code_mapping=code_mapping) + self.death_as_positive = death_as_positive + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + events = _load_events(patient) + if events is None: + return [] + + icu_events = events.filter( + pl.col("meds/code").str.starts_with(ICU_ADMISSION_PREFIX) + ) + samples: list[dict[str, Any]] = [] + for stay in _completed_stays(events): + reached_icu = ( + icu_events.filter( + _is_this_stay(stay["hadm_id"]) + | pl.col("timestamp").is_between(stay["admit"], stay["discharge"]) + ).height + > 0 + ) + samples.append( + { + "patient_id": patient.patient_id, + "hadm_id": stay["hadm_id"], + "codes": _codes_at_admission(events, stay), + "icu_admission": int( + reached_icu or (self.death_as_positive and stay["died"]) + ), + } + ) + return samples + + +class HospitalReadmissionMEDS(BaseTask): + """Readmission prediction at hospital discharge for MEDS datasets. + + One sample per completed stay that did not end in death. The input is the + patient's history up to and including this stay's discharge events, and + the binary label is whether the patient was readmitted or died within + ``window_days``. See the module docstring for the full definition. + + Args: + window_days (float): Outcome window after discharge, inclusive. + Defaults to ``30.0``, matching ETHOS-ARES. + require_full_followup (bool): Drop negatives whose timeline ends less + than ``window_days`` after discharge, since their outcome is + unobserved. Defaults to ``False`` (the "Full" cohort of + ``notebooks/hosp_readmission.ipynb``); ``True`` gives the + "Reduced" cohort. + code_mapping (Optional[Dict[str, Tuple[str, str]]]): Optional vocab + mapping forwarded to :class:`BaseTask`. + + Attributes: + task_name (str): The name of the task. + input_schema (Dict[str, str]): ``codes``, the observed MEDS codes. + output_schema (Dict[str, str]): ``readmission``, a binary label. + + Raises: + ValueError: If ``window_days`` is not positive. + + Examples: + >>> from pathlib import Path + >>> import pyhealth.datasets.configs as meds_configs + >>> from pyhealth.datasets import MEDSDataset + >>> from pyhealth.tasks import HospitalReadmissionMEDS + >>> cfg = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" + >>> dataset = MEDSDataset( + ... root="/path/to/mimic-iv-demo-meds/0.0.1", + ... config_path=str(cfg), + ... ) + >>> samples = dataset.set_task(HospitalReadmissionMEDS()) + >>> reduced = HospitalReadmissionMEDS(require_full_followup=True) + """ + + task_name: str = "HospitalReadmissionMEDS" + input_schema: ClassVar[dict[str, str]] = {"codes": "sequence"} + output_schema: ClassVar[dict[str, str]] = {"readmission": "binary"} + + def __init__( + self, + window_days: float = 30.0, + require_full_followup: bool = False, + code_mapping: dict[str, tuple[str, str]] | None = None, + ) -> None: + if window_days <= 0: + raise ValueError(f"window_days must be positive, got {window_days}.") + super().__init__(code_mapping=code_mapping) + self.window_days = float(window_days) + self.require_full_followup = require_full_followup + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + events = _load_events(patient) + if events is None: + return [] + + window = timedelta(days=self.window_days) + timeline_end = events["timestamp"].max() + samples: list[dict[str, Any]] = [] + for stay in _completed_stays(events): + if stay["died"]: + continue + + discharge = stay["discharge"] + outcome_time = _next_outcome_time(events, stay) + label = outcome_time is not None and outcome_time - discharge <= window + censored = timeline_end - discharge < window + if self.require_full_followup and not label and censored: + continue + + samples.append( + { + "patient_id": patient.patient_id, + "hadm_id": stay["hadm_id"], + "codes": _codes_at_discharge(events, stay), + "readmission": int(label), + } + ) + return samples + + +class ProlongedLengthOfStayMEDS(BaseTask): + """Prolonged length of stay prediction at admission for MEDS datasets. + + One sample per completed stay, including stays that ended in death. The + input is the patient's history up to and including the admission event, + and the binary label is whether the stay lasted at least + ``threshold_days``. See the module docstring for the full definition. + + Args: + threshold_days (float): Minimum length of a prolonged stay, inclusive. + Defaults to ``10.0``, matching + ``notebooks/all_task_label_dump.ipynb``. + code_mapping (Optional[Dict[str, Tuple[str, str]]]): Optional vocab + mapping forwarded to :class:`BaseTask`. + + Attributes: + task_name (str): The name of the task. + input_schema (Dict[str, str]): ``codes``, the observed MEDS codes. + output_schema (Dict[str, str]): ``prolonged_los``, a binary label. + + Raises: + ValueError: If ``threshold_days`` is not positive. + + Examples: + >>> from pathlib import Path + >>> import pyhealth.datasets.configs as meds_configs + >>> from pyhealth.datasets import MEDSDataset + >>> from pyhealth.tasks import ProlongedLengthOfStayMEDS + >>> cfg = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" + >>> dataset = MEDSDataset( + ... root="/path/to/mimic-iv-demo-meds/0.0.1", + ... config_path=str(cfg), + ... ) + >>> samples = dataset.set_task(ProlongedLengthOfStayMEDS()) + >>> week = ProlongedLengthOfStayMEDS(threshold_days=7.0) + """ + + task_name: str = "ProlongedLengthOfStayMEDS" + input_schema: ClassVar[dict[str, str]] = {"codes": "sequence"} + output_schema: ClassVar[dict[str, str]] = {"prolonged_los": "binary"} + + def __init__( + self, + threshold_days: float = 10.0, + code_mapping: dict[str, tuple[str, str]] | None = None, + ) -> None: + if threshold_days <= 0: + raise ValueError(f"threshold_days must be positive, got {threshold_days}.") + super().__init__(code_mapping=code_mapping) + self.threshold_days = float(threshold_days) + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + events = _load_events(patient) + if events is None: + return [] + + threshold = timedelta(days=self.threshold_days) + return [ + { + "patient_id": patient.patient_id, + "hadm_id": stay["hadm_id"], + "codes": _codes_at_admission(events, stay), + "prolonged_los": int(stay["end"] - stay["admit"] >= threshold), + } + for stay in _completed_stays(events) + ] diff --git a/tests/core/test_meds_outcome_tasks.py b/tests/core/test_meds_outcome_tasks.py new file mode 100644 index 0000000000..8f6e227aec --- /dev/null +++ b/tests/core/test_meds_outcome_tasks.py @@ -0,0 +1,400 @@ +"""Tests for ICUAdmissionMEDS, HospitalReadmissionMEDS and +ProlongedLengthOfStayMEDS. + +Most tests apply a task directly to an in-memory ``Patient``, which keeps them +fast and exposes the raw string codes the leakage tests must inspect. One test +runs all three tasks through ``MEDSDataset.set_task`` on synthetic Parquet. +All data here is synthetic. +""" + +import shutil +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path + +import polars as pl + +from pyhealth.data import Patient +from pyhealth.datasets import MEDSDataset +from pyhealth.tasks import ( + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, +) + +T0 = datetime(2024, 1, 1, 8, 0, 0) # noqa: DTZ001 (MEDS times are tz-naive) + +ADMIT = "HOSPITAL_ADMISSION//EW EMER.//ER" +HOME = "HOSPITAL_DISCHARGE//HOME" +DIED = "HOSPITAL_DISCHARGE//DIED" +ICU_IN = "ICU_ADMISSION//MICU" +ICU_OUT = "ICU_DISCHARGE//MICU" +DEATH = "MEDS_DEATH" +LAB = "LAB//51221//%" +DX = "DIAGNOSIS//ICD//10//I10" + +_CONFIG = """version: "1.0" +tables: + meds: + file_path: "data" + patient_id: "subject_id" + timestamp: "time" + attributes: + - "code" + - "numeric_value" + - "hadm_id" +""" + + +def _hours(days: float) -> float: + return days * 24.0 + + +def _at(offset_hours: float | None) -> datetime | None: + if offset_hours is None: + return None + return T0 + timedelta(hours=offset_hours) + + +def _patient(rows, hadm_dtype=pl.Int64) -> Patient: + """Rows are ``(offset_hours_or_None, code, hadm_id_or_None)``.""" + frame = pl.DataFrame( + { + "patient_id": ["1"] * len(rows), + "event_type": ["meds"] * len(rows), + "timestamp": pl.Series( + [_at(r[0]) for r in rows], dtype=pl.Datetime("ms") + ), + "meds/code": pl.Series([r[1] for r in rows], dtype=pl.String), + "meds/hadm_id": pl.Series([r[2] for r in rows], dtype=hadm_dtype), + } + ) + return Patient(patient_id="1", data_source=frame) + + +def _stay(hadm, start, days, discharge_code=HOME, between=()): + """Admission, optional events and discharge, ``start`` hours after T0.""" + rows = [(start, ADMIT, hadm)] + rows.extend(between) + rows.append((start + _hours(days), discharge_code, hadm)) + return rows + + +class TestICUAdmissionMEDS(unittest.TestCase): + def test_icu_stay_is_positive(self): + rows = _stay(1, 0, 3, between=[(5, ICU_IN, 1), (20, ICU_OUT, 1)]) + samples = ICUAdmissionMEDS()(_patient(rows)) + self.assertEqual(len(samples), 1) + self.assertEqual(samples[0]["icu_admission"], 1) + self.assertEqual(samples[0]["hadm_id"], 1) + + def test_ward_stay_is_negative(self): + rows = _stay(1, 0, 3, between=[(5, LAB, 1)]) + self.assertEqual(ICUAdmissionMEDS()(_patient(rows))[0]["icu_admission"], 0) + + def test_icu_event_without_hadm_inside_stay_is_positive(self): + rows = _stay(1, 0, 3, between=[(5, ICU_IN, None)]) + self.assertEqual(ICUAdmissionMEDS()(_patient(rows))[0]["icu_admission"], 1) + + def test_icu_after_discharge_belongs_to_next_stay(self): + rows = _stay(1, 0, 3) + _stay(2, 200, 3, between=[(205, ICU_IN, 2)]) + samples = ICUAdmissionMEDS()(_patient(rows)) + labels = {s["hadm_id"]: s["icu_admission"] for s in samples} + self.assertEqual(labels, {1: 0, 2: 1}) + + def test_death_outside_icu_follows_death_as_positive(self): + rows = _stay(1, 0, 3, discharge_code=DIED) + patient = _patient(rows) + self.assertEqual(ICUAdmissionMEDS()(patient)[0]["icu_admission"], 1) + icu_only = ICUAdmissionMEDS(death_as_positive=False) + self.assertEqual(icu_only(patient)[0]["icu_admission"], 0) + + def test_meds_death_inside_stay_without_died_code_is_positive(self): + rows = _stay(1, 0, 3, between=[(70, DEATH, None)]) + self.assertEqual(ICUAdmissionMEDS()(_patient(rows))[0]["icu_admission"], 1) + + def test_death_after_discharge_is_negative(self): + rows = _stay(1, 0, 3) + [(80, DEATH, None)] + self.assertEqual(ICUAdmissionMEDS()(_patient(rows))[0]["icu_admission"], 0) + + def test_input_stops_at_admission(self): + rows = ( + [(None, "GENDER//F", None), (-100, LAB, None)] + + _stay( + 1, + 0, + 3, + discharge_code=DIED, + between=[(0, ICU_IN, 1), (0, LAB + "//same-time", 1), (5, LAB, 1)], + ) + + [(73, DEATH, None)] + ) + codes = ICUAdmissionMEDS()(_patient(rows))[0]["codes"] + self.assertEqual(codes, ["GENDER//F", LAB, ADMIT]) + + def test_icu_entry_stamped_before_admission_stays_out_of_input(self): + rows = [(-1, ICU_IN, 1)] + _stay(1, 0, 3) + sample = ICUAdmissionMEDS()(_patient(rows))[0] + self.assertEqual(sample["icu_admission"], 1) + self.assertNotIn(ICU_IN, sample["codes"]) + + def test_date_resolution_events_of_this_stay_stay_out_of_input(self): + hcpcs = "HCPCS//G0378" + rows = ( + _stay(1, 0, 3, between=[(-8, hcpcs, 1)]) # midnight of T0's day + + [(-1, LAB, 1)] # timed ED lab of this stay is kept + ) + for task_cls in (ICUAdmissionMEDS, ProlongedLengthOfStayMEDS): + with self.subTest(task=task_cls.__name__): + codes = task_cls()(_patient(rows))[0]["codes"] + self.assertEqual(codes, [LAB, ADMIT]) + + def test_date_resolution_events_of_earlier_stays_remain(self): + hcpcs = "HCPCS//G0378" + rows = _stay(1, 16, 3, between=[(40, hcpcs, 1)]) + _stay(2, 200, 3) + codes = ICUAdmissionMEDS()(_patient(rows))[1]["codes"] + self.assertIn(hcpcs, codes) + + def test_previous_stay_is_history(self): + rows = _stay(1, 0, 3, between=[(5, ICU_IN, 1), (9, ICU_OUT, 1)]) + _stay( + 2, 200, 3 + ) + samples = ICUAdmissionMEDS()(_patient(rows)) + self.assertEqual(samples[1]["codes"], [ADMIT, ICU_IN, ICU_OUT, HOME, ADMIT]) + self.assertEqual(samples[1]["icu_admission"], 0) + + +class TestHospitalReadmissionMEDS(unittest.TestCase): + def test_admission_within_window_is_positive(self): + rows = _stay(1, 0, 3) + _stay(2, _hours(3 + 29), 2) + samples = HospitalReadmissionMEDS()(_patient(rows)) + labels = {s["hadm_id"]: s["readmission"] for s in samples} + self.assertEqual(labels, {1: 1, 2: 0}) + + def test_window_is_inclusive(self): + rows = _stay(1, 0, 3) + _stay(2, _hours(3 + 30), 2) + patient = _patient(rows) + self.assertEqual(HospitalReadmissionMEDS()(patient)[0]["readmission"], 1) + shorter = HospitalReadmissionMEDS(window_days=29.0) + self.assertEqual(shorter(patient)[0]["readmission"], 0) + + def test_admission_after_window_is_negative(self): + rows = _stay(1, 0, 3) + _stay(2, _hours(3 + 31), 2) + self.assertEqual( + HospitalReadmissionMEDS()(_patient(rows))[0]["readmission"], 0 + ) + + def test_death_within_window_is_positive(self): + rows = _stay(1, 0, 3) + [(_hours(3 + 10), DEATH, None)] + self.assertEqual( + HospitalReadmissionMEDS()(_patient(rows))[0]["readmission"], 1 + ) + + def test_in_hospital_death_is_excluded(self): + died_code = _stay(1, 0, 3, discharge_code=DIED) + meds_death = _stay(1, 0, 3, between=[(70, DEATH, None)]) + self.assertEqual(HospitalReadmissionMEDS()(_patient(died_code)), []) + self.assertEqual(HospitalReadmissionMEDS()(_patient(meds_death)), []) + + def test_input_keeps_this_discharge_but_no_outcome(self): + rows = ( + [(None, "GENDER//F", None)] + + _stay(1, 0, 3, between=[(5, LAB, 1)]) + + [(_hours(3), DX, 1), (_hours(3), "DRG//HCFA//871", 1)] + # Stamped at the discharge instant, but not part of this stay. + + _stay(2, _hours(3), 2) + + [(_hours(3), LAB, None), (_hours(4), DEATH, None)] + ) + sample = HospitalReadmissionMEDS()(_patient(rows))[0] + self.assertEqual(sample["readmission"], 1) + self.assertEqual( + sorted(sample["codes"]), + sorted(["GENDER//F", ADMIT, LAB, HOME, DX, "DRG//HCFA//871"]), + ) + self.assertEqual(sample["codes"].count(ADMIT), 1) + + def test_full_followup_drops_censored_negatives_only(self): + censored = _stay(1, 0, 3) + [(_hours(3 + 5), LAB, None)] + observed = _stay(1, 0, 3) + [(_hours(3 + 40), LAB, None)] + positive = _stay(1, 0, 3) + _stay(2, _hours(3 + 5), 1) + task = HospitalReadmissionMEDS(require_full_followup=True) + self.assertEqual(task(_patient(censored)), []) + self.assertEqual(task(_patient(observed))[0]["readmission"], 0) + self.assertEqual(task(_patient(positive))[0]["readmission"], 1) + self.assertEqual(len(HospitalReadmissionMEDS()(_patient(censored))), 1) + + +class TestProlongedLengthOfStayMEDS(unittest.TestCase): + def test_labels_around_inclusive_threshold(self): + for days, expected in ((10, 1), (11, 1), (9.5, 0)): + with self.subTest(days=days): + samples = ProlongedLengthOfStayMEDS()(_patient(_stay(1, 0, days))) + self.assertEqual(samples[0]["prolonged_los"], expected) + + def test_custom_threshold(self): + task = ProlongedLengthOfStayMEDS(threshold_days=2.0) + self.assertEqual(task(_patient(_stay(1, 0, 3)))[0]["prolonged_los"], 1) + + def test_stay_ending_in_death_is_kept(self): + rows = _stay(1, 0, 12, discharge_code=DIED) + samples = ProlongedLengthOfStayMEDS()(_patient(rows)) + self.assertEqual(samples[0]["prolonged_los"], 1) + + def test_stay_is_measured_to_meds_death(self): + rows = _stay(1, 0, 12, between=[(_hours(4), DEATH, None)]) + samples = ProlongedLengthOfStayMEDS()(_patient(rows)) + self.assertEqual(samples[0]["prolonged_los"], 0) + + def test_input_stops_at_admission(self): + rows = _stay( + 1, + 0, + 12, + discharge_code=DIED, + between=[(5, LAB, 1), (6, ICU_IN, 1)], + ) + [(_hours(12) + 3, DEATH, None)] + codes = ProlongedLengthOfStayMEDS()(_patient(rows))[0]["codes"] + self.assertEqual(codes, [ADMIT]) + + +class TestSharedBehavior(unittest.TestCase): + TASKS = (ICUAdmissionMEDS, HospitalReadmissionMEDS, ProlongedLengthOfStayMEDS) + + def _assert_no_samples(self, rows): + for task_cls in self.TASKS: + with self.subTest(task=task_cls.__name__): + self.assertEqual(task_cls()(_patient(rows)), []) + + def test_no_events(self): + self._assert_no_samples([]) + + def test_no_stays(self): + self._assert_no_samples([(0, LAB, None), (5, DEATH, None)]) + + def test_stay_without_discharge(self): + self._assert_no_samples([(0, ADMIT, 1), (5, LAB, 1)]) + + def test_stay_without_admission(self): + self._assert_no_samples([(0, LAB, 1), (5, HOME, 1)]) + + def test_zero_length_stay(self): + self._assert_no_samples([(5, ADMIT, 1), (5, HOME, 1)]) + + def test_admission_events_without_hadm(self): + self._assert_no_samples([(0, ADMIT, None), (5, HOME, None)]) + + def test_stay_without_other_events_yields_admission_only(self): + for task_cls in (ICUAdmissionMEDS, ProlongedLengthOfStayMEDS): + with self.subTest(task=task_cls.__name__): + samples = task_cls()(_patient(_stay(1, 0, 3))) + self.assertEqual(samples[0]["codes"], [ADMIT]) + + def test_float_hadm_id_stays_integral(self): + rows = [ + (r[0], r[1], None if r[2] is None else float(r[2])) + for r in _stay(1, 0, 3) + [(90, LAB, None)] + ] + patient = _patient(rows, hadm_dtype=pl.Float64) + for task_cls in self.TASKS: + with self.subTest(task=task_cls.__name__): + hadm_id = task_cls()(patient)[0]["hadm_id"] + self.assertIsInstance(hadm_id, int) + + def test_outcome_events_never_reach_input(self): + rows = ( + _stay(1, 0, 3, between=[(5, ICU_IN, 1), (9, ICU_OUT, 1)]) + + _stay(2, 200, 12, discharge_code=DIED, between=[(205, ICU_IN, 2)]) + + [(200 + _hours(12) + 2, DEATH, None)] + ) + patient = _patient(rows) + for task_cls in (ICUAdmissionMEDS, ProlongedLengthOfStayMEDS): + with self.subTest(task=task_cls.__name__): + first, second = task_cls()(patient) + self.assertEqual(first["codes"], [ADMIT]) + self.assertEqual( + second["codes"], [ADMIT, ICU_IN, ICU_OUT, HOME, ADMIT] + ) + sample = HospitalReadmissionMEDS()(patient)[0] + self.assertEqual(sample["hadm_id"], 1) + self.assertEqual(sample["readmission"], 1) + self.assertNotIn(ADMIT, sample["codes"][1:]) + self.assertNotIn(DIED, sample["codes"]) + self.assertNotIn(DEATH, sample["codes"]) + + def test_invalid_arguments(self): + with self.assertRaises(ValueError): + HospitalReadmissionMEDS(window_days=0) + with self.assertRaises(ValueError): + ProlongedLengthOfStayMEDS(threshold_days=-1) + + +class TestSetTask(unittest.TestCase): + """All three tasks through MEDSDataset, on synthetic typed Parquet.""" + + def setUp(self): + self.temp_dir = Path(tempfile.mkdtemp()) + root = self.temp_dir / "meds" + (root / "data").mkdir(parents=True) + config_path = self.temp_dir / "meds_hadm.yaml" + config_path.write_text(_CONFIG) + + rows = [ + (1, None, "GENDER//F", None), + (1, 0, ADMIT, 10), + (1, 2, LAB, 10), + (1, 5, ICU_IN, 10), + (1, _hours(11), HOME, 10), + (1, _hours(20), ADMIT, 11), + (1, _hours(20) + 3, LAB, 11), + (1, _hours(22), DIED, 11), + (2, 0, ADMIT, 20), + (2, 3, LAB, 20), + (2, _hours(2), HOME, 20), + (2, _hours(50), LAB, None), + ] + pl.DataFrame( + { + "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), + "time": pl.Series([_at(r[1]) for r in rows], dtype=pl.Datetime("us")), + "code": pl.Series([r[2] for r in rows], dtype=pl.String), + "numeric_value": pl.Series([None] * len(rows), dtype=pl.Float32), + "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), + } + ).write_parquet(root / "data" / "0.parquet") + + self.dataset = MEDSDataset( + root=str(root), + config_path=str(config_path), + cache_dir=self.temp_dir / "cache", + num_workers=1, + ) + + def tearDown(self): + shutil.rmtree(self.temp_dir, ignore_errors=True) + + def _assert_labels(self, task, key, labels): + samples = self.dataset.set_task(task, num_workers=1) + self.assertEqual(len(samples), len(labels)) + self.assertEqual( + sorted(int(samples[i][key]) for i in range(len(samples))), + sorted(labels), + ) + samples.close() + + def test_icu_admission(self): + self._assert_labels(ICUAdmissionMEDS(), "icu_admission", [1, 1, 0]) + + def test_readmission(self): + self._assert_labels(HospitalReadmissionMEDS(), "readmission", [1, 0]) + + def test_prolonged_los(self): + self._assert_labels(ProlongedLengthOfStayMEDS(), "prolonged_los", [1, 0, 0]) + + def test_static_events_survive_the_pipeline(self): + codes = ICUAdmissionMEDS()(self.dataset.get_patient("1"))[0]["codes"] + self.assertEqual(codes, ["GENDER//F", ADMIT]) + + +if __name__ == "__main__": + unittest.main() From c9757df60af5d0e4c0027056db3904b38402b843 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Thu, 5 Nov 2026 13:15:33 -0600 Subject: [PATCH 03/10] Add ETHOS generative timeline model with zero-shot risk estimation Adds the ETHOS GPT-style model as a BaseModel, EthosContextProcessor for the static context, EthosTimelineMEDS for training and EthosOutcomeMEDS to connect the MEDS outcome tasks to it. EthosProcessor now learns interval estimates. Rollouts stop by token or simulated time, and an EthosRolloutRule turns them into a risk. Co-Authored-By: Claude Opus 5.5 --- docs/api/models.rst | 1 + docs/api/models/pyhealth.models.ETHOS.rst | 13 + docs/api/processors.rst | 2 + ...ealth.processors.EthosContextProcessor.rst | 11 + docs/api/tasks.rst | 2 + .../tasks/pyhealth.tasks.EthosOutcomeMEDS.rst | 12 + .../pyhealth.tasks.EthosTimelineMEDS.rst | 7 + examples/ethos_zero_shot.py | 221 +++++++ pyhealth/models/__init__.py | 1 + pyhealth/models/ethos.py | 567 ++++++++++++++++++ pyhealth/processors/__init__.py | 2 + .../processors/ethos_context_processor.py | 244 ++++++++ pyhealth/processors/ethos_processor.py | 23 +- pyhealth/tasks/__init__.py | 5 + pyhealth/tasks/ethos_tasks.py | 326 ++++++++++ pyhealth/tasks/meds_outcome_tasks.py | 30 +- tests/core/test_ethos.py | 451 ++++++++++++++ tests/core/test_ethos_context_processor.py | 120 ++++ tests/core/test_ethos_processor.py | 30 + tests/core/test_ethos_tasks.py | 183 ++++++ 20 files changed, 2238 insertions(+), 13 deletions(-) create mode 100644 docs/api/models/pyhealth.models.ETHOS.rst create mode 100644 docs/api/processors/pyhealth.processors.EthosContextProcessor.rst create mode 100644 docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst create mode 100644 docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst create mode 100644 examples/ethos_zero_shot.py create mode 100644 pyhealth/models/ethos.py create mode 100644 pyhealth/processors/ethos_context_processor.py create mode 100644 pyhealth/tasks/ethos_tasks.py create mode 100644 tests/core/test_ethos.py create mode 100644 tests/core/test_ethos_context_processor.py create mode 100644 tests/core/test_ethos_tasks.py diff --git a/docs/api/models.rst b/docs/api/models.rst index a4f7e0d90d..79dfbdc071 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -230,6 +230,7 @@ API Reference models/pyhealth.models.Deepr models/pyhealth.models.EHRMamba models/pyhealth.models.EHRMambaCEHR + models/pyhealth.models.ETHOS models/pyhealth.models.JambaEHR models/pyhealth.models.ContraWR models/pyhealth.models.SparcNet diff --git a/docs/api/models/pyhealth.models.ETHOS.rst b/docs/api/models/pyhealth.models.ETHOS.rst new file mode 100644 index 0000000000..b041a2327e --- /dev/null +++ b/docs/api/models/pyhealth.models.ETHOS.rst @@ -0,0 +1,13 @@ +pyhealth.models.ETHOS +=================================== + +ETHOS: a GPT-style generative model of tokenized patient timelines, with +zero-shot risk estimation by sampling future timelines +(`Renc et al., 2025 `_). Train it on +:class:`~pyhealth.tasks.EthosTimelineMEDS`, then estimate risks on +:class:`~pyhealth.tasks.EthosOutcomeMEDS`. + +.. autoclass:: pyhealth.models.ETHOS + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/processors.rst b/docs/api/processors.rst index de3fecb269..d40808059b 100644 --- a/docs/api/processors.rst +++ b/docs/api/processors.rst @@ -30,6 +30,7 @@ Available Processors - ``NestedMultiHotProcessor``: For nested categorical sequences as per-visit multi-hot vectors (e.g., generative EHR models) - ``NestedFloatsProcessor``: For nested numerical sequences with optional forward-fill - :doc:`EthosProcessor `: Tokenizes MEDS patient timelines the way ETHOS does, with quantile tokens for numeric values and time-interval tokens (``"ethos"``, fitted on the training split) +- :doc:`EthosContextProcessor `: Encodes a patient's demographics and birth date as the static context of an ETHOS timeline (``"ethos_context"``) **Label Processors:** @@ -566,6 +567,7 @@ API Reference processors/pyhealth.processors.TextProcessor processors/pyhealth.processors.TupleTimeTextProcessor processors/pyhealth.processors.EthosProcessor + processors/pyhealth.processors.EthosContextProcessor processors/pyhealth.processors.AudioProcessor processors/pyhealth.processors.SignalProcessor processors/pyhealth.processors.TimeseriesProcessor diff --git a/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst b/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst new file mode 100644 index 0000000000..c84b4fc87b --- /dev/null +++ b/docs/api/processors/pyhealth.processors.EthosContextProcessor.rst @@ -0,0 +1,11 @@ +pyhealth.processors.EthosContextProcessor +========================================= + +Encodes the static patient context that opens an ETHOS timeline: one token per +demographic attribute, plus the patient's age at the start of the timeline. +Registered as ``"ethos_context"``. + +.. autoclass:: pyhealth.processors.EthosContextProcessor + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 659398a422..afbfeb4fec 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -214,6 +214,8 @@ Available Tasks ICU Admission (MEDS) Hospital Readmission (MEDS) Prolonged Length of Stay (MEDS) + ETHOS Timelines (MEDS) + ETHOS Zero-Shot Outcomes (MEDS) MIMIC-III ICD-9 Coding Cardiology Detection COVID-19 CXR Classification diff --git a/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst b/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst new file mode 100644 index 0000000000..edeefb1a9f --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.EthosOutcomeMEDS.rst @@ -0,0 +1,12 @@ +pyhealth.tasks.EthosOutcomeMEDS +=============================== + +.. autoclass:: pyhealth.tasks.ethos_tasks.EthosOutcomeMEDS + :members: + :undoc-members: + :show-inheritance: + +.. autoclass:: pyhealth.tasks.ethos_tasks.EthosRolloutRule + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst b/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst new file mode 100644 index 0000000000..487671f76d --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.EthosTimelineMEDS.rst @@ -0,0 +1,7 @@ +pyhealth.tasks.EthosTimelineMEDS +================================ + +.. autoclass:: pyhealth.tasks.ethos_tasks.EthosTimelineMEDS + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/ethos_zero_shot.py b/examples/ethos_zero_shot.py new file mode 100644 index 0000000000..432105e949 --- /dev/null +++ b/examples/ethos_zero_shot.py @@ -0,0 +1,221 @@ +"""Train a tiny ETHOS and estimate risks by sampling future timelines. + +Smoke test on synthetic data: this writes a small MEDS directory to a temporary +folder, so it needs no credentials and no download. The numbers mean nothing +clinically, and nothing here reproduces a result from the paper. Sixty made-up +patients and a tiny model cannot, whatever the AUROCs below happen to be. + +For reference, Renc et al. (arXiv:2502.06124, Table S1) report these test +AUROCs for the full model, with 100 rollouts per sample, on all of MIMIC-IV 2.2: +ICU admission 0.932 and prolonged stay 0.853. Those runs also use ETHOS's MIMIC +preprocessing (ICD and ATC mapping, the top-200 lab filter, blood pressure and +BMI rewrites), which PyHealth does not have, so vocabularies will not match the +paper's on MIMIC-IV. + +To use a real MEDS dataset, such as MIMIC-IV after MEDS extraction (credentialed +access required), pass ``--root``, and raise the sizes to the paper's: + + python examples/ethos_zero_shot.py --root /path/to/meds \\ + --n-layer 6 --n-head 12 --n-embd 768 --n-positions 2048 \\ + --dropout 0.3 --lr 6e-4 --epochs 20 --rollouts 100 + +Usage: + python examples/ethos_zero_shot.py +""" + +import argparse +import random +import tempfile +from datetime import datetime, timedelta +from pathlib import Path + +import polars as pl +import torch +from sklearn.metrics import roc_auc_score + +import pyhealth.datasets.configs as meds_configs +from pyhealth.datasets import MEDSDataset, PatientSplit, get_dataloader +from pyhealth.models import ETHOS +from pyhealth.tasks import ( + EthosOutcomeMEDS, + EthosTimelineMEDS, + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, +) +from pyhealth.trainer import Trainer + +ADMIT = "HOSPITAL_ADMISSION//EW EMER.//ER" +SICK_LAB = "LAB//50813//mmol/L" +ROUTINE_LAB = "LAB//51221//%" + + +def write_synthetic_meds(root: Path, n_subjects: int = 60, seed: int = 0) -> None: + """Writes synthetic stays where age and past labs foreshadow the outcome. + + Args: + root: Output directory. + n_subjects: Number of synthetic subjects. + seed: Random seed. + """ + rng = random.Random(seed) + rows = [] + for subject in range(1, n_subjects + 1): + now = datetime.fromisoformat("2024-01-01T08:00:00") # MEDS times are naive + now += timedelta(days=rng.randint(0, 60)) + birth = datetime.fromisoformat(f"{rng.randint(1940, 2000)}-01-01") + frail = birth.year < 1970 # Stays of older patients go worse. + rows.append((subject, None, f"GENDER//{rng.choice('FM')}", None, None)) + rows.append((subject, birth, "MEDS_BIRTH", None, None)) + for stay in range(rng.randint(1, 3)): + hadm = subject * 100 + stay + sick = rng.random() < (0.9 if frail else 0.1) + length = timedelta(days=rng.uniform(11, 16) if sick else rng.uniform(1, 6)) + rows.append((subject, now, ADMIT, hadm, None)) + for hours in (1, 2, 6, 24): + value = rng.gauss(8.0 if sick else 1.5, 0.5) + rows.append( + (subject, now + timedelta(hours=hours), SICK_LAB, hadm, value) + ) + value = rng.gauss(30.0, 3.0) + rows.append( + (subject, now + timedelta(hours=hours), ROUTINE_LAB, hadm, value) + ) + if sick: + icu = now + timedelta(hours=30) + rows.append((subject, icu, "ICU_ADMISSION//MICU", hadm, None)) + rows.append( + (subject, icu + timedelta(hours=40), "ICU_DISCHARGE//MICU", hadm, None) + ) + discharge = now + length + rows.append((subject, discharge, "HOSPITAL_DISCHARGE//HOME", hadm, None)) + now = discharge + timedelta(days=rng.choice([10, 20, 90])) + + (root / "data").mkdir(parents=True) + pl.DataFrame( + { + "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), + "time": pl.Series([r[1] for r in rows], dtype=pl.Datetime("us")), + "code": pl.Series([r[2] for r in rows], dtype=pl.String), + "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), + "numeric_value": pl.Series([r[4] for r in rows], dtype=pl.Float32), + } + ).write_parquet(root / "data" / "0.parquet") + + +def evaluate(dataset, model, test_patients, task, args) -> None: + """Prints zero-shot risks for one outcome on the test patients. + + Args: + dataset: The MEDS dataset. + model: The trained model. + test_patients: Patient ids held out of training. + task: An :class:`EthosOutcomeMEDS`. + args: Command-line arguments. + """ + samples = dataset.set_task( + task, num_workers=1, input_processors=model.dataset.input_processors + ) + held_out = [ + index + for patient, indices in samples.patient_to_index.items() + if patient in test_patients + for index in indices + ] + label_key = next(iter(task.output_schema)) + risk = model.estimate_risk( + get_dataloader(samples.subset(held_out), batch_size=8), + task.rule, + num_rollouts=args.rollouts, + max_new_tokens=args.max_new_tokens, + label_key=label_key, + seed=0, + ) + scored = ~risk["y_prob"].isnan() + y_true, y_prob = risk["y_true"][scored], risk["y_prob"][scored] + kept = risk["num_kept"].float().mean().item() + print( + f"{task.task_name}: samples={len(held_out)} scored={int(scored.sum())} " + f"mean rollouts kept={kept:.1f}/{args.rollouts} " + f"true rate={y_true.mean().item():.3f} mean risk={y_prob.mean().item():.3f}" + ) + if len(set(y_true.tolist())) == 2: + auroc = roc_auc_score(y_true.numpy(), y_prob.numpy()) + print(f" AUROC on these few samples (smoke test only): {auroc:.3f}") + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--root", default=None, help="MEDS root; omit for synthetic.") + parser.add_argument("--n-layer", type=int, default=2) + parser.add_argument("--n-head", type=int, default=2) + parser.add_argument("--n-embd", type=int, default=32) + parser.add_argument("--n-positions", type=int, default=256) + parser.add_argument("--dropout", type=float, default=0.0) + parser.add_argument("--epochs", type=int, default=60) + parser.add_argument("--lr", type=float, default=3e-3) + parser.add_argument("--rollouts", type=int, default=20) + parser.add_argument("--max-new-tokens", type=int, default=256) + args = parser.parse_args() + + config = Path(meds_configs.__file__).parent / "meds_with_hadm.yaml" + with tempfile.TemporaryDirectory() as tmp: + tmp_path = Path(tmp) + if args.root is None: + print("Using synthetic MEDS data: a smoke test, not a result.") + root = tmp_path / "synthetic_meds" + write_synthetic_meds(root) + else: + root = Path(args.root) + + dataset = MEDSDataset( + root=str(root), + config_path=str(config), + cache_dir=tmp_path / "cache", + num_workers=1, + ) + # The split fits the vocabulary and quantile breaks on training patients. + train, test = dataset.set_task( + EthosTimelineMEDS(), + split=PatientSplit(ratios=(0.7, 0.3), seed=0), + num_workers=1, + ) + print("training and held-out patients:", len(train), len(test)) + + model = ETHOS( + train, + n_layer=args.n_layer, + n_head=args.n_head, + n_embd=args.n_embd, + n_positions=args.n_positions, + dropout=args.dropout, + ) + trainer = Trainer(model=model, enable_logging=False) + trainer.train( + train_dataloader=get_dataloader(train, batch_size=8, shuffle=True), + epochs=args.epochs, + optimizer_class=torch.optim.AdamW, + optimizer_params={"lr": args.lr, "betas": (0.9, 0.95)}, + weight_decay=0.1, + max_grad_norm=1.0, + ) + held_out = trainer.evaluate(get_dataloader(test, batch_size=8)) + print("loss on held-out timelines:", held_out["loss"]) + + checkpoint = str(tmp_path / "ethos.ckpt") + trainer.save_ckpt(checkpoint) + trainer.load_ckpt(checkpoint) + print("checkpoint reloaded") + + test_patients = set(test.patient_to_index) + tasks = [ + EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False), + EthosOutcomeMEDS(ProlongedLengthOfStayMEDS), + EthosOutcomeMEDS(HospitalReadmissionMEDS), + ] + for task in tasks: + evaluate(dataset, model, test_patients, task, args) + + +if __name__ == "__main__": + main() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index f83c7aeaab..3f175d455d 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -80,6 +80,7 @@ from .generators.corgan import CorGAN as CorGAN from .survival_mdn import SurvivalMDN as SurvivalMDN from .trajsurv import TrajSurv as TrajSurv +from .ethos import ETHOS as ETHOS from .heartlang import ( HeartLang as HeartLang, HeartLangBackbone as HeartLangBackbone, diff --git a/pyhealth/models/ethos.py b/pyhealth/models/ethos.py new file mode 100644 index 0000000000..4a30c2f069 --- /dev/null +++ b/pyhealth/models/ethos.py @@ -0,0 +1,567 @@ +"""ETHOS: a generative model of patient timelines, with zero-shot risk estimates. + +ETHOS is a GPT-style decoder trained to predict the next token of a tokenized +patient timeline. It needs no labels: to estimate a risk it samples many future +timelines from the prediction time and counts how often the outcome happens. + +Paper: + Renc et al. Foundation Model of Electronic Medical Records for Adaptive + Risk Estimation. https://arxiv.org/abs/2502.06124 + +Adapted from ethos-ares (commit 2d54383), ``src/ethos/model.py`` and +``src/ethos/inference/{inference,utils}.py``: +https://github.com/ipolharvard/ethos-ares + +MIT License. Copyright (c) 2024 Paweł Renc. +""" + +from __future__ import annotations + +import math +from collections.abc import Iterable +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn + +from pyhealth.datasets import SampleDataset +from pyhealth.processors import EthosContextProcessor, EthosProcessor +from pyhealth.processors.ethos_processor import TIMELINE_END_TOKEN +from pyhealth.tasks.ethos_tasks import ( + INVALID_TOKEN, + STOP_TOKEN, + TIME_LIMIT, + TOKEN_LIMIT, + EthosRolloutRule, +) + +from .base_model import BaseModel + +HOURS_PER_YEAR = 24 * 365.25 +IGNORE_INDEX = -100 + + +class _CausalSelfAttention(nn.Module): + """Multi-head causal self-attention without bias terms.""" + + def __init__(self, n_embd: int, n_head: int, dropout: float) -> None: + super().__init__() + self.c_attn = nn.Linear(n_embd, 3 * n_embd, bias=False) + self.c_proj = nn.Linear(n_embd, n_embd, bias=False) + self.resid_dropout = nn.Dropout(dropout) + self.n_head = n_head + self.dropout = dropout + + def forward(self, x: torch.Tensor) -> torch.Tensor: + batch, length, width = x.size() + q, k, v = ( + part.view(batch, length, self.n_head, width // self.n_head).transpose(1, 2) + for part in self.c_attn(x).split(width, dim=2) + ) + y = F.scaled_dot_product_attention( + q, + k, + v, + dropout_p=self.dropout if self.training else 0.0, + is_causal=True, + ) + y = y.transpose(1, 2).contiguous().view(batch, length, width) + return self.resid_dropout(self.c_proj(y)) + + +class _MLP(nn.Module): + """The feed-forward part of a transformer block.""" + + def __init__(self, n_embd: int, dropout: float) -> None: + super().__init__() + self.c_fc = nn.Linear(n_embd, 4 * n_embd, bias=False) + self.activation = nn.GELU() + self.c_proj = nn.Linear(4 * n_embd, n_embd, bias=False) + self.dropout = nn.Dropout(dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + return self.dropout(self.c_proj(self.activation(self.c_fc(x)))) + + +class _Block(nn.Module): + """A pre-norm transformer block.""" + + def __init__(self, n_embd: int, n_head: int, dropout: float) -> None: + super().__init__() + self.ln_1 = nn.LayerNorm(n_embd, bias=False) + self.attn = _CausalSelfAttention(n_embd, n_head, dropout) + self.ln_2 = nn.LayerNorm(n_embd, bias=False) + self.mlp = _MLP(n_embd, dropout) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + x = x + self.attn(self.ln_1(x)) + return x + self.mlp(self.ln_2(x)) + + +def _age_quantiles( + age_years: torch.Tensor, num_quantiles: int +) -> tuple[torch.Tensor, torch.Tensor]: + """Writes ages as two digits in base ``num_quantiles``, as ETHOS does. + + With 10 quantiles, age 46 is ``(4, 6)``: the tokens ``Q5`` and ``Q7``. + + Args: + age_years: Ages in years. + num_quantiles: Number of quantile tokens. + + Returns: + Both digits, from 0, as ``long`` tensors. ``nan`` gives ``-1``. + """ + scaled = (age_years * num_quantiles**2 / 100).clamp(0, num_quantiles**2 - 1) + high = torch.div(scaled, num_quantiles, rounding_mode="floor") + low = torch.round(scaled - high * num_quantiles) + carry = low == num_quantiles + high, low = high + carry, low.masked_fill(carry, 0) + missing = age_years.isnan() + return ( + high.nan_to_num(0).long().masked_fill(missing, -1), + low.nan_to_num(0).long().masked_fill(missing, -1), + ) + + +class ETHOS(BaseModel): + """ETHOS generative timeline model with zero-shot risk estimation. + + :meth:`forward` is the next-token loss, so the model trains with + :class:`~pyhealth.trainer.Trainer` on + :class:`~pyhealth.tasks.EthosTimelineMEDS`, with no labels. It has no + ``mode`` and gives no ``y_prob``. Risks come from :meth:`estimate_risk`, + which samples timelines forward from each sample of + :class:`~pyhealth.tasks.EthosOutcomeMEDS`. + + The input is the static context followed by the timeline, as in ETHOS. A + timeline that does not fit in ``n_positions`` gives a random window in + training and its last tokens otherwise, and the age tokens state the age + where that window starts. Demographics keep their value at the start of the + whole timeline. + + The defaults are the paper's final model. Layer names match ``ethos-ares``. + Reload a checkpoint only with the fitted processors it was trained on: the + token ids mean nothing without them. + + Args: + dataset: A dataset with an ``"ethos"`` field named ``timeline`` and an + ``"ethos_context"`` field named ``context``. + n_layer: Number of transformer blocks. + n_head: Number of attention heads. + n_embd: Embedding size. + n_positions: Context size, including the static context. + dropout: Dropout rate. + + Raises: + ValueError: If ``dataset`` lacks those fields, or the sizes do not fit. + + Examples: + >>> from datetime import datetime, timedelta + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import ETHOS + >>> from pyhealth.tasks import EthosRolloutRule + >>> start = datetime(2024, 1, 1) + >>> codes = ["HOSPITAL_ADMISSION//ER", "LAB//A", "MEDS_DEATH"] + >>> samples = [ + ... { + ... "patient_id": f"p{i}", + ... "timeline": { + ... "time": [start + timedelta(hours=h) for h in (0, 1, 2)], + ... "code": codes, + ... "numeric_value": [None, 1.0 + i, None], + ... }, + ... "context": { + ... "time": [datetime(1980, 1, 1)], + ... "code": ["MEDS_BIRTH"], + ... "start": start, + ... }, + ... } + ... for i in range(3) + ... ] + >>> dataset = create_sample_dataset( + ... samples, + ... input_schema={"timeline": "ethos", "context": "ethos_context"}, + ... output_schema={}, + ... ) + >>> model = ETHOS(dataset, n_layer=1, n_head=2, n_embd=8, n_positions=32) + >>> batch = next(iter(get_dataloader(dataset, batch_size=3))) + >>> model(**batch)["loss"].backward() + >>> rule = EthosRolloutRule(("MEDS_DEATH", "TIMELINE_END"), ("MEDS_DEATH",)) + >>> risk = model.estimate_risk( + ... [batch], rule, num_rollouts=4, max_new_tokens=8, seed=0 + ... ) + >>> risk["y_prob"].shape + torch.Size([3]) + """ + + def __init__( + self, + dataset: SampleDataset, + n_layer: int = 6, + n_head: int = 12, + n_embd: int = 768, + n_positions: int = 2048, + dropout: float = 0.3, + ) -> None: + super().__init__(dataset=dataset) + self.mode = None + + processors = dataset.input_processors + timeline = processors.get("timeline") + context = processors.get("context") + has_fields = isinstance(timeline, EthosProcessor) and isinstance( + context, EthosContextProcessor + ) + if not has_fields: + raise ValueError( + "ETHOS needs a 'timeline' field of type 'ethos' and a 'context' " + "field of type 'ethos_context'; see EthosTimelineMEDS." + ) + if n_embd % n_head != 0: + raise ValueError(f"n_embd {n_embd} must divide by n_head {n_head}.") + if n_positions <= context.context_size: + raise ValueError( + f"n_positions {n_positions} leaves no room after the " + f"{context.context_size} context tokens." + ) + self.timeline_processor = timeline + self.context_processor = context + self.n_positions = n_positions + self.context_size = context.context_size + self.timeline_size = n_positions - context.context_size + + # Context tokens sit after the timeline's. The vocabulary is rounded up + # to a multiple of 64, as in ETHOS, so it can have ids that are not + # tokens; sampling one is an invalid token. + self.timeline_vocab_size = timeline.size() + self.vocab_size = math.ceil((timeline.size() + context.size()) / 64) * 64 + + self.transformer = nn.ModuleDict( + { + "wte": nn.Embedding(self.vocab_size, n_embd), + "wpe": nn.Embedding(n_positions, n_embd), + "drop": nn.Dropout(dropout), + "h": nn.ModuleList( + [_Block(n_embd, n_head, dropout) for _ in range(n_layer)] + ), + "ln_f": nn.LayerNorm(n_embd, bias=False), + } + ) + self.lm_head = nn.Linear(n_embd, self.vocab_size, bias=False) + self.transformer["wte"].weight = self.lm_head.weight + + self.apply(self._init_weights) + for name, parameter in self.named_parameters(): + if name.endswith("c_proj.weight"): + nn.init.normal_(parameter, mean=0.0, std=0.02 / math.sqrt(2 * n_layer)) + + vocab = timeline.vocab + self.register_buffer( + "quantile_ids", + torch.tensor( + [vocab[f"Q{k + 1}"] for k in range(timeline.num_quantiles)], + dtype=torch.long, + ), + persistent=False, + ) + # On the CPU in float64: not every device has that type. + self._interval_hours = torch.zeros(self.vocab_size, dtype=torch.float64) + for label, hours in timeline.interval_estimates.items(): + self._interval_hours[vocab[label]] = hours + self._is_token = torch.zeros(self.vocab_size, dtype=torch.bool) + self._is_token[: self.timeline_vocab_size] = True + self._is_token[[vocab.pad_id, vocab.unk_id]] = False + self._id_to_token = {i: token for token, i in vocab.token_to_id.items()} + + @staticmethod + def _init_weights(module: nn.Module) -> None: + if isinstance(module, (nn.Linear, nn.Embedding)): + nn.init.normal_(module.weight, mean=0.0, std=0.02) + + def _logits(self, ids: torch.Tensor) -> torch.Tensor: + """Returns next-token logits for token ids of shape ``[B, L]``.""" + positions = torch.arange(ids.size(1), device=ids.device) + x = self.transformer["wte"](ids) + self.transformer["wpe"](positions) + x = self.transformer["drop"](x) + for block in self.transformer["h"]: + x = block(x) + return self.lm_head(self.transformer["ln_f"](x)) + + def _context_ids(self, static: torch.Tensor, age: torch.Tensor) -> torch.Tensor: + """Builds model ids of the static context. + + Args: + static: Output tokens of the context processor, ``[B, C]``. + age: Age in years where the timeline window starts, ``[B]``. + + Returns: + Context ids in the model's vocabulary, ``[B, C]``. + """ + ids = static + self.timeline_vocab_size + unknown = self.timeline_processor.vocab.unk_id + position = self.context_processor.age_position + digits = _age_quantiles(age, self.timeline_processor.num_quantiles) + for offset, digit in enumerate(digits): + tokens = self.quantile_ids[digit.clamp(min=0)] + ids[:, position + offset] = tokens.masked_fill(digit < 0, unknown) + return ids + + def forward(self, **kwargs: Any) -> dict[str, torch.Tensor]: + """Computes the next-token loss. + + Args: + **kwargs: A batch, with ``timeline`` and ``context``. + + Returns: + A dictionary with ``loss``, ``logit`` of shape ``[B, L, V]`` and + ``y_true``, the target ids, with ``-100`` where there is none. + """ + time, tokens = kwargs["timeline"] + age, static = kwargs["context"] + tokens = tokens.to(self.device) + time = time.to(self.device, dtype=torch.float32) + static = static.to(self.device) + age = age.to(self.device, dtype=torch.float32).view(-1) + if tokens.size(1) == 0: + tokens = tokens.new_zeros(len(tokens), 1) + time = time.new_zeros(len(time), 1) + + pad_id = self.timeline_processor.vocab.pad_id + lengths = (tokens != pad_id).sum(dim=1) + spare = (lengths - self.timeline_size - 1).clamp(min=0) + if self.training: + starts = (torch.rand_like(spare, dtype=torch.float32) * (spare + 1)).long() + else: + starts = spare + width = min(tokens.size(1), self.timeline_size + 1) + indices = starts[:, None] + torch.arange(width, device=self.device) + window = tokens.gather(1, indices.clamp(max=tokens.size(1) - 1)) + window = window.masked_fill(indices >= lengths[:, None], pad_id) + + age = age + time.gather(1, starts[:, None]).squeeze(1) / HOURS_PER_YEAR + context = self._context_ids(static, age) + ids = torch.cat([context, window[:, :-1]], dim=1) + labels = torch.cat( + [ + torch.full_like(context, IGNORE_INDEX), + window[:, 1:].masked_fill(window[:, 1:] == pad_id, IGNORE_INDEX), + ], + dim=1, + ) + + logits = self._logits(ids) + if (labels != IGNORE_INDEX).any(): + loss = F.cross_entropy( + logits.view(-1, logits.size(-1)), + labels.view(-1), + ignore_index=IGNORE_INDEX, + ) + else: + # No timeline has a next token. A zero that keeps the graph, instead + # of the NaN mean of nothing. + loss = logits.sum() * 0.0 + return {"loss": loss, "logit": logits, "y_true": labels} + + def _token_mask(self, prefixes: Iterable[str]) -> torch.Tensor: + """Marks the vocabulary's tokens that start with one of ``prefixes``.""" + prefixes = tuple(prefixes) + mask = torch.zeros(self.vocab_size, dtype=torch.bool) + for index, token in self._id_to_token.items(): + mask[index] = token.startswith(prefixes) + return mask + + def _prompt( + self, + time: torch.Tensor, + tokens: torch.Tensor, + age: torch.Tensor, + static: torch.Tensor, + ) -> torch.Tensor: + """Builds the ids that a rollout starts from, ``[1, L]``. + + Args: + time: One sample's hours per token, ``[L]``. + tokens: One sample's tokens, ``[L]``, possibly padded. + age: The sample's age in years. + static: The sample's context tokens, ``[C]``. + + Returns: + The context, then the last tokens that fit. A closing + ``TIMELINE_END`` is left out, since the timeline continues here. + """ + vocab = self.timeline_processor.vocab + kept = tokens != vocab.pad_id + time, tokens = time[kept], tokens[kept].to(self.device) + if len(tokens) and tokens[-1] == vocab[TIMELINE_END_TOKEN]: + time, tokens = time[:-1], tokens[:-1] + start = max(len(tokens) - self.timeline_size, 0) + elapsed = time[start].item() if len(time) else 0.0 + age_at_start = age.to(self.device, dtype=torch.float32).view(-1) + age_at_start = age_at_start + elapsed / HOURS_PER_YEAR + context = self._context_ids(static.to(self.device).view(1, -1), age_at_start) + return torch.cat([context, tokens[start:].view(1, -1)], dim=1) + + @torch.no_grad() + def rollout( + self, + timeline: tuple[torch.Tensor, torch.Tensor], + context: tuple[torch.Tensor, torch.Tensor], + rule: EthosRolloutRule, + num_rollouts: int = 100, + temperature: float = 1.0, + max_new_tokens: int = 8192, + generator: torch.Generator | None = None, + ) -> dict[str, list]: + """Samples future timelines for one sample. + + Each rollout samples one token at a time, adding up the mean duration + of each interval token, until ``rule`` stops it, it passes the time + limit, it samples an id that is not a timeline token, or it reaches + ``max_new_tokens``. + + Args: + timeline: ``(time, tokens)`` of one sample, both ``[L]``. + context: ``(age, tokens)`` of one sample. + rule: When to stop. + num_rollouts: Number of timelines to sample. + temperature: Softmax temperature. + max_new_tokens: Limit on generated tokens per rollout. ETHOS has + none, but a poorly trained model may never advance the clock. + generator: Source of randomness, on this model's device. + + Returns: + A dictionary of lists, one element per rollout: ``tokens`` (the + generated ids), ``actual`` (the last token, or ``None`` if invalid), + ``reason`` (why it stopped) and ``days`` (simulated days). + """ + was_training = self.training + self.eval() + prompt = self._prompt(*timeline, *context) + ids = prompt.repeat(num_rollouts, 1) + stops = self._token_mask(rule.stop_prefixes) + limit = rule.time_limit_days * 24.0 + + alive = torch.arange(num_rollouts) + hours = torch.zeros(num_rollouts, dtype=torch.float64) + generated: list[list[int]] = [[] for _ in range(num_rollouts)] + reasons = [TOKEN_LIMIT] * num_rollouts + for _ in range(max_new_tokens): + logits = self._logits(ids)[:, -1, :] / temperature + probs = F.softmax(logits, dim=-1) + next_ids = torch.multinomial(probs, num_samples=1, generator=generator) + + if ids.size(1) == self.n_positions: + ids = torch.cat( + [ids[:, : self.context_size], ids[:, self.context_size + 1 :]], + dim=1, + ) + ids = torch.cat([ids, next_ids], dim=1) + + drawn = next_ids.view(-1).cpu() + hours[alive] += self._interval_hours[drawn] + for index, token in zip(alive.tolist(), drawn.tolist()): + generated[index].append(token) + + invalid = ~self._is_token[drawn] + late = hours[alive] > limit + done = invalid | late | stops[drawn] + for row in done.nonzero().view(-1).tolist(): + reason = STOP_TOKEN + if late[row]: + reason = TIME_LIMIT + if invalid[row]: + reason = INVALID_TOKEN + reasons[alive[row]] = reason + + alive, ids = alive[~done], ids[~done.to(ids.device)] + if len(alive) == 0: + break + + self.train(was_training) + return { + "tokens": generated, + "actual": [ + self._id_to_token[tokens[-1]] + if tokens and self._is_token[tokens[-1]] + else None + for tokens in generated + ], + "reason": reasons, + "days": (hours / 24.0).tolist(), + } + + def estimate_risk( + self, + dataloader: Iterable[dict[str, Any]], + rule: EthosRolloutRule, + num_rollouts: int = 100, + temperature: float = 1.0, + max_new_tokens: int = 8192, + label_key: str | None = None, + seed: int | None = None, + ) -> dict[str, Any]: + """Estimates each sample's risk from sampled timelines. + + The risk is the share of positive rollouts among those ``rule`` keeps. + The paper uses 100 rollouts per sample. + + Args: + dataloader: Batches with ``timeline`` and ``context``. + rule: How rollouts stop and count, such as + :attr:`pyhealth.tasks.EthosOutcomeMEDS.rule`. + num_rollouts: Rollouts per sample. + temperature: Softmax temperature. + max_new_tokens: Limit on generated tokens per rollout. + label_key: A label to return as ``y_true``. + seed: Seed for reproducible rollouts. + + Returns: + A dictionary with ``y_prob`` (``nan`` if every rollout was dropped), + ``num_kept`` (rollouts behind each risk), ``patient_id`` (if the + batches have it) and ``y_true`` (with ``label_key``). + """ + generator = None + if seed is not None: + generator = torch.Generator(device=self.device).manual_seed(seed) + + risks: list[float] = [] + kept_counts: list[int] = [] + patient_ids: list[Any] = [] + labels: list[torch.Tensor] = [] + for batch in dataloader: + time, tokens = batch["timeline"] + age, static = batch["context"] + for i in range(len(tokens)): + result = self.rollout( + (time[i], tokens[i]), + (age[i], static[i]), + rule, + num_rollouts=num_rollouts, + temperature=temperature, + max_new_tokens=max_new_tokens, + generator=generator, + ) + scores = [ + rule.score(actual, reason, days) + for actual, reason, days in zip( + result["actual"], result["reason"], result["days"] + ) + ] + kept = [score for score in scores if score is not None] + risks.append(sum(kept) / len(kept) if kept else math.nan) + kept_counts.append(len(kept)) + patient_ids.extend(batch.get("patient_id", [])) + if label_key is not None: + labels.append(batch[label_key].view(-1).cpu()) + + output: dict[str, Any] = { + "y_prob": torch.tensor(risks, dtype=torch.float32), + "num_kept": torch.tensor(kept_counts, dtype=torch.long), + } + if patient_ids: + output["patient_id"] = patient_ids + if label_key is not None: + output["y_true"] = torch.cat(labels) + return output diff --git a/pyhealth/processors/__init__.py b/pyhealth/processors/__init__.py index c1e99d4a23..d85558897f 100644 --- a/pyhealth/processors/__init__.py +++ b/pyhealth/processors/__init__.py @@ -66,6 +66,7 @@ def get_processor(name: str): from .tuple_time_text_processor import TupleTimeTextProcessor from .cehr_processor import CehrProcessor, ConceptVocab from .ethos_processor import EthosProcessor +from .ethos_context_processor import EthosContextProcessor # Expose public API from .base_processor import ( @@ -108,4 +109,5 @@ def get_processor(name: str): "CehrProcessor", "ConceptVocab", "EthosProcessor", + "EthosContextProcessor", ] diff --git a/pyhealth/processors/ethos_context_processor.py b/pyhealth/processors/ethos_context_processor.py new file mode 100644 index 0000000000..e0bad4fb57 --- /dev/null +++ b/pyhealth/processors/ethos_context_processor.py @@ -0,0 +1,244 @@ +"""Static patient context for ETHOS timelines. + +ETHOS opens every timeline with tokens for the patient's demographics and age. +:class:`~pyhealth.processors.EthosProcessor` keeps those codes out of the +timeline itself; this processor encodes them. + +Paper: + Renc et al. Foundation Model of Electronic Medical Records for Adaptive + Risk Estimation. https://arxiv.org/abs/2502.06124 + +Adapted from ethos-ares (commit 2d54383), ``src/ethos/datasets/base.py`` and +``src/ethos/tokenize/common/basic.py``: +https://github.com/ipolharvard/ethos-ares + +MIT License. Copyright (c) 2024 Paweł Renc. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Sequence +from datetime import datetime +from pathlib import Path +from typing import Any + +import orjson +import torch + +from . import register_processor +from .base_processor import FeatureProcessor +from .cehr_processor import ConceptVocab +from .ethos_processor import STATIC_CODE_PREFIXES + +BIRTH_CODE = "MEDS_BIRTH" +UNKNOWN_SUFFIX = "//UNKNOWN" +DAYS_PER_YEAR = 365.25 + + +def _value_at_start( + rows: list[tuple[datetime | None, str]], + attribute: str, + start: datetime | None, +) -> str: + """Returns the code of one attribute at the start of a timeline. + + An attribute with a single value keeps it whenever it was recorded. With + several values, the latest one recorded by ``start`` applies, as ETHOS does. + + Args: + rows: ``(time, code)`` rows of this attribute in time order. A row + without a time counts as known from the beginning. + attribute: The attribute's prefix. + start: Start of the timeline. + + Returns: + The code, or ``//UNKNOWN`` if nothing applies yet. + """ + if len(rows) == 1: + return rows[0][1] + known = [ + code for time, code in rows if time is None or start is None or time <= start + ] + return known[-1] if known else attribute + UNKNOWN_SUFFIX + + +@register_processor("ethos_context") +class EthosContextProcessor(FeatureProcessor): + """Encodes the static context that opens an ETHOS timeline. + + The input is one patient's static rows: + + * ``time``: a timestamp or ``None`` per row. + * ``code``: a string per row, such as ``GENDER//F`` or ``MEDS_BIRTH``. + * ``start``: when the timeline starts. + + The output has a fixed length. Attributes are sorted by name, so with the + default prefixes it reads ``GENDER``, ``MARITAL``, the two age tokens, + ``RACE``. A patient with no value gets ``//UNKNOWN``, and a value + unseen in :meth:`fit` gets ````. The age tokens hold ```` here: + their quantile tokens belong to the timeline vocabulary and depend on where + a window of the timeline starts, so :class:`~pyhealth.models.ETHOS` fills + them in from the returned age. + + Args: + prefixes: Static code prefixes, including ``MEDS_BIRTH``. Use the same + ones as ``exclude_prefixes`` of + :class:`~pyhealth.processors.EthosProcessor`. + + Raises: + ValueError: If ``prefixes`` leaves out ``MEDS_BIRTH``. + + Examples: + >>> from datetime import datetime + >>> from pyhealth.processors import EthosContextProcessor + >>> static = { + ... "time": [datetime(1980, 1, 1), None], + ... "code": ["MEDS_BIRTH", "GENDER//F"], + ... "start": datetime(2024, 1, 1), + ... } + >>> processor = EthosContextProcessor() + >>> processor.fit([{"context": static}], "context") + >>> age, tokens = processor.process(static) + >>> round(age.item(), 1) + 44.0 + >>> processor.decode(tokens) + ['GENDER//F', 'MARITAL//UNKNOWN', '', '', 'RACE//UNKNOWN'] + """ + + stores_tensor = True + + def __init__(self, prefixes: Sequence[str] = STATIC_CODE_PREFIXES) -> None: + if BIRTH_CODE not in prefixes: + raise ValueError(f"prefixes must include {BIRTH_CODE}, got {prefixes}.") + self.prefixes = tuple(sorted(prefixes)) + self.vocab: ConceptVocab | None = None + + @property + def age_position(self) -> int: + """Index of the first of the two age tokens in the output.""" + return self.prefixes.index(BIRTH_CODE) + + @property + def context_size(self) -> int: + """Length of the output: one per attribute, and two for age.""" + return len(self.prefixes) + 1 + + def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: + """Learns the vocabulary of attribute values. + + Args: + samples: Sample dictionaries. + field: Key of the static rows in each sample. + """ + self.vocab = ConceptVocab() + for prefix in self.prefixes: + if prefix != BIRTH_CODE: + self.vocab.add_token(prefix + UNKNOWN_SUFFIX) + for sample in samples: + for code in sorted(sample[field]["code"]): + if code.startswith(self.prefixes) and code != BIRTH_CODE: + self.vocab.add_token(code) + + def process(self, value: dict[str, Any]) -> tuple[torch.Tensor, torch.Tensor]: + """Encodes one patient's static rows. + + Args: + value: Static rows, as in the class docstring. + + Returns: + ``(age, tokens)``. ``age`` has one ``float64`` element, the age in + years at ``start``, or ``nan`` without a usable birth date. + ``tokens`` is ``long`` and has :attr:`context_size` elements. + + Raises: + RuntimeError: If called before :meth:`fit` or :meth:`load`. + """ + if self.vocab is None: + raise RuntimeError("EthosContextProcessor must be fitted or loaded first.") + + start = value["start"] + pairs = list(zip(value["time"], value["code"])) + rows = [row for row in pairs if row[0] is None] + rows += sorted((row for row in pairs if row[0] is not None), key=lambda r: r[0]) + tokens: list[int] = [] + age = float("nan") + for prefix in self.prefixes: + matching = [row for row in rows if row[1].startswith(prefix)] + if prefix == BIRTH_CODE: + if matching and matching[0][0] is not None and start is not None: + age = (start - matching[0][0]).days / DAYS_PER_YEAR + tokens += [self.vocab.pad_id, self.vocab.pad_id] + elif matching: + tokens.append(self.vocab[_value_at_start(matching, prefix, start)]) + else: + tokens.append(self.vocab[prefix + UNKNOWN_SUFFIX]) + return ( + torch.tensor([age], dtype=torch.float64), + torch.tensor(tokens, dtype=torch.long), + ) + + def decode(self, tokens: torch.Tensor | Iterable[int]) -> list[str]: + """Maps token ids back to token strings. + + Args: + tokens: Token ids, such as the output of :meth:`process`. + + Returns: + The token strings. + + Examples: + >>> from pyhealth.processors import EthosContextProcessor + >>> processor = EthosContextProcessor() + >>> processor.fit([], "context") + >>> processor.decode([0, 1]) + ['', ''] + """ + by_id = {index: token for token, index in self.vocab.token_to_id.items()} + return [by_id[int(token)] for token in tokens] + + def save(self, path: str) -> None: + """Saves the configuration and fitted state as JSON. + + Args: + path: File to write. + """ + state = { + "prefixes": self.prefixes, + "vocab": None if self.vocab is None else self.vocab.to_json(), + } + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_bytes(orjson.dumps(state, option=orjson.OPT_SORT_KEYS)) + + def load(self, path: str) -> None: + """Restores what :meth:`save` wrote, replacing the current state. + + Args: + path: File to read. + """ + state = orjson.loads(Path(path).read_bytes()) + self.prefixes = tuple(state["prefixes"]) + vocab = state["vocab"] + self.vocab = None if vocab is None else ConceptVocab.from_json(vocab) + + def size(self) -> int: + """Returns the vocabulary size.""" + return 0 if self.vocab is None else self.vocab.vocab_size + + def is_token(self) -> bool: + """Output tokens are discrete indices.""" + return True + + def schema(self) -> tuple[str, ...]: + return ("age", "value") + + def dim(self) -> tuple[int, ...]: + return (1, 1) + + def spatial(self) -> tuple[bool, ...]: + return (False,) + + def __repr__(self) -> str: + return ( + f"EthosContextProcessor(prefixes={self.prefixes}, " + f"vocab_size={self.size()})" + ) diff --git a/pyhealth/processors/ethos_processor.py b/pyhealth/processors/ethos_processor.py index ae84ae4078..7501b78f3d 100644 --- a/pyhealth/processors/ethos_processor.py +++ b/pyhealth/processors/ethos_processor.py @@ -186,6 +186,12 @@ class EthosProcessor(FeatureProcessor): An unseen code becomes ```` with no quantile token. All quantile and interval tokens are in the vocabulary, whether or not training saw them. + :meth:`fit` also learns ``interval_estimates``: each interval token's mean + duration in hours, as ETHOS's ``IntervalEstimator`` does, so that a + generated timeline can be converted back to elapsed time. Repeats of + ``=6mt`` split their gap evenly. A token that training never saw falls + back to its lower bound. + Args: num_quantiles: Number of bins per code. ETHOS uses 10. quantize_prefixes: Quantize only codes with one of these prefixes. By @@ -233,6 +239,7 @@ def __init__( self.add_timeline_end = add_timeline_end self.vocab: ConceptVocab | None = None self.quantiles: dict[str, list[float]] = {} + self.interval_estimates: dict[str, float] = {} def _read( self, timeline: dict[str, Any] | None @@ -291,9 +298,16 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: """ observed: dict[str, list[float]] = defaultdict(list) codes: set[str] = set() + spans: dict[str, float] = defaultdict(float) + counts: dict[str, int] = defaultdict(int) for sample in samples: - _, sample_codes, values = self._read(sample.get(field)) + stamps, sample_codes, values = self._read(sample.get(field)) codes.update(sample_codes) + for gap in np.diff(stamps).tolist(): + labels = _interval_tokens(gap) + for label in labels: + spans[label] += gap / len(labels) + counts[label] += 1 for code, value in zip(sample_codes, values.tolist()): if math.isnan(value): continue @@ -306,6 +320,11 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: code: _quantile_breaks(values, self.num_quantiles) for code, values in observed.items() } + self.interval_estimates = { + label: (spans[label] / counts[label] if counts[label] else bound) + / _MICROSECONDS_PER_HOUR + for label, bound in zip(_INTERVAL_LABELS, _INTERVAL_BOUNDS) + } self.vocab = ConceptVocab() for k in range(1, self.num_quantiles + 1): self.vocab.add_token(f"Q{k}") @@ -393,6 +412,7 @@ def save(self, path: str) -> None: "add_timeline_end": self.add_timeline_end, "vocab": None if self.vocab is None else self.vocab.to_json(), "quantiles": self.quantiles, + "interval_estimates": self.interval_estimates, } Path(path).parent.mkdir(parents=True, exist_ok=True) Path(path).write_bytes(orjson.dumps(state, option=orjson.OPT_SORT_KEYS)) @@ -412,6 +432,7 @@ def load(self, path: str) -> None: vocab = state["vocab"] self.vocab = None if vocab is None else ConceptVocab.from_json(vocab) self.quantiles = state["quantiles"] + self.interval_estimates = state["interval_estimates"] def size(self) -> int: """Returns the vocabulary size.""" diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 2413545f8e..16f91f2a9f 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -57,6 +57,11 @@ ICUAdmissionMEDS as ICUAdmissionMEDS, ProlongedLengthOfStayMEDS as ProlongedLengthOfStayMEDS, ) +from .ethos_tasks import ( + EthosOutcomeMEDS as EthosOutcomeMEDS, + EthosRolloutRule as EthosRolloutRule, + EthosTimelineMEDS as EthosTimelineMEDS, +) from .medical_transcriptions_classification import MedicalTranscriptionsClassification from .mortality_prediction import ( MortalityPredictionEICU, diff --git a/pyhealth/tasks/ethos_tasks.py b/pyhealth/tasks/ethos_tasks.py new file mode 100644 index 0000000000..92a77951d4 --- /dev/null +++ b/pyhealth/tasks/ethos_tasks.py @@ -0,0 +1,326 @@ +"""MEDS timelines for the ETHOS generative model, and its zero-shot outcomes. + +ETHOS is trained without labels, on whole patient timelines, and then predicts +an outcome by sampling future timelines from the prediction time: + +* :class:`EthosTimelineMEDS` gives the training timelines. +* :class:`EthosOutcomeMEDS` runs an outcome task from + :mod:`~pyhealth.tasks.meds_outcome_tasks`, keeps its cohort and labels, and + swaps its code list for the same rows in the form ETHOS tokenizes, cut at the + same prediction time. +* :class:`EthosRolloutRule` says when a sampled timeline stops and how it counts + toward the risk. ``EthosOutcomeMEDS`` builds the matching one. + +Rollout rules follow the ETHOS-ARES code that produced the paper's Table S1 +(``src/ethos/datasets/{mimic_icu,readmission,hospital_mortality}.py`` and +``notebooks/{figures,hosp_readmission}.ipynb``, commit 2d54383). MIT License. +Copyright (c) 2024 Paweł Renc. + +References: + Renc P., Grzeszczyk M. K., Oufattole N., et al. Foundation Model of + Electronic Medical Records for Adaptive Risk Estimation. arXiv:2502.06124. + https://arxiv.org/abs/2502.06124 + + Source code: https://github.com/ipolharvard/ethos-ares +""" + +from dataclasses import dataclass +from typing import Any, ClassVar + +import polars as pl + +from ..processors.ethos_processor import ( + DEATH_CODE, + STATIC_CODE_PREFIXES, + TIMELINE_END_TOKEN, +) +from .base_task import BaseTask +from .in_hospital_mortality_meds import ADMISSION_PREFIX, DIED_CODE, DISCHARGE_PREFIX +from .meds_outcome_tasks import ( + ICU_ADMISSION_PREFIX, + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, + _completed_stays, + _load_events, + _rows_at_admission, + _rows_at_discharge, +) + +#: Why a rollout stopped. The first three are ETHOS's. +STOP_TOKEN = "token_of_interest" +TIME_LIMIT = "time_limit" +INVALID_TOKEN = "key_error" +TOKEN_LIMIT = "token_limit" + +#: ETHOS's default limit on simulated time. +DEFAULT_TIME_LIMIT_DAYS = 365.25 * 2 + + +@dataclass(frozen=True) +class EthosRolloutRule: + """When a sampled timeline stops, and how it counts toward a risk. + + The risk of a sample is the share of positive rollouts among those not + dropped, as in ETHOS's ``preprocess_inference_results``. Rollouts stopped by + an invalid token or by ``max_new_tokens`` are always dropped. + + Args: + stop_prefixes: Code prefixes that end a rollout. + positive_prefixes: A rollout stopped by one of these is positive. + time_limit_days: Simulated time at which a rollout gives up. + min_days: A rollout stopped at least this long after the prediction + time is positive, whatever stopped it. + drop_prefixes: Rollouts stopped by one of these are dropped. + keep_time_limited: Count rollouts that reach the time limit as + negative. By default they are dropped. + + Examples: + >>> from pyhealth.tasks import EthosRolloutRule + >>> rule = EthosRolloutRule( + ... stop_prefixes=("HOSPITAL_DISCHARGE", "MEDS_DEATH", "TIMELINE_END"), + ... positive_prefixes=("HOSPITAL_DISCHARGE//DIED", "MEDS_DEATH"), + ... drop_prefixes=("TIMELINE_END",), + ... ) + >>> rule.score("MEDS_DEATH", "token_of_interest", days=3.0) + True + >>> rule.score("HOSPITAL_DISCHARGE//HOME", "token_of_interest", days=3.0) + False + >>> rule.score("TIMELINE_END", "token_of_interest", days=3.0) is None + True + """ + + stop_prefixes: tuple[str, ...] + positive_prefixes: tuple[str, ...] = () + time_limit_days: float = DEFAULT_TIME_LIMIT_DAYS + min_days: float | None = None + drop_prefixes: tuple[str, ...] = () + keep_time_limited: bool = False + + def score(self, code: str | None, reason: str, days: float) -> bool | None: + """Scores one rollout. + + Args: + code: The last generated token. + reason: Why the rollout stopped. + days: Simulated days since the prediction time. + + Returns: + Whether the rollout is positive, or ``None`` if it is dropped. + """ + if reason == TIME_LIMIT: + return False if self.keep_time_limited else None + if reason != STOP_TOKEN or code.startswith(self.drop_prefixes): + return None + if code.startswith(self.positive_prefixes): + return True + return self.min_days is not None and days >= self.min_days + + +def _rollout_rule(task: BaseTask) -> EthosRolloutRule: + """Returns the rollout rule that matches an outcome task's label. + + Args: + task: An outcome task from :mod:`.meds_outcome_tasks`. + + Returns: + The rule, using the task's ``death_as_positive``, ``window_days`` or + ``threshold_days``. + """ + if isinstance(task, ICUAdmissionMEDS): + deaths = (DEATH_CODE, DIED_CODE) if task.death_as_positive else () + return EthosRolloutRule( + stop_prefixes=( + ICU_ADMISSION_PREFIX, + DISCHARGE_PREFIX, + DEATH_CODE, + TIMELINE_END_TOKEN, + ), + positive_prefixes=(ICU_ADMISSION_PREFIX, *deaths), + drop_prefixes=(TIMELINE_END_TOKEN,), + ) + if isinstance(task, HospitalReadmissionMEDS): + return EthosRolloutRule( + stop_prefixes=(ADMISSION_PREFIX, DEATH_CODE, TIMELINE_END_TOKEN), + positive_prefixes=(ADMISSION_PREFIX, DEATH_CODE), + time_limit_days=task.window_days, + keep_time_limited=True, + ) + return EthosRolloutRule( + stop_prefixes=(DISCHARGE_PREFIX, DEATH_CODE, TIMELINE_END_TOKEN), + min_days=task.threshold_days, + drop_prefixes=(TIMELINE_END_TOKEN,), + ) + + +def _timeline_fields( + rows: pl.DataFrame, + prefixes: tuple[str, ...] = STATIC_CODE_PREFIXES, +) -> dict[str, dict[str, Any]] | None: + """Splits MEDS rows into the ``timeline`` and ``context`` sample fields. + + Args: + rows: MEDS events, with ``timestamp``, ``meds/code`` and + ``meds/numeric_value``. + prefixes: Static code prefixes. + + Returns: + The two fields, or ``None`` if no row is left for the timeline. + """ + code = pl.col("meds/code") + is_static = code.str.starts_with(prefixes[0]) + for prefix in prefixes[1:]: + is_static = is_static | code.str.starts_with(prefix) + static = rows.filter(is_static) + timeline = rows.filter(~is_static & pl.col("timestamp").is_not_null()) + if timeline.height == 0: + return None + return { + "timeline": { + "time": timeline["timestamp"].to_list(), + "code": timeline["meds/code"].to_list(), + "numeric_value": timeline["meds/numeric_value"].to_list(), + }, + "context": { + "time": static["timestamp"].to_list(), + "code": static["meds/code"].to_list(), + "start": timeline["timestamp"].min(), + }, + } + + +class EthosTimelineMEDS(BaseTask): + """One whole MEDS timeline per patient, for training ETHOS. + + There is no label: :class:`~pyhealth.models.ETHOS` learns to predict the + next token. Fit on the training patients only, with + ``set_task(EthosTimelineMEDS(), split=PatientSplit(...))``. + + Attributes: + task_name (str): The name of the task. + input_schema (Dict[str, str]): ``timeline``, the tokenized events, and + ``context``, the static patient context. + output_schema (Dict[str, str]): Empty. + + Examples: + >>> from pyhealth.datasets import MEDSDataset, PatientSplit + >>> from pyhealth.tasks import EthosTimelineMEDS + >>> dataset = MEDSDataset(root="/path/to/meds") # doctest: +SKIP + >>> train, test = dataset.set_task( # doctest: +SKIP + ... EthosTimelineMEDS(), split=PatientSplit(ratios=(0.9, 0.1), seed=0) + ... ) + """ + + task_name: str = "EthosTimelineMEDS" + input_schema: ClassVar[dict[str, str]] = { + "timeline": "ethos", + "context": "ethos_context", + } + output_schema: ClassVar[dict[str, str]] = {} + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + fields = _timeline_fields(patient.get_events(event_type="meds", return_df=True)) + if fields is None: + return [] + return [{"patient_id": patient.patient_id, **fields}] + + +class EthosOutcomeMEDS(BaseTask): + """An outcome task's cohort and labels, as ETHOS timelines. + + Runs ``outcome_task(**options)`` and replaces each sample's ``codes`` with + the same rows, so that the cohort, the label and every leakage exclusion + stay the outcome task's own. The timeline ends at the prediction time, and + :attr:`rule` says how rollouts from there become a risk: + + * :class:`~pyhealth.tasks.ICUAdmissionMEDS`, at admission: stop at ICU + admission, discharge, death or the end of the timeline. An ICU admission + is positive, and so is a death if ``death_as_positive`` is on, including + a discharge coded ``HOSPITAL_DISCHARGE//DIED``. ETHOS's Table S1 uses the + ICU-only label, ``death_as_positive=False``. The two-year time limit and + ``TIMELINE_END`` drop a rollout. + * :class:`~pyhealth.tasks.ProlongedLengthOfStayMEDS`, at admission: stop at + discharge, death or the end of the timeline. A rollout is positive if it + stops at least ``threshold_days`` after admission, inclusive. The + two-year time limit and ``TIMELINE_END`` drop a rollout. + * :class:`~pyhealth.tasks.HospitalReadmissionMEDS`, at discharge: stop at + admission, death or the end of the timeline. An admission or a death is + positive. A rollout that passes ``window_days``, or reaches + ``TIMELINE_END``, is negative. ``require_full_followup`` only changes the + cohort, not the rollout. + + Pass the fitted processors of :class:`EthosTimelineMEDS` as + ``input_processors``, so that both tasks share one vocabulary. + + Args: + outcome_task (type[BaseTask]): One of the three task classes above. + **options: Keyword arguments for ``outcome_task``. + + Attributes: + task_name (str): ``Ethos`` and the outcome task's name. + input_schema (Dict[str, str]): Same as :class:`EthosTimelineMEDS`. + output_schema (Dict[str, str]): The outcome task's. + rule (EthosRolloutRule): How rollouts become a risk. + + Raises: + ValueError: If ``outcome_task`` is not one of the three. + + Examples: + >>> from pyhealth.tasks import EthosOutcomeMEDS, ICUAdmissionMEDS + >>> task = EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False) + >>> task.task_name + 'EthosICUAdmissionMEDS' + >>> task.output_schema + {'icu_admission': 'binary'} + >>> task.rule.positive_prefixes + ('ICU_ADMISSION',) + """ + + input_schema: ClassVar[dict[str, str]] = EthosTimelineMEDS.input_schema + + def __init__(self, outcome_task: type[BaseTask], **options: Any) -> None: + if outcome_task not in ( + ICUAdmissionMEDS, + HospitalReadmissionMEDS, + ProlongedLengthOfStayMEDS, + ): + raise ValueError( + "outcome_task must be ICUAdmissionMEDS, HospitalReadmissionMEDS " + f"or ProlongedLengthOfStayMEDS, got {outcome_task}." + ) + super().__init__() + # The class and options rather than an instance: dataset caches hash + # this object's attributes, and an instance's text form changes per run. + self.outcome_task = outcome_task + self.options = options + self.task_name = f"Ethos{outcome_task.task_name}" + self.output_schema = dict(outcome_task.output_schema) + self.rule = _rollout_rule(outcome_task(**options)) + + def pre_filter(self, df: pl.LazyFrame) -> pl.LazyFrame: + """Restricts the global scan to MEDS events.""" + return df.filter(pl.col("event_type") == "meds") + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + outcomes = self.outcome_task(**self.options)(patient) + if not outcomes: + return [] + + events = _load_events(patient) + stays = {stay["hadm_id"]: stay for stay in _completed_stays(events)} + cut = ( + _rows_at_discharge + if self.outcome_task is HospitalReadmissionMEDS + else _rows_at_admission + ) + samples = [] + for outcome in outcomes: + fields = _timeline_fields(cut(events, stays[outcome["hadm_id"]])) + if fields is not None: + kept = {key: val for key, val in outcome.items() if key != "codes"} + samples.append({**kept, **fields}) + return samples diff --git a/pyhealth/tasks/meds_outcome_tasks.py b/pyhealth/tasks/meds_outcome_tasks.py index 3e763198b9..62ef146985 100644 --- a/pyhealth/tasks/meds_outcome_tasks.py +++ b/pyhealth/tasks/meds_outcome_tasks.py @@ -172,15 +172,15 @@ def _is_this_stay(hadm_id: int) -> pl.Expr: return (pl.col("_hadm") == hadm_id).fill_null(False) -def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: - """Returns the input of an admission-time prediction. +def _rows_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> pl.DataFrame: + """Returns the input rows of an admission-time prediction. Args: events (pl.DataFrame): Output of :func:`_load_events`. stay (dict[str, Any]): A record from :func:`_completed_stays`. Returns: - list[str]: Static codes, history before admission, then the admission + pl.DataFrame: Static rows, history before admission, then the admission event itself. See the module docstring for the exclusions. """ code = pl.col("meds/code") @@ -196,28 +196,34 @@ def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str] ) history = (time < stay["admit"]) & ~this_stay_icu & ~this_stay_dated window = time.is_null() | history - return events.filter((window | admission_event) & (code != DEATH_CODE))[ - "meds/code" - ].to_list() + return events.filter((window | admission_event) & (code != DEATH_CODE)) -def _codes_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: - """Returns the input of a discharge-time prediction. +def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the codes of :func:`_rows_at_admission`.""" + return _rows_at_admission(events, stay)["meds/code"].to_list() + + +def _rows_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> pl.DataFrame: + """Returns the input rows of a discharge-time prediction. Args: events (pl.DataFrame): Output of :func:`_load_events`. stay (dict[str, Any]): A record from :func:`_completed_stays`. Returns: - list[str]: Static codes, everything before discharge, then the events + pl.DataFrame: Static rows, everything before discharge, then the events of this stay stamped at discharge. """ time = pl.col("timestamp") at_discharge = (time == stay["discharge"]) & _is_this_stay(stay["hadm_id"]) window = time.is_null() | (time < stay["discharge"]) | at_discharge - return events.filter(window & (pl.col("meds/code") != DEATH_CODE))[ - "meds/code" - ].to_list() + return events.filter(window & (pl.col("meds/code") != DEATH_CODE)) + + +def _codes_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the codes of :func:`_rows_at_discharge`.""" + return _rows_at_discharge(events, stay)["meds/code"].to_list() def _next_outcome_time( diff --git a/tests/core/test_ethos.py b/tests/core/test_ethos.py new file mode 100644 index 0000000000..7929a8be62 --- /dev/null +++ b/tests/core/test_ethos.py @@ -0,0 +1,451 @@ +"""Tests for the ETHOS model. Tiny models on synthetic timelines only.""" + +import inspect +import math +import tempfile +import unittest +from datetime import datetime, timedelta +from pathlib import Path + +import torch +import torch.nn.functional as F + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import ETHOS +from pyhealth.models.ethos import _age_quantiles +from pyhealth.tasks import EthosRolloutRule +from pyhealth.trainer import Trainer + +START = datetime.fromisoformat("2024-01-01") +BIRTH = datetime.fromisoformat("1980-01-01") +ADMIT = "HOSPITAL_ADMISSION//ER" +HOME = "HOSPITAL_DISCHARGE//HOME" +DEATH = "MEDS_DEATH" +LAB = "LAB//A" +RULE = EthosRolloutRule( + stop_prefixes=(HOME, DEATH, "TIMELINE_END"), + positive_prefixes=(DEATH,), + time_limit_days=1.0, +) + + +def sample(index, rows): + """Rows are ``(hours, code, value)``.""" + return { + "patient_id": f"p{index}", + "timeline": { + "time": [START + timedelta(hours=r[0]) for r in rows], + "code": [r[1] for r in rows], + "numeric_value": [r[2] for r in rows], + }, + "context": { + "time": [BIRTH, None], + "code": ["MEDS_BIRTH", "GENDER//F" if index % 2 else "GENDER//M"], + "start": START, + }, + } + + +def tiny_dataset(extra=()): + samples = [ + sample( + i, + [ + (0.0, ADMIT, None), + (1.0, LAB, 1.0 + i), + (30.0, HOME if i else DEATH, None), + ], + ) + for i in range(3) + ] + samples.extend(extra) + return create_sample_dataset( + samples, + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={}, + ) + + +def tiny_model(dataset, **kwargs): + options = {"n_layer": 1, "n_head": 2, "n_embd": 8, "n_positions": 32, "dropout": 0.0} + return ETHOS(dataset, **{**options, **kwargs}) + + +def batch_of(dataset, size=3): + return next(iter(get_dataloader(dataset, batch_size=size))) + + +def script(model, *tokens): + """Makes the model sample these tokens in turn, then keep to the last.""" + ids = [model.timeline_processor.vocab[token] for token in tokens] + steps = iter(ids) + + def logits(prompt): + token = next(steps, ids[-1]) + forced = F.one_hot(torch.tensor(token), model.vocab_size).float() * 1e4 + return forced.expand(*prompt.shape, -1) + + model._logits = logits + + +def one_sample(batch): + time, tokens = batch["timeline"] + age, static = batch["context"] + return (time[0], tokens[0]), (age[0], static[0]) + + +class TestArchitecture(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def test_defaults_are_the_papers_final_model(self): + parameters = inspect.signature(ETHOS).parameters + defaults = { + name: parameters[name].default + for name in ("n_layer", "n_head", "n_embd", "n_positions", "dropout") + } + self.assertEqual( + defaults, + { + "n_layer": 6, + "n_head": 12, + "n_embd": 768, + "n_positions": 2048, + "dropout": 0.3, + }, + ) + + def test_vocabulary_is_a_multiple_of_64(self): + model = self.model + self.assertEqual(model.vocab_size % 64, 0) + self.assertGreaterEqual( + model.vocab_size, + model.timeline_processor.size() + model.context_processor.size(), + ) + + def test_weights_are_tied_and_have_no_bias(self): + self.assertIs(self.model.transformer["wte"].weight, self.model.lm_head.weight) + self.assertFalse([n for n, _ in self.model.named_parameters() if "bias" in n]) + + def test_forward_pass(self): + output = self.model(**self.batch) + self.assertTrue(torch.isfinite(output["loss"])) + logits, labels = output["logit"], output["y_true"] + self.assertEqual(logits.shape[:2], labels.shape) + self.assertEqual(logits.size(-1), self.model.vocab_size) + self.assertIsNone(self.model.mode) + + def test_labels_shift_and_skip_the_context_and_padding(self): + labels = self.model(**self.batch)["y_true"] + tokens = self.batch["timeline"][1] + size = self.model.context_size + self.assertTrue((labels[:, :size] == -100).all()) + self.assertTrue(torch.equal(labels[:, size:], tokens[:, 1:])) + + short = sample(9, [(0.0, ADMIT, None)]) + dataset = tiny_dataset(extra=[short]) + batch = batch_of(dataset, size=4) + model = tiny_model(dataset) + labels = model(**batch)["y_true"] + self.assertTrue((labels[3, size + 2 :] == -100).all()) + + def test_gradients_reach_every_parameter(self): + self.model(**self.batch)["loss"].backward() + for name, parameter in self.model.named_parameters(): + if name != "_dummy_param": + self.assertIsNotNone(parameter.grad, name) + self.assertGreater(parameter.grad.abs().sum().item(), 0, name) + + def test_attention_is_causal(self): + ids = torch.randint(2, 10, (1, 8)) + changed = ids.clone() + changed[0, -1] = 11 + self.model.eval() + before, after = self.model._logits(ids), self.model._logits(changed) + self.assertTrue(torch.allclose(before[0, :-1], after[0, :-1])) + self.assertFalse(torch.allclose(before[0, -1], after[0, -1])) + + def test_batch_without_any_target_has_zero_loss(self): + time, tokens = self.batch["timeline"] + empty = { + "timeline": (time[:, :0], tokens[:, :0]), + "context": self.batch["context"], + } + loss = self.model(**empty)["loss"] + self.assertEqual(loss.item(), 0.0) + loss.backward() + + def test_rejects_datasets_without_ethos_fields(self): + dataset = create_sample_dataset( + [{"patient_id": "p", "codes": ["a"]}], + input_schema={"codes": "sequence"}, + output_schema={}, + ) + with self.assertRaises(ValueError): + tiny_model(dataset) + + def test_rejects_sizes_that_do_not_fit(self): + with self.assertRaises(ValueError): + tiny_model(self.dataset, n_head=3) + with self.assertRaises(ValueError): + tiny_model(self.dataset, n_positions=5) + + +class TestContext(unittest.TestCase): + def test_age_digits(self): + age = torch.tensor([46.0, 0.0, 99.0, 150.0, -3.0, 45.97, math.nan]) + high, low = _age_quantiles(age, 10) + self.assertEqual(high.tolist(), [4, 0, 9, 9, 0, 4, -1]) + self.assertEqual(low.tolist(), [6, 0, 9, 9, 0, 6, -1]) + + def test_age_digits_carry(self): + high, low = _age_quantiles(torch.tensor([49.7]), 10) + self.assertEqual((high.item(), low.item()), (5, 0)) + + def test_context_ids(self): + dataset = tiny_dataset() + model = tiny_model(dataset) + batch = batch_of(dataset) + _, static = batch["context"] + ids = model._context_ids(static, torch.tensor([46.0, 46.0, math.nan])) + vocab = model.timeline_processor.vocab + position = model.context_processor.age_position + self.assertEqual(ids[0, position].item(), vocab["Q5"]) + self.assertEqual(ids[0, position + 1].item(), vocab["Q7"]) + self.assertEqual(ids[2, position].item(), vocab.unk_id) + others = ids[0, : position] + self.assertTrue((others >= model.timeline_vocab_size).all()) + + def test_long_timeline_uses_a_window_and_the_age_where_it_starts(self): + rows = [(float(i * 24 * 365), LAB, None) for i in range(40)] + dataset = tiny_dataset(extra=[sample(5, rows)]) + model = tiny_model(dataset) + batch = batch_of(dataset, size=4) + model.eval() + window = model.timeline_size + output = model(**batch) + self.assertEqual(output["logit"].size(1), model.n_positions) + + captured = {} + original = model._context_ids + + def spy(static, age): + captured["age"] = age + return original(static, age) + + model._context_ids = spy + model(**batch) + time, tokens = batch["timeline"] + start = (tokens[3] != 0).sum() - (window + 1) + self.assertGreater(start.item(), 0) + expected = (START - BIRTH).days / 365.25 + expected += time[3, start].item() / (24 * 365.25) + self.assertAlmostEqual(captured["age"][3].item(), expected, places=3) + + def test_training_windows_are_random_and_stay_in_the_timeline(self): + rows = [(float(i), LAB, 1.0) for i in range(60)] + dataset = tiny_dataset(extra=[sample(5, rows)]) + model = tiny_model(dataset) + batch = batch_of(dataset, size=4) + model.train() + ages = set() + original = model._context_ids + + def spy(static, age): + ages.add(round(age[3].item(), 6)) + return original(static, age) + + model._context_ids = spy + for _ in range(8): + self.assertTrue(torch.isfinite(model(**batch)["loss"])) + self.assertGreater(len(ages), 1) + + +class TestRollout(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def rollout(self, **kwargs): + options = {"num_rollouts": 2, "max_new_tokens": 6, **kwargs} + return self.model.rollout(*one_sample(self.batch), RULE, **options) + + def test_seeded_rollout_is_reproducible(self): + def run(seed): + generator = torch.Generator().manual_seed(seed) + return self.rollout(generator=generator, num_rollouts=8) + + first, second, other = run(1), run(1), run(2) + self.assertEqual(first, second) + self.assertNotEqual(first["tokens"], other["tokens"]) + + def test_stops_on_a_stop_token(self): + script(self.model, LAB, DEATH) + result = self.rollout() + self.assertEqual(result["reason"], ["token_of_interest"] * 2) + self.assertEqual(result["actual"], [DEATH] * 2) + self.assertEqual(len(result["tokens"][0]), 2) + + def test_interval_tokens_advance_the_clock_up_to_the_limit(self): + script(self.model, "12h-18h") + hours = self.model.timeline_processor.interval_estimates["12h-18h"] + result = self.rollout(max_new_tokens=8) + self.assertEqual(result["reason"], ["time_limit"] * 2) + steps = len(result["tokens"][0]) + self.assertEqual(steps, math.floor(24.0 / hours) + 1) + self.assertAlmostEqual(result["days"][0], steps * hours / 24.0) + + def test_tokens_that_are_not_timeline_tokens_are_invalid(self): + self.model._logits = lambda ids: ( + F.one_hot( + torch.tensor(self.model.vocab_size - 1), self.model.vocab_size + ).float() + * 1e4 + ).expand(*ids.shape, -1) + result = self.rollout() + self.assertEqual(result["reason"], ["key_error"] * 2) + self.assertEqual(result["actual"], [None] * 2) + + def test_gives_up_after_max_new_tokens(self): + script(self.model, LAB) + result = self.rollout(max_new_tokens=3) + self.assertEqual(result["reason"], ["token_limit"] * 2) + self.assertEqual(len(result["tokens"][0]), 3) + + def test_rollouts_stop_separately(self): + vocab = self.model.timeline_processor.vocab + calls = iter([[LAB, DEATH], [HOME]]) + + def logits(ids): + tokens = next(calls) + forced = torch.zeros(len(tokens), 1, self.model.vocab_size) + for row, token in enumerate(tokens): + forced[row, 0, vocab[token]] = 1e4 + return forced + + self.model._logits = logits + result = self.rollout() + self.assertEqual(result["actual"], [HOME, DEATH]) + self.assertEqual([len(t) for t in result["tokens"]], [2, 1]) + + def test_a_full_context_slides_and_keeps_the_static_tokens(self): + seen = [] + + def logits(ids): + seen.append(ids.clone()) + forced = torch.zeros(*ids.shape, self.model.vocab_size) + forced[..., self.model.timeline_processor.vocab[LAB]] = 1e4 + return forced + + self.model._logits = logits + self.rollout(max_new_tokens=40, num_rollouts=1) + size = self.model.context_size + self.assertEqual(max(ids.size(1) for ids in seen), self.model.n_positions) + self.assertTrue(torch.equal(seen[-1][:, :size], seen[0][:, :size])) + + def test_prompt_leaves_out_timeline_end(self): + (time, tokens), (age, static) = one_sample(self.batch) + vocab = self.model.timeline_processor.vocab + self.assertEqual(tokens[tokens != 0][-1].item(), vocab["TIMELINE_END"]) + prompt = self.model._prompt(time, tokens, age, static) + self.assertNotEqual(prompt[0, -1].item(), vocab["TIMELINE_END"]) + + def test_restores_training_mode(self): + self.model.train() + self.rollout() + self.assertTrue(self.model.training) + + +class TestEstimateRisk(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.dataset = tiny_dataset() + cls.batch = batch_of(cls.dataset) + + def setUp(self): + torch.manual_seed(0) + self.model = tiny_model(self.dataset) + + def test_all_positive(self): + script(self.model, DEATH) + risk = self.model.estimate_risk([self.batch], RULE, num_rollouts=2) + self.assertEqual(risk["y_prob"].tolist(), [1.0, 1.0, 1.0]) + self.assertEqual(risk["num_kept"].tolist(), [2, 2, 2]) + self.assertEqual(sorted(risk["patient_id"]), ["p0", "p1", "p2"]) + + def test_all_negative(self): + script(self.model, HOME) + risk = self.model.estimate_risk([self.batch], RULE, num_rollouts=2) + self.assertEqual(risk["y_prob"].tolist(), [0.0, 0.0, 0.0]) + + def test_all_dropped_is_nan(self): + script(self.model, LAB) + risk = self.model.estimate_risk( + [self.batch], RULE, num_rollouts=2, max_new_tokens=2 + ) + self.assertTrue(risk["y_prob"].isnan().all()) + self.assertEqual(risk["num_kept"].tolist(), [0, 0, 0]) + + def test_seed_makes_it_reproducible(self): + options = {"num_rollouts": 4, "max_new_tokens": 8, "seed": 3} + first = self.model.estimate_risk([self.batch], RULE, **options) + second = self.model.estimate_risk([self.batch], RULE, **options) + self.assertTrue(first["y_prob"].nan_to_num(-1).equal(second["y_prob"].nan_to_num(-1))) + + def test_label_key(self): + script(self.model, DEATH) + batch = {**self.batch, "outcome": torch.tensor([[1.0], [0.0], [1.0]])} + risk = self.model.estimate_risk( + [batch], RULE, num_rollouts=1, label_key="outcome" + ) + self.assertEqual(risk["y_true"].tolist(), [1.0, 0.0, 1.0]) + + +class TestTraining(unittest.TestCase): + def test_trainer_and_checkpoint_round_trip(self): + dataset = tiny_dataset() + loader = get_dataloader(dataset, batch_size=3) + torch.manual_seed(0) + model = tiny_model(dataset, n_embd=16) + trainer = Trainer(model=model, enable_logging=False) + batch = next(iter(loader)) + before = model(**batch)["loss"].item() + trainer.train( + train_dataloader=loader, + epochs=6, + optimizer_params={"lr": 0.05}, + max_grad_norm=1.0, + ) + model.eval() + self.assertLess(model(**batch)["loss"].item(), before) + self.assertIn("loss", trainer.evaluate(loader)) + + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "ethos.ckpt") + trainer.save_ckpt(path) + restored = tiny_model(dataset, n_embd=16) + Trainer(model=restored, enable_logging=False).load_ckpt(path) + restored.eval() + self.assertTrue( + torch.allclose(model(**batch)["logit"], restored(**batch)["logit"]) + ) + options = {"num_rollouts": 2, "max_new_tokens": 8, "seed": 1} + self.assertEqual( + model.estimate_risk([batch], RULE, **options)["num_kept"].tolist(), + restored.estimate_risk([batch], RULE, **options)["num_kept"].tolist(), + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ethos_context_processor.py b/tests/core/test_ethos_context_processor.py new file mode 100644 index 0000000000..70fb496bfc --- /dev/null +++ b/tests/core/test_ethos_context_processor.py @@ -0,0 +1,120 @@ +"""Tests for EthosContextProcessor. All data here is synthetic.""" + +import math +import tempfile +import unittest +from datetime import datetime +from pathlib import Path + +import torch + +from pyhealth.processors import EthosContextProcessor + +BIRTH = datetime.fromisoformat("1980-01-01") +START = datetime.fromisoformat("2024-01-01") + + +def static(*rows, start=START): + return { + "time": [time for time, _ in rows], + "code": [code for _, code in rows], + "start": start, + } + + +def fitted(*contexts, **kwargs): + processor = EthosContextProcessor(**kwargs) + processor.fit([{"context": context} for context in contexts], "context") + return processor + + +def tokens_of(processor, context): + return processor.decode(processor.process(context)[1]) + + +class TestEthosContextProcessor(unittest.TestCase): + def test_order_and_shape(self): + context = static( + (BIRTH, "MEDS_BIRTH"), + (None, "RACE//WHITE"), + (None, "GENDER//F"), + (BIRTH, "MARITAL//SINGLE"), + ) + processor = fitted(context) + age, tokens = processor.process(context) + self.assertEqual(processor.context_size, 5) + self.assertEqual(processor.age_position, 2) + self.assertEqual(tokens.dtype, torch.long) + self.assertEqual(age.dtype, torch.float64) + self.assertEqual(age.shape, (1,)) + self.assertAlmostEqual(age.item(), (START - BIRTH).days / 365.25) + self.assertEqual( + processor.decode(tokens), + ["GENDER//F", "MARITAL//SINGLE", "", "", "RACE//WHITE"], + ) + + def test_missing_attributes_are_unknown(self): + processor = fitted(static()) + age, tokens = processor.process(static()) + self.assertTrue(math.isnan(age.item())) + self.assertEqual( + processor.decode(tokens), + ["GENDER//UNKNOWN", "MARITAL//UNKNOWN", "", "", "RACE//UNKNOWN"], + ) + + def test_unseen_value_is_unk(self): + processor = fitted(static((None, "GENDER//F"))) + out = tokens_of(processor, static((None, "GENDER//X"))) + self.assertEqual(out[0], "") + + def test_birth_without_a_time_gives_no_age(self): + processor = fitted(static((None, "MEDS_BIRTH"))) + age, _ = processor.process(static((None, "MEDS_BIRTH"))) + self.assertTrue(math.isnan(age.item())) + + def test_changing_attribute_uses_the_latest_known_value(self): + early, late = datetime.fromisoformat("2020-01-01"), datetime.fromisoformat("2030-01-01") + context = static((early, "MARITAL//SINGLE"), (late, "MARITAL//MARRIED")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//SINGLE") + + def test_changing_attribute_before_any_value_is_unknown(self): + later = datetime.fromisoformat("2030-01-01"), datetime.fromisoformat("2031-01-01") + context = static((later[0], "MARITAL//A"), (later[1], "MARITAL//B")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//UNKNOWN") + + def test_single_value_applies_whenever_recorded(self): + context = static((datetime.fromisoformat("2030-01-01"), "MARITAL//SINGLE")) + processor = fitted(context) + self.assertEqual(tokens_of(processor, context)[1], "MARITAL//SINGLE") + + def test_prefixes_must_include_birth(self): + with self.assertRaises(ValueError): + EthosContextProcessor(prefixes=("GENDER",)) + + def test_process_needs_fit(self): + with self.assertRaises(RuntimeError): + EthosContextProcessor().process(static()) + + def test_save_and_load(self): + context = static((BIRTH, "MEDS_BIRTH"), (None, "GENDER//F")) + processor = fitted(context, prefixes=("MEDS_BIRTH", "GENDER")) + with tempfile.TemporaryDirectory() as tmp: + path = str(Path(tmp) / "context.json") + processor.save(path) + restored = EthosContextProcessor() + restored.load(path) + self.assertEqual(restored.prefixes, processor.prefixes) + self.assertTrue( + torch.equal(restored.process(context)[1], processor.process(context)[1]) + ) + + def test_schema_matches_the_output(self): + processor = fitted(static()) + self.assertEqual(len(processor.schema()), len(processor.process(static()))) + self.assertTrue(processor.is_token()) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_ethos_processor.py b/tests/core/test_ethos_processor.py index faff7c7dc6..3aa2cc9289 100644 --- a/tests/core/test_ethos_processor.py +++ b/tests/core/test_ethos_processor.py @@ -374,6 +374,36 @@ def test_sample_dataset_and_batching(self): self.assertEqual(time.shape, (3, 5)) self.assertEqual(int((tokens == 0).sum()), 7) + def test_interval_estimates_are_mean_hours_per_token(self): + processor = EthosProcessor() + timelines = [ + timeline((0, "A", None), (10, "A", None)), + timeline((0, "A", None), (14, "A", None)), + ] + processor.fit([{"timeline": t} for t in timelines], "timeline") + self.assertAlmostEqual( + processor.interval_estimates["5m-15m"], (10 + 14) / 2 / 60 + ) + + def test_interval_estimates_split_repeated_tokens(self): + days = 24 * 60 + processor = fitted((0, "A", None), (400 * days, "A", None)) + self.assertAlmostEqual(processor.interval_estimates["=6mt"], 200 * 24.0) + + def test_interval_estimates_fall_back_to_the_lower_bound(self): + processor = fitted((0, "A", None)) + self.assertEqual(len(processor.interval_estimates), 19) + self.assertAlmostEqual(processor.interval_estimates["2h-3h"], 2.0) + + def test_interval_estimates_survive_save_and_load(self): + processor = fitted((0, "A", None), (10, "A", None)) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "ethos.json") + processor.save(path) + restored = EthosProcessor() + restored.load(path) + self.assertEqual(restored.interval_estimates, processor.interval_estimates) + if __name__ == "__main__": unittest.main() diff --git a/tests/core/test_ethos_tasks.py b/tests/core/test_ethos_tasks.py new file mode 100644 index 0000000000..8825613ed7 --- /dev/null +++ b/tests/core/test_ethos_tasks.py @@ -0,0 +1,183 @@ +"""Tests for EthosTimelineMEDS, EthosOutcomeMEDS and EthosRolloutRule. + +Tasks run directly on an in-memory ``Patient``. All data here is synthetic. +""" + +import unittest +from datetime import datetime, timedelta + +import polars as pl + +from pyhealth.data import Patient +from pyhealth.tasks import ( + EthosOutcomeMEDS, + EthosRolloutRule, + EthosTimelineMEDS, + HospitalReadmissionMEDS, + ICUAdmissionMEDS, + ProlongedLengthOfStayMEDS, +) + +T0 = datetime.fromisoformat("2024-01-01T08:00:00") +ADMIT = "HOSPITAL_ADMISSION//ER" +HOME = "HOSPITAL_DISCHARGE//HOME" +DIED = "HOSPITAL_DISCHARGE//DIED" +ICU = "ICU_ADMISSION//MICU" +DEATH = "MEDS_DEATH" +GOT = "token_of_interest" + + +def patient(*rows): + """Rows are ``(hours or None, code, hadm_id, value)``.""" + frame = pl.DataFrame( + { + "patient_id": ["1"] * len(rows), + "event_type": ["meds"] * len(rows), + "timestamp": pl.Series( + [None if r[0] is None else T0 + timedelta(hours=r[0]) for r in rows], + dtype=pl.Datetime("ms"), + ), + "meds/code": pl.Series([r[1] for r in rows], dtype=pl.String), + "meds/hadm_id": pl.Series([r[2] for r in rows], dtype=pl.Int64), + "meds/numeric_value": pl.Series([r[3] for r in rows], dtype=pl.Float64), + } + ) + return Patient(patient_id="1", data_source=frame) + + +STAYS = patient( + (None, "GENDER//F", None, None), + (-1000.0, "MEDS_BIRTH", None, None), + (-5.0, "LAB//EARLY", None, 3.0), + (0.0, ADMIT, 1, None), + (2.0, ICU, 1, None), + (3.0, "LAB//DURING", 1, 7.0), + (48.0, HOME, 1, None), + (48.0, "DX//AT_DISCHARGE", 1, None), + (96.0, ADMIT, 2, None), + (400.0, DIED, 2, None), + (400.0, DEATH, None, None), +) + + +class TestEthosTimelineMEDS(unittest.TestCase): + def test_whole_timeline_and_static_split(self): + samples = EthosTimelineMEDS()(STAYS) + self.assertEqual(len(samples), 1) + sample = samples[0] + self.assertEqual(sample["patient_id"], "1") + self.assertEqual(len(sample["timeline"]["code"]), 9) + self.assertIn(DEATH, sample["timeline"]["code"]) + self.assertNotIn("GENDER//F", sample["timeline"]["code"]) + self.assertEqual(sample["timeline"]["numeric_value"][0], 3.0) + self.assertEqual( + sorted(sample["context"]["code"]), ["GENDER//F", "MEDS_BIRTH"] + ) + self.assertEqual(sample["context"]["start"], T0 + timedelta(hours=-5)) + + def test_patient_with_only_static_rows_has_no_sample(self): + only_static = patient((None, "GENDER//F", None, None)) + self.assertEqual(EthosTimelineMEDS()(only_static), []) + + +class TestEthosOutcomeMEDS(unittest.TestCase): + def test_keeps_the_cohort_labels_and_codes_of_the_outcome_task(self): + for task_class in ( + ICUAdmissionMEDS, + HospitalReadmissionMEDS, + ProlongedLengthOfStayMEDS, + ): + with self.subTest(task=task_class.__name__): + outcomes = task_class()(STAYS) + samples = EthosOutcomeMEDS(task_class)(STAYS) + label = next(iter(task_class.output_schema)) + self.assertEqual(len(samples), len(outcomes)) + for sample, outcome in zip(samples, outcomes): + self.assertNotIn("codes", sample) + self.assertEqual(sample[label], outcome[label]) + self.assertEqual(sample["hadm_id"], outcome["hadm_id"]) + rows = sample["timeline"]["code"] + sample["context"]["code"] + self.assertEqual(sorted(rows), sorted(outcome["codes"])) + + def test_admission_cut_excludes_the_stay(self): + sample = EthosOutcomeMEDS(ICUAdmissionMEDS)(STAYS)[0] + self.assertEqual(sample["timeline"]["code"], ["LAB//EARLY", ADMIT]) + self.assertEqual(sample["timeline"]["numeric_value"], [3.0, None]) + + def test_discharge_cut_excludes_what_follows(self): + sample = EthosOutcomeMEDS(HospitalReadmissionMEDS)(STAYS)[0] + codes = sample["timeline"]["code"] + self.assertEqual(codes[-2:], [HOME, "DX//AT_DISCHARGE"]) + self.assertNotIn(DIED, codes) + self.assertNotIn(DEATH, codes) + + def test_patient_without_a_stay_has_no_sample(self): + lab_only = patient((0.0, "LAB//X", None, 1.0)) + self.assertEqual(EthosOutcomeMEDS(ICUAdmissionMEDS)(lab_only), []) + + def test_names_and_schema(self): + task = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS, threshold_days=7.0) + self.assertEqual(task.task_name, "EthosProlongedLengthOfStayMEDS") + self.assertEqual(task.output_schema, {"prolonged_los": "binary"}) + self.assertEqual(task.input_schema, EthosTimelineMEDS.input_schema) + + def test_rejects_other_tasks(self): + with self.assertRaises(ValueError): + EthosOutcomeMEDS(EthosTimelineMEDS) + + +class TestRolloutRules(unittest.TestCase): + def test_icu_admission(self): + rule = EthosOutcomeMEDS(ICUAdmissionMEDS).rule + self.assertIs(rule.score(ICU, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), True) + self.assertIs(rule.score(DIED, GOT, 1.0), True) + self.assertIs(rule.score(HOME, GOT, 1.0), False) + self.assertIsNone(rule.score("TIMELINE_END", GOT, 1.0)) + self.assertIsNone(rule.score("LAB//X", "time_limit", 800.0)) + self.assertEqual(rule.time_limit_days, 730.5) + + def test_icu_admission_without_deaths(self): + rule = EthosOutcomeMEDS(ICUAdmissionMEDS, death_as_positive=False).rule + self.assertIs(rule.score(ICU, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), False) + self.assertIs(rule.score(DIED, GOT, 1.0), False) + self.assertEqual( + rule.stop_prefixes, + EthosOutcomeMEDS(ICUAdmissionMEDS).rule.stop_prefixes, + ) + + def test_prolonged_stay_threshold_is_inclusive(self): + rule = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS).rule + self.assertIs(rule.score(HOME, GOT, 10.0), True) + self.assertIs(rule.score(DEATH, GOT, 11.0), True) + self.assertIs(rule.score(HOME, GOT, 9.9), False) + self.assertIs(rule.score(DEATH, GOT, 9.9), False) + self.assertIsNone(rule.score("TIMELINE_END", GOT, 11.0)) + custom = EthosOutcomeMEDS(ProlongedLengthOfStayMEDS, threshold_days=3.0).rule + self.assertIs(custom.score(HOME, GOT, 3.0), True) + + def test_readmission(self): + rule = EthosOutcomeMEDS(HospitalReadmissionMEDS).rule + self.assertEqual(rule.time_limit_days, 30.0) + self.assertIs(rule.score(ADMIT, GOT, 1.0), True) + self.assertIs(rule.score(DEATH, GOT, 1.0), True) + self.assertIs(rule.score("TIMELINE_END", GOT, 1.0), False) + self.assertIs(rule.score("LAB//X", "time_limit", 31.0), False) + custom = EthosOutcomeMEDS(HospitalReadmissionMEDS, window_days=7.0).rule + self.assertEqual(custom.time_limit_days, 7.0) + + def test_full_followup_does_not_change_the_rollout(self): + self.assertEqual( + EthosOutcomeMEDS(HospitalReadmissionMEDS).rule, + EthosOutcomeMEDS(HospitalReadmissionMEDS, require_full_followup=True).rule, + ) + + def test_failed_rollouts_are_always_dropped(self): + rule = EthosRolloutRule(stop_prefixes=("X",), keep_time_limited=True) + self.assertIsNone(rule.score(None, "key_error", 0.0)) + self.assertIsNone(rule.score("X", "token_limit", 0.0)) + + +if __name__ == "__main__": + unittest.main() From 0eb64154b5da724d082a29010d56940d597ce54d Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 16:24:46 -0600 Subject: [PATCH 04/10] Keep EthosProcessor's vocabulary local instead of importing ConceptVocab EthosVocab is a 50-line copy of the parts of cehr_processor.ConceptVocab the tokenizer uses, so the processor no longer links to the CEHR processor. Co-Authored-By: Claude Opus 5.5 --- pyhealth/processors/ethos_processor.py | 71 ++++++++++++++++++++++++-- 1 file changed, 67 insertions(+), 4 deletions(-) diff --git a/pyhealth/processors/ethos_processor.py b/pyhealth/processors/ethos_processor.py index ae84ae4078..3a1bde5c16 100644 --- a/pyhealth/processors/ethos_processor.py +++ b/pyhealth/processors/ethos_processor.py @@ -21,6 +21,7 @@ import math from collections import defaultdict from collections.abc import Iterable, Sequence +from dataclasses import dataclass, field from datetime import timedelta from pathlib import Path from typing import Any @@ -32,7 +33,6 @@ from . import register_processor from .base_processor import FeatureProcessor -from .cehr_processor import ConceptVocab DEATH_CODE = "MEDS_DEATH" DISCHARGE_PREFIX = "HOSPITAL_DISCHARGE" @@ -70,6 +70,69 @@ ("=6mt", timedelta(days=180)), ) +PAD_TOKEN = "" +UNK_TOKEN = "" + + +@dataclass +class EthosVocab: + """Maps token strings to dense ids, with ```` at 0 and ```` at 1. + + Unknown tokens map to ``unk_id``. :class:`EthosProcessor` keeps one as + ``vocab`` and saves it with :meth:`to_json`. + + Examples: + >>> from pyhealth.processors.ethos_processor import EthosVocab + >>> vocab = EthosVocab() + >>> vocab.add_token("Q1") + 2 + >>> vocab["Q1"], vocab["unseen"], vocab.vocab_size + (2, 1, 3) + """ + + token_to_id: dict[str, int] = field(default_factory=dict) + pad_id: int = 0 + unk_id: int = 1 + _next_id: int = 2 + + def __post_init__(self) -> None: + if not self.token_to_id: + self.token_to_id = {PAD_TOKEN: self.pad_id, UNK_TOKEN: self.unk_id} + self._next_id = 2 + + def add_token(self, token: str) -> int: + """Returns the token's id, adding it first if it is new.""" + if token not in self.token_to_id: + self.token_to_id[token] = self._next_id + self._next_id += 1 + return self.token_to_id[token] + + def __getitem__(self, token: str) -> int: + return self.token_to_id.get(token, self.unk_id) + + @property + def vocab_size(self) -> int: + """Returns the number of ids, including ```` and ````.""" + return self._next_id + + def to_json(self) -> dict[str, Any]: + """Returns the vocabulary as a JSON-ready dict.""" + return { + "token_to_id": self.token_to_id, + "next_id": self._next_id, + "pad_id": self.pad_id, + "unk_id": self.unk_id, + } + + @classmethod + def from_json(cls, data: dict[str, Any]) -> "EthosVocab": + """Rebuilds a vocabulary from :meth:`to_json`'s output.""" + vocab = cls(pad_id=int(data["pad_id"]), unk_id=int(data["unk_id"])) + vocab.token_to_id = dict(data["token_to_id"]) + vocab._next_id = int(data["next_id"]) + return vocab + + _MICROSECONDS = timedelta(microseconds=1) _INTERVAL_LABELS = [label for label, _ in TIME_INTERVALS] _INTERVAL_BOUNDS = [bound // _MICROSECONDS for _, bound in TIME_INTERVALS] @@ -231,7 +294,7 @@ def __init__( ) self.exclude_prefixes = tuple(exclude_prefixes) self.add_timeline_end = add_timeline_end - self.vocab: ConceptVocab | None = None + self.vocab: EthosVocab | None = None self.quantiles: dict[str, list[float]] = {} def _read( @@ -306,7 +369,7 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: code: _quantile_breaks(values, self.num_quantiles) for code, values in observed.items() } - self.vocab = ConceptVocab() + self.vocab = EthosVocab() for k in range(1, self.num_quantiles + 1): self.vocab.add_token(f"Q{k}") for label in _INTERVAL_LABELS: @@ -410,7 +473,7 @@ def load(self, path: str) -> None: self.exclude_prefixes = tuple(state["exclude_prefixes"]) self.add_timeline_end = state["add_timeline_end"] vocab = state["vocab"] - self.vocab = None if vocab is None else ConceptVocab.from_json(vocab) + self.vocab = None if vocab is None else EthosVocab.from_json(vocab) self.quantiles = state["quantiles"] def size(self) -> int: From 15aa1df4e2b1c87ca318253b3fd42fa62d75a474 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 16:25:21 -0600 Subject: [PATCH 05/10] Drop quoted return annotation in EthosVocab Co-Authored-By: Claude Opus 5.5 --- pyhealth/processors/ethos_processor.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyhealth/processors/ethos_processor.py b/pyhealth/processors/ethos_processor.py index 3a1bde5c16..53613d3a0d 100644 --- a/pyhealth/processors/ethos_processor.py +++ b/pyhealth/processors/ethos_processor.py @@ -125,7 +125,7 @@ def to_json(self) -> dict[str, Any]: } @classmethod - def from_json(cls, data: dict[str, Any]) -> "EthosVocab": + def from_json(cls, data: dict[str, Any]) -> EthosVocab: """Rebuilds a vocabulary from :meth:`to_json`'s output.""" vocab = cls(pad_id=int(data["pad_id"]), unk_id=int(data["unk_id"])) vocab.token_to_id = dict(data["token_to_id"]) From 02619cbeee177118f75d187b68c86234c7e30153 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 16:28:34 -0600 Subject: [PATCH 06/10] Keep the MEDS codes local and return input rows from the window helpers meds_outcome_tasks.py now defines ADMISSION_PREFIX, DISCHARGE_PREFIX, DIED_CODE and DEATH_CODE itself instead of importing them from in_hospital_mortality_meds.py. _rows_at_admission and _rows_at_discharge return the input rows, and _codes_at_admission and _codes_at_discharge take their codes, so a caller can read other columns of the same window. The task classes are unchanged. This moves the refactor from #1397 here, so #1397 no longer changes this file. Co-Authored-By: Claude Opus 5.5 --- pyhealth/tasks/meds_outcome_tasks.py | 43 ++++++++++++++++------------ 1 file changed, 25 insertions(+), 18 deletions(-) diff --git a/pyhealth/tasks/meds_outcome_tasks.py b/pyhealth/tasks/meds_outcome_tasks.py index 3e763198b9..9ab491b8a8 100644 --- a/pyhealth/tasks/meds_outcome_tasks.py +++ b/pyhealth/tasks/meds_outcome_tasks.py @@ -88,12 +88,13 @@ import polars as pl from .base_task import BaseTask -from .in_hospital_mortality_meds import ( - ADMISSION_PREFIX, - DEATH_CODE, - DIED_CODE, - DISCHARGE_PREFIX, -) + +# The same MEDS codes as in_hospital_mortality_meds.py, kept here so these +# tasks do not import another task's module. +ADMISSION_PREFIX = "HOSPITAL_ADMISSION" +DISCHARGE_PREFIX = "HOSPITAL_DISCHARGE" +DIED_CODE = "HOSPITAL_DISCHARGE//DIED" +DEATH_CODE = "MEDS_DEATH" ICU_ADMISSION_PREFIX = "ICU_ADMISSION" ICU_DISCHARGE_PREFIX = "ICU_DISCHARGE" @@ -172,15 +173,15 @@ def _is_this_stay(hadm_id: int) -> pl.Expr: return (pl.col("_hadm") == hadm_id).fill_null(False) -def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: - """Returns the input of an admission-time prediction. +def _rows_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> pl.DataFrame: + """Returns the input rows of an admission-time prediction. Args: events (pl.DataFrame): Output of :func:`_load_events`. stay (dict[str, Any]): A record from :func:`_completed_stays`. Returns: - list[str]: Static codes, history before admission, then the admission + pl.DataFrame: Static rows, history before admission, then the admission event itself. See the module docstring for the exclusions. """ code = pl.col("meds/code") @@ -196,28 +197,34 @@ def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str] ) history = (time < stay["admit"]) & ~this_stay_icu & ~this_stay_dated window = time.is_null() | history - return events.filter((window | admission_event) & (code != DEATH_CODE))[ - "meds/code" - ].to_list() + return events.filter((window | admission_event) & (code != DEATH_CODE)) -def _codes_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: - """Returns the input of a discharge-time prediction. +def _codes_at_admission(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the codes of :func:`_rows_at_admission`.""" + return _rows_at_admission(events, stay)["meds/code"].to_list() + + +def _rows_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> pl.DataFrame: + """Returns the input rows of a discharge-time prediction. Args: events (pl.DataFrame): Output of :func:`_load_events`. stay (dict[str, Any]): A record from :func:`_completed_stays`. Returns: - list[str]: Static codes, everything before discharge, then the events + pl.DataFrame: Static rows, everything before discharge, then the events of this stay stamped at discharge. """ time = pl.col("timestamp") at_discharge = (time == stay["discharge"]) & _is_this_stay(stay["hadm_id"]) window = time.is_null() | (time < stay["discharge"]) | at_discharge - return events.filter(window & (pl.col("meds/code") != DEATH_CODE))[ - "meds/code" - ].to_list() + return events.filter(window & (pl.col("meds/code") != DEATH_CODE)) + + +def _codes_at_discharge(events: pl.DataFrame, stay: dict[str, Any]) -> list[str]: + """Returns the codes of :func:`_rows_at_discharge`.""" + return _rows_at_discharge(events, stay)["meds/code"].to_list() def _next_outcome_time( From 15b15af52134e809bf060173d4660e609da2d6c8 Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 16:33:56 -0600 Subject: [PATCH 07/10] Port ETHOS to the LabelProcessor API and keep its MEDS codes local - BaseModel.mode is now a read-only property, so ETHOS no longer sets self.mode = None (it raised AttributeError on master). The dataset must have no label processor, so mode is None; a labelled dataset now raises a clear ValueError instead of failing later in Trainer. - ethos_tasks.py defines ADMISSION_PREFIX, DISCHARGE_PREFIX, DIED_CODE and DEATH_CODE itself instead of importing them from in_hospital_mortality_meds.py and ethos_processor.py. - EthosContextProcessor uses EthosVocab from ethos_processor.py instead of cehr_processor.ConceptVocab. - estimate_risk notes that rollouts have no key-value cache. Co-Authored-By: Claude Opus 5.5 --- pyhealth/models/ethos.py | 19 +++++++++++++++---- .../processors/ethos_context_processor.py | 9 ++++----- pyhealth/tasks/ethos_tasks.py | 14 ++++++++------ tests/core/test_ethos.py | 14 ++++++++++++++ 4 files changed, 41 insertions(+), 15 deletions(-) diff --git a/pyhealth/models/ethos.py b/pyhealth/models/ethos.py index 4a30c2f069..9a9f87b97f 100644 --- a/pyhealth/models/ethos.py +++ b/pyhealth/models/ethos.py @@ -130,8 +130,8 @@ class ETHOS(BaseModel): :meth:`forward` is the next-token loss, so the model trains with :class:`~pyhealth.trainer.Trainer` on - :class:`~pyhealth.tasks.EthosTimelineMEDS`, with no labels. It has no - ``mode`` and gives no ``y_prob``. Risks come from :meth:`estimate_risk`, + :class:`~pyhealth.tasks.EthosTimelineMEDS`, with no labels. Its dataset has + no label processor, so ``mode`` is ``None`` and there is no ``y_prob``. Risks come from :meth:`estimate_risk`, which samples timelines forward from each sample of :class:`~pyhealth.tasks.EthosOutcomeMEDS`. @@ -155,7 +155,8 @@ class ETHOS(BaseModel): dropout: Dropout rate. Raises: - ValueError: If ``dataset`` lacks those fields, or the sizes do not fit. + ValueError: If ``dataset`` lacks those fields or has a label, or the + sizes do not fit. Examples: >>> from datetime import datetime, timedelta @@ -206,7 +207,12 @@ def __init__( dropout: float = 0.3, ) -> None: super().__init__(dataset=dataset) - self.mode = None + if self.label_processors: + raise ValueError( + "ETHOS trains without labels, so its dataset needs an empty " + f"output_schema, not {sorted(self.label_processors)}; see " + "EthosTimelineMEDS. Score labels with estimate_risk." + ) processors = dataset.input_processors timeline = processors.get("timeline") @@ -507,6 +513,11 @@ def estimate_risk( The risk is the share of positive rollouts among those ``rule`` keeps. The paper uses 100 rollouts per sample. + Rollouts have no key-value cache: each new token re-runs the model over + the whole sequence so far. That is fine for small models and short + rollouts, but it will be slow at the paper's scale (2048-token context, + 100 rollouts per sample). + Args: dataloader: Batches with ``timeline`` and ``context``. rule: How rollouts stop and count, such as diff --git a/pyhealth/processors/ethos_context_processor.py b/pyhealth/processors/ethos_context_processor.py index e0bad4fb57..488992f4c9 100644 --- a/pyhealth/processors/ethos_context_processor.py +++ b/pyhealth/processors/ethos_context_processor.py @@ -27,8 +27,7 @@ from . import register_processor from .base_processor import FeatureProcessor -from .cehr_processor import ConceptVocab -from .ethos_processor import STATIC_CODE_PREFIXES +from .ethos_processor import STATIC_CODE_PREFIXES, EthosVocab BIRTH_CODE = "MEDS_BIRTH" UNKNOWN_SUFFIX = "//UNKNOWN" @@ -111,7 +110,7 @@ def __init__(self, prefixes: Sequence[str] = STATIC_CODE_PREFIXES) -> None: if BIRTH_CODE not in prefixes: raise ValueError(f"prefixes must include {BIRTH_CODE}, got {prefixes}.") self.prefixes = tuple(sorted(prefixes)) - self.vocab: ConceptVocab | None = None + self.vocab: EthosVocab | None = None @property def age_position(self) -> int: @@ -130,7 +129,7 @@ def fit(self, samples: Iterable[dict[str, Any]], field: str) -> None: samples: Sample dictionaries. field: Key of the static rows in each sample. """ - self.vocab = ConceptVocab() + self.vocab = EthosVocab() for prefix in self.prefixes: if prefix != BIRTH_CODE: self.vocab.add_token(prefix + UNKNOWN_SUFFIX) @@ -218,7 +217,7 @@ def load(self, path: str) -> None: state = orjson.loads(Path(path).read_bytes()) self.prefixes = tuple(state["prefixes"]) vocab = state["vocab"] - self.vocab = None if vocab is None else ConceptVocab.from_json(vocab) + self.vocab = None if vocab is None else EthosVocab.from_json(vocab) def size(self) -> int: """Returns the vocabulary size.""" diff --git a/pyhealth/tasks/ethos_tasks.py b/pyhealth/tasks/ethos_tasks.py index 92a77951d4..03457a3acb 100644 --- a/pyhealth/tasks/ethos_tasks.py +++ b/pyhealth/tasks/ethos_tasks.py @@ -29,13 +29,8 @@ import polars as pl -from ..processors.ethos_processor import ( - DEATH_CODE, - STATIC_CODE_PREFIXES, - TIMELINE_END_TOKEN, -) +from ..processors.ethos_processor import STATIC_CODE_PREFIXES, TIMELINE_END_TOKEN from .base_task import BaseTask -from .in_hospital_mortality_meds import ADMISSION_PREFIX, DIED_CODE, DISCHARGE_PREFIX from .meds_outcome_tasks import ( ICU_ADMISSION_PREFIX, HospitalReadmissionMEDS, @@ -47,6 +42,13 @@ _rows_at_discharge, ) +# MEDS codes, the same as in in_hospital_mortality_meds.py and +# meds_outcome_tasks.py, kept here so this module does not import them. +ADMISSION_PREFIX = "HOSPITAL_ADMISSION" +DISCHARGE_PREFIX = "HOSPITAL_DISCHARGE" +DIED_CODE = "HOSPITAL_DISCHARGE//DIED" +DEATH_CODE = "MEDS_DEATH" + #: Why a rollout stopped. The first three are ETHOS's. STOP_TOKEN = "token_of_interest" TIME_LIMIT = "time_limit" diff --git a/tests/core/test_ethos.py b/tests/core/test_ethos.py index 7929a8be62..c891c0c89e 100644 --- a/tests/core/test_ethos.py +++ b/tests/core/test_ethos.py @@ -190,6 +190,20 @@ def test_rejects_datasets_without_ethos_fields(self): with self.assertRaises(ValueError): tiny_model(dataset) + def test_has_no_mode_and_rejects_labels(self): + self.assertIsNone(self.model.mode) + samples = [ + {**sample(i, [(0.0, ADMIT, None), (1.0, LAB, 1.0)]), "label": i % 2} + for i in range(2) + ] + dataset = create_sample_dataset( + samples, + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={"label": "binary"}, + ) + with self.assertRaises(ValueError): + tiny_model(dataset) + def test_rejects_sizes_that_do_not_fit(self): with self.assertRaises(ValueError): tiny_model(self.dataset, n_head=3) From 5f3a65f1c5038505d3ee6c363b66e0a648a007ff Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 16:58:33 -0600 Subject: [PATCH 08/10] Say how HospitalReadmissionMEDS differs from ReadmissionPredictionMIMIC4 Also note in the module docstring that the midnight rule can drop a true midnight event, and that the discharge-code pick among exact timestamp ties is not guaranteed stable. Co-Authored-By: Claude Opus 5.5 --- pyhealth/tasks/meds_outcome_tasks.py | 32 ++++++++++++++++++++++++++-- 1 file changed, 30 insertions(+), 2 deletions(-) diff --git a/pyhealth/tasks/meds_outcome_tasks.py b/pyhealth/tasks/meds_outcome_tasks.py index 9ab491b8a8..09975ec3d7 100644 --- a/pyhealth/tasks/meds_outcome_tasks.py +++ b/pyhealth/tasks/meds_outcome_tasks.py @@ -20,7 +20,9 @@ and discharge time ``t_d`` (latest ``HOSPITAL_DISCHARGE//*``). Stays without both events, or with ``t_d <= t_a``, produce no sample. A stay *ended in death* if its discharge code is ``HOSPITAL_DISCHARGE//DIED`` or a ``MEDS_DEATH`` event -falls in ``[t_a, t_d]``. +falls in ``[t_a, t_d]``. The discharge code is the one stamped ``t_d``; if a +stay has two discharge events at exactly ``t_d``, which one is taken is not +guaranteed to be stable. ICU admission and prolonged stay predict **at hospital admission**: @@ -58,7 +60,8 @@ midnight before ``t_a``. These are date-resolution records such as HCPCS billing codes, which sort before the admission on the same day but describe care given during the stay. Timed events of the current stay before ``t_a``, such as -emergency department labs and transfers, are kept. +emergency department labs and transfers, are kept. This is a heuristic: it also +drops a timed event of the current stay that really happened at midnight. Configuration ------------- @@ -341,6 +344,31 @@ class HospitalReadmissionMEDS(BaseTask): the binary label is whether the patient was readmitted or died within ``window_days``. See the module docstring for the full definition. + Differences from + :class:`~pyhealth.tasks.readmission_prediction.ReadmissionPredictionMIMIC4`, + which also labels readmission within a window after discharge: + + * **Data.** This task reads any MEDS dataset through + :class:`~pyhealth.datasets.MEDSDataset`, whose events are all in one + ``meds`` table. ``ReadmissionPredictionMIMIC4`` reads the MIMIC-IV + ``patients``, ``admissions``, ``diagnoses_icd``, ``procedures_icd`` and + ``prescriptions`` tables of ``MIMIC4EHRDataset``. + * **Input.** One code sequence with the whole history up to discharge, + instead of the current admission's diagnoses, procedures and drugs as + three sequences. + * **Death.** A death within the window counts as positive, and stays that + ended in death are excluded. ``ReadmissionPredictionMIMIC4`` does not + look at deaths. + * **Cohort.** Every completed stay that did not end in death is a sample, + including a patient's last stay (negative unless the patient dies within + the window), and ``require_full_followup`` gives the ETHOS-ARES + "Reduced" cohort. ``ReadmissionPredictionMIMIC4`` only makes samples for + admissions followed by another admission, skips visits missing any of + the three code types, and drops patients under 18. + * **Window.** 30 days by default, inclusive, from discharge to the next + admission of another stay at or after discharge, as in ETHOS-ARES. + ``ReadmissionPredictionMIMIC4`` uses 15 days by default, exclusive. + Args: window_days (float): Outcome window after discharge, inclusive. Defaults to ``30.0``, matching ETHOS-ARES. From 79af6ea04ea5bfa3479aca01fba87a21c0407ddb Mon Sep 17 00:00:00 2001 From: jhnwu3 Date: Tue, 10 Nov 2026 17:00:42 -0600 Subject: [PATCH 09/10] Test EthosTimelineMEDS and EthosOutcomeMEDS through MEDSDataset.set_task On synthetic Parquet: the timeline task fits both ETHOS processors, and two EthosOutcomeMEDS options give their own cached labels while reusing the timeline vocabularies. Co-Authored-By: Claude Opus 5.5 --- tests/core/test_ethos_tasks.py | 103 ++++++++++++++++++++++++++++++++- 1 file changed, 102 insertions(+), 1 deletion(-) diff --git a/tests/core/test_ethos_tasks.py b/tests/core/test_ethos_tasks.py index 8825613ed7..91511b79e4 100644 --- a/tests/core/test_ethos_tasks.py +++ b/tests/core/test_ethos_tasks.py @@ -1,14 +1,21 @@ """Tests for EthosTimelineMEDS, EthosOutcomeMEDS and EthosRolloutRule. -Tasks run directly on an in-memory ``Patient``. All data here is synthetic. +Most tests run the tasks directly on an in-memory ``Patient``; +``TestSetTask`` runs them through ``MEDSDataset.set_task`` on synthetic +Parquet. All data here is synthetic. """ +import shutil +import tempfile import unittest from datetime import datetime, timedelta +from pathlib import Path import polars as pl from pyhealth.data import Patient +from pyhealth.datasets import MEDSDataset +from pyhealth.processors import EthosContextProcessor, EthosProcessor from pyhealth.tasks import ( EthosOutcomeMEDS, EthosRolloutRule, @@ -179,5 +186,99 @@ def test_failed_rollouts_are_always_dropped(self): self.assertIsNone(rule.score("X", "token_limit", 0.0)) +_CONFIG = """version: "1.0" +tables: + meds: + file_path: "data" + patient_id: "subject_id" + timestamp: "time" + attributes: + - "code" + - "numeric_value" + - "hadm_id" +""" + + +class TestSetTask(unittest.TestCase): + """Both tasks through MEDSDataset, so cache keys and processors are real.""" + + @classmethod + def setUpClass(cls): + cls.temp_dir = Path(tempfile.mkdtemp()) + root = cls.temp_dir / "meds" + (root / "data").mkdir(parents=True) + config_path = cls.temp_dir / "meds_hadm.yaml" + config_path.write_text(_CONFIG) + rows = [ # (subject, hours or None, code, hadm_id, value) + (1, None, "GENDER//F", None, None), + (1, -1e5, "MEDS_BIRTH", None, None), + (1, 0.0, ADMIT, 10, None), + (1, 2.0, "LAB//A", 10, 1.0), + (1, 5.0, ICU, 10, None), + (1, 264.0, HOME, 10, None), + (1, 480.0, ADMIT, 11, None), + (1, 483.0, "LAB//A", 11, 3.0), + (1, 528.0, DIED, 11, None), + (2, None, "GENDER//M", None, None), + (2, 0.0, ADMIT, 20, None), + (2, 3.0, "LAB//A", 20, 2.0), + (2, 48.0, HOME, 20, None), + ] + times = [None if r[1] is None else T0 + timedelta(hours=r[1]) for r in rows] + pl.DataFrame( + { + "subject_id": pl.Series([r[0] for r in rows], dtype=pl.Int64), + "time": pl.Series(times, dtype=pl.Datetime("us")), + "code": pl.Series([r[2] for r in rows], dtype=pl.String), + "numeric_value": pl.Series([r[4] for r in rows], dtype=pl.Float32), + "hadm_id": pl.Series([r[3] for r in rows], dtype=pl.Int64), + } + ).write_parquet(root / "data" / "0.parquet") + cls.dataset = MEDSDataset( + root=str(root), + config_path=str(config_path), + cache_dir=cls.temp_dir / "cache", + num_workers=1, + ) + cls.timelines = cls.dataset.set_task(EthosTimelineMEDS(), num_workers=1) + + @classmethod + def tearDownClass(cls): + cls.timelines.close() + shutil.rmtree(cls.temp_dir, ignore_errors=True) + + def outcome_labels(self, **options): + task = EthosOutcomeMEDS(ICUAdmissionMEDS, **options) + samples = self.dataset.set_task( + task, num_workers=1, input_processors=self.timelines.input_processors + ) + try: + for key in ("timeline", "context"): + self.assertEqual( + samples.input_processors[key].vocab.token_to_id, + self.timelines.input_processors[key].vocab.token_to_id, + ) + return sorted(int(samples[i]["icu_admission"]) for i in range(len(samples))) + finally: + samples.close() + + def test_timeline_processors_are_fitted(self): + self.assertEqual(len(self.timelines), 2) + timeline = self.timelines.input_processors["timeline"] + context = self.timelines.input_processors["context"] + self.assertIsInstance(timeline, EthosProcessor) + self.assertIsInstance(context, EthosContextProcessor) + self.assertIn("LAB//A", timeline.vocab.token_to_id) + self.assertNotIn("GENDER//F", timeline.vocab.token_to_id) + self.assertIn("GENDER//F", context.vocab.token_to_id) + _, tokens = self.timelines[0]["timeline"] + self.assertEqual(timeline.decode(tokens)[-1], "TIMELINE_END") + + def test_outcome_options_reach_the_cache_key(self): + # Stays: ICU (10), death without ICU (11), neither (20). + self.assertEqual(self.outcome_labels(), [0, 1, 1]) + self.assertEqual(self.outcome_labels(death_as_positive=False), [0, 0, 1]) + + if __name__ == "__main__": unittest.main() From 7d24d2958797bf62b94ac77ecc4006accbf3fae1 Mon Sep 17 00:00:00 2001 From: solarsys Date: Sat, 14 Nov 2026 02:17:50 -0500 Subject: [PATCH 10/10] ETHOS.estimate_risk: fail loudly on processors other than the model's An outcome dataset built without the training model's processors fits its own vocabulary and quantiles, so token ids mean something else and the risks are silently wrong. estimate_risk now compares the dataloader's dataset processors (vocabularies, quantiles, interval estimates) with the model's and raises; for loaders without a dataset it raises on any id outside the model's vocabulary. Docstring and test. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01BdtuVKBLhWpYbhTQbaZaTt --- pyhealth/models/ethos.py | 51 ++++++++++++++++++++++++++++++++++++++++ tests/core/test_ethos.py | 22 +++++++++++++++++ 2 files changed, 73 insertions(+) diff --git a/pyhealth/models/ethos.py b/pyhealth/models/ethos.py index 9a9f87b97f..91998db44d 100644 --- a/pyhealth/models/ethos.py +++ b/pyhealth/models/ethos.py @@ -498,6 +498,48 @@ def rollout( "days": (hours / 24.0).tolist(), } + def _check_processors(self, dataset: Any) -> None: + """Raises if ``dataset`` encodes with other processors than the model's.""" + processors = getattr(dataset, "input_processors", None) + if not processors: + return + ours = {"timeline": self.timeline_processor, "context": self.context_processor} + for key, mine in ours.items(): + theirs = processors.get(key) + if theirs is mine: + continue + same = ( + theirs is not None + and type(theirs) is type(mine) + and theirs.vocab is not None + and theirs.vocab.to_json() == mine.vocab.to_json() + and getattr(theirs, "quantiles", None) == getattr(mine, "quantiles", None) + and getattr(theirs, "interval_estimates", None) + == getattr(mine, "interval_estimates", None) + ) + if not same: + raise ValueError( + f"The dataset's {key!r} processor is not the one this model " + "was trained with, so its token ids mean something else. " + "Build the outcome dataset with " + "input_processors=model.dataset.input_processors." + ) + + def _check_ids(self, tokens: torch.Tensor, static: torch.Tensor) -> None: + """Raises if a batch has ids outside the model's vocabularies.""" + if tokens.numel() and int(tokens.max()) >= self.timeline_vocab_size: + raise ValueError( + "A timeline token id is outside this model's vocabulary; the " + "batch was encoded with other processors. Build the outcome " + "dataset with input_processors=model.dataset.input_processors." + ) + if static.numel() and int(static.max()) >= self.context_processor.size(): + raise ValueError( + "A context token id is outside this model's vocabulary; build " + "the outcome dataset with " + "input_processors=model.dataset.input_processors." + ) + def estimate_risk( self, dataloader: Iterable[dict[str, Any]], @@ -513,6 +555,13 @@ def estimate_risk( The risk is the share of positive rollouts among those ``rule`` keeps. The paper uses 100 rollouts per sample. + The batches must be encoded with this model's processors: build the + outcome dataset with ``input_processors=model.dataset.input_processors`` + (see :class:`~pyhealth.tasks.EthosOutcomeMEDS`). Processors fitted on + the outcome samples give token ids that mean something else, so this + raises ``ValueError`` when the dataloader's dataset has other + processors, or when a token id falls outside the model's vocabulary. + Rollouts have no key-value cache: each new token re-runs the model over the whole sequence so far. That is fine for small models and short rollouts, but it will be slow at the paper's scale (2048-token context, @@ -533,6 +582,7 @@ def estimate_risk( ``num_kept`` (rollouts behind each risk), ``patient_id`` (if the batches have it) and ``y_true`` (with ``label_key``). """ + self._check_processors(getattr(dataloader, "dataset", None)) generator = None if seed is not None: generator = torch.Generator(device=self.device).manual_seed(seed) @@ -544,6 +594,7 @@ def estimate_risk( for batch in dataloader: time, tokens = batch["timeline"] age, static = batch["context"] + self._check_ids(tokens, static) for i in range(len(tokens)): result = self.rollout( (time[i], tokens[i]), diff --git a/tests/core/test_ethos.py b/tests/core/test_ethos.py index c891c0c89e..6b67ef599f 100644 --- a/tests/core/test_ethos.py +++ b/tests/core/test_ethos.py @@ -391,6 +391,28 @@ def setUp(self): torch.manual_seed(0) self.model = tiny_model(self.dataset) + def test_outcome_data_must_use_the_models_processors(self): + script(self.model, DEATH) + new_codes = [(0.5 + k, f"LAB//NEW{k}", None) for k in range(8)] + refitted = tiny_dataset(extra=[sample(9, [(0.0, ADMIT, None), *new_codes])]) + with self.assertRaisesRegex(ValueError, "input_processors"): + self.model.estimate_risk(get_dataloader(refitted, batch_size=3), RULE, + num_rollouts=1) + # a plain list of batches has no dataset to compare; out-of-vocabulary + # ids still raise + with self.assertRaisesRegex(ValueError, "outside this model's vocabulary"): + self.model.estimate_risk([batch_of(refitted, size=4)], RULE, + num_rollouts=1) + shared = create_sample_dataset( + [sample(i, [(0.0, ADMIT, None), (30.0, HOME, None)]) for i in range(2)], + input_schema={"timeline": "ethos", "context": "ethos_context"}, + output_schema={}, + input_processors=self.dataset.input_processors, + ) + risk = self.model.estimate_risk(get_dataloader(shared, batch_size=2), RULE, + num_rollouts=1) + self.assertEqual(len(risk["y_prob"]), 2) + def test_all_positive(self): script(self.model, DEATH) risk = self.model.estimate_risk([self.batch], RULE, num_rollouts=2)