Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
364090d
Add Chest ImaGenome dataset
jhnwu3 Nov 5, 2026
5608d43
Add EHR + CXR mortality and phenotyping tasks for MIMIC-IV
jhnwu3 Nov 5, 2026
494dbfc
Merge feat/chest-imagenome-dataset (#1392) into feat/disease-progress…
jhnwu3 Nov 5, 2026
f679b33
Add disease progression task over MIMIC-IV and Chest ImaGenome
jhnwu3 Nov 5, 2026
f20ae7e
Add DiPro model for disease progression between chest X-rays
jhnwu3 Nov 6, 2026
4441be5
Merge origin/master (be1ecbf) into feat/chest-imagenome-dataset
jhnwu3 Nov 10, 2026
424b911
Merge origin/master (be1ecbf) into feat/ehr-cxr-image-task
jhnwu3 Nov 10, 2026
d10690b
Merge feat/ehr-cxr-image-task (424b911) into feat/disease-progression…
jhnwu3 Nov 10, 2026
5e028e7
Merge feat/chest-imagenome-dataset (4441be5) into feat/disease-progre…
jhnwu3 Nov 10, 2026
2026f80
Move the ImaGenome join and GoldTestSplit out of shared modules
jhnwu3 Nov 10, 2026
15c3f92
Merge feat/disease-progression-task (2026f80) into feat/dipro-model
jhnwu3 Nov 10, 2026
c0cd585
Record origin/master (be1ecbf) as merged into feat/ehr-cxr-image-task
jhnwu3 Nov 10, 2026
fd10e2a
Merge feat/ehr-cxr-image-task (c0cd585) into feat/disease-progression…
jhnwu3 Nov 10, 2026
8b49638
Merge feat/disease-progression-task into feat/dipro-model
jhnwu3 Nov 10, 2026
dc5cc7e
DiPro: mask padded image pairs everywhere; fix the ehr docstring
jhnwu3 Nov 10, 2026
45e0587
DiPro: interval fallback attends only to real EHR rows
jhnwu3 Nov 10, 2026
aef5d9c
Merge master into feat/dipro-model
solarsys Nov 14, 2026
bf3a9d4
Trigger CI after retargeting to master
solarsys Nov 14, 2026
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 @@ -316,6 +316,7 @@ API Reference
models/pyhealth.models.Agent
models/pyhealth.models.GRASP
models/pyhealth.models.MedFuse
models/pyhealth.models.DiPro
models/pyhealth.models.MedLink
models/pyhealth.models.TCN
models/pyhealth.models.TFMTokenizer
Expand Down
25 changes: 25 additions & 0 deletions docs/api/models/pyhealth.models.DiPro.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
pyhealth.models.DiPro
=====================

Overview
--------

DiPro identifies disease progression between two chest X-rays from anatomical
regions and the EHR recorded around them, by separating static from dynamic
image features and aligning them with the EHR at several time scales. Use it
with :class:`~pyhealth.tasks.DiseaseProgressionMIMIC4`.

DiPro as published works on anatomical region crops: build the task with
``region_crops=True``. The model also accepts whole images, as a single
region, but results in that mode are not those of DiPro as published.

Reference: Liu et al., "Multimodal Disease Progression Modeling via
Spatiotemporal Disentanglement and Multiscale Alignment." NeurIPS 2025.

API Reference
-------------

.. autoclass:: pyhealth.models.DiPro
:members:
:undoc-members:
:show-inheritance:
3 changes: 3 additions & 0 deletions docs/api/processors.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ MLP and others) train on a field of that type.
- ``SignalProcessor``: For general signal data (e.g., EEG, ECG)
- ``TimeseriesProcessor``: For time-series data; optional ``normalization`` (``"zscore"`` or ``"minmax"``, fitted on the training split) and ``missing_indicators``
- ``TimeImageProcessor``: For time-stamped image sequences (e.g., serial X-rays)
- ``TimeRegionImageProcessor``: For the same regions cropped from time-stamped images
- ``TensorProcessor``: For pre-processed tensor data; optional ``normalization``, ``missing_indicators`` and ``impute_strategy="zero"``
- ``RawProcessor``: Pass-through processor for raw data

