Skip to content

Add Dynamic Survival Analysis (DSA) model and MIMIC-III decompensation task - #1646

Open
ashleyxz wants to merge 5 commits into
sunlabuiuc:masterfrom
ashleyxz:feature/dsa-decompensation-cse6250
Open

ashleyxz wants to merge 5 commits into
sunlabuiuc:masterfrom
ashleyxz:feature/dsa-decompensation-cse6250

Conversation

@ashleyxz

@ashleyxz ashleyxz commented Nov 28, 2026 •

Copy link
Copy Markdown

Contributors

Georgia Institute of Technology — CSE 6250: Big Data for Health, Fall 2026

Team B5 — Paper #31

Contribution Type

  • New Model: Dynamic Survival Analysis (DSA)
  • New Task: MIMIC-III Decompensation Prediction
  • Dedicated MIMIC-III dataset configuration with backward compatibility
  • Reproduction, ablation study, and methodological extension

Related Paper

Dynamic Survival Analysis for Early Event Prediction, CHIL 2024.

Description

This PR introduces Dynamic Survival Analysis (DSA) for early event prediction and integrates an hourly MIMIC-III decompensation prediction task into PyHealth.

Model

  • GRU-based architecture inheriting from BaseModel.
  • Discrete-time hazard, survival, probability mass function (PMF), and cumulative risk outputs.
  • Masked survival likelihood, hazard bias initialization, and support for survTLS-smoothed targets.
  • Configurable model hyperparameters and prediction horizons.

Task

  • Hourly ICU decompensation prediction inheriting from BaseTask.
  • Seventeen clinical channels represented by 76 dynamic features (12 continuous, 47 categorical, and 17 observation masks).
  • Normalization, categorical encoding, missing-value imputation, and survival target generation.
  • Integration with the existing MIMIC-III dataset infrastructure and jagged feature processor.
  • Optional dedicated configuration for ward ID comparisons without modifying the default MIMIC-III configuration.

Additional Contributions

  • Event-level alarm evaluation with validation-selected thresholds.
  • Patient-specific PMF urgency scoring extension.
  • Runnable synthetic ablation and end-to-end integration examples, API documentation, and unit tests.

Files to Review

Core Implementation

  • pyhealth/models/dsa.py: DSA model and survival prediction.
  • pyhealth/tasks/decompensation_mimic3.py: Hourly feature processing and survival targets.
  • pyhealth/datasets/configs/mimic3_decompensation.yaml: Dedicated configuration exposing first and last ward IDs while preserving the default MIMIC-III configuration.
  • pyhealth/models/__init__.py: Model export.
  • pyhealth/tasks/__init__.py: Task export.

Examples and Evaluation

All six files below are in examples/mortality_prediction/.

  • mimic3_decompensation_dsa.py: Synthetic model ablation.
  • mimic3_decompensation_dsa_full_pipeline.py: Synthetic patient-to-task-to-model training and evaluation.
  • early_event_metrics.py: Event-level alarm evaluation.
  • pmf_urgency.py: PMF urgency scoring and synthetic example.
  • DSA_REPRODUCTION_RESULTS.md: Reproduction and extension results.
  • DSA_SYNTHETIC_PIPELINE_RESULTS.md: Synthetic integration results.

Documentation

  • docs/api/models/pyhealth.models.DSA.rst
  • docs/api/tasks/pyhealth.tasks.decompensation_mimic3.rst
  • docs/api/models.rst
  • docs/api/tasks.rst

Unit Tests

  • tests/core/test_dsa.py
  • tests/core/test_decompensation_mimic3.py: Task tests, including five additional ward and care-unit filtering regression tests.
  • tests/core/test_early_event_metrics.py
  • tests/core/test_pmf_urgency.py

Reproduction and Ablation Results

Compute-constrained training reproduced the qualitative improvement across the DSA ablations. Full-cohort evaluation using saved predictions yielded the following timestep-level test AuPRC values:

  • Vanilla DSA: 0.018762
  • Bias initialization: 0.215951
  • Truncated likelihood: 0.230058
  • survTLS: 0.230893
  • EEP baseline: 0.233280

The MIMIC-III test cohort contains 523,208 timesteps from 6,237 ICU stays, including 490 event stays. Bias initialization and truncation improved AuPRC, while survTLS performed slightly better than truncation. The EEP baseline achieved slightly higher fixed-horizon AuPRC than survTLS.

Extension: PMF-Based Patient-Specific Urgency

The extension combines cumulative event risk with near-term event probability share and expected event imminence. It uses a 24-hour prediction horizon, a 6-hour near-term horizon, and equal weighting (alpha = 0.5).

