Summarize P6 benchmark, package it, write results, review proofs

- Benchmark summary: scripts/36_bench_verdicts.py applies the locked
  protocol_bench statements as worded (9/11 pass; S2-H1 fails for rock
  physics and wavelet phase), outside the lock hash.
- S7 packaging: scripts/37_bench_package.py, benchmark/ (manifest,
  reference tables, README, draft Zenodo metadata). Deposit not done.
- Paper: Experiment 3 (Sec. 6.5), T2 mechanism (Sec. 6.4), benchmark
  figures (scripts/38_bench_figures.py), dataset citations.
- Proof review of Sec. 4 and App. A (14 of 15 findings fixed, 1 partly;
  no verdict or reported number changed); docs/theory.md synced.
- Reproduction package: scripts/39_repro_package.py and repro/
  (manifest, README, clean-room verify report: 12/12 stages pass).
- Related work: preliminary novelty scan; full texts of AWSM, BootNet,
  Li et al. 2024, Guillon et al. 2020, Rizzuti et al. 2024/2025 and
  Castagna et al. 2026 checked; abstract-only markers updated and the
  Castagna sentence corrected. Paper compiles cleanly (68 pages).
- Docs synced (AGENTS.md, plan.md, report.html, READMEs).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-02 07:12:58 +00:00
parent 2e4f618947
commit 423a333ae9
40 changed files with 82893 additions and 170 deletions

View File

