diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 88af307576..4348362998 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -339,6 +339,7 @@ Available Tasks Value Set Pair Classification (VSAC) Time-to-event survival (GBSG and SUPPORT) TCGA RNA-seq Survival Prediction + Hourly remaining ICU LOS Query-Focused EHR Summarization (MIMIC-III) Multi-event survival (Rotterdam) Vasopressor Onset (MIMIC-III) diff --git a/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst new file mode 100644 index 0000000000..7acff7904c --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.tpc_eicu.rst @@ -0,0 +1,116 @@ +.. Contributors: Manling Tan, Yining Jin, Xiao Luo +.. NetIDs: manling4, yining34, xiaoluo6 +.. +.. Paper Title: +.. Temporal Pointwise Convolutional Networks for +.. Length of Stay Prediction in the Intensive Care Unit +.. +.. Paper Authors: +.. Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) +.. +.. Paper URL: +.. https://arxiv.org/abs/2007.09483 + + +Hourly remaining ICU length of stay +=================================== + +.. automodule:: pyhealth.tasks.tpc_eicu + :members: + :show-inheritance: + +Implementation status +--------------------- + +The task implements adult cohort selection, hourly dynamic feature +extraction, admission static features, and hourly remaining-LOS labels. +The observation horizon is capped at 336 hours. + +Remaining LOS labels are clamped to a minimum of 0.5 hours +(1/48 day). + +Label normalization is controlled by ``normalize_labels``. +The default is ``True``, which preserves YAIB's min-max label +normalization. Set ``normalize_labels=False`` to preserve raw +remaining-LOS labels in hours for MSLE-based models. + +Observation removal is controlled by ``missing_rate`` (0.0 to 1.0). +Removal uses one deterministic mask per stay for a given seed and stay +identifier, so repeated training epochs over the same dataset see the same +masked observations. A rate of 0.0 preserves all observed values, while a rate +of 1.0 removes all observed feature cells. + +When ``include_decay=True``, decay features are calculated after +observation removal. Observed values reset to 1.0, and unobserved +values decay by a factor of 0.75 per hour. + +Missing dynamic values remain NaN in the task output. Forward filling +and normalization are handled by the configured YAIB preprocessing +pipeline. + + +Usage and validation +-------------------- + +From a repository checkout in Python 3.12 or 3.13:: + + python -m pip install -e . pytest + python examples/tpc_support/generate_synthetic.py /tmp/tpc_synthetic + python -m examples.tpc_support.checkpoint --output /tmp/tpc_checkpoint.json + python -m pytest tests/core/test_tpc_eicu.py -q --durations=5 + python -m pytest tests/core/test_tpc_checkpoint.py -q + python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 + +The synthetic CSV generator produces invented records across five patients. +The committed CSV files in ``examples/tpc_support/synthetic_eicu/`` +serve as illustrative examples of the expected eICU data format for +manual inspection. They are not required at runtime. The synthetic +generator creates fresh CSV files for the example and checkpoint scripts. + +The checkpoint script validates cohort selection, static values, aggregated +measurements, and remaining-LOS labels against independent numerical +expectations without training a model. The CSV-to-task checkpoint test +is included in the core test suite. + +Input and output specification +------------------------------ + +Load ``lab``, ``vitalperiodic``, ``vitalaperiodic``, ``intakeoutput``, +``respiratorycharting``, and ``nursecharting`` using :class:`~pyhealth.datasets.eICUDataset`. +One sample is produced per eligible stay: + +* Adults have known age >=18 and total ICU stay >=5 hours; ``> 89`` maps to 90. + Unknown age excludes the stay. Unknown sex or invalid height/weight is NaN. +* Static features are age, sex (male=1, female=0), admission height and weight. +* Dynamic uses 48 YAIB features. For H=min(floor(total LOS hours),336), its + values have shape (H,48), with missing values retained as NaN. +* Bin [b,b+1) becomes available at timestamp b+1. At hour 5 the model may + consume bins 0–4 only. +* Labels at hours 5..H have shape (H-4,1) and equal + max(0.5, total LOS hours - h). All raw labels are at least + 0.5 hours, including exact-discharge labels. The observation + horizon is capped; remaining LOS is not capped. +* ``missing_rate`` controls deterministic per-stay removal of observed hourly + feature cells prior to forward-fill. A rate of 0.0 preserves observations; + 1.0 removes all observed cells. +* ``include_decay=True`` adds decay features matching the dynamic + feature dimensions. Decay resets to 1.0 upon observation and + decreases by a factor of 0.75 per unobserved hour. +* Split by ``patient_id`` rather than ``stay_id``, and fit learned processors + on training patients only. By default, YAIB label processors min-max scale + training targets. Set ``normalize_labels=False`` to disable label + normalization and retain raw LOS targets in hours for MSLE-based models. + +For models requiring unnormalized LOS targets:: + + from pyhealth.tasks import TPCLengthOfStayEICU + + task = TPCLengthOfStayEICU( + missing_rate=0.1, + include_decay=True, + normalize_labels=False, + ) + +This task reproduces the hourly remaining-LOS prediction formulation from the +paper using YAIB feature extraction and PyHealth's existing preprocessing +pipeline, rather than re-implementing the TPC model architecture. diff --git a/examples/eicu_hourly_los_lstm.py b/examples/eicu_hourly_los_lstm.py new file mode 100644 index 0000000000..f93eb39b55 --- /dev/null +++ b/examples/eicu_hourly_los_lstm.py @@ -0,0 +1,617 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Hourly remaining ICU length-of-stay training and 2x3 missingness ablation. + +Trains PyHealth ``RNN_V2(rnn_type="LSTM")`` on ``TPCLengthOfStayEICU`` using +patient-disjoint splits (70% train / 15% validation / 15% test) and evaluates +the six paper metrics (MAD, MAPE, MSE, MSLE, R^2, and Cohen's linear weighted +Kappa) plus training-set mean/median baselines. + +Novel Missingness Robustness Ablation (2 x 3 design): + * Two training conditions with identical model architecture and splits: + Model A (0% extra observation removal) and Model B (10% extra random + observation removal before forward-fill). + * Three held-out test conditions (0%, 10%, 20% extra observation removal), + evaluated with deterministic per-stay seeds so both models see the exact + same masked test cells, while reusing each model's own training-fitted + imputation/normalization processors. + +Metric conventions (Section 5.3.1 & Appendix A/D of Rocheteau et al.): + * Targets and predictions are converted together from hours to days + (divided by 24.0) before scoring. + * MAPE clamps the true denominator below at 4/24 days (4 hours) to + prevent explosion near discharge. + * Minimum-target policy & MSLE: raw remaining-LOS labels from + ``TPCLengthOfStayEICU`` are clamped to a minimum of 0.5 hours. + Following Appendix A of the paper (HardTanh bounds + ``[1/48, 100]`` days), both targets and predictions are clipped + to ``[1/48, 100.0]`` days before taking the natural logarithm + for MSLE. + * Cohen's linear weighted Kappa discretizes days into 10 ordered bins: + ``[0-1, 1-2, 2-3, 3-4, 4-5, 5-6, 6-7, 7-8, 8-14, 14+]``. + +Pre-Rebase Experimental Setup & Results (eICU-CRD subset): + * Note: These single-seed (``seed=42``) numerical results were measured + prior to rebasing onto upstream PyHealth ``master`` and have not been + rerun after the rebase. + * Subset & split: The reported pre-rebase experiments used a subset + of 15,000 eICU-CRD patients. The current script does not perform + patient subsampling automatically. To reproduce the reported + results, the corresponding subset must be prepared externally + and provided through ``--root``. + Patients are split 70% / 15% / 15% by ``patient_id`` (seed=42). + * Model & training: ``RNN_V2(rnn_type="LSTM")``, ``embedding_dim=64``, + ``hidden_dim=128``, ``num_layers=2``, ``dropout=0.2``, ``mask="concat"``, + ``include_decay=True``, ``lr=0.00129``, ``batch_size=128``, ``epochs=8``, + MSE loss on min-max normalized hours (PyHealth default for + ``timeseries_regression``). + * Results (in days, pre-rebase, ``seed=42``): + + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | Model / Condition | Train Drop | Test Drop | MAD ↓ | MAPE (%) | MSE ↓ | MSLE | R^2 ↑ | Kappa ↑ | + +=======================+============+===========+=======+==========+=======+=======+========+=========+ + | Mean Baseline | 0% | 0% | 3.336 | 413.3 | 28.24 | 2.750 | -0.002 | 0.000 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | Median Baseline | 0% | 0% | 2.837 | 187.8 | 31.32 | 2.008 | -0.111 | 0.000 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 0% | 2.859 | 260.7 | 24.72 | 2.266 | 0.123 | 0.253 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 10% | 2.839 | 255.6 | 24.79 | 2.256 | 0.120 | 0.247 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 0% drop) | 0% | 20% | 2.819 | 251.1 | 24.84 | 2.223 | 0.118 | 0.243 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 0% | 2.893 | 271.6 | 24.74 | 2.205 | 0.122 | 0.252 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 10% | 2.869 | 266.3 | 24.76 | 2.189 | 0.121 | 0.247 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + | LSTM (Train 10% drop) | 10% | 20% | 2.844 | 261.1 | 24.77 | 2.153 | 0.121 | 0.243 | + +-----------------------+------------+-----------+-------+----------+-------+-------+--------+---------+ + + * Findings: + 1. Baseline alignment: our experimental subset baselines closely match the full + eICU paper baselines (Table 2: Mean MAD 3.21 / MSE 29.5; Median MAD + 2.76 / MSE 32.6), and ``LSTM (Train 0% drop)`` at 0% test drop + closely tracks the paper's ``Standard LSTM (MSE)`` (MSE 24.72 vs + 24.5, Kappa 0.253 vs 0.28). Remaining gaps may reflect differences in cohort + size, 48 YAIB dynamic + 4 static features (vs 87 + 17), and MSE loss rather + than log-space MSLE loss. + 2. Robustness ablation: in this single-seed (``seed=42``) evaluation, as + test missingness increases from 0% to 20%, Model A (0% train drop) + degrades by +0.12 MSE and -0.005 R^2, whereas Model B (10% train drop) + degrades by only +0.03 MSE and -0.001 R^2, achieving lower MSE and + MSLE and slightly higher R^2 than Model A under 10% and 20% + missingness. + +Examples: + Smoke check on five synthetic patients:: + + python examples/eicu_hourly_los_lstm.py --synthetic --epochs 2 + + Run full 2x3 ablation on a local eICU-CRD or eICU Demo directory:: + + python examples/eicu_hourly_los_lstm.py --root /path/to/eicu-crd +""" + +import argparse +import gc +import json +import os +import sys +import tempfile +from pathlib import Path +from typing import TYPE_CHECKING, Any + +if __name__ == "__main__": + REPO_ROOT = Path(__file__).resolve().parents[1] + if str(REPO_ROOT) not in sys.path: + sys.path.insert(0, str(REPO_ROOT)) + + # Bound native thread pools before importing numerical libraries. + for _var in ("POLARS_MAX_THREADS", "OMP_NUM_THREADS", "MKL_NUM_THREADS"): + os.environ.setdefault(_var, "4") + +import numpy as np +from sklearn.metrics import cohen_kappa_score, r2_score + +if TYPE_CHECKING: + from pyhealth.datasets import PatientSplit, eICUDataset + from pyhealth.models import RNN_V2 + from pyhealth.trainer import Trainer + +HOURS_PER_DAY = 24.0 +MAPE_FLOOR_DAYS = 4.0 / 24.0 +MIN_LOS_DAYS = 1.0 / 48.0 +MAX_LOS_DAYS = 100.0 +KAPPA_BIN_EDGES = (1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 14.0) +KAPPA_LABELS = list(range(len(KAPPA_BIN_EDGES) + 1)) + +DEFAULT_TRAIN_RATES = (0.0, 0.1) +DEFAULT_TEST_RATES = (0.0, 0.1, 0.2) + + +def compute_los_metrics( + y_true_hours: np.ndarray, + y_pred_hours: np.ndarray, +) -> dict[str, float]: + """Compute the 6 paper LoS evaluation metrics in days. + + Args: + y_true_hours: 1D array of ground-truth remaining LoS in hours. + y_pred_hours: 1D array of predicted remaining LoS in hours. + + Returns: + Dictionary with keys ``mad``, ``mape``, ``mse``, ``msle``, ``r2``, + and ``kappa``. + """ + y_true = np.asarray(y_true_hours, dtype=np.float64).reshape(-1) / HOURS_PER_DAY + y_pred = np.asarray(y_pred_hours, dtype=np.float64).reshape(-1) / HOURS_PER_DAY + if y_true.shape != y_pred.shape or y_true.size == 0: + raise ValueError( + f"Expected non-empty matching shapes, got {y_true.shape} and {y_pred.shape}." + ) + + abs_err = np.abs(y_true - y_pred) + mad = float(np.mean(abs_err)) + mape = float(np.mean(abs_err / np.maximum(y_true, MAPE_FLOOR_DAYS)) * 100.0) + mse = float(np.mean((y_true - y_pred) ** 2)) + + # Clip both targets and predictions to [1/48, 100] days for log-space MSLE. + log_true = np.log(np.clip(y_true, MIN_LOS_DAYS, MAX_LOS_DAYS)) + log_pred = np.log(np.clip(y_pred, MIN_LOS_DAYS, MAX_LOS_DAYS)) + msle = float(np.mean((log_true - log_pred) ** 2)) + + r2 = float(r2_score(y_true, y_pred)) if y_true.size >= 2 else float("nan") + + true_bins = np.digitize(y_true, KAPPA_BIN_EDGES, right=False) + pred_bins = np.digitize(y_pred, KAPPA_BIN_EDGES, right=False) + if len(np.unique(np.concatenate([true_bins, pred_bins]))) < 2: + kappa = 0.0 + else: + kappa = float( + cohen_kappa_score( + true_bins, + pred_bins, + labels=KAPPA_LABELS, + weights="linear", + ) + ) + if np.isnan(kappa): + kappa = 0.0 + + return { + "mad": mad, + "mape": mape, + "mse": mse, + "msle": msle, + "r2": r2, + "kappa": kappa, + } + + +def _extract_target_hours(dataset: Any, batch_size: int) -> np.ndarray: + """Extract unscaled ground-truth hourly targets from a SampleDataset.""" + from pyhealth.datasets import get_dataloader + + label_proc = dataset.output_processors["los"] + loader = get_dataloader( + dataset, + batch_size=min(batch_size, len(dataset)), + shuffle=False, + ) + parts: list[np.ndarray] = [] + for batch in loader: + true_list, _ = label_proc.to_numpy(batch["los"], batch["los"][0]) + parts.extend(true_list) + return np.concatenate(parts, axis=0) + + +def compute_constant_baselines( + train_true_hours: np.ndarray, + test_true_hours: np.ndarray, +) -> dict[str, dict[str, float]]: + """Evaluate training-set mean and median baselines on test targets.""" + mean_hours = float(np.mean(train_true_hours)) + median_hours = float(np.median(train_true_hours)) + return { + "mean_baseline": compute_los_metrics( + test_true_hours, + np.full_like(test_true_hours, mean_hours, dtype=np.float64), + ), + "median_baseline": compute_los_metrics( + test_true_hours, + np.full_like(test_true_hours, median_hours, dtype=np.float64), + ), + } + + +def _build_embedding_dim( + embedding_dim: int, + include_decay: bool, +) -> dict[str, list[dict[str, int]]]: + """Build per-field LevelEmbedding config matching TPCLengthOfStayEICU.""" + config: dict[str, list[dict[str, int]]] = { + "dynamic": [{"values": embedding_dim}], + "static": [{"values": embedding_dim}], + } + if include_decay: + config["decay"] = [{"values": embedding_dim}] + return config + + +def _train_single_model( + base_dataset: "eICUDataset", + *, + train_missing_rate: float, + include_decay: bool, + split: "PatientSplit", + epochs: int, + batch_size: int, + lr: float, + embedding_dim: int, + hidden_dim: int, + num_layers: int, + dropout: float, + seed: int, + num_workers: int, + device: str, +) -> tuple["RNN_V2", "Trainer", Any, Any, dict[int, Any], np.ndarray, dict[str, int]]: + """Train one LSTM model at ``train_missing_rate`` using training-only stats.""" + from pyhealth.datasets import get_dataloader + from pyhealth.models import RNN_V2 + from pyhealth.tasks import TPCLengthOfStayEICU + from pyhealth.trainer import Trainer + from pyhealth.utils import set_seed + + set_seed(seed) + train_task = TPCLengthOfStayEICU( + missing_rate=train_missing_rate, + seed=seed, + include_decay=include_decay, + ) + train_data, val_data, test_data = base_dataset.set_task( + train_task, + split=split, + num_workers=num_workers, + ) + sizes = { + "train": len(train_data), + "val": len(val_data), + "test": len(test_data), + } + if not all(sizes.values()): + raise ValueError(f"Empty dataset split encountered: {sizes}") + + train_loader = get_dataloader( + train_data, + batch_size=min(batch_size, len(train_data)), + shuffle=True, + seed=seed, + ) + val_loader = get_dataloader( + val_data, + batch_size=min(batch_size, len(val_data)), + shuffle=False, + ) + + model = RNN_V2( + dataset=train_data, + embedding_dim=_build_embedding_dim(embedding_dim, include_decay), + hidden_dim=hidden_dim, + rnn_type="LSTM", + num_layers=num_layers, + dropout=dropout, + bidirectional=False, + mask="concat", + ) + trainer = Trainer( + model=model, + metrics=["mae", "mse"], + device=device, + enable_logging=False, + ) + trainer.train( + train_dataloader=train_loader, + val_dataloader=val_loader, + epochs=epochs, + optimizer_params={"lr": lr}, + monitor="loss", + monitor_criterion="min", + load_best_model_at_last=True, + max_grad_norm=5.0, + ) + + train_true_hours = _extract_target_hours(train_data, batch_size) + processors = (train_data.input_processors, train_data.output_processors) + # Free training/validation loader references while keeping fitted processors. + del train_loader, val_loader, train_data, val_data + return ( + model, + trainer, + processors[0], + processors[1], + {0: test_data}, + train_true_hours, + sizes, + ) + + +def _format_results_table(rows: list[dict[str, Any]]) -> str: + """Format experiment results into a readable Markdown comparison table.""" + header = ( + "| Model / Condition | Train Drop | Test Drop | " + "MAD ↓ | MAPE (%) ↓ | MSE ↓ | MSLE ↓ | R^2 ↑ | Kappa ↑ |" + ) + sep = "| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |" + lines = [header, sep] + for row in rows: + m = row["metrics"] + lines.append( + f"| {row['label']} | {row['train_missing_rate']:.0%} | " + f"{row['test_missing_rate']:.0%} | " + f"{m['mad']:.3f} | {m['mape']:.1f} | {m['mse']:.2f} | " + f"{m['msle']:.3f} | {m['r2']:.3f} | {m['kappa']:.3f} |" + ) + return "\n".join(lines) + + +def train_and_evaluate( + root: str | Path | None = None, + *, + synthetic: bool = False, + train_rates: tuple[float, ...] = DEFAULT_TRAIN_RATES, + test_rates: tuple[float, ...] = DEFAULT_TEST_RATES, + include_decay: bool = True, + epochs: int = 8, + batch_size: int = 128, + lr: float = 0.00129, + embedding_dim: int = 64, + hidden_dim: int = 128, + num_layers: int = 2, + dropout: float = 0.2, + seed: int = 42, + num_workers: int = 1, + device: str | None = None, + cache_dir: str | Path | None = None, +) -> list[dict[str, Any]]: + """Run the 2x3 missingness ablation study and return all metric rows.""" + if not synthetic and root is None: + raise ValueError("Provide --root or pass --synthetic.") + + import torch + + from examples.tpc_support.generate_synthetic import TABLES, generate + from pyhealth.datasets import PatientSplit, eICUDataset, get_dataloader + from pyhealth.tasks import TPCLengthOfStayEICU + + chosen_device = device or ("cuda" if torch.cuda.is_available() else "cpu") + + def _run_with_root( + data_root: Path, + effective_cache: Path | None, + split_ratios: tuple[float, float, float], + ) -> list[dict[str, Any]]: + dataset_kwargs: dict[str, Any] = { + "root": str(data_root), + "tables": list(TABLES), + "num_workers": num_workers, + } + if effective_cache is not None: + dataset_kwargs["cache_dir"] = str(effective_cache) + + base_dataset = eICUDataset(**dataset_kwargs) + split = PatientSplit(ratios=split_ratios, seed=seed) + results: list[dict[str, Any]] = [] + baselines_recorded = False + + for train_rate in train_rates: + ( + model, + trainer, + in_procs, + out_procs, + cached_test_by_rate, + train_true_hours, + sizes, + ) = _train_single_model( + base_dataset, + train_missing_rate=train_rate, + include_decay=include_decay, + split=split, + epochs=epochs, + batch_size=batch_size, + lr=lr, + embedding_dim=embedding_dim, + hidden_dim=hidden_dim, + num_layers=num_layers, + dropout=dropout, + seed=seed, + num_workers=num_workers, + device=chosen_device, + ) + + model_label = f"LSTM (Train {train_rate:.0%} drop)" + for test_rate in test_rates: + if np.isclose(test_rate, train_rate): + test_data = cached_test_by_rate[0] + else: + test_task = TPCLengthOfStayEICU( + missing_rate=test_rate, + seed=seed, + include_decay=include_decay, + ) + # Reuse training-fitted processors so test stats never leak. + _, _, test_data = base_dataset.set_task( + test_task, + input_processors=in_procs, + output_processors=out_procs, + split=split, + num_workers=num_workers, + ) + + test_loader = get_dataloader( + test_data, + batch_size=min(batch_size, len(test_data)), + shuffle=False, + ) + y_true_stays, y_pred_stays, test_loss = trainer.inference(test_loader) + test_true_hours = np.concatenate(y_true_stays, axis=0) + test_pred_hours = np.concatenate(y_pred_stays, axis=0) + metrics = compute_los_metrics(test_true_hours, test_pred_hours) + + if not baselines_recorded: + baselines = compute_constant_baselines( + train_true_hours, test_true_hours + ) + for base_name, base_label in ( + ("mean_baseline", "Mean Baseline"), + ("median_baseline", "Median Baseline"), + ): + results.append( + { + "label": base_label, + "train_missing_rate": float(train_rate), + "test_missing_rate": float(test_rate), + "include_decay": include_decay, + "splits": sizes, + "n_test_hours": len(test_true_hours), + "metrics": baselines[base_name], + } + ) + baselines_recorded = True + + results.append( + { + "label": model_label, + "train_missing_rate": float(train_rate), + "test_missing_rate": float(test_rate), + "include_decay": include_decay, + "splits": sizes, + "test_loss_scaled_mse": float(test_loss), + "n_test_hours": len(test_true_hours), + "metrics": metrics, + } + ) + del test_loader, test_data + + del trainer, model, in_procs, out_procs, cached_test_by_rate + gc.collect() + if torch.device(chosen_device).type == "cuda": + torch.cuda.empty_cache() + + del base_dataset + gc.collect() + return results + + if synthetic: + with tempfile.TemporaryDirectory( + prefix="tpc-lstm-ablation-", ignore_cleanup_errors=True + ) as tmp: + tmp_path = Path(tmp) + csv_dir = tmp_path / "csv" + generate(csv_dir) + # Only 3 of the 5 synthetic stays pass cohort criteria; + # (0.4, 0.3, 0.3) guarantees 1 train / 1 val / 1 test patient. + return _run_with_root(csv_dir, tmp_path / "cache", (0.4, 0.3, 0.3)) + + assert root is not None + data_root = Path(root).expanduser().resolve() + effective_cache = ( + Path(cache_dir).expanduser().resolve() if cache_dir is not None else None + ) + return _run_with_root(data_root, effective_cache, (0.7, 0.15, 0.15)) + + +def _parse_args() -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", + type=Path, + default=None, + help="Path to eICU-CRD or eICU Demo CSV directory.", + ) + parser.add_argument( + "--synthetic", + action="store_true", + help="Run a fast smoke ablation on generated synthetic patients.", + ) + parser.add_argument( + "--train-rates", + type=float, + nargs="+", + default=list(DEFAULT_TRAIN_RATES), + help="Training missingness rates (default: 0.0 0.1).", + ) + parser.add_argument( + "--test-rates", + type=float, + nargs="+", + default=list(DEFAULT_TEST_RATES), + help="Test missingness rates (default: 0.0 0.1 0.2).", + ) + parser.add_argument( + "--no-decay", + dest="include_decay", + action="store_false", + help="Disable exponential decay indicators (0.75^hours_since_obs).", + ) + parser.set_defaults(include_decay=True) + parser.add_argument("--epochs", type=int, default=8) + parser.add_argument("--batch-size", type=int, default=128) + parser.add_argument("--lr", type=float, default=0.00129) + parser.add_argument("--embedding-dim", type=int, default=64) + parser.add_argument("--hidden-dim", type=int, default=128) + parser.add_argument("--num-layers", type=int, default=2) + parser.add_argument("--dropout", type=float, default=0.2) + parser.add_argument("--seed", type=int, default=42) + parser.add_argument("--num-workers", type=int, default=1) + parser.add_argument("--device", type=str, default=None) + parser.add_argument("--cache-dir", type=Path, default=None) + parser.add_argument( + "--output-json", + type=Path, + default=None, + help="Optional path to save full JSON metrics.", + ) + return parser.parse_args() + + +if __name__ == "__main__": + args = _parse_args() + rows = train_and_evaluate( + root=args.root, + synthetic=args.synthetic, + train_rates=tuple(args.train_rates), + test_rates=tuple(args.test_rates), + include_decay=args.include_decay, + epochs=args.epochs, + batch_size=args.batch_size, + lr=args.lr, + embedding_dim=args.embedding_dim, + hidden_dim=args.hidden_dim, + num_layers=args.num_layers, + dropout=args.dropout, + seed=args.seed, + num_workers=args.num_workers, + device=args.device, + cache_dir=args.cache_dir, + ) + print("\n=== Hourly Remaining ICU LoS (2x3 Missingness Ablation) ===") + print(_format_results_table(rows)) + if args.output_json is not None: + out_path = args.output_json + if out_path.is_dir(): + out_path = out_path / "results.json" + out_path.parent.mkdir(parents=True, exist_ok=True) + out_path.write_text(json.dumps(rows, indent=2), encoding="utf-8") diff --git a/examples/tpc_support/checkpoint.py b/examples/tpc_support/checkpoint.py new file mode 100644 index 0000000000..bc7f6c9310 --- /dev/null +++ b/examples/tpc_support/checkpoint.py @@ -0,0 +1,99 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Synthetic CSV-to-task checkpoint for cohort, static features and labels. +""" + +import json +import tempfile +from pathlib import Path + +import numpy as np + +from examples.tpc_support.generate_synthetic import TABLES, generate +from pyhealth.datasets import eICUDataset +from pyhealth.tasks import TPCLengthOfStayEICU + + +def run(root: Path) -> dict: + """Generate data and validate numerical cohort, feature and label expectations.""" + generate(root / "csv") + source = eICUDataset( + root=str(root / "csv"), tables=TABLES, cache_dir=root / "cache" + ) + task = TPCLengthOfStayEICU() + samples = {} + for sid in (101, 102, 103, 104, 105): + out = task(source.get_patient(f"synthetic-{sid}")) + if sid in (102, 104): + assert out == [], f"Excluded stay {sid} survived" + else: + assert len(out) == 1 + samples[sid] = out[0] + short = samples[101] + names = task.DYNAMIC_FEATURES + + def value(hour, name): + return short["dynamic"]["values"][hour, names.index(name)] + + # Hand-calculated oracle: not computed by the task under test. + for hour, name, expected in [ + (0, "hr", 90), + (2, "hr", 110), + (5, "hr", 120), + (1, "k", 5), + (4, "k", 3), + (2, "crea", 1.2), + (3, "sbp", 130), + (1, "urine", 150), + (3, "fio2", 40), + (4, "temp", 37), + ]: + np.testing.assert_allclose(value(hour, name), expected) + assert np.isnan(value(1, "hr")) + assert np.isnan(value(5, "k")) # implausible 99 mmol/L discarded + assert short["static"]["values"] == [[18.0, 0.0, 165.0, 65.0]] + assert short["los"]["time"] == list(range(5, 13)) + np.testing.assert_allclose( + short["los"]["values"], [[7.5], [6.5], [5.5], [4.5], [3.5], [2.5], [1.5], [0.5]] + ) + assert samples[103]["los"]["time"][-1] == 336 + assert samples[103]["los"]["values"][-1] == [64.5] + assert samples[103]["dynamic"]["values"][0, names.index("hr")] == 100 + assert np.isnan(samples[105]["static"]["values"][0][2]) + # Downstream model training and ablation live in examples/eicu_hourly_los_lstm.py. + return { + "status": "passed", + "scope": "CSV loading, cohort, static features, hourly labels", + "synthetic_patients": 5, + "included_stays": [101, 103, 105], + "excluded_stays": [102, 104], + "model_training": "implemented in examples/eicu_hourly_los_lstm.py", + "missingness_and_decay": "implemented in TPCLengthOfStayEICU", + } + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path) + args = parser.parse_args() + with tempfile.TemporaryDirectory(prefix="tpc-checkpoint-") as tmp: + report = run(Path(tmp)) + text = json.dumps(report, indent=2) + print(text) + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(text + "\n") diff --git a/examples/tpc_support/generate_synthetic.py b/examples/tpc_support/generate_synthetic.py new file mode 100644 index 0000000000..a5d68e34ef --- /dev/null +++ b/examples/tpc_support/generate_synthetic.py @@ -0,0 +1,160 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Write five invented patients in the shipped eICU CSV schema. +""" + +import csv +from pathlib import Path + +import yaml + +TABLES = [ + "lab", + "vitalperiodic", + "vitalaperiodic", + "intakeoutput", + "respiratorycharting", + "nursecharting", +] + + +def generate(root: Path) -> None: + """Create schema-complete CSVs; all values are invented.""" + root.mkdir(parents=True, exist_ok=True) + config = yaml.safe_load( + (Path(__file__).parents[2] / "pyhealth/datasets/configs/eicu.yaml").read_text() + ) + rows = {table: [] for table in ["patient", *TABLES]} + for sid, age, hours in [ + (101, "18", 12.5), + (102, "60", 4), + (103, "> 89", 400.5), + (104, "17", 12), + (105, "45", 8), + ]: + rows["patient"].append( + dict( + patientunitstayid=sid, + uniquepid=f"synthetic-{sid}", + patienthealthsystemstayid=sid, + unitvisitnumber=1, + hospitalid=1, + age=age, + gender="Male" if sid == 103 else "Female", + admissionheight="" if sid == 105 else 165, + admissionweight=65, + unitdischargeoffset=int(hours * 60), + unitdischargestatus="Alive", + hospitaladmitoffset=0, + hospitaldischargeoffset=int(hours * 60), + hospitaldischargeyear=2020, + hospitaldischargestatus="Alive", + ) + ) + # Identical timing, contrasting values: detect cross-patient leakage. + shift = 10 if sid == 103 else 0 + for minute, hr in [ + (-60, 250), + (10, 80 + shift), + (40, 100 + shift), + (120, 110 + shift), + (359, 120 + shift), + (900, 200), + ]: + rows["vitalperiodic"].append( + dict( + patientunitstayid=sid, + observationoffset=minute, + heartrate=hr, + sao2=98, + respiration=16, + systemicsystolic=120, + systemicdiastolic=70, + systemicmean=85, + temperature=37, + ) + ) + for minute, value in [(60, 4), (90, 6), (240, 3), (300, 99)]: + rows["lab"].append( + dict( + patientunitstayid=sid, + labresultoffset=minute, + labname="potassium", + labresult=value, + labmeasurenameinterface="mmol/L", + ) + ) + rows["lab"].append( + dict( + patientunitstayid=sid, + labresultoffset=150, + labname="creatinine", + labresult=1.2, + labmeasurenameinterface="mg/dL", + ) + ) + rows["vitalaperiodic"].append( + dict( + patientunitstayid=sid, + observationoffset=180, + noninvasivesystolic=130, + noninvasivediastolic=75, + noninvasivemean=90, + ) + ) + for minute, amount in [(65, 100), (95, 50)]: + rows["intakeoutput"].append( + dict( + patientunitstayid=sid, + intakeoutputoffset=minute, + celllabel="Urine", + cellvaluenumeric=amount, + ) + ) + rows["respiratorycharting"].append( + dict( + patientunitstayid=sid, + respchartoffset=180, + respchartvaluelabel="FiO2", + respchartvalue="40%", + ) + ) + rows["nursecharting"].append( + dict( + patientunitstayid=sid, + nursingchartoffset=240, + nursingchartcelltypevalname="Temperature (F)", + nursingchartvalue="98.6", + ) + ) + for table, values in rows.items(): + cfg = config["tables"][table] + fields = list( + dict.fromkeys( + [*cfg["attributes"], *(["uniquepid"] if table == "patient" else [])] + ) + ) + with (root / cfg["file_path"]).open("w", newline="") as f: + writer = csv.DictWriter(f, fieldnames=fields, lineterminator="\n") + writer.writeheader() + writer.writerows(values) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("output", type=Path) + generate(parser.parse_args().output) diff --git a/examples/tpc_support/synthetic_eicu/intakeOutput.csv b/examples/tpc_support/synthetic_eicu/intakeOutput.csv new file mode 100644 index 0000000000..ab6ccc45dd --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/intakeOutput.csv @@ -0,0 +1,11 @@ +patientunitstayid,intakeoutputoffset,celllabel,cellvaluenumeric +101,65,Urine,100 +101,95,Urine,50 +102,65,Urine,100 +102,95,Urine,50 +103,65,Urine,100 +103,95,Urine,50 +104,65,Urine,100 +104,95,Urine,50 +105,65,Urine,100 +105,95,Urine,50 diff --git a/examples/tpc_support/synthetic_eicu/lab.csv b/examples/tpc_support/synthetic_eicu/lab.csv new file mode 100644 index 0000000000..5ffd9e07b0 --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/lab.csv @@ -0,0 +1,26 @@ +patientunitstayid,labresultoffset,labname,labresult,labresulttext,labmeasurenamesystem,labmeasurenameinterface,labtypeid +101,60,potassium,4,,,mmol/L, +101,90,potassium,6,,,mmol/L, +101,240,potassium,3,,,mmol/L, +101,300,potassium,99,,,mmol/L, +101,150,creatinine,1.2,,,mg/dL, +102,60,potassium,4,,,mmol/L, +102,90,potassium,6,,,mmol/L, +102,240,potassium,3,,,mmol/L, +102,300,potassium,99,,,mmol/L, +102,150,creatinine,1.2,,,mg/dL, +103,60,potassium,4,,,mmol/L, +103,90,potassium,6,,,mmol/L, +103,240,potassium,3,,,mmol/L, +103,300,potassium,99,,,mmol/L, +103,150,creatinine,1.2,,,mg/dL, +104,60,potassium,4,,,mmol/L, +104,90,potassium,6,,,mmol/L, +104,240,potassium,3,,,mmol/L, +104,300,potassium,99,,,mmol/L, +104,150,creatinine,1.2,,,mg/dL, +105,60,potassium,4,,,mmol/L, +105,90,potassium,6,,,mmol/L, +105,240,potassium,3,,,mmol/L, +105,300,potassium,99,,,mmol/L, +105,150,creatinine,1.2,,,mg/dL, diff --git a/examples/tpc_support/synthetic_eicu/nurseCharting.csv b/examples/tpc_support/synthetic_eicu/nurseCharting.csv new file mode 100644 index 0000000000..fc99da8c3b --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/nurseCharting.csv @@ -0,0 +1,6 @@ +patientunitstayid,nursingchartoffset,nursingchartcelltypevalname,nursingchartvalue +101,240,Temperature (F),98.6 +102,240,Temperature (F),98.6 +103,240,Temperature (F),98.6 +104,240,Temperature (F),98.6 +105,240,Temperature (F),98.6 diff --git a/examples/tpc_support/synthetic_eicu/patient.csv b/examples/tpc_support/synthetic_eicu/patient.csv new file mode 100644 index 0000000000..41e5e67cd9 --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/patient.csv @@ -0,0 +1,6 @@ +patientunitstayid,patienthealthsystemstayid,gender,age,ethnicity,hospitalid,wardid,apacheadmissiondx,admissionheight,admissionweight,dischargeweight,hospitaladmittime24,hospitaladmitoffset,hospitaladmitsource,hospitaldischargeyear,hospitaldischargeoffset,hospitaldischargestatus,hospitaldischargetime24,unittype,unitadmittime24,unitadmitsource,unitvisitnumber,unitstaytype,unitdischargeoffset,unitdischargestatus,unitdischargetime24,unitdischargelocation,uniquepid +101,101,Female,18,,1,,,165,65,,,0,,2020,750,Alive,,,,,1,,750,Alive,,,synthetic-101 +102,102,Female,60,,1,,,165,65,,,0,,2020,240,Alive,,,,,1,,240,Alive,,,synthetic-102 +103,103,Male,> 89,,1,,,165,65,,,0,,2020,24030,Alive,,,,,1,,24030,Alive,,,synthetic-103 +104,104,Female,17,,1,,,165,65,,,0,,2020,720,Alive,,,,,1,,720,Alive,,,synthetic-104 +105,105,Female,45,,1,,,,65,,,0,,2020,480,Alive,,,,,1,,480,Alive,,,synthetic-105 diff --git a/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv b/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv new file mode 100644 index 0000000000..9cad3d3910 --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/respiratoryCharting.csv @@ -0,0 +1,6 @@ +patientunitstayid,respchartoffset,respcharttypecat,respchartvaluelabel,respchartvalue +101,180,,FiO2,40% +102,180,,FiO2,40% +103,180,,FiO2,40% +104,180,,FiO2,40% +105,180,,FiO2,40% diff --git a/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv b/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv new file mode 100644 index 0000000000..7fdd26b806 --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/vitalAperiodic.csv @@ -0,0 +1,6 @@ +patientunitstayid,observationoffset,noninvasivesystolic,noninvasivediastolic,noninvasivemean +101,180,130,75,90 +102,180,130,75,90 +103,180,130,75,90 +104,180,130,75,90 +105,180,130,75,90 diff --git a/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv b/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv new file mode 100644 index 0000000000..e97a843a8f --- /dev/null +++ b/examples/tpc_support/synthetic_eicu/vitalPeriodic.csv @@ -0,0 +1,31 @@ +patientunitstayid,observationoffset,temperature,sao2,heartrate,respiration,systemicsystolic,systemicdiastolic,systemicmean +101,-60,37,98,250,16,120,70,85 +101,10,37,98,80,16,120,70,85 +101,40,37,98,100,16,120,70,85 +101,120,37,98,110,16,120,70,85 +101,359,37,98,120,16,120,70,85 +101,900,37,98,200,16,120,70,85 +102,-60,37,98,250,16,120,70,85 +102,10,37,98,80,16,120,70,85 +102,40,37,98,100,16,120,70,85 +102,120,37,98,110,16,120,70,85 +102,359,37,98,120,16,120,70,85 +102,900,37,98,200,16,120,70,85 +103,-60,37,98,250,16,120,70,85 +103,10,37,98,90,16,120,70,85 +103,40,37,98,110,16,120,70,85 +103,120,37,98,120,16,120,70,85 +103,359,37,98,130,16,120,70,85 +103,900,37,98,200,16,120,70,85 +104,-60,37,98,250,16,120,70,85 +104,10,37,98,80,16,120,70,85 +104,40,37,98,100,16,120,70,85 +104,120,37,98,110,16,120,70,85 +104,359,37,98,120,16,120,70,85 +104,900,37,98,200,16,120,70,85 +105,-60,37,98,250,16,120,70,85 +105,10,37,98,80,16,120,70,85 +105,40,37,98,100,16,120,70,85 +105,120,37,98,110,16,120,70,85 +105,359,37,98,120,16,120,70,85 +105,900,37,98,200,16,120,70,85 diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index 624f055cd6..ef8beb4118 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -372,6 +372,8 @@ YAIBMortalityEICU as YAIBMortalityEICU, YAIBSepsisEICU as YAIBSepsisEICU, ) + +from .tpc_eicu import TPCLengthOfStayEICU as TPCLengthOfStayEICU from .tpc_day_one import TPCDayOne as TPCDayOne from .tcga_survival_prediction import TCGASurvivalPrediction as TCGASurvivalPrediction @@ -392,4 +394,4 @@ def __getattr__(name: str): from .ptbxl import PTBXLSuperclassClassification return PTBXLSuperclassClassification - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") \ No newline at end of file diff --git a/pyhealth/tasks/tpc_eicu.py b/pyhealth/tasks/tpc_eicu.py new file mode 100644 index 0000000000..33159b1cb3 --- /dev/null +++ b/pyhealth/tasks/tpc_eicu.py @@ -0,0 +1,337 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Hourly remaining ICU length-of-stay task with missingness experiments. +""" + +import hashlib +from copy import deepcopy +from typing import Any, ClassVar + +import numpy as np +import polars as pl + +from .yaib_eicu import _DYNAMIC_FEATURES, YAIBLengthOfStayEICU + + +class TPCLengthOfStayEICU(YAIBLengthOfStayEICU): + """Generate hourly remaining-LOS labels for eICU stays. + + This is a standalone task, not a TPC model implementation. + + Static features are inherited from YAIB. Labels are in hours, + starting at hour 5 and continuing through min(floor(LOS), 336). + Remaining LOS labels are clamped to a minimum of 0.5 hours. + + Dynamic timestamps represent completed hourly bins: + bin [h-1, h) is available at hour h. + + Dynamic measurements remain raw with NaNs at task creation. + Inherited sequence_v2 processors handle normalization and + forward-fill downstream. + + Missingness is applied to observed values before processing using one + deterministic mask per stay (derived from ``seed`` and ``stay_id``), + so every training epoch sees the same masked matrix for a given stay. + Decay is computed from the post-masking, pre-forward-fill + observation matrix. + + Args: + missing_rate: Fraction of observed feature cells to mask, + between 0 and 1. + seed: Seed combined with stay ID for reproducible masking. + include_decay: Whether to add per-feature decay sequences. + normalize_labels: Whether to apply min-max normalization to LOS + labels during processing. Defaults to True. Set to False + to preserve raw LOS labels in hours. + + Examples: + >>> from pyhealth.datasets import eICUDataset + >>> from pyhealth.tasks import TPCLengthOfStayEICU + >>> task = TPCLengthOfStayEICU(missing_rate=0.1, include_decay=True) + >>> task.task_name + 'TPCLengthOfStayEICU' + >>> dataset = eICUDataset( # doctest: +SKIP + ... root="/path/to/eicu-crd/2.0", + ... tables=[ + ... "lab", + ... "vitalperiodic", + ... "vitalaperiodic", + ... "intakeoutput", + ... "respiratorycharting", + ... "nursecharting", + ... ], + ... ) + >>> samples = dataset.set_task(task) # doctest: +SKIP + """ + + task_name: str = "TPCLengthOfStayEICU" + + MAX_HOURS: ClassVar[int] = 14 * 24 + START_HOUR: ClassVar[int] = 5 + + def __init__( + self, + missing_rate: float = 0.0, + seed: int = 42, + include_decay: bool = False, + normalize_labels: bool = True, + ) -> None: + """Configure masking, decay features, and label normalization.""" + + if not 0.0 <= missing_rate <= 1.0: + raise ValueError("missing_rate must be between 0 and 1.") + + self.missing_rate = missing_rate + self.seed = seed + self.include_decay = include_decay + self.input_schema = deepcopy(type(self).input_schema) + self.output_schema = deepcopy(type(self).output_schema) + + if not normalize_labels: + self.output_schema["los"][1]["normalization"] = None + + if include_decay: + self.input_schema["decay"] = ( + "jagged", + { + "levels": [ + { + "ordering": "series", + "values": [len(self.DYNAMIC_FEATURES)], + } + ] + }, + ) + self.output_schema["los"][1]["timeline"].append("decay") + + def _base_cohort( + self, + patient: Any, + stays: pl.DataFrame, + ) -> tuple[pl.DataFrame, pl.DataFrame, dict[int, list[float]]]: + """Select eligible adult ICU stays. + + Args: + patient: PyHealth patient with eICU events. + stays: Parsed ICU stay records. + + Returns: + Eligible stays, hourly measurements, and static features. + """ + + static = self._static(patient, stays) + + keep = [ + stay_id + for stay_id, hours in stays.select("stay_id", "los_hours").iter_rows() + if np.isfinite(hours) + and hours >= self.START_HOUR + and np.isfinite(static[stay_id][0]) + and static[stay_id][0] >= 18 + ] + + stays = stays.filter(pl.col("stay_id").is_in(keep)) + + # Extract the 48 hourly YAIB dynamic features for eligible adult stays. + hourly = self._hourly( + self._measurements( + patient, + stays, + _DYNAMIC_FEATURES, + ) + ) + + return stays, hourly, {key: static[key] for key in keep} + + @staticmethod + def _decay(values: np.ndarray) -> np.ndarray: + """Compute exponentially decaying observation indicators. + + An observed value resets its decay indicator to 1. + Each subsequent missing hour multiplies the previous + indicator by 0.75. + + Features with no previous observations remain at 0. + + Decay is computed before forward-fill so that artificially + imputed values do not count as new observations. + + Args: + values: Two-dimensional hourly feature matrix + containing NaNs for missing observations. + + Returns: + Float array of the same shape with decay indicators. + """ + + if values.ndim != 2: + raise ValueError("values must be a 2D (hours, features) array") + + n_hours, n_features = values.shape + + decay = np.zeros( + (n_hours, n_features), + dtype=float, + ) + + for hour in range(n_hours): + observed = ~np.isnan(values[hour]) + + if hour > 0: + decay[hour] = 0.75 * decay[hour - 1] + + decay[hour, observed] = 1.0 + + return decay + + def _apply_missingness( + self, + values: np.ndarray, + stay_id: Any, + ) -> np.ndarray: + """Randomly mask observed cells reproducibly for each stay. + + Args: + values: Hourly dynamic feature matrix. + stay_id: ICU stay identifier for deterministic masking. + + Returns: + Copy of values with selected cells replaced by NaN. + """ + + values = values.copy() + + if self.missing_rate == 0.0: + return values + + observed = np.argwhere(~np.isnan(values)) + + n_hide = round(len(observed) * self.missing_rate) + + if n_hide == 0: + return values + + key = f"{self.seed}:{stay_id}".encode() + + stay_seed = int.from_bytes( + hashlib.sha256(key).digest()[:8], + "little", + ) + + rng = np.random.default_rng(stay_seed) + + selected = rng.choice( + len(observed), + size=n_hide, + replace=False, + ) + + rows, cols = observed[selected].T + + values[rows, cols] = np.nan + + return values + + def __call__( + self, + patient: Any, + ) -> list[dict[str, Any]]: + """Create hourly remaining-LOS samples for eligible stays. + + Args: + patient: PyHealth patient with eICU records. + + Returns: + Per-stay samples containing patient_id, stay_id, + dynamic, static, los, and optionally decay. + """ + + all_stays = self._stays(patient) + + if all_stays.height == 0: + return [] + + stays, hourly, static = self._base_cohort( + patient, + all_stays, + ) + + samples = [] + + for stay_id, los_hours, end in stays.select( + "stay_id", + "los_hours", + "end", + ).iter_rows(): + if end < self.START_HOUR: + continue + + last_hour = min( + end, + self.MAX_HOURS, + ) + + # Each hourly bin becomes available only after + # the bin is complete, preventing future leakage. + dynamic = self._dynamic( + hourly, + stay_id, + last_hour - 1, + ) + + dynamic["time"] = [float(h) for h in range(1, last_hour + 1)] + + dynamic["values"] = self._apply_missingness( + dynamic["values"], + stay_id, + ) + + prediction_hours = [ + float(hour) + for hour in range( + self.START_HOUR, + last_hour + 1, + ) + ] + + # Clamp remaining LOS to 0.5 hours for MSLE compatibility. + remaining = [ + max( + 0.5, + float(los_hours) - hour, + ) + for hour in prediction_hours + ] + + sample = { + "patient_id": patient.patient_id, + "stay_id": stay_id, + "dynamic": dynamic, + "static": self._static_record(static[stay_id]), + "los": self._labels( + prediction_hours, + remaining, + ), + } + + if self.include_decay: + sample["decay"] = { + "time": list(dynamic["time"]), + "values": self._decay(dynamic["values"]), + } + + samples.append(sample) + + return samples diff --git a/tests/core/test_tpc_checkpoint.py b/tests/core/test_tpc_checkpoint.py new file mode 100644 index 0000000000..c4195b9e21 --- /dev/null +++ b/tests/core/test_tpc_checkpoint.py @@ -0,0 +1,24 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Synthetic CSV loader and task smoke test. +""" + +from examples.tpc_support.checkpoint import run + + +def test_csv_to_task(tmp_path): + result = run(tmp_path) + assert result["status"] == "passed" + assert result["scope"] == "CSV loading, cohort, static features, hourly labels" diff --git a/tests/core/test_tpc_eicu.py b/tests/core/test_tpc_eicu.py new file mode 100644 index 0000000000..ee5915b050 --- /dev/null +++ b/tests/core/test_tpc_eicu.py @@ -0,0 +1,576 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetID: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Synthetic cohort, hourly-label, and preprocessing regression tests. + +Tests for the TPCLengthOfStayEICU task using synthetic patient data. +No real clinical records are used. + +Coverage includes cohort eligibility, hourly LOS labels, truncation, +missingness, decay, temporal leakage prevention, and stay isolation. +""" + +import math + +import numpy as np +import pytest + +from examples.eicu_hourly_los_lstm import ( + compute_constant_baselines, + compute_los_metrics, + train_and_evaluate, +) +from pyhealth.tasks import TPCLengthOfStayEICU +from tests.core.tpc_fixtures import _lab, _labels, _patient + + +@pytest.mark.parametrize( + "hours,age,eligible", + [ + (4.99, "60", False), + (5, "18", True), + (5.5, "60", True), + (12, "17", False), + (12, None, False), + (12, "> 89", True), + (12, "invalid", False), + (-1, "60", False), + ], +) +def test_cohort(hours, age, eligible): + """Check adult cohort and minimum ICU stay requirements.""" + samples = TPCLengthOfStayEICU()(_patient(hours=hours, age=age, hr_hours=[])) + assert bool(samples) == eligible + + +def test_static_features(): + """Verify static features and invalid-value handling.""" + sample = TPCLengthOfStayEICU()(_patient(hours=5, age="> 89", gender="Female"))[0] + + assert sample["static"]["values"] == [[90, 0, 180, 80]] + + missing = TPCLengthOfStayEICU()( + _patient( + hours=5, + gender="Unknown", + height=-1, + weight=999, + ) + )[0] + + assert np.isnan(missing["static"]["values"][0][1:]).all() + + +def test_labels_and_horizon(): + """Verify hourly remaining LOS and 14-day truncation.""" + task = TPCLengthOfStayEICU() + + sample = task(_patient(hours=400.5, hr_hours=[0, 1]))[0] + + assert sample["los"]["time"] == list(range(5, 337)) + assert _labels(sample["los"])[0] == 395.5 + assert _labels(sample["los"])[-1] == 64.5 + assert sample["dynamic"]["values"].shape == (336, 48) + + short_sample = task(_patient(hours=5, hr_hours=[]))[0] + + assert _labels(short_sample["los"]) == [0.5] + + +def test_fractional_remaining_hours(): + """Check remaining LOS for fractional stay durations.""" + sample = TPCLengthOfStayEICU()(_patient(hours=6.5, hr_hours=[]))[0] + + assert sample["los"]["time"] == [5, 6] + assert _labels(sample["los"]) == [1.5, 0.5] + + +def test_minimum_remaining_los(): + """Ensure remaining LOS labels are at least 0.5 hours.""" + sample = TPCLengthOfStayEICU()(_patient(hours=6.25, hr_hours=[]))[0] + + assert sample["los"]["time"] == [5, 6] + assert _labels(sample["los"]) == [1.25, 0.5] + + +def test_optional_label_normalization(): + """Verify optional LOS normalization and schema isolation.""" + from pyhealth.processors import TimeseriesRegressionLabelProcessor + + normalized = TPCLengthOfStayEICU() + raw = TPCLengthOfStayEICU(normalize_labels=False) + + assert normalized.output_schema["los"][1]["normalization"] == "minmax" + assert raw.output_schema["los"][1]["normalization"] is None + + default_task = TPCLengthOfStayEICU() + assert default_task.output_schema["los"][1]["normalization"] == "minmax" + + sample = raw(_patient(hours=6.25, hr_hours=[]))[0] + + processor = TimeseriesRegressionLabelProcessor(**raw.output_schema["los"][1]) + processor.fit([sample], "los") + + values, times = processor.process(sample["los"]) + + np.testing.assert_allclose( + values.reshape(-1).numpy(), + [1.25, 0.5], + ) + + +def test_missingness_count_repeatability_no_mutation(): + """Verify masking fraction, reproducibility, and input safety.""" + values = np.arange(20, dtype=float).reshape(5, 4) + values[0, 0] = np.nan + + original = values.copy() + + for rate in [0, 0.1, 0.2, 1]: + task = TPCLengthOfStayEICU(missing_rate=rate) + + result = task._apply_missingness(values, 10) + + assert np.isnan(result).sum() == (1 + round(19 * rate)) + + np.testing.assert_equal( + result, + task._apply_missingness(values, 10), + ) + + np.testing.assert_equal(values, original) + + assert not np.shares_memory(values, result) + + np.testing.assert_equal( + TPCLengthOfStayEICU()._apply_missingness(values, 10), + values, + ) + + +@pytest.mark.parametrize( + "rate", + [-0.1, 1.1, float("nan")], +) +def test_invalid_rate(rate): + """Reject missingness rates outside the valid interval.""" + with pytest.raises(ValueError): + TPCLengthOfStayEICU(missing_rate=rate) + + +def test_hourly_measurements_and_missing_data(): + """Check hourly lab aggregation and masking.""" + task = TPCLengthOfStayEICU() + + patient = _patient( + hours=6, + hr_hours=[], + extra=[ + _lab(60, "potassium", 4), + _lab(90, "potassium", 6), + ], + ) + + sample = task(patient)[0] + k = task.DYNAMIC_FEATURES.index("k") + + assert sample["dynamic"]["values"][1, k] == 5 + assert np.isnan(sample["dynamic"]["values"][0, k]) + assert np.isnan(sample["dynamic"]["values"][2, k]) + + masked = TPCLengthOfStayEICU(missing_rate=1)(patient)[0] + + assert np.isnan(masked["dynamic"]["values"]).all() + + assert masked["los"] == sample["los"] + assert masked["static"] == sample["static"] + + +def test_forward_fill_after_removal(): + """Check forward-fill behavior after missingness removal.""" + from pyhealth.processors import JaggedFeatureProcessor + + values = { + "time": [0.0, 1.0, 2.0, 3.0], + "values": [ + [80.0], + [np.nan], + [100.0], + [np.nan], + ], + } + + proc = JaggedFeatureProcessor( + levels=[ + { + "ordering": "series", + "values": [1], + "impute": [ + {"method": "forward_fill"}, + {"method": "zero"}, + ], + } + ] + ) + + proc.fit([{"x": values}], "x") + + result = proc.process(values) + + np.testing.assert_allclose( + result[0].reshape(-1).numpy(), + [80, 80, 100, 100], + ) + + removed = { + "time": values["time"], + "values": [ + [80.0], + [np.nan], + [np.nan], + [np.nan], + ], + } + + np.testing.assert_allclose( + proc.process(removed)[0].reshape(-1).numpy(), + [80] * 4, + ) + + +def test_decay_oracle_and_full_removal(): + """Verify exponential decay and fully missing features.""" + raw = np.array( + [ + [np.nan, 80], + [4, np.nan], + [np.nan, 100], + [np.nan, np.nan], + [3, np.nan], + ], + dtype=float, + ) + + expected = [ + [0, 1], + [1, 0.75], + [0.75, 1], + [0.5625, 0.75], + [1, 0.5625], + ] + + np.testing.assert_allclose( + TPCLengthOfStayEICU._decay(raw), + expected, + ) + + removed = TPCLengthOfStayEICU(missing_rate=1)._apply_missingness(raw, 10) + + assert not TPCLengthOfStayEICU._decay(removed).any() + + +def test_decay_optional_schema_does_not_mutate_other_instances(): + """Ensure optional decay does not modify the class schema.""" + assert "decay" in TPCLengthOfStayEICU(include_decay=True).input_schema + + assert "decay" not in TPCLengthOfStayEICU().input_schema + + +def test_future_observations_do_not_change_earlier_hours(): + """Ensure future observations do not leak into earlier bins.""" + task = TPCLengthOfStayEICU() + + first = task(_patient(hours=12, hr_hours=[0, 2]))[0] + + future = task(_patient(hours=12, hr_hours=[0, 2, 10]))[0] + + np.testing.assert_equal( + first["dynamic"]["values"][:10], + future["dynamic"]["values"][:10], + ) + + +def test_stays_are_isolated(): + """Ensure measurements cannot leak between ICU stays.""" + from pyhealth.data import Patient + from tests.core.tpc_fixtures import _frame, _stay_rows + + task = TPCLengthOfStayEICU() + + rows = _stay_rows(10, 8, hr_hours=[0]) + _stay_rows(11, 8, hr_hours=[]) + + samples = { + sample["stay_id"]: sample + for sample in task( + Patient( + patient_id="same-patient", + data_source=_frame(rows), + ) + ) + } + + assert np.isfinite(samples[10]["dynamic"]["values"]).any() + + assert np.isnan(samples[11]["dynamic"]["values"]).all() + + +def test_empty_patient(): + """Return no samples for a patient without admission records.""" + from pyhealth.data import Patient + from tests.core.tpc_fixtures import _event, _frame + + patient = Patient( + patient_id="empty", + data_source=_frame([_event("lab")]), + ) + + assert TPCLengthOfStayEICU()(patient) == [] + + +@pytest.mark.parametrize( + "rate", + [0, 0.1, 0.2, 1], +) +def test_combined_mask_fill_and_decay(rate): + """Check masking, forward-fill, and decay together.""" + from pyhealth.processors import JaggedFeatureProcessor + + patient = _patient( + hours=8, + hr_hours=[0, 2, 4, 6], + ) + + task = TPCLengthOfStayEICU( + missing_rate=rate, + include_decay=True, + ) + + sample = task(patient)[0] + + original = TPCLengthOfStayEICU()(patient)[0]["dynamic"]["values"] + + raw = sample["dynamic"]["values"] + + assert np.isfinite(original).sum() - np.isfinite(raw).sum() == round(4 * rate) + + np.testing.assert_equal( + raw, + task(patient)[0]["dynamic"]["values"], + ) + + proc = JaggedFeatureProcessor( + levels=[ + { + "ordering": "series", + "values": [48], + "impute": [ + {"method": "forward_fill"}, + {"method": "zero"}, + ], + } + ] + ) + + proc.fit( + [{"x": sample["dynamic"]}], + "x", + ) + + filled = proc.process(sample["dynamic"])[0].numpy() + + hr = task.DYNAMIC_FEATURES.index("hr") + + retained = np.flatnonzero(np.isfinite(raw[:, hr])) + + if len(retained): + assert not filled[: retained[0], hr].any() + + assert not sample["decay"]["values"][: retained[0], hr].any() + + for start, end in zip( + retained, + [*retained[1:], len(raw)], + ): + np.testing.assert_allclose( + filled[start:end, hr], + raw[start, hr], + ) + + assert sample["decay"]["values"][start, hr] == 1 + + else: + assert not filled.any() + assert not sample["decay"]["values"].any() + + +def test_incomplete_hour_cannot_enter_prediction(): + """Prevent measurements from unfinished bins entering predictions.""" + task = TPCLengthOfStayEICU() + + baseline = task(_patient(hours=8, hr_hours=[]))[0] + + changed = task( + _patient( + hours=8, + hr_hours=[], + extra=[_lab(359, "potassium", 5)], + ) + )[0] + + for sample in [baseline, changed]: + assert sample["dynamic"]["time"] == list(range(1, 9)) + + times = np.asarray(changed["dynamic"]["time"]) + + np.testing.assert_equal( + baseline["dynamic"]["values"][times <= 5], + changed["dynamic"]["values"][times <= 5], + ) + + k = task.DYNAMIC_FEATURES.index("k") + + assert changed["dynamic"]["values"][5, k] == 5 + + assert changed["dynamic"]["time"][5] == 6 + + +def test_zero_removal_baseline_and_completed_extensions(): + """Verify implemented missingness and decay functionality.""" + raw = np.array([[80.0, np.nan]]) + + result = TPCLengthOfStayEICU(missing_rate=0)._apply_missingness(raw, 10) + + np.testing.assert_equal( + raw, + result, + ) + + assert not np.shares_memory( + raw, + result, + ) + + masked = TPCLengthOfStayEICU(missing_rate=1.0)._apply_missingness(raw, 10) + + assert np.isnan(masked).all() + + decay = TPCLengthOfStayEICU._decay(raw) + + np.testing.assert_allclose( + decay, + [[1.0, 0.0]], + ) + + +def test_output_timeline_with_optional_decay(): + """Ensure temporal features use the correct prediction timeline.""" + with_decay = TPCLengthOfStayEICU(include_decay=True) + without_decay = TPCLengthOfStayEICU(include_decay=False) + + assert with_decay.output_schema["los"][1]["timeline"] == [ + "dynamic", + "decay", + ] + assert without_decay.output_schema["los"][1]["timeline"] == ["dynamic"] + + +def test_compute_los_metrics_conventions(): + """Verify day conversion, 4h MAPE floor, MSLE clipping, R^2, and Kappa.""" + # Targets: [0h, 24h, 48h] -> [0, 1, 2] days; + # Preds: [2h, 24h, 72h] -> [1/12, 1, 3] days. + metrics = compute_los_metrics( + np.array([0.0, 24.0, 48.0]), + np.array([2.0, 24.0, 72.0]), + ) + + expected_mad = (2.0 / 24.0 + 0.0 + 1.0) / 3.0 + expected_mape = ((2.0 / 24.0) / (4.0 / 24.0) + 0.0 + 1.0 / 2.0) / 3.0 * 100.0 + expected_mse = ((2.0 / 24.0) ** 2 + 0.0 + 1.0) / 3.0 + expected_msle = ( + (math.log(2.0 / 24.0) - math.log(1.0 / 48.0)) ** 2 + + 0.0 + + (math.log(3.0) - math.log(2.0)) ** 2 + ) / 3.0 + + assert math.isclose(metrics["mad"], expected_mad, rel_tol=1e-9) + assert math.isclose(metrics["mape"], expected_mape, rel_tol=1e-9) + assert math.isclose(metrics["mse"], expected_mse, rel_tol=1e-9) + assert math.isclose(metrics["msle"], expected_msle, rel_tol=1e-9) + assert math.isclose(metrics["r2"], 1.0 - (3.0 * expected_mse) / 2.0, rel_tol=1e-9) + assert 0.0 <= metrics["kappa"] <= 1.0 + + # Negative predictions must be safely clipped for MSLE without NaNs. + neg_metrics = compute_los_metrics( + np.array([24.0, 48.0]), + np.array([-5.0, 48.0]), + ) + assert np.isfinite(neg_metrics["msle"]) + + +def test_compute_los_metrics_single_bin_and_validation(): + """Verify degenerate single-bin Kappa fallback and input validation.""" + single_bin = compute_los_metrics( + np.array([1.0, 2.0, 3.0]), + np.array([4.0, 5.0, 6.0]), + ) + assert single_bin["kappa"] == 0.0 + + with pytest.raises(ValueError): + compute_los_metrics(np.array([1.0, 2.0]), np.array([1.0])) + with pytest.raises(ValueError): + compute_los_metrics(np.array([]), np.array([])) + + +def test_compute_constant_baselines(): + """Verify training-set mean and median baselines score test targets.""" + baselines = compute_constant_baselines( + np.array([24.0, 24.0, 72.0]), + np.array([24.0, 72.0]), + ) + # Train mean = 40h (5/3 days), train median = 24h (1 day). + assert math.isclose(baselines["mean_baseline"]["mad"], 1.0, rel_tol=1e-9) + assert math.isclose(baselines["median_baseline"]["mad"], 1.0, rel_tol=1e-9) + assert baselines["mean_baseline"]["mse"] < baselines["median_baseline"]["mse"] + + +def test_train_and_evaluate_synthetic_smoke(): + """Verify synthetic training and baselines without a zero test rate.""" + rows = train_and_evaluate( + synthetic=True, + epochs=1, + test_rates=(0.1, 0.2), + batch_size=2, + embedding_dim=8, + hidden_dim=16, + num_layers=1, + device="cpu", + ) + + assert len(rows) == 6 + labels = [row["label"] for row in rows] + assert labels.count("Mean Baseline") == 1 + assert labels.count("Median Baseline") == 1 + assert labels.count("LSTM (Train 0% drop)") == 2 + assert labels.count("LSTM (Train 10% drop)") == 2 + + for row in rows: + if row["label"] in ("Mean Baseline", "Median Baseline"): + assert row["train_missing_rate"] == 0.0 + assert row["test_missing_rate"] == 0.1 + + metric_names = ("mad", "mape", "mse", "msle", "r2", "kappa") + for row in rows: + assert row["n_test_hours"] > 0 + for name in metric_names: + assert math.isfinite(row["metrics"][name]) diff --git a/tests/core/tpc_fixtures.py b/tests/core/tpc_fixtures.py new file mode 100644 index 0000000000..aa9ee844de --- /dev/null +++ b/tests/core/tpc_fixtures.py @@ -0,0 +1,113 @@ +""" +Contributors: Manling Tan, Yining Jin, Xiao Luo +NetIDs: manling4, yining34, xiaoluo6 + +Paper Title: +Temporal Pointwise Convolutional Networks for +Length of Stay Prediction in the Intensive Care Unit + +Paper Authors: +Emma Rocheteau, Pietro Liò, and Stephanie Hyland (2021) + +Paper URL: +https://arxiv.org/abs/2007.09483 + +Small synthetic eICU records; adapted from YAIB regression fixtures. +""" + +from pathlib import Path + +import polars as pl +import yaml + +from pyhealth.data import Patient + +# Every column of the eICU config, as in the dataset's event dataframe. +_CONFIG = yaml.safe_load( + ( + Path(__file__).parents[2] / "pyhealth" / "datasets" / "configs" / "eicu.yaml" + ).read_text() +) +COLUMNS = [ + f"{table}/{column}" + for table, config in _CONFIG["tables"].items() + for column in config["attributes"] +] + + +def _labels(records): + """The label values of a ``timeseries_*`` label series.""" + return [value[0] for value in records["values"]] + + +def _event(event_type, **attrs): + # Attributes are strings in the dataset's event dataframe. + row = {"event_type": event_type, "timestamp": None} + for key, value in attrs.items(): + row[f"{event_type}/{key}"] = None if value is None else str(value) + return row + + +def _frame(rows, patient_id="p1"): + df = pl.from_dicts(rows, infer_schema_length=None) + return df.with_columns( + pl.lit(patient_id).alias("patient_id"), + pl.col("timestamp").cast(pl.Datetime("ms")), + *( + (pl.col(c) if c in df.columns else pl.lit(None)).cast(pl.String).alias(c) + for c in COLUMNS + ), + ) + + +def _stay_rows( + stay_id, + hours, + age="60", + gender="Male", + height=180, + weight=80, + status="Alive", + hospital_id=1, + hr_hours=None, +): + """A stay and one heart rate per hour, so it passes the base cohort.""" + rows = [ + _event( + "patient", + patientunitstayid=stay_id, + unitdischargeoffset=int(hours * 60), + gender=gender, + age=age, + admissionheight=height, + admissionweight=weight, + unitdischargestatus=status, + hospitalid=hospital_id, + ) + ] + for hour in range(int(hours)) if hr_hours is None else hr_hours: + rows.append( + _event( + "vitalperiodic", + patientunitstayid=stay_id, + observationoffset=hour * 60 + 5, + heartrate=80 + hour, + ) + ) + return rows + + +def _patient(stay_id=10, hours: float = 48, extra=(), patient_id="p1", **stay): + rows = _stay_rows(stay_id, hours, **stay) + list(extra) + return Patient(patient_id=patient_id, data_source=_frame(rows, patient_id)) + + +def _lab(minute, name, value, unit="mg/dL", stay_id=10): + return _event( + "lab", + patientunitstayid=stay_id, + labresultoffset=minute, + labname=name, + labresult=value, + labmeasurenameinterface=unit, + )