Full-cohort event-level test AuPRC:

  • EEP fixed horizon: 0.412300
  • survTLS fixed horizon: 0.421205
  • Reproduced paper imminent priority: 0.432762
  • Proposed PMF urgency: 0.429362

The proposed strategy outperformed both fixed-horizon strategies but did not exceed the reproduced imminent priority strategy.

The reusable scoring function was verified against 808,167 saved validation and test timestep scores (284,959 validation and 523,208 test). All records aligned, with a maximum absolute error of approximately 3.33e-16 in both splits. This verifies scoring consistency, not an independent recomputation of the complete event-level evaluation.

Synthetic Examples and End-to-End Validation

The lightweight model ablation uses 48 synthetic samples. Test AuPRC for the three configurations:

  • Truncated: 0.2917
  • Truncated + Bias: 0.3750
  • Truncated + Bias + survTLS: 0.3750

The end-to-end example processes 12 synthetic ICU patients through the decompensation task, constructs PyHealth sample datasets, trains DSA using PyHealth Trainer, and evaluates held-out patients. It uses patient-level train/validation/test splits (8/2/2 patients; 204/51/51 hourly samples).

Synthetic end-to-end test AuPRC:

  • Truncated: 0.4706
  • Truncated + Bias: 0.4659
  • Truncated + Bias + survTLS: 0.5173

Both examples run on CPU without restricted clinical data. These synthetic scores demonstrate functionality, not clinical performance.

Testing and Validation

The following checks were completed locally:

  • Official PyHealth PR contribution rules.
  • 34 contribution-specific unit tests and 2 subtests passed in 9.06 seconds, with no pytest warnings reported.
  • 55 existing regression tests and 21 subtests passed in 62.89 seconds (3 skipped, 29 warnings; no failures or errors).
  • Five additional ward and care-unit filtering regression tests, included in the 34 contribution-specific tests.
  • Both the default and dedicated MIMIC-III configurations validated through the actual dataset loader using temporary synthetic CSV fixtures.
  • Model initialization, forward pass, output shapes, gradients, and state-dict restoration.
  • Task feature processing, imputation, survival labels, and edge cases.
  • Event-level metrics, validation threshold selection, and PMF urgency tests.
  • All three runnable synthetic examples validated before the compatibility-only fix.
  • Numerical consistency with original PMF urgency scores.
  • API documentation and package exports updated.
  • Upstream master alignment checked before the initial submission.
  • Ruff, whitespace checks, and local contribution rules passed after the compatibility fix.
  • Full GitHub CI revalidation after the compatibility fix.

Running the Tests

From the repository root in a PyHealth environment with the required dependencies:

PYTHONPATH=. python -m pytest \
  tests/core/test_dsa.py \
  tests/core/test_decompensation_mimic3.py \
  tests/core/test_early_event_metrics.py \
  tests/core/test_pmf_urgency.py -q

Running the Examples

PYTHONPATH=. python examples/mortality_prediction/mimic3_decompensation_dsa.py
PYTHONPATH=. python examples/mortality_prediction/mimic3_decompensation_dsa_full_pipeline.py
PYTHONPATH=. python examples/mortality_prediction/pmf_urgency.py

Backward Compatibility Fix

The initial GitHub CI run reported 15 failures and 12 setup errors caused by mandatory ward ID attributes in the default MIMIC-III configuration. The repository's demo fixture does not contain those columns.

Commit b0a3025d addresses this issue:

  • Restored the original mimic3.yaml configuration, leaving existing tasks unaffected by the additional attribute requirements.
  • Introduced mimic3_decompensation.yaml as an opt-in configuration for datasets containing both ward ID columns.
  • Preserved the task's existing ward ID and care-unit comparisons.
  • Added five task regression tests for matching, mismatched, and missing ward IDs and mismatched care units.
  • Updated API documentation with configuration usage and limitations.

All nine affected regression test files were rerun locally: 55 tests passed, 3 were skipped, and there were no failures or errors. The actual dataset loader also successfully loaded both configurations using synthetic CSV fixtures, including preservation of two distinct ward IDs in the dedicated configuration.

The DSA model, survival target generation, PMF urgency extension, and previously reported reproduction results remain unchanged. The full upstream CI suite has not yet been confirmed passing after this fix.

Using the Dedicated Configuration

From the repository root, with MIMIC-III data containing both ward ID columns:

from pyhealth.datasets import MIMIC3Dataset
from pyhealth.tasks import DecompensationMIMIC3

dataset = MIMIC3Dataset(
    root="/path/to/mimic-iii/1.4",
    tables=["chartevents", "labevents"],
    dataset_name="mimic3_decompensation",
    config_path=(
        "pyhealth/datasets/configs/"
        "mimic3_decompensation.yaml"
    ),
    cache_dir="/path/to/controlled/cache",
)
sample_dataset = dataset.set_task(DecompensationMIMIC3())

