diff --git a/docs/api/models.rst b/docs/api/models.rst index 38be3d8362..4224505ef7 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -297,6 +297,7 @@ API Reference models/pyhealth.models.CNN models/pyhealth.models.UNet models/pyhealth.models.RNN + models/pyhealth.models.DSA models/pyhealth.models.GNN models/pyhealth.models.Transformer models/pyhealth.models.BEHRT diff --git a/docs/api/models/pyhealth.models.DSA.rst b/docs/api/models/pyhealth.models.DSA.rst new file mode 100644 index 0000000000..ab55577910 --- /dev/null +++ b/docs/api/models/pyhealth.models.DSA.rst @@ -0,0 +1,9 @@ +pyhealth.models.DSA +=================================== + +Dynamic Survival Analysis model for early event prediction. + +.. autoclass:: pyhealth.models.DSA + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 7152bf7b07..a1c2f1a174 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -256,6 +256,7 @@ Available Tasks Medical Transcriptions Classification MPF Clinical Prediction (FHIR) Mortality Prediction (Next Visit) + Decompensation Prediction (MIMIC-III) Mortality Prediction (StageNet MIMIC-IV) Next-Visit Diagnosis Prediction Patient Linkage (MIMIC-III, legacy) diff --git a/docs/api/tasks/pyhealth.tasks.decompensation_mimic3.rst b/docs/api/tasks/pyhealth.tasks.decompensation_mimic3.rst new file mode 100644 index 0000000000..21dfcd8782 --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.decompensation_mimic3.rst @@ -0,0 +1,59 @@ +pyhealth.tasks.decompensation_mimic3 +======================================= + +MIMIC-III hourly 24-hour decompensation prediction task. + +Dataset Configuration +--------------------- + +The default MIMIC-III dataset configuration remains unchanged +for backward compatibility with existing PyHealth tasks. + +For ward-level cohort filtering, this contribution provides a +dedicated configuration, ``mimic3_decompensation.yaml``, which +includes the ``first_wardid`` and ``last_wardid`` attributes. + +Example usage from the repository root: + +.. code-block:: python + + from pyhealth.datasets import MIMIC3Dataset + from pyhealth.tasks import DecompensationMIMIC3 + + dataset = MIMIC3Dataset( + root="/path/to/mimic-iii/1.4", + tables=["chartevents", "labevents"], + dataset_name="mimic3_decompensation", + config_path=( + "pyhealth/datasets/configs/" + "mimic3_decompensation.yaml" + ), + ) + + sample_dataset = dataset.set_task( + DecompensationMIMIC3() + ) + +The dedicated configuration requires source data containing +both ward ID columns. + +Cohort Filtering +---------------- + +The task excludes ICU stays with different first and last +ward IDs or different first and last care units. + +If both ward IDs are unavailable, the task can still process +the stay subject to the remaining cohort criteria. However, +ward ID consistency cannot be verified in this case. + +If only one ward ID is available, the stay is excluded. + +The dedicated configuration preserves the ward ID comparison +used in the reproduction while avoiding changes to the +default MIMIC-III dataset configuration. + +.. autoclass:: pyhealth.tasks.decompensation_mimic3.DecompensationMIMIC3 + :members: + :undoc-members: + :show-inheritance: diff --git a/examples/mortality_prediction/DSA_REPRODUCTION_RESULTS.md b/examples/mortality_prediction/DSA_REPRODUCTION_RESULTS.md new file mode 100644 index 0000000000..82dfb4da95 --- /dev/null +++ b/examples/mortality_prediction/DSA_REPRODUCTION_RESULTS.md @@ -0,0 +1,145 @@ +# DSA Reproduction Results — MIMIC-III + +## Evaluation Setup + +- Task: 24-hour ICU decompensation prediction +- Dataset: MIMIC-III +- Test timesteps: 523,208 +- ICU stays: 6,237 +- Event stays: 490 +- All four DSA variants evaluated on identical records +- DSA evaluation score: risk_h23 +- Metric: Area Under the Precision-Recall Curve (AuPRC) + +## Full-Cohort Test Results + +| Model | Test AuPRC | +|---|---:| +| Vanilla DSA | 0.018762 | +| Bias Initialization | 0.215951 | +| Truncated Likelihood | 0.230058 | +| survTLS | 0.230893 | +| EEP Baseline | 0.233280 | + +EEP uses its corresponding fixed-horizon prediction score. + +These full-test-cohort metrics were recalculated from stored predictions. +They are distinct from the compute-constrained subset training results +reported in `mimic3_decompensation_dsa.py`. The synthetic PyHealth examples +validate the contributed implementation and do not independently reproduce +these MIMIC-III numbers. + +## Reproduction Findings + +- Bias initialization produced the largest improvement. +- Truncated likelihood further improved AuPRC. +- survTLS performed similarly to Truncated. +- EEP slightly outperformed survTLS at the fixed 24-hour horizon. +- The DSA-only ablation ordering is consistent with our earlier subset + experiments; the relative ordering of EEP and survTLS differs. + +## Evaluation Validation + +- All four DSA prediction files contain 523,208 timesteps. +- All four DSA prediction files contain 6,237 ICU stays. +- Stay, time, and label fields match across DSA variants. +- All DSA AuPRC values were recalculated using risk_h23. + +## Additional Clinical Evaluation + +Validation-selected operating points were evaluated on the +independent test cohort. + +At the 70% validation precision target: + +| Metric | EEP | survTLS | +|---|---:|---:| +| Test alarm precision | 0.8029 | 0.7452 | +| Test event recall | 0.1633 | 0.2408 | +| Median lead time (hourly steps) | 5 | 4 | +| False alarms per 100 stays | 1.09 | 2.12 | + +The event-level and clinical-extension comparisons above +were performed for EEP and survTLS, not all DSA variants. + +## Limitations + +- These results come from a specific reproduction setup + and do not establish statistical significance. +- Direct numerical comparison with the original paper + requires matching its evaluation protocol and cohort. +- MIMIC-III patient-level data and predictions are not + included in this public-facing documentation. + +## Evaluation Utility Consistency Check + +The reusable early-event evaluation utility was compared against +the original event-level evaluation implementation using the +same MIMIC-III test predictions. + +Six frozen validation-selected operating points were checked: +60%, 70%, and 80% validation precision targets for EEP and survTLS. + +All six operating points matched across the compared event-level +metrics, including event recall, alarm precision, alarm counts, +detected events, and mean lead time. + +This establishes consistency at the tested operating points, +not universal equivalence across all thresholds or datasets. + +## PMF-Based Patient-Specific Urgency Extension + +The proposed extension combines cumulative event risk with +the predicted temporal distribution of the event. + +Configuration: + +- Prediction horizon: 24 hours +- Near-term horizon: 6 hours +- Alpha: 0.5 +- Numerical stability threshold: 1e-8 +- Event-level evaluation threshold points: 201 +- Alarm silence: 1 hourly step + +### Full-Cohort Event-Level Results + +| Alarm strategy | Event-level AuPRC | +|---|---:| +| EEP fixed horizon | 0.412300 | +| survTLS fixed horizon | 0.421205 | +| Reproduced paper imminent priority | 0.432762 | +| Proposed PMF urgency | 0.429362 | + +The proposed extension outperformed both fixed-horizon +strategies but did not exceed the reproduced imminent +priority strategy. These are reproduction experiment +results, not values reported in the original paper. + +### Numerical Consistency Validation + +The reusable `pmf_urgency_score` function was compared +against saved scores from the original experiments. + +| Check | Validation | Test | +|---|---:|---:| +| Timesteps | 284,959 | 523,208 | +| Record alignment | PASS | PASS | +| Maximum absolute error | 3.33e-16 | 3.33e-16 | +| Score consistency | PASS | PASS | + +All 808,167 timestep scores agreed within numerical +tolerance (rtol=1e-7, atol=1e-10). + +This validates the scoring function against the original +experiment outputs. It does not constitute independent +retraining or recomputation of the complete event-level +evaluation. + +### Reusable Implementation + +- `pmf_urgency.py`: PMF-based urgency scoring and synthetic + usage example. +- `tests/core/test_pmf_urgency.py`: Six synthetic unit tests. + +No patient-level predictions or restricted MIMIC-III +records are distributed with this contribution. diff --git a/examples/mortality_prediction/DSA_SYNTHETIC_PIPELINE_RESULTS.md b/examples/mortality_prediction/DSA_SYNTHETIC_PIPELINE_RESULTS.md new file mode 100644 index 0000000000..a6756e090b --- /dev/null +++ b/examples/mortality_prediction/DSA_SYNTHETIC_PIPELINE_RESULTS.md @@ -0,0 +1,32 @@ +# DSA Synthetic Full-Pipeline Validation + +## Setup +- Data: 12 synthetic ICU patients +- Split: 8 train / 2 validation / 2 test patients +- Hourly samples: 204 / 51 / 51 +- Task: DecompensationMIMIC3 +- Model: DSA (GRU, hidden dimension 16) +- Training: 1 epoch, CPU +- Evaluation metric: Test AuPRC + +## Results + +| Configuration | Synthetic Test AuPRC | +|---|---:| +| Truncated | 0.4706 | +| Truncated + Bias | 0.4659 | +| Truncated + Bias + survTLS | 0.5173 | + +## Validation +- All three variants completed training and evaluation. +- Hourly samples and survival labels were generated by the + DecompensationMIMIC3 task. +- Patient-level train/validation/test separation was used. +- The DSA model was trained through PyHealth Trainer. + +## Limitations +- These are synthetic demonstration results, not MIMIC-III results. +- The synthetic test cohort is small. +- No statistical significance is claimed. +- This example does not independently demonstrate a new + PyHealth Dataset contribution. diff --git a/examples/mortality_prediction/early_event_metrics.py b/examples/mortality_prediction/early_event_metrics.py new file mode 100644 index 0000000000..f49cd0aca2 --- /dev/null +++ b/examples/mortality_prediction/early_event_metrics.py @@ -0,0 +1,131 @@ +"""Transparent event-level evaluation for early-event prediction examples. + +This lightweight example utility deliberately has no dataset or local-file dependency. +Each record is a dict with stay, period_length, last_t, ever_event, +y_true (whether an alarm at that instant is timely), and the score column. +One event at most per stay is assumed. Time units must be consistent. + +This implementation uses *time-based* alarm silence. With silence_steps=1, +an alarm at hour 5 suppresses another at hour 6 (next eligible hour 7). +That equals the source script for contiguous hourly observations, but differs +when observations are missing. It is NOT a drop-in replacement for previous +reported results without protocol equivalence checks. +""" + +from collections import defaultdict +from math import isfinite +from statistics import mean, median + + +def prepare_records(records, score_col="score"): + """Validate and group records by stay, ordered by observation time.""" + grouped = defaultdict(list) + for record in records: + for field in ("stay", "period_length", "last_t", "ever_event", "y_true", score_col): + if field not in record: + raise ValueError(f"Missing required field: {field}") + row = dict(record) + for field in ("period_length", "last_t", score_col): + row[field] = float(row[field]) + if not isfinite(row[field]): + raise ValueError(f"Non-finite {field}") + for field in ("ever_event", "y_true"): + if row[field] not in (0, 1, False, True): + raise ValueError(f"{field} must be 0 or 1") + row[field] = bool(row[field]) + grouped[str(row["stay"])].append(row) + if not grouped: + raise ValueError("At least one observation is required") + for stay, rows in grouped.items(): + rows.sort(key=lambda r: r["period_length"]) + if len({r["period_length"] for r in rows}) != len(rows): + raise ValueError(f"Duplicate observation times in stay {stay}") + if len({r["ever_event"] for r in rows}) != 1: + raise ValueError(f"Inconsistent ever_event within stay {stay}") + if any(r["y_true"] and not r["ever_event"] for r in rows): + raise ValueError(f"Positive y_true in non-event stay {stay}") + return dict(grouped) + + +def evaluate_threshold(grouped, threshold, *, score_col="score", silence_steps=1): + """Evaluate a fixed alarm threshold; no threshold fitting occurs here. + + Precision is None if no alarms; recall is None if no event stays. + False alarms count alarms with y_true=False, even on event stays. + Lead time is measured at the *first timely alarm per event stay*. + """ + if not isfinite(threshold) or silence_steps < 0: + raise ValueError("Invalid threshold or silence_steps") + total = true = detected = event_stays = 0 + leads, per_stay_alarms, per_stay_false = [], [], [] + for rows in grouped.values(): + event_stays += int(rows[0]["ever_event"]) + last_alarm_time = float("-inf") + first_lead = None + n_alarms = n_false = 0 + for row in rows: + now = row["period_length"] + if now <= last_alarm_time + silence_steps: + continue + if row[score_col] < threshold: + continue + last_alarm_time = now + total += 1 + n_alarms += 1 + if row["y_true"]: + true += 1 + if first_lead is None: + first_lead = row["last_t"] + 1.0 - now + else: + n_false += 1 + if first_lead is not None: + detected += 1 + leads.append(float(first_lead)) + per_stay_alarms.append(n_alarms) + per_stay_false.append(n_false) + n_stays = len(grouped) + false_alarms = total - true + return { + "threshold": float(threshold), + "event_recall": detected / event_stays if event_stays else None, + "alarm_precision": true / total if total else None, + "total_alarms": total, + "true_alarms": true, + "false_alarms": false_alarms, + "events": event_stays, + "detected_events": detected, + "stays": n_stays, + "false_alarms_per_100_stays": 100.0 * false_alarms / n_stays, + "mean_lead_steps": mean(leads) if leads else None, + "median_lead_steps": median(leads) if leads else None, + "mean_alarms_per_stay": mean(per_stay_alarms), + "stays_ge2_false_alarms": sum(n >= 2 for n in per_stay_false) / n_stays, + } + + +def select_validation_threshold(validation, thresholds, target_precision, *, score_col="score", silence_steps=1): + """Choose max validation event recall subject to alarm precision constraint. + + Empty-alarm operating points are INELIGIBLE. Tie-break by precision, + then threshold (deterministically). Never reads the test set. + """ + if not 0 <= target_precision <= 1: + raise ValueError("target_precision must be between zero and one") + candidates = [] + for threshold in thresholds: + metric = evaluate_threshold(validation, float(threshold), score_col=score_col, silence_steps=silence_steps) + if metric["total_alarms"] and metric["alarm_precision"] >= target_precision: + candidates.append(metric) + if not candidates: + return None + return max(candidates, key=lambda x: (x["event_recall"] if x["event_recall"] is not None else -1, x["alarm_precision"], x["threshold"])) + + +def evaluate_validation_selected_test(val_records, test_records, thresholds, target_precision, *, score_col="score", silence_steps=1): + """Select threshold only on validation; apply unchanged to test.""" + val = prepare_records(val_records, score_col=score_col) + test = prepare_records(test_records, score_col=score_col) + chosen = select_validation_threshold(val, thresholds, target_precision, score_col=score_col, silence_steps=silence_steps) + if chosen is None: + return {"validation": None, "test": None} + return {"validation": chosen, "test": evaluate_threshold(test, chosen["threshold"], score_col=score_col, silence_steps=silence_steps)} diff --git a/examples/mortality_prediction/mimic3_decompensation_dsa.py b/examples/mortality_prediction/mimic3_decompensation_dsa.py new file mode 100644 index 0000000000..67fca3faa0 --- /dev/null +++ b/examples/mortality_prediction/mimic3_decompensation_dsa.py @@ -0,0 +1,274 @@ +"""Runnable DSA decompensation example with a lightweight synthetic ablation. + +This example demonstrates the PyHealth implementation contributed for +"Dynamic Survival Analysis for Early Event Prediction" (Yeche et al., 2024). +It uses synthetic samples by default so that the complete example can run +without access to protected MIMIC-III data. + +The example compares three configurations at the 24-hour prediction horizon: + +1. Truncated DSA likelihood. +2. Truncated DSA with hazard-prevalence bias initialization. +3. Truncated DSA with bias initialization and survTLS (lengthscale=8). + +The synthetic experiment is intended only as a runnable API demonstration; +its metrics should not be interpreted as reproduction results. + +Compute-constrained MIMIC-III reproduction +------------------------------------------ +Using a fixed 100,000/20,000/50,000 train/validation/test timestep subset, +seed 42, a 2-layer GRU with hidden dimension 128, and the same training +budget across variants, the observed test timestep AuPRCs were: + + Vanilla DSA 0.0196 + + hazard bias initialization 0.2062 + + truncated likelihood 0.2145 + + survTLS 0.2177 + EEP baseline 0.2159 + +These experiments use a reduced compute budget relative to the original +paper and are therefore intended to reproduce the qualitative ablation +trend rather than the paper's absolute reported values. +""" + +from __future__ import annotations + +import numpy as np +import torch +from sklearn.metrics import average_precision_score + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import DSA +from pyhealth.tasks import DecompensationMIMIC3 +from pyhealth.trainer import Trainer + + +SEED = 42 +HORIZON = 24 + + +def _record(steps: int, width: int, rng: np.random.Generator) -> dict: + """Creates one synthetic dynamic sequence.""" + return { + "time": [float(i + 1) for i in range(steps)], + "values": rng.normal(size=(steps, width)).tolist(), + } + + +def build_synthetic_samples( + task: DecompensationMIMIC3, + n_samples: int = 48, +) -> list[dict]: + """Builds deterministic synthetic DSA samples using the task schema.""" + rng = np.random.default_rng(SEED) + samples = [] + + for i in range(n_samples): + steps = 5 + (i % 6) + positive = i % 3 == 0 + + hazard_label = [0.0] * HORIZON + hazard_mask = [1.0] * HORIZON + + if positive: + event_bin = 6 + (i % 13) + event_index = event_bin - 1 + + if task.survtls_lengthscale is None: + hazard_label[event_index] = 1.0 + else: + hazard_label = task._smooth_survival_label(event_bin) + + for k in range(event_bin, HORIZON): + hazard_mask[k] = 0.0 + + samples.append( + { + "patient_id": f"synthetic-{i:03d}", + "dynamic_continuous": _record( + steps, + task.N_CONTINUOUS, + rng, + ), + "dynamic_categorical": _record( + steps, + task.N_CATEGORICAL, + rng, + ), + "dynamic_mask": { + "time": [float(j + 1) for j in range(steps)], + "values": np.ones( + (steps, task.N_MASKS), + dtype=float, + ).tolist(), + }, + "hazard_label": hazard_label, + "hazard_mask": hazard_mask, + "y_true": int(positive), + } + ) + + return samples + + +def make_dataset(samples: list[dict], name: str): + """Creates a PyHealth sample dataset from synthetic DSA samples.""" + task = DecompensationMIMIC3() + return create_sample_dataset( + samples=samples, + input_schema=task.input_schema, + output_schema=task.output_schema, + dataset_name=name, + ) + + +def hazard_prevalence(samples: list[dict]) -> np.ndarray: + """Estimates per-bin hazard prevalence for bias initialization.""" + labels = np.asarray( + [sample["hazard_label"] for sample in samples], + dtype=np.float32, + ) + masks = np.asarray( + [sample["hazard_mask"] for sample in samples], + dtype=np.float32, + ) + + numerator = labels.sum(axis=0) + denominator = masks.sum(axis=0) + + return np.divide( + numerator, + denominator, + out=np.zeros(HORIZON, dtype=np.float32), + where=denominator > 0, + ) + + +@torch.no_grad() +def evaluate_auprc( + model: DSA, + dataloader, +) -> float: + """Evaluates fixed-horizon binary AuPRC.""" + model.eval() + y_true = [] + y_prob = [] + + for batch in dataloader: + output = model(**batch) + y_true.append( + output["y_true"].cpu().numpy().reshape(-1) + ) + y_prob.append( + output["y_prob"].cpu().numpy().reshape(-1) + ) + + return float( + average_precision_score( + np.concatenate(y_true), + np.concatenate(y_prob), + ) + ) + + +def run_variant( + name: str, + use_bias: bool, + use_survtls: bool, +) -> float: + """Trains one lightweight synthetic DSA ablation configuration.""" + torch.manual_seed(SEED) + np.random.seed(SEED) + + task = DecompensationMIMIC3( + horizon_hours=HORIZON, + min_observation_hours=5, + survtls_lengthscale=8.0 if use_survtls else None, + ) + samples = build_synthetic_samples(task) + + train_samples = samples[:32] + val_samples = samples[32:40] + test_samples = samples[40:] + + train_dataset = make_dataset( + train_samples, + f"{name}_train", + ) + val_dataset = make_dataset( + val_samples, + f"{name}_val", + ) + test_dataset = make_dataset( + test_samples, + f"{name}_test", + ) + + train_loader = get_dataloader( + train_dataset, + batch_size=16, + shuffle=True, + ) + val_loader = get_dataloader( + val_dataset, + batch_size=8, + shuffle=False, + ) + test_loader = get_dataloader( + test_dataset, + batch_size=8, + shuffle=False, + ) + + prevalence = ( + hazard_prevalence( + build_synthetic_samples( + DecompensationMIMIC3( + horizon_hours=HORIZON, + min_observation_hours=5, + ), + n_samples=32, + ) + ) + if use_bias + else None + ) + + model = DSA( + dataset=train_dataset, + hidden_dim=16, + max_horizon=HORIZON, + prediction_horizon=HORIZON - 1, + num_layers=1, + dropout=0.0, + hazard_prevalence=prevalence, + ) + + trainer = Trainer(model=model) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=1, + ) + + auprc = evaluate_auprc(model, test_loader) + print(f"{name:24s} synthetic AuPRC = {auprc:.4f}") + return auprc + + +if __name__ == "__main__": + run_variant( + "truncated", + use_bias=False, + use_survtls=False, + ) + run_variant( + "truncated+bias", + use_bias=True, + use_survtls=False, + ) + run_variant( + "truncated+bias+survTLS", + use_bias=True, + use_survtls=True, + ) diff --git a/examples/mortality_prediction/mimic3_decompensation_dsa_full_pipeline.py b/examples/mortality_prediction/mimic3_decompensation_dsa_full_pipeline.py new file mode 100644 index 0000000000..2125390564 --- /dev/null +++ b/examples/mortality_prediction/mimic3_decompensation_dsa_full_pipeline.py @@ -0,0 +1,231 @@ +"""Synthetic patient -> decompensation task -> PyHealth DSA pipeline. + +This example uses no real MIMIC-III records. It exercises the actual +DecompensationMIMIC3.__call__ patient processing rather than hand-crafting +hazard labels. It is intended for course reproducibility/CI demonstrations. + +Run from the PyHealth repository environment with the custom DSA implementation: + python examples/mortality_prediction/mimic3_decompensation_dsa_full_pipeline.py + +This is a task + model integration example, NOT a new BaseDataset contribution. +""" + +from __future__ import annotations + +from datetime import datetime, timedelta +from types import SimpleNamespace +from typing import Any + +import numpy as np +import torch +from sklearn.metrics import average_precision_score + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import DSA +from pyhealth.tasks import DecompensationMIMIC3 +from pyhealth.trainer import Trainer + +SEED = 42 +HORIZON = 24 +T0 = datetime(2020, 1, 1) + + +class FakePatient: + """Minimal synthetic stand-in for a PyHealth Patient event interface.""" + + def __init__(self, patient_id: str, events: dict[str, list[Any]]): + self.patient_id = patient_id + self.events = events + + def get_events(self, event_type: str) -> list[Any]: + return self.events.get(event_type, []) + + +def make_patient(index: int, *, event: bool) -> FakePatient: + """Create one synthetic adult ICU patient with charted observations.""" + patient_id = f"synthetic-{index:03d}" + hadm_id = str(1000 + index) + stay_id = str(2000 + index) + start = T0 + timedelta(days=index * 3) + stay_hours = 30.0 + death_hours = 29.5 if event else None + + stay = SimpleNamespace( + hadm_id=hadm_id, + icustay_id=stay_id, + timestamp=start, + outtime=start + timedelta(hours=stay_hours), + first_wardid="1", + last_wardid="1", + first_careunit="MICU", + last_careunit="MICU", + ) + admission = SimpleNamespace( + hadm_id=hadm_id, + timestamp=start - timedelta(hours=2), + dischtime=start + timedelta(hours=40), + deathtime=( + start + timedelta(hours=death_hours) + if death_hours is not None + else None + ), + ) + demographic = SimpleNamespace( + dob=datetime(1980, 1, 1), + dod=None, + ) + + # Observations are deliberately simple and wholly synthetic. + # Distinct hours provide a time series while preserving the MIMIC item-ID + # mapping used by the actual task implementation. + charts = [ + SimpleNamespace( + icustay_id=stay_id, + hadm_id=hadm_id, + timestamp=start + timedelta(hours=hour, minutes=5), + itemid=220045, + value=str(78 + (index % 4) + hour // 8), + valueuom="bpm", + label="Heart Rate", + ) + for hour in (0, 4, 8, 12, 16, 20, 24) + ] + return FakePatient( + patient_id, + { + "icustays": [stay], + "admissions": [admission], + "patients": [demographic], + "chartevents": charts, + "labevents": [], + }, + ) + + +def make_sample_dataset( + samples: list[dict[str, Any]], + task: DecompensationMIMIC3, + name: str, +): + """Apply PyHealth's feature/label processors to task-generated samples.""" + return create_sample_dataset( + samples=samples, + input_schema=task.input_schema, + output_schema=task.output_schema, + dataset_name=name, + ) + + +def make_partition( + patients: list[FakePatient], task: DecompensationMIMIC3 +) -> list[dict[str, Any]]: + """Generate all hourly records by executing the actual task on patients.""" + samples = [sample for p in patients for sample in task(p)] + if not samples: + raise RuntimeError("Task produced no hourly samples") + labels = {int(sample["y_true"]) for sample in samples} + if labels != {0, 1}: + raise RuntimeError(f"Expected both classes per split; found {labels}") + return samples + + +def validation_auprc(model: DSA, loader) -> float: + """Calculate timestep-level AuPRC on held-out synthetic patients.""" + model.eval() + labels: list[np.ndarray] = [] + scores: list[np.ndarray] = [] + with torch.no_grad(): + for batch in loader: + output = model(**batch) + labels.append(output["y_true"].detach().cpu().numpy().reshape(-1)) + scores.append(output["y_prob"].detach().cpu().numpy().reshape(-1)) + return float( + average_precision_score(np.concatenate(labels), np.concatenate(scores)) + ) + + +def run_variant(name: str, *, use_bias: bool, use_survtls: bool) -> float: + """Train/evaluate a DSA variant on task-generated synthetic patient data.""" + torch.manual_seed(SEED) + np.random.seed(SEED) + + task = DecompensationMIMIC3( + horizon_hours=HORIZON, + min_observation_hours=5, + survtls_lengthscale=8.0 if use_survtls else None, + ) + + # Split by PATIENT, not hourly sample: no patient's timepoints leak + # between training, validation, and evaluation. + patients = [make_patient(i, event=(i % 2 == 0)) for i in range(12)] + train_patients, val_patients, test_patients = ( + patients[:8], patients[8:10], patients[10:12] + ) + train_samples = make_partition(train_patients, task) + val_samples = make_partition(val_patients, task) + test_samples = make_partition(test_patients, task) + print( + f"{name}: patients 8/2/2, hourly samples " + f"{len(train_samples)}/{len(val_samples)}/{len(test_samples)}" + ) + + train_ds = make_sample_dataset(train_samples, task, f"{name}_train") + val_ds = make_sample_dataset(val_samples, task, f"{name}_val") + test_ds = make_sample_dataset(test_samples, task, f"{name}_test") + + train_loader = get_dataloader(train_ds, batch_size=16, shuffle=True) + val_loader = get_dataloader(val_ds, batch_size=16, shuffle=False) + test_loader = get_dataloader(test_ds, batch_size=16, shuffle=False) + + prevalence = None + if use_bias: + # Training-only estimates, not validation/test labels. + hazards = np.asarray( + [sample["hazard_label"] for sample in train_samples], dtype=float + ) + masks = np.asarray( + [sample["hazard_mask"] for sample in train_samples], dtype=float + ) + prevalence = np.divide( + (hazards * masks).sum(axis=0), + masks.sum(axis=0), + out=np.zeros(HORIZON, dtype=float), + where=masks.sum(axis=0) > 0, + ).astype(np.float32) + + model = DSA( + dataset=train_ds, + hidden_dim=16, + max_horizon=HORIZON, + prediction_horizon=HORIZON - 1, + num_layers=1, + dropout=0.0, + hazard_prevalence=prevalence, + ) + trainer = Trainer(model=model) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=1, + ) + auprc = validation_auprc(model, test_loader) + print(f"{name:28s} synthetic task-to-model test AuPRC = {auprc:.4f}") + return auprc + + +if __name__ == "__main__": + results = { + "truncated": run_variant( + "truncated", use_bias=False, use_survtls=False + ), + "truncated+bias": run_variant( + "truncated+bias", use_bias=True, use_survtls=False + ), + "truncated+bias+survTLS": run_variant( + "truncated+bias+survTLS", use_bias=True, use_survtls=True + ), + } + print("\nSynthetic full-pipeline example completed:") + for variant, score in results.items(): + print(f" {variant}: AuPRC={score:.4f}") + print("These synthetic scores are not MIMIC-III reproduction results.") diff --git a/examples/mortality_prediction/pmf_urgency.py b/examples/mortality_prediction/pmf_urgency.py new file mode 100644 index 0000000000..b832d6123c --- /dev/null +++ b/examples/mortality_prediction/pmf_urgency.py @@ -0,0 +1,72 @@ +"""PMF-based urgency score for 24-hour early-event prediction. + +The score combines total event risk, the conditional probability of an +event within the first six hours, and conditional expected-time imminence. +It is a ranking score, not a calibrated event probability. +""" + +import numpy as np + + +def pmf_urgency_score( + pmf: np.ndarray, near_horizon: int = 6, alpha: float = 0.5 +) -> np.ndarray: + """Compute the urgency score used in the DSA reproduction extension. + + Args: + pmf: Array of shape (n_samples, 24), containing unconditional event + probability masses for hours 1 through 24. Rows may sum to less + than one because an event may occur beyond the horizon. + near_horizon: Number of near-term hourly bins. + alpha: Weight on near-term share; 1 - alpha weights imminence. + + Returns: + One urgency score per row. Risk at or below 1e-8 yields zero, + matching the original experiment's zero-risk convention. + + Raises: + ValueError: If the input shape, probability masses or parameters + are invalid. + + Example: + >>> pmf = np.zeros((2, 24)) + >>> pmf[0, 0] = pmf[1, 23] = 0.5 + >>> pmf_urgency_score(pmf).tolist() + [0.5, 0.0] + """ + pmf = np.asarray(pmf, dtype=np.float64) + if pmf.ndim != 2 or pmf.shape[1] != 24: + raise ValueError("pmf must have shape (n_samples, 24)") + if not isinstance(near_horizon, (int, np.integer)) or not 1 <= near_horizon <= 24: + raise ValueError("near_horizon must be an integer in [1, 24]") + if not 0.0 <= alpha <= 1.0: + raise ValueError("alpha must be in [0, 1]") + if not np.isfinite(pmf).all() or (pmf < 0).any(): + raise ValueError("pmf must contain finite, nonnegative masses") + + risk = pmf.sum(axis=1) + if (risk > 1.0 + 1e-6).any(): + raise ValueError("PMF row sums must not exceed one (within tolerance)") + hours = np.arange(1, 25, dtype=np.float64) + valid = risk > 1e-8 + near_share = np.divide( + pmf[:, :near_horizon].sum(axis=1), + risk, + out=np.zeros_like(risk), + where=valid, + ) + expected_tte = np.divide( + (pmf * hours[None, :]).sum(axis=1), + risk, + out=np.full_like(risk, 24), + where=valid, + ) + imminence = np.clip(1.0 - (expected_tte - 1.0) / 23.0, 0.0, 1.0) + return risk * (alpha * near_share + (1.0 - alpha) * imminence) + + +if __name__ == "__main__": + pmf = np.zeros((3, 24)) + pmf[0, 0] = pmf[1, 11] = pmf[2, 23] = 0.5 + for hour, score in zip((1, 12, 24), pmf_urgency_score(pmf)): + print(f"Event mass at hour {hour:2d}: urgency={score:.6f}") diff --git a/pyhealth/datasets/configs/mimic3_decompensation.yaml b/pyhealth/datasets/configs/mimic3_decompensation.yaml new file mode 100644 index 0000000000..3ef6472eb4 --- /dev/null +++ b/pyhealth/datasets/configs/mimic3_decompensation.yaml @@ -0,0 +1,284 @@ +version: "1.4" +tables: + patients: + file_path: "PATIENTS.csv.gz" + patient_id: "subject_id" + timestamp: null + attributes: + - "gender" + - "dob" + - "dod" + - "dod_hosp" + - "dod_ssn" + - "expire_flag" + + admissions: + file_path: "ADMISSIONS.csv.gz" + patient_id: "subject_id" + timestamp: "admittime" + attributes: + - "hadm_id" + - "admission_type" + - "admission_location" + - "insurance" + - "language" + - "religion" + - "marital_status" + - "ethnicity" + - "edregtime" + - "edouttime" + - "deathtime" + - "diagnosis" + - "discharge_location" + - "dischtime" + - "hospital_expire_flag" + + icustays: + file_path: "ICUSTAYS.csv.gz" + patient_id: "subject_id" + timestamp: "intime" + attributes: + - "hadm_id" + - "icustay_id" + - "first_careunit" + - "dbsource" + - "last_careunit" + - "first_wardid" + - "last_wardid" + - "outtime" + + diagnoses_icd: + file_path: "DIAGNOSES_ICD.csv.gz" + patient_id: "subject_id" + join: + - file_path: "ADMISSIONS.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + timestamp: "dischtime" + attributes: + - "hadm_id" + - "icd9_code" + - "seq_num" + + prescriptions: + file_path: "PRESCRIPTIONS.csv.gz" + patient_id: "subject_id" + timestamp: "startdate" + join: + - file_path: "ADMISSIONS.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + attributes: + - "hadm_id" + - "drug" + - "drug_type" + - "drug_name_poe" + - "drug_name_generic" + - "formulary_drug_cd" + - "gsn" + - "ndc" + - "prod_strength" + - "dose_val_rx" + - "dose_unit_rx" + - "form_val_disp" + - "form_unit_disp" + - "route" + - "enddate" + + procedures_icd: + file_path: "PROCEDURES_ICD.csv.gz" + patient_id: "subject_id" + join: + - file_path: "ADMISSIONS.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + timestamp: "dischtime" + attributes: + - "hadm_id" + - "icd9_code" + - "seq_num" + + services: + file_path: "SERVICES.csv.gz" + patient_id: "subject_id" + timestamp: "transfertime" + attributes: + - "hadm_id" + - "prev_service" + - "curr_service" + + drgcodes: + file_path: "DRGCODES.csv.gz" + patient_id: "subject_id" + join: + - file_path: "ADMISSIONS.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + timestamp: "dischtime" + attributes: + - "hadm_id" + - "drg_type" + - "drg_code" + - "description" + - "drg_severity" + - "drg_mortality" + + cptevents: + file_path: "CPTEVENTS.csv.gz" + patient_id: "subject_id" + timestamp: "chartdate" + attributes: + - "hadm_id" + - "costcenter" + - "cpt_cd" + - "cpt_number" + - "cpt_suffix" + - "ticket_id_seq" + - "sectionheader" + - "subsectionheader" + - "description" + + labevents: + file_path: "LABEVENTS.csv.gz" + patient_id: "subject_id" + join: + - file_path: "D_LABITEMS.csv.gz" + "on": "itemid" + how: "inner" + columns: + - "label" + - "fluid" + - "category" + timestamp: "charttime" + attributes: + - "hadm_id" + - "itemid" + - "label" + - "fluid" + - "category" + - "value" + - "valuenum" + - "valueuom" + - "flag" + + noteevents: + file_path: "NOTEEVENTS.csv.gz" + patient_id: "subject_id" + join: + - file_path: "ADMISSIONS.csv.gz" + "on": "hadm_id" + how: "inner" + columns: + - "dischtime" + timestamp: + - "charttime" + attributes: + - "row_id" + - "hadm_id" + - "text" + - "category" + - "description" + - "storetime" + + transfers: + file_path: "TRANSFERS.csv.gz" + patient_id: "subject_id" + timestamp: "intime" + attributes: + - "hadm_id" + - "icustay_id" + - "dbsource" + - "eventtype" + - "prev_careunit" + - "curr_careunit" + - "outtime" + + microbiologyevents: + file_path: "MICROBIOLOGYEVENTS.csv.gz" + patient_id: "subject_id" + timestamp: "chartdate" + attributes: + - "hadm_id" + - "charttime" + - "spec_itemid" + - "spec_type_desc" + - "org_itemid" + - "org_name" + + chartevents: + file_path: "CHARTEVENTS.csv.gz" + patient_id: "subject_id" + timestamp: "charttime" + attributes: + - "hadm_id" + - "icustay_id" + - "itemid" + - "value" + - "valuenum" + - "valueuom" + + outputevents: + file_path: "OUTPUTEVENTS.csv.gz" + patient_id: "subject_id" + timestamp: "charttime" + attributes: + - "hadm_id" + - "icustay_id" + - "itemid" + - "value" + - "valueuom" + + inputevents_cv: + file_path: "INPUTEVENTS_CV.csv.gz" + patient_id: "subject_id" + timestamp: "charttime" + attributes: + - "hadm_id" + - "icustay_id" + - "itemid" + - "amount" + - "amountuom" + - "rate" + - "rateuom" + - "orderid" + - "linkorderid" + + inputevents_mv: + file_path: "INPUTEVENTS_MV.csv.gz" + patient_id: "subject_id" + timestamp: "starttime" + attributes: + - "hadm_id" + - "icustay_id" + - "itemid" + - "endtime" + - "amount" + - "amountuom" + - "rate" + - "rateuom" + - "patientweight" + - "orderid" + - "linkorderid" + - "ordercategoryname" + - "statusdescription" + + procedureevents_mv: + file_path: "PROCEDUREEVENTS_MV.csv.gz" + patient_id: "subject_id" + timestamp: "starttime" + attributes: + - "hadm_id" + - "icustay_id" + - "itemid" + - "endtime" + - "value" + - "valueuom" + - "statusdescription" diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 6526791a3f..f5cffaf1e6 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -198,3 +198,4 @@ medtok_keys as medtok_keys, ) from .query_focused_ehr import QueryFocusedEHRModel as QueryFocusedEHRModel +from .dsa import DSA as DSA diff --git a/pyhealth/models/dsa.py b/pyhealth/models/dsa.py new file mode 100644 index 0000000000..a4e7afcf53 --- /dev/null +++ b/pyhealth/models/dsa.py @@ -0,0 +1,388 @@ +"""Dynamic Survival Analysis model for early event prediction. + +Contributors: + Zhipeng Zhou + Xinyue Zuo + +Related paper: + Dynamic Survival Analysis for Early Event Prediction + https://proceedings.mlr.press/v248/yeche24a.html + +This module implements the DSA model and discrete-time survival outputs for +integration with PyHealth. +""" + +from collections.abc import Sequence +from typing import Any + +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.utils.rnn import pack_padded_sequence, pad_sequence + +from pyhealth.datasets import SampleDataset +from pyhealth.models import BaseModel + + +class DSA(BaseModel): + """Dynamic Survival Analysis model for early event prediction. + + DSA models the discrete-time conditional hazard of an event over a future + prediction horizon. Each input timestep combines continuous measurements, + categorical measurements, and observation masks. A linear timestep + embedding and GRU encode the observed history, and a hazard head predicts + one conditional hazard probability for each future time bin. + + The model computes its own masked discrete-time survival loss rather than + using a standard PyHealth label-processor loss. It additionally returns the + probability mass function, survival function, cumulative risk, and a + fixed-horizon event probability. + + Args: + dataset: Processed PyHealth sample dataset containing + ``dynamic_continuous``, ``dynamic_categorical``, ``dynamic_mask``, + ``hazard_label``, ``hazard_mask``, and ``y_true`` fields. + hidden_dim: Size of the timestep embedding and GRU hidden state. + max_horizon: Number of future discrete hazard bins predicted. + prediction_horizon: Zero-based cumulative-risk index returned as + ``y_prob``. For hourly bins, index 23 represents risk through the + first 24 future hours. + num_layers: Number of stacked GRU layers. + dropout: Dropout probability between GRU layers. PyTorch applies GRU + dropout only when ``num_layers > 1``. + hazard_prevalence: Optional per-bin hazard prevalence used to initialize + the hazard-head bias logits. + l1_reg_embedding: Weight applied to the mean absolute value of the + timestep-embedding parameters. + + Examples: + >>> from pyhealth.datasets import create_sample_dataset, get_dataloader + >>> from pyhealth.models import DSA + >>> from pyhealth.tasks import DecompensationMIMIC3 + >>> task = DecompensationMIMIC3() + >>> sample = { + ... "patient_id": "synthetic-0", + ... "dynamic_continuous": {"time": [1.0], "values": [[0.0] * 12]}, + ... "dynamic_categorical": {"time": [1.0], "values": [[0.0] * 47]}, + ... "dynamic_mask": {"time": [1.0], "values": [[1.0] * 17]}, + ... "hazard_label": [0.0] * 24, + ... "hazard_mask": [1.0] * 24, + ... "y_true": 0, + ... } + >>> positive = dict(sample, patient_id="synthetic-1", y_true=1) + >>> positive["hazard_label"] = [0.0] * 23 + [1.0] + >>> dataset = create_sample_dataset( + ... samples=[sample, positive], + ... input_schema=task.input_schema, + ... output_schema=task.output_schema, + ... dataset_name="dsa_example", + ... ) + >>> model = DSA(dataset, hidden_dim=8) + >>> batch = next(iter(get_dataloader(dataset, batch_size=2))) + >>> model(**batch)["hazard"].shape + torch.Size([2, 24]) + + Raises: + ValueError: If a model hyperparameter is invalid or the dataset is + missing required inputs or outputs. + """ + + @property + def label_processors(self) -> dict[str, Any]: + """Disable standard label-processor loss for the custom survival loss.""" + return {} + + def __init__( + self, + dataset: SampleDataset, + hidden_dim: int = 128, + max_horizon: int = 24, + prediction_horizon: int = 23, + num_layers: int = 1, + dropout: float = 0.0, + hazard_prevalence: Sequence[float] | torch.Tensor | None = None, + l1_reg_embedding: float = 0.0, + ) -> None: + super().__init__(dataset) + + if hidden_dim <= 0: + raise ValueError("hidden_dim must be positive.") + if max_horizon <= 0: + raise ValueError("max_horizon must be positive.") + if not 0 <= prediction_horizon < max_horizon: + raise ValueError( + "prediction_horizon must satisfy " + "0 <= prediction_horizon < max_horizon." + ) + if num_layers <= 0: + raise ValueError("num_layers must be positive.") + if not 0.0 <= dropout < 1.0: + raise ValueError("dropout must be in [0, 1).") + if l1_reg_embedding < 0.0: + raise ValueError("l1_reg_embedding must be non-negative.") + + self.hidden_dim = hidden_dim + self.max_horizon = max_horizon + self.prediction_horizon = prediction_horizon + self.l1_reg_embedding = l1_reg_embedding + + required_inputs = { + "dynamic_continuous", + "dynamic_categorical", + "dynamic_mask", + } + missing = required_inputs - set(dataset.input_schema) + if missing: + raise ValueError(f"Missing DSA inputs: {sorted(missing)}") + + required_outputs = {"hazard_label", "hazard_mask", "y_true"} + missing = required_outputs - set(dataset.output_schema) + if missing: + raise ValueError(f"Missing DSA outputs: {sorted(missing)}") + + sample = dataset[0] + continuous_dim = int(sample["dynamic_continuous"][0].shape[-1]) + categorical_dim = int(sample["dynamic_categorical"][0].shape[-1]) + mask_dim = int(sample["dynamic_mask"][0].shape[-1]) + self.input_dim = continuous_dim + categorical_dim + mask_dim + + self.time_step_embedding = nn.Linear(self.input_dim, hidden_dim) + + self.gru = nn.GRU( + hidden_dim, + hidden_dim, + num_layers=num_layers, + dropout=dropout if num_layers > 1 else 0.0, + batch_first=True, + ) + + self.hazard_head = nn.Linear(hidden_dim, max_horizon) + + if hazard_prevalence is not None: + self.initialize_hazard_bias(hazard_prevalence) + + def initialize_hazard_bias( + self, + hazard_prevalence: Sequence[float] | torch.Tensor, + ) -> None: + """Initialize hazard-head biases from per-bin prevalence. + + Args: + hazard_prevalence: Sequence containing one event prevalence value + for each discrete future hazard bin. + + Raises: + ValueError: If the number of prevalence values does not equal + ``max_horizon``. + """ + prevalence = torch.as_tensor( + hazard_prevalence, + dtype=self.hazard_head.bias.dtype, + device=self.hazard_head.bias.device, + ).flatten() + + if prevalence.numel() != self.max_horizon: + raise ValueError( + "hazard_prevalence must contain exactly " + f"{self.max_horizon} values, got {prevalence.numel()}." + ) + + prevalence = prevalence.clamp(1e-7, 1.0 - 1e-7) + + with torch.no_grad(): + self.hazard_head.bias.copy_(torch.logit(prevalence)) + + def embedding_l1_loss(self) -> torch.Tensor: + """Compute L1 regularization for the timestep embedding. + + Returns: + Mean absolute value across all timestep-embedding parameters. + """ + params = list(self.time_step_embedding.parameters()) + n_params = sum(p.numel() for p in params) + return sum(p.abs().sum() for p in params) / n_params + + @staticmethod + def _unpack( + field: tuple[torch.Tensor, ...], + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + if len(field) != 3: + raise ValueError( + "DSA expects jagged fields as " + "(values, time, offsets)." + ) + return field + + @staticmethod + def _pad( + values: torch.Tensor, + offsets: torch.Tensor, + ) -> tuple[torch.Tensor, torch.Tensor]: + sequences = [ + values[offsets[i] : offsets[i + 1]] + for i in range(len(offsets) - 1) + ] + + if any(len(sequence) == 0 for sequence in sequences): + raise ValueError( + "DSA requires at least one observation per sample." + ) + + lengths = torch.tensor( + [len(sequence) for sequence in sequences], + dtype=torch.long, + device=values.device, + ) + + return pad_sequence(sequences, batch_first=True), lengths + + def forward(self, **batch: Any) -> dict[str, torch.Tensor]: + """Run a forward pass and compute the discrete survival loss. + + Args: + **batch: Batched PyHealth fields. The three dynamic inputs must be + ``jagged`` tuples of ``(values, time, offsets)``. + ``hazard_label`` and ``hazard_mask`` must have shape + ``(batch_size, max_horizon)``. + + Returns: + Dictionary containing ``loss``, ``survival_loss``, ``l1_loss``, + ``y_prob``, ``y_true``, ``logit``, ``hazard_logit``, ``hazard``, + ``pmf``, ``survival``, ``cumulative_risk``, and ``embed``. + + Raises: + ValueError: If sequence metadata are inconsistent or survival + targets do not match the configured horizon. + """ + continuous, continuous_time, continuous_offsets = self._unpack( + batch["dynamic_continuous"] + ) + categorical, categorical_time, categorical_offsets = self._unpack( + batch["dynamic_categorical"] + ) + observation_mask, mask_time, mask_offsets = self._unpack( + batch["dynamic_mask"] + ) + + continuous = continuous.to(self.device) + categorical = categorical.to(self.device) + observation_mask = observation_mask.to(self.device) + + continuous_time = continuous_time.to(self.device) + categorical_time = categorical_time.to(self.device) + mask_time = mask_time.to(self.device) + + continuous_offsets = continuous_offsets.to(self.device) + categorical_offsets = categorical_offsets.to(self.device) + mask_offsets = mask_offsets.to(self.device) + + if not torch.equal(continuous_offsets, categorical_offsets): + raise ValueError( + "Continuous and categorical offsets do not match." + ) + if not torch.equal(continuous_offsets, mask_offsets): + raise ValueError("Continuous and mask offsets do not match.") + if not torch.equal(continuous_time, categorical_time): + raise ValueError("Continuous and categorical times do not match.") + if not torch.equal(continuous_time, mask_time): + raise ValueError("Continuous and mask times do not match.") + + values = torch.cat( + [continuous, categorical, observation_mask], + dim=-1, + ) + + values = self.time_step_embedding(values) + + padded, lengths = self._pad(values, continuous_offsets) + + packed = pack_padded_sequence( + padded, + lengths.cpu(), + batch_first=True, + enforce_sorted=False, + ) + + _, hidden = self.gru(packed) + representation = hidden[-1] + + hazard_logit = self.hazard_head(representation) + hazard = torch.sigmoid(hazard_logit) + + survival = torch.cumprod(1.0 - hazard, dim=-1) + + survival_before = torch.cat( + [ + torch.ones( + hazard.shape[0], + 1, + dtype=hazard.dtype, + device=hazard.device, + ), + survival[:, :-1], + ], + dim=-1, + ) + + pmf = survival_before * hazard + cumulative_risk = 1.0 - survival + + hazard_label = batch["hazard_label"].to(self.device).float() + hazard_mask = batch["hazard_mask"].to(self.device).float() + + if hazard_label.shape != hazard_logit.shape: + raise ValueError( + f"hazard_label shape {hazard_label.shape} " + f"does not match {hazard_logit.shape}." + ) + + if hazard_mask.shape != hazard_logit.shape: + raise ValueError( + f"hazard_mask shape {hazard_mask.shape} " + f"does not match {hazard_logit.shape}." + ) + + survival_loss = F.binary_cross_entropy_with_logits( + hazard_logit, + hazard_label, + reduction="none", + ) + survival_loss = ( + survival_loss * hazard_mask + ).sum(dim=-1).mean() + + l1_loss = ( + self.l1_reg_embedding * self.embedding_l1_loss() + if self.l1_reg_embedding > 0.0 + else survival_loss.new_zeros(()) + ) + + loss = survival_loss + l1_loss + + y_true = batch["y_true"].to( + self.device + ).float().reshape(-1, 1) + + y_prob = cumulative_risk[ + :, + self.prediction_horizon : self.prediction_horizon + 1, + ] + + logit = torch.logit( + y_prob.clamp(1e-7, 1.0 - 1e-7) + ) + + return { + "loss": loss, + "survival_loss": survival_loss, + "l1_loss": l1_loss, + "y_prob": y_prob, + "y_true": y_true, + "logit": logit, + "hazard_logit": hazard_logit, + "hazard": hazard, + "pmf": pmf, + "survival": survival, + "cumulative_risk": cumulative_risk, + "embed": representation, + } diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index e0bde093f7..8fd04b4593 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -358,3 +358,4 @@ def __getattr__(name: str): return PTBXLSuperclassClassification raise AttributeError(f"module {__name__!r} has no attribute {name!r}") +from .decompensation_mimic3 import DecompensationMIMIC3 as DecompensationMIMIC3 diff --git a/pyhealth/tasks/decompensation_mimic3.py b/pyhealth/tasks/decompensation_mimic3.py new file mode 100644 index 0000000000..1d41004c6c --- /dev/null +++ b/pyhealth/tasks/decompensation_mimic3.py @@ -0,0 +1,877 @@ +"""MIMIC-III 24-hour decompensation task for dynamic survival analysis. + +Contributors: + Zhipeng Zhou + Xinyue Zuo + +Related paper: + Dynamic Survival Analysis for Early Event Prediction + https://proceedings.mlr.press/v248/yeche24a.html + +This module implements hourly MIMIC-III decompensation sample generation and +survival targets for DSA-style early event prediction. +""" + +from __future__ import annotations + +import math +from datetime import datetime +from typing import Any, ClassVar + +import numpy as np + +from .base_task import BaseTask + + +class DecompensationMIMIC3(BaseTask): + """Hourly decompensation prediction for MIMIC-III ICU stays. + + Each sample represents one hourly prediction time during an ICU stay. + Clinical measurements are mapped to the 17 MIMIC-III benchmark channels + and encoded as 12 continuous features, 47 categorical one-hot features, + and 17 observation-mask features, for 76 dynamic features per timestep. + + The prediction target is represented as a discrete-time survival target + over ``horizon_hours`` future hourly bins. ``hazard_label`` identifies the + event bin, ``hazard_mask`` identifies observed future bins, and ``y_true`` + indicates whether death occurs strictly within the prediction horizon. + + The cohort follows the MIMIC-III benchmark convention of adult ICU stays + and excludes transfers between wards or care units within the stay. + + Args: + horizon_hours: Number of future hourly hazard bins. Defaults to 24. + min_observation_hours: Earliest ICU hour at which a prediction sample + may be generated. Defaults to 5. + survtls_lengthscale: Optional survTLS Gaussian smoothing lengthscale. + When provided, event-time survival targets are smoothed using the + paper's released-code formulation. For MIMIC-III decompensation, + the paper uses a lengthscale of 8. Defaults to None. + + Examples: + >>> from pyhealth.tasks import DecompensationMIMIC3 + >>> task = DecompensationMIMIC3(horizon_hours=24, survtls_lengthscale=8.0) + >>> task.horizon_hours + 24 + >>> sorted(task.output_schema) + ['hazard_label', 'hazard_mask', 'y_true'] + + Apply the configured task to a MIMIC-III patient to generate hourly + samples, or pass it to the dataset's task-processing interface. + + Returns: + Samples containing dynamic continuous, categorical, and observation + mask sequences together with discrete-time survival targets. + """ + + task_name: str = "DecompensationMIMIC3" + + CHANNELS: ClassVar[tuple[str, ...]] = ( + "Capillary refill rate", + "Diastolic blood pressure", + "Fraction inspired oxygen", + "Glascow coma scale eye opening", + "Glascow coma scale motor response", + "Glascow coma scale total", + "Glascow coma scale verbal response", + "Glucose", + "Heart Rate", + "Height", + "Mean blood pressure", + "Oxygen saturation", + "Respiratory rate", + "Systolic blood pressure", + "Temperature", + "Weight", + "pH", + ) + + CATEGORICAL_VALUES: ClassVar[dict[str, tuple[str, ...]]] = { + "Capillary refill rate": ("0.0", "1.0"), + "Glascow coma scale eye opening": ( + "To Pain", + "3 To speech", + "1 No Response", + "4 Spontaneously", + "None", + "To Speech", + "Spontaneously", + "2 To pain", + ), + "Glascow coma scale motor response": ( + "1 No Response", + "3 Abnorm flexion", + "Abnormal extension", + "No response", + "4 Flex-withdraws", + "Localizes Pain", + "Flex-withdraws", + "Obeys Commands", + "Abnormal Flexion", + "6 Obeys Commands", + "5 Localizes Pain", + "2 Abnorm extensn", + ), + "Glascow coma scale total": ( + "11", "10", "13", "12", "15", "14", + "3", "5", "4", "7", "6", "9", "8", + ), + "Glascow coma scale verbal response": ( + "1 No Response", + "No Response", + "Confused", + "Inappropriate Words", + "Oriented", + "No Response-ETT", + "5 Oriented", + "Incomprehensible sounds", + "1.0 ET/Trach", + "4 Confused", + "2 Incomp sounds", + "3 Inapprop words", + ), + } + + CHARTEVENT_ITEMIDS: ClassVar[dict[int, str]] = { + 115: "Capillary refill rate", + 3348: "Capillary refill rate", + 8377: "Capillary refill rate", + 8368: "Diastolic blood pressure", + 8440: "Diastolic blood pressure", + 8441: "Diastolic blood pressure", + 8502: "Diastolic blood pressure", + 8503: "Diastolic blood pressure", + 8504: "Diastolic blood pressure", + 8507: "Diastolic blood pressure", + 8508: "Diastolic blood pressure", + 8555: "Diastolic blood pressure", + 220051: "Diastolic blood pressure", + 220180: "Diastolic blood pressure", + 224643: "Diastolic blood pressure", + 225310: "Diastolic blood pressure", + 189: "Fraction inspired oxygen", + 727: "Fraction inspired oxygen", + 3420: "Fraction inspired oxygen", + 3422: "Fraction inspired oxygen", + 223835: "Fraction inspired oxygen", + 184: "Glascow coma scale eye opening", + 220739: "Glascow coma scale eye opening", + 454: "Glascow coma scale motor response", + 223901: "Glascow coma scale motor response", + 198: "Glascow coma scale total", + 723: "Glascow coma scale verbal response", + 223900: "Glascow coma scale verbal response", + 807: "Glucose", + 811: "Glucose", + 1529: "Glucose", + 3745: "Glucose", + 220621: "Glucose", + 225664: "Glucose", + 226537: "Glucose", + 211: "Heart Rate", + 220045: "Heart Rate", + 1394: "Height", + 226707: "Height", + 226730: "Height", + 52: "Mean blood pressure", + 224: "Mean blood pressure", + 456: "Mean blood pressure", + 6702: "Mean blood pressure", + 6927: "Mean blood pressure", + 220052: "Mean blood pressure", + 220181: "Mean blood pressure", + 224322: "Mean blood pressure", + 225312: "Mean blood pressure", + 646: "Oxygen saturation", + 834: "Oxygen saturation", + 8498: "Oxygen saturation", + 220227: "Oxygen saturation", + 220277: "Oxygen saturation", + 614: "Respiratory rate", + 615: "Respiratory rate", + 618: "Respiratory rate", + 651: "Respiratory rate", + 3603: "Respiratory rate", + 220210: "Respiratory rate", + 224422: "Respiratory rate", + 224689: "Respiratory rate", + 224690: "Respiratory rate", + 51: "Systolic blood pressure", + 442: "Systolic blood pressure", + 455: "Systolic blood pressure", + 6701: "Systolic blood pressure", + 220050: "Systolic blood pressure", + 220179: "Systolic blood pressure", + 224167: "Systolic blood pressure", + 225309: "Systolic blood pressure", + 227243: "Systolic blood pressure", + 676: "Temperature", + 677: "Temperature", + 678: "Temperature", + 679: "Temperature", + 3654: "Temperature", + 3655: "Temperature", + 223761: "Temperature", + 223762: "Temperature", + 763: "Weight", + 3580: "Weight", + 3581: "Weight", + 3582: "Weight", + 3693: "Weight", + 224639: "Weight", + 226512: "Weight", + 226531: "Weight", + 780: "pH", + 860: "pH", + 1126: "pH", + 1673: "pH", + 3839: "pH", + 4202: "pH", + 4753: "pH", + 220274: "pH", + 223830: "pH", + } + + LABEVENT_ITEMIDS: ClassVar[dict[int, str]] = { + 50809: "Glucose", + 50931: "Glucose", + 51478: "Glucose", + 50817: "Oxygen saturation", + 50820: "pH", + 50831: "pH", + 51094: "pH", + 51491: "pH", + } + + N_CONTINUOUS: ClassVar[int] = 12 + N_CATEGORICAL: ClassVar[int] = 47 + N_VALUE_FEATURES: ClassVar[int] = 59 + N_MASKS: ClassVar[int] = 17 + N_DYNAMIC_FEATURES: ClassVar[int] = 76 + + NORMAL_VALUES: ClassVar[dict[str, float | str]] = { + "Capillary refill rate": "0.0", + "Diastolic blood pressure": 59.0, + "Fraction inspired oxygen": 0.21, + "Glascow coma scale eye opening": "4 Spontaneously", + "Glascow coma scale motor response": "6 Obeys Commands", + "Glascow coma scale total": "15", + "Glascow coma scale verbal response": "5 Oriented", + "Glucose": 128.0, + "Heart Rate": 86.0, + "Height": 170.0, + "Mean blood pressure": 77.0, + "Oxygen saturation": 98.0, + "Respiratory rate": 19.0, + "Systolic blood pressure": 118.0, + "Temperature": 36.6, + "Weight": 81.0, + "pH": 7.4, + } + + CONTINUOUS_MEANS: ClassVar[tuple[float, ...]] = ( + 61.73746731237323, + 0.2941986945120962, + 140.38699662380586, + 85.53853938464474, + 169.80350234321443, + 79.59640838796953, + 104.98108350952208, + 19.867925156740334, + 122.3975667186341, + 36.94399135355236, + 83.76208973419455, + 7.207267791681239, + ) + + CONTINUOUS_STDS: ClassVar[tuple[float, ...]] = ( + 221.89647947315552, + 0.1714931950435367, + 1766.7412133808477, + 57.11693013941011, + 6.222631784123813, + 148.53013549514117, + 5135.238732591619, + 7.3213287278950965, + 141.3988560835634, + 5.277914736088037, + 27.233083363220278, + 1.6568268628593597, + ) + + input_schema: ClassVar[dict[str, Any]] = { + "dynamic_continuous": ( + "jagged", + { + "levels": [ + { + "ordering": "series", + "values": [N_CONTINUOUS], + } + ] + }, + ), + "dynamic_categorical": ( + "jagged", + { + "levels": [ + { + "ordering": "series", + "values": [N_CATEGORICAL], + } + ] + }, + ), + "dynamic_mask": ( + "jagged", + { + "levels": [ + { + "ordering": "series", + "values": [N_MASKS], + } + ] + }, + ), +} + output_schema: ClassVar[dict[str, Any]] = { + "hazard_label": "tensor", + "hazard_mask": "tensor", + "y_true": "binary", + } + + @staticmethod + def _parse_float(value: Any) -> float | None: + if value is None: + return None + + text = str(value).strip() + if not text or text.lower() in {"nan", "none", "error"}: + return None + + try: + return float(text) + except (TypeError, ValueError): + return None + + @classmethod + def _clean_value( + cls, + channel: str, + value: Any, + valueuom: Any = None, + label: Any = None, + ) -> float | str | None: + text = "" if value is None else str(value).strip() + unit = "" if valueuom is None else str(valueuom).lower() + item_label = "" if label is None else str(label).lower() + + if channel == "Capillary refill rate": + if text in {"Normal <3 secs", "Brisk"}: + return "0.0" + if text in {"Abnormal >3 secs", "Delayed"}: + return "1.0" + return None + + if channel == "Systolic blood pressure": + if "/" in text: + parts = text.split("/") + if len(parts) == 2: + return cls._parse_float(parts[0]) + return cls._parse_float(text) + + if channel == "Diastolic blood pressure": + if "/" in text: + parts = text.split("/") + if len(parts) == 2: + return cls._parse_float(parts[1]) + return cls._parse_float(text) + + if channel in {"Glucose", "pH"}: + return cls._parse_float(text) + + if channel == "Oxygen saturation": + numeric = cls._parse_float(text) + if numeric is None: + return None + if numeric <= 1: + numeric *= 100.0 + return numeric + + if channel == "Fraction inspired oxygen": + numeric = cls._parse_float(text) + if numeric is None: + return None + + if "torr" not in unit: + numeric /= 100.0 + + return numeric + + if channel == "Temperature": + numeric = cls._parse_float(text) + if numeric is None: + return None + + if numeric >= 79: + numeric = (numeric - 32.0) * 5.0 / 9.0 + + return numeric + + if channel == "Weight": + numeric = cls._parse_float(text) + if numeric is None: + return None + + if "oz" in unit or "oz" in item_label: + numeric /= 16.0 + numeric *= 0.453592 + elif "lb" in unit or "lb" in item_label: + numeric *= 0.453592 + + return numeric + + if channel == "Height": + numeric = cls._parse_float(text) + if numeric is None: + return None + + if "in" in unit or "in" in item_label: + numeric = round(numeric * 2.54) + + return numeric + + if channel in cls.CATEGORICAL_VALUES: + return text if text in cls.CATEGORICAL_VALUES[channel] else None + + return cls._parse_float(text) + + @classmethod + def _hourly_observations( + cls, + patient: Any, + stay: Any, + intime: datetime, + outtime: datetime, + ) -> dict[int, dict[str, float | str]]: + hourly: dict[int, dict[str, float | str]] = {} + observations: list[tuple[datetime, str, float | str]] = [] + + icustay_id = getattr(stay, "icustay_id", None) + hadm_id = getattr(stay, "hadm_id", None) + + for event in patient.get_events(event_type="chartevents"): + event_stay_id = getattr(event, "icustay_id", None) + if ( + icustay_id is not None + and event_stay_id is not None + and str(event_stay_id) != str(icustay_id) + ): + continue + + timestamp = cls._to_datetime(getattr(event, "timestamp", None)) + if timestamp is None or timestamp < intime or timestamp > outtime: + continue + + try: + itemid = int(getattr(event, "itemid", None)) + except (TypeError, ValueError): + continue + + channel = cls.CHARTEVENT_ITEMIDS.get(itemid) + if channel is None: + continue + + value = cls._clean_value( + channel, + getattr(event, "value", None), + getattr(event, "valueuom", None), + getattr(event, "label", None), + ) + if value is not None: + observations.append((timestamp, channel, value)) + + for event in patient.get_events(event_type="labevents"): + event_hadm_id = getattr(event, "hadm_id", None) + if ( + hadm_id is not None + and event_hadm_id is not None + and str(event_hadm_id) != str(hadm_id) + ): + continue + + timestamp = cls._to_datetime(getattr(event, "timestamp", None)) + if timestamp is None or timestamp < intime or timestamp > outtime: + continue + + try: + itemid = int(getattr(event, "itemid", None)) + except (TypeError, ValueError): + continue + + channel = cls.LABEVENT_ITEMIDS.get(itemid) + if channel is None: + continue + + value = cls._clean_value( + channel, + getattr(event, "value", None), + getattr(event, "valueuom", None), + getattr(event, "label", None), + ) + if value is not None: + observations.append((timestamp, channel, value)) + + observations.sort(key=lambda x: x[0]) + + for timestamp, channel, value in observations: + hours = (timestamp - intime).total_seconds() / 3600.0 + bin_id = int(hours - 1e-6) + bin_id = max(bin_id, 0) + hourly.setdefault(bin_id, {})[channel] = value + + return hourly + + @classmethod + def _value_feature_names(cls) -> list[str]: + names: list[str] = [] + + for channel in cls.CHANNELS: + if channel in cls.CATEGORICAL_VALUES: + for value in cls.CATEGORICAL_VALUES[channel]: + names.append(f"{channel}->{value}") + else: + names.append(channel) + + return names + + @classmethod + def _build_dynamic( + cls, + hourly: dict[int, dict[str, float | str]], + end_hour: int, + ) -> tuple[dict[str, Any], dict[str, Any], dict[str, Any]]: + if end_hour < 1: + raise ValueError("end_hour must be at least 1") + + continuous_channels = [ + channel + for channel in cls.CHANNELS + if channel not in cls.CATEGORICAL_VALUES + ] + + continuous_index = { + channel: i + for i, channel in enumerate(continuous_channels) + } + + categorical_names: list[str] = [] + for channel in cls.CHANNELS: + if channel in cls.CATEGORICAL_VALUES: + for value in cls.CATEGORICAL_VALUES[channel]: + categorical_names.append(f"{channel}->{value}") + + categorical_index = { + name: i + for i, name in enumerate(categorical_names) + } + + continuous = np.zeros( + (end_hour, cls.N_CONTINUOUS), + dtype=float, + ) + categorical = np.zeros( + (end_hour, cls.N_CATEGORICAL), + dtype=float, + ) + masks = np.zeros( + (end_hour, cls.N_MASKS), + dtype=float, + ) + + previous: dict[str, float | str] = {} + + for hour in range(end_hour): + observed = hourly.get(hour, {}) + + for channel_id, channel in enumerate(cls.CHANNELS): + is_observed = channel in observed + + if is_observed: + current = observed[channel] + previous[channel] = current + elif channel in previous: + current = previous[channel] + else: + current = cls.NORMAL_VALUES[channel] + + if channel in cls.CATEGORICAL_VALUES: + feature_name = f"{channel}->{current}" + feature_id = categorical_index.get(feature_name) + + if feature_id is None: + normal = cls.NORMAL_VALUES[channel] + feature_name = f"{channel}->{normal}" + feature_id = categorical_index[feature_name] + + categorical[hour, feature_id] = 1.0 + else: + feature_id = continuous_index[channel] + value = float(current) + continuous[hour, feature_id] = ( + value - cls.CONTINUOUS_MEANS[feature_id] + ) / cls.CONTINUOUS_STDS[feature_id] + + masks[hour, channel_id] = float(is_observed) + + time = [float(hour + 1) for hour in range(end_hour)] + + return ( + {"time": time, "values": continuous}, + {"time": time, "values": categorical}, + {"time": time, "values": masks}, + ) + + def __init__( + self, + horizon_hours: int = 24, + min_observation_hours: int = 5, + survtls_lengthscale: float | None = None, + ) -> None: + super().__init__() + if horizon_hours < 1: + raise ValueError("horizon_hours must be positive") + if min_observation_hours < 0: + raise ValueError("min_observation_hours must be non-negative") + if survtls_lengthscale is not None and survtls_lengthscale <= 0: + raise ValueError("survtls_lengthscale must be positive") + + self.horizon_hours = int(horizon_hours) + self.min_observation_hours = int(min_observation_hours) + self.survtls_lengthscale = ( + float(survtls_lengthscale) + if survtls_lengthscale is not None + else None + ) + + @staticmethod + def _normal_cdf(x: float, mean: float, std: float) -> float: + z = (x - mean) / (std * math.sqrt(2.0)) + return 0.5 * (1.0 + math.erf(z)) + + def _smooth_survival_label(self, event_bin: int) -> list[float]: + if self.survtls_lengthscale is None: + raise ValueError("survtls_lengthscale is not configured") + + mean = float(event_bin) + std = mean / self.survtls_lengthscale + pmf = [0.0] * self.horizon_hours + + for k in range(1, self.horizon_hours + 1): + lower = k - 0.5 + upper = k + 0.5 + pmf[k - 1] = ( + self._normal_cdf(upper, mean, std) + - self._normal_cdf(lower, mean, std) + ) + + pmf[0] = self._normal_cdf(1.5, mean, std) + pmf[-1] = 1.0 - self._normal_cdf( + self.horizon_hours - 0.5, + mean, + std, + ) + + return pmf + + @staticmethod + def _to_datetime(value: Any) -> datetime | None: + if value is None: + return None + if isinstance(value, datetime): + return value + + value = str(value).strip() + if not value or value.lower() in {"nan", "nat", "none"}: + return None + + try: + return datetime.fromisoformat(value) + except ValueError: + return None + + @staticmethod + def _in_interval( + value: datetime | None, + start: datetime | None, + end: datetime | None, + ) -> bool: + return ( + value is not None + and start is not None + and end is not None + and start <= value <= end + ) + + def __call__(self, patient: Any) -> list[dict[str, Any]]: + """Generate hourly decompensation samples for one patient. + + Args: + patient: PyHealth patient containing MIMIC-III admissions, ICU + stays, chart events, lab events, and patient demographics. + + Returns: + List of hourly prediction samples. Patients or stays that do not + satisfy cohort or minimum-observation requirements return no + samples. + """ + stays = patient.get_events(event_type="icustays") + admissions = patient.get_events(event_type="admissions") + patient_rows = patient.get_events(event_type="patients") + + if not stays or not admissions: + return [] + + admissions_by_hadm = { + str(event.hadm_id): event + for event in admissions + if getattr(event, "hadm_id", None) is not None + } + + dob = None + dod = None + if patient_rows: + dob = self._to_datetime(getattr(patient_rows[0], "dob", None)) + dod = self._to_datetime(getattr(patient_rows[0], "dod", None)) + + samples: list[dict[str, Any]] = [] + + for stay in stays: + hadm_id = getattr(stay, "hadm_id", None) + if hadm_id is None: + continue + + hadm_id = str(hadm_id) + admission = admissions_by_hadm.get(hadm_id) + if admission is None: + continue + + first_wardid = getattr(stay, "first_wardid", None) + last_wardid = getattr(stay, "last_wardid", None) + first_careunit = getattr(stay, "first_careunit", None) + last_careunit = getattr(stay, "last_careunit", None) + + if ( + first_wardid != last_wardid + or first_careunit != last_careunit + ): + continue + + intime = self._to_datetime(getattr(stay, "timestamp", None)) + outtime = self._to_datetime(getattr(stay, "outtime", None)) + admittime = self._to_datetime(getattr(admission, "timestamp", None)) + dischtime = self._to_datetime(getattr(admission, "dischtime", None)) + deathtime = self._to_datetime(getattr(admission, "deathtime", None)) + + if intime is None or outtime is None: + continue + if outtime <= intime: + continue + + if dob is not None: + age_years = (intime - dob).total_seconds() / (365.0 * 86400.0) + if age_years < 0: + age_years = 90 + if age_years < 18: + continue + + mortality = ( + self._in_interval(dod, admittime, dischtime) + or self._in_interval(deathtime, admittime, dischtime) + ) + + death_time = deathtime + + observed_end = outtime + if death_time is not None and death_time < observed_end: + observed_end = death_time + + observed_hours = ( + observed_end - intime + ).total_seconds() / 3600.0 + + if observed_hours < self.min_observation_hours: + continue + + hourly = self._hourly_observations( + patient, + stay, + intime, + outtime, + ) + + last_prediction_hour = math.floor(observed_hours) + + for t in range( + self.min_observation_hours, + last_prediction_hour + 1, + ): + if not any(hour < t for hour in hourly): + continue + remaining_observed = max(0.0, observed_hours - t) + + observed_bins = min( + self.horizon_hours, + math.ceil(remaining_observed), + ) + + hazard_label = [0.0] * self.horizon_hours + hazard_mask = [0.0] * self.horizon_hours + + for k in range(observed_bins): + hazard_mask[k] = 1.0 + + y_true = 0 + + if mortality and death_time is not None: + delta = ( + death_time - intime + ).total_seconds() / 3600.0 - t + + # MIMIC benchmark uses death within strictly < 24 hours. + if 0.0 < delta < self.horizon_hours: + y_true = 1 + event_bin = math.ceil(delta) + event_index = event_bin - 1 + + if self.survtls_lengthscale is not None: + hazard_label = self._smooth_survival_label(event_bin) + else: + hazard_label[event_index] = 1.0 + + for k in range(event_bin, self.horizon_hours): + hazard_mask[k] = 0.0 + + ( + dynamic_continuous, + dynamic_categorical, + dynamic_mask, + ) = self._build_dynamic(hourly, t) + + samples.append( + { + "patient_id": patient.patient_id, + "hadm_id": hadm_id, + "icustay_id": getattr(stay, "icustay_id", None), + "prediction_time": float(t), + "mortality": int(mortality), + "dynamic_continuous": dynamic_continuous, + "dynamic_categorical": dynamic_categorical, + "dynamic_mask": dynamic_mask, + "hazard_label": hazard_label, + "hazard_mask": hazard_mask, + "y_true": y_true, + } + ) + + return samples diff --git a/tests/core/test_decompensation_mimic3.py b/tests/core/test_decompensation_mimic3.py new file mode 100644 index 0000000000..a9d2e0ae37 --- /dev/null +++ b/tests/core/test_decompensation_mimic3.py @@ -0,0 +1,295 @@ +import math +import unittest +from datetime import datetime, timedelta +from types import SimpleNamespace + +import numpy as np + +from pyhealth.tasks.decompensation_mimic3 import DecompensationMIMIC3 + +T0 = datetime(2020, 1, 1, 0, 0, 0) + + +class FakePatient: + def __init__(self, events): + self.patient_id = "p1" + self.events = events + + def get_events(self, event_type): + return self.events.get(event_type, []) + + +def _patient(death_hours=29.5, stay_hours=30.0): + stay = SimpleNamespace( + hadm_id="100", + icustay_id="200", + timestamp=T0, + outtime=T0 + timedelta(hours=stay_hours), + first_wardid="1", + last_wardid="1", + first_careunit="MICU", + last_careunit="MICU", + ) + admission = SimpleNamespace( + hadm_id="100", + timestamp=T0 - timedelta(hours=2), + dischtime=T0 + timedelta(hours=40), + deathtime=( + None if death_hours is None else T0 + timedelta(hours=death_hours) + ), + ) + patient_row = SimpleNamespace( + dob=datetime(1980, 1, 1), + dod=None, + ) + chart = [ + SimpleNamespace( + icustay_id="200", + hadm_id="100", + timestamp=T0 + timedelta(minutes=5), + itemid=220045, + value="80", + valueuom="bpm", + label="Heart Rate", + ) + ] + return FakePatient( + { + "icustays": [stay], + "admissions": [admission], + "patients": [patient_row], + "chartevents": chart, + "labevents": [], + } + ) + + +class TestDecompensationMIMIC3(unittest.TestCase): + def test_dynamic_shapes_and_normalization(self): + task = DecompensationMIMIC3() + hourly = { + 0: { + "Diastolic blood pressure": 100.0, + "Heart Rate": 80.0, + } + } + continuous, categorical, mask = task._build_dynamic(hourly, 2) + + self.assertEqual(continuous["values"].shape, (2, 12)) + self.assertEqual(categorical["values"].shape, (2, 47)) + self.assertEqual(mask["values"].shape, (2, 17)) + + dbp = [ + c + for c in task.CHANNELS + if c not in task.CATEGORICAL_VALUES + ].index("Diastolic blood pressure") + expected = ( + 100.0 - task.CONTINUOUS_MEANS[dbp] + ) / task.CONTINUOUS_STDS[dbp] + + self.assertAlmostEqual( + continuous["values"][0, dbp], + expected, + ) + self.assertAlmostEqual( + continuous["values"][1, dbp], + expected, + ) + + dbp_mask = task.CHANNELS.index("Diastolic blood pressure") + self.assertEqual(mask["values"][0, dbp_mask], 1.0) + self.assertEqual(mask["values"][1, dbp_mask], 0.0) + + def test_normal_value_imputation(self): + task = DecompensationMIMIC3() + continuous, categorical, mask = task._build_dynamic({}, 1) + + continuous_channels = [ + c + for c in task.CHANNELS + if c not in task.CATEGORICAL_VALUES + ] + + for i, channel in enumerate(continuous_channels): + expected = ( + float(task.NORMAL_VALUES[channel]) + - task.CONTINUOUS_MEANS[i] + ) / task.CONTINUOUS_STDS[i] + self.assertAlmostEqual( + continuous["values"][0, i], + expected, + ) + + self.assertTrue(np.all(mask["values"] == 0.0)) + self.assertEqual( + categorical["values"].sum(), + len(task.CATEGORICAL_VALUES), + ) + + def test_decompensation_labels_and_hazard(self): + task = DecompensationMIMIC3() + samples = task(_patient()) + + self.assertEqual(len(samples), 25) + self.assertEqual(samples[0]["prediction_time"], 5.0) + self.assertEqual(samples[-1]["prediction_time"], 29.0) + + by_time = { + int(sample["prediction_time"]): sample + for sample in samples + } + + self.assertEqual(by_time[5]["y_true"], 0) + self.assertEqual(sum(by_time[5]["hazard_label"]), 0.0) + + self.assertEqual(by_time[6]["y_true"], 1) + self.assertEqual( + by_time[6]["hazard_label"][23], + 1.0, + ) + self.assertEqual( + sum(by_time[6]["hazard_mask"]), + 24.0, + ) + + self.assertEqual(by_time[29]["y_true"], 1) + self.assertEqual( + by_time[29]["hazard_label"][0], + 1.0, + ) + self.assertEqual( + sum(by_time[29]["hazard_mask"]), + 1.0, + ) + + def test_survtls_invalid_lengthscale(self): + with self.assertRaises(ValueError): + DecompensationMIMIC3(survtls_lengthscale=0.0) + + with self.assertRaises(ValueError): + DecompensationMIMIC3(survtls_lengthscale=-1.0) + + def test_survtls_smoothed_label(self): + task = DecompensationMIMIC3(survtls_lengthscale=8.0) + + event_bin = 12 + label = task._smooth_survival_label(event_bin) + + self.assertEqual(len(label), 24) + self.assertTrue(all(0.0 <= value <= 1.0 for value in label)) + self.assertAlmostEqual(sum(label), 1.0, places=6) + + mean = float(event_bin) + std = mean / 8.0 + + def cdf(x): + z = (x - mean) / (std * math.sqrt(2.0)) + return 0.5 * (1.0 + math.erf(z)) + + expected = [ + cdf(k + 0.5) - cdf(k - 0.5) + for k in range(1, 25) + ] + expected[0] = cdf(1.5) + expected[-1] = 1.0 - cdf(23.5) + + np.testing.assert_allclose( + label, + expected, + rtol=1e-7, + atol=1e-7, + ) + + def test_survtls_task_generation(self): + task = DecompensationMIMIC3(survtls_lengthscale=8.0) + samples = task(_patient()) + + by_time = { + int(sample["prediction_time"]): sample + for sample in samples + } + + hard_task = DecompensationMIMIC3() + hard_samples = hard_task(_patient()) + hard_by_time = { + int(sample["prediction_time"]): sample + for sample in hard_samples + } + + # At t=6, death is in the 24th future hourly bin. + smooth = by_time[6]["hazard_label"] + hard = hard_by_time[6]["hazard_label"] + + self.assertAlmostEqual(sum(smooth), 1.0, places=6) + self.assertGreater(sum(value > 0.0 for value in smooth), 1) + self.assertEqual(hard[23], 1.0) + self.assertEqual(sum(hard), 1.0) + + # survTLS changes training labels, not the binary EEP target. + self.assertEqual(by_time[6]["y_true"], hard_by_time[6]["y_true"]) + self.assertEqual( + by_time[6]["hazard_mask"], + hard_by_time[6]["hazard_mask"], + ) + + def test_survivor_has_no_positive_labels(self): + task = DecompensationMIMIC3() + samples = task(_patient(death_hours=None)) + + self.assertGreater(len(samples), 0) + self.assertTrue( + all(sample["y_true"] == 0 for sample in samples) + ) + self.assertTrue( + all( + sum(sample["hazard_label"]) == 0.0 + for sample in samples + ) + ) + + + def test_same_ward_ids_retains_stay(self): + task = DecompensationMIMIC3() + patient = _patient() + self.assertEqual(len(task(patient)), 25) + + def test_different_ward_ids_excludes_stay(self): + task = DecompensationMIMIC3() + patient = _patient() + stay = patient.get_events("icustays")[0] + stay.last_wardid = "2" + + self.assertEqual(task(patient), []) + + def test_missing_both_ward_ids_retains_stay(self): + task = DecompensationMIMIC3() + patient = _patient() + stay = patient.get_events("icustays")[0] + + del stay.first_wardid + del stay.last_wardid + + self.assertEqual(len(task(patient)), 25) + + def test_missing_one_ward_id_excludes_stay(self): + task = DecompensationMIMIC3() + + for field in ("first_wardid", "last_wardid"): + with self.subTest(field=field): + patient = _patient() + stay = patient.get_events("icustays")[0] + delattr(stay, field) + + self.assertEqual(task(patient), []) + + def test_different_careunits_excludes_stay(self): + task = DecompensationMIMIC3() + patient = _patient() + stay = patient.get_events("icustays")[0] + stay.last_careunit = "SICU" + + self.assertEqual(task(patient), []) + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_dsa.py b/tests/core/test_dsa.py new file mode 100644 index 0000000000..4544b33b0a --- /dev/null +++ b/tests/core/test_dsa.py @@ -0,0 +1,323 @@ +import unittest + +import numpy as np +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import DSA +from pyhealth.tasks import DecompensationMIMIC3 + + +MAX_HORIZON = 25 +PREDICTION_HORIZON = 24 + + +def _record(steps, width, seed): + rng = np.random.default_rng(seed) + return { + "time": [float(i + 1) for i in range(steps)], + "values": rng.normal(size=(steps, width)).tolist(), + } + + +def _dataset(horizon=MAX_HORIZON): + task = DecompensationMIMIC3(horizon_hours=horizon) + samples = [] + + for i, steps in enumerate([5, 7, 6, 9]): + hazard_label = [0.0] * horizon + hazard_mask = [1.0] * horizon + y_true = i % 2 + + if y_true: + event_index = 4 + i + hazard_label[event_index] = 1.0 + for k in range(event_index + 1, horizon): + hazard_mask[k] = 0.0 + + samples.append( + { + "patient_id": f"p{i}", + "dynamic_continuous": _record( + steps, + task.N_CONTINUOUS, + 10 + i, + ), + "dynamic_categorical": _record( + steps, + task.N_CATEGORICAL, + 20 + i, + ), + "dynamic_mask": { + "time": [ + float(j + 1) + for j in range(steps) + ], + "values": np.ones( + (steps, task.N_MASKS) + ).tolist(), + }, + "hazard_label": hazard_label, + "hazard_mask": hazard_mask, + "y_true": y_true, + } + ) + + return create_sample_dataset( + samples=samples, + input_schema=task.input_schema, + output_schema=task.output_schema, + dataset_name="dsa_test", + ) + + +class TestDSA(unittest.TestCase): + def test_default_model_matches_default_task_horizon(self): + dataset = _dataset(horizon=24) + model = DSA(dataset, hidden_dim=8) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + output = model(**batch) + self.assertEqual(model.max_horizon, 24) + self.assertEqual(model.prediction_horizon, 23) + self.assertEqual(output["hazard"].shape, (4, 24)) + torch.testing.assert_close( + output["y_prob"], output["cumulative_risk"][:, 23:24] + ) + + def test_forward_backward_and_shapes(self): + dataset = _dataset() + model = DSA( + dataset, + hidden_dim=8, + max_horizon=MAX_HORIZON, + prediction_horizon=PREDICTION_HORIZON, + dropout=0.0, + ) + + self.assertEqual(model.label_processors, {}) + self.assertEqual(model.input_dim, 76) + self.assertEqual(model.max_horizon, 25) + self.assertEqual(model.prediction_horizon, 24) + + batch = next( + iter(get_dataloader(dataset, batch_size=4)) + ) + out = model(**batch) + + self.assertEqual( + out["hazard"].shape, + (4, MAX_HORIZON), + ) + self.assertEqual( + out["pmf"].shape, + (4, MAX_HORIZON), + ) + self.assertEqual( + out["survival"].shape, + (4, MAX_HORIZON), + ) + self.assertEqual( + out["cumulative_risk"].shape, + (4, MAX_HORIZON), + ) + self.assertEqual(out["y_prob"].shape, (4, 1)) + self.assertEqual(out["y_true"].shape, (4, 1)) + self.assertEqual(out["embed"].shape, (4, 8)) + + torch.testing.assert_close( + out["y_prob"], + out["cumulative_risk"][ + :, + PREDICTION_HORIZON: + PREDICTION_HORIZON + 1, + ], + ) + + self.assertTrue(torch.isfinite(out["loss"])) + out["loss"].backward() + + grads = [ + p.grad + for p in model.parameters() + if p.requires_grad + ] + self.assertTrue( + any( + g is not None + and torch.any(g != 0) + for g in grads + ) + ) + + def test_survival_probability_identities(self): + dataset = _dataset() + model = DSA( + dataset, + hidden_dim=8, + max_horizon=MAX_HORIZON, + prediction_horizon=PREDICTION_HORIZON, + ) + + batch = next( + iter(get_dataloader(dataset, batch_size=4)) + ) + + model.eval() + + with torch.no_grad(): + out = model(**batch) + + hazard = out["hazard"] + survival = out["survival"] + pmf = out["pmf"] + cumulative = out["cumulative_risk"] + + expected_survival = torch.cumprod( + 1.0 - hazard, + dim=-1, + ) + + torch.testing.assert_close( + survival, + expected_survival, + ) + torch.testing.assert_close( + cumulative, + 1.0 - survival, + ) + + survival_before = torch.cat( + [ + torch.ones( + hazard.shape[0], + 1, + dtype=hazard.dtype, + ), + survival[:, :-1], + ], + dim=-1, + ) + + torch.testing.assert_close( + pmf, + survival_before * hazard, + ) + + self.assertTrue( + torch.all( + cumulative[:, 1:] + >= cumulative[:, :-1] - 1e-7 + ) + ) + + self.assertTrue( + torch.all( + survival[:, 1:] + <= survival[:, :-1] + 1e-7 + ) + ) + + def test_prevalence_bias_initialization(self): + dataset = _dataset() + + prevalence = torch.linspace( + 0.001, + 0.025, + MAX_HORIZON, + ) + + model = DSA( + dataset, + hidden_dim=8, + max_horizon=MAX_HORIZON, + prediction_horizon=PREDICTION_HORIZON, + hazard_prevalence=prevalence, + ) + + expected = torch.logit(prevalence) + + torch.testing.assert_close( + model.hazard_head.bias.detach(), + expected, + ) + + torch.testing.assert_close( + torch.sigmoid( + model.hazard_head.bias.detach() + ), + prevalence, + ) + + def test_rejects_wrong_bias_length(self): + dataset = _dataset() + + with self.assertRaises(ValueError): + DSA( + dataset, + max_horizon=MAX_HORIZON, + prediction_horizon=PREDICTION_HORIZON, + hazard_prevalence=[0.01] * 24, + ) + + def test_ragged_sequences(self): + dataset = _dataset() + + model = DSA( + dataset, + hidden_dim=8, + max_horizon=MAX_HORIZON, + prediction_horizon=PREDICTION_HORIZON, + ) + + batch = next( + iter(get_dataloader(dataset, batch_size=4)) + ) + + offsets = batch["dynamic_continuous"][2] + lengths = offsets[1:] - offsets[:-1] + + self.assertEqual( + lengths.tolist(), + [5, 7, 6, 9], + ) + + out = model(**batch) + + self.assertEqual( + out["embed"].shape, + (4, 8), + ) + + def test_invalid_horizons(self): + dataset = _dataset() + + with self.assertRaises(ValueError): + DSA( + dataset, + max_horizon=24, + prediction_horizon=24, + ) + + +if __name__ == "__main__": + unittest.main() + +def test_dsa_state_dict_roundtrip(): + dataset = _dataset() + model = DSA( + dataset=dataset, + hidden_dim=8, + max_horizon=24, + prediction_horizon=23, + ) + + restored = DSA( + dataset=dataset, + hidden_dim=8, + max_horizon=24, + prediction_horizon=23, + ) + restored.load_state_dict(model.state_dict()) + + for original, loaded in zip(model.parameters(), restored.parameters()): + assert torch.equal(original, loaded) diff --git a/tests/core/test_early_event_metrics.py b/tests/core/test_early_event_metrics.py new file mode 100644 index 0000000000..703f8c4baa --- /dev/null +++ b/tests/core/test_early_event_metrics.py @@ -0,0 +1,72 @@ +"""Synthetic tests. Run: python -m unittest -v test_early_event_metrics.py""" +import unittest +import sys +from pathlib import Path + +EXAMPLE_DIR = Path(__file__).resolve().parents[2] / "examples" / "mortality_prediction" +sys.path.insert(0, str(EXAMPLE_DIR)) + +from early_event_metrics import ( + prepare_records, evaluate_threshold, evaluate_validation_selected_test, + select_validation_threshold, +) + + +def row(stay, time, score, label=0, event=False, last_t=9): + return {"stay": stay, "period_length": time, "last_t": last_t, + "ever_event": int(event), "y_true": label, "score": score} + + +class EventEvaluationTests(unittest.TestCase): + def test_counts_recall_precision_and_false_alarms(self): + records = [row("a", 2, .9, 1, True), row("a", 4, .8, 1, True), + row("b", 1, .9), row("c", 3, .1, 0, True)] + result = evaluate_threshold(prepare_records(records), .5) + self.assertEqual(result["total_alarms"], 3) + self.assertEqual(result["true_alarms"], 2) + self.assertEqual(result["false_alarms"], 1) + self.assertEqual(result["detected_events"], 1) + self.assertAlmostEqual(result["event_recall"], .5) + self.assertAlmostEqual(result["alarm_precision"], 2/3) + self.assertAlmostEqual(result["false_alarms_per_100_stays"], 100/3) + self.assertAlmostEqual(result["median_lead_steps"], 8) + + def test_silence_uses_times_not_row_positions(self): + data = prepare_records([row("a", 1, .8), row("a", 3, .8)]) + self.assertEqual(evaluate_threshold(data, .5, silence_steps=1)["total_alarms"], 2) + data = prepare_records([row("a", 1, .8), row("a", 2, .8)]) + self.assertEqual(evaluate_threshold(data, .5, silence_steps=1)["total_alarms"], 1) + + def test_no_alarms_is_not_perfect_precision(self): + result = evaluate_threshold(prepare_records([row("a", 1, .1, event=True)]), .9) + self.assertIsNone(result["alarm_precision"]) + self.assertEqual(result["event_recall"], 0.0) + + def test_no_events_has_undefined_recall(self): + result = evaluate_threshold(prepare_records([row("a", 1, .9)]), .5) + self.assertIsNone(result["event_recall"]) + + def test_validation_threshold_is_frozen_on_test(self): + validation = [row("a", 1, .9, 1, True), row("b", 1, .4)] + test = [row("c", 1, .4, 1, True), row("d", 1, .9)] + out = evaluate_validation_selected_test(validation, test, [.4, .9], .75) + self.assertEqual(out["validation"]["threshold"], .9) + self.assertEqual(out["test"]["threshold"], .9) + self.assertEqual(out["test"]["event_recall"], 0) + self.assertEqual(out["test"]["alarm_precision"], 0) + + def test_threshold_without_alarm_is_not_eligible(self): + data = prepare_records([row("a", 1, .2, 1, True)]) + self.assertIsNone(select_validation_threshold(data, [1.0], .7)) + + def test_reject_duplicate_times(self): + with self.assertRaises(ValueError): + prepare_records([row("a", 1, .2), row("a", 1, .3)]) + + def test_reject_inconsistent_event_status(self): + with self.assertRaises(ValueError): + prepare_records([row("a", 1, .2, event=True), row("a", 2, .3, event=False)]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_pmf_urgency.py b/tests/core/test_pmf_urgency.py new file mode 100644 index 0000000000..b3ec498d4d --- /dev/null +++ b/tests/core/test_pmf_urgency.py @@ -0,0 +1,62 @@ +"""Synthetic regression tests for the PMF urgency extension.""" + +import numpy as np +import pytest + +from examples.mortality_prediction.pmf_urgency import pmf_urgency_score + + +def test_equal_risk_earlier_event_has_higher_urgency(): + pmf = np.zeros((3, 24)) + pmf[0, 0] = pmf[1, 11] = pmf[2, 23] = 0.5 + scores = pmf_urgency_score(pmf) + np.testing.assert_allclose(scores, [0.5, 0.25 * (1 - 11 / 23), 0.0]) + assert scores[0] > scores[1] > scores[2] + + +def test_mixed_event_time_matches_hand_calculation(): + pmf = np.zeros((1, 24)) + pmf[0, 2] = 0.2 + pmf[0, 11] = 0.4 + expected = 0.6 * (0.5 * (0.2 / 0.6) + 0.5 * (1 - (9 - 1) / 23)) + np.testing.assert_allclose(pmf_urgency_score(pmf), [expected]) + + +def test_zero_and_negligible_risk(): + pmf = np.zeros((2, 24)) + pmf[1, 0] = 1e-8 + np.testing.assert_array_equal(pmf_urgency_score(pmf), [0.0, 0.0]) + + +def test_alpha_and_near_horizon_configuration(): + pmf = np.zeros((1, 24)) + pmf[0, 5] = 0.4 + np.testing.assert_allclose(pmf_urgency_score(pmf, alpha=1.0), [0.4]) + np.testing.assert_allclose( + pmf_urgency_score(pmf, near_horizon=5, alpha=1.0), [0.0] + ) + np.testing.assert_allclose( + pmf_urgency_score(pmf, alpha=0.0), [0.4 * (1 - 5 / 23)] + ) + + +def test_score_bounded_by_total_event_risk(): + pmf = np.random.default_rng(42).dirichlet(np.ones(25), size=10)[:, :24] + scores = pmf_urgency_score(pmf) + assert np.all(scores >= 0.0) + assert np.all(scores <= pmf.sum(axis=1) + 1e-12) + + +def test_reject_invalid_pmf_and_parameters(): + with pytest.raises(ValueError): + pmf_urgency_score(np.zeros((1, 23))) + with pytest.raises(ValueError): + pmf_urgency_score(np.full((1, 24), -0.1)) + with pytest.raises(ValueError): + pmf_urgency_score(np.full((1, 24), np.nan)) + with pytest.raises(ValueError): + pmf_urgency_score(np.ones((1, 24))) + with pytest.raises(ValueError): + pmf_urgency_score(np.zeros((1, 24)), alpha=1.1) + with pytest.raises(ValueError): + pmf_urgency_score(np.zeros((1, 24)), near_horizon=0)