"""Figure generation for the LNPBench manuscript. All five figures are produced from the CSV tables in ``results/`` (plus the saved per-sample predictions), so they can be regenerated without retraining. python scripts/make_figures.py --results results --outdir figures """ from __future__ import annotations import argparse import re from pathlib import Path import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd from scipy import stats mpl.rcParams.update({ "font.family": "DejaVu Sans", "font.size": 9, "axes.spines.top": False, "axes.spines.right": False, "axes.linewidth": 0.8, "figure.dpi": 120, "savefig.dpi": 300, "pdf.fonttype": 42, }) SHORT = { "physset_phys": "PhysSet-LNP (ours)", "phcausal_phys": "PhyCausal-LNP (ours)", "probe_flat_rank": "Identity-free probe (ours)", "seqcausal": "SeqCausal-LNP (ours)", "randomforest": "Random forest", "extratrees": "Extra trees", "xgboost": "XGBoost", "agile": "AGILE", "lion": "LiON", "mlp_fp": "Morgan + MLP", } FAMILY_COLOR = { "neural": "#4C72B0", "tree": "#DD8452", "ours": "#55A868", "stack": "#C44E52", } STUDIES = ["LM_2019", "BL_2023", "SL_2020", "ZC_2023"] PATTERN = re.compile(r"(?P.+?)__(?P.+?)__s(?P\d+)\.npz$") def _save(fig, outdir: Path, name: str): outdir.mkdir(parents=True, exist_ok=True) fig.savefig(outdir / f"{name}.png", bbox_inches="tight") fig.savefig(outdir / f"{name}.pdf", bbox_inches="tight") plt.close(fig) print(f" wrote {name}.png/.pdf") def fig_main(models: pd.DataFrame, ens: pd.DataFrame, outdir: Path): """Horizontal bar chart: every single model plus the declared stack.""" # prefer the seed-averaged score (the deployed estimator); fall back to the # per-seed mean for models without saved predictions if ens is not None: se = ens[ens.group.str.startswith("single:")].copy() se["model"] = se.group.str.replace("single:", "", regex=False) agg = se.groupby("model").spearman.agg(["size", "mean", "std"]) else: t = (models[models.spearman.notna()] .groupby(["model", "task"], as_index=False).spearman.mean()) agg = t.groupby("model").spearman.agg(["size", "mean", "std"]) singles = [m for m in SHORT if m in agg.index and agg.loc[m, "size"] >= 8] singles = sorted(singles, key=lambda m: agg.loc[m, "mean"]) labels = [SHORT[m] for m in singles] vals = [agg.loc[m, "mean"] for m in singles] errs = [agg.loc[m, "std"] for m in singles] colors = [FAMILY_COLOR["ours"] if "(ours)" in SHORT[m] else FAMILY_COLOR["tree"] if m in ("randomforest", "extratrees", "xgboost") else FAMILY_COLOR["neural"] for m in singles] if ens is not None and "LNPBench-Stack" in set(ens.group): s = ens[ens.group == "LNPBench-Stack"].spearman singles.append("stack") labels.append("LNPBench-Stack") vals.append(s.mean()) errs.append(s.std()) colors.append(FAMILY_COLOR["stack"]) fig, ax = plt.subplots(figsize=(4.6, 0.34 * len(labels) + 1.0)) y = np.arange(len(labels)) ax.barh(y, vals, xerr=errs, color=colors, edgecolor="white", error_kw=dict(lw=0.8, capsize=2, ecolor="#444444")) ax.set_yticks(y, labels) ax.set_xlabel("Spearman on the held-out study (mean over the external tasks)") ax.axvline(0, color="black", lw=0.6) for yi, v in zip(y, vals): ax.text(v + 0.004, yi, f"{v:.3f}", va="center", fontsize=7.5) ax.set_xlim(min(0, min(vals)) - 0.02, max(vals) + max(errs) + 0.03) handles = [mpl.patches.Patch(color=FAMILY_COLOR[k], label=v) for k, v in [("ours", "proposed"), ("tree", "tree ensembles"), ("neural", "neural baselines"), ("stack", "stack")]] ax.legend(handles=handles, frameon=False, fontsize=7, ncol=4, loc="upper center", bbox_to_anchor=(0.45, -0.14)) _save(fig, outdir, "fig1_models") def fig_per_study(models: pd.DataFrame, ens: pd.DataFrame, outdir: Path): keep = ["physset_phys", "agile", "lion", "randomforest", "extratrees", "xgboost"] if ens is not None: se = ens[ens.group.str.startswith("single:")].copy() se["model"] = se.group.str.replace("single:", "", regex=False) se["study"] = se.task.str.extract(r"^([A-Z]{2}_\d{4})")[0] piv = (se.groupby(["model", "study"]).spearman.mean().unstack() .reindex(columns=STUDIES)) else: t = (models[models.spearman.notna()] .groupby(["model", "study"], as_index=False).spearman.mean()) piv = t.pivot(index="model", columns="study", values="spearman").reindex(columns=STUDIES) TREE_COLOR = {"randomforest": "#DD8452", "extratrees": "#E9B48C", "xgboost": "#8C510A"} rows = [(SHORT[m], piv.loc[m], FAMILY_COLOR["ours"] if m == "physset_phys" else TREE_COLOR[m] if m in TREE_COLOR else FAMILY_COLOR["neural"]) for m in keep if m in piv.index] if ens is not None and "LNPBench-Stack" in set(ens.group): e = ens[ens.group == "LNPBench-Stack"].copy() e["study"] = e.task.str.extract(r"^([A-Z]{2}_\d{4})")[0] rows.append(("LNPBench-Stack", e.groupby("study").spearman.mean().reindex(STUDIES), FAMILY_COLOR["stack"])) fig, ax = plt.subplots(figsize=(6.0, 2.9)) n = len(rows) w = 0.82 / n x = np.arange(len(STUDIES)) for i, (lab, vals, c) in enumerate(rows): ax.bar(x + (i - (n - 1) / 2) * w, vals.values, width=w, label=lab, color=c, edgecolor="white", lw=0.5) ax.set_xticks(x, STUDIES) ax.set_ylabel("Spearman") ax.axhline(0, color="black", lw=0.6) ax.legend(frameon=False, fontsize=7, ncol=4, loc="upper left", bbox_to_anchor=(0, 1.18)) ax.set_ylim(-0.1, 0.85) _save(fig, outdir, "fig2_per_study") def fig_identity(models: pd.DataFrame, ablation: pd.DataFrame, ladder: pd.DataFrame, outdir: Path): """The identity-shortcut figure: what each added ingredient costs on transfer.""" fig, axes = plt.subplots(1, 2, figsize=(7.2, 2.9), gridspec_kw={"width_ratios": [1, 1]}) ax = axes[0] lab, val = [], [] if ladder is not None: for m, name in [("probe_flat", "flat, chem only"), ("probe_set", "+ formulation set"), ("probe_set_bias", "+ physics bias"), ("probe_physset_rank", "+ set + bias + rank")]: if m in set(ladder.model): lab.append(name) val.append(ladder[ladder.model == m].spearman.mean()) if lab: ax.bar(range(len(lab)), val, color="#8172B3", edgecolor="white") ax.set_xticks(range(len(lab)), lab, rotation=25, ha="right", fontsize=7) ax.axhline(0, color="black", lw=0.6) ax.set_ylabel("Spearman (2 held-out studies)") ax.set_title("isolating the set encoder", fontsize=8.5) ax = axes[1] # the ablations were all run at seed 0, fold 0, so the reference must be too base = models[(models.model == "physset_phys") & (models.fold == 0) & (models.seed == 0)] rows = [("full model", base.spearman.mean()), ] if ablation is not None: for m, name in [("physset_phys_norank", "w/o rank loss"), ("physset_phys_nophys", "w/o physics bias"), ("physset_phys_fp", "fingerprint nodes\n(study identity)")]: if m in set(ablation.model): rows.append((name, ablation[ablation.model == m].spearman.mean())) colors = ["#55A868"] + ["#999999"] * (len(rows) - 2) + ["#C44E52"] * (len(rows) > 1) ax.bar(range(len(rows)), [r[1] for r in rows], color=colors[:len(rows)], edgecolor="white") ax.set_xticks(range(len(rows)), [r[0] for r in rows], rotation=25, ha="right", fontsize=7) ax.axhline(0, color="black", lw=0.6) ax.set_title("ablations of the final model", fontsize=8.5) for i, r in enumerate(rows): ax.text(i, r[1] + 0.01, f"{r[1]:.3f}", ha="center", fontsize=7) _save(fig, outdir, "fig3_identity_shortcut") def fig_scatter(pred_dirs, outdir: Path, model: str = "physset_phys"): """Predicted vs measured, one panel per held-out study, seed-averaged.""" table: dict = {} for d in pred_dirs: p = Path(d) if not p.exists(): continue for f in sorted(p.glob(f"{model}__*.npz")): m = PATTERN.match(f.name) if not m: continue z = np.load(f) table.setdefault(m["task"], []).append((z["y"], z["pred"])) if not table: print(" (no predictions found, skipping scatter)") return fig, axes = plt.subplots(1, 4, figsize=(8.4, 2.3)) for ax, study in zip(axes, STUDIES): ys, ps, per_fold = [], [], [] for task, lst in table.items(): if not task.startswith(study): continue y = lst[0][0] pred = np.mean([stats.rankdata(p) / len(p) for _, p in lst], axis=0) per_fold.append(stats.spearmanr(y, pred).statistic) ys.append(y) ps.append(pred) if not ys: ax.set_visible(False) continue y = np.concatenate(ys) pr = np.concatenate(ps) bins = np.linspace(pr.min(), pr.max(), 26) idx = np.clip(np.digitize(pr, bins) - 1, 0, len(bins) - 2) mw = np.array([y[idx == b].mean() if (idx == b).any() else np.nan for b in range(len(bins) - 1)]) ax.scatter(pr, y, s=3, alpha=0.18, color="#4C72B0", linewidths=0) ax.plot((bins[:-1] + bins[1:]) / 2, mw, color="#C44E52", lw=1.4) rho = float(np.mean(per_fold)) ax.set_title(f"{study} $\\rho$={rho:.2f}", fontsize=8.5) ax.set_xlabel("predicted (rank)") ax.set_ylim(np.percentile(y, 0.5), np.percentile(y, 99.5)) axes[0].set_ylabel("measured delivery") fig.tight_layout() _save(fig, outdir, "fig4_calibration") def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--results", default="results") ap.add_argument("--pred-dirs", nargs="+", default=["results_gpu/pred_gpu", "results_gpu/pred_cpu"]) ap.add_argument("--outdir", default="figures") args = ap.parse_args() R = Path(args.results) outdir = Path(args.outdir) def read(n): p = R / n return pd.read_csv(p) if p.exists() else None models = read("benchmark_models.csv") classical = read("benchmark_classical.csv") if models is not None and classical is not None: models = pd.concat([models[models.protocol == "external"], classical[classical.protocol == "external"]], ignore_index=True) ens = read("ensemble.csv") abl = read("benchmark_ablation.csv") ladder = read("diagnosis_ladder.csv") print("figures:") fig_main(models, ens, outdir) fig_per_study(models, ens, outdir) fig_identity(models, abl, ladder, outdir) fig_scatter(args.pred_dirs, outdir) if __name__ == "__main__": main()