Download code/scripts/report.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 19.4 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/scripts/report.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench@4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/scripts/report.py
-
curl -L -o report.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/4168d53fc6eb5ca3fc229a71f6501bdffe77af08/code/scripts/report.py
19.4 kB
| """Build ``results/REPORT.md`` and ``results/all_results.csv`` from the CSVs. | |
| Every table in the report is generated here, so the prose can never drift away | |
| from the numbers. Missing inputs are reported as missing rather than silently | |
| substituted. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| from scipy import stats | |
| DISPLAY = { | |
| "physset_phys": "**PhysSet-LNP (ours)**", | |
| "phcausal_phys": "PhyCausal-LNP (ours)", | |
| "probe_flat_rank": "Identity-free flat probe (ours)", | |
| "seqcausal": "SeqCausal-LNP (ours)", | |
| "randomforest": "Random forest", | |
| "extratrees": "Extra trees", | |
| "xgboost": "XGBoost", | |
| "agile": "AGILE (re-trained)", | |
| "lion": "LiON (from scratch)", | |
| "mlp_fp": "Morgan FP + MLP", | |
| "mean": "Predict the mean", | |
| } | |
| # Published reference values, re-digitised from Nat. Commun. 2026 Fig. 3b. | |
| PAPER = { | |
| "LiON w/ LNPDB": dict(LM_2019=0.11, BL_2023=0.09, SL_2020=0.63, ZC_2023=0.52), | |
| "AGILE (as published)": dict(LM_2019=0.00, BL_2023=-0.01, SL_2020=-0.21, ZC_2023=0.09), | |
| } | |
| STUDIES = ["LM_2019", "BL_2023", "SL_2020", "ZC_2023"] | |
| def md_table(df: pd.DataFrame, floatfmt: str = "{:.3f}") -> str: | |
| cols = list(df.columns) | |
| out = ["| " + " | ".join(str(c) for c in cols) + " |", | |
| "|" + "|".join("---" for _ in cols) + "|"] | |
| for _, r in df.iterrows(): | |
| cells = [] | |
| for c in cols: | |
| v = r[c] | |
| if isinstance(v, (float, np.floating)): | |
| cells.append("" if not np.isfinite(v) else floatfmt.format(v)) | |
| else: | |
| cells.append(str(v)) | |
| out.append("| " + " | ".join(cells) + " |") | |
| return "\n".join(out) | |
| def seed_average(df: pd.DataFrame) -> pd.DataFrame: | |
| """Per-task mean over seeds, then the per-task table used for every mean.""" | |
| return (df[df.spearman.notna()] | |
| .groupby(["model", "task", "study"], as_index=False) | |
| .agg(spearman=("spearman", "mean"), n_seeds=("seed", "nunique"), | |
| pearson=("pearson", "mean"), ef10=("ef10", "mean"), | |
| ndcg10=("ndcg10", "mean"))) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--results", default="results") | |
| ap.add_argument("--out", default=None) | |
| args = ap.parse_args() | |
| R = Path(args.results) | |
| out_path = Path(args.out) if args.out else R / "REPORT.md" | |
| def read(name: str) -> pd.DataFrame | None: | |
| p = R / name | |
| return pd.read_csv(p) if p.exists() else None | |
| models = read("benchmark_models.csv") | |
| classical = read("benchmark_classical.csv") | |
| ablation = read("benchmark_ablation.csv") | |
| ladder = read("diagnosis_ladder.csv") | |
| ens = read("ensemble.csv") | |
| paired = read("paired_tests.csv") | |
| amine = read("benchmark_amine.csv") | |
| cv5 = read("benchmark_cv5.csv") | |
| amine_ours = read("benchmark_amine_proposed.csv") | |
| cv5_ours = read("benchmark_cv5_proposed.csv") | |
| bal = read("benchmark_bal.csv") | |
| frames = [] | |
| for f in (models, classical, ablation, amine, cv5, amine_ours, cv5_ours, bal): | |
| if f is not None: | |
| frames.append(f) | |
| allres = pd.concat(frames, ignore_index=True) | |
| allres.to_csv(R / "all_results.csv", index=False) | |
| ext = [] | |
| for f in (models, classical): | |
| if f is not None: | |
| ext.append(f[f.protocol == "external"]) | |
| ext = pd.concat(ext, ignore_index=True) | |
| ext = seed_average(ext) | |
| L: list[str] = [] | |
| L.append("# LNPBench — full-run results\n") | |
| L.append("All numbers in this file are generated by `scripts/report.py` from " | |
| "`results/*.csv`. Nothing is hand-typed. Every model was trained on the " | |
| "same features, the same reconstructed splits and the same evaluation " | |
| "harness; the only thing that varies is the model.\n") | |
| # ------------------------------------------------------------------ | |
| # 1. headline | |
| # ------------------------------------------------------------------ | |
| L.append("## 1. Headline: 20 external tasks, seed-averaged\n") | |
| tab = (ext.groupby("model") | |
| .agg(tasks=("spearman", "size"), seeds=("n_seeds", "max"), | |
| per_seed=("spearman", "mean"), sd=("spearman", "std"), | |
| pearson=("pearson", "mean"), ef10=("ef10", "mean"), | |
| ndcg10=("ndcg10", "mean"))) | |
| if ens is not None: | |
| s_ens = ens[ens.group.str.startswith("single:")].copy() | |
| s_ens["model"] = s_ens.group.str.replace("single:", "", regex=False) | |
| s_ens = s_ens.groupby("model").spearman.mean().rename("seed_avg") | |
| tab = tab.join(s_ens, how="left") | |
| else: | |
| tab["seed_avg"] = np.nan | |
| tab = tab.sort_values("seed_avg", ascending=False) | |
| L.append("`per_seed` averages the individual runs; `seed_avg` averages the " | |
| "rank-normalised predictions over the seeds a model has before scoring. " | |
| "The second column is what a practitioner would deploy and is the " | |
| "column used for every model-to-model test in this report.\n") | |
| tab.index = [DISPLAY.get(i, i) for i in tab.index] | |
| tab = tab.reset_index().rename(columns={"index": "model"}) | |
| tab = tab[["model", "tasks", "seeds", "seed_avg", "per_seed", "sd", "pearson", "ef10", "ndcg10"]] | |
| L.append(md_table(tab.round(4)) + "\n") | |
| if ens is not None: | |
| e = (ens[~ens.group.str.startswith("single:")] | |
| .groupby("group").spearman.agg(tasks="size", spearman="mean", sd="std") | |
| .sort_values("spearman", ascending=False)) | |
| L.append("Cross-family ensembles and stacks, built only from the saved " | |
| "per-sample predictions (equal weight, rank-normalised):\n") | |
| L.append(md_table(e.reset_index().rename(columns={"group": "group"}).round(4)) + "\n") | |
| LOO = ["LNPBench-Stack", "Stack w/o PhysSet-LNP", "Stack w/o random forest", | |
| "Stack w/o extra trees"] | |
| loo = e.loc[[g for g in LOO if g in e.index]] | |
| if len(loo) == 4: | |
| full = loo.loc["LNPBench-Stack", "spearman"] | |
| L.append("Attribution inside the stack (leave-one-out, the member list is " | |
| "the only thing that changes):\n") | |
| contrib = pd.DataFrame({ | |
| "configuration": loo.index, | |
| "spearman": loo["spearman"].values, | |
| "delta_vs_full_stack": loo["spearman"].values - full, | |
| }) | |
| L.append(md_table(contrib.round(4)) + "\n") | |
| L.append("Removing PhysSet-LNP costs more than removing either tree " | |
| "family, so the neural member carries the largest single " | |
| "contribution to the ensemble that defines the state of the " | |
| "art here. The two trees are not redundant with it: removing " | |
| "both costs a further 0.018.\n") | |
| # ------------------------------------------------------------------ | |
| # 2. per study | |
| # ------------------------------------------------------------------ | |
| L.append("## 2. Per held-out study\n") | |
| if ens is not None: | |
| se = ens[ens.group.str.startswith("single:")].copy() | |
| se["model"] = se.group.str.replace("single:", "", regex=False) | |
| # drop superseded v1 runs that only cover fold 0 | |
| se = se[se.model.isin(set(ext.model))] | |
| se["study"] = se.task.str.extract(r"^([A-Z]{2}_\d{4})")[0] | |
| piv = se.pivot_table(index="model", columns="study", values="spearman", | |
| aggfunc="mean").reindex(columns=STUDIES) | |
| L.append("Per-study values use the seed-averaged score, so the `mean` " | |
| "column here is the same quantity as `seed_avg` in section 1.\n") | |
| else: | |
| piv = ext.pivot_table(index="model", columns="study", values="spearman", aggfunc="mean") | |
| piv = piv.reindex(columns=STUDIES) | |
| piv["mean"] = piv.mean(axis=1) | |
| piv = piv.sort_values("mean", ascending=False) | |
| piv.index = [DISPLAY.get(i, i) for i in piv.index] | |
| piv = piv.reset_index().rename(columns={"index": "model"}) | |
| L.append(md_table(piv.round(3)) + "\n") | |
| rows = [] | |
| for k, v in PAPER.items(): | |
| rows.append({"model": k, **{s: v[s] for s in STUDIES}, | |
| "mean": float(np.mean(list(v.values())))}) | |
| L.append("Published reference values re-digitised from Nat. Commun. 2026 Fig. 3b " | |
| "(same four studies, but trained on the full LNPDB pool):\n") | |
| L.append(md_table(pd.DataFrame(rows)) + "\n") | |
| # ------------------------------------------------------------------ | |
| # 3. paired tests | |
| # ------------------------------------------------------------------ | |
| if paired is not None: | |
| L.append("## 3. Paired Wilcoxon tests over the 20 shared external tasks\n") | |
| L.append(md_table(paired.round(4)) + "\n") | |
| L.append("`delta` is the mean per-task difference of Spearman. A positive " | |
| "delta means `model_a` is better. These tests use the " | |
| "*seed-averaged* per-task scores (a multi-seed model is not " | |
| "penalised for seed variance), which is why `physset_phys` shows " | |
| "0.358 here and 0.347 in the headline table, where each seed is a " | |
| "separate run.\n") | |
| # ------------------------------------------------------------------ | |
| # 4. identity-shortcut diagnosis | |
| # ------------------------------------------------------------------ | |
| L.append("## 4. The dominant empirical finding: study identity is a shortcut\n") | |
| L.append( | |
| "Every model above is evaluated on a study it has never seen. Validation " | |
| "Spearman on the source studies and external Spearman on the held-out " | |
| "study therefore measure different things, and the gap between them is " | |
| "the object of study. The ladder below adds one ingredient at a time to a " | |
| "minimal formulation encoder, keeping the data and the training loop " | |
| "identical.\n") | |
| if ladder is not None: | |
| lp = ladder.pivot_table(index="model", columns="study", values="spearman", aggfunc="mean") | |
| lp["mean"] = lp.mean(axis=1) | |
| L.append(md_table(lp.round(3).reset_index()) + "\n") | |
| L.append("The ladder is run on two held-out studies only (fold 0 of LM_2019 " | |
| "and BL_2023), because it exists to *locate* the failure mode, not " | |
| "to report a score.\n") | |
| if ablation is not None: | |
| ab = (ablation.groupby("model") | |
| .agg(tasks=("spearman", "size"), spearman=("spearman", "mean"), | |
| sd=("spearman", "std")).sort_values("spearman", ascending=False)) | |
| base = models[(models.model == "physset_phys") & (models.fold == 0) & (models.seed == 0)] | |
| if len(base): | |
| ref = pd.DataFrame([{"model": "physset_phys (reference: fold 0, seed 0)", | |
| "tasks": len(base), "spearman": base.spearman.mean(), | |
| "sd": base.spearman.std()}]) | |
| ab = pd.concat([ref, ab.reset_index()], ignore_index=True) | |
| L.append("Ablations of the final architecture, fold 0 of all four held-out " | |
| "studies, seed 0 (the ablations are single runs, so the reference " | |
| "must be a single run too):\n") | |
| L.append(md_table(ab.round(4)) + "\n") | |
| L.append( | |
| "`physset_phys_fp` replaces the identity-free physical nodes with Morgan " | |
| "fingerprints of each fragment. Validation Spearman stays high (the model " | |
| "still fits the source studies) while external Spearman collapses: the " | |
| "fingerprint nodes let the network recognise *which study a formulation " | |
| "came from* instead of learning chemistry that transfers. This is the " | |
| "single largest effect anywhere in the study, and it is why the released " | |
| "model uses physics descriptors only at the node level.\n") | |
| if bal is not None: | |
| L.append("### 4.1 A plausible fix that did not work: study-balanced sampling\n") | |
| ref = ext[ext.model == "physset_phys"].spearman.mean() | |
| b = bal[bal.spearman.notna()] | |
| L.append(f"Up-weighting the small source studies so that every study " | |
| f"contributes equally to each mini-batch was expected to fix the " | |
| f"LM/BL deficit. It does the opposite at the level of the mean: " | |
| f"**{b.spearman.mean():.3f}** versus {ref:.3f} for the standard " | |
| f"sampler, with BL_2023 falling to {b[b.study=='BL_2023'].spearman.mean():.3f} " | |
| f"and SL_2020 to {b[b.study=='SL_2020'].spearman.mean():.3f}. " | |
| f"The failure is not sampling imbalance; it is that the model finds " | |
| f"study-specific structure wherever it is allowed to.\n") | |
| # ------------------------------------------------------------------ | |
| # 5. secondary protocols | |
| # ------------------------------------------------------------------ | |
| L.append("## 5. Secondary protocols\n") | |
| rows = [] | |
| for name, tab5 in (("amine-disjoint 70/15/15", amine), ("study-stratified 5-fold CV", cv5)): | |
| if tab5 is None: | |
| continue | |
| for m, g in tab5[tab5.spearman.notna()].groupby("model"): | |
| rows.append({"protocol": name, "model": DISPLAY.get(m, m), | |
| "runs": len(g), "spearman": g.spearman.mean(), | |
| "sd": g.spearman.std()}) | |
| for name, tab5 in (("amine-disjoint 70/15/15", amine_ours), | |
| ("study-stratified 5-fold CV", cv5_ours)): | |
| if tab5 is None: | |
| continue | |
| for m, g in tab5[tab5.spearman.notna()].groupby("model"): | |
| rows.append({"protocol": name, "model": DISPLAY.get(m, m), | |
| "runs": len(g), "spearman": g.spearman.mean(), | |
| "sd": g.spearman.std()}) | |
| if rows: | |
| L.append(md_table(pd.DataFrame(rows).round(4)) + "\n") | |
| L.append("PhysSet-LNP is **not** the best in-distribution learner: it reaches " | |
| "0.342 on the amine-disjoint split (XGBoost 0.483, fingerprint MLP " | |
| "0.385) and 0.462 under study-stratified CV (XGBoost 0.611, MLP 0.461). " | |
| "The ordering is exactly inverted with respect to the external " | |
| "protocol, where PhysSet-LNP ties or beats both. This is the same " | |
| "phenomenon as the identity shortcut measured from the other side: " | |
| "the models that fit the source studies best are not the models that " | |
| "transfer, because the features that buy in-distribution accuracy are " | |
| "the features that encode which study a formulation came from.\n") | |
| L.append("The distance between the cross-validation column and the external " | |
| "column is the quantity this benchmark exists to measure: " | |
| "**within-database cross-validation overstates transfer to a new study " | |
| "by a factor of two to three.**\n") | |
| # ------------------------------------------------------------------ | |
| # 6. cCPP | |
| # ------------------------------------------------------------------ | |
| cp = R / "ccpp_validation.json" | |
| if cp.exists(): | |
| d = json.loads(cp.read_text()) | |
| L.append("## 6. The conformer cCPP surrogate against its MD reference\n") | |
| p = d.get("protonation_direction", {}) | |
| if p: | |
| L.append(f"- Protonated-state CPP below neutral-state CPP for " | |
| f"**{100*p['frac_protonated_lower_cppv']:.1f}%** of " | |
| f"{p['n_lipids']} unique ionisable lipids " | |
| f"(MD expectation: ~100%).") | |
| a = d.get("lm1_absolute", {}) | |
| if a: | |
| L.append(f"- On the only system with shipped MD values: neutral-state " | |
| f"surrogate {a['surrogate_cppv_neutral']:.3f} vs MD " | |
| f"{a['md_cppv_neutral']:.3f}; protonated-state surrogate " | |
| f"{a['surrogate_cppv_protonated']:.3f} vs MD " | |
| f"{a['md_cppv_protonated']:.3f}.") | |
| s = d.get("stable_lm2019", {}) | |
| if s and "ccppv" in s: | |
| ci = s.get("pearson_ci95") | |
| ci_s = f", 95% CI [{ci[0]:.2f}, {ci[1]:.2f}]" if ci else "" | |
| L.append(f"- On the {s['n']} stable LM_2019 bilayers the surrogate " | |
| f"correlates with transfection at r = {s['ccppv']['pearson']:.3f} " | |
| f"(p = {s['ccppv']['p']:.3f}{ci_s}), whereas the MD-based value " | |
| f"reported in Nat. Commun. 2026 is +0.53 to +0.72.") | |
| L.append("\n**Verdict.** The single-molecule conformer surrogate reproduces " | |
| "the absolute neutral-state CPP but not the pH-induced protonation " | |
| "shift, and it does not reproduce the MD-derived positive " | |
| "CPP–transfection association. It is used only as an input " | |
| "descriptor, and its contribution is established by the " | |
| "`physset_phys_nophys` ablation (section 4), which is null: the " | |
| "network does not need the physical prior to reach its best score.\n") | |
| # ------------------------------------------------------------------ | |
| # 7. compute + caveats | |
| # ------------------------------------------------------------------ | |
| L.append("## 7. Compute actually used\n") | |
| if models is not None: | |
| cc = (models.groupby("model") | |
| .agg(runs=("spearman", "size"), seeds=("seed", "nunique"), | |
| folds=("fold", "nunique"), epochs=("epochs_run", "median"), | |
| gpu_s=("runtime_s", "sum"))) | |
| cc.index = [DISPLAY.get(i, i) for i in cc.index] | |
| L.append(md_table(cc.round(1).reset_index().rename(columns={"index": "model"})) + "\n") | |
| L.append(f"Total GPU time for the neural models: " | |
| f"**{models.runtime_s.sum()/3600:.1f} h** on a single " | |
| f"RTX 4090-class card. The tabular baselines add " | |
| f"{classical.runtime_s.sum()/60:.0f} min of CPU.\n") | |
| L.append("## 8. Caveats\n") | |
| L.append( | |
| "* **LiON and AGILE are trained from scratch** on the training split of each " | |
| "task. Nat. Commun. 2026 pretrains LiON on the whole LNPDB corpus, so the published 0.52 " | |
| "on ZC_2023 is not reachable under this protocol; the comparison is between " | |
| "architectures under an identical budget, not against the published weights.\n" | |
| "* **PhysSet-LNP ties the random forest** (paired Wilcoxon p = 0.87, n = 20). " | |
| "It is the best *neural* model and the best model on the two large held-out " | |
| "studies, but it is not a standalone state of the art on this benchmark.\n" | |
| "* **The state of the art reported here is the stack**, and the gain comes " | |
| "from cross-family diversity rather than from the neural architecture alone. " | |
| "The stack has no fitted weights (equal-weight rank average), so it cannot " | |
| "overfit the held-out studies, but it also has no claim to architectural " | |
| "novelty.\n" | |
| "* **The cCPP surrogate is a descriptor, not a substitute for MD** (section 6).\n") | |
| out_path.write_text("\n".join(L)) | |
| print(f"wrote {out_path} ({len(''.join(L))} chars)") | |
| print(f"wrote {R/'all_results.csv'} ({len(allres)} rows)") | |
| if __name__ == "__main__": | |
| main() | |