Skip to content

Add multi-event survival on Rotterdam(2/2): RotterdamDataset, MultiEventSurvivalRotterdam and MENSA (Lillelund et al., ML4H 2025) - #1642

Merged
solarsys merged 3 commits into
sunlabuiuc:masterfrom
sosqwq:mensa-rotterdam
Nov 29, 2026
Merged

solarsys merged 3 commits into
sunlabuiuc:masterfrom
sosqwq:mensa-rotterdam

Conversation

@sosqwq

@sosqwq sosqwq commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Contributor: Zhenshuo Xu (NetID: zx65)
Contribution type: Full pipeline (CS 598 DL4H Option 4, reproducibility), part 2 of 2. Part 1, #1644 (merged), added RotterdamDataset, MultiEventSurvivalRotterdam and MENSA with their tests and docs.
Paper: Lillelund et al., "MENSA: A Multi-Event Network for Survival Analysis with Trajectory-based Likelihood Estimation", ML4H 2025 (PMLR 297).
Links: PMLR | arXiv | Reference code

Description

This PR adds the reproduction script for MENSA on Rotterdam. The dataset, task and model are already in master (#1644), so this diff has only three files:

  • examples/rotterdam_multi_event_survival_mensa.py runs the paper's Rotterdam protocol and experiments E1-E4.
  • docs/api/models/pyhealth.models.MENSA.rst gets an "Example and results" section.
  • tests/core/test_rotterdam_mensa_example.py tests the script's numerical helpers.

It does not change any library code.

Data: The cohort is public in R's survival package (survival::rotterdam). Download data/rotterdam.csv from the authors' repository, or export it from R with write.csv(survival::rotterdam, "rotterdam.csv", row.names = FALSE). Pass --synthetic to run the whole pipeline without the data.

Extra packages: pip install scikit-multilearn SurvivalEVAL scikit-survival. Only this script uses them, and they are not added to PyHealth's dependencies.

Relation to existing code

  • Dataset constants: To write the synthetic CSV, the script imports ROTTERDAM_COLUMNS and ROTTERDAM_SIZE_CATEGORIES from pyhealth/datasets/rotterdam.py (merged in MENSA on Rotterdam (1/2): RotterdamDataset, MultiEventSurvivalRotterdam and MENSA (Lillelund et al., ML4H 2025) #1644). This keeps the synthetic file in the format that RotterdamDataset validates, so the two cannot drift apart.
  • Trainer progress bars: When run from the command line, the script turns off the Trainer's per-epoch progress bars by wrapping tqdm and trange in pyhealth.trainer. It cannot use TQDM_DISABLE, because tqdm reads it only when first imported, which happens before the script parses its options. This happens only in main(), not when the script is imported (the tests import it), and --progress keeps the bars. The Trainer code itself is not changed.
  • Validation loss: train_mensa wraps evaluate on its own Trainer instance to record the validation loss of each epoch, and restores it after training.
  • Baselines: CoxPH (CoxPHSurvivalAnalysis(alpha=10, n_iter=100, tol=1e-5) with a Breslow baseline) and DeepSurv follow the reference code's Rotterdam configs and put their curves on MENSA's time grid. This keeps them comparable with the paper's baselines, so the script does not reuse the adapters in examples/survival_benchmark/baselines.py.
  • Metrics: pyhealth.metrics has a Harrell C-index but not the local C-index (pairs within one patient), and both need the same pair rules, so the script computes both. AUC, IBS, MAE and D-calibration use SurvivalEVAL, as in the reference code, instead of integrated_brier_score_td, so the numbers are computed the same way as the paper's.

Differences from the reference code

  • Trajectory loss: Paper Eq. 1 and the authors' code compute the trajectory term differently. The default follows the paper; trajectory_variant="reference" follows the code (compared in E4).
  • Hyperparameters: Defaults are hidden size 32, dropout 0.25 and weight decay 1e-3. The reference Rotterdam config uses 16, 0.5 and 1e-4 (also run in E4).
  • Seeds: The reference code always sets the model seed to 0, for every split. Here the model seed matches the split seed.
  • Best weights: In the reference repository, saving the best weights stores a reference instead of a copy, so restoring them has no effect. Here PyHealth's Trainer restores an actual copy.

Experiments

  • E1: Main comparison on seeds 0-9.
  • E2 (new): Learning curves using 25%, 50% and 100% of the training split.
  • E3: 10 vs. 8 features (dropping treatment indicators), and trajectory weight 0.25 vs. 0 (weight 0 is also in the paper).
  • E4 (new): Paper vs. reference trajectory loss, plus our defaults vs. the reference config.

Reproduction results

E1 on real data, seeds 0-9, mean over seeds (x100). Paper numbers are in parentheses.

Method CI_G CI_L AUC IBS IBS (tau90) D-cal
MENSA 69.3 (69.4) 90.9 (90.1) 73.7 (73.8) 23.1 (18.8) 17.0 (-) 20/20 (18/20)
CoxPH 68.5 (69.7) 83.1 (83.6) 73.2 (75.1) 22.8 (19.6) 17.4 (-) 20/20 (20/20)
DeepSurv 68.7 (70.0) 85.5 (84.6) 73.4 (75.4) 22.5 (19.4) 17.4 (-) 20/20 (18/20)

Key findings:

  • MENSA matches the paper closely on CI_G, CI_L and AUC.
  • Most of CI_L comes from event order: predicting recurrence before death for every patient, with no model, already scores 91.0. MENSA equals that on 8 of 10 seeds. CoxPH and DeepSurv are 7.9 and 5.5 points lower.
  • The default IBS is unstable on some splits, because a few censored test patients get large IPCW weights (up to about 720). Truncating at the 90th percentile of training times (IBS (tau90)) makes it stable, and MENSA is best on it.
  • In E2, MENSA keeps its CI_L lead on smaller training sets but loses its IBS advantage (at 25% data, IBS (tau90) is worse on 5 of 5 seeds).
  • In E3, dropping the treatment features or setting the trajectory weight to 0 changes every metric by at most 0.18 points.
  • In E4, the reference trajectory loss changes the results very little. The reference config is slightly worse on CI_G and IBS (tau90).

Tests

18 tests on small hand-worked or synthetic inputs, all running in well under a second:

  • Global and local C-index, and the no-model reference, on the hand-worked case from --self-check (global 6.5/10, local 1/3), plus ties and cases with no pairs.
  • cox_nll (hand-worked value, tied times, weight penalty), breslow_baseline (hand-worked hazards, ties and censoring) and curves_on_grid (interpolation, capping, never increasing).
  • stratified_split_ids (disjoint, complete, about 70/10/20, reproducible; skipped without scikit-multilearn) and nested_training_subsets (25% ⊂ 50% ⊂ 100%, outcome mix kept, small groups kept).
python -m pytest tests/core/test_rotterdam_mensa_example.py

The 52 tests for the dataset, task and model were added in #1644.

Files to review

  • examples/rotterdam_multi_event_survival_mensa.py
  • docs/api/models/pyhealth.models.MENSA.rst (new "Example and results" section)
  • tests/core/test_rotterdam_mensa_example.py

@github-actions

github-actions Bot commented Nov 27, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.55% (52980 / 60516 lines)

No modified files under pyhealth/.

Workflow run · 8dfaa0f

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 27, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

/review

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 44f119b

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: approve
decision: human review

Thank you for this contribution. It adds an example script that follows the MENSA paper's Rotterdam protocol, with CoxPH and DeepSurv baselines and learning-curve and ablation experiments. It also adds a results section to the MENSA docs page. It looks ready to merge.

  • Scope: The diff is only the example script and the docs section. It doesn't change any base class, Trainer, registry or shared utility.
  • Docs: The figures in the MENSA docs section match the script's module docstring.
  • Coverage: No files under pyhealth/ changed in this diff, so there is nothing to measure per file. Whole-repository coverage is 87.15%, above the 60% bar.
  • Sharing: The script imports ROTTERDAM_COLUMNS and ROTTERDAM_SIZE_CATEGORIES from pyhealth/datasets/rotterdam.py to write the synthetic CSV. It is an example for the dataset, task and model in this same PR, so I don't see this as a problem. It would help to add one line to the description saying that the script reuses these constants so the synthetic file always matches the dataset's validation.

Optional suggestions:

  • The script is about 3,300 lines, and its docstring holds a lot of result text that will go stale. You could move the results into the docs page or a README and keep only the usage in the script.
  • The C-index helpers (concordance_pairs, global_c_index, local_c_index, constant_order_local_ci) are checked only by --self-check. A small test for them would protect the reported numbers.
  • The script patches tqdm in pyhealth.trainer and replaces Trainer.evaluate on an instance. This works, but it is fragile if the Trainer changes.

Reviewed commit 44f119b

@solarsys solarsys added status: automatic The PR will go through automatic review process. and removed status: manual Pending maintainer's review labels Nov 28, 2026
@solarsys

Copy link
Copy Markdown
Collaborator

Good news: this PR has moved from status: manual to status: automatic. It had the manual label only because of its size. It adds only new files, it fits under the AI review's size limit, and the AI review already suggests approve on the latest commit.

One step is left. The AI review doesn't review a commit twice, so please push a new commit (rebasing on master is enough) and then comment /review. On automatic PRs you can request the review yourself. If the review approves, the PR merges.

@solarsys

Copy link
Copy Markdown
Collaborator

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit ead9231

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

AI Review

suggestion: need change
decision: need change

Thank you for this substantial contribution. It adds multi-event survival analysis on Rotterdam, with a MENSA reproduction, baselines, ablations and a synthetic smoke-run mode. The write-up is careful and honest about where the results differ from the paper.

The diff I can see is close, but it has a few blocking points.

To get this merged:

  1. The diff is incomplete compared with the description. The description lists the dataset, task, model, YAML config, exports, the other docs pages and 52 tests across three files. The diff only contains the example script, tests/core/test_rotterdam_mensa_example.py and the MENSA docs section. Please make sure the dataset, task, model and their tests are included in the PR, so they can be reviewed and their coverage measured. The coverage report lists no changed files under pyhealth/.
  2. The example imports ROTTERDAM_COLUMNS and ROTTERDAM_SIZE_CATEGORIES from pyhealth/datasets/rotterdam.py. It also replaces tqdm and trange in pyhealth.trainer for the whole process. The description doesn't mention either link. Please confirm the sharing is intended and say why in the description, or keep the example self-contained, for example by defining those constants locally and passing a Trainer option or an environment variable for the progress bars.
  3. The new numerical helpers in the example have no tests: cox_nll, breslow_baseline, stratified_split_ids, nested_training_subsets and curves_on_grid. The existing test file only covers the C-index helpers. Please add small synthetic tests for these.

Optional suggestions:

  • The example is about 3,300 lines. Moving the baselines, plotting and ablation machinery into separate files, or trimming them, would make it easier to review.
  • The docs section should list the extra packages the --synthetic run needs: scikit-multilearn, SurvivalEVAL and scikit-survival.
  • Briefly say why the example has its own CoxPH, DeepSurv and IBS code when examples/survival_benchmark/baselines.py and pyhealth/metrics/survival_curve.py already exist.

Overall coverage (87.55%) is above the 60% bar. Per-file coverage could not be checked because no changed library files appear in the report.

Reviewed commit ead9231

@sosqwq sosqwq changed the title Add multi-event survival on Rotterdam: RotterdamDataset, MultiEventSurvivalRotterdam and MENSA (Lillelund et al., ML4H 2025) Add multi-event survival on Rotterdam(2/2): RotterdamDataset, MultiEventSurvivalRotterdam and MENSA (Lillelund et al., ML4H 2025) Nov 28, 2026
@sosqwq

sosqwq commented Nov 28, 2026

Copy link
Copy Markdown
Contributor Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 8dfaa0f

return hashlib.sha256(path.read_bytes()).hexdigest()


def run_once(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[medium] Run, reuse and evaluation path has no tests

Only pure helpers are tested (C-index, Cox loss, Breslow, curves_on_grid, nested subsets). Nothing exercises train_mensa, baseline_curves/fit_deepsurv/predict_*, evaluate_survival, the run_once reuse check or invalid-curve check, paired_differences, or the --synthetic pipeline that the docs advertise as running 'the whole pipeline'. Comparable tests/core/test_pbc_neural_fine_gray_example.py tests its synthetic path and checkpoint identity. Add a test that runs make_synthetic_cohort through RotterdamDataset with one seed and two epochs for coxph and mensa, checks metric keys and curve validity, and checks that a second run_once call reuses the saved file and that a changed config triggers a rerun.

cls.times = rng.uniform(1, 100, size=(100, 2))
cls.events = rng.integers(0, 2, size=(100, 2))

@unittest.skipUnless(HAS_SKMULTILEARN, "needs scikit-multilearn")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Split tests are skipped in a default environment

stratified_split_ids is tested only when scikit-multilearn is installed, and no requirements file or pyproject declares it. In a default install the reproducibility-critical split is never checked. Either declare the optional dependency for the example or state in the description that the split is verified only when it is installed.

return np.minimum.accumulate(np.clip(spline(grid), 0.0, 1.0), axis=-1)


def fit_coxph(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] CoxPH and DeepSurv duplicate examples/survival_benchmark/baselines.py

fit_coxph and DeepSurvNet/fit_deepsurv implement the same two baselines as CoxAdapter and DeepSurvAdapter in examples/survival_benchmark/baselines.py. The description gives reasons (reference configs, own time grid, paper-matching training behavior), so this is not treated as redundant. Name CoxAdapter and DeepSurvAdapter in the description and state which behaviors differ (Breslow fit, last-epoch weights, dropout on during validation), or keep the separate implementations.

@@ -0,0 +1,3285 @@
# Author: Zhenshuo Xu (zx65).

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[low] Example is much longer than comparable examples and has no requirements file

The file is 3,285 lines; comparable examples (examples/pbc_neural_fine_gray/pbc_experiment.py, examples/survival_benchmark/run_baselines.py) are 340 to 540 lines. The plotting, CSV reporting and self-check code could be cut or moved so the core reproduction reads more easily. The three optional packages are documented only in the docstring and docs page; add a requirements file next to the example, as examples/survival_benchmark/requirements.txt does.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

AI Review

suggestion: approve
decision: approve

Thank you for this contribution. It adds a reproduction script for MENSA on Rotterdam. The script covers the paper's protocol, the CoxPH and DeepSurv baselines, and the E1–E4 experiments. It comes with a docs section and 18 tests for its numerical helpers. It looks ready to merge.

  • Sharing: The three links to existing code (the dataset constants, the tqdm/trange wrapping inside main(), and the Trainer.evaluate wrapper on your own instance) are each explained in the description. The script doesn't change any library code.
  • Docs and code: The docs section and the commands match the script.
  • Coverage: No file under pyhealth/ changed, so there is no per-file coverage to check. Whole-repo coverage is 87.55%, above the 60% bar.
  • Tests: The helper tests use hand-worked values and look sound.

Optional suggestions:

  • Add a small smoke test that runs the --synthetic pipeline with a tiny epoch cap. It would cover train_mensa, run_once (including run-file reuse), baseline_curves and evaluate_survival, which the helper tests don't reach. It could skip when scikit-multilearn, SurvivalEVAL or scikit-survival is missing.
  • The module docstring is long. You could move some of the results narrative into the docs page and keep the docstring shorter.

Reviewed commit 8dfaa0f

@solarsys
solarsys merged commit 35170a1 into sunlabuiuc:master Nov 29, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: automatic The PR will go through automatic review process.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants