minhy112 commited on
Commit
9df13b0
·
verified ·
1 Parent(s): 70f7ab5

Add scripts

Browse files
scripts/finish.sh ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Full remaining pipeline, run sequentially so nothing competes for the GPU.
3
+ # Idempotent: run_experiments skips configs whose summary.json already exists.
4
+ set -u
5
+ cd /root/al
6
+ export PYTHONPATH=src
7
+ LOG=results/logs
8
+
9
+ echo "[finish] $(date +%H:%M:%S) main grid ..."
10
+ python scripts/run_experiments.py --grid main --device cuda >> "$LOG/main_grid.log" 2>&1
11
+
12
+ echo "[finish] $(date +%H:%M:%S) ablation grid ..."
13
+ python scripts/run_experiments.py --grid ablation --device cuda >> "$LOG/ablation_grid.log" 2>&1
14
+
15
+ echo "[finish] $(date +%H:%M:%S) confound analysis ..."
16
+ python src/trifuse/analysis/confound.py data/metadata/subjects_clean.csv \
17
+ results/tables/confound >> "$LOG/analysis.log" 2>&1
18
+
19
+ echo "[finish] $(date +%H:%M:%S) subgroup analysis (main-grid OOF) ..."
20
+ python - >> "$LOG/analysis.log" 2>&1 <<'PY'
21
+ import sys, glob; sys.path.insert(0, "src")
22
+ from pathlib import Path
23
+ from trifuse.analysis.subgroup import run_subgroup
24
+ oof = {Path(p).parent.name: p for p in glob.glob("results/*/oof.csv")}
25
+ print("subgroup over:", sorted(oof))
26
+ run_subgroup(oof, "data/metadata/subjects_clean.csv", "results/tables/subgroup")
27
+ PY
28
+
29
+ echo "[finish] $(date +%H:%M:%S) tables ..."
30
+ python scripts/make_tables.py >> "$LOG/tables.log" 2>&1
31
+
32
+ echo "[finish] $(date +%H:%M:%S) figures ..."
33
+ python scripts/make_figures.py >> "$LOG/figures.log" 2>&1
34
+
35
+ echo "[finish] $(date +%H:%M:%S) interpretability (Grad-CAM) ..."
36
+ python scripts/make_interpret.py >> "$LOG/interpret.log" 2>&1
37
+
38
+ echo "[finish] $(date +%H:%M:%S) DONE"
scripts/make_figures.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Render the paper's figures from results/<name>/ OOF predictions and summaries.
2
+
3
+ Figures (saved under results/figures/):
4
+ fig_main_comparison.png Macro-F1 mean±std bar chart across all models
5
+ fig_confusion_<name>.png pooled 3x3 confusion matrix (row-normalized) per model
6
+ fig_roc_<name>.png one-vs-rest ROC curves (CN/VMD/AD) per model
7
+ fig_subgroup.png Macro-F1 by age band and sex for the strongest models
8
+
9
+ All figures are regenerated deterministically from saved OOF preds; no re-training.
10
+ Models without a summary.json yet are silently skipped, so this can run while the
11
+ grid is still in progress.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+ import matplotlib
22
+ matplotlib.use("Agg")
23
+ import matplotlib.pyplot as plt # noqa: E402
24
+ from sklearn.metrics import roc_curve, auc # noqa: E402
25
+
26
+ ROOT = Path(__file__).resolve().parents[1]
27
+ sys.path.insert(0, str(ROOT / "src"))
28
+ RESULTS = ROOT / "results"
29
+ FIGURES = RESULTS / "figures"
30
+ SUBJECTS_CSV = ROOT / "data/metadata/subjects_clean.csv"
31
+
32
+ from trifuse.eval.metrics import CLASS_NAMES, confusion # noqa: E402
33
+ from trifuse.analysis.subgroup import subgroup_table # noqa: E402
34
+
35
+ # display order + labels (same keys as make_tables.MAIN_ORDER)
36
+ MODELS = [
37
+ ("xgboost", "XGBoost"),
38
+ ("tabular_mlp", "MLP"),
39
+ ("resnet50", "ResNet50"),
40
+ ("densenet2p5d", "DenseNet121"),
41
+ ("resnet3d", "3D ResNet18"),
42
+ ("vit_b16", "ViT-B/16"),
43
+ ("swin3d", "3D Swin-T"),
44
+ ("hcct", "3D HCCT"),
45
+ ("vswin_lite", "VSwinFormer-lite"),
46
+ ("densenet_latefusion", "DenseNet+concat"),
47
+ ("trifuse_ad", "TriFuse-AD"),
48
+ ]
49
+ PROB_COLS = ["prob_0", "prob_1", "prob_2"]
50
+
51
+
52
+ def _summary(name):
53
+ p = RESULTS / name / "summary.json"
54
+ return json.loads(p.read_text()) if p.exists() else None
55
+
56
+
57
+ def _oof(name):
58
+ p = RESULTS / name / "oof.csv"
59
+ return pd.read_csv(p) if p.exists() else None
60
+
61
+
62
+ def fig_main_comparison():
63
+ names, means, stds = [], [], []
64
+ for key, disp in MODELS:
65
+ s = _summary(key)
66
+ if s is None:
67
+ continue
68
+ m = s["summary"]["macro_f1"]
69
+ names.append(disp)
70
+ means.append(m["mean"] * 100)
71
+ stds.append(m["std"] * 100)
72
+ if not names:
73
+ return
74
+ colors = ["#4c72b0"] * len(names)
75
+ if "TriFuse-AD" in names:
76
+ colors[names.index("TriFuse-AD")] = "#c44e52"
77
+ fig, ax = plt.subplots(figsize=(10, 5))
78
+ y = np.arange(len(names))
79
+ ax.barh(y, means, xerr=stds, color=colors, capsize=3, alpha=0.9)
80
+ ax.set_yticks(y)
81
+ ax.set_yticklabels(names)
82
+ ax.invert_yaxis()
83
+ ax.set_xlabel("Macro-F1 (%) — mean ± std over 15 runs")
84
+ ax.set_title("Three-stage classification (CN / VMD / AD), OASIS-1 age≥60")
85
+ ax.grid(axis="x", alpha=0.3)
86
+ for yi, mv in zip(y, means):
87
+ ax.text(mv + 1, yi, f"{mv:.1f}", va="center", fontsize=8)
88
+ fig.tight_layout()
89
+ fig.savefig(FIGURES / "fig_main_comparison.png", dpi=150)
90
+ plt.close(fig)
91
+
92
+
93
+ def fig_confusion(name, disp):
94
+ oof = _oof(name)
95
+ if oof is None:
96
+ return
97
+ cm = confusion(oof["y_true"].to_numpy(), oof["y_pred"].to_numpy())
98
+ cmn = cm / cm.sum(axis=1, keepdims=True).clip(min=1)
99
+ fig, ax = plt.subplots(figsize=(4.2, 3.8))
100
+ im = ax.imshow(cmn, cmap="Blues", vmin=0, vmax=1)
101
+ ax.set_xticks(range(3)); ax.set_yticks(range(3))
102
+ ax.set_xticklabels(CLASS_NAMES); ax.set_yticklabels(CLASS_NAMES)
103
+ ax.set_xlabel("Predicted"); ax.set_ylabel("True")
104
+ ax.set_title(f"{disp} (pooled 15 runs)")
105
+ for i in range(3):
106
+ for j in range(3):
107
+ ax.text(j, i, f"{cmn[i, j]:.2f}\n({cm[i, j]})", ha="center", va="center",
108
+ color="white" if cmn[i, j] > 0.5 else "black", fontsize=8)
109
+ fig.colorbar(im, ax=ax, fraction=0.046)
110
+ fig.tight_layout()
111
+ fig.savefig(FIGURES / f"fig_confusion_{name}.png", dpi=150)
112
+ plt.close(fig)
113
+
114
+
115
+ def fig_roc(name, disp):
116
+ oof = _oof(name)
117
+ if oof is None or not set(PROB_COLS).issubset(oof.columns):
118
+ return
119
+ y = oof["y_true"].to_numpy()
120
+ prob = oof[PROB_COLS].to_numpy()
121
+ fig, ax = plt.subplots(figsize=(4.5, 4.2))
122
+ for c, cname in enumerate(CLASS_NAMES):
123
+ yc = (y == c).astype(int)
124
+ if yc.sum() == 0:
125
+ continue
126
+ fpr, tpr, _ = roc_curve(yc, prob[:, c])
127
+ ax.plot(fpr, tpr, label=f"{cname} (AUC={auc(fpr, tpr):.2f})")
128
+ ax.plot([0, 1], [0, 1], "k--", alpha=0.4)
129
+ ax.set_xlabel("False positive rate"); ax.set_ylabel("True positive rate")
130
+ ax.set_title(f"{disp} — one-vs-rest ROC")
131
+ ax.legend(loc="lower right", fontsize=8)
132
+ fig.tight_layout()
133
+ fig.savefig(FIGURES / f"fig_roc_{name}.png", dpi=150)
134
+ plt.close(fig)
135
+
136
+
137
+ def fig_subgroup():
138
+ """Macro-F1 by age band / sex for the models that have OOF, focused on the strongest."""
139
+ if not SUBJECTS_CSV.exists():
140
+ return
141
+ have = [(k, d) for k, d in MODELS if (RESULTS / k / "oof.csv").exists()]
142
+ # prefer TriFuse-AD + best MRI-only + a tabular shortcut, if present
143
+ pick = [kd for kd in have if kd[0] in {"trifuse_ad", "resnet3d", "xgboost", "densenet_latefusion"}]
144
+ pick = pick or have[:3]
145
+ if not pick:
146
+ return
147
+ subgroups = ["Overall", "60-69", "70-79", "80+", "Male", "Female"]
148
+ fig, ax = plt.subplots(figsize=(9, 4.5))
149
+ width = 0.8 / len(pick)
150
+ x = np.arange(len(subgroups))
151
+ for i, (key, disp) in enumerate(pick):
152
+ t = subgroup_table(RESULTS / key / "oof.csv", SUBJECTS_CSV).set_index("subgroup")
153
+ vals = [t.loc[g, "macro_f1"] * 100 if g in t.index and "macro_f1" in t.columns
154
+ and not pd.isna(t.loc[g, "macro_f1"]) else 0 for g in subgroups]
155
+ ax.bar(x + i * width, vals, width, label=disp)
156
+ ax.set_xticks(x + width * (len(pick) - 1) / 2)
157
+ ax.set_xticklabels(subgroups)
158
+ ax.set_ylabel("Macro-F1 (%)")
159
+ ax.set_title("Subgroup robustness (pooled OOF)")
160
+ ax.legend(fontsize=8)
161
+ ax.grid(axis="y", alpha=0.3)
162
+ fig.tight_layout()
163
+ fig.savefig(FIGURES / "fig_subgroup.png", dpi=150)
164
+ plt.close(fig)
165
+
166
+
167
+ def main():
168
+ FIGURES.mkdir(parents=True, exist_ok=True)
169
+ fig_main_comparison()
170
+ for key, disp in MODELS:
171
+ fig_confusion(key, disp)
172
+ fig_roc(key, disp)
173
+ fig_subgroup()
174
+ made = sorted(p.name for p in FIGURES.glob("*.png"))
175
+ print(f"wrote {len(made)} figures to {FIGURES}:")
176
+ for m in made:
177
+ print(" ", m)
178
+
179
+
180
+ if __name__ == "__main__":
181
+ main()
scripts/make_interpret.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """P11 interpretability: train TriFuse-AD on one representative fold, then run
2
+ Grad-CAM on the shared CNN encoder for a few correct + incorrect test cases.
3
+
4
+ Qualitative only. We do NOT claim the model localizes specific structures; we
5
+ report that attended regions overlap with anatomy known to be relevant in AD
6
+ (medial temporal lobe, ventricles, cortical atrophy).
7
+
8
+ Needs the GPU, so run this AFTER the main grid finishes (TriFuse-AD is the last
9
+ config in the grid and holds the GPU until then).
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+ import torch
19
+ import torch.nn as nn
20
+ import matplotlib
21
+ matplotlib.use("Agg")
22
+ import matplotlib.pyplot as plt # noqa: E402
23
+
24
+ ROOT = Path(__file__).resolve().parents[1]
25
+ sys.path.insert(0, str(ROOT / "src"))
26
+ RESULTS = ROOT / "results"
27
+ FIGURES = RESULTS / "figures"
28
+ SUBJECTS_CSV = ROOT / "data/metadata/subjects_clean.csv"
29
+
30
+ from trifuse.data.datasets import SliceDataset, collate, fit_tab_stats # noqa: E402
31
+ from trifuse.data.splits import make_folds, split_for # noqa: E402
32
+ from trifuse.models.registry import build_model # noqa: E402
33
+ from trifuse.training.config import TrainConfig # noqa: E402
34
+ from trifuse.training.trainer import fit # noqa: E402
35
+ from trifuse.analysis.gradcam import GradCAM, overlay_heatmap # noqa: E402
36
+ from trifuse.eval.metrics import CLASS_NAMES # noqa: E402
37
+ from torch.utils.data import DataLoader # noqa: E402
38
+
39
+ TRI = ("axial", "coronal", "sagittal")
40
+ SEED, FOLD = 7, 0
41
+
42
+
43
+ class _SlicesOnly(nn.Module):
44
+ """Adapt TriFuse-AD's (slices, tab) forward to the single-input API Grad-CAM expects."""
45
+
46
+ def __init__(self, model: nn.Module, tab: torch.Tensor):
47
+ super().__init__()
48
+ self.model = model
49
+ self.tab = tab
50
+
51
+ def forward(self, slices: torch.Tensor) -> torch.Tensor:
52
+ return self.model(slices, self.tab)
53
+
54
+
55
+ def _target_layer(model: nn.Module) -> nn.Module:
56
+ """Last conv stage of the timm ConvNeXt encoder (outputs B,C,H,W)."""
57
+ enc = model.encoder
58
+ if hasattr(enc, "stages"):
59
+ return enc.stages[-1]
60
+ # fallback: last Conv2d
61
+ convs = [m for m in enc.modules() if isinstance(m, nn.Conv2d)]
62
+ return convs[-1]
63
+
64
+
65
+ def _train_fold(device: str) -> tuple[nn.Module, pd.DataFrame, dict, TrainConfig]:
66
+ df = pd.read_csv(SUBJECTS_CSV)
67
+ folds = make_folds(df)
68
+ tr, va, te = split_for(folds, df, SEED, FOLD)
69
+ train_df = df[df.subject_id.isin(tr)]
70
+ val_df = df[df.subject_id.isin(va)]
71
+ test_df = df[df.subject_id.isin(te)]
72
+
73
+ cfg = TrainConfig(name="trifuse_interp", model="trifuse", modality="multimodal",
74
+ n_slices=9, planes=TRI, epochs=70, batch_size=6,
75
+ lr=3e-4, backbone_lr=3e-5, freeze_epochs=6, seed=SEED)
76
+ tab_stats = fit_tab_stats(train_df, cfg.tab_features)
77
+ counts = np.bincount(train_df["class_id"], minlength=3).tolist()
78
+
79
+ def loader(sub, shuffle, aug):
80
+ ds = SliceDataset(sub, cfg.tab_features, tab_stats, planes=TRI,
81
+ n_slices=cfg.n_slices, modality="multimodal", augment=aug)
82
+ return DataLoader(ds, batch_size=cfg.batch_size, shuffle=shuffle,
83
+ num_workers=cfg.num_workers, collate_fn=collate, pin_memory=True)
84
+
85
+ model = build_model(cfg, n_tab_features=len(cfg.tab_features), pretrained=True)
86
+ fit(model, loader(train_df, True, True), loader(val_df, False, False),
87
+ cfg, counts, device=device)
88
+ return model, test_df, tab_stats, cfg
89
+
90
+
91
+ def _gradcam_for_subject(model, target, batch, device, n_slices, planes):
92
+ """Return {plane: (gray_center, heat_center)} for the argmax class, center slice per plane.
93
+
94
+ TriFuse-AD flattens the 27 slices into the CNN batch dim, so the target layer's
95
+ captured activations/grads are (T, C, H', W') — one per slice. We compute a
96
+ per-token Grad-CAM here rather than using GradCAM.__call__'s single-map return.
97
+ """
98
+ import torch.nn.functional as F
99
+ slices = batch["slices"].to(device) # (1, T, 3, H, W)
100
+ tab = batch["tab"].to(device)
101
+ wrapper = _SlicesOnly(model, tab)
102
+ cam = GradCAM(wrapper, target)
103
+ _ = cam(slices, class_idx=None) # triggers fwd+bwd, fills cam._acts/_grads
104
+ acts, grads = cam._acts, cam._grads # (T, C, H', W')
105
+ cam.remove()
106
+
107
+ H, W = slices.shape[-2:]
108
+ weights = grads.mean(dim=(2, 3), keepdim=True) # (T, C, 1, 1)
109
+ heat = F.relu((weights * acts).sum(dim=1)) # (T, H', W')
110
+ heat = F.interpolate(heat.unsqueeze(1), size=(H, W), mode="bilinear",
111
+ align_corners=False)[:, 0] # (T, H, W)
112
+ heat = heat.detach().cpu().numpy()
113
+
114
+ out = {}
115
+ center = n_slices // 2
116
+ for p_idx, plane in enumerate(planes):
117
+ tok = p_idx * n_slices + center
118
+ gray = slices[0, tok, 0].detach().cpu().numpy()
119
+ h = heat[tok]
120
+ h = (h - h.min()) / (np.ptp(h) + 1e-8) # per-slice normalize
121
+ out[plane] = (gray, h)
122
+ return out
123
+
124
+
125
+ def main():
126
+ device = "cuda" if torch.cuda.is_available() else "cpu"
127
+ FIGURES.mkdir(parents=True, exist_ok=True)
128
+ print(f"training TriFuse-AD on seed={SEED} fold={FOLD} ({device}) for interpretability...",
129
+ flush=True)
130
+ model, test_df, tab_stats, cfg = _train_fold(device)
131
+ model.eval()
132
+ target = _target_layer(model)
133
+
134
+ ds = SliceDataset(test_df, cfg.tab_features, tab_stats, planes=TRI,
135
+ n_slices=cfg.n_slices, modality="multimodal", augment=False)
136
+ dl = DataLoader(ds, batch_size=1, shuffle=False, collate_fn=collate)
137
+
138
+ cases = [] # (subject_id, y_true, y_pred, {plane:(gray,heat)})
139
+ for batch in dl:
140
+ with torch.no_grad():
141
+ logits = model(batch["slices"].to(device), batch["tab"].to(device))
142
+ pred = int(logits.argmax(1)[0])
143
+ yt = int(batch["y"][0])
144
+ maps = _gradcam_for_subject(model, target, batch, device, cfg.n_slices, TRI)
145
+ cases.append((batch["subject_id"][0], yt, pred, maps))
146
+
147
+ correct = [c for c in cases if c[1] == c[2]][:6]
148
+ wrong = [c for c in cases if c[1] != c[2]][:3]
149
+ picked = correct + wrong
150
+ if not picked:
151
+ print("no test cases produced; aborting figure")
152
+ return
153
+
154
+ n = len(picked)
155
+ fig, axes = plt.subplots(n, 3, figsize=(9, 3 * n))
156
+ if n == 1:
157
+ axes = axes[None, :]
158
+ for r, (sid, yt, yp, maps) in enumerate(picked):
159
+ tag = "OK" if yt == yp else "WRONG"
160
+ for c, plane in enumerate(TRI):
161
+ gray, heat = maps[plane]
162
+ axes[r, c].imshow(overlay_heatmap(gray, heat))
163
+ axes[r, c].axis("off")
164
+ if c == 0:
165
+ axes[r, c].set_ylabel(f"{sid}\nT:{CLASS_NAMES[yt]} P:{CLASS_NAMES[yp]} [{tag}]",
166
+ fontsize=8, rotation=0, ha="right", va="center")
167
+ axes[r, c].set_title(plane if r == 0 else "", fontsize=9)
168
+ fig.suptitle("TriFuse-AD Grad-CAM (shared CNN encoder, center slice per plane)")
169
+ fig.tight_layout()
170
+ out = FIGURES / "fig_gradcam_trifuse.png"
171
+ fig.savefig(out, dpi=150)
172
+ plt.close(fig)
173
+ print(f"wrote {out} ({len(correct)} correct + {len(wrong)} wrong cases)")
174
+
175
+
176
+ if __name__ == "__main__":
177
+ main()
scripts/make_tables.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Assemble the paper's result tables from results/<name>/ outputs.
2
+
3
+ Table 3: main comparison (mean±std over 15 runs + bootstrap CI on Macro-F1).
4
+ Table 3b: per-class F1 / recall.
5
+ Table 4: ablation (A1-A5 + full).
6
+ Significance: paired permutation test, TriFuse-AD vs best baseline, on per-run Macro-F1.
7
+
8
+ Outputs CSV + a markdown rendering under results/tables/.
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import sys
14
+ from pathlib import Path
15
+
16
+ import numpy as np
17
+ import pandas as pd
18
+
19
+ ROOT = Path(__file__).resolve().parents[1]
20
+ sys.path.insert(0, str(ROOT / "src"))
21
+ RESULTS = ROOT / "results"
22
+ TABLES = RESULTS / "tables"
23
+
24
+ from trifuse.eval.stats import paired_permutation_test # noqa: E402
25
+
26
+ # display order + grouping for the main table
27
+ MAIN_ORDER = [
28
+ ("Metadata", "xgboost", "XGBoost", "Tabular"),
29
+ ("Metadata", "tabular_mlp", "MLP", "Tabular"),
30
+ ("CNN", "resnet50", "ResNet50", "2D"),
31
+ ("CNN", "densenet2p5d", "DenseNet121", "2.5D"),
32
+ ("CNN", "resnet3d", "3D ResNet18", "3D"),
33
+ ("Transformer", "vit_b16", "ViT-B/16", "2.5D"),
34
+ ("Transformer", "swin3d", "3D Swin-T", "3D"),
35
+ ("Hybrid", "hcct", "3D HCCT", "3D"),
36
+ ("Hybrid", "vswin_lite", "CNN-VSwinFormer-lite", "3D"),
37
+ ("Multimodal", "densenet_latefusion", "DenseNet + concat", "MRI+tab"),
38
+ ("Proposed", "trifuse_ad", "TriFuse-AD", "MRI+tab"),
39
+ ]
40
+
41
+ METRIC_COLS = ["accuracy", "balanced_accuracy", "macro_precision",
42
+ "macro_recall", "macro_f1", "macro_auc"]
43
+ PERCLASS_COLS = ["f1_CN", "f1_VMD", "f1_AD", "recall_CN", "recall_VMD", "recall_AD"]
44
+
45
+
46
+ def _load(name):
47
+ p = RESULTS / name / "summary.json"
48
+ if not p.exists():
49
+ return None
50
+ return json.loads(p.read_text())
51
+
52
+
53
+ def _runs(name):
54
+ p = RESULTS / name / "runs.json"
55
+ return json.loads(p.read_text()) if p.exists() else None
56
+
57
+
58
+ def _fmt(summary, key):
59
+ s = summary["summary"].get(key)
60
+ if not s:
61
+ return "-"
62
+ return f"{s['mean']*100:.1f}±{s['std']*100:.1f}"
63
+
64
+
65
+ def build_main_table():
66
+ rows = []
67
+ for group, name, disp, inp in MAIN_ORDER:
68
+ s = _load(name)
69
+ if s is None:
70
+ rows.append({"Group": group, "Method": disp, "Input": inp,
71
+ **{c: "-" for c in METRIC_COLS}})
72
+ continue
73
+ row = {"Group": group, "Method": disp, "Input": inp}
74
+ for c in METRIC_COLS:
75
+ row[c] = _fmt(s, c)
76
+ ci = s.get("macro_f1_bootstrap", {})
77
+ row["macro_f1_CI"] = (f"[{ci['ci_lo']*100:.1f}, {ci['ci_hi']*100:.1f}]"
78
+ if ci else "-")
79
+ rows.append(row)
80
+ return pd.DataFrame(rows)
81
+
82
+
83
+ def build_perclass_table():
84
+ rows = []
85
+ for group, name, disp, inp in MAIN_ORDER:
86
+ s = _load(name)
87
+ if s is None:
88
+ continue
89
+ row = {"Method": disp}
90
+ for c in PERCLASS_COLS:
91
+ v = s["summary"].get(c)
92
+ row[c] = f"{v['mean']*100:.1f}±{v['std']*100:.1f}" if v else "-"
93
+ rows.append(row)
94
+ return pd.DataFrame(rows)
95
+
96
+
97
+ def build_ablation_table():
98
+ order = [
99
+ ("abl_A1_axial", "A1: axial-only"),
100
+ ("abl_A2_meanpool", "A2: mean-pool (no Transformer)"),
101
+ ("abl_A3_nometa", "A3: no metadata"),
102
+ ("abl_A4_concat", "A4: concat (no gate)"),
103
+ ("abl_A5_weightedce", "A5: weighted-CE"),
104
+ ("abl_full", "Full TriFuse-AD"),
105
+ ]
106
+ rows = []
107
+ for name, disp in order:
108
+ s = _load(name)
109
+ if s is None:
110
+ rows.append({"Variant": disp, "macro_f1": "-", "balanced_accuracy": "-", "f1_AD": "-"})
111
+ continue
112
+ rows.append({"Variant": disp, "macro_f1": _fmt(s, "macro_f1"),
113
+ "balanced_accuracy": _fmt(s, "balanced_accuracy"),
114
+ "f1_AD": _fmt(s, "f1_AD")})
115
+ return pd.DataFrame(rows)
116
+
117
+
118
+ def significance():
119
+ """Paired permutation test: TriFuse-AD vs best non-proposed baseline (per-run Macro-F1)."""
120
+ prop = _runs("trifuse_ad")
121
+ if prop is None:
122
+ return None
123
+ prop_f1 = [r["macro_f1"] for r in prop]
124
+ best_name, best_mean, best_f1 = None, -1, None
125
+ for _, name, _, _ in MAIN_ORDER:
126
+ if name == "trifuse_ad":
127
+ continue
128
+ r = _runs(name)
129
+ if r is None:
130
+ continue
131
+ f1 = [x["macro_f1"] for x in r]
132
+ if np.mean(f1) > best_mean:
133
+ best_mean, best_name, best_f1 = np.mean(f1), name, f1
134
+ if best_f1 is None:
135
+ return None
136
+ p = paired_permutation_test(prop_f1, best_f1)
137
+ return {"proposed_mean": float(np.mean(prop_f1)), "best_baseline": best_name,
138
+ "best_baseline_mean": float(best_mean),
139
+ "delta": float(np.mean(prop_f1) - best_mean), "p_value": p}
140
+
141
+
142
+ def main():
143
+ TABLES.mkdir(parents=True, exist_ok=True)
144
+ t3 = build_main_table()
145
+ t3b = build_perclass_table()
146
+ t4 = build_ablation_table()
147
+ t3.to_csv(TABLES / "table3_main.csv", index=False)
148
+ t3b.to_csv(TABLES / "table3b_perclass.csv", index=False)
149
+ t4.to_csv(TABLES / "table4_ablation.csv", index=False)
150
+
151
+ md = ["# Table 3 — Main comparison\n", t3.to_markdown(index=False),
152
+ "\n\n# Table 3b — Per-class F1 / Recall\n", t3b.to_markdown(index=False),
153
+ "\n\n# Table 4 — Ablation\n", t4.to_markdown(index=False)]
154
+ sig = significance()
155
+ if sig:
156
+ md.append(f"\n\n# Significance\nTriFuse-AD {sig['proposed_mean']*100:.1f} vs "
157
+ f"{sig['best_baseline']} {sig['best_baseline_mean']*100:.1f} "
158
+ f"(Δ={sig['delta']*100:+.1f}, permutation p={sig['p_value']:.4f})")
159
+ (TABLES / "significance.json").write_text(json.dumps(sig, indent=2))
160
+ (TABLES / "tables.md").write_text("\n".join(md))
161
+ print("\n".join(md))
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()
scripts/prepare_data.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """End-to-end data preparation: extract discs -> build cohort -> preprocess.
2
+
3
+ Usage:
4
+ python scripts/prepare_data.py --extract # extract all discs (idempotent)
5
+ python scripts/prepare_data.py --cohort # build subjects_clean.csv + stats
6
+ python scripts/prepare_data.py --preprocess # 3D volumes + 2.5D slices
7
+ python scripts/prepare_data.py --splits # repeated stratified folds
8
+ python scripts/prepare_data.py --all # everything in order
9
+ """
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ ROOT = Path(__file__).resolve().parents[1]
18
+ sys.path.insert(0, str(ROOT / "src"))
19
+
20
+ RAW = ROOT / "data" / "raw"
21
+ META = ROOT / "data" / "metadata"
22
+
23
+
24
+ def extract_discs() -> None:
25
+ """Extract every disc tarball into data/raw/ (skips already-extracted)."""
26
+ discs = sorted(RAW.glob("oasis_cross-sectional_disc*.tar.gz"))
27
+ if not discs:
28
+ sys.exit("no disc tarballs found in data/raw/")
29
+ for tgz in discs:
30
+ n = tgz.name.split("disc")[1].split(".")[0]
31
+ marker = RAW / f"disc{n}"
32
+ if marker.exists():
33
+ print(f"disc{n}: already extracted")
34
+ continue
35
+ print(f"disc{n}: verifying gzip ...", flush=True)
36
+ r = subprocess.run(["gzip", "-t", str(tgz)], capture_output=True)
37
+ if r.returncode != 0:
38
+ print(f" disc{n} CORRUPT: {r.stderr.decode()[:200]}", flush=True)
39
+ continue
40
+ print(f"disc{n}: extracting ...", flush=True)
41
+ subprocess.run(["tar", "xzf", str(tgz), "-C", str(RAW)], check=True)
42
+ print("extraction done")
43
+
44
+
45
+ def build_cohort() -> None:
46
+ from trifuse.data.cohort import build_cohort as _bc
47
+ _bc(RAW, META)
48
+
49
+
50
+ def preprocess() -> None:
51
+ from trifuse.data.preprocess_3d import run as run3d
52
+ from trifuse.data.preprocess_2d import run as run2d
53
+ csv = META / "subjects_clean.csv"
54
+ if not csv.exists():
55
+ sys.exit("run --cohort first (subjects_clean.csv missing)")
56
+ run3d(csv, ROOT / "data" / "processed_3d")
57
+ run2d(csv, ROOT / "data" / "processed_2d")
58
+
59
+
60
+ def make_splits() -> None:
61
+ import pandas as pd
62
+ from trifuse.data.splits import make_folds
63
+ csv = META / "subjects_clean.csv"
64
+ df = pd.read_csv(csv)
65
+ folds = make_folds(df)
66
+ out = META / "folds.csv"
67
+ folds.to_csv(out, index=False)
68
+ print(f"wrote {out} ({len(folds)} rows = {folds['seed'].nunique()} seeds x {len(df)} subjects)")
69
+
70
+
71
+ def main() -> None:
72
+ ap = argparse.ArgumentParser()
73
+ ap.add_argument("--extract", action="store_true")
74
+ ap.add_argument("--cohort", action="store_true")
75
+ ap.add_argument("--preprocess", action="store_true")
76
+ ap.add_argument("--splits", action="store_true")
77
+ ap.add_argument("--all", action="store_true")
78
+ a = ap.parse_args()
79
+ if a.all or a.extract:
80
+ extract_discs()
81
+ if a.all or a.cohort:
82
+ build_cohort()
83
+ if a.all or a.preprocess:
84
+ preprocess()
85
+ if a.all or a.splits:
86
+ make_splits()
87
+ if not any([a.extract, a.cohort, a.preprocess, a.splits, a.all]):
88
+ ap.print_help()
89
+
90
+
91
+ if __name__ == "__main__":
92
+ main()
scripts/run_experiments.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run the experiment grid: main models, ablation, or a named subset.
2
+
3
+ Usage:
4
+ python scripts/run_experiments.py --grid main # all 11 main configs
5
+ python scripts/run_experiments.py --grid ablation # A1-A5 + full
6
+ python scripts/run_experiments.py --only xgboost resnet50 # named subset
7
+ python scripts/run_experiments.py --grid main --device cuda
8
+
9
+ Each config runs the full 15-evaluation CV (3 seeds x 5 folds); OOF predictions and
10
+ per-run metrics land in results/<name>/. Idempotent: skips configs whose summary.json
11
+ already exists unless --force.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import argparse
16
+ import sys
17
+ import traceback
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ sys.path.insert(0, str(ROOT / "src"))
22
+
23
+ from trifuse.experiments import main_grid, ablation_grid
24
+ from trifuse.eval.runner import run_experiment, RESULTS
25
+
26
+
27
+ def main() -> None:
28
+ ap = argparse.ArgumentParser()
29
+ ap.add_argument("--grid", choices=["main", "ablation"], default=None)
30
+ ap.add_argument("--only", nargs="+", default=None, help="run only these config names")
31
+ ap.add_argument("--device", default="cuda")
32
+ ap.add_argument("--force", action="store_true", help="rerun even if summary.json exists")
33
+ a = ap.parse_args()
34
+
35
+ configs = []
36
+ if a.grid == "main":
37
+ configs += main_grid()
38
+ if a.grid == "ablation":
39
+ configs += ablation_grid()
40
+ if not a.grid:
41
+ configs = main_grid() + ablation_grid()
42
+ if a.only:
43
+ configs = [c for c in configs if c.name in set(a.only)]
44
+ if not configs:
45
+ sys.exit("no configs selected")
46
+
47
+ print(f"running {len(configs)} configs: {[c.name for c in configs]}", flush=True)
48
+ for cfg in configs:
49
+ done = (RESULTS / cfg.name / "summary.json").exists()
50
+ if done and not a.force:
51
+ print(f"[skip] {cfg.name} (summary.json exists)", flush=True)
52
+ continue
53
+ print(f"\n===== {cfg.name} ({cfg.model}, {cfg.modality}) =====", flush=True)
54
+ try:
55
+ run_experiment(cfg, device=a.device)
56
+ except Exception: # noqa: BLE001 - keep the grid going, log the failure
57
+ print(f"[FAIL] {cfg.name}:\n{traceback.format_exc()}", flush=True)
58
+
59
+
60
+ if __name__ == "__main__":
61
+ main()