Expand Down Expand Up @@ -398,6 +399,7 @@ Common string keys for automatic processor selection:
- ``"signal"``: For signal data
- ``"timeseries"``: For time-series data
- ``"time_image"``: For time-stamped image sequences
- ``"time_region_image"``: For regions cropped from time-stamped images
- ``"tensor"``: For pre-processed tensors
- ``"raw"``: For raw/unprocessed data
- ``"graph"``: For knowledge graph subgraphs
Expand Down Expand Up @@ -614,6 +616,7 @@ API Reference
processors/pyhealth.processors.TimeseriesProcessor
processors/pyhealth.processors.TemporalTimeseriesProcessor
processors/pyhealth.processors.TimeImageProcessor
processors/pyhealth.processors.TimeRegionImageProcessor
processors/pyhealth.processors.TensorProcessor
processors/pyhealth.processors.RawProcessor
processors/pyhealth.processors.IgnoreProcessor
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
pyhealth.processors.TimeRegionImageProcessor
=============================================

Processor for anatomical regions cropped from time-stamped images.

.. autoclass:: pyhealth.processors.TimeRegionImageProcessor
:members:
:undoc-members:
:show-inheritance:
168 changes: 168 additions & 0 deletions examples/cxr/dipro_mimic4.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,168 @@
"""DiPro for disease progression between chest X-rays: smoke test.

SMOKE TEST ONLY. By default this script writes the tiny fabricated MIMIC-IV,
MIMIC-CXR and Chest ImaGenome tree of ``disease_progression_mimic4.py`` to a
temporary directory (random values and images, no patient data), then trains a
tiny DiPro for a few steps. It reproduces nothing, and its numbers mean nothing
clinically.

To run on the real data, you need credentialed PhysioNet access to MIMIC-IV,
MIMIC-CXR-JPG and Chest ImaGenome. Unzip ``silver_dataset/scene_graph.zip``,
then pass the three roots and DiPro's sizes:

python examples/cxr/dipro_mimic4.py \
--ehr-root /path/to/mimic-iv/2.2 \
--cxr-root /path/to/mimic-cxr-jpg/2.0.0 \
--imagenome-root /path/to/chest-imagenome/1.0.0 \
--image-size 224 --d-model 256 --backbone resnet50 --pretrained \
--batch-size 8 --epochs 100

That is still not DiPro's full setup: it uses 17 EHR variables, not 38, and
``Trainer`` has no gradient accumulation or cosine decay.

For reference, Liu et al. (2025) report for DiPro on this task, over three
seeds: precision 0.484 ± 0.008, recall 0.471 ± 0.024, F1 0.466 ± 0.018, AUPRC
0.478 ± 0.018, AUROC 0.664 ± 0.013 and accuracy 0.565 ± 0.013, on 3982/560/1137
train/val/test samples.

Paper:
Liu et al. "Multimodal Disease Progression Modeling via Spatiotemporal
Disentanglement and Multiscale Alignment." NeurIPS 2025.
https://arxiv.org/abs/2510.11112
"""

from __future__ import annotations

import argparse
import json
import tempfile
from pathlib import Path

import numpy as np
import torch
from disease_progression_mimic4 import write_ehr, write_imagenome, write_images
from sklearn.metrics import f1_score

from pyhealth.datasets import GoldTestSplit, MIMIC4ImaGenomeDataset, get_dataloader
from pyhealth.models import DiPro
from pyhealth.tasks import DiseaseProgressionMIMIC4
from pyhealth.trainer import Trainer


def add_boxes(root: Path, regions: list[str]) -> None:
"""Adds fabricated boxes to the scene graphs, leaving out the last region."""
for path in (root / "silver_dataset" / "scene_graph").glob("*.json"):
graph = json.loads(path.read_text())
graph["objects"] = [
{"bbox_name": region, "original_x1": 4 * index, "original_y1": 4,
"original_x2": 4 * index + 20, "original_y2": 40}
for index, region in enumerate(regions[:-1])
]
path.write_text(json.dumps(graph))