The dedicated configuration requires source data containing both ward ID columns. If both ward IDs are unavailable under the default configuration, the task can still process a stay subject to the remaining cohort criteria, but ward ID consistency cannot be verified. If only one ward ID is available, the task excludes the stay. Comparing the first and last ward IDs does not detect every possible intermediate transfer.

Limitations

  • The reproduction used a reduced training budget rather than independently reproducing full-dataset training. Full-cohort clinical evaluation uses saved predictions.
  • Reported clinical metrics are reproduction results, not the original paper's published results.
  • The synthetic end-to-end example validates model and task integration using existing dataset infrastructure; it does not introduce a new standalone dataset implementation.
  • The dedicated configuration was validated with synthetic CSV fixtures, not independently verified end-to-end training with full MIMIC-III data. The default configuration cannot verify ward ID consistency when the attributes are absent.
  • No restricted MIMIC-III records, patient-level predictions, or trained checkpoints are included in the contribution.

@github-actions

github-actions Bot commented Nov 28, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 87.03% (51038 / 58641 lines)

Modified file Coverage Lines
pyhealth/models/__init__.py 100.00% 103 / 103
pyhealth/models/dsa.py 84.75% 100 / 118
pyhealth/tasks/__init__.py 98.29% 115 / 117
pyhealth/tasks/decompensation_mimic3.py 66.67% 210 / 315

Workflow run · b0a3025

@solarsys solarsys added the status: manual Pending maintainer's review label Nov 28, 2026
@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.

Reviewed commit b0a3025

indicates whether death occurs strictly within the prediction horizon.

The cohort follows the MIMIC-III benchmark convention of adult ICU stays
and excludes transfers between wards or care units within the stay.

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] Class docstring says transfers within the stay are excluded; code checks only first vs last unit

The docstring says the cohort 'excludes transfers between wards or care units within the stay'. The code (lines 763-768) only compares first_wardid with last_wardid and first_careunit with last_careunit, and the PR's own docs say intermediate transfers are not detected. Reword to say the stay is excluded when its first and last ward or care unit differ, and that intermediate transfers are not checked.

if task.survtls_lengthscale is None:
hazard_label[event_index] = 1.0
else:
hazard_label = task._smooth_survival_label(event_bin)

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] Example reuses the task's private _smooth_survival_label helper (undisclosed link)

This example calls task._smooth_survival_label, a private method of DecompensationMIMIC3, to build synthetic survTLS targets. The description does not mention this link. PyHealth keeps components self-contained so that changing one does not silently change another, so a private helper used from outside the class is a coupling. Either confirm the sharing and explain it in the description, or keep the component self-contained by building the synthetic targets inside the example.

import numpy as np
import pytest

from examples.mortality_prediction.pmf_urgency import pmf_urgency_score

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] Test imports the example module examples/mortality_prediction/pmf_urgency.py (undisclosed link)

The test imports pmf_urgency_score from an example script. The description calls the function 'reusable' but does not say a test depends on the example module. Either confirm the sharing and say why in the description (for example, that the example module is the canonical implementation), or keep the test self-contained by moving the scoring function to a module the test can own.

EXAMPLE_DIR = Path(__file__).resolve().parents[2] / "examples" / "mortality_prediction"
sys.path.insert(0, str(EXAMPLE_DIR))

from early_event_metrics import (

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] Test loads examples/mortality_prediction/early_event_metrics.py through sys.path (undisclosed link)

The test puts the example directory on sys.path and imports early_event_metrics. The description does not state this link. Either confirm and explain the sharing in the description, or keep the component self-contained. Note that the metrics live in examples/ rather than pyhealth/metrics/, so they are not importable as library code.

- "first_careunit"
- "dbsource"
- "last_careunit"
- "first_wardid"

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] New dedicated MIMIC-III config has no committed loader test

The config adds first_wardid and last_wardid to icustays, and the description says it was validated only with temporary synthetic CSV fixtures that are not in the repo. Existing MIMIC-III config behavior is covered by tests such as tests/core/test_mimic3.py. Add a committed test that loads the dedicated config with a small CSV fixture and checks that both ward IDs appear in the patient events, plus a check that the default config still loads without them.

if age_years < 18:
continue

mortality = (

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] mortality flag includes dod, but labels use only deathtime

mortality is true when dod falls in the admission window (line 789), but death_time is taken only from deathtime (line 793), so a stay with dod in the window and no deathtime gets mortality=1 in the sample (line 867) while every y_true is 0. Either use deathtime for both, or document the difference.

7.207267791681239,
)

CONTINUOUS_STDS: ClassVar[tuple[float, ...]] = (

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] Normalization constants look outlier-driven; provenance should be stated

Several standard deviations look implausible for the channels they describe: glucose about 1767 (mean 140), SpO2 about 5135 (mean 105), diastolic BP about 222 (mean 62), and pH about 1.66 (mean 7.2). With these values, typical measurements z-score to near zero, and the tests only check the arithmetic. Document where the statistics came from, state whether they were computed on cleaned data, and confirm they match the reference preprocessing.

return samples


def validation_auprc(model: DSA, loader) -> float:

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] validation_auprc is used to score the test split

The helper is named validation_auprc but is called with test_loader on line 211. Rename it to something like evaluate_auprc so the reported number is not mistaken for a validation score.

Comment thread tests/core/test_dsa.py
if __name__ == "__main__":
unittest.main()

def test_dsa_state_dict_roundtrip():

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] State-dict test is defined after the main block

test_dsa_state_dict_roundtrip sits after the if name == 'main' block that calls unittest.main(), so running the file directly exits before the test is defined. Move it above the block and use self.assertTrue or assertEqual inside a TestCase for consistency with the rest of the file.

@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: need change
decision: human review

Thank you for this substantial contribution. It adds a Dynamic Survival Analysis (DSA) model, an hourly MIMIC-III decompensation task, an opt-in ward-ID config, examples, docs and tests. It is close, but a few things need fixing first.

To get this merged:

  1. Coverage: pyhealth/tasks/decompensation_mimic3.py is at 66.67%, below the 80% per-file bar. The uncovered code is probably the chartevent and labevent parsing in _clean_value and _hourly_observations. Please add tests for the unit conversions (temperature, weight, height, FiO2, blood pressure strings, categorical values) and for event filtering by stay and time. Overall repo coverage (87%) and dsa.py (84.75%) are fine.
  2. Sharing between components: examples/mortality_prediction/mimic3_decompensation_dsa.py calls the task's private _smooth_survival_label. Two tests (test_early_event_metrics.py and test_pmf_urgency.py) import from the examples/ modules. The description doesn't mention either. Please say in the description why you share this code, or keep the pieces self-contained, for example by using a public method or copying the logic. Either choice is fine.
  3. Docstring accuracy: the task docstring says transfers between wards or care units within the stay are excluded. The code only compares the first and last ward and the first and last care unit. Please reword it to match, as your API docs already do.
  4. Config test: the new mimic3_decompensation.yaml is never loaded by a committed test. Please add a small test that loads it through the dataset loader with a synthetic fixture. You have already run this manually.

Optional suggestions:

  • The mortality flag counts dod, but the labels use only deathtime. Consider aligning them or documenting the difference.
  • Please document where CONTINUOUS_STDS comes from. Some values look very large.
  • validation_auprc in the full-pipeline example actually scores the test set, so a rename would help.
  • The module-level test_dsa_state_dict_roundtrip sits after the __main__ guard in test_dsa.py. Moving it above the guard is cleaner.
  • The from .decompensation_mimic3 import ... line in tasks/__init__.py sits after the __getattr__ function. Moving it up with the other imports is tidier.

Reviewed commit b0a3025

@solarsys

Copy link
Copy Markdown
Collaborator

Why this PR has status: manual: #1558 and #1646 both add a dynamic survival analysis model and a MIMIC-III decompensation task (tasks/decompensation_mimic3.py in both), so a maintainer has to pick one.

To help the maintainers decide, please comment here with what your PR does that the others don't, such as fidelity to the paper, results or test coverage. Whichever PR isn't picked can still contribute its unique parts on top of the chosen one. The decision is tracked in #1668.

The AI review's open points on this PR still apply.

@solarsys

Copy link
Copy Markdown
Collaborator

We compared this with #1558 and picked #1558 as the base. This PR has these problems:

  • There's no filter for one ICU stay per admission.
  • For patients who die after ICU discharge but within the horizon, hazard_mask stops at discharge. The event bin is masked out, so the loss trains those positives toward no event.
  • Coverage of the task is under 80%.
  • Tests import from examples/.

Your PR has several things #1558 doesn't, and we'd like them on top.

After #1558 merges, please contribute the following, with tests in tests/core and nothing imported from examples/:

  • survTLS target smoothing as a loss option on DynamicSurvivalRNN, computed from time_to_event/event;
  • pmf and survival outputs on DynamicSurvivalRNN;
  • imminent-priority and PMF-urgency alarm scoring and validation-selected thresholds, as functions in pyhealth/metrics/event_alarm.py;
  • optionally, the L1 embedding penalty.

Drop:

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants