Files
ML-Porosity/scripts/18_summarize_p2r.py
lamlvh 5a6fb2fc8c P2r main grid: runner, summary, results; close the P2r decision
- scripts/11: check_rids guard; scripts 14/15 accept the protocol_p2r main grid
  (realizations 8-15) only when protocol_p2r and its inputs match the locked SHA-256
- scripts/run_p2r_main.sh: per-regime pipelines (posterior then training) on cuda:0/cuda:1
- scripts/18_summarize_p2r.py: H2a / H2b / H3 / sigma_a verdicts per the locked rules
- docs/plan.md, report.html: H2a and H2b pass, sigma_a arm fails, no Pivot 1
- logs/index.csv: run records of the P2r grid

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:27:32 +00:00

318 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Verdicts of protocol_p2r (configs/protocol_p2r.yaml) on its main grid (realizations 8–15; scripts/run_p2r_main.sh).
python scripts/18_summarize_p2r.py # reads outputs/p2r/{posterior,train}/<regime>/
python scripts/18_summarize_p2r.py --root DIR # another root with the same layout (e.g. a dry run on dev data)
Every rule below is the locked rule of protocol_p2r; this script only applies it.
H2a per full-anchor regime (R10, R0, Rm5): B3d-Sa against the best point tie {B3b, B3c, B3c-R} with the
protocol_p2 rule (band RMSE ≤ 0.90 × best OR band PCC ≥ best + 0.05; cell_pass ≥ 4/5 seeds AND > 1/2 of
realizations). Regime passes if c = 1 passes for both N and the c = 0 guard holds (≤ 1.02, macro and per N).
H2a passes if R10 passes. Also reported: M2-Sa under the same rule, the secondary competitor set with B3d,
c = 2 cells (flagged: unstable posterior).
σ_a arm the H2a rule at R10, c = 1, N 4/16 with every method registered with σ_a = 3.5 / 14 ms (no guard).
H2b at N = 16 over all cells (regime × c): ratio = band RMSE M2-Sa / B3d-Sa; σ_post from the SMC particles of
the train wells (no labels). a: M2-Sa < B3d-Sa (cell_pass) in ≥ 2/3 of wide cells (σ_post ≥ 1.5 ms);
b: Spearman ρ(σ_post, ratio) < 0 (one-sided permutation p reported); c: mean ratio over narrow cells ≤ 1.02.
N = 4 reported only. Mechanism: the ratio is compared with the blur bound 1/B(σ_post) from the Oracle
predictions of the same regime and N.
H3 descriptive only: CE, coverage 50/80/90/95%, NLL, CRPS, mean σ of each 5-seed ensemble at c = 1.
Ratios carry a 95% bootstrap CI over realizations (2000 resamples).
→ outputs/p2r/summary/: h2a.csv, sigma_a.csv, h2b.csv, h3.csv, sigma_post.csv, warp.csv, blur.csv, band_rmse.csv,
verdict.json, summary.md
"""
from __future__ import annotations
import argparse
import importlib.util
import json
import math
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
sp13 = load_script("13_summarize_p2.py")
sp17 = load_script("17_summarize_p2r_dev.py")
P = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2r.yaml").read_text())
G = P["grid"]
H2A_REGIMES = P["hypotheses"]["H2a"]["regimes"]
POINT_TIES = P["hypotheses"]["H2a"]["competitors"]
WIDE_MS = 1.5
NARROW_GUARD, WIDE_FRAC = 1.02, 2 / 3
Z90 = sp17.Z90
N_PERM = 10000
# ---------------------------------------------------------------- inputs
def load_runs(root: Path) -> dict[str, pd.DataFrame]:
return {d.name: pd.read_csv(d / "runs.csv") for d in sorted((root / "train").glob("*")) if (d / "runs.csv").exists()}
def sigma_post(root: Path) -> pd.DataFrame:
"""σ_post per (setting, c, N): 90% width of τ(t) of the SMC particles (estR, γ = 1/κ), mean over train wells, / 3.29;
then mean over realizations. Warp error and coverage (true warp) are descriptive only."""
rows = []
for d in sorted((root / "posterior").glob("*")):
files = sorted(d.glob("r*_s*.csv"))
if not files:
continue
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
s = df[(df.method == "SMC_g_acf") & (df.wavelet == "estR")]
per_rid = s.groupby(["c", "n_train", "rid"]).agg(width90=("warp_width90_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
warp_cov90=("warp_cov90", "mean"), kappa_post=("kappa_post", "mean"),
phase_R=("phase_R", "first"))
per_rid["sigma_post_ms"] = per_rid.width90 / Z90
rows.append(per_rid.groupby(["c", "n_train"]).agg(
sigma_post_ms=("sigma_post_ms", "mean"), sigma_post_min=("sigma_post_ms", "min"), sigma_post_max=("sigma_post_ms", "max"),
warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean"), kappa_post=("kappa_post", "mean"),
n_rid=("width90", "size")).reset_index().assign(setting=d.name))
return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
# ---------------------------------------------------------------- H2a
def h2a_cells(run: pd.DataFrame, cand: str, comp: list[str], rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
"""protocol_p2 G-B cell rule (scripts/13 gate_gb) with `cand` in the role of M2 and `comp` as competitors."""
r = run[run.method.isin(comp) | (run.method == cand)].replace({"method": {cand: "M2"}})
grid = G | {"n_train": sorted(r.n_train.unique().tolist()), "drift_factors": sorted(r.c.unique().tolist())}
Pg = {"grid": grid, "gates": {"G-B": {"competitors": comp}}}
return sp13.gate_gb(r, Pg, n_boot, rng)
def h2a(runs: dict, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
sets = {"point_ties": POINT_TIES, "with_B3d": POINT_TIES + ["B3d"]}
rows, verdicts = [], {}
for reg in H2A_REGIMES:
if reg not in runs:
continue
for cand in ("B3d-Sa", "M2-Sa"):
for sname, comp in sets.items():
run = runs[reg]
if not set(comp + [cand]) <= set(run.method):
continue
cells, gv = h2a_cells(run, cand, comp, rng, n_boot)
c1 = cells[cells.c == G["realistic_drift"]]
ok_n = sorted(int(n) for n in c1.n_train[c1.cell_pass])
passed = bool(len(c1) == len(G["n_train"]) and c1.cell_pass.all() and gv["zero_drift_guard"])
verdicts[f"{reg}/{cand}/{sname}"] = {
"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}", "c1_pass_n": ok_n,
"zero_drift_macro_ratio": gv["zero_drift_macro_ratio"], "zero_drift_ratio_per_N": gv["zero_drift_ratio_per_N"],
"zero_drift_guard": gv["zero_drift_guard"], "regime_pass": passed,
"complete": bool((cells.n_rid == len(G["realizations"])).all() and (cells.n_seed == len(G["seeds"])).all()
and len(cells) == len(G["drift_factors"]) * len(G["n_train"]))}
rows.append(cells.assign(regime=reg, candidate=cand, competitors=sname,
flag=np.where(cells.c == 2, "unstable posterior", "")))
tab = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
key = "R10/B3d-Sa/point_ties"
verdict = {"pass": verdicts[key]["regime_pass"] if key in verdicts else None,
"regimes_pass": [r for r in H2A_REGIMES if verdicts.get(f"{r}/B3d-Sa/point_ties", {}).get("regime_pass")],
"per_regime": verdicts}
return tab, verdict
def sigma_a_arm(runs: dict, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
arm = G["sigma_a_arm"]
rows, verdicts = [], {}
for sa in arm["sigma_a_reg_ms"]:
name = f"{arm['regime']}_sa{sa:g}"
if name not in runs:
continue
cells, _ = h2a_cells(runs[name], "B3d-Sa", POINT_TIES, rng, n_boot)
c1 = cells[cells.c.isin(arm["drift_factors"])]
verdicts[f"sa{sa:g}"] = {"cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}",
"pass": bool(len(c1) == len(arm["n_train"]) and c1.cell_pass.all())}
rows.append(c1.assign(sigma_a_reg_ms=sa))
return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()), verdicts
# ---------------------------------------------------------------- H2b
def pair_cell(g: pd.DataFrame, a: str, b: str, rng, n_boot: int) -> dict:
"""Ratio mean(a)/mean(b) of band RMSE in one cell, its bootstrap CI over realizations, and the direction rule
(a < b in ≥ 4/5 seeds and > 1/2 of realizations)."""
x = g[g.method == a].set_index(["rid", "seed"])["band_rmse"]
y = g[g.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
d = x - y
ds, dr = d.groupby("seed").mean(), d.groupby("rid").mean()
xr, yr = x.groupby("rid").mean(), y.groupby("rid").mean()
lo, hi = sp13.boot(xr.to_numpy(), yr.to_numpy(), n_boot, rng)
return {"ratio": x.mean() / y.mean(), "ratio_lo": lo, "ratio_hi": hi, "seeds_better": int((ds < 0).sum()),
"rids_better": int((dr < 0).sum()), "n_seed": len(ds), "n_rid": len(dr),
"cell_pass": bool((ds < 0).sum() >= math.ceil(sp13.SEED_FRAC * len(ds) - 1e-9) and (dr < 0).sum() > len(dr) / 2)}
def h2b(runs: dict, sp: pd.DataFrame, bl: pd.DataFrame | None, rng, n_boot: int) -> tuple[pd.DataFrame, dict]:
from scipy.stats import spearmanr
rows = []
for reg in G["regimes"]:
if reg not in runs or not {"M2-Sa", "B3d-Sa"} <= set(runs[reg].method):
continue
for (c, N), g in runs[reg].groupby(["c", "n_train"]):
rows.append({"regime": reg, "c": c, "n_train": N} | pair_cell(g, "M2-Sa", "B3d-Sa", rng, n_boot))
t = pd.DataFrame(rows)
if t.empty:
return t, {}
t = t.merge(sp.rename(columns={"setting": "regime"})[["regime", "c", "n_train", "sigma_post_ms"]],
on=["regime", "c", "n_train"], how="left")
t["wide"] = t.sigma_post_ms >= WIDE_MS
if bl is not None and len(bl):
def bound(r):
b = bl[(bl.source == r.regime) & (bl.n_train == r.n_train)]
return 1.0 / np.interp(r.sigma_post_ms, b.sigma_ms, b["mean"]) if len(b) else np.nan
t["bound_1/B"] = t.apply(bound, axis=1)
out = {}
for N, g in t.groupby("n_train"):
g = g.dropna(subset=["sigma_post_ms"])
wide, narrow = g[g.wide], g[~g.wide]
rho = spearmanr(g.sigma_post_ms, g.ratio).statistic if len(g) > 2 else np.nan
perm = np.array([spearmanr(g.sigma_post_ms, rng.permutation(g.ratio.to_numpy())).statistic
for _ in range(N_PERM)]) if len(g) > 2 else np.array([np.nan])
a = bool(len(wide) > 0 and wide.cell_pass.sum() >= math.ceil(WIDE_FRAC * len(wide) - 1e-9))
b = bool(rho < 0)
c = bool(len(narrow) == 0 or narrow.ratio.mean() <= NARROW_GUARD)
out[f"n{N}"] = {"role": "primary" if N == P["hypotheses"]["H2b"]["primary_n"] else "reported only",
"cells": len(g), "wide_cells": len(wide), "wide_cells_pass": int(wide.cell_pass.sum()),
"a_wide_gain": a, "spearman_rho": rho, "perm_p_one_sided": float(np.mean(perm <= rho)),
"b_dose": b, "narrow_cells": len(narrow),
"narrow_ratio_mean": narrow.ratio.mean() if len(narrow) else None, "c_narrow_guard": c,
"pass": a and b and c}
out["pass"] = out.get(f"n{P['hypotheses']['H2b']['primary_n']}", {}).get("pass")
return t, out
def blur(root: Path) -> pd.DataFrame | None:
"""B(σ) per regime and N from the Oracle predictions of the main run (scripts/17 blur(), same σ grid)."""
from ml_porosity.eval.metrics import band_metrics
f_c = yaml.safe_load((REPO_ROOT / "configs" / "protocol_p2.yaml").read_text())["metrics"]["bands"]["f_c_hz"]
rows = []
for reg in G["regimes"]:
cells = root / "train" / reg / "cells"
for f in sorted(cells.glob("r*_c*_n*.npz")) if cells.exists() else []:
rid, c, N = sp13.parse_tag(f.stem)
z = np.load(f)
Y = z["y_true"].astype(float)
for k in (k for k in z.files if k.startswith("Oracle/") and k.endswith("/mu")):
P0 = z[k].astype(float)
b0 = np.mean([band_metrics(Y[i], P0[i], f_c)["band_rmse"] for i in range(len(Y))])
for s in sp17.BLUR_SIGMAS:
Pb = sp17.blur(P0, s)
rows.append({"source": reg, "rid": rid, "c": c, "n_train": N, "sigma_ms": s,
"ratio": np.mean([band_metrics(Y[i], Pb[i], f_c)["band_rmse"] for i in range(len(Y))]) / b0})
if not rows:
return None
return pd.DataFrame(rows).groupby(["source", "n_train", "sigma_ms"])["ratio"].agg(["mean", "min", "max", "size"]).reset_index()
# ---------------------------------------------------------------- H3 (descriptive)
def h3(root: Path, rng, n_boot: int) -> pd.DataFrame:
rows = []
for reg in G["regimes"]:
f = root / "train" / reg / "h3.csv"
if not f.exists():
continue
e = pd.read_csv(f)
e = e[e.c == G["realistic_drift"]]
for (N, m), g in e.groupby(["n_train", "method"]):
per = g.groupby("rid")["ce"].mean().to_numpy()
rows.append({"regime": reg, "n_train": N, "method": m, "members": int(g.members.min()), "n_rid": len(per),
**g[["ce", "coverage_50", "coverage_80", "coverage_90", "coverage_95", "nll", "crps", "mean_sigma"]].mean().to_dict(),
**dict(zip(("ce_lo", "ce_hi"), sp13.boot(per, None, n_boot, rng)))})
return pd.DataFrame(rows)
# ---------------------------------------------------------------- report
def md(df: pd.DataFrame, fmt: str = ".3f") -> str:
return df.to_markdown(index=False, floatfmt=fmt) if len(df) else "(no data)"
def write_md(path: Path, v: dict, h2a_tab, sa_tab, h2b_tab, h3_tab, sp, band) -> None:
L = ["# protocol_p2r: main grid (realizations 8–15)", "",
"Locked rules of configs/protocol_p2r.yaml applied as written; nothing here was selected on these results.", ""]
hv = v["H2a"]
L += ["## H2a — posterior-mean labels (B3d-Sa) vs the best point tie {B3b, B3c, B3c-R}", "",
f"**H2a (R10): {'PASS' if hv['pass'] else 'FAIL' if hv['pass'] is not None else 'not available'}**; "
f"regimes that pass: {', '.join(hv['regimes_pass']) or 'none'}", ""]
if len(h2a_tab):
per = pd.DataFrame(hv["per_regime"]).T.reset_index(names="regime/candidate/competitors")
L += [md(per[["regime/candidate/competitors", "c1_cells_pass", "zero_drift_macro_ratio", "zero_drift_guard",
"regime_pass", "complete"]]), ""]
cols = ["regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc",
"seeds_improve", "rids_improve", "cell_pass", "flag"]
L += ["Cells (ratio = band RMSE candidate / best competitor; CI over realizations; c = 2 not primary evidence):", "",
md(h2a_tab[cols]), ""]
L += ["## σ_a arm (R10, c = 1; every method registered with the misspecified σ_a)", "",
json.dumps(v["sigma_a_arm"]), ""]
if len(sa_tab):
L += [md(sa_tab[["sigma_a_reg_ms", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve",
"rids_improve", "cell_pass"]]), ""]
L += ["## H2b — RML on the posterior bank (M2-Sa) vs posterior-mean labels (B3d-Sa)", ""]
for k, x in v["H2b"].items():
if isinstance(x, dict):
L += [f"- N = {k[1:]} ({x['role']}): a {x['a_wide_gain']} ({x['wide_cells_pass']}/{x['wide_cells']} wide cells pass), "
f"b {x['b_dose']} (ρ = {x['spearman_rho']:.3f}, one-sided permutation p = {x['perm_p_one_sided']:.3f}), "
f"c {x['c_narrow_guard']} (narrow mean ratio "
f"{'n/a' if x['narrow_ratio_mean'] is None else format(x['narrow_ratio_mean'], '.3f')}) → {'PASS' if x['pass'] else 'FAIL'}"]
L += ["", f"**H2b: {v['H2b'].get('pass')}**", ""]
if len(h2b_tab):
cols = [c for c in ["regime", "c", "n_train", "sigma_post_ms", "wide", "ratio", "ratio_lo", "ratio_hi", "bound_1/B",
"seeds_better", "rids_better", "cell_pass"] if c in h2b_tab.columns]
L += ["Mechanism: a gain is attributed to deblurring only if the ratio lies within the bound 1/B(σ_post).", "",
md(h2b_tab[cols].sort_values(["n_train", "sigma_post_ms"])), ""]
L += ["## σ_post and warp error of the SMC posterior (train wells; warp error and coverage use the true warp, descriptive)", "",
md(sp), "", "## Band RMSE per method (mean over realization × seed)", "", md(band), "",
"## H3 (descriptive only; no calibration claim) — 5-seed ensembles at c = 1", "", md(h3_tab), ""]
path.write_text("\n".join(L))
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--root", type=Path, default=outputs_dir() / "p2r")
ap.add_argument("--out-dir", type=Path, default=None, help="default: <root>/summary")
ap.add_argument("--n-boot", type=int, default=2000)
args = ap.parse_args()
out = args.out_dir or args.root / "summary"
out.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(0)
runs = load_runs(args.root)
sp = sigma_post(args.root)
sp.to_csv(out / "sigma_post.csv", index=False)
h2a_tab, h2a_v = h2a(runs, rng, args.n_boot)
h2a_tab.to_csv(out / "h2a.csv", index=False)
sa_tab, sa_v = sigma_a_arm(runs, rng, args.n_boot)
sa_tab.to_csv(out / "sigma_a.csv", index=False)
bl = blur(args.root)
if bl is not None:
bl.to_csv(out / "blur.csv", index=False)
h2b_tab, h2b_v = h2b(runs, sp, bl, rng, args.n_boot)
h2b_tab.to_csv(out / "h2b.csv", index=False)
h3_tab = h3(args.root, rng, args.n_boot)
h3_tab.to_csv(out / "h3.csv", index=False)
band = pd.concat([r.groupby(["c", "n_train", "method"])["band_rmse"].mean().unstack("method").reset_index().assign(setting=k)
for k, r in runs.items()], ignore_index=True) if runs else pd.DataFrame()
if len(band):
band = band[["setting"] + [c for c in band.columns if c != "setting"]]
band.to_csv(out / "band_rmse.csv", index=False)
v = {"protocol": "configs/protocol_p2r.yaml",
"protocol_sha256": (REPO_ROOT / "configs" / "protocol_p2r.sha256").read_text().split()[0],
"settings": sorted(runs), "H2a": h2a_v, "sigma_a_arm": sa_v, "H2b": h2b_v}
(out / "verdict.json").write_text(json.dumps(v, indent=1, default=float))
write_md(out / "summary.md", v, h2a_tab, sa_tab, h2b_tab, h3_tab, sp, band)
print((out / "summary.md").read_text())
if __name__ == "__main__":
main()