"""Assemble the paper's result tables from results// outputs. Table 3: main comparison (mean±std over 15 runs + bootstrap CI on Macro-F1). Table 3b: per-class F1 / recall. Table 4: ablation (A1-A5 + full). Significance: paired permutation test, TriFuse-AD vs best baseline, on per-run Macro-F1. Outputs CSV + a markdown rendering under results/tables/. """ from __future__ import annotations import json import sys from pathlib import Path import numpy as np import pandas as pd ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "src")) RESULTS = ROOT / "results" TABLES = RESULTS / "tables" from trifuse.eval.stats import paired_permutation_test # noqa: E402 # display order + grouping for the main table MAIN_ORDER = [ ("Metadata", "xgboost", "XGBoost", "Tabular"), ("Metadata", "tabular_mlp", "MLP", "Tabular"), ("CNN", "resnet50", "ResNet50", "2D"), ("CNN", "densenet2p5d", "DenseNet121", "2.5D"), ("CNN", "resnet3d", "3D ResNet18", "3D"), ("Transformer", "vit_b16", "ViT-B/16", "2.5D"), ("Transformer", "swin3d", "3D Swin-T", "3D"), ("Hybrid", "hcct", "3D HCCT", "3D"), ("Hybrid", "vswin_lite", "CNN-VSwinFormer-lite", "3D"), ("Multimodal", "densenet_latefusion", "DenseNet + concat", "MRI+tab"), ("Proposed", "trifuse_ad", "TriFuse-AD", "MRI+tab"), ] METRIC_COLS = ["accuracy", "balanced_accuracy", "macro_precision", "macro_recall", "macro_f1", "macro_auc"] PERCLASS_COLS = ["f1_CN", "f1_VMD", "f1_AD", "recall_CN", "recall_VMD", "recall_AD"] def _load(name): p = RESULTS / name / "summary.json" if not p.exists(): return None return json.loads(p.read_text()) def _runs(name): p = RESULTS / name / "runs.json" return json.loads(p.read_text()) if p.exists() else None def _fmt(summary, key): s = summary["summary"].get(key) if not s: return "-" return f"{s['mean']*100:.1f}±{s['std']*100:.1f}" def build_main_table(): rows = [] for group, name, disp, inp in MAIN_ORDER: s = _load(name) if s is None: rows.append({"Group": group, "Method": disp, "Input": inp, **{c: "-" for c in METRIC_COLS}}) continue row = {"Group": group, "Method": disp, "Input": inp} for c in METRIC_COLS: row[c] = _fmt(s, c) ci = s.get("macro_f1_bootstrap", {}) row["macro_f1_CI"] = (f"[{ci['ci_lo']*100:.1f}, {ci['ci_hi']*100:.1f}]" if ci else "-") rows.append(row) return pd.DataFrame(rows) def build_perclass_table(): rows = [] for group, name, disp, inp in MAIN_ORDER: s = _load(name) if s is None: continue row = {"Method": disp} for c in PERCLASS_COLS: v = s["summary"].get(c) row[c] = f"{v['mean']*100:.1f}±{v['std']*100:.1f}" if v else "-" rows.append(row) return pd.DataFrame(rows) def build_ablation_table(): order = [ ("abl_A1_axial", "A1: axial-only"), ("abl_A2_meanpool", "A2: mean-pool (no Transformer)"), ("abl_A3_nometa", "A3: no metadata"), ("abl_A4_concat", "A4: concat (no gate)"), ("abl_A5_weightedce", "A5: weighted-CE"), ("abl_full", "Full TriFuse-AD"), ] rows = [] for name, disp in order: s = _load(name) if s is None: rows.append({"Variant": disp, "macro_f1": "-", "balanced_accuracy": "-", "f1_AD": "-"}) continue rows.append({"Variant": disp, "macro_f1": _fmt(s, "macro_f1"), "balanced_accuracy": _fmt(s, "balanced_accuracy"), "f1_AD": _fmt(s, "f1_AD")}) return pd.DataFrame(rows) def significance(): """Paired permutation test: TriFuse-AD vs best non-proposed baseline (per-run Macro-F1).""" prop = _runs("trifuse_ad") if prop is None: return None prop_f1 = [r["macro_f1"] for r in prop] best_name, best_mean, best_f1 = None, -1, None for _, name, _, _ in MAIN_ORDER: if name == "trifuse_ad": continue r = _runs(name) if r is None: continue f1 = [x["macro_f1"] for x in r] if np.mean(f1) > best_mean: best_mean, best_name, best_f1 = np.mean(f1), name, f1 if best_f1 is None: return None p = paired_permutation_test(prop_f1, best_f1) return {"proposed_mean": float(np.mean(prop_f1)), "best_baseline": best_name, "best_baseline_mean": float(best_mean), "delta": float(np.mean(prop_f1) - best_mean), "p_value": p} def main(): TABLES.mkdir(parents=True, exist_ok=True) t3 = build_main_table() t3b = build_perclass_table() t4 = build_ablation_table() t3.to_csv(TABLES / "table3_main.csv", index=False) t3b.to_csv(TABLES / "table3b_perclass.csv", index=False) t4.to_csv(TABLES / "table4_ablation.csv", index=False) md = ["# Table 3 — Main comparison\n", t3.to_markdown(index=False), "\n\n# Table 3b — Per-class F1 / Recall\n", t3b.to_markdown(index=False), "\n\n# Table 4 — Ablation\n", t4.to_markdown(index=False)] sig = significance() if sig: md.append(f"\n\n# Significance\nTriFuse-AD {sig['proposed_mean']*100:.1f} vs " f"{sig['best_baseline']} {sig['best_baseline_mean']*100:.1f} " f"(Δ={sig['delta']*100:+.1f}, permutation p={sig['p_value']:.4f})") (TABLES / "significance.json").write_text(json.dumps(sig, indent=2)) (TABLES / "tables.md").write_text("\n".join(md)) print("\n".join(md)) if __name__ == "__main__": main()