"""P2 summary per protocol_p2: gate G-B, v1 phase map, H1, H3, H4 and warp diagnostics. Reads each cell in outputs/p2//cells, so it can run before the grid is finished (the gate then records complete = false). A run is (realization, c, N, method, seed); a run's metric is the mean over the 8 test wells at the method's locked budget. 95% CIs are bootstrapped over realizations (each realization averaged over seeds); the cell's best competitor is held fixed during bootstrapping. python scripts/13_summarize_p2.py [--mode main|dev] [--n-boot 2000] → outputs/p2/summary//: gate_gb.json, cells.csv, methods.csv, h3.csv, h3.json, h4.json, warp.csv, h1.csv, summary.md figures outputs/figures/p2_{phase,band_lines,h3,h1}.png (dev mode: in the summary directory) """ from __future__ import annotations import argparse import importlib.util import json import math import re import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.patches import Rectangle from ml_porosity.eval import figstyle as fs from ml_porosity.eval.metrics import band_metrics, gaussian_metrics, point_metrics from ml_porosity.paths import REPO_ROOT, outputs_dir METRICS = ["rmse", "pcc", "low_rmse", "band_rmse", "band_pcc", "band_std_ratio", "nll", "crps", "mean_sigma", "coverage_50", "coverage_80", "coverage_90", "coverage_95"] LEVELS = (50, 80, 90, 95) # thresholds stated verbally in protocol_p2 (gates.G-B, hypotheses.H3, H4) RATIO_MAX, DPCC_MIN, GUARD, SEED_FRAC, N_FRAC = 0.90, 0.05, 1.02, 4 / 5, 3 / 4 H3_WIDTH, H4_WARP, H4_BAND = 1.2, 1.10, 1.02 RAMP4 = ["#86b6ef", "#5598e7", "#256abf", "#104281"] # 4-step ordinal ramp (σ of H1), validated 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 def parse_tag(stem: str) -> tuple[int, float, int]: rid, c, n = re.fullmatch(r"r(\d+)_c([\d.]+)_n(\d+)", stem).groups() return int(rid), float(c), int(n) def ce(d): """Calibration error: mean |coverage − nominal| over 50/80/90/95%.""" return sum(abs(d[f"coverage_{q}"] - q / 100) for q in LEVELS) / len(LEVELS) def boot(num: np.ndarray, den: np.ndarray | None, n_boot: int, rng) -> list[float]: """95% CI of mean(num)/mean(den) (den = None: of mean(num)) under resampling of realizations.""" idx = rng.integers(0, len(num), (n_boot, len(num))) s = num[idx].mean(1) if den is None else num[idx].mean(1) / den[idx].mean(1) return np.percentile(s, [2.5, 97.5]).tolist() def load_runs(cell_dir, budgets: dict) -> tuple[pd.DataFrame, pd.DataFrame]: files = sorted(f for f in cell_dir.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv")) df = pd.concat([pd.read_csv(f) for f in files], ignore_index=True) df = df[df["budget"] == df["method"].map(lambda m: budgets[m.removesuffix("-na")])] run = df.groupby(["rid", "c", "n_train", "method", "seed"], as_index=False)[METRICS].mean() diag = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in files], ignore_index=True) return run, diag # ---------------------------------------------------------------- G-B def improves(m2: pd.DataFrame, best: pd.DataFrame) -> pd.Series: return (m2["band_rmse"] <= RATIO_MAX * best["band_rmse"]) | (m2["band_pcc"] >= best["band_pcc"] + DPCC_MIN) def gate_gb(run: pd.DataFrame, P: dict, n_boot: int, rng) -> tuple[pd.DataFrame, dict]: G, grid = P["gates"]["G-B"], P["grid"] rows = [] for (c, N), d in run.groupby(["c", "n_train"]): mean = d.groupby("method")[["band_rmse", "band_pcc"]].mean() comp = mean.loc[mean.index.intersection(G["competitors"]), "band_rmse"].sort_values() best = comp.index[0] a = d[d.method == "M2"].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]] b = d[d.method == best].set_index(["rid", "seed"])[["band_rmse", "band_pcc"]].reindex(a.index) ok = b.notna().all(axis=1) a, b = a[ok], b[ok] imp = {lvl: improves(a.groupby(lvl).mean(), b.groupby(lvl).mean()) for lvl in ("seed", "rid")} ar, br = a.groupby("rid").mean(), b.groupby("rid").mean() n_s, n_r = len(imp["seed"]), len(imp["rid"]) rows.append({ "c": c, "n_train": N, "best": best, "runner_up": comp.index[1], "n_rid": n_r, "n_seed": n_s, "m2_band_rmse": a["band_rmse"].mean(), "best_band_rmse": b["band_rmse"].mean(), "ratio": a["band_rmse"].mean() / b["band_rmse"].mean(), **dict(zip(("ratio_lo", "ratio_hi"), boot(ar["band_rmse"].to_numpy(), br["band_rmse"].to_numpy(), n_boot, rng))), "dpcc": a["band_pcc"].mean() - b["band_pcc"].mean(), **dict(zip(("dpcc_lo", "dpcc_hi"), boot((ar["band_pcc"] - br["band_pcc"]).to_numpy(), None, n_boot, rng))), "seeds_improve": int(imp["seed"].sum()), "rids_improve": int(imp["rid"].sum()), "cell_pass": bool(imp["seed"].sum() >= math.ceil(SEED_FRAC * n_s - 1e-9) and imp["rid"].sum() > n_r / 2), "ratio_vs_B3b": a["band_rmse"].mean() / mean.loc["B3b", "band_rmse"], }) cells = pd.DataFrame(rows) real, zero = cells[cells.c == grid["realistic_drift"]], cells[cells.c == 0] need = math.ceil(N_FRAC * len(grid["n_train"]) - 1e-9) macro = zero.m2_band_rmse.mean() / zero.best_band_rmse.mean() if len(zero) else float("nan") guard = bool(len(zero) == len(grid["n_train"]) and macro <= GUARD and (zero.ratio <= GUARD).all()) complete = bool(len(cells) == len(grid["drift_factors"]) * len(grid["n_train"]) and (cells.n_rid == len(grid["realizations"])).all() and (cells.n_seed == len(grid["seeds"])).all()) verdict = { "complete": complete, "cells": len(cells), "realistic_cells_pass": f"{int(real.cell_pass.sum())}/{len(real)}", "realistic_pass": bool(real.cell_pass.sum() >= need), "zero_drift_macro_ratio": macro, "zero_drift_ratio_per_N": {int(r.n_train): r.ratio for r in zero.itertuples()}, "zero_drift_guard": guard, } verdict["pass"] = verdict["realistic_pass"] and guard return cells, verdict # ---------------------------------------------------------------- H3, H4, warp def h3_table(cell_dir, P: dict, budgets: dict, pairs=(("B5", "B3b"), ("M2-ens", "M2")), pattern=None) -> pd.DataFrame: """B5 / M2-ens: μ = mean of μ_s, σ² = mean of σ_s² + variance of μ_s over 5 seeds (from saved predictions). pairs: (ensemble name, method); pattern: defaults to the c = 1 cells.""" f_c, c1 = P["metrics"]["bands"]["f_c_hz"], P["grid"]["realistic_drift"] rows = [] for f in sorted(cell_dir.glob(pattern or f"r*_c{c1:g}_n*.npz")): rid, c, N = parse_tag(f.stem) z = np.load(f) yt = z["y_true"].astype(float) for name, m in pairs: ks = sorted(k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{budgets[m]}/mu")) if not ks: continue mu = np.stack([z[k] for k in ks]).astype(float) sg = np.stack([z[k[:-2] + "sigma"] for k in ks]).astype(float) mu_e, sg_e = mu.mean(0), np.sqrt((sg**2).mean(0) + mu.var(0)) per_well = [point_metrics(y, a) | band_metrics(y, a, f_c) | gaussian_metrics(y, a, s) for y, a, s in zip(yt, mu_e, sg_e)] rows.append({"rid": rid, "c": c, "n_train": N, "method": name, "members": len(ks)} | pd.DataFrame(per_well)[METRICS].mean().to_dict()) e = pd.DataFrame(rows) return e.assign(ce=ce(e)) def h3_verdict(e: pd.DataFrame, run: pd.DataFrame, P: dict, n_boot: int, rng) -> dict: def judge(d): m = d.groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean() a, b = m.loc["M2-ens"], m.loc["B5"] width = a.mean_sigma / b.mean_sigma return {"ce_m2ens": a.ce, "ce_b5": b.ce, "width_ratio": width, "nll_m2ens": a.nll, "nll_b5": b.nll, "crps_m2ens": a.crps, "crps_b5": b.crps, "reject_H3": bool(a.ce >= b.ce or (width > H3_WIDTH and a.nll >= b.nll and a.crps >= b.crps))} out = {"pooled": judge(e), "per_N": {int(N): judge(d) for N, d in e.groupby("n_train")}} per_rid = e.groupby(["method", "rid"])["ce"].mean() diff = (per_rid.loc["M2-ens"] - per_rid.loc["B5"]).to_numpy() out["pooled"] |= {"dce": float(diff.mean()), "dce_ci95": boot(diff, None, n_boot, rng)} s = run[(run.c == P["grid"]["realistic_drift"]) & run.method.isin(["B3b", "M2"])] out["single_model"] = s.assign(ce=ce(s)).groupby("method")[["ce", "mean_sigma", "nll", "crps"]].mean().to_dict("index") return out def h4(run: pd.DataFrame, diag: pd.DataFrame, n_boot: int, rng) -> dict: d = diag[(diag.c == 1) & (diag.n_train == 4)] if "no_anchor" not in set(d.variant): return {"available": False} w = d.groupby(["variant", "rid"])[["M1_warp_rmse_ms", "M2_warp_rmse_ms", "M1_warp_cov90", "M2_warp_cov90"]].mean() r = run[(run.c == 1) & (run.n_train == 4)].groupby(["method", "rid"])[["band_rmse", "band_pcc"]].mean() out = {"available": True} for m in ("M1", "M2"): wa, wn = w.loc["anchor", f"{m}_warp_rmse_ms"].to_numpy(), w.loc["no_anchor", f"{m}_warp_rmse_ms"].to_numpy() ba, bn = r.loc[m, "band_rmse"].to_numpy(), r.loc[f"{m}-na", "band_rmse"].to_numpy() out[m] = {"warp_rmse_anchor_ms": wa.mean(), "warp_rmse_no_anchor_ms": wn.mean(), "warp_ratio": wn.mean() / wa.mean(), "warp_ratio_ci95": boot(wn, wa, n_boot, rng), "warp_cov90_anchor": w.loc["anchor", f"{m}_warp_cov90"].mean(), "warp_cov90_no_anchor": w.loc["no_anchor", f"{m}_warp_cov90"].mean(), "band_rmse_anchor": ba.mean(), "band_rmse_no_anchor": bn.mean(), "band_ratio": bn.mean() / ba.mean(), "band_ratio_ci95": boot(bn, ba, n_boot, rng), "band_pcc_anchor": r.loc[m, "band_pcc"].mean(), "band_pcc_no_anchor": r.loc[f"{m}-na", "band_pcc"].mean()} out["reject_H4"] = bool(out["M2"]["warp_ratio"] <= H4_WARP and out["M2"]["band_ratio"] <= H4_BAND) return out def warp_table(diag: pd.DataFrame) -> pd.DataFrame: """Means per (variant, c, N): per-well warp error; phase, λ, τ_c and hyperparameters per registration run.""" cols = [c for c in diag.columns if c.endswith("_warp_rmse_ms")] + \ ["M1_warp_cov90", "M2_warp_cov90", "M2_warp_width90_ms", "n_anchor", "n_valid", "gamma", "ess", "ess_gamma1"] per_well = diag.groupby(["variant", "c", "n_train"])[cols].mean() reg = diag.drop_duplicates(["variant", "rid", "c", "n_train", "seed"]) per_reg = reg.groupby(["variant", "c", "n_train"]).agg( phase_zero=("phase", lambda p: float(np.mean(p == 0))), phase_within15=("phase", lambda p: float(np.mean(np.abs(p) <= 15))), lam=("lam", "mean"), tau_c=("tau_c", "mean"), m_g=("hyper_m_g", "mean"), sigma_g=("hyper_sigma_g", "mean"), ell_ms=("hyper_ell_ms", "mean"), at_bound=("hyper_at_bound", lambda s: float(s.notna().mean()))) return per_well.join(per_reg).reset_index() # ---------------------------------------------------------------- H1 def h1_summary(P: dict, s12) -> dict | None: d = outputs_dir() / "p2" / "h1" if not (d / "h1.json").exists(): return None h = json.loads((d / "h1.json").read_text()) res = pd.read_csv(d / "results.csv") tab = res.groupby(["rid", "seed", "sigma_ms"])[["rmse", "band_rmse", "band_pcc", "band_std_ratio"]].mean() \ .groupby("sigma_ms").mean() # cross-spectrum rebuilt from saved predictions to recover the frequencies used (same rule as scripts/12) and to check r(σ) z = np.load(d / "preds.npz") f, f_c = np.array(h["f_hz"]), P["metrics"]["bands"]["f_c_hz"] S = {} for k in z.files: rid, _, sg = k.split("/") if k.count("/") == 2 else (None, None, None) if sg is not None: S[float(sg[5:])] = S.get(float(sg[5:]), 0.0) + s12.cross_spectrum(z[f"{rid}/y_true"], z[k]) tf = s12.transfer(S, f, f_c) assert all(abs(tf["r"][sg] - h["r"][str(sg)]) < 1e-9 for sg in S), "rebuilt r(σ) differs from h1.json" use = {sg: (f >= f_c) & (np.array(tf["theory"][sg]) >= 0.1) & (S[0.0] >= 0.1 * S[0.0][f >= f_c].max()) for sg in S} tab["r"] = [h["r"][str(sg)] for sg in tab.index] tab["r_lo"], tab["r_hi"] = zip(*[h["r_ci95"][str(sg)] for sg in tab.index]) tab["n_freq"] = [h["n_freq"][str(sg)] for sg in tab.index] return {"json": h, "table": tab, "f": f, "use": use, "H": tf["H_hat"], "theory": tf["theory"]} # ---------------------------------------------------------------- figures def text_on(rgba) -> str: lum = 0.2126 * rgba[0] + 0.7152 * rgba[1] + 0.0722 * rgba[2] return fs.INK if lum > 0.55 else fs.SURFACE def plot_phase(cells: pd.DataFrame, verdict: dict, P: dict, path) -> None: fs.apply() cs, Ns = sorted(cells.c.unique()), sorted(cells.n_train.unique()) fig, axes = plt.subplots(1, 2, figsize=(13, 1.2 + 1.25 * len(cs)), layout="constrained") # leave room for colorbar labels panels = [("ratio", "(a) Band RMSE: M2 / best competitor", fs.diverging_norm(0.8, 1.0, 1.2), fs.DIVERGING, "{:.3f}", [RATIO_MAX, 1.0], "ratio (< 1: M2 better; threshold 0.90)"), ("dpcc", "(b) Band PCC: M2 − best competitor", fs.diverging_norm(-0.1, 0.0, 0.1), fs.DIVERGING.reversed(), "{:+.3f}", [0.0, DPCC_MIN], "difference (> 0: M2 better; threshold +0.05)")] ix = cells.set_index(["c", "n_train"]) for ax, (k, title, norm, cmap, fmt, ticks, clabel) in zip(axes, panels): Z = ix[k].unstack("n_train").reindex(index=cs, columns=Ns).to_numpy() im = ax.imshow(Z, cmap=cmap, norm=norm, origin="lower", aspect="auto") for i, c in enumerate(cs): for j, N in enumerate(Ns): if (c, N) not in ix.index: continue r = ix.loc[(c, N)] col = text_on(cmap(norm(r[k]))) ax.text(j, i + 0.2, fmt.format(r[k]), ha="center", va="center", fontsize=11, color=col) ax.text(j, i - 0.02, f"[{fmt.format(r[k + '_lo'])}, {fmt.format(r[k + '_hi'])}]", ha="center", va="center", fontsize=7, color=col) if k == "ratio": ax.text(j, i - 0.22, f"vs {r.best}", ha="center", va="center", fontsize=8, color=col) ax.text(j, i - 0.38, f"{'✓' if r.cell_pass else '✗'} {r.seeds_improve}/{r.n_seed} seed · " f"{r.rids_improve}/{r.n_rid} rz", ha="center", va="center", fontsize=6.5, color=col) c1 = P["grid"]["realistic_drift"] ax.set_xticks(range(len(Ns)), [str(n) for n in Ns]) ax.set_yticks(range(len(cs)), [f"{c:g}" + ("\n(realistic)" if c == c1 else "") for c in cs]) ax.set(xlabel="number of training wells N", ylabel="drift factor c (× F3 prior)", title=title) ax.grid(False) if c1 in cs: ax.add_patch(Rectangle((-0.5, cs.index(c1) - 0.5), len(Ns), 1, fill=False, ec=fs.INK, lw=1.6)) cb = fig.colorbar(im, ax=ax, shrink=0.9, extend="both", pad=0.1) for t in ticks: cb.ax.axhline(t, color=fs.INK, lw=1.0) cb.set_label(clabel, color=fs.INK2) cb.outline.set_visible(False) v = verdict head = (f"Gate G-B: {'PASS' if v['pass'] else 'FAIL'} — c = 1: {v['realistic_cells_pass']} cells pass (required ≥ 3/4); " f"c = 0: macro ratio {v['zero_drift_macro_ratio']:.3f} (required ≤ 1.02 both macro and per N) → " f"{'held' if v['zero_drift_guard'] else 'violated'}{'' if v['complete'] else ' · INCOMPLETE GRID'}") fig.suptitle(head, x=0.02, ha="left", fontsize=10, color=fs.INK) fig.text(0.02, -0.02, "Each cell: mean over 8 realizations × 5 seeds (8 test wells per run); [95% CI, bootstrap over realizations, " "competitor fixed]; ✓/✗: a cell passes if M2 improves (ratio ≤ 0.90 or PCC +0.05) in ≥ 4/5 seeds and > 1/2 of realizations (rz).", fontsize=7.5, color=fs.INK2) fig.savefig(path, dpi=150, bbox_inches="tight") plt.close(fig) def direct_labels(ax, items, x, gap_frac=0.08) -> None: """items: [(y, label)] at the right edge; spread vertically to avoid overlap, in ink colour.""" lo, hi = ax.get_ylim() items = sorted(items) ys = [items[0][0]] for y, _ in items[1:]: ys.append(max(y, ys[-1] + gap_frac * (hi - lo))) for (y0, t), y in zip(items, ys): ax.annotate(t, (x, y0), xytext=(x + 0.12, y), textcoords="data", fontsize=8, color=fs.INK2, va="center", annotation_clip=False) def plot_lines(run: pd.DataFrame, cells: pd.DataFrame, path, n_boot: int, rng) -> None: fs.apply() cs, Ns = sorted(run.c.unique()), sorted(run.n_train.unique()) per_rid = run.groupby(["c", "n_train", "method", "rid"])[["band_rmse", "band_pcc"]].mean() best = cells.set_index(["c", "n_train"])["best"] series = [("M2", fs.BLUE, "o", "-", "M2"), ("best", fs.ORANGE, "s", "-", "best competitor in cell"), ("B3b", fs.AQUA, "^", "-", "B3b (tie marker)"), ("Oracle", fs.MUTED, None, "--", "Oracle (true warp; upper bound)")] fig, axes = plt.subplots(2, len(Ns), figsize=(2.7 * len(Ns) + 1.2, 6.0), sharey="row", squeeze=False) for i, (k, ylab) in enumerate([("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC")]): for j, N in enumerate(Ns): ax = axes[i, j] ends = [] for name, col, mk, ls, lab in series: pts = [] for c in cs: m = best.get((c, N)) if name == "best" else name if m is None or (c, N, m) not in per_rid.index: continue v = per_rid.loc[(c, N, m), k].to_numpy() pts.append((c, v.mean(), *boot(v, None, n_boot, rng), m)) if not pts: continue x, y, lo, hi, who = zip(*pts) ax.plot(x, y, color=col, marker=mk, ls=ls, ms=5, lw=1.0 if name == "Oracle" else 1.5, label=lab, zorder=3 if name == "M2" else 2) if name != "Oracle": ax.vlines(x, lo, hi, color=col, lw=1.0, zorder=2) if name == "best": for xx, yy, ww in zip(x, y, who): ax.annotate(ww, (xx, yy), xytext=(0, -11 if i == 0 else 7), textcoords="offset points", ha="center", fontsize=6.5, color=fs.INK2) ends.append((y[-1], lab.split(" (")[0] if name != "best" else "best")) ax.axvspan(0.85, 1.15, color=fs.GRID, alpha=0.45, lw=0, zorder=0) ax.set_xticks(cs, [f"{c:g}" for c in cs]) ax.set_xlim(min(cs) - 0.15, max(cs) + 0.15) if i == 0: ax.set_title(f"N = {N} training wells") if i == 1: ax.set_xlabel("drift factor c") if j == 0: ax.set_ylabel(ylab) if j == len(Ns) - 1 and ends: direct_labels(ax, ends, max(cs)) h, l = axes[0, 0].get_legend_handles_labels() fig.legend(h, l, loc="upper left", ncol=4, bbox_to_anchor=(0.06, 1.02)) fig.text(0.06, -0.03, "Markers: mean over 8 realizations × 5 seeds; bars: 95% CI, bootstrap over realizations. " "Grey band: realistic drift (c = 1). Labels at orange squares: the competitor with the lowest band RMSE in the cell.", fontsize=7.5, color=fs.INK2) fig.tight_layout() fig.savefig(path, dpi=150, bbox_inches="tight") plt.close(fig) def plot_h3(e: pd.DataFrame, path) -> None: fs.apply() Ns = sorted(e.n_train.unique()) fig, axes = plt.subplots(1, len(Ns), figsize=(2.6 * len(Ns) + 1.0, 3.2), sharey=True, squeeze=False) nom = np.array(LEVELS) / 100 for ax, N in zip(axes[0], Ns): d = e[e.n_train == N].groupby("method")[[f"coverage_{q}" for q in LEVELS] + ["ce"]].mean() ax.plot([0.4, 1], [0.4, 1], color=fs.AXIS, lw=1.0, ls="--") for m, col, mk in (("M2-ens", fs.BLUE, "o"), ("B5", fs.ORANGE, "s")): if m in d.index: ax.plot(nom, d.loc[m].iloc[:4].to_numpy(), color=col, marker=mk, ms=5, label=m) ax.set(title=f"N = {N}", xlabel="nominal level", xlim=(0.4, 1.0), ylim=(0, 1.0)) ax.text(0.42, 0.95, "\n".join(f"CE {m}: {d.loc[m, 'ce']:.3f}" for m in ("M2-ens", "B5") if m in d.index), va="top", fontsize=7.5, color=fs.INK2) axes[0, 0].set_ylabel("empirical coverage") axes[0, 0].legend(loc="lower right") fig.suptitle("H3 (c = 1): coverage of central intervals, 5-seed ensemble; dashed: perfect calibration", x=0.02, ha="left", fontsize=10) fig.tight_layout() fig.savefig(path, dpi=150, bbox_inches="tight") plt.close(fig) def plot_h1(h1: dict, path) -> None: fs.apply() f, tab = h1["f"], h1["table"] fig, (ax, bx) = plt.subplots(1, 2, figsize=(11, 3.9), gridspec_kw={"width_ratios": [1.6, 1]}) sig = [s for s in sorted(h1["use"]) if s > 0] for s, col in zip(sig, RAMP4): th, H, u = np.array(h1["theory"][s]), np.array(h1["H"][s]), h1["use"][s] ax.plot(f, th, color=col, lw=1.0, ls="--") ax.plot(f[u], H[u], color=col, lw=1.8, marker="o", ms=2.5, label=f"σ = {s:g} ms") ax.annotate(f"σ = {s:g} ms", (f[u][-1], H[u][-1]), xytext=(5, 0), textcoords="offset points", va="center", fontsize=8, color=fs.INK2) ax.axvspan(0, 6, color=fs.GRID, alpha=0.6, lw=0) ax.text(3, -0.12, "< 6 Hz\nnot used", ha="center", fontsize=7, color=fs.INK2) ax.set(xlim=(0, 80), ylim=(-0.2, 1.3), xlabel="frequency (Hz)", ylabel="transfer function", title="(a) Estimated Ĥ(f) (solid, frequencies used) and exp(−2π²σ²f²) (dashed)") ax.legend(loc="upper right") s = tab.index[tab.index > 0] bx.axhspan(0.5, 2.0, color=fs.GRID, alpha=0.6, lw=0) bx.axhline(1.0, color=fs.AXIS, lw=1.0) bx.vlines(s, tab.loc[s, "r_lo"], tab.loc[s, "r_hi"], color=fs.BLUE, lw=1.5) bx.plot(s, tab.loc[s, "r"], "o", color=fs.BLUE, ms=6) for x, r, n in zip(s, tab.loc[s, "r"], tab.loc[s, "n_freq"]): bx.annotate(f"{r:.2f}\n{n} freq.", (x, r), xytext=(0, 9), textcoords="offset points", ha="center", va="bottom", fontsize=8, color=fs.INK2) bx.set_xscale("log", base=2) bx.set_yscale("log", base=2) bx.set_xticks(list(s), [f"{x:g}" for x in s]) bx.set_yticks([0.25, 0.5, 1, 2, 4], ["0.25", "0.5", "1", "2", "4"]) bx.set(xlim=(3, 50), ylim=(0.25, 4), xlabel="σ_δ (ms)", ylabel="r(σ) = geometric mean of Ĥ / theory", title="(b) r(σ), 95% CI over realizations; shaded: non-rejection region [0.5, 2]") rej = h1["json"]["reject_H1"] fig.suptitle(f"H1 (Prop 1, c = 0, N = 16, MSE): {'rejected' if rej else 'not rejected'}", x=0.02, ha="left", fontsize=10) fig.tight_layout() fig.savefig(path, dpi=150, bbox_inches="tight") plt.close(fig) # ---------------------------------------------------------------- markdown def md(df: pd.DataFrame, fmt: str = ".3f") -> str: return df.to_markdown(floatfmt=fmt) def write_md(path, P, verdict, cells, methods, h3j, h4j, warp, h1) -> None: c1 = P["grid"]["realistic_drift"] L = [f"# P2 summary (protocol {P['sha256'][:12]})", ""] L += [f"## Gate G-B: {'PASS' if verdict['pass'] else 'FAIL'}" + ("" if verdict["complete"] else " (incomplete grid)"), "", f"- c = {c1:g}: {verdict['realistic_cells_pass']} cells pass (required ≥ 3/4) → realistic_pass = {verdict['realistic_pass']}", f"- c = 0: macro ratio {verdict['zero_drift_macro_ratio']:.4f}, per N " f"{ {k: round(v, 4) for k, v in verdict['zero_drift_ratio_per_N'].items()} } → guard = {verdict['zero_drift_guard']}", ""] t = cells.set_index(["c", "n_train"])[["best", "runner_up", "ratio", "ratio_lo", "ratio_hi", "dpcc", "dpcc_lo", "dpcc_hi", "seeds_improve", "rids_improve", "cell_pass", "ratio_vs_B3b"]] L += [md(t), ""] for k, lab in (("band_rmse", "band RMSE (p.u.)"), ("band_pcc", "band PCC"), ("rmse", "total RMSE (p.u.)")): piv = methods.pivot_table(index="method", columns=["c", "n_train"], values=k) piv.columns = [f"c{c:g}/N{n}" for c, n in piv.columns] L += [f"### {lab} by method (mean over realizations × seeds)", "", md(piv), ""] if h3j: rows = {"pooled": h3j["pooled"]} | {f"N = {n}": v for n, v in h3j["per_N"].items()} L += [f"## H3: {'rejected' if h3j['pooled']['reject_H3'] else 'not rejected'} (pooled over all N at c = {c1:g})", "", md(pd.DataFrame(rows).T.drop(columns="dce_ci95", errors="ignore")), "", f"ΔCE (M2-ens − B5) = {h3j['pooled']['dce']:.4f}, 95% CI {np.round(h3j['pooled']['dce_ci95'], 4).tolist()}", "", "Single model (mean over 5 individual seeds):", "", md(pd.DataFrame(h3j["single_model"]).T), ""] if h4j.get("available"): L += [f"## H4: {'rejected' if h4j['reject_H4'] else 'not rejected'} (c = 1, N = 4)", "", md(pd.DataFrame({m: {k: (str(np.round(v, 3).tolist()) if isinstance(v, list) else v) for k, v in h4j[m].items()} for m in ("M1", "M2")}).T, ".3f"), ""] if h1 is not None: L += [f"## H1: {'rejected' if h1['json']['reject_H1'] else 'not rejected'} (budget MSE0 = {h1['json']['budget']})", "", md(h1["table"]), ""] L += ["## Warp diagnostics (means over training wells; phase/λ/hyperparameters per registration run)", "", md(warp.set_index(["variant", "c", "n_train"]).T, ".3f"), ""] path.write_text("\n".join(L)) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--mode", choices=["main", "dev"], default="main") ap.add_argument("--n-boot", type=int, default=2000) args = ap.parse_args() s11, s12 = load_script("11_run_d2.py"), load_script("12_h1_blur.py") P = s11.load_protocol(check=args.mode == "main") budgets = P["training"]["budgets"] cell_dir = outputs_dir() / "p2" / args.mode / "cells" out = outputs_dir() / "p2" / "summary" / args.mode out.mkdir(parents=True, exist_ok=True) figs = outputs_dir() / "figures" if args.mode == "main" else out rng = np.random.default_rng(0) run, diag = load_runs(cell_dir, budgets) methods = run.groupby(["c", "n_train", "method"])[METRICS].mean().reset_index() cells, verdict = gate_gb(run, P, args.n_boot, rng) e = h3_table(cell_dir, P, budgets) h3j = h3_verdict(e, run, P, args.n_boot, rng) if len(e) else None h4j = h4(run, diag, args.n_boot, rng) warp = warp_table(diag) h1 = h1_summary(P, s12) verdict |= {"protocol_sha256": P["sha256"][:12], "n_boot": args.n_boot} (out / "gate_gb.json").write_text(json.dumps(verdict, indent=1, ensure_ascii=False)) cells.to_csv(out / "cells.csv", index=False) methods.to_csv(out / "methods.csv", index=False) e.to_csv(out / "h3.csv", index=False) (out / "h3.json").write_text(json.dumps(h3j, indent=1, ensure_ascii=False, default=float)) (out / "h4.json").write_text(json.dumps(h4j, indent=1, ensure_ascii=False, default=float)) warp.to_csv(out / "warp.csv", index=False) if h1 is not None: h1["table"].to_csv(out / "h1.csv") plot_h1(h1, figs / "p2_h1.png") write_md(out / "summary.md", P, verdict, cells, methods, h3j, h4j, warp, h1) plot_phase(cells, verdict, P, figs / "p2_phase.png") plot_lines(run, cells, figs / "p2_band_lines.png", args.n_boot, rng) if len(e): plot_h3(e, figs / "p2_h3.png") print(json.dumps(verdict, indent=1, ensure_ascii=False)) print(cells[["c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "dpcc", "seeds_improve", "rids_improve", "cell_pass"]] .to_string(index=False, float_format="%.3f")) if h3j: print("H3:", {k: round(v, 4) if isinstance(v, float) else v for k, v in h3j["pooled"].items() if k != "dce_ci95"}) if h4j.get("available"): print("H4 rejected:", h4j["reject_H4"], {m: (round(h4j[m]["warp_ratio"], 3), round(h4j[m]["band_ratio"], 3)) for m in ("M1", "M2")}) if h1 is not None: print("H1:", h1["table"][["r", "r_lo", "r_hi", "n_freq"]].round(3).to_dict("index")) print("->", out) if __name__ == "__main__": main()