- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
(sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
wavelets, horizon cache, budgets) so load_protocol() and summarize work
after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.
Main S1 runs are still training at this commit; results follow.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
540 lines
33 KiB
Python
540 lines
33 KiB
Python
"""Pre-declared analyses of protocol_bench (hypotheses block of configs/protocol_bench.yaml), applied as written.
|
||
|
||
Rules are those of protocol_p2 / protocol_p2r through scripts/13 (gate_gb, boot) and scripts/18 (pair_cell). Runs of
|
||
the P2r cells come from outputs/p2r (reference, read-only). Everything is reported regardless of direction; a
|
||
hypothesis of kind `claim` gets a pass/fail, `descriptive` items get tables only.
|
||
→ <root>/summary/: s1_cells.csv, s1_h2a.csv, s1_families.csv, s1_additivity.csv, s2_cells.csv, s2_smc.csv, s2_h2a.csv,
|
||
s2_degradation.csv, s3_h2a.csv, s3_table.csv, s4_cells.csv, s4_h2a.csv, s8_cells.csv, s8_transfer.csv, verdict.json,
|
||
summary.md
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import math
|
||
from pathlib import Path
|
||
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
from ml_porosity.benchmark.cells import Cell, bench_root, study_cells, train_paths
|
||
from ml_porosity.benchmark.data import load_script
|
||
from ml_porosity.paths import REPO_ROOT, outputs_dir
|
||
|
||
sp13 = load_script("13_summarize_p2.py")
|
||
METRICS = sp13.METRICS
|
||
Z90 = 3.29
|
||
NFFT = 256
|
||
POINT_TIES = ["B3b", "B3c", "B3c-R"]
|
||
|
||
|
||
# ---------------------------------------------------------------- loading
|
||
|
||
def _runs_from_cells(files: list[Path], budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
|
||
if not files:
|
||
return pd.DataFrame(), pd.DataFrame()
|
||
df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
|
||
df = df[df["budget"] == df["method"].map(lambda m: budgets.get(m, np.nan))]
|
||
by = ["study", "regime", "preset", "delta_ms", "rid", "c", "n_train", "method", "seed"]
|
||
by = [b for b in by if b in df.columns]
|
||
run = df.groupby(by, as_index=False, dropna=False)[METRICS].mean()
|
||
return df, run
|
||
|
||
|
||
def study_budgets(p: dict, study: str, arm: int | None = None) -> dict:
|
||
"""Registered budgets per method (TCN names for S4); arm: the equal-budget arm instead (every method at `arm`)."""
|
||
b = dict(p["training"]["budgets"])
|
||
if p["studies"][study].get("backbone", "cnngru") != "cnngru":
|
||
alt = p["training"].get("budgets_tcn") or {}
|
||
b = {f"{m}-TCN": int(alt.get(m, v)) for m, v in b.items()}
|
||
if arm:
|
||
b = {m: int(arm) for m in b}
|
||
return b
|
||
|
||
|
||
def load_study(p: dict, root: Path, study: str, arm: int | None = None) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
|
||
"""(rows, runs, diag) of every completed cell of a study under root at the registered budgets (arm=None) or at
|
||
the equal-budget arm."""
|
||
d = root / study.lower() / "train"
|
||
files = sorted(f for f in d.glob("*/cells/*.csv") if not f.name.endswith("_diag.csv")) if d.exists() else []
|
||
rows, run = _runs_from_cells(files, study_budgets(p, study, arm))
|
||
diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True) if files else pd.DataFrame()
|
||
return rows, run, diag
|
||
|
||
|
||
USE_P2R = True # set to False by summarize(dev=True): a dev summary must never read main-grid results
|
||
|
||
|
||
def p2r_runs(p: dict) -> pd.DataFrame:
|
||
root = REPO_ROOT / p["reference"]["p2r"]["root"]
|
||
parts = []
|
||
if not USE_P2R:
|
||
return pd.DataFrame()
|
||
for reg in p["reference"]["p2r"]["regimes"]:
|
||
f = root / "train" / reg / "runs.csv"
|
||
if f.exists():
|
||
parts.append(pd.read_csv(f).assign(regime=reg, preset="nominal", study="P2r"))
|
||
return pd.concat(parts, ignore_index=True) if parts else pd.DataFrame()
|
||
|
||
|
||
def sigma_post_table(dirs: dict[str, Path]) -> pd.DataFrame:
|
||
"""σ_post and SMC diagnostics per (setting, c, N) from posterior CSVs (SMC_g_acf, estR), mean over wells then rids."""
|
||
rows = []
|
||
for setting, d in dirs.items():
|
||
files = sorted(d.glob("r*_s*.csv")) if d.exists() else []
|
||
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 = 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"),
|
||
r_post=("r_post", "mean"), phase_R=("phase_R", "first"), phase0=("phase", "first"))
|
||
per["sigma_post_ms"] = per.width90 / Z90
|
||
per["overconfidence"] = per.warp_rmse_ms / per.sigma_post_ms
|
||
g = per.groupby(["c", "n_train"]).agg(sigma_post_ms=("sigma_post_ms", "mean"), warp_rmse_ms=("warp_rmse_ms", "mean"),
|
||
warp_cov90=("warp_cov90", "mean"), overconfidence=("overconfidence", "mean"),
|
||
kappa_post=("kappa_post", "mean"), r_post=("r_post", "mean"),
|
||
phase_R_mean=("phase_R", "mean"), phase_R_abs_mean=("phase_R", lambda x: float(np.mean(np.abs(x)))),
|
||
n_rid=("sigma_post_ms", "size")).reset_index()
|
||
rows.append(g.assign(setting=setting))
|
||
return pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||
|
||
|
||
# ---------------------------------------------------------------- rules
|
||
|
||
def h2a_cells(run: pd.DataFrame, cand: str, comp: list[str], rng, n_boot: int) -> pd.DataFrame:
|
||
"""protocol_p2 cell rule with `cand` in the role of M2 against the best of `comp` (scripts/13 gate_gb)."""
|
||
r = run[run.method.isin(comp) | (run.method == cand)].replace({"method": {cand: "M2"}})
|
||
if r.empty or "M2" not in set(r.method) or not (set(r.method) & set(comp)):
|
||
return pd.DataFrame()
|
||
if any(m.endswith("-TCN") for m in comp): # gate_gb reads 'B3b' by name: drop the backbone suffix locally
|
||
r = r.assign(method=r.method.str.replace("-TCN", "", regex=False))
|
||
comp = [m.removesuffix("-TCN") for m in comp]
|
||
grid = {"n_train": sorted(r.n_train.unique().tolist()), "drift_factors": sorted(r.c.unique().tolist()),
|
||
"realistic_drift": 1, "realizations": sorted(r.rid.unique().tolist()), "seeds": sorted(r.seed.unique().tolist())}
|
||
cells, _ = sp13.gate_gb(r, {"grid": grid, "gates": {"G-B": {"competitors": comp}}}, n_boot, rng)
|
||
return cells
|
||
|
||
|
||
def pair(run: pd.DataFrame, a: str, b: str, rng, n_boot: int) -> dict:
|
||
"""Ratio mean(a)/mean(b) of band RMSE with CI over realizations and the 'better' rule (scripts/18 pair_cell)."""
|
||
x = run[run.method == a].set_index(["rid", "seed"])["band_rmse"]
|
||
y = run[run.method == b].set_index(["rid", "seed"])["band_rmse"].reindex(x.index)
|
||
ok = y.notna()
|
||
x, y = x[ok], y[ok]
|
||
if len(x) == 0:
|
||
return {}
|
||
d = x - y
|
||
ds, dr = d.groupby("seed").mean(), d.groupby("rid").mean()
|
||
lo, hi = sp13.boot(x.groupby("rid").mean().to_numpy(), y.groupby("rid").mean().to_numpy(), n_boot, rng)
|
||
return {"ratio": float(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),
|
||
"better": bool((ds < 0).sum() >= math.ceil(sp13.SEED_FRAC * len(ds) - 1e-9) and (dr < 0).sum() > len(dr) / 2)}
|
||
|
||
|
||
def perm_spearman(x, y, groups, rng, n_perm: int) -> tuple[float, float]:
|
||
"""Spearman ρ(x, y) and one-sided permutation p (ρ ≤ observed) permuting y within groups."""
|
||
from scipy.stats import spearmanr
|
||
|
||
x, y, groups = np.asarray(x, float), np.asarray(y, float), np.asarray(groups)
|
||
if len(x) < 3:
|
||
return float("nan"), float("nan")
|
||
rho = spearmanr(x, y).statistic
|
||
idx = {g: np.flatnonzero(groups == g) for g in np.unique(groups)}
|
||
cnt = 0
|
||
for _ in range(n_perm):
|
||
yp = y.copy()
|
||
for ii in idx.values():
|
||
yp[ii] = y[rng.permutation(ii)]
|
||
cnt += spearmanr(x, yp).statistic <= rho
|
||
return float(rho), float(cnt / n_perm)
|
||
|
||
|
||
# ---------------------------------------------------------------- S1
|
||
|
||
def s1(p: dict, root: Path, rng, n_boot: int, n_perm: int) -> tuple[dict, dict]:
|
||
_, run_new, _ = load_study(p, root, "S1")
|
||
run = pd.concat([p2r_runs(p), run_new], ignore_index=True) if len(run_new) else p2r_runs(p)
|
||
if run.empty:
|
||
return {}, {"available": False}
|
||
sp = sigma_post_table({reg: root / "posterior" / reg for reg in p["studies"]["S1"]["regimes"]})
|
||
sp_ref = REPO_ROOT / p["reference"]["p2r"]["root"] / "summary" / "sigma_post.csv"
|
||
if sp_ref.exists() and USE_P2R:
|
||
ref = pd.read_csv(sp_ref).rename(columns={"setting": "regime"})
|
||
ref = ref[ref.regime.isin(p["studies"]["S1"]["regimes"])][["regime", "c", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]]
|
||
sp = pd.concat([sp.rename(columns={"setting": "regime"}), ref.assign(source="p2r")], ignore_index=True) if len(sp) else ref.assign(source="p2r")
|
||
else:
|
||
sp = sp.rename(columns={"setting": "regime"})
|
||
tables, verdict = {}, {}
|
||
# phase-diagram cells: per (regime, c, N) band RMSE per method, ratios with CI
|
||
cells = []
|
||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||
mean = g.groupby("method")["band_rmse"].mean()
|
||
row = {"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||
if "M2-Sa" in mean and "B3d-Sa" in mean:
|
||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()}
|
||
pt = [m for m in POINT_TIES if m in mean.index]
|
||
if pt and "B3d-Sa" in mean:
|
||
best = mean.loc[pt].idxmin()
|
||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(g, "B3d-Sa", best, rng, n_boot).items()}
|
||
cells.append(row)
|
||
cells = pd.DataFrame(cells).merge(sp[["regime", "c", "n_train", "sigma_post_ms"]].drop_duplicates(["regime", "c", "n_train"]),
|
||
on=["regime", "c", "n_train"], how="left")
|
||
tables["s1_cells"] = cells
|
||
# H2a rule at every (regime, c, N) (S1-H1: R10, c = 1.5, both N)
|
||
h2a = []
|
||
for reg, g in run.groupby("regime"):
|
||
t = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||
if len(t):
|
||
h2a.append(t.assign(regime=reg))
|
||
h2a = pd.concat(h2a, ignore_index=True) if h2a else pd.DataFrame()
|
||
tables["s1_h2a"] = h2a
|
||
if len(h2a):
|
||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1.5)]
|
||
verdict["S1-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||
"ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all())}
|
||
# S1-H2: families with σ_post(N = 16) ≥ 1.5 ms; r(N) decreasing in N
|
||
wide16 = cells[(cells.n_train == 16) & (cells.sigma_post_ms >= 1.5)][["regime", "c"]]
|
||
fam = cells.merge(wide16, on=["regime", "c"]).dropna(subset=["m2_pm_ratio"])
|
||
fam["family"] = fam.regime + "_c" + fam.c.map(lambda v: f"{v:g}")
|
||
tables["s1_families"] = fam[["family", "regime", "c", "n_train", "sigma_post_ms", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better"]]
|
||
if len(fam):
|
||
r16 = fam[fam.n_train == 16].set_index("family").m2_pm_ratio
|
||
r2 = fam[fam.n_train == 2].set_index("family").m2_pm_ratio
|
||
both = r16.index.intersection(r2.index)
|
||
sign = int((r16[both] < r2[both]).sum())
|
||
rho, pval = perm_spearman(np.log2(fam.n_train), fam.m2_pm_ratio, fam.family, rng, n_perm)
|
||
a = bool(len(both) > 0 and sign >= math.ceil(2 / 3 * len(both) - 1e-9))
|
||
b = bool(rho < 0 and pval < 0.05)
|
||
verdict["S1-H2"] = {"families": sorted(fam.family.unique()), "families_with_N2_and_N16": int(len(both)), "r16_below_r2": sign,
|
||
"a_sign": a, "spearman_rho": rho, "perm_p_one_sided": pval, "b_dose": b,
|
||
"pass": (a and b) if len(both) > 0 and fam.n_train.nunique() >= 3 else None}
|
||
# S1-D additivity: band_rmse²(B3d-Sa) = band_rmse²(Oracle) + β σ_post² per regime
|
||
add = []
|
||
for reg, g in cells.dropna(subset=["sigma_post_ms"]).groupby("regime"):
|
||
if "band_rmse_B3d-Sa" not in g or "band_rmse_Oracle" not in g:
|
||
continue
|
||
y = g["band_rmse_B3d-Sa"] ** 2 - g["band_rmse_Oracle"] ** 2
|
||
x = g["sigma_post_ms"] ** 2
|
||
if len(g) < 3 or x.var() == 0:
|
||
continue
|
||
beta = float((x * y).sum() / (x * x).sum())
|
||
resid = y - beta * x
|
||
add.append({"regime": reg, "n_cells": len(g), "beta_pu2_per_ms2": beta,
|
||
"r2": float(1 - (resid ** 2).sum() / ((y - y.mean()) ** 2).sum()) if (y - y.mean()).abs().sum() > 0 else float("nan")})
|
||
tables["s1_additivity"] = pd.DataFrame(add)
|
||
return tables, verdict
|
||
|
||
|
||
# ---------------------------------------------------------------- S2
|
||
|
||
def s2(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||
_, run, diag = load_study(p, root, "S2")
|
||
if run.empty:
|
||
return {}, {"available": False}
|
||
s = p["studies"]["S2"]
|
||
axes = {name: axis for axis, names in s["presets"].items() for name in names}
|
||
levels = {name: i + 1 for names in s["presets"].values() for i, name in enumerate(names)}
|
||
settings = {f"{reg}__{name}": root / "posterior" / f"{reg}__{name}" for reg in s["regimes"] for name in list(axes) + list(s.get("controls", {}).get("presets", []))}
|
||
smc = sigma_post_table(settings)
|
||
if len(smc):
|
||
smc["regime"] = smc.setting.str.split("__").str[0]
|
||
smc["preset"] = smc.setting.str.split("__").str[1]
|
||
smc["axis"] = smc.preset.map(lambda n: axes.get(n, "control"))
|
||
smc["level"] = smc.preset.map(lambda n: levels.get(n, 0))
|
||
tables = {"s2_smc": smc}
|
||
ref = p2r_runs(p)
|
||
cells, h2a_rows, verdict = [], [], {"S2-H1": {"per_axis": {}}, "S2-H2": {"pairs": {}}}
|
||
for (reg, name), g in run.groupby(["regime", "preset"]):
|
||
h = h2a_cells(g, "B3d-Sa", POINT_TIES, rng, n_boot)
|
||
if len(h):
|
||
h2a_rows.append(h.assign(regime=reg, preset=name, axis=axes.get(name, "control"), level=levels.get(name, 0)))
|
||
ratios = {}
|
||
for N, gN in g.groupby("n_train"):
|
||
mean = gN.groupby("method")["band_rmse"].mean()
|
||
row = {"regime": reg, "preset": name, "axis": axes.get(name, "control"), "level": levels.get(name, 0), "c": 1.0, "n_train": N,
|
||
"n_rid": gN.rid.nunique(), "n_seed": gN.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||
pr = pair(gN, "M2-Sa", "B3d-Sa", rng, n_boot)
|
||
row |= {f"m2_pm_{k}": v for k, v in pr.items()}
|
||
ratios[N] = pr.get("ratio", np.nan)
|
||
if "Ctl-GP" in mean.index: # disclosed (T2 ii)
|
||
row |= {f"ctl_pm_{k}": v for k, v in pair(gN, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||
row |= {f"m2_ctl_{k}": v for k, v in pair(gN, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||
pt = [m for m in POINT_TIES if m in mean.index]
|
||
if pt and "B3d-Sa" in mean:
|
||
best = mean.loc[pt].idxmin()
|
||
row |= {"best_point_tie": best} | {f"pm_best_{k}": v for k, v in pair(gN, "B3d-Sa", best, rng, n_boot).items()}
|
||
row["pm_no_harm"] = bool(row["pm_best_ratio"] <= sp13.GUARD)
|
||
# degradation vs the P2r nominal cell (descriptive)
|
||
if len(ref):
|
||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||
for m in mean.index:
|
||
nm = nom[nom.method == m]
|
||
if len(nm):
|
||
row[f"degradation_{m}"] = float(mean[m] / nm.band_rmse.mean())
|
||
sm = smc[(smc.setting == f"{reg}__{name}") & (smc.n_train == N)] if len(smc) else pd.DataFrame()
|
||
if len(sm):
|
||
row |= {k: float(sm.iloc[0][k]) for k in ("sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence")}
|
||
row["wide"] = bool(row["sigma_post_ms"] >= 1.5)
|
||
cells.append(row)
|
||
if name in axes:
|
||
mean_ratio = float(np.nanmean(list(ratios.values()))) if ratios else float("nan")
|
||
verdict["S2-H2"]["pairs"][f"{reg}/{name}"] = {"mean_ratio_M2-Sa/B3d-Sa": mean_ratio, "ok": bool(mean_ratio <= sp13.GUARD),
|
||
"n_cells": len(ratios)}
|
||
tables["s2_cells"] = pd.DataFrame(cells)
|
||
h2a = pd.concat(h2a_rows, ignore_index=True) if h2a_rows else pd.DataFrame()
|
||
tables["s2_h2a"] = h2a
|
||
for axis, names in s["presets"].items():
|
||
l1 = names[0]
|
||
t = h2a[(h2a.regime == "R10") & (h2a.preset == l1) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||
per = {}
|
||
for reg in s["regimes"]:
|
||
for name in names:
|
||
tt = h2a[(h2a.regime == reg) & (h2a.preset == name) & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||
per[f"{reg}/{name}"] = {int(r.n_train): {"cell_pass": bool(r.cell_pass), "ratio": r.ratio, "ci": [r.ratio_lo, r.ratio_hi], "best": r.best}
|
||
for r in tt.itertuples()}
|
||
verdict["S2-H1"]["per_axis"][axis] = {"L1_R10_cells_pass": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()},
|
||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None,
|
||
"complete": bool(len(t) == 2 and (t.n_rid == len(p["grid"]["realizations"])).all()),
|
||
"all_cells": per}
|
||
verdict["S2-H1"]["axes_pass"] = [a for a, v in verdict["S2-H1"]["per_axis"].items() if v["pass"]]
|
||
verdict["S2-H1"]["pass_all_axes"] = bool(len(verdict["S2-H1"]["axes_pass"]) == len(s["presets"]))
|
||
pairs = verdict["S2-H2"]["pairs"]
|
||
expected = len(s["regimes"]) * sum(len(v) for v in s["presets"].values())
|
||
verdict["S2-H2"]["complete"] = bool(len(pairs) == expected)
|
||
verdict["S2-H2"]["pass"] = all(v["ok"] for v in pairs.values()) if len(pairs) == expected else None
|
||
tables["s2_degradation"] = tables["s2_cells"][[c for c in tables["s2_cells"].columns if c.startswith("degradation_") or c in ("regime", "preset", "axis", "level", "n_train")]] if len(cells) else pd.DataFrame()
|
||
return tables, verdict
|
||
|
||
|
||
# ---------------------------------------------------------------- S3
|
||
|
||
def s3(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||
_, run_b4, _ = load_study(p, root, "S3")
|
||
ref = p2r_runs(p)
|
||
if run_b4.empty or ref.empty:
|
||
return {}, {"available": False}
|
||
comp = POINT_TIES + list(p["studies"]["S3"]["methods"])
|
||
run = pd.concat([ref, run_b4], ignore_index=True)
|
||
rows, verdict = [], {"per_regime": {}}
|
||
for reg, g in run.groupby("regime"):
|
||
if "B3d-Sa" not in set(g.method):
|
||
continue
|
||
cells = h2a_cells(g, "B3d-Sa", comp, rng, n_boot)
|
||
if not len(cells):
|
||
continue
|
||
rows.append(cells.assign(regime=reg, flag=np.where(cells.c == 2, "unstable posterior", "")))
|
||
c1, c0 = cells[cells.c == 1], cells[cells.c == 0]
|
||
macro = c0.m2_band_rmse.mean() / c0.best_band_rmse.mean() if len(c0) else float("nan")
|
||
guard = bool(len(c0) == 2 and macro <= sp13.GUARD and (c0.ratio <= sp13.GUARD).all())
|
||
verdict["per_regime"][reg] = {"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}", "best_at_c1": {int(r.n_train): r.best for r in c1.itertuples()},
|
||
"zero_drift_macro_ratio": macro, "zero_drift_guard": guard,
|
||
"regime_pass": bool(len(c1) == 2 and c1.cell_pass.all() and guard),
|
||
"complete": bool((cells.n_rid == len(p["grid"]["realizations"])).all() and len(cells) == 6)}
|
||
tab = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||
h2a_regimes = ["R10", "R0", "Rm5"]
|
||
verdict["pass"] = verdict["per_regime"].get("R10", {}).get("regime_pass")
|
||
verdict["regimes_pass"] = [r for r in h2a_regimes if verdict["per_regime"].get(r, {}).get("regime_pass")]
|
||
table = run.groupby(["regime", "c", "n_train", "method"])["band_rmse"].mean().unstack("method").reset_index()
|
||
ctl = []
|
||
if "Ctl-GP" in set(run.method): # T2-1 (disclosed): control bank across the P2r grid
|
||
for (reg, c, N), g in run.groupby(["regime", "c", "n_train"]):
|
||
if "Ctl-GP" not in set(g.method):
|
||
continue
|
||
ctl.append({"regime": reg, "c": c, "n_train": N, "n_rid": g.rid.nunique(), "flag": "unstable posterior" if c == 2 else ""}
|
||
| {f"ctl_pm_{k}": v for k, v in pair(g, "Ctl-GP", "B3d-Sa", rng, n_boot).items()}
|
||
| {f"m2_ctl_{k}": v for k, v in pair(g, "M2-Sa", "Ctl-GP", rng, n_boot).items()}
|
||
| {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa", "B3d-Sa", rng, n_boot).items()})
|
||
ctl = pd.DataFrame(ctl)
|
||
if len(ctl) and {"m2_ctl_better", "ctl_pm_better"} <= set(ctl.columns):
|
||
verdict["T2-1"] = {"cells": int(len(ctl)), "m2_better_than_ctl": int(ctl.m2_ctl_better.sum()),
|
||
"m2_better_than_ctl_by_c": {f"c{c:g}": int(d.m2_ctl_better.sum()) for c, d in ctl.groupby("c")},
|
||
"ctl_better_than_pm": int(ctl.ctl_pm_better.sum())}
|
||
return {"s3_h2a": tab, "s3_table": table, "s3_control": ctl}, verdict
|
||
|
||
|
||
# ---------------------------------------------------------------- S4
|
||
|
||
def s4(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||
_, run, _ = load_study(p, root, "S4")
|
||
if run.empty:
|
||
return {}, {"available": False}
|
||
pt = [f"{m}-TCN" for m in POINT_TIES]
|
||
rows, verdict = [], {}
|
||
for reg, g in run.groupby("regime"):
|
||
cells = h2a_cells(g, "B3d-Sa-TCN", pt, rng, n_boot)
|
||
if len(cells):
|
||
rows.append(cells.assign(regime=reg))
|
||
h2a = pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()
|
||
t = h2a[(h2a.regime == "R10") & (h2a.c == 1)] if len(h2a) else pd.DataFrame()
|
||
verdict["S4-H1"] = {"cells": {int(r.n_train): bool(r.cell_pass) for r in t.itertuples()}, "ratios": {int(r.n_train): [r.ratio, r.ratio_lo, r.ratio_hi] for r in t.itertuples()},
|
||
"pass": bool(t.cell_pass.all()) if len(t) == 2 else None}
|
||
cells = []
|
||
ref = p2r_runs(p)
|
||
for (reg, N), g in run.groupby(["regime", "n_train"]):
|
||
mean = g.groupby("method")["band_rmse"].mean()
|
||
row = {"regime": reg, "c": 1.0, "n_train": N, "n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||
row |= {f"m2_pm_{k}": v for k, v in pair(g, "M2-Sa-TCN", "B3d-Sa-TCN", rng, n_boot).items()}
|
||
if len(ref):
|
||
nom = ref[(ref.regime == reg) & (ref.c == 1) & (ref.n_train == N)]
|
||
for m in mean.index:
|
||
nm = nom[nom.method == m.removesuffix("-TCN")]
|
||
if len(nm):
|
||
row[f"tcn_over_cnngru_{m.removesuffix('-TCN')}"] = float(mean[m] / nm.band_rmse.mean())
|
||
cells.append(row)
|
||
cells = pd.DataFrame(cells)
|
||
wide = cells[(cells.n_train == 16) & cells.regime.isin(["Rm5", "R0h"])]
|
||
verdict["S4-H2"] = {"cells": {r.regime: {"ratio": r.m2_pm_ratio, "ci": [r.m2_pm_ratio_lo, r.m2_pm_ratio_hi], "better": bool(r.m2_pm_better)} for r in wide.itertuples()},
|
||
"pass": bool(wide.m2_pm_better.all()) if len(wide) == 2 else None}
|
||
return {"s4_cells": cells, "s4_h2a": h2a}, verdict
|
||
|
||
|
||
# ---------------------------------------------------------------- S8
|
||
|
||
def cross_spectrum(Y: np.ndarray, P: np.ndarray) -> np.ndarray:
|
||
w = np.hanning(Y.shape[1])
|
||
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
|
||
Fp = np.fft.rfft((P - P.mean(1, keepdims=True)) * w, NFFT)
|
||
return np.real(np.conj(Fy) * Fp).sum(0)
|
||
|
||
|
||
def s8(p: dict, root: Path, rng, n_boot: int) -> tuple[dict, dict]:
|
||
rows_all, run, _ = load_study(p, root, "S8")
|
||
if run.empty:
|
||
return {}, {"available": False}
|
||
f = np.fft.rfftfreq(NFFT, 4.0 / 1000.0)
|
||
f_c = 6.0
|
||
budgets = study_budgets(p, "S8")
|
||
cells, transfer, verdict = [], [], {"S8-H1": {"cells": {}}, "S8-H2": {"cells": {}}}
|
||
for (reg, d, N), g in run.groupby(["regime", "delta_ms", "n_train"]):
|
||
mean = g.groupby("method")["band_rmse"].mean()
|
||
row = {"regime": reg, "delta_ms": d, "n_train": N, "n_rid": g.rid.nunique(), "n_seed": g.seed.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||
for a, b, tag in (("PM2", "Oracle", "pm_or"), ("BK2", "PM2", "bk_pm"), ("HM2", "PM2", "hm_pm"), ("BK2", "Oracle", "bk_or")):
|
||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items()}
|
||
# transfer Ĥ(f) relative to the Oracle predictions, pooled over rids, seeds and test wells
|
||
S = {m: np.zeros(len(f)) for m in ("Oracle", "PM2", "BK2", "HM2")}
|
||
for rid in sorted(g.rid.unique()):
|
||
cell = Cell("S8", reg, None, 1.0, int(N), int(rid), tuple(p["studies"]["S8"]["methods"]), posterior="none", delta_ms=float(d))
|
||
npz = train_paths(cell, root)["npz"]
|
||
if not npz.exists():
|
||
continue
|
||
with np.load(npz) as z:
|
||
Y = z["y_true"].astype(float)
|
||
for m in S:
|
||
for k in (k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu")):
|
||
S[m] += cross_spectrum(Y, z[k].astype(float))
|
||
band = f >= f_c
|
||
use = band & (S["Oracle"] >= 0.1 * S["Oracle"][band].max())
|
||
lo, hi = 1000.0 / (2 * d), 3000.0 / (2 * d)
|
||
flip = use & (f > lo) & (f < hi)
|
||
for m in ("PM2", "BK2", "HM2"):
|
||
H = S[m] / np.where(S["Oracle"] == 0, np.nan, S["Oracle"])
|
||
theory = np.cos(np.pi * f * d / 1000.0)
|
||
zero = f[band][np.flatnonzero(np.diff(np.sign(H[band])) != 0)[:1]]
|
||
transfer.append({"regime": reg, "delta_ms": d, "n_train": N, "method": m, "flip_band_hz": [lo, hi], "n_freq_flip": int(flip.sum()),
|
||
"mean_H_flip_band": float(np.nanmean(H[flip])) if flip.any() else float("nan"),
|
||
"mean_cos_flip_band": float(theory[flip].mean()) if flip.any() else float("nan"),
|
||
"first_zero_crossing_hz": float(zero[0]) if len(zero) else float("nan"), "theory_zero_hz": lo,
|
||
"H": H.tolist(), "f_hz": f.tolist()})
|
||
row[f"meanH_flip_{m}"] = transfer[-1]["mean_H_flip_band"]
|
||
cells.append(row)
|
||
if reg == "R10" and d == 32:
|
||
verdict["S8-H1"]["cells"][int(N)] = {"mean_H_PM2_flip_band": row["meanH_flip_PM2"], "negative": bool(row["meanH_flip_PM2"] < 0)}
|
||
if N == 16 and d in (16, 32):
|
||
verdict["S8-H2"]["cells"][f"{reg}/d{d:g}"] = {"ratio_BK2_PM2": row.get("bk_pm_ratio"), "ci": [row.get("bk_pm_ratio_lo"), row.get("bk_pm_ratio_hi")],
|
||
"better": bool(row.get("bk_pm_better", False))}
|
||
cells = pd.DataFrame(cells)
|
||
verdict["S8-H1"]["pass"] = all(v["negative"] for v in verdict["S8-H1"]["cells"].values()) if len(verdict["S8-H1"]["cells"]) == 2 else None
|
||
d8 = cells[cells.delta_ms == 8]
|
||
no_harm = float(d8.bk_pm_ratio.mean()) if len(d8) else float("nan")
|
||
verdict["S8-H2"]["no_harm_mean_ratio_d8"] = no_harm
|
||
verdict["S8-H2"]["pass"] = all(v["better"] for v in verdict["S8-H2"]["cells"].values()) if len(verdict["S8-H2"]["cells"]) == 4 else None
|
||
verdict["S8-H2"]["d8_descriptive"] = {f"{r.regime}/n{int(r.n_train)}": [r.bk_pm_ratio, r.bk_pm_ratio_lo, r.bk_pm_ratio_hi] for r in d8.itertuples()}
|
||
tr = pd.DataFrame(transfer)
|
||
return {"s8_cells": cells, "s8_transfer": tr.drop(columns=["H", "f_hz"]) if len(tr) else tr,
|
||
"s8_transfer_curves": tr}, verdict
|
||
|
||
|
||
# ---------------------------------------------------------------- equal-budget arm (disclosed, T2 v)
|
||
|
||
def equal_budget(p: dict, root: Path, rng, n_boot: int) -> pd.DataFrame:
|
||
arm = p["training"].get("equal_budget_arm")
|
||
if not arm:
|
||
return pd.DataFrame()
|
||
rows = []
|
||
for study in p["studies"]:
|
||
_, run, _ = load_study(p, root, study, arm=int(arm))
|
||
if run.empty:
|
||
continue
|
||
keys = [k for k in ("regime", "preset", "delta_ms", "c", "n_train") if k in run.columns]
|
||
for key, g in run.groupby(keys, dropna=False):
|
||
mean = g.groupby("method")["band_rmse"].mean()
|
||
row = {"study": study, "budget": int(arm)} | dict(zip(keys, key)) | {"n_rid": g.rid.nunique()} | {f"band_rmse_{m}": v for m, v in mean.items()}
|
||
sfx = "-TCN" if p["studies"][study].get("backbone", "cnngru") != "cnngru" else ""
|
||
for a, b, tag in ((f"M2-Sa{sfx}", f"B3d-Sa{sfx}", "m2_pm"), (f"B3d-Sa{sfx}", f"Oracle{sfx}", "pm_or"), ("Ctl-GP", f"B3d-Sa{sfx}", "ctl_pm"),
|
||
("BK2", "PM2", "bk_pm"), ("PM2", "Oracle", "pm2_or")):
|
||
if a in mean.index and b in mean.index:
|
||
row |= {f"{tag}_{k}": v for k, v in pair(g, a, b, rng, n_boot).items() if k in ("ratio", "ratio_lo", "ratio_hi", "better")}
|
||
rows.append(row)
|
||
return pd.DataFrame(rows)
|
||
|
||
|
||
# ---------------------------------------------------------------- report
|
||
|
||
def _md(df: pd.DataFrame, cols=None, fmt: str = ".3f") -> str:
|
||
if df is None or not len(df):
|
||
return "(no data)"
|
||
d = df[[c for c in cols if c in df.columns]] if cols else df
|
||
return d.to_markdown(index=False, floatfmt=fmt)
|
||
|
||
|
||
def summarize(p: dict, root: Path, n_boot: int = 2000, dev: bool = False, n_perm: int = 10000) -> dict:
|
||
global USE_P2R
|
||
USE_P2R = not dev
|
||
out = root / "summary"
|
||
out.mkdir(parents=True, exist_ok=True)
|
||
rng = np.random.default_rng(0)
|
||
tables, verdict = {}, {"protocol": "configs/protocol_bench.yaml", "dev": dev, "root": str(root)}
|
||
sha = REPO_ROOT / "configs" / "protocol_bench.sha256"
|
||
verdict["protocol_sha256"] = sha.read_text().split()[0] if sha.exists() else "UNLOCKED"
|
||
for name, fn, extra in (("S1", s1, (n_perm,)), ("S2", s2, ()), ("S3", s3, ()), ("S4", s4, ()), ("S8", s8, ())):
|
||
t, v = fn(p, root, rng, n_boot, *extra)
|
||
tables |= t
|
||
verdict[name] = v
|
||
tables["equal_budget"] = equal_budget(p, root, rng, n_boot)
|
||
for name, df in tables.items():
|
||
if name == "s8_transfer_curves":
|
||
(out / "s8_transfer_curves.json").write_text(df.to_json(orient="records"))
|
||
elif isinstance(df, pd.DataFrame):
|
||
df.to_csv(out / f"{name}.csv", index=False)
|
||
(out / "verdict.json").write_text(json.dumps(verdict, indent=1, default=float))
|
||
L = [f"# protocol_bench summary ({'DEV — never a result' if dev else 'main grid'})", "",
|
||
"Rules of configs/protocol_bench.yaml applied as written. Realizations and seeds as recorded per cell.", ""]
|
||
hyp = p["hypotheses"]
|
||
for key in ("S1-H1", "S1-H2", "S2-H1", "S2-H2", "S3-H1", "S4-H1", "S4-H2", "S8-H1", "S8-H2"):
|
||
v = verdict.get(key.split("-")[0], {})
|
||
v = v.get(key, v) if key != "S3-H1" else v
|
||
res = v.get("pass") if isinstance(v, dict) else None
|
||
L.append(f"- **{key}** ({hyp[key]['kind']}): {'PASS' if res else 'FAIL' if res is False else 'not available'} — {hyp[key]['statement'].strip()[:160]}…")
|
||
L.append("")
|
||
sections = [("S1 cells (phase diagram)", "s1_cells", ["regime", "c", "n_train", "sigma_post_ms", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "n_rid"]),
|
||
("S1 families (S1-H2)", "s1_families", None), ("S1 additivity (descriptive)", "s1_additivity", None),
|
||
("S2 SMC diagnostics", "s2_smc", ["regime", "preset", "axis", "level", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90", "overconfidence", "phase_R_mean", "kappa_post", "r_post", "n_rid"]),
|
||
("S2 cells", "s2_cells", ["regime", "preset", "axis", "level", "n_train", "best_point_tie", "pm_best_ratio", "pm_best_ratio_lo", "pm_best_ratio_hi", "pm_no_harm", "m2_pm_ratio", "m2_pm_ratio_lo", "m2_pm_ratio_hi", "m2_pm_better", "wide", "n_rid"]),
|
||
("S2 H2a rule per preset", "s2_h2a", ["regime", "preset", "axis", "level", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||
("S3 H2a rule with B4 competitors", "s3_h2a", ["regime", "c", "n_train", "best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass", "flag"]),
|
||
("S3 benchmark table (band RMSE)", "s3_table", None),
|
||
("S3 control bank across the P2r grid (T2-1, disclosed)", "s3_control", ["regime", "c", "n_train", "ctl_pm_ratio", "ctl_pm_ratio_lo", "ctl_pm_ratio_hi", "ctl_pm_better", "m2_ctl_ratio", "m2_ctl_ratio_lo", "m2_ctl_ratio_hi", "m2_ctl_better", "m2_pm_ratio", "flag", "n_rid"]),
|
||
("S4 cells (TCN)", "s4_cells", None), ("S4 H2a rule (TCN)", "s4_h2a", ["regime", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]),
|
||
("S8 cells", "s8_cells", ["regime", "delta_ms", "n_train", "pm_or_ratio", "bk_pm_ratio", "bk_pm_ratio_lo", "bk_pm_ratio_hi", "bk_pm_better", "hm_pm_ratio", "meanH_flip_PM2", "meanH_flip_BK2", "n_rid"]),
|
||
("S8 transfer", "s8_transfer", ["regime", "delta_ms", "n_train", "method", "n_freq_flip", "mean_H_flip_band", "mean_cos_flip_band", "first_zero_crossing_hz", "theory_zero_hz"]),
|
||
("Equal-budget arm, 500 iterations for every method (disclosed, T2 v; no rule uses it)", "equal_budget", None)]
|
||
for title, key, cols in sections:
|
||
L += [f"## {title}", "", _md(tables.get(key), cols), ""]
|
||
L += ["## Verdicts (json)", "", "```", json.dumps({k: v for k, v in verdict.items() if k.startswith("S")}, indent=1, default=float), "```", ""]
|
||
(out / "summary.md").write_text("\n".join(L))
|
||
print("\n".join(L[:14]))
|
||
return verdict
|