def macro_f1(y_true: np.ndarray, y_prob: np.ndarray, diseases: int) -> float:
"""Computes DiPro's F1: macro over statuses, then mean over diseases.

``Trainer``'s multilabel metrics would count a disease that is not
mentioned as a negative, so they are not comparable with the paper.
"""
scores = []
truth = y_true.reshape(-1, diseases, 3)
predicted = y_prob.reshape(-1, diseases, 3).argmax(-1)
for disease in range(diseases):
mentioned = truth[:, disease].sum(-1) > 0
if mentioned.any():
scores.append(
f1_score(
truth[mentioned, disease].argmax(-1),
predicted[mentioned, disease],
average="macro",
)
)
return float(np.mean(scores)) if scores else float("nan")


def parse_args() -> argparse.Namespace:
"""Parses CLI arguments."""
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("--ehr-root", help="MIMIC-IV root; fabricated data if unset")
parser.add_argument("--cxr-root", help="MIMIC-CXR-JPG root")
parser.add_argument("--imagenome-root", help="chest-imagenome/1.0.0 root")
parser.add_argument("--patients", type=int, default=10)
parser.add_argument("--image-size", type=int, default=32)
parser.add_argument("--d-model", type=int, default=32)
parser.add_argument("--backbone", default="resnet18")
parser.add_argument("--pretrained", action="store_true")
parser.add_argument("--batch-size", type=int, default=4)
parser.add_argument("--epochs", type=int, default=2)
parser.add_argument("--lr", type=float, default=1.6e-4, help="DiPro's scaled rate")
parser.add_argument("--seed", type=int, default=0)
return parser.parse_args()


def main() -> None:
"""Builds the samples, trains DiPro and evaluates it."""
args = parse_args()
torch.manual_seed(args.seed)
task = DiseaseProgressionMIMIC4(
image_size=args.image_size, region_crops=True, include_demographics=True
)
with tempfile.TemporaryDirectory() as tmp:
ehr_root, cxr_root = args.ehr_root, args.cxr_root
imagenome_root = args.imagenome_root
if ehr_root is None:
print("SMOKE TEST on fabricated data; results are not meaningful.")
root, rng = Path(tmp), np.random.default_rng(args.seed)
ehr_root = root / "mimic-iv"
cxr_root = root / "mimic-cxr"
imagenome_root = root / "chest-imagenome"
write_ehr(ehr_root, args.patients, rng)
write_images(cxr_root, args.patients, rng)
write_imagenome(imagenome_root, args.patients, rng)
add_boxes(imagenome_root, task.REGIONS)
dataset = MIMIC4ImaGenomeDataset(
imagenome_root=str(imagenome_root),
imagenome_tables=[
"silver_images",
"silver_objects",
"silver_comparisons",
"gold_comparisons",
],
ehr_root=str(ehr_root),
cxr_root=str(cxr_root),
ehr_tables=["chartevents", "labevents"],
cxr_tables=["metadata"],
cache_dir=str(Path(tmp) / "cache") if args.ehr_root is None else None,
)
train, val, test = dataset.set_task(
task, split=GoldTestSplit(task.gold_subjects(dataset), seed=args.seed)
)
print(f"{len(train)}/{len(val)}/{len(test)} train/val/test samples")

model = DiPro(
train,
d_model=args.d_model,
backbone=args.backbone,
pretrained=args.pretrained,
)
model.set_class_weights(train)
print(f"{sum(p.numel() for p in model.parameters())} parameters")

trainer = Trainer(model, metrics=["hamming_loss"], enable_logging=False)
trainer.train(
get_dataloader(train, batch_size=args.batch_size, shuffle=True),
get_dataloader(val, batch_size=args.batch_size),
epochs=args.epochs,
optimizer_class=torch.optim.AdamW,
optimizer_params={"lr": args.lr},
)
y_true, y_prob, loss = trainer.inference(
get_dataloader(test, batch_size=args.batch_size)
)
print(f"test loss {loss:.4f}")
print(f"test F1 {macro_f1(y_true, y_prob, model.num_diseases):.4f}")


if __name__ == "__main__":
main()
1 change: 1 addition & 0 deletions pyhealth/models/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
from .graph_torchvision_model import Graph_TorchvisionModel
from .graphcare import GraphCare
from .grasp import GRASP, GRASPLayer
from .dipro import DiPro as DiPro
from .medfuse import MedFuse, MedFuseLayer
from .medlink import MedLink
from .micron import MICRON, MICRONLayer
Expand Down
Loading
Loading