"""Generate results/REPORT_R2.md - the method-convergence round report. Covers everything after the published benchmark: the RelMode screening rounds, the full-20-task confirmation, the ablation ladder, the hybrid read-out, the three reviewer suggestions, the tree family, the family-rule ensembles, and the few-shot calibration variants. PYTHONPATH=src python scripts/report_r2.py """ from __future__ import annotations import re from pathlib import Path import numpy as np import pandas as pd from scipy import stats R = Path(__file__).resolve().parents[1] / "results" OUT = R / "REPORT_R2.md" EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") def read(name: str) -> pd.DataFrame | None: p = R / name if not p.exists(): return None df = pd.read_csv(p) return df if len(df) else None def external_only(df: pd.DataFrame) -> pd.DataFrame: return df[df["task"].str.match(EXTERNAL)] def paired(variant: pd.DataFrame, control: pd.DataFrame) -> dict | None: """Paired per-(task, seed) comparison of two run tables.""" if variant is None or control is None: return None key = ["task", "seed"] m = variant.merge(control, on=key, suffixes=("_v", "_c")) if len(m) < 6: return None d = m["spearman_v"] - m["spearman_c"] try: p = stats.wilcoxon(m["spearman_v"], m["spearman_c"]).pvalue except ValueError: p = float("nan") return {"n": len(m), "variant": float(m["spearman_v"].mean()), "control": float(m["spearman_c"].mean()), "delta": float(d.mean()), "p": float(p)} def screen_row(name: str, label: str, control_name: str) -> list[str]: v, c = read(name), read(control_name) st = paired(v, c) if st is None: return [] p = "--" if np.isnan(st["p"]) else f"{st['p']:.3f}" return [f"| {label} | {st['n']} | {st['variant']:.4f} | {st['control']:.4f} | " f"{st['delta']:+.4f} | {p} |"] def main() -> None: L: list[str] = [] L.append("# Method-convergence round report\n") L.append("Auto-generated by `scripts/report_r2.py`. All comparisons are paired " "per (task, seed); p values are two-sided Wilcoxon signed-rank tests. " "Screens use the four fold-0 external tasks x 2 seeds unless noted; " "confirmations use all 20 external tasks. Only external tasks are " "counted everywhere (cv5 rows are excluded).\n") # ---- 0. the definitive unified ladder ---------------------------------- ul = read("unified_ladder.csv") if ul is not None and len(ul): L.append("## 0. The definitive unified-budget k-shot ladder\n") L.append("Every method receives the same pilot batch (same draw, same seeds) " "and is evaluated on the unlabelled remainder. " "Sources: `fewshot_ens_refit.csv`, `fewshot_kscale*.csv`, " "`fewshot_final.csv`, `fewshot_baselines*.csv`; built by " "`scripts/unified_ladder.py`.\n") L.append("| k (labels) | strongest same-budget baseline | ours | our arm | improvement |") L.append("|---|---|---|---|---|") for _, r in ul.iterrows(): mean_labels = {0.1: 53, 0.2: 106, 0.3: 159, 0.5: 265, 0.8: 424}.get(r['k_shot'], "?") L.append(f"| {int(r['k_shot']*100)}% ({mean_labels}) | " f"{r['best_baseline']:.4f} ({r['best_baseline_name']}) | " f"**{r['best_ours']:.4f}** | {r['best_ours_name']} | " f"{r['rel_improve']*100:+.1f}% |") L.append("\n0.55+ is reached at k=50% (0.593, adapted-tree ensemble); the " "protocol dominates every same-budget baseline up to k=50% and ties " "the strongest one at k=80%. Our k=10% (0.466) beats every baseline " "at k=20% (0.450) - twice the label efficiency.\n") # ---- 1. full-20 confirmation of the adopted pair-level variant ---------- f20n = pd.concat([d for d in (read("f20_nrw_s0.csv"), read("f20_nrw_s1.csv")) if d is not None]) f20b = pd.concat([d for d in (read("f20_base_s0.csv"), read("f20_base_s1.csv")) if d is not None]) if len(f20n) and len(f20b): L.append("## 1. RelMode-LNP full-20-task confirmation\n") L.append("Adopted configuration `relmode_nr_w` (identity-free pair space, " "warm-up 8 epochs) against its nested control `relmode_base` " "(relation branch disabled), both at seeds 0 and 1:\n") for seed in sorted(f20n["seed"].unique()): st = paired(f20n[f20n["seed"] == seed], f20b[f20b["seed"] == seed]) if st: p = "--" if np.isnan(st["p"]) else f"{st['p']:.3f}" L.append(f"| seed {seed} | n={st['n']} | variant {st['variant']:.4f} | " f"control {st['control']:.4f} | delta {st['delta']:+.4f} | p {p} |") st = paired(f20n, f20b) p = "--" if np.isnan(st["p"]) else f"{st['p']:.3f}" L.append(f"| pooled | n={st['n']} | {st['variant']:.4f} | {st['control']:.4f} | " f"{st['delta']:+.4f} | {p} |") L.append("\nThe pair-level codebook is the only variant that does not lose to " "its nested control; the delta is not significant at n = 40 paired " "runs, so it is adopted as an *interpretable kernel*, not as a " "performance claim.\n") # ---- 2. screening rounds ------------------------------------------------ L.append("## 2. Screening rounds (4 fold-0 tasks x 2 seeds)\n") rounds = [ ("round 1 - formulation-level and first pair-level variants", [("rs_relmode.csv", "relmode (formulation-level VQ)", "rs_relmode_base.csv"), ("rs_relmode_h.csv", "relmode_h (per-head expert)", "rs_relmode_base.csv"), ("rs_relmode_sc.csv", "relmode_sc (scalar expert)", "rs_relmode_base.csv"), ("rs_relmode_lin.csv", "relmode_lin (linear mix)", "rs_relmode_base.csv"), ("rs_relmode_a1.csv", "relmode_a1 (alpha=1)", "rs_relmode_base.csv"), ("rs_relmode_sc_a1.csv", "relmode_sc_a1", "rs_relmode_base.csv"), ("rs_relmode_h_a1.csv", "relmode_h_a1", "rs_relmode_base.csv")]), ("round 2 - identity-free pair space", [("rt_relmode_nr.csv", "relmode_nr (drop molar ratio)", "rt_relmode_base.csv"), ("rt_relmode_nr_sc.csv", "relmode_nr_sc", "rt_relmode_base.csv"), ("rt_relmode_nr_w.csv", "relmode_nr_w (warm-up 8)", "rt_relmode_base.csv"), ("rt_relmode_nr_w_sch.csv", "relmode_nr_w_sch (schema only)", "rt_relmode_base.csv")]), ] for title, rows in rounds: lines = [] for f, label, ctrl in rows: lines += screen_row(f, label, ctrl) if lines: L.append(f"### {title}\n") L.append("| variant | n | variant | control | delta | p |") L.append("|---|---|---|---|---|---|") L += lines L.append("") # ---- 3. ablation ladder ------------------------------------------------- abl = [("ra_relmode_nr_w_k8.csv", "K=8"), ("ra_relmode_nr_w_k32.csv", "K=32"), ("ra_relmode_nr_w_novq.csv", "no VQ"), ("ra_relmode_nr_w_hard.csv", "hard assignment"), ("ra_relmode_nr_w_nocent.csv", "no centering")] lines = [] for f, label in abl: lines += screen_row(f, label, "rt_relmode_nr_w.csv") if lines: L.append("## 3. Ablation ladder around the adopted configuration\n") L.append("| ablation | n | variant | control (relmode_nr_w) | delta | p |") L.append("|---|---|---|---|---|---|") L += lines L.append("") # ---- 4. hybrid read-out ------------------------------------------------- lines = screen_row("rb_relmode_blk.csv", "relmode_blk (neural + 398-d block)", "rt_relmode_nr_w.csv") lines += screen_row("rb_relset_blk.csv", "relset_blk (PhysSet + 398-d block)", "rt_relmode_base.csv") if lines: L.append("## 4. Hybrid read-out\n") L.append("| variant | n | variant | control | delta | p |") L.append("|---|---|---|---|---|---|") L += lines L.append("") # ---- 5. reviewer suggestions ------------------------------------------- lines = screen_row("e3_relmode_ctx.csv", "coarse context (47/109 dims)", "rt_relmode_nr_w.csv") lines += screen_row("e3_relmode_ctx_blk.csv", "coarse context + block", "rt_relmode_nr_w.csv") lines += screen_row("e3_relmode_rank.csv", "pure ranking (lam_rank=1)", "rt_relmode_nr_w.csv") lines += screen_row("e3_relmode_rank0.csv", "pure ranking (no reg)", "rt_relmode_nr_w.csv") lines += screen_row("e3_relset_rank.csv", "pure ranking (no relmode)", "rt_relmode_base.csv") if lines: L.append("## 5. Reviewer suggestions, tested at full scale\n") L.append("| variant | n | variant | control | delta | p |") L.append("|---|---|---|---|---|---|") L += lines L.append("\nAll three suggestions lose; none is adopted.\n") # ---- 6. tree family ----------------------------------------------------- tf = read("tree_family.csv") if tf is not None: tf = external_only(tf) L.append("## 6. Tree family on the 398-d chemistry block (20 external tasks)\n") L.append("| model | tasks | mean Spearman |") L.append("|---|---|---|") for m, g in tf.groupby("model"): L.append(f"| {m} | {len(g)} | {g['spearman'].mean():.4f} |") L.append("\nReference: random forest 0.3761 on the same block " "(`results/benchmark_models.csv`). No boosted learner beats it. " "Within-database cv5 numbers (~0.56 for the same learners) are " "excluded on purpose - they overstate transfer 2-3x.\n") # ---- 7. ensembles over saved predictions -------------------------------- sf = read("stack_family.csv") if sf is not None and len(sf): L.append("## 7. Family-rule ensembles over saved predictions\n") L.append("One member per model family (identity-free tree, physics-informed " "neural, neural baseline, discrete-relation kernel), rank-averaged. " "The honest variant selects each family's representative on the " "three training studies only (`stack_family.py`):\n") fix = sf[sf["selection"] == "fixed"] if len(fix): L.append("| fixed set | tasks | mean | BL_2023 | LM_2019 | SL_2020 | ZC_2023 |") L.append("|---|---|---|---|---|---|---|") for _, r in fix.iterrows(): L.append(f"| {r['stack']} | {int(r['n'])} | {r['mean']:.4f} | " f"{r.get('s_BL_2023', float('nan')):.4f} | " f"{r.get('s_LM_2019', float('nan')):.4f} | " f"{r.get('s_SL_2020', float('nan')):.4f} | " f"{r.get('s_ZC_2023', float('nan')):.4f} |") L.append("") loso = sf[sf["stack"] == "family4_loso"] if len(loso): L.append(f"Honest leave-one-study-out estimate of the family rule: " f"**{loso['mean'].mean():.4f}** - the same four members " "(physchem_tree / physset_phys / lion / relmode_nr_w) are " "selected no matter which study is held out, so the fixed-set " "number is not a selection artifact.\n") sl = read("stack_loso.csv") if sl is not None and len(sl): L.append(f"Free (greedy, unconstrained) member selection under the same " f"protocol: **{sl['held_mean'].mean():.4f}** " "(`stack_loso.csv`) - the family constraint costs nothing.\n") # ---- 8. few-shot on the ensemble base ---------------------------------- fs = read("fewshot_stack.csv") if fs is not None and len(fs): L.append("## 8. Few-shot calibration on the ensemble base\n") L.append("Isotonic / residual-Ridge calibration of the rank-averaged " "six-member ensemble (`fewshot_stack.py`), same protocol as the " "published ladder:\n") g = fs.groupby(["k_shot", "select", "use"])["spearman"].agg(["size", "mean"]) L.append("| k | select | use | n | mean Spearman |") L.append("|---|---|---|---|---|") for (k, s, u), r in g.iterrows(): L.append(f"| {k} | {s} | {u} | {int(r['size'])} | {r['mean']:.4f} |") L.append("\nResidual Ridge on a rank-scale base is itself monotone, so it " "cannot change Spearman; isotonic adds only ~+0.016 at k=20%. " "Calibration of a fixed prediction is much weaker than refitting " "with the pilot labels - the pilot lets the model re-learn the " "target study's chemistry->activity mapping in feature space.\n") fer = read("fewshot_ens_refit.csv") if fer is not None and len(fer): L.append("## 9. Pilot refit combined with the ensemble\n") L.append("Refit the identity-free forest on train + pilot, then rank-average " "the refit forest with the fixed ensemble base " "(`fewshot_ens_refit.py`); evaluated on the unlabelled remainder:\n") g = fer.groupby(["k_shot", "select", "use"])["spearman"].agg(["size", "mean"]) L.append("| k | select | use | n | mean Spearman |") L.append("|---|---|---|---|---|") for (k, s, u), r in g.iterrows(): L.append(f"| {k} | {s} | {u} | {int(r['size'])} | {r['mean']:.4f} |") L.append("") # ---- 9. round-1 running files ------------------------------------------ bv = read("block_v2.csv") if bv is not None and len(bv) and "block" in bv.columns: bv = external_only(bv) L.append("## 10. Extended chemistry blocks (fingerprints / MACCS)\n") g = bv.groupby(["block", "model"])["spearman"].agg(["mean", "count"]) L.append("| block | model | tasks | mean Spearman |") L.append("|---|---|---|---|") for (b, m), r in g.iterrows(): L.append(f"| {b} | {m} | {int(r['count'])} | {r['mean']:.4f} |") L.append("") fa = read("fewshot_active.csv") if fa is not None and len(fa) and "select" in fa.columns: L.append("## 11. Active few-shot calibration (single forest)\n") g = fa.groupby(["select", "use", "k_shot"])["spearman"].agg(["mean", "count"]) L.append("| select | use | k | n | mean Spearman |") L.append("|---|---|---|---|---|") for (s, u, k), r in g.iterrows(): L.append(f"| {s} | {u} | {k} | {int(r['count'])} | {r['mean']:.4f} |") L.append("") OUT.write_text("\n".join(L)) print(f"wrote {OUT} ({len(OUT.read_text())} chars)") if __name__ == "__main__": main()