@@ -0,0 +1,149 @@
"""Final verdicts of protocol_bench (phase P6): the 11 pre-declared verdicts read exactly as their statements are worded.
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/36_bench_verdicts.py
Runs after `scripts/34_run_bench.py summarize` and never edits its outputs. The locked summary code
(ml_porosity/benchmark/summary.py) computes every cell correctly, but three verdict extractions differ from the
statements of configs/protocol_bench.yaml (found after the main runs, before any paper text used them):
S1-H1 the statement names N ∈ {4, 16}; the code requires exactly two R10 c = 1.5 rows, but S1 has four N values
(2, 4, 8, 16), so it returns pass = null. Here: the two rows N ∈ {4, 16} of s1_h2a.csv.
S2-H1 the code stores one verdict per axis (per_axis) and no top-level `pass`, so summary.md prints
"not available". Here: per axis from s2_h2a.csv (R10, preset *_L1, c = 1, N ∈ {4, 16}).
S3-H1 the statement fixes the competitors {B3b, B3c, B3c-R, B4a, B4b, B4c, B4d}; the code uses POINT_TIES + every
S3 method, which adds the disclosed control bank Ctl-GP (T2-1). Ctl-GP uses the posterior mean and
covariance, so it is not a point tie or an anchor-free baseline. Here: h2a_cells of the locked code with the
stated set (bootstrap rng 0, 2000 resamples, one generator per regime in the summary's regime order).
The other eight verdicts are copied from verdict.json. Both readings are written side by side; the as-run S3-H1
result (with Ctl-GP) stays reported. The lock is checked first (code, protocol, inputs).
→ outputs/bench/summary/verdict_final.json, verdict_final.md, s3_h2a_stated.csv
"""
from __future__ import annotations
import json
import numpy as np
import pandas as pd
from ml_porosity.benchmark import summary as S
from ml_porosity.benchmark.cells import bench_root
from ml_porosity.benchmark.protocol import freeze, load_protocol
S3_COMP = S.POINT_TIES + ["B4a", "B4b", "B4c", "B4d"]
H2A_REGIMES = ["R10", "R0", "Rm5"]
ORDER = ["S1-H1", "S1-H2", "S2-H1/rock_physics", "S2-H1/wavelet", "S2-H1/drift", "S2-H2", "S3-H1", "S4-H1", "S4-H2",
"S8-H1", "S8-H2"]
PRED_S2 = {"rock_physics": "pass", "wavelet": "pass (phase sub-axis wv_L1)", "drift": "uncertain"} # S2-H1.prediction
def _cell(r) -> dict:
return {"best": r.best, "ratio": float(r.ratio), "ci": [float(r.ratio_lo), float(r.ratio_hi)], "dpcc": float(r.dpcc),
"seeds_improve": int(r.seeds_improve), "rids_improve": int(r.rids_improve), "cell_pass": bool(r.cell_pass)}
def s1_h1(out, n_rid: int) -> dict:
t = pd.read_csv(out / "s1_h2a.csv")
t = t[(t.regime == "R10") & (t.c == 1.5) & t.n_train.isin([4, 16])]
ok = len(t) == 2 and bool((t.n_rid == n_rid).all())
return {"cells": {int(r.n_train): _cell(r) for r in t.itertuples()}, "complete": ok,
"pass": bool(t.cell_pass.all()) if ok else None}
def s2_h1(out, n_rid: int) -> dict:
t = pd.read_csv(out / "s2_h2a.csv")
t = t[(t.regime == "R10") & t.preset.str.endswith("_L1") & (t.c == 1) & t.n_train.isin([4, 16])]
res = {}
for axis, g in t.groupby("axis"):
ok = len(g) == 2 and bool((g.n_rid == n_rid).all())
res[axis] = {"preset": g.preset.iloc[0], "cells": {int(r.n_train): _cell(r) for r in g.itertuples()},
"complete": ok, "pass": bool(g.cell_pass.all()) if ok else None}
return res
def s3_h1(p: dict, n_boot: int) -> tuple[dict, pd.DataFrame]:
_, run_b4, _ = S.load_study(p, bench_root(dev=False), "S3")
run = pd.concat([S.p2r_runs(p), run_b4], ignore_index=True)
assert set(S3_COMP) <= set(run.method), sorted(run.method.unique())
rows, per = [], {}
for reg, g in run.groupby("regime"):
cells = S.h2a_cells(g, "B3d-Sa", S3_COMP, np.random.default_rng(0), n_boot)
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 = float(c0.m2_band_rmse.mean() / c0.best_band_rmse.mean())
guard = bool(len(c0) == 2 and macro <= S.sp13.GUARD and (c0.ratio <= S.sp13.GUARD).all())
per[reg] = {"c1_cells": {int(r.n_train): _cell(r) for r in c1.itertuples()},
"zero_drift_ratios": {int(r.n_train): float(r.ratio) for r in c0.itertuples()},
"zero_drift_macro_ratio": macro, "zero_drift_guard": guard,
"regime_pass": bool(len(c1) == 2 and c1.cell_pass.all() and guard),
"b4_best_anywhere": sorted({f"c{r.c:g}/N{r.n_train}:{r.best}" for r in cells.itertuples() if r.best.startswith("B4")}),
"complete": bool(len(cells) == 6 and (cells.n_rid == len(p["grid"]["realizations"])).all())}
v = {"competitors": S3_COMP, "per_regime": per, "pass": per.get("R10", {}).get("regime_pass"),
"regimes_pass": [r for r in H2A_REGIMES if per.get(r, {}).get("regime_pass")]}
return v, pd.concat(rows, ignore_index=True)
def main() -> None:
freeze(check=True)
p = load_protocol()
out = bench_root(dev=False) / "summary"
raw = json.loads((out / "verdict.json").read_text())
n_rid, n_boot = len(p["grid"]["realizations"]), 2000
s3, s3_tab = s3_h1(p, n_boot)
s3_tab.to_csv(out / "s3_h2a_stated.csv", index=False)
s2 = s2_h1(out, n_rid)
as_run = {"S1-H1": raw["S1"]["S1-H1"].get("pass"), "S1-H2": raw["S1"]["S1-H2"]["pass"],
**{f"S2-H1/{a}": raw["S2"]["S2-H1"]["per_axis"][a]["pass"] for a in ("rock_physics", "wavelet", "drift")},
"S2-H2": raw["S2"]["S2-H2"]["pass"], "S3-H1": raw["S3"]["pass"], "S4-H1": raw["S4"]["S4-H1"]["pass"],
"S4-H2": raw["S4"]["S4-H2"]["pass"], "S8-H1": raw["S8"]["S8-H1"]["pass"], "S8-H2": raw["S8"]["S8-H2"]["pass"]}
detail = {"S1-H1": s1_h1(out, n_rid), "S1-H2": raw["S1"]["S1-H2"],
**{f"S2-H1/{a}": s2[a] for a in ("rock_physics", "wavelet", "drift")},
"S2-H2": raw["S2"]["S2-H2"], "S3-H1": s3, "S4-H1": raw["S4"]["S4-H1"], "S4-H2": raw["S4"]["S4-H2"],
"S8-H1": raw["S8"]["S8-H1"], "S8-H2": raw["S8"]["S8-H2"]}
final = {k: detail[k]["pass"] for k in ORDER}
for a in ("rock_physics", "wavelet", "drift"): # the per-axis extraction of the code is correct
assert final[f"S2-H1/{a}"] == as_run[f"S2-H1/{a}"], a
note = {"S1-H1": "code filter: exactly 2 rows at R10 c = 1.5 (S1 has N = 2, 4, 8, 16) → null; statement: N ∈ {4, 16}",
"S3-H1": "code competitors include Ctl-GP (POINT_TIES + S3 methods); statement: {B3b, B3c, B3c-R, B4a–d}"}
verdict = {"protocol_sha256": raw["protocol_sha256"], "source": "outputs/bench/summary/verdict.json (scripts/34 summarize)",
"final": final, "as_run": as_run, "differences": note, "detail": detail,
"passed": [k for k in ORDER if final[k]], "failed": [k for k in ORDER if final[k] is False],
"S2_axes_pass": [a for a in ("rock_physics", "wavelet", "drift") if final[f"S2-H1/{a}"]]}
(out / "verdict_final.json").write_text(json.dumps(verdict, indent=1, default=float))
hyp = p["hypotheses"]
fmt = lambda x: "PASS" if x else "FAIL" if x is False else "null"
L = ["# protocol_bench final verdicts (scripts/36_bench_verdicts.py)", "",
f"Protocol sha256 {raw['protocol_sha256'][:12]}…; lock checked. Statements of configs/protocol_bench.yaml applied as "
"written; `as run` is verdict.json of scripts/34 summarize (locked code). No family-wise correction (11 verdicts).", "",
"| verdict | final | as run | prediction | note |", "|---|---|---|---|---|"]
for k in ORDER:
pred = PRED_S2[k.split("/")[1]] if k.startswith("S2-H1") else str(hyp[k]["prediction"]).split(";")[0].strip()
L.append(f"| {k} | **{fmt(final[k])}** | {fmt(as_run[k])} | {pred} | {note.get(k, '')} |")
L += ["", "## S1-H1 (R10, c = 1.5)", ""]
L += [f"- N = {n}: best {c['best']}, ratio {c['ratio']:.3f} [{c['ci'][0]:.3f}, {c['ci'][1]:.3f}], ΔPCC {c['dpcc']:+.3f}, "
f"seeds {c['seeds_improve']}/5, rids {c['rids_improve']}/{n_rid}, cell_pass {c['cell_pass']}" for n, c in detail["S1-H1"]["cells"].items()]
L += ["", "## S2-H1 per axis (R10, L1, c = 1)", ""]
for a in ("rock_physics", "wavelet", "drift"):
d = detail[f"S2-H1/{a}"]
L += [f"- {a} ({d['preset']}), N = {n}: best {c['best']}, ratio {c['ratio']:.3f} [{c['ci'][0]:.3f}, {c['ci'][1]:.3f}], "
f"ΔPCC {c['dpcc']:+.3f}, seeds {c['seeds_improve']}/5, rids {c['rids_improve']}/{n_rid} → {fmt(c['cell_pass'])}"
for n, c in d["cells"].items()]
L += ["", "## S3-H1 with the stated competitors", "", "| regime | c = 1, N = 4 | c = 1, N = 16 | c = 0 guard (macro) | regime | B4 best in |",
"|---|---|---|---|---|---|"]
for reg, d in s3["per_regime"].items():
cc = [f"{d['c1_cells'][n]['ratio']:.3f} ({d['c1_cells'][n]['best']}) {fmt(d['c1_cells'][n]['cell_pass'])}" for n in (4, 16)]
L.append(f"| {reg} | {cc[0]} | {cc[1]} | {fmt(d['zero_drift_guard'])} ({d['zero_drift_macro_ratio']:.3f}) | "
f"{fmt(d['regime_pass'])} | {', '.join(d['b4_best_anywhere']) or '—'} |")
r = raw["S3"]["per_regime"]
L += ["", f"As run (with Ctl-GP): best at c = 1 is Ctl-GP in {sum(v['best_at_c1'] == {'4': 'Ctl-GP', '16': 'Ctl-GP'} for v in r.values())}/{len(r)} "
f"regimes; R10 zero-drift macro ratio {r['R10']['zero_drift_macro_ratio']:.4f} → regime fail. Kept as a disclosed reading "
"(see T2-1 in verdict.json).", ""]
(out / "verdict_final.md").write_text("\n".join(L))
print("\n".join(L))
if __name__ == "__main__":
main()