Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/api/datasets.rst
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,11 @@ PyHealth does not ship any data: you download each dataset from its source and p
- `GitHub <https://github.com/neheller/kits23>`__ + `Hugging Face <https://huggingface.co/datasets/neheller/KiTS-Challenge-Imaging>`__
- No (``kits23_download_data``)
- Single CTs by URL (``wget``)
* - :doc:`Rotterdam <datasets/pyhealth.datasets.RotterdamDataset>`
- Open
- `R survival <https://stat.ethz.ch/R-manual/R-devel/library/survival/html/rotterdam.html>`__
- No
- —
* - :doc:`TCGA-PRAD <datasets/pyhealth.datasets.TCGAPRADDataset>`
- Open
- `GDC <https://portal.gdc.cancer.gov/projects/TCGA-PRAD>`__
Expand Down Expand Up @@ -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
Expand Down
71 changes: 71 additions & 0 deletions docs/api/datasets/pyhealth.datasets.RotterdamDataset.rst
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
110 changes: 110 additions & 0 deletions docs/api/models/pyhealth.models.MENSA.rst
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -326,3 +326,4 @@ Available Tasks
Time-to-event survival (GBSG and SUPPORT) <tasks/pyhealth.tasks.survival_time_to_event>
TCGA RNA-seq Survival Prediction <tasks/pyhealth.tasks.TCGASurvivalPrediction>
Query-Focused EHR Summarization (MIMIC-III) <tasks/pyhealth.tasks.QueryFocusedEHRTask>
Multi-event survival (Rotterdam) <tasks/pyhealth.tasks.multi_event_survival_rotterdam>
65 changes: 65 additions & 0 deletions docs/api/tasks/pyhealth.tasks.multi_event_survival_rotterdam.rst
Original file line number Diff line number Diff line change
@@ -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
1 change: 1 addition & 0 deletions pyhealth/datasets/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
21 changes: 21 additions & 0 deletions pyhealth/datasets/configs/rotterdam.yaml
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading