Skip to content
Open
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
1 change: 1 addition & 0 deletions docs/api/models.rst
Original file line number Diff line number Diff line change
Expand Up @@ -297,6 +297,7 @@ API Reference
models/pyhealth.models.CNN
models/pyhealth.models.UNet
models/pyhealth.models.RNN
models/pyhealth.models.DSA
models/pyhealth.models.GNN
models/pyhealth.models.Transformer
models/pyhealth.models.BEHRT
Expand Down
9 changes: 9 additions & 0 deletions docs/api/models/pyhealth.models.DSA.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pyhealth.models.DSA
===================================

Dynamic Survival Analysis model for early event prediction.

.. autoclass:: pyhealth.models.DSA
:members:
:undoc-members:
:show-inheritance:
1 change: 1 addition & 0 deletions docs/api/tasks.rst
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,7 @@ Available Tasks
Medical Transcriptions Classification <tasks/pyhealth.tasks.MedicalTranscriptionsClassification>
MPF Clinical Prediction (FHIR) <tasks/pyhealth.tasks.mpf_clinical_prediction>
Mortality Prediction (Next Visit) <tasks/pyhealth.tasks.mortality_prediction>
Decompensation Prediction (MIMIC-III) <tasks/pyhealth.tasks.decompensation_mimic3>
Mortality Prediction (StageNet MIMIC-IV) <tasks/pyhealth.tasks.mortality_prediction_stagenet_mimic4>
Next-Visit Diagnosis Prediction <tasks/pyhealth.tasks.next_visit_diagnosis_prediction>
Patient Linkage (MIMIC-III, legacy) <tasks/pyhealth.tasks.patient_linkage_mimic3_fn>
Expand Down
59 changes: 59 additions & 0 deletions docs/api/tasks/pyhealth.tasks.decompensation_mimic3.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
pyhealth.tasks.decompensation_mimic3
=======================================

MIMIC-III hourly 24-hour decompensation prediction task.

Dataset Configuration
---------------------

The default MIMIC-III dataset configuration remains unchanged
for backward compatibility with existing PyHealth tasks.

For ward-level cohort filtering, this contribution provides a
dedicated configuration, ``mimic3_decompensation.yaml``, which
includes the ``first_wardid`` and ``last_wardid`` attributes.

Example usage from the repository root:

.. code-block:: python

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"
),
)

sample_dataset = dataset.set_task(
DecompensationMIMIC3()
)

The dedicated configuration requires source data containing
both ward ID columns.

Cohort Filtering
----------------

The task excludes ICU stays with different first and last
ward IDs or different first and last care units.

If both ward IDs are unavailable, the task can still process
the stay subject to the remaining cohort criteria. However,
ward ID consistency cannot be verified in this case.

If only one ward ID is available, the stay is excluded.

The dedicated configuration preserves the ward ID comparison
used in the reproduction while avoiding changes to the
default MIMIC-III dataset configuration.

.. autoclass:: pyhealth.tasks.decompensation_mimic3.DecompensationMIMIC3
:members:
:undoc-members:
:show-inheritance:
145 changes: 145 additions & 0 deletions examples/mortality_prediction/DSA_REPRODUCTION_RESULTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
# DSA Reproduction Results — MIMIC-III

## Evaluation Setup

- Task: 24-hour ICU decompensation prediction
- Dataset: MIMIC-III
- Test timesteps: 523,208
- ICU stays: 6,237
- Event stays: 490
- All four DSA variants evaluated on identical records
- DSA evaluation score: risk_h23
- Metric: Area Under the Precision-Recall Curve (AuPRC)

## Full-Cohort Test Results

| Model | Test AuPRC |
|---|---:|
| Vanilla DSA | 0.018762 |
| Bias Initialization | 0.215951 |
| Truncated Likelihood | 0.230058 |
| survTLS | 0.230893 |
| EEP Baseline | 0.233280 |

EEP uses its corresponding fixed-horizon prediction score.

These full-test-cohort metrics were recalculated from stored predictions.
They are distinct from the compute-constrained subset training results
reported in `mimic3_decompensation_dsa.py`. The synthetic PyHealth examples
validate the contributed implementation and do not independently reproduce
these MIMIC-III numbers.

## Reproduction Findings

- Bias initialization produced the largest improvement.
- Truncated likelihood further improved AuPRC.
- survTLS performed similarly to Truncated.
- EEP slightly outperformed survTLS at the fixed 24-hour horizon.
- The DSA-only ablation ordering is consistent with our earlier subset
experiments; the relative ordering of EEP and survTLS differs.

## Evaluation Validation

- All four DSA prediction files contain 523,208 timesteps.
- All four DSA prediction files contain 6,237 ICU stays.
- Stay, time, and label fields match across DSA variants.
- All DSA AuPRC values were recalculated using risk_h23.

## Additional Clinical Evaluation

Validation-selected operating points were evaluated on the
independent test cohort.

At the 70% validation precision target:

| Metric | EEP | survTLS |
|---|---:|---:|
| Test alarm precision | 0.8029 | 0.7452 |
| Test event recall | 0.1633 | 0.2408 |
| Median lead time (hourly steps) | 5 | 4 |
| False alarms per 100 stays | 1.09 | 2.12 |

The event-level and clinical-extension comparisons above
were performed for EEP and survTLS, not all DSA variants.

## Limitations

- These results come from a specific reproduction setup
and do not establish statistical significance.
- Direct numerical comparison with the original paper
requires matching its evaluation protocol and cohort.
- MIMIC-III patient-level data and predictions are not
included in this public-facing documentation.

## Evaluation Utility Consistency Check

The reusable early-event evaluation utility was compared against
the original event-level evaluation implementation using the
same MIMIC-III test predictions.

Six frozen validation-selected operating points were checked:
60%, 70%, and 80% validation precision targets for EEP and survTLS.

All six operating points matched across the compared event-level
metrics, including event recall, alarm precision, alarm counts,
detected events, and mean lead time.

This establishes consistency at the tested operating points,
not universal equivalence across all thresholds or datasets.

## PMF-Based Patient-Specific Urgency Extension

The proposed extension combines cumulative event risk with
the predicted temporal distribution of the event.

Configuration:

- Prediction horizon: 24 hours
- Near-term horizon: 6 hours
- Alpha: 0.5
- Numerical stability threshold: 1e-8
- Event-level evaluation threshold points: 201
- Alarm silence: 1 hourly step

### Full-Cohort Event-Level Results

| Alarm strategy | Event-level AuPRC |
|---|---:|
| EEP fixed horizon | 0.412300 |
| survTLS fixed horizon | 0.421205 |
| Reproduced paper imminent priority | 0.432762 |
| Proposed PMF urgency | 0.429362 |

The proposed extension outperformed both fixed-horizon
strategies but did not exceed the reproduced imminent
priority strategy. These are reproduction experiment
results, not values reported in the original paper.

### Numerical Consistency Validation

The reusable `pmf_urgency_score` function was compared
against saved scores from the original experiments.

| Check | Validation | Test |
|---|---:|---:|
| Timesteps | 284,959 | 523,208 |
| Record alignment | PASS | PASS |
| Maximum absolute error | 3.33e-16 | 3.33e-16 |
| Score consistency | PASS | PASS |

All 808,167 timestep scores agreed within numerical
tolerance (rtol=1e-7, atol=1e-10).

This validates the scoring function against the original
experiment outputs. It does not constitute independent
retraining or recomputation of the complete event-level
evaluation.

### Reusable Implementation

- `pmf_urgency.py`: PMF-based urgency scoring and synthetic
usage example.
- `tests/core/test_pmf_urgency.py`: Six synthetic unit tests.

No patient-level predictions or restricted MIMIC-III
records are distributed with this contribution.
32 changes: 32 additions & 0 deletions examples/mortality_prediction/DSA_SYNTHETIC_PIPELINE_RESULTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# DSA Synthetic Full-Pipeline Validation

## Setup
- Data: 12 synthetic ICU patients
- Split: 8 train / 2 validation / 2 test patients
- Hourly samples: 204 / 51 / 51
- Task: DecompensationMIMIC3
- Model: DSA (GRU, hidden dimension 16)
- Training: 1 epoch, CPU
- Evaluation metric: Test AuPRC

## Results

| Configuration | Synthetic Test AuPRC |
|---|---:|
| Truncated | 0.4706 |
| Truncated + Bias | 0.4659 |
| Truncated + Bias + survTLS | 0.5173 |

## Validation
- All three variants completed training and evaluation.
- Hourly samples and survival labels were generated by the
DecompensationMIMIC3 task.
- Patient-level train/validation/test separation was used.
- The DSA model was trained through PyHealth Trainer.

## Limitations
- These are synthetic demonstration results, not MIMIC-III results.
- The synthetic test cohort is small.
- No statistical significance is claimed.
- This example does not independently demonstrate a new
PyHealth Dataset contribution.
131 changes: 131 additions & 0 deletions examples/mortality_prediction/early_event_metrics.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
"""Transparent event-level evaluation for early-event prediction examples.

This lightweight example utility deliberately has no dataset or local-file dependency.
Each record is a dict with stay, period_length, last_t, ever_event,
y_true (whether an alarm at that instant is timely), and the score column.
One event at most per stay is assumed. Time units must be consistent.

This implementation uses *time-based* alarm silence. With silence_steps=1,
an alarm at hour 5 suppresses another at hour 6 (next eligible hour 7).
That equals the source script for contiguous hourly observations, but differs
when observations are missing. It is NOT a drop-in replacement for previous
reported results without protocol equivalence checks.
"""

from collections import defaultdict
from math import isfinite
from statistics import mean, median


def prepare_records(records, score_col="score"):
"""Validate and group records by stay, ordered by observation time."""
grouped = defaultdict(list)
for record in records:
for field in ("stay", "period_length", "last_t", "ever_event", "y_true", score_col):
if field not in record:
raise ValueError(f"Missing required field: {field}")
row = dict(record)
for field in ("period_length", "last_t", score_col):
row[field] = float(row[field])
if not isfinite(row[field]):
raise ValueError(f"Non-finite {field}")
for field in ("ever_event", "y_true"):
if row[field] not in (0, 1, False, True):
raise ValueError(f"{field} must be 0 or 1")
row[field] = bool(row[field])
grouped[str(row["stay"])].append(row)
if not grouped:
raise ValueError("At least one observation is required")
for stay, rows in grouped.items():
rows.sort(key=lambda r: r["period_length"])
if len({r["period_length"] for r in rows}) != len(rows):
raise ValueError(f"Duplicate observation times in stay {stay}")
if len({r["ever_event"] for r in rows}) != 1:
raise ValueError(f"Inconsistent ever_event within stay {stay}")
if any(r["y_true"] and not r["ever_event"] for r in rows):
raise ValueError(f"Positive y_true in non-event stay {stay}")
return dict(grouped)


def evaluate_threshold(grouped, threshold, *, score_col="score", silence_steps=1):
"""Evaluate a fixed alarm threshold; no threshold fitting occurs here.

Precision is None if no alarms; recall is None if no event stays.
False alarms count alarms with y_true=False, even on event stays.
Lead time is measured at the *first timely alarm per event stay*.
"""
if not isfinite(threshold) or silence_steps < 0:
raise ValueError("Invalid threshold or silence_steps")
total = true = detected = event_stays = 0
leads, per_stay_alarms, per_stay_false = [], [], []
for rows in grouped.values():
event_stays += int(rows[0]["ever_event"])
last_alarm_time = float("-inf")
first_lead = None
n_alarms = n_false = 0
for row in rows:
now = row["period_length"]
if now <= last_alarm_time + silence_steps:
continue
if row[score_col] < threshold:
continue
last_alarm_time = now
total += 1
n_alarms += 1
if row["y_true"]:
true += 1
if first_lead is None:
first_lead = row["last_t"] + 1.0 - now
else:
n_false += 1
if first_lead is not None:
detected += 1
leads.append(float(first_lead))
per_stay_alarms.append(n_alarms)
per_stay_false.append(n_false)
n_stays = len(grouped)
false_alarms = total - true
return {
"threshold": float(threshold),
"event_recall": detected / event_stays if event_stays else None,
"alarm_precision": true / total if total else None,
"total_alarms": total,
"true_alarms": true,
"false_alarms": false_alarms,
"events": event_stays,
"detected_events": detected,
"stays": n_stays,
"false_alarms_per_100_stays": 100.0 * false_alarms / n_stays,
"mean_lead_steps": mean(leads) if leads else None,
"median_lead_steps": median(leads) if leads else None,
"mean_alarms_per_stay": mean(per_stay_alarms),
"stays_ge2_false_alarms": sum(n >= 2 for n in per_stay_false) / n_stays,
}


def select_validation_threshold(validation, thresholds, target_precision, *, score_col="score", silence_steps=1):
"""Choose max validation event recall subject to alarm precision constraint.

Empty-alarm operating points are INELIGIBLE. Tie-break by precision,
then threshold (deterministically). Never reads the test set.
"""
if not 0 <= target_precision <= 1:
raise ValueError("target_precision must be between zero and one")
candidates = []
for threshold in thresholds:
metric = evaluate_threshold(validation, float(threshold), score_col=score_col, silence_steps=silence_steps)
if metric["total_alarms"] and metric["alarm_precision"] >= target_precision:
candidates.append(metric)
if not candidates:
return None
return max(candidates, key=lambda x: (x["event_recall"] if x["event_recall"] is not None else -1, x["alarm_precision"], x["threshold"]))


def evaluate_validation_selected_test(val_records, test_records, thresholds, target_precision, *, score_col="score", silence_steps=1):
"""Select threshold only on validation; apply unchanged to test."""
val = prepare_records(val_records, score_col=score_col)
test = prepare_records(test_records, score_col=score_col)
chosen = select_validation_threshold(val, thresholds, target_precision, score_col=score_col, silence_steps=silence_steps)
if chosen is None:
return {"validation": None, "test": None}
return {"validation": chosen, "test": evaluate_threshold(test, chosen["threshold"], score_col=score_col, silence_steps=silence_steps)}
Loading
Loading