diff --git a/docs/api/datasets.rst b/docs/api/datasets.rst index 7b95e009a8..b3b24f6faa 100644 --- a/docs/api/datasets.rst +++ b/docs/api/datasets.rst @@ -555,6 +555,11 @@ PyHealth does not ship any data: you download each dataset from its source and p - `GitHub `__ + `Hugging Face `__ - No (``kits23_download_data``) - Single CTs by URL (``wget``) + * - :doc:`Rotterdam ` + - Open + - `R survival `__ + - No + - — * - :doc:`TCGA-PRAD ` - Open - `GDC `__ @@ -665,6 +670,7 @@ Available Datasets datasets/pyhealth.datasets.Support2Dataset datasets/pyhealth.datasets.MetabricDataset datasets/pyhealth.datasets.GBSGDataset + datasets/pyhealth.datasets.RotterdamDataset datasets/pyhealth.datasets.BMDHSDataset datasets/pyhealth.datasets.COVID19CXRDataset datasets/pyhealth.datasets.ISIC2019Dataset diff --git a/docs/api/datasets/pyhealth.datasets.RotterdamDataset.rst b/docs/api/datasets/pyhealth.datasets.RotterdamDataset.rst new file mode 100644 index 0000000000..99cee8fb8d --- /dev/null +++ b/docs/api/datasets/pyhealth.datasets.RotterdamDataset.rst @@ -0,0 +1,71 @@ +pyhealth.datasets.RotterdamDataset +================================== + +Overview +-------- + +Load the Rotterdam tumour-bank breast-cancer cohort from a local CSV, keeping +recurrence and death as two separate outcomes. The file has one row per +patient: 2,982 patients with primary breast cancer (surgery 1978-1993), ten +baseline covariates, and for each outcome its own follow-up time in days and +event indicator (``rtime``/``recur`` and ``dtime``/``death``). 1,518 patients +recurred and 1,272 died; 1,077 had both events and 1,269 neither. + +This is the full multi-event cohort. It is not the 2,232-row pooled +Rotterdam/GBSG benchmark loaded by :doc:`pyhealth.datasets.GBSGDataset`, which +has seven features and a single recurrence-free survival endpoint in months. + +Patient times are kept exactly as recorded. 43 patients died after their +recurrence follow-up had ended without a recorded recurrence (``recur=0``, +``death=1``, ``rtime < dtime``); their recurrence stays censored at ``rtime`` +and is not extended to the death time. Tied recurrence and death times are +kept, and tumour ``size`` stays one of its three source categories +(``"<=20"``, ``"20-50"``, ``">50"`` mm); numeric coding belongs to the task. +The whole CSV is validated when the dataset is created, before anything is +cached, and errors name the column and ``pid``. The default task is +:class:`~pyhealth.tasks.MultiEventSurvivalRotterdam`. + +Data source +----------- + +The cohort is distributed with the R ``survival`` package as +`survival::rotterdam`_, from Royston and Altman, `External validation of a Cox +prognostic model: principles and methods`_ (BMC Medical Research Methodology, +2013). It is open; no account or agreement is needed. The MENSA authors ship +the same table as `data/rotterdam.csv`_ in their repository: download that +file (**Download raw file**) and put it in the folder you pass as ``root``. +Alternatively, export it from R with +``write.csv(survival::rotterdam, "rotterdam.csv", row.names = FALSE)``; the +loader validates whichever file you use. The loader never downloads anything. + +The CSV needs these 15 columns: ``pid``, ``year``, ``age``, ``meno``, +``size``, ``grade``, ``nodes``, ``pgr``, ``er``, ``hormon``, ``chemo``, +``rtime``, ``recur``, ``dtime`` and ``death``. + +Usage +----- + +.. code-block:: python + + from pyhealth.datasets import RotterdamDataset, split_by_patient + + dataset = RotterdamDataset(root="/path/to/folder") # holds rotterdam.csv + samples = dataset.set_task() # MultiEventSurvivalRotterdam by default + train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=0) + +See :doc:`../tasks/pyhealth.tasks.multi_event_survival_rotterdam` for the +sample format and :doc:`../models/pyhealth.models.MENSA` for a model that +uses it. + +API reference +------------- + +.. autoclass:: pyhealth.datasets.RotterdamDataset + :members: + :show-inheritance: + +.. autofunction:: pyhealth.datasets.rotterdam.parse_rotterdam_record + +.. _survival::rotterdam: https://stat.ethz.ch/R-manual/R-devel/library/survival/html/rotterdam.html +.. _External validation of a Cox prognostic model\: principles and methods: https://doi.org/10.1186/1471-2288-13-33 +.. _data/rotterdam.csv: https://github.com/thecml/mensa/blob/main/data/rotterdam.csv diff --git a/docs/api/models.rst b/docs/api/models.rst index 917d185afe..959ff53066 100644 --- a/docs/api/models.rst +++ b/docs/api/models.rst @@ -361,6 +361,7 @@ API Reference models/pyhealth.models.XGBoostModel models/pyhealth.models.survival_mdn models/pyhealth.models.personalized_survival_moe + models/pyhealth.models.MENSA models/pyhealth.models.cet models/pyhealth.models.TrajSurv models/pyhealth.models.KnowRare diff --git a/docs/api/models/pyhealth.models.MENSA.rst b/docs/api/models/pyhealth.models.MENSA.rst new file mode 100644 index 0000000000..1715860d7c --- /dev/null +++ b/docs/api/models/pyhealth.models.MENSA.rst @@ -0,0 +1,110 @@ +pyhealth.models.MENSA +===================== + +Overview +-------- + +MENSA (Multi-Event Network for Survival Analysis) predicts a survival curve +for each of several events from one shared network. Each event, plus an +event-free state used only in training, gets a mixture of Weibull +distributions and its own residual adapter on a shared trunk. Training +minimizes ``(1 - lambda) * L_surv + lambda * L_traj``: a weighted censored +likelihood over all states, plus a trajectory term that penalizes predicting +the later event (death) before the earlier one (recurrence) for patients who +had both. ``trajectory_variant="paper"`` follows the paper's Eq. 1; +``"reference"`` follows the authors' code. + +Paper +----- + +Lillelund, Gharari Foomani, Sun, Qi and Greiner, `MENSA: A Multi-Event Network +for Survival Analysis with Trajectory-based Likelihood Estimation`_, Machine +Learning for Health (ML4H) 2025, PMLR 297 (`arXiv:2409.06525`_). This +implementation is adapted from the authors' `reference code`_ (MIT License, +commit 6b219cd). + +Inputs and outputs +------------------ + +MENSA works with the ``"tensor"`` outputs of +:doc:`../tasks/pyhealth.tasks.multi_event_survival_rotterdam`: ``features +[F]``, ``event_times [K]`` and ``event_indicators [K]``, in source time units. +It has no label processor, so ``mode`` is ``None`` and PyHealth's Trainer +tracks only the loss; compute survival metrics from survival curves. + +Call ``fit_preprocessing`` with the **training split only** before training. +It fits the feature standardization, the per-state loss weights and the time +grid used for ``y_prob``, and stores them as buffers, so they are saved with +the model. ``forward`` returns ``loss``, ``y_prob`` (survival probabilities, +``[batch, K, T]`` on that grid) and ``y_true`` (times and indicators). +``predict_survival(features, times)`` returns ``[batch, K, len(times)]`` +curves on any time grid; it runs in evaluation mode without gradients and +restores each module's previous mode. + +Defaults are one hidden layer of 32, dropout 0.25, three Weibull components +and ``lambda = 0.25``, trained with batch size 32, learning rate 1e-3, weight +decay 1e-3 and gradient clipping at norm 1.0. The training loader drops its +last incomplete batch (``drop_last=True``), because BatchNorm cannot train on +a batch of one. The reference code's Rotterdam config uses +``hidden_dims=(16,)``, ``dropout=0.5`` and weight decay 1e-4 instead. + +Usage +----- + +.. code-block:: python + + import torch + from pyhealth.datasets import RotterdamDataset, get_dataloader, split_by_patient + from pyhealth.models import MENSA + from pyhealth.trainer import Trainer + + samples = RotterdamDataset(root="/path/to/folder").set_task() + train, val, test = split_by_patient(samples, [0.7, 0.1, 0.2], seed=0) + + model = MENSA(samples) + model.fit_preprocessing(train) # training split only + trainer = Trainer(model=model) + trainer.train( + train_dataloader=get_dataloader( + train, batch_size=32, shuffle=True, drop_last=True + ), + val_dataloader=get_dataloader(val, batch_size=1024), + epochs=1000, + optimizer_params={"lr": 1e-3}, + weight_decay=1e-3, + max_grad_norm=1.0, + monitor="loss", + monitor_criterion="min", + patience=20, + ) + + batch = next(iter(get_dataloader(test, batch_size=len(test)))) + times = torch.linspace(0, 7000, 50) # days + curves = model.predict_survival(batch["features"], times) # [N, 2, 50] + +API reference +------------- + +.. autoclass:: pyhealth.models.MENSA + :members: + :show-inheritance: + +Loss and distribution functions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Stateless tensor functions used by :class:`~pyhealth.models.MENSA`. + +.. autofunction:: pyhealth.models.mensa.mensa_loss +.. autofunction:: pyhealth.models.mensa.survival_nll +.. autofunction:: pyhealth.models.mensa.trajectory_nll +.. autofunction:: pyhealth.models.mensa.extend_labels +.. autofunction:: pyhealth.models.mensa.compute_state_weights +.. autofunction:: pyhealth.models.mensa.mixture_log_weights +.. autofunction:: pyhealth.models.mensa.mixture_log_survival +.. autofunction:: pyhealth.models.mensa.mixture_log_density +.. autofunction:: pyhealth.models.mensa.weibull_log_survival +.. autofunction:: pyhealth.models.mensa.weibull_log_density + +.. _MENSA\: A Multi-Event Network for Survival Analysis with Trajectory-based Likelihood Estimation: https://proceedings.mlr.press/v297/lillelund26a.html +.. _arXiv:2409.06525: https://arxiv.org/abs/2409.06525 +.. _reference code: https://github.com/thecml/mensa diff --git a/docs/api/tasks.rst b/docs/api/tasks.rst index 00149a96e0..6580b9afaa 100644 --- a/docs/api/tasks.rst +++ b/docs/api/tasks.rst @@ -326,3 +326,4 @@ Available Tasks Time-to-event survival (GBSG and SUPPORT) TCGA RNA-seq Survival Prediction Query-Focused EHR Summarization (MIMIC-III) + Multi-event survival (Rotterdam) diff --git a/docs/api/tasks/pyhealth.tasks.multi_event_survival_rotterdam.rst b/docs/api/tasks/pyhealth.tasks.multi_event_survival_rotterdam.rst new file mode 100644 index 0000000000..afe461c90b --- /dev/null +++ b/docs/api/tasks/pyhealth.tasks.multi_event_survival_rotterdam.rst @@ -0,0 +1,65 @@ +Multi-event survival (Rotterdam) +================================ + +Overview +-------- + +:class:`~pyhealth.tasks.MultiEventSurvivalRotterdam` turns each patient of +:doc:`../datasets/pyhealth.datasets.RotterdamDataset` into one sample with a +dense feature vector and two events, recurrence then death: + +- ``features``: ten values in this order: ``year``, ``age``, ``meno``, + ``grade``, ``nodes``, ``pgr``, ``er``, ``hormon``, ``chemo`` and + ``size_mm``, with tumour size coded as 10, 35 or 75 mm for ``"<=20"``, + ``"20-50"`` and ``">50"``. With ``use_treatment=False`` the treatment + indicators ``hormon`` and ``chemo`` are dropped, leaving eight features in + the same order; the labels do not change. +- ``event_times``: ``[rtime, dtime]`` in days, exactly as recorded. A + recurrence censored before a later death keeps its own ``rtime``, and tied + times are kept. +- ``event_indicators``: ``[recur, death]``, 1 for an observed event and 0 for + censoring at that time. + +Every value is validated by +:func:`~pyhealth.datasets.rotterdam.parse_rotterdam_record`. Features are not +standardized here: fit any standardization on training patients only, after +splitting. Like PyHealth's other duration/event survival tasks, the labels use +the ``"tensor"`` processor, so a model consuming them sets ``mode=None`` and +supplies its own censored likelihood to the standard Trainer, as +:doc:`../models/pyhealth.models.MENSA` does. + +Paper +----- + +The features, size coding and event order follow the Rotterdam setup of +Lillelund et al., `MENSA: A Multi-Event Network for Survival Analysis with +Trajectory-based Likelihood Estimation`_ (ML4H 2025, PMLR 297), and its +`reference code`_. + +Usage +----- + +.. code-block:: python + + from pyhealth.datasets import RotterdamDataset + from pyhealth.tasks import MultiEventSurvivalRotterdam + + dataset = RotterdamDataset(root="/path/to/folder") + samples = dataset.set_task(MultiEventSurvivalRotterdam()) # ten features + sample = samples[0] + sample["features"].shape # torch.Size([10]) + sample["event_times"] # tensor([rtime, dtime]), days + sample["event_indicators"] # tensor([recur, death]) + + # Without the treatment indicators (eight features): + samples_8 = dataset.set_task(MultiEventSurvivalRotterdam(use_treatment=False)) + +API reference +------------- + +.. autoclass:: pyhealth.tasks.MultiEventSurvivalRotterdam + :members: + :show-inheritance: + +.. _MENSA\: A Multi-Event Network for Survival Analysis with Trajectory-based Likelihood Estimation: https://proceedings.mlr.press/v297/lillelund26a.html +.. _reference code: https://github.com/thecml/mensa diff --git a/pyhealth/datasets/__init__.py b/pyhealth/datasets/__init__.py index 17043a7c6b..40b07a2e5c 100644 --- a/pyhealth/datasets/__init__.py +++ b/pyhealth/datasets/__init__.py @@ -89,6 +89,7 @@ def __init__(self, *args, **kwargs): ) from .meds import MEDSDataset as MEDSDataset from .metabric import MetabricDataset as MetabricDataset +from .rotterdam import RotterdamDataset as RotterdamDataset from .mimic3 import MIMIC3Dataset from .mimic4 import MIMIC4CXRDataset, MIMIC4Dataset, MIMIC4EHRDataset, MIMIC4NoteDataset from .mimic4 import MIMIC4EDDataset as MIMIC4EDDataset diff --git a/pyhealth/datasets/configs/rotterdam.yaml b/pyhealth/datasets/configs/rotterdam.yaml new file mode 100644 index 0000000000..9844801374 --- /dev/null +++ b/pyhealth/datasets/configs/rotterdam.yaml @@ -0,0 +1,21 @@ +version: "1.0" +tables: + rotterdam: + file_path: "rotterdam.csv" + patient_id: "pid" + timestamp: null + attributes: + - year + - age + - meno + - size + - grade + - nodes + - pgr + - er + - hormon + - chemo + - rtime + - recur + - dtime + - death diff --git a/pyhealth/datasets/rotterdam.py b/pyhealth/datasets/rotterdam.py new file mode 100644 index 0000000000..ea71959fda --- /dev/null +++ b/pyhealth/datasets/rotterdam.py @@ -0,0 +1,268 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +"""Rotterdam breast-cancer cohort with separate recurrence and death outcomes.""" + +import csv +import math +from collections.abc import Mapping +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import numpy as np + +from .base_dataset import BaseDataset + +if TYPE_CHECKING: + from pyhealth.tasks import MultiEventSurvivalRotterdam + +ROTTERDAM_COLUMNS: tuple[str, ...] = ( + "pid", + "year", + "age", + "meno", + "size", + "grade", + "nodes", + "pgr", + "er", + "hormon", + "chemo", + "rtime", + "recur", + "dtime", + "death", +) +ROTTERDAM_SIZE_CATEGORIES: tuple[str, ...] = ("<=20", "20-50", ">50") + +_BINARY = frozenset({"meno", "hormon", "chemo", "recur", "death"}) +_POSITIVE = frozenset({"age", "rtime", "dtime"}) +_NON_NEGATIVE = frozenset({"nodes", "pgr", "er"}) +_FLOAT32_MAX = float(np.finfo(np.float32).max) + + +def parse_rotterdam_record( + record: Mapping[str, Any], pid: str +) -> dict[str, float | str]: + """Validate one Rotterdam source row without imputation or label repair. + + Every value is checked and returned as read: numeric columns become + floats and ``size`` stays one of its three source categories. Times are + never shifted, rounded or replaced, so a recurrence censored before a + later death keeps its own ``rtime``. + + Args: + record: Mapping from the 14 non-ID column names to raw values, + typically strings read from the CSV. + pid: Patient identifier, used only in error messages. + + Returns: + The 14 validated values keyed by column name. + + Raises: + ValueError: If a value is missing, non-numeric, non-finite or outside + its allowed range, or if ``rtime`` exceeds ``dtime``. The message + names the column and the patient. + + Examples: + >>> values = parse_rotterdam_record( + ... {"year": "1992", "age": "74", "meno": "1", "size": "<=20", + ... "grade": "3", "nodes": "0", "pgr": "35", "er": "291", + ... "hormon": "0", "chemo": "0", "rtime": "1799", "recur": "0", + ... "dtime": "1799", "death": "0"}, + ... pid="1", + ... ) + >>> values["size"], values["rtime"], values["recur"] + ('<=20', 1799.0, 0.0) + """ + values: dict[str, float | str] = {} + for column in ROTTERDAM_COLUMNS[1:]: + raw = record.get(column) + text = "" if raw is None else str(raw).strip() + if not text: + raise ValueError(f"Rotterdam pid {pid!r}: {column} is missing") + if column == "size": + if text not in ROTTERDAM_SIZE_CATEGORIES: + raise ValueError( + f"Rotterdam pid {pid!r}: size must be one of " + f"{list(ROTTERDAM_SIZE_CATEGORIES)}, got {text!r}" + ) + values[column] = text + continue + try: + value = float(text) + except ValueError: + raise ValueError( + f"Rotterdam pid {pid!r}: {column} must be numeric, got {text!r}" + ) from None + if not math.isfinite(value) or abs(value) > _FLOAT32_MAX: + raise ValueError( + f"Rotterdam pid {pid!r}: {column} must be finite float32, got {text!r}" + ) + if column in _BINARY and value not in (0.0, 1.0): + raise ValueError( + f"Rotterdam pid {pid!r}: {column} must be 0 or 1, got {text!r}" + ) + if column in _POSITIVE and (value <= 0 or np.float32(value) <= 0): + raise ValueError( + f"Rotterdam pid {pid!r}: {column} must be strictly positive, " + f"got {text!r}" + ) + if column in _NON_NEGATIVE and value < 0: + raise ValueError( + f"Rotterdam pid {pid!r}: {column} must be non-negative, got {text!r}" + ) + values[column] = value + if values["rtime"] > values["dtime"]: + raise ValueError( + f"Rotterdam pid {pid!r}: rtime ({values['rtime']:g}) exceeds dtime " + f"({values['dtime']:g}); recurrence follow-up cannot outlast " + "death follow-up" + ) + return values + + +def _validate_rotterdam_csv(path: Path) -> int: + """Check the whole source file before any caching and count its patients. + + Args: + path: Location of rotterdam.csv. + + Returns: + Number of patient rows. + + Raises: + FileNotFoundError: If the file does not exist. + ValueError: If a column is missing, a pid is empty or repeated, a + value is invalid, or the file has no patient rows. + """ + seen: set[str] = set() + with path.open(newline="", encoding="utf-8") as stream: + reader = csv.DictReader(stream) + missing = set(ROTTERDAM_COLUMNS) - set(reader.fieldnames or ()) + if missing: + raise ValueError(f"Rotterdam CSV missing columns: {sorted(missing)}") + for row in reader: + pid = row["pid"] or "" + if not pid.strip() or pid in seen: + raise ValueError( + f"Rotterdam pid must be nonempty and unique, got {pid!r}" + ) + parse_rotterdam_record(row, pid) + seen.add(pid) + if not seen: + raise ValueError("Rotterdam CSV must contain at least one patient row") + return len(seen) + + +class RotterdamDataset(BaseDataset): + """Rotterdam breast-cancer cohort with recurrence and death outcomes. + + One row per patient from the Rotterdam tumor bank: 2,982 primary breast + cancer patients with ten baseline covariates and two outcomes, each with + its own follow-up time in days. ``rtime``/``recur`` give time to + recurrence or recurrence censoring, and ``dtime``/``death`` give time to + death or censoring. A patient can have both events, one or neither. + + All patient times are kept exactly as recorded. In the source, 43 + patients died without a recorded recurrence after recurrence follow-up + had ended (``recur=0``, ``death=1``, ``rtime < dtime``). Their recurrence + stays censored at ``rtime`` and is not extended to the death time. Tied + recurrence and death times are also kept. No value is imputed, rounded or + remapped: tumor ``size`` stays one of ``"<=20"``, ``"20-50"`` or ``">50"`` + (mm), and numeric coding belongs to the task. The default task is + :class:`~pyhealth.tasks.MultiEventSurvivalRotterdam`. + + This differs from :class:`~pyhealth.datasets.GBSGDataset`, which loads + DeepSurv's pooled Rotterdam/GBSG benchmark: 2,232 records, seven + features and a single recurrence-free survival endpoint in months. This + loader uses the full cohort released with the R ``survival`` package + (``survival::rotterdam``), as also distributed in the MENSA authors' + repository, and keeps both events separate for multi-event survival + analysis. + + Source: R ``survival`` package, ``survival::rotterdam`` + (https://stat.ethz.ch/R-manual/R-devel/library/survival/html/rotterdam.html), + from Royston and Altman (2013), https://doi.org/10.1186/1471-2288-13-33. + + The whole CSV is validated when the dataset is created, before anything + is cached. Validation requires all 15 columns; nonempty, unique ``pid`` + values; no missing values; finite numeric covariates; ``meno``, + ``hormon``, ``chemo``, ``recur`` and ``death`` coded 0/1; positive + ``age``, ``rtime`` and ``dtime``; non-negative ``nodes``, ``pgr`` and + ``er``; one of the three ``size`` categories; and ``rtime <= dtime``. + No network request is made by this loader. + + Args: + root: Directory containing rotterdam.csv. + tables: Optional table selection; only ``["rotterdam"]`` is supported. + dataset_name: Optional cache/display name, default ``"rotterdam"``. + config_path: Optional YAML configuration using the same column + contract. Defaults to ``configs/rotterdam.yaml``. + **kwargs: BaseDataset options, including cache_dir and num_workers. + + Raises: + ValueError: If the table selection or configuration is unsupported, + or the CSV fails validation. Messages name the column and pid. + FileNotFoundError: If rotterdam.csv does not exist under ``root``. + + Examples: + >>> from pyhealth.datasets import RotterdamDataset + >>> dataset = RotterdamDataset( # doctest: +SKIP + ... root="../data", cache_dir="../cache/rotterdam" + ... ) + >>> len(dataset.unique_patient_ids) # doctest: +SKIP + 2982 + >>> samples = dataset.set_task() # doctest: +SKIP + >>> patient = dataset.get_patient("1") # doctest: +SKIP + >>> event = patient.get_events("rotterdam")[0] # doctest: +SKIP + >>> event.attr_dict["rtime"], event.attr_dict["recur"] # doctest: +SKIP + ('1799', '0') + """ + + def __init__( + self, + root: str, + tables: list[str] | None = None, + dataset_name: str | None = None, + config_path: str | None = None, + **kwargs: Any, + ) -> None: + tables = ["rotterdam"] if tables is None else tables + if tables != ["rotterdam"]: + raise ValueError('RotterdamDataset supports only tables=["rotterdam"]') + super().__init__( + root=str(Path(root).expanduser().resolve()), + tables=tables, + dataset_name=dataset_name or "rotterdam", + config_path=config_path + or str(Path(__file__).parent / "configs" / "rotterdam.yaml"), + **kwargs, + ) + table = self.config.tables.get("rotterdam") + if ( + table is None + or table.patient_id != "pid" + or table.timestamp is not None + or not set(ROTTERDAM_COLUMNS[1:]).issubset(table.attributes) + ): + raise ValueError( + "Rotterdam config must use pid, no timestamp, and all 14 source " + "attributes" + ) + self.num_source_patients = _validate_rotterdam_csv( + Path(self.root) / table.file_path + ) + + @property + def default_task(self) -> "MultiEventSurvivalRotterdam": + """Recurrence/death task with ten features and source times in days. + + Examples: + >>> dataset = RotterdamDataset(root="../data") # doctest: +SKIP + >>> type(dataset.default_task).__name__ # doctest: +SKIP + 'MultiEventSurvivalRotterdam' + """ + from pyhealth.tasks import MultiEventSurvivalRotterdam + + return MultiEventSurvivalRotterdam() diff --git a/pyhealth/models/__init__.py b/pyhealth/models/__init__.py index 703b5c9fa8..175fea27c5 100644 --- a/pyhealth/models/__init__.py +++ b/pyhealth/models/__init__.py @@ -127,6 +127,7 @@ from .generators.corgan import CorGAN as CorGAN from .generators.tardiff import TarDiff as TarDiff from .survival_mdn import SurvivalMDN as SurvivalMDN +from .mensa import MENSA as MENSA from .personalized_survival_moe import PersonalizedSurvivalMoE as PersonalizedSurvivalMoE from .cet import CET as CET from .trajsurv import TrajSurv as TrajSurv diff --git a/pyhealth/models/mensa.py b/pyhealth/models/mensa.py new file mode 100644 index 0000000000..ff058a5302 --- /dev/null +++ b/pyhealth/models/mensa.py @@ -0,0 +1,840 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +# Adapted from thecml/mensa (MIT License, commit 6b219cd), +# Copyright (c) 2024 Christian Lillelund. Reimplemented natively; no code +# from that repository is imported. +"""MENSA model, with its pure Weibull-mixture functions and losses. + +The module-level functions are stateless: tensors in, tensors out. +:class:`MENSA` wraps them in a PyHealth model. States follow the +reference code's order: 0 is the event-free state (training only), and +1..K are the observed events (for Rotterdam, 1 = recurrence, 2 = death). + +Each mixture component is a Weibull distribution with log shape ``k`` and +log rate ``b``, so shape ``rho = exp(k)`` and rate ``lam = exp(b)``:: + + log S(t) = -(lam * t) ** rho + log f(t) = k + b + (rho - 1) * (b + log t) + log S(t) + +Components are mixed with weights ``softmax(gate / temperature)``. +""" + +from collections.abc import Sequence + +import torch +from torch import Tensor, nn + +from pyhealth.datasets import SampleDataset, get_dataloader +from pyhealth.models.base_model import BaseModel +from pyhealth.processors import LabelProcessor + +TRAJECTORY_VARIANTS: tuple[str, ...] = ("paper", "reference") + +# Numerical guards: log-parameters are capped before exponentiation and times +# are floored before taking logarithms. +MAX_LOG_PARAMETER = 20.0 +MIN_TIME = 1e-12 +# Cap on the survival exponent (e^b t)^(e^k), in log space. exp overflows +# float32 just above 88.7; beyond the cap survival is still 0 in float32, but +# the gradient stays finite instead of 0 * inf = NaN (see weibull_log_survival). +MAX_SURVIVAL_EXPONENT = 88.0 + + +def _rate_and_shape(log_shape: Tensor, log_rate: Tensor) -> tuple[Tensor, Tensor]: + """Return the capped log rate and the shape ``exp(min(k, 20))``.""" + capped_log_rate = log_rate.clamp(max=MAX_LOG_PARAMETER) + shape = torch.exp(log_shape.clamp(max=MAX_LOG_PARAMETER)) + return capped_log_rate, shape + + +def weibull_log_survival(time: Tensor, log_shape: Tensor, log_rate: Tensor) -> Tensor: + """Log survival of each Weibull component, ``-(exp(b) t) ** exp(k)``. + + Args: + time: Non-negative times, broadcastable against the parameters + (e.g. ``[B, 1]`` against ``[B, K]``). + log_shape: Log shape ``k`` per component. + log_rate: Log rate ``b`` per component. + + Returns: + Log survival per component, with the broadcast shape. Exactly 0 + (survival 1) wherever ``time == 0``. The exponent is capped at + ``MAX_SURVIVAL_EXPONENT``, so log survival never reaches ``-inf``: + a component that would overflow, even one with negligible mixture + weight or in a censored term the loss does not use, would otherwise + get the gradient ``0 * inf = NaN`` and corrupt every weight. Values + below the cap are unchanged. + + Examples: + >>> weibull_log_survival(torch.tensor([2.0]), torch.zeros(1), torch.zeros(1)) + tensor([-2.]) + """ + capped_log_rate, shape = _rate_and_shape(log_shape, log_rate) + log_time = torch.log(time.clamp(min=MIN_TIME)) + exponent = (shape * (capped_log_rate + log_time)).clamp(max=MAX_SURVIVAL_EXPONENT) + log_survival = -torch.exp(exponent) + return torch.where(time > 0, log_survival, torch.zeros_like(log_survival)) + + +def weibull_log_density(time: Tensor, log_shape: Tensor, log_rate: Tensor) -> Tensor: + """Log density of each Weibull component. + + ``log f = k + b + (exp(k) - 1) * (b + log t) + log S``. Times are + floored at a tiny positive value, so a zero time gives a large finite + value rather than an infinite one. + + Args: + time: Non-negative times, broadcastable against the parameters. + log_shape: Log shape ``k`` per component. + log_rate: Log rate ``b`` per component. + + Returns: + Log density per component, with the broadcast shape. + + Examples: + >>> weibull_log_density(torch.tensor([2.0]), torch.zeros(1), torch.zeros(1)) + tensor([-2.]) + """ + _, shape = _rate_and_shape(log_shape, log_rate) + clamped = time.clamp(min=MIN_TIME) + log_hazard = log_shape + log_rate + (shape - 1) * (log_rate + clamped.log()) + return log_hazard + weibull_log_survival(clamped, log_shape, log_rate) + + +def mixture_log_weights(gate_logits: Tensor, temperature: float = 1000.0) -> Tensor: + """Log mixture weights, ``log_softmax(gate / temperature)`` over components. + + Args: + gate_logits: Unnormalized gate outputs, ``[..., K]``. + temperature: Positive softmax temperature. The reference uses 1000, + which keeps the weights close to uniform early in training. + + Returns: + Log weights, ``[..., K]``, whose exponentials sum to 1. + + Raises: + ValueError: If the temperature is not positive. + + Examples: + >>> mixture_log_weights(torch.tensor([0.0, 0.0])).exp() + tensor([0.5000, 0.5000]) + """ + if not temperature > 0: + raise ValueError("temperature must be positive") + return torch.log_softmax(gate_logits / temperature, dim=-1) + + +def mixture_log_survival( + time: Tensor, + log_shape: Tensor, + log_rate: Tensor, + gate_logits: Tensor, + temperature: float = 1000.0, +) -> Tensor: + """Log survival of a Weibull mixture, ``logsumexp(log pi + log S_j)``. + + Args: + time: Times with shape ``[...]``; a component axis is added. + log_shape: Log shapes, ``[..., K]``. + log_rate: Log rates, ``[..., K]``. + gate_logits: Unnormalized gate outputs, ``[..., K]``. + temperature: Softmax temperature for the gate. + + Returns: + Mixture log survival with shape ``[...]``; exactly 0 where + ``time == 0`` and never above 0. When every component is still + near 1, float32 rounding in ``logsumexp`` can return a value one + step above 0 (survival 1.0000001); capping removes it. + + Examples: + Two equal unit-rate exponential components (shape 1, rate 1): + + >>> zeros = torch.zeros(2, 2) + >>> mixture_log_survival(torch.tensor([0.0, 1.0]), zeros, zeros, zeros).exp() + tensor([1.0000, 0.3679]) + """ + log_weights = mixture_log_weights(gate_logits, temperature) + components = weibull_log_survival(time.unsqueeze(-1), log_shape, log_rate) + log_survival = torch.logsumexp(log_weights + components, dim=-1).clamp(max=0.0) + return torch.where(time > 0, log_survival, torch.zeros_like(log_survival)) + + +def mixture_log_density( + time: Tensor, + log_shape: Tensor, + log_rate: Tensor, + gate_logits: Tensor, + temperature: float = 1000.0, +) -> Tensor: + """Log density of a Weibull mixture, ``logsumexp(log pi + log f_j)``. + + Args: + time: Times with shape ``[...]``; a component axis is added. + log_shape: Log shapes, ``[..., K]``. + log_rate: Log rates, ``[..., K]``. + gate_logits: Unnormalized gate outputs, ``[..., K]``. + temperature: Softmax temperature for the gate. + + Returns: + Mixture log density with shape ``[...]``. + + Examples: + >>> zeros = torch.zeros(1, 2) + >>> mixture_log_density(torch.tensor([1.0]), zeros, zeros, zeros).exp() + tensor([0.3679]) + """ + log_weights = mixture_log_weights(gate_logits, temperature) + components = weibull_log_density(time.unsqueeze(-1), log_shape, log_rate) + return torch.logsumexp(log_weights + components, dim=-1) + + +def extend_labels( + event_times: Tensor, event_indicators: Tensor +) -> tuple[Tensor, Tensor]: + """Prepend the event-free state to per-event times and indicators. + + The event-free state's time is the patient's largest observed time, + and its indicator is 1 only when no event was observed. The input + times are copied unchanged into columns 1..K. + + Args: + event_times: ``[B, K]`` times, one column per event. + event_indicators: ``[B, K]`` 0/1 indicators in the same order. + + Returns: + ``(times, indicators)``, each ``[B, K + 1]`` with state 0 first. + + Raises: + ValueError: If the inputs are not matching 2-D tensors. + + Examples: + >>> t, e = extend_labels(torch.tensor([[1200.0, 2100.0]]), + ... torch.tensor([[0.0, 1.0]])) + >>> t.tolist(), e.tolist() + ([[2100.0, 1200.0, 2100.0]], [[0.0, 0.0, 1.0]]) + """ + if event_times.ndim != 2 or event_times.shape != event_indicators.shape: + raise ValueError("event_times and event_indicators must both be [B, K]") + event_free_time = event_times.max(dim=1, keepdim=True).values + event_free = (event_indicators.sum(dim=1, keepdim=True) == 0).to( + event_indicators.dtype + ) + return ( + torch.cat([event_free_time, event_times], dim=1), + torch.cat([event_free, event_indicators], dim=1), + ) + + +def compute_state_weights(train_indicators: Tensor) -> Tensor: + """Inverse-frequency state weights, rescaled to sum to the state count. + + ``w_p = 1 / (n_p + 1e-8)`` where ``n_p`` is the number of training + patients with state ``p`` observed, then ``w * P / sum(w)``. Compute + these from the training split only. + + Args: + train_indicators: ``[N, P]`` extended 0/1 indicators, as returned + by :func:`extend_labels`. + + Returns: + ``[P]`` weights summing to ``P``. + + Examples: + >>> compute_state_weights(torch.tensor([[1.0, 0, 0], [0, 1, 1], [1, 0, 1]])) + tensor([0.7500, 1.5000, 0.7500]) + """ + counts = train_indicators.sum(dim=0).to(torch.float32) + weights = 1.0 / (counts + 1e-8) + return weights / weights.sum() * counts.numel() + + +def survival_nll( + log_density: Tensor, + log_survival: Tensor, + indicators: Tensor, + state_weights: Tensor | None = None, +) -> Tensor: + """Weighted censored negative log-likelihood over all states. + + ``-(1/N) sum_p w_p sum_i [d_ip log f_p(t_ip) + (1 - d_ip) log S_p(t_ip)]``. + Each patient contributes the density for observed states and the + survival for censored ones. The unused term is never multiplied in, so + an infinite unused value cannot produce NaN. + + Args: + log_density: ``[B, P]`` mixture log density at each state's time. + log_survival: ``[B, P]`` mixture log survival at each state's time. + indicators: ``[B, P]`` 0/1 observed indicators. + state_weights: Optional ``[P]`` weights; all ones when omitted. + + Returns: + Scalar loss averaged over the batch. + + Examples: + One patient, state 0 observed (density 0.5) and state 1 censored + (survival 0.4), so the loss is ``-(log 0.5 + log 0.4)``: + + >>> log_f = torch.tensor([[0.5, 0.2]]).log() + >>> log_s = torch.tensor([[0.8, 0.4]]).log() + >>> survival_nll(log_f, log_s, torch.tensor([[1.0, 0.0]])) + tensor(1.6094) + """ + observed = indicators == 1 + log_likelihood = torch.where(observed, log_density, log_survival) + if state_weights is not None: + log_likelihood = log_likelihood * state_weights + return -log_likelihood.sum() / indicators.shape[0] + + +def trajectory_nll( + log_survival_later: Tensor, + indicators: Tensor, + earlier: int = 1, + later: int = 2, + variant: str = "paper", +) -> Tensor: + """Penalty for predicting the later event before the earlier one. + + Applies to patients who had both events. With ``variant="paper"`` + (Eq. 1 of the proposal), pass ``log S_later(t_earlier)``: the model + should say the later event had not yet happened when the earlier one + did. The sum is divided by the full batch size. With + ``variant="reference"`` (the authors' code), pass + ``log S_later(t_later)``; the loss is the mean over patients with both + events, or 0 when there are none. + + Args: + log_survival_later: ``[B]`` log survival of the later event at the + time the variant requires. + indicators: ``[B, P]`` extended 0/1 indicators. + earlier: State index of the earlier event (1 = recurrence). + later: State index of the later event (2 = death). + variant: ``"paper"`` or ``"reference"``. + + Returns: + Scalar penalty; 0 when no patient in the batch had both events. + + Raises: + ValueError: If ``variant`` is unknown. + + Examples: + Two patients; only the first had both events, with + ``S_death(t_recurrence) = 0.9``, so the paper variant gives + ``-log(0.9) / 2``: + + >>> indicators = torch.tensor([[0.0, 1.0, 1.0], [0.0, 1.0, 0.0]]) + >>> log_s_later = torch.tensor([0.9, 0.5]).log() + >>> trajectory_nll(log_s_later, indicators) + tensor(0.0527) + >>> trajectory_nll(log_s_later, indicators, variant="reference") + tensor(0.1054) + """ + if variant not in TRAJECTORY_VARIANTS: + raise ValueError(f"variant must be one of {list(TRAJECTORY_VARIANTS)}") + both = (indicators[:, earlier] == 1) & (indicators[:, later] == 1) + selected = torch.where( + both, log_survival_later, torch.zeros_like(log_survival_later) + ) + if variant == "paper": + return -selected.sum() / indicators.shape[0] + count = both.sum() + return -selected.sum() / count.clamp(min=1) + + +def mensa_loss( + log_density: Tensor, + log_survival: Tensor, + indicators: Tensor, + log_survival_later: Tensor, + state_weights: Tensor | None = None, + trajectory_weight: float = 0.25, + variant: str = "paper", + earlier: int = 1, + later: int = 2, +) -> Tensor: + """Total MENSA loss, ``(1 - lambda) * L_surv + lambda * L_traj``. + + Args: + log_density: ``[B, P]`` mixture log density at each state's time. + log_survival: ``[B, P]`` mixture log survival at each state's time. + indicators: ``[B, P]`` extended 0/1 indicators. + log_survival_later: ``[B]`` input for :func:`trajectory_nll`. + state_weights: Optional ``[P]`` weights from the training split. + trajectory_weight: ``lambda`` in ``[0, 1]``; 0.25 in the paper's + Rotterdam setting. + variant: Trajectory variant, ``"paper"`` or ``"reference"``. + earlier: State index of the earlier event. + later: State index of the later event. + + Returns: + Scalar loss. + + Raises: + ValueError: If ``trajectory_weight`` is outside ``[0, 1]`` or + ``variant`` is unknown. + + Examples: + >>> indicators = torch.tensor([[0.0, 1.0, 1.0], [0.0, 1.0, 0.0]]) + >>> log_f = torch.tensor([[0.1, 0.2, 0.3], [0.2, 0.3, 0.1]]).log() + >>> log_s = torch.tensor([[0.9, 0.5, 0.6], [0.8, 0.4, 0.7]]).log() + >>> log_s_later = torch.tensor([0.9, 0.5]).log() + >>> mensa_loss(log_f, log_s, indicators, log_s_later) + tensor(1.7766) + >>> mensa_loss(log_f, log_s, indicators, log_s_later, trajectory_weight=0.0) + tensor(2.3513) + """ + if not 0.0 <= trajectory_weight <= 1.0: + raise ValueError("trajectory_weight must be in [0, 1]") + surv = survival_nll(log_density, log_survival, indicators, state_weights) + traj = trajectory_nll(log_survival_later, indicators, earlier, later, variant) + return (1.0 - trajectory_weight) * surv + trajectory_weight * traj + + +def _value_tensor(value: Tensor | tuple[Tensor, ...]) -> Tensor: + """Return the primary tensor emitted by a PyHealth processor.""" + return value[0] if isinstance(value, tuple) else value + + +class _MENSANetwork(nn.Module): + """Shared trunk with a residual adapter and Weibull heads per state. + + Follows the reference architecture: ``Linear -> BatchNorm1d -> ReLU6 -> + Dropout`` blocks, then for each state ``h_p = h + adapter_p(h)`` and + linear shape, rate and gate heads. Shape and rate are + ``SELU(head(h_p)) + base``, where the per-state base offsets start at -1. + + Args: + input_dim: Number of input features. + hidden_dims: Widths of the shared hidden layers. + n_dists: Weibull components per state. + n_states: Number of states, including the event-free state. + dropout: Dropout probability after each shared layer. + """ + + def __init__( + self, + input_dim: int, + hidden_dims: Sequence[int], + n_dists: int, + n_states: int, + dropout: float, + ) -> None: + super().__init__() + blocks: list[nn.Module] = [] + width = input_dim + for hidden in hidden_dims: + blocks += [ + nn.Linear(width, hidden), + nn.BatchNorm1d(hidden), + nn.ReLU6(), + nn.Dropout(dropout), + ] + width = hidden + self.embedding = nn.Sequential(*blocks) + adapter_width = max(16, width // 2) + self.adapters = nn.ModuleList( + nn.Sequential( + nn.Linear(width, adapter_width), + nn.ReLU6(), + nn.Linear(adapter_width, width), + ) + for _ in range(n_states) + ) + self.shape_heads = nn.ModuleList( + nn.Linear(width, n_dists) for _ in range(n_states) + ) + self.rate_heads = nn.ModuleList( + nn.Linear(width, n_dists) for _ in range(n_states) + ) + self.gate_heads = nn.ModuleList( + nn.Linear(width, n_dists, bias=False) for _ in range(n_states) + ) + self.base_log_shape = nn.Parameter(-torch.ones(n_states, n_dists)) + self.base_log_rate = nn.Parameter(-torch.ones(n_states, n_dists)) + self.activation = nn.SELU() + + def forward(self, features: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Map standardized features to mixture parameters. + + Args: + features: ``[B, F]`` standardized features. + + Returns: + ``(log_shape, log_rate, gate_logits)``, each ``[B, P, K]``. Gate + logits are raw; the mixture functions apply the temperature. + """ + shared = self.embedding(features) + log_shapes, log_rates, gates = [], [], [] + for p, adapter in enumerate(self.adapters): + state = shared + adapter(shared) + log_shapes.append( + self.activation(self.shape_heads[p](state)) + self.base_log_shape[p] + ) + log_rates.append( + self.activation(self.rate_heads[p](state)) + self.base_log_rate[p] + ) + gates.append(self.gate_heads[p](state)) + return ( + torch.stack(log_shapes, dim=1), + torch.stack(log_rates, dim=1), + torch.stack(gates, dim=1), + ) + + +class MENSA(BaseModel): + """Multi-event survival network with a trajectory-based likelihood. + + MENSA (Lillelund et al.) predicts a survival curve for each of several + events from one shared network. Each event, plus an event-free state used + only in training, gets a mixture of Weibull distributions. Training + minimizes ``(1 - lambda) * L_surv + lambda * L_traj``: a weighted + censored likelihood over all states, plus a penalty when a patient who + had both events is predicted to have the later event before the earlier + one (:func:`mensa_loss`). + + Works with the ``"tensor"`` outputs of + :class:`~pyhealth.tasks.MultiEventSurvivalRotterdam`: ``features [F]``, + ``event_times [K]`` and ``event_indicators [K]``, in source time units. + Like :class:`~pyhealth.models.SurvivalMDN`, it has no label processor, so + ``mode`` is ``None`` and PyHealth's Trainer tracks only the loss. Compute + survival metrics from :meth:`predict_survival` or ``y_prob``. + + Before training, call :meth:`fit_preprocessing` with the **training + split only**. It fits the feature standardization, the state weights and + the time grid used for ``y_prob``, and stores them as buffers, so they + are saved and restored with the model's ``state_dict``. + + Defaults follow this reproduction's Rotterdam setting: one hidden layer + of 32, dropout 0.25, three components and ``lambda = 0.25``, trained with + batch size 32, learning rate 1e-3, weight decay 1e-3 and gradient + clipping at norm 1.0, e.g. + ``get_dataloader(train, batch_size=32, shuffle=True, drop_last=True)`` + and ``Trainer.train(...)`` with ``optimizer_params={"lr": 1e-3}``, + ``weight_decay=1e-3`` and ``max_grad_norm=1.0``. ``drop_last`` matters + because BatchNorm cannot train on a batch of one. The reference code's + Rotterdam config (``configs/mensa/rotterdam.yaml`` in thecml/mensa, + commit 6b219cd) instead uses ``hidden_dims=(16,)``, + ``dropout=0.5`` and weight decay 1e-4, with the same components, + ``lambda = 0.25``, batch size, learning rate and up to 1000 epochs; pass + those to match it. + + Args: + dataset: Sample dataset defining the schema; used to check keys and + infer the number of features and events. + feature_key: Input key of the dense feature vector. + times_key: Output key of the per-event times. + indicators_key: Output key of the per-event 0/1 indicators. + hidden_dims: Widths of the shared hidden layers. + n_dists: Weibull components per state. + dropout: Dropout probability in the shared layers. + trajectory_weight: ``lambda`` in ``[0, 1]``. + trajectory_variant: ``"paper"`` (Eq. 1, ``S_later(t_earlier)``) or + ``"reference"`` (the authors' code, ``S_later(t_later)``). + trajectory: ``(earlier, later)`` event positions in ``event_times``, + 1-based; ``(1, 2)`` is recurrence before death. + temperature: Softmax temperature of the mixture gates. + num_time_bins: Training-time quantiles in the ``y_prob`` grid; the + grid also starts at 0. The reference uses ``ceil(sqrt(N))``. + + Examples: + >>> from pyhealth.datasets import RotterdamDataset, split_by_patient + >>> from pyhealth.models import MENSA + >>> samples = RotterdamDataset(root="../data").set_task() # doctest: +SKIP + >>> ratios = [0.7, 0.1, 0.2] + >>> train, val, test = split_by_patient(samples, ratios) # doctest: +SKIP + >>> model = MENSA(samples) # doctest: +SKIP + >>> model.fit_preprocessing(train) # doctest: +SKIP + """ + + @property + def label_processors(self) -> dict[str, LabelProcessor]: + """None: the model scores its survival outputs with its own loss. + + Examples: + >>> model.label_processors # doctest: +SKIP + {} + """ + return {} + + def __init__( + self, + dataset: SampleDataset, + feature_key: str = "features", + times_key: str = "event_times", + indicators_key: str = "event_indicators", + hidden_dims: Sequence[int] = (32,), + n_dists: int = 3, + dropout: float = 0.25, + trajectory_weight: float = 0.25, + trajectory_variant: str = "paper", + trajectory: tuple[int, int] = (1, 2), + temperature: float = 1000.0, + num_time_bins: int = 50, + ) -> None: + super().__init__(dataset) + if feature_key not in dataset.input_schema: + raise ValueError(f"feature_key {feature_key!r} is not an input key") + for key in (times_key, indicators_key): + if key not in dataset.output_schema: + raise ValueError(f"output key {key!r} is not in the dataset") + if not 0.0 <= trajectory_weight <= 1.0: + raise ValueError("trajectory_weight must be in [0, 1]") + if trajectory_variant not in TRAJECTORY_VARIANTS: + raise ValueError( + f"trajectory_variant must be one of {list(TRAJECTORY_VARIANTS)}" + ) + if not 0.0 <= dropout < 1.0: + raise ValueError("dropout must be in [0, 1)") + if n_dists < 1 or num_time_bins < 2 or not temperature > 0: + raise ValueError( + "n_dists must be >= 1, num_time_bins >= 2 and temperature > 0" + ) + sample = dataset[0] + features = torch.as_tensor(_value_tensor(sample[feature_key])) + times = torch.as_tensor(_value_tensor(sample[times_key])) + if features.ndim != 1 or times.ndim != 1: + raise ValueError("features and event times must be 1-D per sample") + self.feature_key = feature_key + self.times_key = times_key + self.indicators_key = indicators_key + self.input_dim = int(features.shape[0]) + self.n_events = int(times.shape[0]) + self.n_states = self.n_events + 1 + earlier, later = trajectory + if not 1 <= earlier <= self.n_events or not 1 <= later <= self.n_events: + raise ValueError(f"trajectory must name events 1..{self.n_events}") + if earlier == later: + raise ValueError("trajectory needs two different events") + self.trajectory = (int(earlier), int(later)) + self.hidden_dims = tuple(int(h) for h in hidden_dims) + self.n_dists = int(n_dists) + self.dropout = float(dropout) + self.trajectory_weight = float(trajectory_weight) + self.trajectory_variant = trajectory_variant + self.temperature = float(temperature) + self.network = _MENSANetwork( + self.input_dim, self.hidden_dims, self.n_dists, self.n_states, dropout + ) + # Fixed-size buffers, filled by fit_preprocessing and kept in state_dict. + self.register_buffer("feature_mean", torch.zeros(self.input_dim)) + self.register_buffer("feature_scale", torch.ones(self.input_dim)) + self.register_buffer("state_weights", torch.ones(self.n_states)) + self.register_buffer("time_grid", torch.zeros(num_time_bins + 1)) + self.register_buffer("is_fitted", torch.tensor(False)) + + @torch.no_grad() + def fit_preprocessing(self, train_dataset: SampleDataset) -> None: + """Fit standardization, state weights and the time grid on training data. + + Feature means and population standard deviations (constant features + get scale 1), inverse-frequency state weights + (:func:`compute_state_weights`), and a grid of 0 followed by + ``num_time_bins`` quantiles of all training event times. + + Args: + train_dataset: The training split only. Using validation or test + patients here leaks their information into the model. + + Raises: + ValueError: If the split is empty, has the wrong widths, or holds + non-finite values or invalid labels. + + Examples: + The grid is 0 followed by ``num_time_bins`` (50) quantiles: + + >>> model = MENSA(samples) # doctest: +SKIP + >>> model.fit_preprocessing(train) # doctest: +SKIP + >>> model.time_grid.shape # doctest: +SKIP + torch.Size([51]) + """ + features, times, indicators = [], [], [] + for batch in get_dataloader(train_dataset, batch_size=1024, shuffle=False): + features.append(torch.as_tensor(_value_tensor(batch[self.feature_key]))) + times.append(torch.as_tensor(_value_tensor(batch[self.times_key]))) + indicators.append( + torch.as_tensor(_value_tensor(batch[self.indicators_key])) + ) + if not features: + raise ValueError("train_dataset must contain at least one sample") + x = torch.cat(features).double() + t = torch.cat(times).double() + e = torch.cat(indicators).double() + if x.shape[1] != self.input_dim or t.shape[1] != self.n_events: + raise ValueError("train_dataset widths do not match the model") + self._check_labels(t, e) + if not torch.isfinite(x).all(): + raise ValueError("training features must be finite") + scale = x.std(dim=0, unbiased=False) + scale = torch.where(scale > 0, scale, torch.ones_like(scale)) + levels = torch.linspace(0, 1, self.time_grid.numel() - 1, dtype=torch.float64) + grid = torch.cat([torch.zeros(1, dtype=torch.float64), t.quantile(levels)]) + _, extended = extend_labels(t, e) + self.feature_mean.copy_(x.mean(dim=0)) + self.feature_scale.copy_(scale) + self.state_weights.copy_(compute_state_weights(extended)) + self.time_grid.copy_(grid) + self.is_fitted.fill_(True) + + @staticmethod + def _check_labels(times: Tensor, indicators: Tensor) -> None: + """Reject non-finite or non-positive times and non-binary indicators.""" + if times.shape != indicators.shape: + raise ValueError("event_times and event_indicators must match in shape") + if not torch.isfinite(times).all() or (times <= 0).any(): + raise ValueError("event times must be finite and strictly positive") + if not ((indicators == 0) | (indicators == 1)).all(): + raise ValueError("event indicators must be 0 or 1") + + def _mixture(self, features: Tensor) -> tuple[Tensor, Tensor, Tensor]: + """Standardize features and return per-state mixture parameters.""" + if not bool(self.is_fitted): + raise RuntimeError( + "Call fit_preprocessing(train_dataset) before using MENSA" + ) + features = torch.as_tensor(features, dtype=torch.float32, device=self.device) + if features.ndim != 2 or features.shape[1] != self.input_dim: + raise ValueError( + f"features must be [batch, {self.input_dim}], " + f"got {tuple(features.shape)}" + ) + if features.shape[0] == 0 or not torch.isfinite(features).all(): + raise ValueError("features must be nonempty and finite") + return self.network((features - self.feature_mean) / self.feature_scale) + + def _event_survival( + self, log_shape: Tensor, log_rate: Tensor, gate: Tensor, times: Tensor + ) -> Tensor: + """Survival of each event (not the event-free state) at shared times.""" + batch, n_times = log_shape.shape[0], times.numel() + grid = times.reshape(1, 1, n_times).expand(batch, self.n_events, n_times) + log_survival = mixture_log_survival( + grid, + log_shape[:, 1:, None, :], + log_rate[:, 1:, None, :], + gate[:, 1:, None, :], + self.temperature, + ) + return log_survival.exp() + + def forward(self, **kwargs: Tensor | tuple[Tensor, ...]) -> dict[str, Tensor]: + """Compute the loss and survival curves for one batch. + + Args: + **kwargs: Batch fields from the PyHealth dataloader. The feature + key is required; with the times and indicators keys present, + the loss and ``y_true`` are also returned. + + Returns: + ``y_prob``: ``[B, K, T]`` survival of each event on + :attr:`time_grid`. With labels, also ``loss`` (scalar) and + ``y_true``: ``[B, 2K]`` as event times then indicators. + + Raises: + RuntimeError: If :meth:`fit_preprocessing` has not been called. + KeyError: If the feature key, or only one label key, is missing. + ValueError: For malformed features or labels. + + Examples: + >>> from pyhealth.datasets import get_dataloader + >>> loader = get_dataloader(test, batch_size=64) # doctest: +SKIP + >>> batch = next(iter(loader)) # doctest: +SKIP + >>> out = model(**batch) # doctest: +SKIP + >>> sorted(out), out["y_prob"].shape # doctest: +SKIP + (['loss', 'y_prob', 'y_true'], torch.Size([64, 2, 51])) + """ + if self.feature_key not in kwargs: + raise KeyError(f"Missing required batch field: {self.feature_key!r}") + log_shape, log_rate, gate = self._mixture( + _value_tensor(kwargs[self.feature_key]) + ) + output = { + "y_prob": self._event_survival(log_shape, log_rate, gate, self.time_grid) + } + has_labels = [k in kwargs for k in (self.times_key, self.indicators_key)] + if not any(has_labels): + return output + if not all(has_labels): + raise KeyError("Provide both event times and event indicators, or neither") + times = torch.as_tensor( + _value_tensor(kwargs[self.times_key]), + dtype=torch.float32, + device=self.device, + ).reshape(-1, self.n_events) + indicators = torch.as_tensor( + _value_tensor(kwargs[self.indicators_key]), + dtype=torch.float32, + device=self.device, + ).reshape(-1, self.n_events) + self._check_labels(times, indicators) + ext_times, ext_indicators = extend_labels(times, indicators) + log_density = mixture_log_density( + ext_times, log_shape, log_rate, gate, self.temperature + ) + log_survival = mixture_log_survival( + ext_times, log_shape, log_rate, gate, self.temperature + ) + earlier, later = self.trajectory + if self.trajectory_variant == "paper": + log_survival_later = mixture_log_survival( + ext_times[:, earlier], + log_shape[:, later], + log_rate[:, later], + gate[:, later], + self.temperature, + ) + else: + log_survival_later = log_survival[:, later] + output["loss"] = mensa_loss( + log_density, + log_survival, + ext_indicators, + log_survival_later, + self.state_weights, + self.trajectory_weight, + self.trajectory_variant, + earlier, + later, + ) + output["y_true"] = torch.cat([times, indicators], dim=1) + return output + + @torch.no_grad() + def predict_survival(self, features: Tensor, times: Tensor) -> Tensor: + """Predict each event's survival probability at the given times. + + Runs in evaluation mode without gradients, so BatchNorm statistics + and dropout are not affected, and restores every module's previous + mode afterwards. + + Args: + features: ``[B, F]`` raw (unstandardized) features. + times: ``[T]`` non-negative times, in the label units. + + Returns: + ``[B, K, T]`` survival probabilities, non-increasing in time, + equal to 1 at time 0. + + Raises: + RuntimeError: If :meth:`fit_preprocessing` has not been called. + ValueError: For malformed features or negative times. + + Examples: + >>> times = torch.linspace(0, 7000, 50) + >>> features = batch["features"] # doctest: +SKIP + >>> curves = model.predict_survival(features, times) # doctest: +SKIP + >>> curves.shape # doctest: +SKIP + torch.Size([64, 2, 50]) + """ + times = torch.as_tensor(times, dtype=torch.float32, device=self.device) + times = times.reshape(-1) + if not torch.isfinite(times).all() or (times < 0).any(): + raise ValueError("times must be finite and non-negative") + previous_modes = [(module, module.training) for module in self.modules()] + try: + self.eval() + log_shape, log_rate, gate = self._mixture(features) + return self._event_survival(log_shape, log_rate, gate, times) + finally: + for module, training in previous_modes: + module.training = training diff --git a/pyhealth/tasks/__init__.py b/pyhealth/tasks/__init__.py index e01d41b267..e74e43fdaa 100644 --- a/pyhealth/tasks/__init__.py +++ b/pyhealth/tasks/__init__.py @@ -197,6 +197,9 @@ from .survival_time_to_event import ( SurvivalTimeToEventSupport2 as SurvivalTimeToEventSupport2, ) +from .multi_event_survival_rotterdam import ( + MultiEventSurvivalRotterdam as MultiEventSurvivalRotterdam, +) from .mortality_prediction_stagenet_mimic4 import ( MortalityPredictionStageNetMIMIC4, ) diff --git a/pyhealth/tasks/multi_event_survival_rotterdam.py b/pyhealth/tasks/multi_event_survival_rotterdam.py new file mode 100644 index 0000000000..37c42cbe58 --- /dev/null +++ b/pyhealth/tasks/multi_event_survival_rotterdam.py @@ -0,0 +1,138 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +"""Recurrence and death times/indicators for the Rotterdam cohort.""" + +from typing import ClassVar + +from pyhealth.data import Patient + +from .base_task import BaseTask + +ROTTERDAM_FEATURES: tuple[str, ...] = ( + "year", + "age", + "meno", + "grade", + "nodes", + "pgr", + "er", + "hormon", + "chemo", + "size_mm", +) +ROTTERDAM_TREATMENT_FEATURES: tuple[str, ...] = ("hormon", "chemo") +ROTTERDAM_EVENTS: tuple[str, ...] = ("recurrence", "death") +# Representative tumor diameters (mm) for the source size categories, as in +# the MENSA authors' Rotterdam preprocessing. +ROTTERDAM_SIZE_MM: dict[str, float] = {"<=20": 10.0, "20-50": 35.0, ">50": 75.0} + + +class MultiEventSurvivalRotterdam(BaseTask): + """Baseline features with recurrence and death times and indicators. + + Works with :class:`~pyhealth.datasets.RotterdamDataset`. + + Each patient's single ``rotterdam`` record is validated and converted + from strings by :func:`~pyhealth.datasets.rotterdam.parse_rotterdam_record`. + The task emits ``features: [10]`` in :attr:`feature_names` order, with + tumor size coded as 10, 35 or 75 mm. With ``use_treatment=False``, the + hormonal therapy and chemotherapy indicators (``hormon``, ``chemo``) are + removed, leaving ``features: [8]`` in the same relative order. Labels are + the same either way. It also emits + ``event_times: [rtime, dtime]`` and ``event_indicators: [recur, death]``, + where 1 is an observed event and 0 is censoring at that time. + + Times stay in source days and are never shifted, scaled or replaced. A + recurrence censored before a later death keeps its own ``rtime``, and + tied event times are kept. Features are not standardized here; fit any + standardization on training patients only, after splitting. + + Like PyHealth's other duration/event survival tasks, the labels use the + ``"tensor"`` processor, so models consuming them set ``mode=None`` and + supply their own censored likelihood to the standard Trainer. + + Args: + use_treatment: Whether to include ``hormon`` and ``chemo``. Default + True (ten features); False gives eight features. + + Attributes: + use_treatment: Whether the treatment indicators are included. + feature_names: The ten or eight feature names, in output order. + event_names: Names of the two events, in label order. + + Examples: + >>> from pyhealth.tasks import MultiEventSurvivalRotterdam + >>> task = MultiEventSurvivalRotterdam() + >>> task.output_schema + {'event_times': 'tensor', 'event_indicators': 'tensor'} + >>> task.feature_names[-1] + 'size_mm' + >>> len(MultiEventSurvivalRotterdam(use_treatment=False).feature_names) + 8 + >>> from pyhealth.datasets import RotterdamDataset + >>> samples = RotterdamDataset(root="../data").set_task() # doctest: +SKIP + """ + + task_name: str = "MultiEventSurvivalRotterdam" + input_schema: ClassVar[dict[str, str]] = {"features": "tensor"} + output_schema: ClassVar[dict[str, str]] = { + "event_times": "tensor", + "event_indicators": "tensor", + } + event_names: ClassVar[tuple[str, ...]] = ROTTERDAM_EVENTS + + def __init__(self, use_treatment: bool = True) -> None: + """Choose the feature set. + + Args: + use_treatment: Whether to include ``hormon`` and ``chemo``. + + Raises: + TypeError: If ``use_treatment`` is not a bool. + """ + super().__init__() + if not isinstance(use_treatment, bool): + raise TypeError("use_treatment must be True or False") + self.use_treatment = use_treatment + # Stored per instance so each variant gets its own set_task cache. + self.feature_names: tuple[str, ...] = tuple( + name + for name in ROTTERDAM_FEATURES + if use_treatment or name not in ROTTERDAM_TREATMENT_FEATURES + ) + + def __call__(self, patient: Patient) -> list[dict]: + """Return one sample, rejecting missing or multiple source records. + + Args: + patient: Patient containing exactly one ``rotterdam`` event whose + attributes are the 14 non-ID source columns. + + Returns: + One sample with the patient ID, features, event times and event + indicators. + + Raises: + ValueError: If the patient does not have exactly one record or a + value fails validation. Messages name the patient. + """ + # Imported here because pyhealth.datasets imports pyhealth.tasks on load. + from pyhealth.datasets.rotterdam import parse_rotterdam_record + + events = patient.get_events("rotterdam") + if len(events) != 1: + raise ValueError( + f"Rotterdam pid {patient.patient_id!r}: expected exactly one " + f"rotterdam event, got {len(events)}" + ) + values = parse_rotterdam_record(events[0].attr_dict, patient.patient_id) + values["size_mm"] = ROTTERDAM_SIZE_MM[values["size"]] + return [ + { + "patient_id": patient.patient_id, + "features": [float(values[name]) for name in self.feature_names], + "event_times": [values["rtime"], values["dtime"]], + "event_indicators": [values["recur"], values["death"]], + } + ] diff --git a/tests/core/test_mensa.py b/tests/core/test_mensa.py new file mode 100644 index 0000000000..1f8bcd91da --- /dev/null +++ b/tests/core/test_mensa.py @@ -0,0 +1,522 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +"""MENSA pure functions, losses and model, on tiny synthetic data. + +Hand-worked example used below (one component, k = 0, so each Weibull is an +exponential distribution with rate exp(b)). With b = log 2 in every state: + + log S(t) = -2t log f(t) = log 2 - 2t + +Patient A: rtime 1, recur 1; dtime 2, death 1. + Extended times [2, 1, 2], indicators [0, 1, 1]. + log-likelihood = log S0(2) + log f1(1) + log f2(2) + = -4 + (log 2 - 2) + (log 2 - 4) = 2 log 2 - 10 +Patient B: rtime 3, recur 0; dtime 3, death 0. + Extended times [3, 3, 3], indicators [1, 0, 0]. + log-likelihood = log f0(3) + log S1(3) + log S2(3) + = (log 2 - 6) - 6 - 6 = log 2 - 18 +L_surv (unit weights, N = 2) = -(3 log 2 - 28) / 2 = 14 - 1.5 log 2 + +Trajectory term (only patient A had both events): + paper: -(1/N) log S2(t_recur = 1) = -(-2) / 2 = 1 + reference: -mean over A of log S2(t_death = 2) = -(-4) = 4 +""" + +import math +import tempfile +import unittest + +import torch + +from pyhealth.datasets import create_sample_dataset, get_dataloader +from pyhealth.models import MENSA +from pyhealth.models.mensa import ( + compute_state_weights, + extend_labels, + mensa_loss, + mixture_log_density, + mixture_log_survival, + mixture_log_weights, + survival_nll, + trajectory_nll, + weibull_log_density, + weibull_log_survival, +) + +LOG2 = math.log(2.0) + + +def worked_example() -> dict[str, torch.Tensor]: + """Patients A and B from the module docstring, as model inputs.""" + times = torch.tensor([[1.0, 2.0], [3.0, 3.0]]) + indicators = torch.tensor([[1.0, 1.0], [0.0, 0.0]]) + ext_times, ext_indicators = extend_labels(times, indicators) + k = torch.zeros(2, 1) # one component, shape exp(0) = 1 + b = torch.full((2, 1), LOG2) # rate 2 + gate = torch.zeros(2, 1) + log_f = torch.stack( + [mixture_log_density(ext_times[:, p], k, b, gate) for p in range(3)], 1 + ) + log_s = torch.stack( + [mixture_log_survival(ext_times[:, p], k, b, gate) for p in range(3)], 1 + ) + return { + "times": times, + "ext_times": ext_times, + "indicators": ext_indicators, + "log_f": log_f, + "log_s": log_s, + # S_death at the recurrence time (paper) and at the death time (reference) + "log_s_death_at_recur": mixture_log_survival(ext_times[:, 1], k, b, gate), + "log_s_death_at_death": log_s[:, 2], + } + + +class TestWeibullComponents(unittest.TestCase): + def test_shape_one_is_exponential(self): + t = torch.tensor([[0.5], [1.0], [3.0]]) + k, b = torch.zeros(3, 1), torch.full((3, 1), LOG2) + torch.testing.assert_close(weibull_log_survival(t, k, b), -2 * t) + torch.testing.assert_close(weibull_log_density(t, k, b), LOG2 - 2 * t) + + def test_matches_torch_weibull_distribution(self): + torch.manual_seed(0) + k, b = torch.randn(50, 1) * 0.5, torch.randn(50, 1) - 3 + t = torch.rand(50, 1) * 100 + 0.1 + # torch's Weibull uses scale = 1 / rate and concentration = shape. + reference = torch.distributions.Weibull(torch.exp(-b), torch.exp(k)) + torch.testing.assert_close( + weibull_log_density(t, k, b), reference.log_prob(t), rtol=1e-4, atol=1e-4 + ) + torch.testing.assert_close( + weibull_log_survival(t, k, b).exp(), + 1 - reference.cdf(t), + rtol=1e-4, + atol=1e-5, + ) + + def test_overflowing_component_does_not_produce_nan_gradients(self): + # One component's survival exponent overflows float32 at t = 5000 + # (shape e^3 ~ 20, rate e^-1: 20 * (log 5000 - 1) ~ 150 > 88.7). Its + # mixture weight is tiny, so the loss is finite, but without the cap + # its gradient would be 0 * inf = NaN. + k = torch.tensor([[3.0, -1.0, -1.0]], requires_grad=True) + b = torch.tensor([[-1.0, -8.0, -8.0]], requires_grad=True) + gate = torch.tensor([[-500.0, 0.0, 0.0]], requires_grad=True) + t = torch.tensor([5000.0]) + log_s = mixture_log_survival(t, k, b, gate, temperature=1.0) + log_f = mixture_log_density(t, k, b, gate, temperature=1.0) + self.assertTrue(torch.isfinite(log_s).all() and torch.isfinite(log_f).all()) + (log_s.sum() + log_f.sum()).backward() + for tensor in (k, b, gate): + self.assertTrue(torch.isfinite(tensor.grad).all()) + self.assertLess(weibull_log_survival(t[:, None], k, b)[0, 0].item(), -1e30) + + def test_survival_is_one_at_zero_bounded_and_non_increasing(self): + torch.manual_seed(1) + k, b, gate = torch.randn(4, 3), torch.randn(4, 3) - 2, torch.randn(4, 3) + grid = torch.tensor([0.0, 0.1, 1.0, 10.0, 100.0, 1000.0]) + curves = mixture_log_survival( + grid.expand(4, -1), k.unsqueeze(1), b.unsqueeze(1), gate.unsqueeze(1) + ).exp() + self.assertEqual(curves.shape, (4, 6)) + self.assertTrue(torch.equal(curves[:, 0], torch.ones(4))) + self.assertTrue(((curves >= 0) & (curves <= 1)).all()) + self.assertTrue((curves[:, 1:] <= curves[:, :-1]).all()) + + def test_extreme_parameters_stay_finite_or_minus_infinity(self): + t = torch.tensor([[1.0], [7000.0]]) + big = torch.full((2, 1), 50.0) # capped at 20 before exponentiation + log_s = weibull_log_survival(t, big, big) + self.assertFalse(torch.isnan(log_s).any()) + self.assertFalse(torch.isnan(weibull_log_density(t, big, -big)).any()) + + +class TestMixture(unittest.TestCase): + def test_weights_sum_to_one_and_temperature_softens_them(self): + gate = torch.tensor([[10.0, 0.0, -10.0], [1.0, 2.0, 3.0]]) + for temperature in (1.0, 1000.0): + weights = mixture_log_weights(gate, temperature).exp() + with self.subTest(temperature=temperature): + torch.testing.assert_close(weights.sum(-1), torch.ones(2)) + nearly_uniform = mixture_log_weights(gate, 1000.0).exp() + self.assertLess((nearly_uniform - 1 / 3).abs().max().item(), 0.01) + with self.assertRaises(ValueError): + mixture_log_weights(gate, 0.0) + + def test_identical_components_equal_a_single_component(self): + t = torch.tensor([5.0, 50.0]) + k1, b1 = torch.tensor([[0.3], [0.3]]), torch.tensor([[-3.0], [-3.0]]) + k3, b3 = k1.expand(2, 3), b1.expand(2, 3) + gate = torch.randn(2, 3) + torch.testing.assert_close( + mixture_log_survival(t, k3, b3, gate), + weibull_log_survival(t.unsqueeze(-1), k1, b1).squeeze(-1), + ) + torch.testing.assert_close( + mixture_log_density(t, k3, b3, gate), + weibull_log_density(t.unsqueeze(-1), k1, b1).squeeze(-1), + ) + + def test_rounding_never_pushes_survival_above_one(self): + # A large shape and a tiny rate keep every component near 1 early on, + # where float32 logsumexp can round to +1.2e-7 (S = 1.0000001). + k = torch.tensor([[2.3756, 1.7242, 1.0063]]) + b = torch.tensor([[-8.7331, -8.3532, -7.5364]]) + gate = torch.tensor([[0.2784, 0.1588, -0.4333]]) + times = torch.tensor([0.0, 1.0, 2.0, 3.5215, 5.0, 10.0, 100.0, 1000.0]) + log_s = torch.stack( + [mixture_log_survival(t.reshape(1), k, b, gate)[0] for t in times] + ) + self.assertTrue((log_s <= 0).all()) + survival = log_s.exp() + self.assertTrue((survival[1:] <= survival[:-1]).all()) + + +class TestLabelsAndWeights(unittest.TestCase): + def test_extend_labels_four_outcome_combinations(self): + times = torch.tensor( + [[900.0, 900.0], [1200.0, 2100.0], [365.5, 3000.0], [5000.0, 5000.0]] + ) + indicators = torch.tensor([[1.0, 1.0], [0.0, 1.0], [1.0, 0.0], [0.0, 0.0]]) + ext_times, ext_indicators = extend_labels(times, indicators) + self.assertTrue(torch.equal(ext_times[:, 1:], times)) # times unchanged + self.assertTrue(torch.equal(ext_indicators[:, 1:], indicators)) + self.assertEqual(ext_times[:, 0].tolist(), [900.0, 2100.0, 3000.0, 5000.0]) + self.assertEqual(ext_indicators[:, 0].tolist(), [0.0, 0.0, 0.0, 1.0]) + with self.assertRaises(ValueError): + extend_labels(times, indicators[:, :1]) + + def test_state_weights_are_inverse_frequency_and_sum_to_three(self): + indicators = torch.tensor( + [[1.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 1.0], [0.0, 0.0, 1.0]] + ) + weights = compute_state_weights(indicators) # counts [2, 1, 2] + torch.testing.assert_close(weights, torch.tensor([0.75, 1.5, 0.75])) + torch.testing.assert_close(weights.sum(), torch.tensor(3.0)) + + +class TestLosses(unittest.TestCase): + def setUp(self): + self.ex = worked_example() + + def test_worked_example_survival_nll(self): + self.assertEqual(self.ex["ext_times"].tolist(), [[2, 1, 2], [3, 3, 3]]) + self.assertEqual(self.ex["indicators"].tolist(), [[0, 1, 1], [1, 0, 0]]) + loss = survival_nll(self.ex["log_f"], self.ex["log_s"], self.ex["indicators"]) + self.assertAlmostEqual(loss.item(), 14 - 1.5 * LOG2, places=5) + weighted = survival_nll( + self.ex["log_f"], + self.ex["log_s"], + self.ex["indicators"], + torch.ones(3), + ) + self.assertAlmostEqual(weighted.item(), loss.item(), places=6) + + def test_censored_rows_ignore_an_infinite_density(self): + log_f = torch.tensor([[-float("inf"), -1.0]]) + log_s = torch.tensor([[-2.0, -float("inf")]]) + loss = survival_nll(log_f, log_s, torch.tensor([[0.0, 1.0]])) + self.assertEqual(loss.item(), 3.0) + + def test_worked_example_trajectory_variants(self): + paper = trajectory_nll( + self.ex["log_s_death_at_recur"], self.ex["indicators"], variant="paper" + ) + reference = trajectory_nll( + self.ex["log_s_death_at_death"], self.ex["indicators"], variant="reference" + ) + self.assertAlmostEqual(paper.item(), 1.0, places=5) + self.assertAlmostEqual(reference.item(), 4.0, places=5) + with self.assertRaises(ValueError): + trajectory_nll( + self.ex["log_s_death_at_recur"], self.ex["indicators"], variant="x" + ) + + def test_trajectory_is_zero_without_patients_having_both_events(self): + indicators = torch.tensor([[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, 0.0, 0.0]]) + log_s = torch.tensor([-5.0, -6.0, -7.0], requires_grad=True) + for variant in ("paper", "reference"): + with self.subTest(variant=variant): + value = trajectory_nll(log_s, indicators, variant=variant) + self.assertEqual(value.item(), 0.0) + value.backward() # still part of the graph + + def test_total_loss_mixes_terms_with_lambda(self): + args = (self.ex["log_f"], self.ex["log_s"], self.ex["indicators"]) + traj_in = self.ex["log_s_death_at_recur"] + surv = 14 - 1.5 * LOG2 + for lam, expected in [(0.0, surv), (1.0, 1.0), (0.25, 0.75 * surv + 0.25)]: + with self.subTest(lam=lam): + total = mensa_loss(*args, traj_in, trajectory_weight=lam) + self.assertAlmostEqual(total.item(), expected, places=5) + for bad in (-0.1, 1.5): + with self.subTest(bad=bad), self.assertRaises(ValueError): + mensa_loss(*args, traj_in, trajectory_weight=bad) + + def test_gradients_are_finite_through_mixture_and_loss(self): + torch.manual_seed(2) + params = [ + torch.randn(5, 3, 3, requires_grad=True), # k + (torch.randn(5, 3, 3) - 7).requires_grad_(), # b, rate ~ 1/1000 days + torch.randn(5, 3, 3, requires_grad=True), # gate + ] + times = torch.tensor( + [[900.0, 900.0], [1200, 2100], [365.5, 3000], [5000, 5000], [40, 50]] + ) + indicators = torch.tensor([[1.0, 1], [0, 1], [1, 0], [0, 0], [1, 1]]) + ext_t, ext_e = extend_labels(times, indicators) + k, b, g = params + log_f = mixture_log_density(ext_t, k, b, g) + log_s = mixture_log_survival(ext_t, k, b, g) + later = mixture_log_survival(ext_t[:, 1], k[:, 2], b[:, 2], g[:, 2]) + loss = mensa_loss(log_f, log_s, ext_e, later, compute_state_weights(ext_e)) + self.assertEqual(loss.shape, ()) + self.assertTrue(torch.isfinite(loss)) + loss.backward() + for p in params: + self.assertTrue(torch.isfinite(p.grad).all()) + + +def synthetic_samples(n_features: int = 10) -> list[dict]: + """Four patients, one per outcome combination, in the task's layout. + + Column 2 is constant, to check that a zero-variance feature gets scale 1. + """ + rows = [ + ("21", [1985, 61, 1, 3, 0, 35, 291, 0, 0, 10], [900, 900], [1, 1]), + ("22", [1988, 70, 1, 2, 4, 0, 12, 1, 0, 35], [1200, 2100], [0, 1]), + ("23", [1979, 45, 1, 3, 2, 138, 0, 0, 1, 75], [365.5, 3000], [1, 0]), + ("24", [1992, 52, 1, 2, 0, 60, 45, 0, 1, 10], [5000, 5000], [0, 0]), + ] + return [ + { + "patient_id": pid, + "features": [float(v) for v in features[:n_features]], + "event_times": [float(v) for v in times], + "event_indicators": [float(v) for v in indicators], + } + for pid, features, times, indicators in rows + ] + + +def make_dataset(samples: list[dict]): + return create_sample_dataset( + samples=samples, + input_schema={"features": "tensor"}, + output_schema={"event_times": "tensor", "event_indicators": "tensor"}, + dataset_name="mensa_test", + ) + + +class TestMENSAModel(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.samples = synthetic_samples() + cls.dataset = make_dataset(cls.samples) + cls.batch = next(iter(get_dataloader(cls.dataset, batch_size=4))) + + def model(self, seed: int = 0, fit: bool = True, **kwargs) -> MENSA: + torch.manual_seed(seed) + model = MENSA(self.dataset, num_time_bins=8, **kwargs) + if fit: + model.fit_preprocessing(self.dataset) + return model + + def test_instantiation_infers_widths_and_has_no_label_mode(self): + model = self.model(fit=False) + self.assertEqual((model.input_dim, model.n_events, model.n_states), (10, 2, 3)) + self.assertIsNone(model.mode) + self.assertEqual(model.label_processors, {}) + self.assertFalse(bool(model.is_fitted)) + self.assertEqual(model.time_grid.shape, (9,)) + + def test_default_hyperparameters(self): + model = MENSA(self.dataset) + self.assertEqual(model.hidden_dims, (32,)) + self.assertEqual(model.n_dists, 3) + self.assertEqual(model.dropout, 0.25) + self.assertEqual(model.trajectory_weight, 0.25) + linear, _, _, dropout = model.network.embedding + self.assertEqual((linear.in_features, linear.out_features), (10, 32)) + self.assertEqual(dropout.p, 0.25) + first, _, last = model.network.adapters[0] + self.assertEqual((first.in_features, first.out_features), (32, 16)) + self.assertEqual(last.out_features, 32) + self.assertEqual(model.network.gate_heads[0].out_features, 3) + + def test_reference_rotterdam_config_can_be_passed(self): + # thecml/mensa configs/mensa/rotterdam.yaml (commit 6b219cd): + # layers [16], n_dists 3, dropout_rate 0.5, traj_lambda 0.25. + model = MENSA(self.dataset, hidden_dims=(16,), dropout=0.5) + linear, _, _, dropout = model.network.embedding + self.assertEqual(linear.out_features, 16) + self.assertEqual(dropout.p, 0.5) + first, _, last = model.network.adapters[0] + self.assertEqual((first.in_features, first.out_features), (16, 16)) + self.assertEqual(last.out_features, 16) + + def test_forward_shapes_finite_loss_and_gradients(self): + model = self.model() + output = model(**self.batch) + self.assertEqual(output["y_prob"].shape, (4, 2, 9)) + self.assertEqual(output["y_true"].shape, (4, 4)) + torch.testing.assert_close( + output["y_true"], + torch.cat([self.batch["event_times"], self.batch["event_indicators"]], 1), + ) + self.assertEqual(output["loss"].shape, ()) + self.assertTrue(torch.isfinite(output["loss"])) + output["loss"].backward() + # BaseModel's empty _dummy_param only tracks the device. + grads = [p.grad for n, p in model.named_parameters() if n != "_dummy_param"] + self.assertTrue(all(g is not None and torch.isfinite(g).all() for g in grads)) + + def test_survival_curves_bounded_non_increasing_and_one_at_zero(self): + model = self.model() + curves = model.predict_survival( + self.batch["features"], torch.tensor([0.0, 30, 365, 1000, 3000, 7000]) + ) + self.assertEqual(curves.shape, (4, 2, 6)) + self.assertTrue(torch.equal(curves[..., 0], torch.ones(4, 2))) + self.assertTrue(((curves >= 0) & (curves <= 1)).all()) + self.assertTrue((curves[..., 1:] <= curves[..., :-1]).all()) + y_prob = model(**self.batch)["y_prob"] + self.assertEqual(model.time_grid[0].item(), 0.0) + self.assertTrue((y_prob[..., 1:] <= y_prob[..., :-1]).all()) + + def test_fit_preprocessing_uses_only_the_given_split(self): + train = self.samples[:2] # patients 21 and 22 + model = self.model(fit=False) + model.fit_preprocessing(make_dataset(train)) + x = torch.tensor([s["features"] for s in train], dtype=torch.float64) + expected_scale = x.std(0, unbiased=False) + expected_scale[expected_scale == 0] = 1.0 + torch.testing.assert_close(model.feature_mean, x.mean(0).float()) + torch.testing.assert_close(model.feature_scale, expected_scale.float()) + self.assertEqual(model.feature_scale[2].item(), 1.0) # constant column + # Extended indicators: 21 = [0, 1, 1], 22 = [0, 0, 1] -> counts [0, 1, 2]. + expected = compute_state_weights(torch.tensor([[0.0, 1, 1], [0, 0, 1]])) + torch.testing.assert_close(model.state_weights, expected) + times = torch.tensor([900.0, 900, 1200, 2100]) + self.assertEqual(model.time_grid[0].item(), 0.0) + self.assertEqual(model.time_grid[1].item(), times.min().item()) + self.assertEqual(model.time_grid[-1].item(), times.max().item()) + self.assertTrue(bool(model.is_fitted)) + + def test_using_the_model_before_fitting_raises(self): + model = self.model(fit=False) + with self.assertRaisesRegex(RuntimeError, "fit_preprocessing"): + model(**self.batch) + with self.assertRaisesRegex(RuntimeError, "fit_preprocessing"): + model.predict_survival(self.batch["features"], torch.tensor([1.0])) + + def test_loss_matches_the_pure_functions_and_lambda(self): + model = self.model(trajectory_weight=0.25) + model.eval() + output = model(**self.batch) + x = (self.batch["features"] - model.feature_mean) / model.feature_scale + k, b, g = model.network(x) + t, e = extend_labels(self.batch["event_times"], self.batch["event_indicators"]) + log_f = mixture_log_density(t, k, b, g) + log_s = mixture_log_survival(t, k, b, g) + later = mixture_log_survival(t[:, 1], k[:, 2], b[:, 2], g[:, 2]) + surv = survival_nll(log_f, log_s, e, model.state_weights) + traj = trajectory_nll(later, e) + torch.testing.assert_close(output["loss"], 0.75 * surv + 0.25 * traj) + model.trajectory_weight = 0.0 + torch.testing.assert_close(model(**self.batch)["loss"], surv) + model.trajectory_weight, model.trajectory_variant = 1.0, "reference" + torch.testing.assert_close( + model(**self.batch)["loss"], + trajectory_nll(log_s[:, 2], e, variant="reference"), + ) + + def test_state_dict_round_trip_gives_identical_predictions(self): + model = self.model(seed=0) + optimizer = torch.optim.Adam(model.parameters(), lr=1e-2) + model.train() + for _ in range(3): + optimizer.zero_grad() + model(**self.batch)["loss"].backward() + optimizer.step() + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmp: + path = f"{tmp}/mensa.pt" + torch.save(model.state_dict(), path) + restored = self.model(seed=1, fit=False) + restored.load_state_dict(torch.load(path)) + self.assertTrue(bool(restored.is_fitted)) + times = torch.tensor([0.0, 100, 1000, 5000]) + self.assertTrue( + torch.equal( + model.predict_survival(self.batch["features"], times), + restored.predict_survival(self.batch["features"], times), + ) + ) + + def test_training_mode_batch_of_two_and_mode_is_restored(self): + model = self.model() + model.train() + batch = next(iter(get_dataloader(self.dataset, batch_size=2))) + loss = model(**batch)["loss"] + self.assertTrue(torch.isfinite(loss)) + loss.backward() + model.predict_survival(batch["features"], torch.tensor([10.0])) + self.assertTrue(all(m.training for m in model.modules())) + + def test_eight_feature_variant(self): + dataset = make_dataset(synthetic_samples(n_features=8)) + torch.manual_seed(0) + model = MENSA(dataset, num_time_bins=4) + model.fit_preprocessing(dataset) + batch = next(iter(get_dataloader(dataset, batch_size=4))) + self.assertEqual(model.input_dim, 8) + self.assertTrue(torch.isfinite(model(**batch)["loss"])) + + def test_invalid_configuration_and_labels_are_rejected(self): + for kwargs in ( + {"feature_key": "x"}, + {"times_key": "t"}, + {"trajectory_weight": 1.5}, + {"trajectory_variant": "other"}, + {"trajectory": (1, 3)}, + {"trajectory": (2, 2)}, + {"dropout": 1.0}, + {"num_time_bins": 1}, + ): + with self.subTest(kwargs=kwargs), self.assertRaises(ValueError): + MENSA(self.dataset, **kwargs) + model = self.model() + for key, value in (("event_times", -1.0), ("event_indicators", 2.0)): + batch = dict(self.batch) + batch[key] = batch[key].clone() + batch[key][0, 0] = value + with self.subTest(key=key), self.assertRaises(ValueError): + model(**batch) + with self.assertRaises(ValueError): + model(features=self.batch["features"][:, :5]) + + def test_trainer_trains_and_reports_loss(self): + from pyhealth.trainer import Trainer + + model = self.model() + loader = get_dataloader(self.dataset, batch_size=2, shuffle=True) + # Capture the Trainer's INFO logs (it logs the whole model) to keep + # test output readable. + with self.assertLogs("pyhealth.trainer", level="INFO"): + trainer = Trainer(model=model, device="cpu", enable_logging=False) + trainer.train( + train_dataloader=loader, + val_dataloader=loader, + epochs=2, + monitor="loss", + monitor_criterion="min", + ) + scores = trainer.evaluate(get_dataloader(self.dataset, batch_size=4)) + self.assertEqual(set(scores), {"loss"}) + self.assertTrue(math.isfinite(scores["loss"])) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_multi_event_survival_rotterdam.py b/tests/core/test_multi_event_survival_rotterdam.py new file mode 100644 index 0000000000..2dc0b8f27a --- /dev/null +++ b/tests/core/test_multi_event_survival_rotterdam.py @@ -0,0 +1,270 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +"""MultiEventSurvivalRotterdam features and labels, using four synthetic patients.""" + +import csv +import tempfile +import unittest +from pathlib import Path + +import polars as pl +import torch + +from pyhealth.data import Patient +from pyhealth.datasets import RotterdamDataset, get_dataloader +from pyhealth.datasets.rotterdam import ROTTERDAM_COLUMNS +from pyhealth.tasks import MultiEventSurvivalRotterdam +from tests.core.survival_test_utils import threaded_csv_loading + +FEATURES = ( + "year", + "age", + "meno", + "grade", + "nodes", + "pgr", + "er", + "hormon", + "chemo", + "size_mm", +) +FEATURES_WITHOUT_TREATMENT = tuple(f for f in FEATURES if f not in ("hormon", "chemo")) +TREATMENT_COLUMNS = [FEATURES.index("hormon"), FEATURES.index("chemo")] + + +def without_treatment(features: list) -> list: + """Drop the hormon and chemo positions from a ten-feature list.""" + return [v for i, v in enumerate(features) if i not in TREATMENT_COLUMNS] + + +def rows_fixture() -> list[dict[str, str]]: + """Four synthetic patients, one per recurrence/death outcome combination. + + Values are strings, as read from the CSV. Patient 22 matches the 43 + source patients whose recurrence was censored before a later death; + patient 21 has tied event times; patient 23 has a fractional time. + """ + rows = [ + # pid year age meno size grade nodes pgr er hormon chemo + # rtime recur dtime death + ("21", "1985", "61", "1", "<=20", "3", "0", "35", "291", "0", "0") + + ("900", "1", "900", "1"), # both events, tied times + ("22", "1988", "70", "1", "20-50", "2", "4", "0", "12", "1", "0") + + ("1200", "0", "2100", "1"), # recurrence censored, then death + ("23", "1979", "45", "0", ">50", "3", "2", "138", "0", "0", "1") + + ("365.5", "1", "3000", "0"), # recurrence only, fractional time + ("24", "1992", "52", "0", "<=20", "2", "0", "60", "45", "0", "1") + + ("5000", "0", "5000", "0"), # neither event + ] + return [dict(zip(ROTTERDAM_COLUMNS, row, strict=True)) for row in rows] + + +# Expected task output per pid: features, [rtime, dtime], [recur, death]. +EXPECTED = { + "21": ( + [1985, 61, 1, 3, 0, 35, 291, 0, 0, 10], + [900, 900], + [1, 1], + ), + "22": ( + [1988, 70, 1, 2, 4, 0, 12, 1, 0, 35], + [1200, 2100], + [0, 1], + ), + "23": ( + [1979, 45, 0, 3, 2, 138, 0, 0, 1, 75], + [365.5, 3000], + [1, 0], + ), + "24": ( + [1992, 52, 0, 2, 0, 60, 45, 0, 1, 10], + [5000, 5000], + [0, 0], + ), +} + + +def patient_from_rows(rows: list[dict[str, str]], pid: str = "21") -> Patient: + """Build a Patient whose ``rotterdam`` events hold the given source rows.""" + events = [ + { + "patient_id": pid, + "event_type": "rotterdam", + "timestamp": None, + **{f"rotterdam/{k}": v for k, v in row.items() if k != "pid"}, + } + for row in rows + ] + df = ( + pl.DataFrame(events) + if events + else pl.DataFrame( + schema={ + "patient_id": pl.String, + "event_type": pl.String, + "timestamp": pl.Datetime, + } + ) + ) + return Patient(pid, df) + + +class TestMultiEventSurvivalRotterdamTask(unittest.TestCase): + def setUp(self): + self.task = MultiEventSurvivalRotterdam() + self.rows = rows_fixture() + + def sample(self, row: dict[str, str]) -> dict: + samples = self.task(patient_from_rows([row], row["pid"])) + self.assertEqual(len(samples), 1) + return samples[0] + + def test_schema_and_feature_order(self): + self.assertEqual(self.task.task_name, "MultiEventSurvivalRotterdam") + self.assertEqual(self.task.input_schema, {"features": "tensor"}) + self.assertEqual( + self.task.output_schema, + {"event_times": "tensor", "event_indicators": "tensor"}, + ) + self.assertTrue(self.task.use_treatment) + self.assertEqual(self.task.feature_names, FEATURES) + self.assertEqual(self.task.event_names, ("recurrence", "death")) + + def test_string_values_become_ten_ordered_float_features(self): + sample = self.sample(self.rows[1]) + self.assertEqual(sample["patient_id"], "22") + self.assertEqual(len(sample["features"]), 10) + self.assertTrue(all(type(v) is float for v in sample["features"])) + self.assertEqual(sample["features"], [float(v) for v in EXPECTED["22"][0]]) + + def test_size_categories_map_to_millimetres(self): + for size, millimetres in [("<=20", 10.0), ("20-50", 35.0), (">50", 75.0)]: + row = dict(self.rows[0], size=size) + with self.subTest(size=size): + self.assertEqual(self.sample(row)["features"][-1], millimetres) + + def test_four_outcome_combinations_keep_source_times(self): + for row in self.rows: + pid = row["pid"] + _, times, indicators = EXPECTED[pid] + with self.subTest(pid=pid): + patient = patient_from_rows([row], pid) + sample = self.task(patient)[0] + self.assertEqual(sample["event_times"], times) + self.assertEqual(sample["event_indicators"], indicators) + attrs = patient.get_events("rotterdam")[0].attr_dict + self.assertEqual( + [attrs[c] for c in ("rtime", "recur", "dtime", "death")], + [row[c] for c in ("rtime", "recur", "dtime", "death")], + ) + + def test_without_treatment_drops_hormon_and_chemo_only(self): + task = MultiEventSurvivalRotterdam(use_treatment=False) + self.assertFalse(task.use_treatment) + self.assertEqual(task.feature_names, FEATURES_WITHOUT_TREATMENT) + for row in self.rows: + pid = row["pid"] + features, times, indicators = EXPECTED[pid] + with self.subTest(pid=pid): + sample = task(patient_from_rows([row], pid))[0] + self.assertEqual(len(sample["features"]), 8) + self.assertEqual(sample["features"], without_treatment(features)) + self.assertEqual(sample["event_times"], times) + self.assertEqual(sample["event_indicators"], indicators) + + def test_use_treatment_must_be_bool(self): + for value in (1, 0, "False", None): + with self.subTest(value=value), self.assertRaises(TypeError): + MultiEventSurvivalRotterdam(use_treatment=value) + + def test_missing_or_multiple_records_are_rejected(self): + for rows in ([], self.rows[:2]): + with ( + self.subTest(n=len(rows)), + self.assertRaisesRegex(ValueError, "exactly one"), + ): + self.task(patient_from_rows(rows)) + + def test_invalid_values_are_rejected_by_shared_parser(self): + for column, value in [ + ("size", "50+"), + ("rtime", "0"), + ("dtime", "nan"), + ("recur", "2"), + ("age", ""), + ("rtime", "901"), # exceeds dtime + ]: + row = dict(self.rows[0], **{column: value}) + with ( + self.subTest(column=column, value=value), + self.assertRaisesRegex(ValueError, rf"pid '21': {column}"), + ): + self.sample(row) + + +class TestMultiEventSurvivalRotterdamDataset(unittest.TestCase): + """Run the default task through the real loader once, on synthetic rows.""" + + @classmethod + def setUpClass(cls): + # litdata can keep cache files open on Windows, so cleanup may fail there. + cls.tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + cls.addClassCleanup(cls.tmp.cleanup) + root = Path(cls.tmp.name) + with (root / "rotterdam.csv").open("w", newline="", encoding="utf-8") as f: + writer = csv.DictWriter(f, fieldnames=list(ROTTERDAM_COLUMNS)) + writer.writeheader() + writer.writerows(rows_fixture()) + with threaded_csv_loading(): + cls.dataset = RotterdamDataset( + str(root), cache_dir=root / "cache", num_workers=1 + ) + cls.samples = cls.dataset.set_task() + cls.no_treatment_task = MultiEventSurvivalRotterdam(use_treatment=False) + cls.no_treatment = cls.dataset.set_task(cls.no_treatment_task) + cls.batch = next(iter(get_dataloader(cls.samples, batch_size=4))) + cls.no_treatment_batch = next( + iter(get_dataloader(cls.no_treatment, batch_size=4)) + ) + + def test_default_task_is_multi_event_survival(self): + self.assertIsInstance(self.dataset.default_task, MultiEventSurvivalRotterdam) + + def test_set_task_yields_one_sample_per_patient_with_tensor_shapes(self): + self.assertEqual(len(self.samples), 4) + self.assertEqual(sorted(self.batch["patient_id"]), ["21", "22", "23", "24"]) + self.assertEqual(self.batch["features"].shape, (4, 10)) + self.assertEqual(self.batch["event_times"].shape, (4, 2)) + self.assertEqual(self.batch["event_indicators"].shape, (4, 2)) + for key in ("features", "event_times", "event_indicators"): + self.assertEqual(self.batch[key].dtype, torch.float32, key) + + def test_batched_values_match_source_rows(self): + for i, pid in enumerate(self.batch["patient_id"]): + features, times, indicators = EXPECTED[pid] + with self.subTest(pid=pid): + self.assertEqual(self.batch["features"][i].tolist(), features) + self.assertEqual(self.batch["event_times"][i].tolist(), times) + self.assertEqual(self.batch["event_indicators"][i].tolist(), indicators) + + def test_eight_feature_variant_has_its_own_cache_and_values(self): + self.assertNotEqual( + self.dataset._task_cache_dir(self.no_treatment_task), + self.dataset._task_cache_dir(self.dataset.default_task), + ) + batch = self.no_treatment_batch + self.assertEqual(batch["features"].shape, (4, 8)) + self.assertEqual(batch["event_times"].shape, (4, 2)) + for i, pid in enumerate(batch["patient_id"]): + features, times, indicators = EXPECTED[pid] + with self.subTest(pid=pid): + self.assertEqual( + batch["features"][i].tolist(), without_treatment(features) + ) + self.assertEqual(batch["event_times"][i].tolist(), times) + self.assertEqual(batch["event_indicators"][i].tolist(), indicators) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/core/test_rotterdam.py b/tests/core/test_rotterdam.py new file mode 100644 index 0000000000..ed684b8234 --- /dev/null +++ b/tests/core/test_rotterdam.py @@ -0,0 +1,250 @@ +# Author: Zhenshuo Xu (zx65). +# MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based +# Likelihood Estimation, Lillelund et al. https://arxiv.org/abs/2409.06525 +"""Rotterdam source validation and loading, using four synthetic patients.""" + +import csv +import tempfile +import unittest +from pathlib import Path +from typing import Any + +from pyhealth.datasets import RotterdamDataset +from pyhealth.datasets.rotterdam import ROTTERDAM_COLUMNS, parse_rotterdam_record +from tests.core.survival_test_utils import threaded_csv_loading + + +def write_csv(root: Path, rows: list[dict[str, Any]], name: str = "rotterdam.csv"): + """Write synthetic rows with the source header order.""" + with (root / name).open("w", newline="", encoding="utf-8") as stream: + writer = csv.DictWriter(stream, fieldnames=list(ROTTERDAM_COLUMNS)) + writer.writeheader() + writer.writerows(rows) + + +def rows_fixture() -> list[dict[str, Any]]: + """Four synthetic patients, one per recurrence/death outcome combination. + + PIDs are not contiguous, to show that IDs come from ``pid`` and not from + row positions. Patient 12 matches the 43 source patients whose + recurrence was censored before a later death; patient 11 has tied event + times; patient 13 has a fractional time that must not be rounded. + """ + covariates = { + "year": 1985, + "meno": 1, + "grade": 3, + "pgr": 35, + "er": 291, + "hormon": 0, + "chemo": 0, + } + outcomes = [ + # pid, age, size, nodes, rtime, recur, dtime, death + (11, 61, "<=20", 0, 900, 1, 900, 1), # both events, tied times + (12, 70, "20-50", 4, 1200, 0, 2100, 1), # recurrence censored, then death + (13, 45, ">50", 2, 365.5, 1, 3000, 0), # recurrence only, fractional time + (14, 52, "<=20", 0, 5000, 0, 5000, 0), # neither event + ] + return [ + dict( + pid=pid, + age=age, + size=size, + nodes=nodes, + rtime=rtime, + recur=recur, + dtime=dtime, + death=death, + **covariates, + ) + for pid, age, size, nodes, rtime, recur, dtime, death in outcomes + ] + + +def as_record(row: dict[str, Any]) -> dict[str, str]: + """Return a row as the strings a CSV reader would produce.""" + return {k: str(v) for k, v in row.items()} + + +class TestRotterdamRecord(unittest.TestCase): + def test_valid_record_values_are_returned_unchanged(self): + row = rows_fixture()[2] + values = parse_rotterdam_record(as_record(row), "13") + self.assertEqual(set(values), set(ROTTERDAM_COLUMNS[1:])) + self.assertEqual(values["size"], ">50") + self.assertEqual(values["rtime"], 365.5) + self.assertEqual(values["dtime"], 3000.0) + self.assertEqual((values["recur"], values["death"]), (1.0, 0.0)) + self.assertEqual(values["age"], 45.0) + + def test_censored_recurrence_before_death_keeps_both_times(self): + values = parse_rotterdam_record(as_record(rows_fixture()[1]), "12") + self.assertEqual((values["rtime"], values["recur"]), (1200.0, 0.0)) + self.assertEqual((values["dtime"], values["death"]), (2100.0, 1.0)) + + def test_invalid_values_name_column_and_pid(self): + cases = [ + ("rtime", "0", "strictly positive"), + ("dtime", "-1", "strictly positive"), + ("rtime", "1e-100", "strictly positive"), + ("dtime", "nan", "finite"), + ("recur", "2", "0 or 1"), + ("death", "0.5", "0 or 1"), + ("meno", "-1", "0 or 1"), + ("size", "big", "must be one of"), + ("size", "", "missing"), + ("age", "", "missing"), + ("age", "0", "strictly positive"), + ("nodes", "-1", "non-negative"), + ("pgr", "abc", "numeric"), + ("er", "inf", "finite"), + ("year", "1e100", "finite"), + ] + for column, value, message in cases: + record = as_record(rows_fixture()[0]) + record[column] = value + with ( + self.subTest(column=column, value=value), + self.assertRaisesRegex(ValueError, rf"pid '11': {column} .*{message}"), + ): + parse_rotterdam_record(record, "11") + record = as_record(rows_fixture()[0]) + del record["chemo"] + with self.assertRaisesRegex(ValueError, "pid '11': chemo is missing"): + parse_rotterdam_record(record, "11") + + def test_recurrence_follow_up_cannot_exceed_death_follow_up(self): + record = as_record(rows_fixture()[3]) + record["rtime"] = "5001" + with self.assertRaisesRegex(ValueError, "pid '14': rtime .* exceeds dtime"): + parse_rotterdam_record(record, "14") + + +class TestRotterdamDatasetLoading(unittest.TestCase): + """Load the synthetic cohort once and check the cached events.""" + + @classmethod + def setUpClass(cls): + # litdata can keep cache files open on Windows, so cleanup may fail there. + cls.tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + cls.addClassCleanup(cls.tmp.cleanup) + root = Path(cls.tmp.name) + cls.rows = rows_fixture() + write_csv(root, cls.rows) + with threaded_csv_loading(): + cls.dataset = RotterdamDataset( + str(root), cache_dir=root / "cache", num_workers=1 + ) + cls.patient_ids = set(cls.dataset.unique_patient_ids) + cls.patients = { + pid: cls.dataset.get_patient(pid) for pid in cls.patient_ids + } + + def test_patient_ids_come_from_pid(self): + self.assertEqual(self.patient_ids, {"11", "12", "13", "14"}) + self.assertEqual(self.dataset.num_source_patients, 4) + + def test_each_patient_keeps_one_record_with_source_values(self): + for row in self.rows: + pid = str(row["pid"]) + with self.subTest(pid=pid): + events = self.patients[pid].get_events("rotterdam") + self.assertEqual(len(events), 1) + attrs = events[0].attr_dict + for column in ROTTERDAM_COLUMNS[1:]: + self.assertEqual(str(attrs[column]), str(row[column]), column) + + def test_all_patient_times_are_preserved(self): + times = { + pid: tuple( + float(patient.get_events("rotterdam")[0].attr_dict[column]) + for column in ("rtime", "recur", "dtime", "death") + ) + for pid, patient in self.patients.items() + } + self.assertEqual( + times, + { + "11": (900.0, 1.0, 900.0, 1.0), + "12": (1200.0, 0.0, 2100.0, 1.0), + "13": (365.5, 1.0, 3000.0, 0.0), + "14": (5000.0, 0.0, 5000.0, 0.0), + }, + ) + + +class TestRotterdamDatasetValidation(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(ignore_cleanup_errors=True) + self.addCleanup(self.tmp.cleanup) + self.root = Path(self.tmp.name) + write_csv(self.root, rows_fixture()) + + def dataset(self, **kwargs: Any) -> RotterdamDataset: + return RotterdamDataset( + str(self.root), cache_dir=self.root / "cache", num_workers=1, **kwargs + ) + + def test_invalid_csv_fails_before_caching(self): + for column, value in [ + ("pid", ""), + ("rtime", 0), + ("dtime", -5), + ("recur", 2), + ("death", "yes"), + ("size", "50+"), + ("age", ""), + ("rtime", 6000), + ]: + rows = rows_fixture() + rows[1][column] = value + write_csv(self.root, rows) + pattern = "pid" if column == "pid" else rf"pid '12': {column}" + with self.subTest(column=column, value=value): + with self.assertRaisesRegex(ValueError, pattern): + self.dataset() + self.assertFalse(any((self.root / "cache").rglob("*.parquet"))) + + def test_duplicate_pid_rejected_but_equal_values_allowed(self): + rows = rows_fixture() + rows[3] = {**rows[0], "pid": 14} # Same values under another pid is valid. + write_csv(self.root, rows) + self.assertEqual(self.dataset().num_source_patients, 4) + rows[3]["pid"] = 11 + write_csv(self.root, rows) + with self.assertRaisesRegex(ValueError, "unique, got '11'"): + self.dataset() + + def test_wrong_table_or_config_is_rejected(self): + with self.assertRaisesRegex(ValueError, "supports only"): + self.dataset(tables=["other"]) + import pyhealth.datasets.rotterdam as module + + text = (Path(module.__file__).parent / "configs/rotterdam.yaml").read_text() + for old, new in [ + ('patient_id: "pid"', 'patient_id: "year"'), + (" - dtime\n", ""), + ]: + config = self.root / "bad.yaml" + config.write_text(text.replace(old, new)) + with ( + self.subTest(change=new or f"drop {old.strip()}"), + self.assertRaisesRegex(ValueError, "config must use pid"), + ): + self.dataset(config_path=str(config)) + + def test_empty_missing_column_and_missing_file(self): + write_csv(self.root, []) + with self.assertRaisesRegex(ValueError, "at least one"): + self.dataset() + (self.root / "rotterdam.csv").write_text("pid,rtime,recur\n1,10,1\n") + with self.assertRaisesRegex(ValueError, r"missing columns: \['age'"): + self.dataset() + (self.root / "rotterdam.csv").unlink() + with self.assertRaises(FileNotFoundError): + self.dataset() + + +if __name__ == "__main__": + unittest.main()