Files
ML-Porosity/scripts/51_gp_review.py
lamlvh 1985fcfa02 Complete GP manuscript checks and verify revision artifacts
Move the comparator definitions and core evidence into the main text and
lead with effect sizes and intervals. Preserve the locked verdicts and
record the independent GP-D referee report.

Archive the saved GP results and regenerate 43 outputs in the clean
room. Add a source-backed numerical guard for the submission and
record the correction to anchor warp RMSE and the scope of the pooled
blind-well power estimates.

Co-Authored-By: Codex <noreply@openai.com>
2026-11-18 04:08:10 +00:00

1029 lines
62 KiB
Python

"""GP review, Phase 2 (exploratory, post hoc): analyses A1-A9 on existing outputs.
Declared in docs/research/gp-review-analyses.md before any of these quantities was computed; its SHA-256 is in
docs/research/gp-review-analyses.sha256 and this script refuses to run if the declaration differs. Outside every
locked protocol and the reproduction archives; reads outputs/ only and writes outputs/gp_review/a{1..9}/ and
outputs/gp_review/a_results.md (deviations from the declaration are listed at the top of that file).
Stages (each skipped when its output exists, unless --force):
a1 point ties against the Oracle (warp RMSE from a rebuilt cell; band RMSE; ratios with three intervals)
a2 equal-budget evidence reported as is (outputs/lambda_limit/)
a3 predicted vs measured transfer, and the declared E3 rule
a4 signal band: spectra, 6-25 Hz error, share of the gain kept
a5 truth-free checks on the nominal cell, the S2 presets and F3
a6 blind-well power, collated
a7 field cases per well
a8 Figure 4b aggregation (pooled MSE vs mean per-well RMSE)
a9 Gaussian-bank count against outputs/t2/ and Figure 3
The cell rebuilds (a1, a3, a4) share one CPU job per (regime, realization, c, N), cached in a3/cells/ (realizations
8-15) and a1/cells_rep/ (16-23).
scripts/run_gp_review.sh a --stage all --workers 4
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import math
import os
import re
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
from pathlib import Path
import numpy as np
import pandas as pd
from ml_porosity.paths import REPO_ROOT, outputs_dir
DECL = REPO_ROOT / "docs" / "research" / "gp-review-analyses.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "gp-review-analyses.sha256"
OUT = outputs_dir() / "gp_review"
P2R = outputs_dir() / "p2r"
REP = outputs_dir() / "replication"
PT = outputs_dir() / "point_tie"
BENCH = outputs_dir() / "bench"
RIDS, RIDS_REP, SEEDS = list(range(8, 16)), list(range(16, 24)), [0, 1, 2, 3, 4]
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
BUDGET = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250,
"SMC-MAP": 250, "Anchor-LS": 250}
TIES = ["B3b", "B3c", "B3c-R"]
A1_METHODS = ["Oracle", "B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "SMC-MAP", "Anchor-LS"]
A3_METHODS = ["B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "M2-Sa"]
PRED_METHODS = ["Oracle", "B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "M2-Sa"]
A1_CELLS = [(r, c, n) for r in ("R10", "R0", "Rm5") for c in (0.0, 1.0) for n in (4, 16)]
A3_CELLS = [(r, c, n) for r in REGIMES for c in (0.0, 1.0, 2.0) for n in (4, 16)]
PRESETS = ["rp_L1", "rp_L2", "wv_L1", "wv_L2", "wv_Q", "dr_L1", "dr_L2"]
L, DT = 126, 4.0
FREQ = np.fft.rfftfreq(L, DT / 1000.0)
A3_BINS = np.flatnonzero((FREQ >= 6.8) & (FREQ <= 22.5))
KSTAR = int(A3_BINS[-1])
HANN = np.hanning(L)
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
t2 = load_script("32_t2_mechanism.py")
ci = load_script("43_referee_r5_ci.py")
run_d2 = t2.run_d2
def check_declaration() -> str:
expected = DECL_HASH.read_text().split()[0]
actual = hashlib.sha256(DECL.read_bytes()).hexdigest()
if actual != expected:
raise SystemExit(f"{DECL.name} differs from its recorded SHA-256 ({actual[:12]} != {expected[:12]})")
return actual
def set_threads(n: int = 2) -> None:
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ.setdefault(k, str(n))
def run_pool(fn, jobs, workers: int, label: str) -> None:
print(f"{label}: {len(jobs)} jobs, {workers} workers", flush=True)
if not jobs:
return
t0 = time.time()
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(fn, j): j for j in jobs}
for i, f in enumerate(as_completed(futs), 1):
stem, dt = f.result()
print(f"[{i}/{len(jobs)}] {stem} done ({dt:.0f} s; total {time.time() - t0:.0f} s)", flush=True)
def side(r: dict, m: str = "pct") -> str:
return "below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains")
def spec(x: np.ndarray) -> np.ndarray:
"""rfft of the mean-removed, Hann-tapered series (last axis, 126 samples)."""
x = np.asarray(x, float)
return np.fft.rfft((x - x.mean(-1, keepdims=True)) * HANN, axis=-1)
def md(df: pd.DataFrame, nd: int = 3) -> str:
return df.to_markdown(index=False, floatfmt=f".{nd}f")
# ----------------------------------------------------------------------------------------------------------------
# cell job (a1, a3, a4): rebuild the cell with the registration, record the tie warps, label time errors, transfer
# sums and spectra
# ----------------------------------------------------------------------------------------------------------------
def cell_job(job) -> tuple[str, float]:
regime, rid, c, N, rep, out_file, P = job
set_threads(2)
t0 = time.time()
import ml_porosity.registration.pipeline as pl
from ml_porosity.registration.labels import invert_warps
from ml_porosity.registration.ties import warp_errors
if rep:
t2.P2R = REP
rec = {"B3c": [], "B3d": []}
orig_c, orig_m = pl.tie_b3c, pl.warp_mean
def rc(*a, **k):
r = orig_c(*a, **k)
rec["B3c"].append(np.array(r, copy=True))
return r
def rm(*a, **k):
r = orig_m(*a, **k)
rec["B3d"].append(np.array(r, copy=True))
return r
pl.tie_b3c, pl.warp_mean = rc, rm
try:
cell = t2.build_cell(regime, rid, c, N, P, with_register=True)
finally:
pl.tie_b3c, pl.warp_mean = orig_c, orig_m
R, out, wells = cell["R"], cell["out"], cell["wells"]
if len(rec["B3c"]) != N or len(rec["B3d"]) != N:
raise RuntimeError(f"recorder caught {len(rec['B3c'])}/{len(rec['B3d'])} warps for N = {N}")
if len(R.t_main) != L:
raise RuntimeError("main window is not 126 samples")
base = (REP if rep else P2R) / "train" / regime / "cells"
stem = f"r{rid}_c{c:g}_n{N}"
dg = pd.read_csv(base / f"{stem}_diag.csv")
res = {"regime": regime, "rid": rid, "c": c, "n_train": N, "warp": {}, "check": {}, "hpred_s": {}, "hpred_n": {},
"delta_rms": {}}
f_ms = FREQ * 1e-3
for i, w in enumerate(wells):
o = w["o"]
warps = {"B3b": w["t_b3b"][None], "B3c": rec["B3c"][i][None], "B3c-R": w["t3c"][None], "B3d": rec["B3d"][i][None],
"B3d-Sa": w["tm"][None], "M2-Sa": w["Tf"][w["sub"]][w["ok"]]}
d = out["diag"][i]
if d["well"] != o["name"]:
raise RuntimeError("well order differs between register and build_cell")
drow = dg[dg.well == o["name"]].iloc[0]
for m in ("B3b", "B3c", "B3c-R", "B3d", "B3d-Sa"):
e = warp_errors(warps[m], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
res["warp"].setdefault(m, []).append(e)
ref = d[f"{m}_warp_rmse_ms"] if m in ("B3b", "B3c", "B3d") else drow[f"{m}_warp_rmse_ms"]
res["check"][m] = max(res["check"].get(m, 0.0), abs(e - float(ref)))
if rep:
continue
for m in A3_METHODS:
tau_m = invert_warps(warps[m], R.tau_fine, R.t_main) # (S, 126)
t_true = np.interp(tau_m, R.tau_fine, o["t_of_tau_true"])
t_true[~np.isfinite(tau_m)] = np.nan
delta = t_true - R.t_main[None] # ms
cosk = np.cos(2 * np.pi * f_ms[:, None, None] * delta[None]) # (F, S, 126)
per_t = np.nanmean(cosk, axis=1) # member mean per sample
fin = np.isfinite(per_t[0])
res["hpred_s"].setdefault(m, np.zeros(len(FREQ)))
res["hpred_s"][m] = res["hpred_s"][m] + per_t[:, fin].sum(1)
res["hpred_n"][m] = res["hpred_n"].get(m, 0) + int(fin.sum())
res["delta_rms"].setdefault(m, []).append(float(np.sqrt(np.nanmean(delta ** 2))))
res["warp"] = {m: list(map(float, v)) for m, v in res["warp"].items()}
if not rep:
res["hpred_s"] = {m: v.tolist() for m, v in res["hpred_s"].items()}
z = np.load(base / f"{stem}.npz")
y = np.asarray(z["y_true"], float) # (8, 126), p.u.
Y = spec(y)
res["cross"], res["amp"], res["band625"], res["bandcheck"] = {}, {}, [], 0.0
res["amp"]["label"] = np.abs(Y).mean(0).tolist()
seis = np.stack([o["seis"][o["seis"].shape[0] // 2][R.main].astype(float) for o in cell["test"]])
res["amp"]["seismic"] = np.abs(spec(seis)).mean(0).tolist()
from ml_porosity.eval.metrics import split_bands
cells_csv = pd.read_csv(base / f"{stem}.csv")
for m in PRED_METHODS:
b = BUDGET[m]
mus = np.stack([np.asarray(z[f"{m}/s{s}/b{b}/mu"], float) for s in SEEDS]) # (5, 8, 126)
Mh = spec(mus)
res["cross"][m] = np.real(Mh * np.conj(Y)[None]).sum((0, 1)).tolist()
res["amp"][m] = np.abs(Mh).mean((0, 1)).tolist()
for s in SEEDS:
for j in range(len(y)):
e = mus[s, j] - y[j]
high = e - split_bands(e, 6.0)[0]
e625 = split_bands(high, 25.0)[0]
res["band625"].append({"seed": s, "well": j, "method": m,
"band625_rmse": float(np.sqrt(np.mean(e625 ** 2))),
"band_rmse": float(np.sqrt(np.mean(high ** 2)))})
# reproduction check: band RMSE from the saved predictions vs the cell CSV
cc = cells_csv[(cells_csv.method == m) & (cells_csv.budget == b)].sort_values(["seed", "test_well"])
mine = pd.DataFrame([r for r in res["band625"] if r["method"] == m]).sort_values(["seed", "well"])
res["bandcheck"] = max(res["bandcheck"], float(np.max(np.abs(cc.band_rmse.to_numpy() - mine.band_rmse.to_numpy()))))
out_file.parent.mkdir(parents=True, exist_ok=True)
out_file.write_text(json.dumps(res))
return f"{regime}_{stem}", time.time() - t0
def cell_jobs(force: bool) -> None:
P = run_d2.load_protocol(check=True)
jobs = []
for regime, c, N in A3_CELLS:
for rid in RIDS:
f = OUT / "a3" / "cells" / f"{regime}_r{rid}_c{c:g}_n{N}.json"
if force or not f.exists():
jobs.append((regime, rid, c, N, False, f, P))
for regime, c, N in A1_CELLS:
for rid in RIDS_REP:
if not (REP / "train" / regime / "cells" / f"r{rid}_c{c:g}_n{N}.csv").exists():
continue
f = OUT / "a1" / "cells_rep" / f"{regime}_r{rid}_c{c:g}_n{N}.json"
if force or not f.exists():
jobs.append((regime, rid, c, N, True, f, P))
return jobs
def load_cells(rep: bool) -> dict:
d = OUT / "a1" / "cells_rep" if rep else OUT / "a3" / "cells"
return {(j["regime"], j["rid"], float(j["c"]), j["n_train"]): j
for j in (json.loads(f.read_text()) for f in sorted(d.glob("*.json")))}
# ----------------------------------------------------------------------------------------------------------------
# run tables
# ----------------------------------------------------------------------------------------------------------------
def p2r_cell_rows(regime: str, c: float, N: int, rep: bool) -> pd.DataFrame:
base = (REP if rep else P2R) / "train" / regime / "cells"
rids = RIDS_REP if rep else RIDS
fs = [base / f"r{rid}_c{c:g}_n{N}.csv" for rid in rids]
d = pd.concat([pd.read_csv(f) for f in fs if f.exists()], ignore_index=True)
d = d[d.method.map(BUDGET).notna()]
return d[d.budget == d.method.map(BUDGET)]
def arm_rows(regime: str, c: float, N: int, rep: bool) -> tuple[pd.DataFrame, pd.DataFrame]:
rids = RIDS_REP if rep else RIDS
base = REP / "arms" if rep else PT / "cells"
fs = [base / f"{regime}_r{rid}_c{c:g}_n{N}.csv" for rid in rids]
fs = [f for f in fs if f.exists()]
if not fs:
return pd.DataFrame(), pd.DataFrame()
d = pd.concat([pd.read_csv(f) for f in fs], ignore_index=True)
d = d[d.method.isin(["SMC-MAP", "Anchor-LS"]) & (d.budget == 250)]
g = pd.concat([pd.read_csv(f.with_name(f.stem + "_diag.csv")) for f in fs], ignore_index=True)
return d, g
def extra_arm_rows(regime: str, c: float, N: int, rep: bool) -> tuple[pd.DataFrame, dict]:
"""E2 (B3p) and E4 (SMC-opt) rows if their outputs exist at run time."""
rows, warp = [], {}
rids = set(RIDS_REP if rep else RIDS)
e2 = OUT / "e2" / ("train_rep" if rep else "train_p2r")
e4 = OUT / "e4" / "cells"
for name, root, col in (("B3p", e2, "B3p_warp_rmse_ms"), ("SMC-opt", e4, "SMC-opt_warp_rmse_ms")):
if not root.exists():
continue
for f in sorted(root.rglob("*.csv")):
if f.name.endswith("_diag.csv"):
continue
d = pd.read_csv(f)
if not {"rid", "c", "n_train", "method", "seed", "band_rmse"} <= set(d.columns):
continue
reg = d.regime.iloc[0] if "regime" in d.columns else (f.parent.parent.name if f.parent.name == "cells" else f.stem.split("_r")[0])
d = d[(d.method == name) & d.rid.isin(rids) & (d.c == c) & (d.n_train == N)]
if reg != regime or d.empty:
continue
if "budget" in d.columns and d.budget.nunique() > 1:
b = json.loads((OUT / "e2" / "budget.json").read_text())["B3p"] if name == "B3p" and (OUT / "e2" / "budget.json").exists() else 250
d = d[d.budget == b]
rows.append(d.assign(regime=regime))
g = f.with_name(f.stem + "_diag.csv")
if g.exists():
gg = pd.read_csv(g)
if col in gg.columns:
warp.setdefault(name, {})[int(d.rid.iloc[0])] = float(gg[col].mean())
return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()), warp
# ----------------------------------------------------------------------------------------------------------------
# A1
# ----------------------------------------------------------------------------------------------------------------
def stage_a1(reproduce_original: bool = False) -> list[str]:
rng = np.random.default_rng(0)
rows, checks, extra_seen = [], [], set()
for rep in (False, True):
cells = load_cells(rep)
for regime, c, N in A1_CELLS:
run = p2r_cell_rows(regime, c, N, rep)
arms, adiag = arm_rows(regime, c, N, rep)
# The original A1 aggregation preceded E2 and all but one complete E4 cell.
if not reproduce_original or (not rep and (regime, c, N) == ("R10", 0, 16)):
ex, exw = extra_arm_rows(regime, c, N, rep)
if reproduce_original:
ex = ex[ex.method == "SMC-opt"]
exw = {"SMC-opt": exw["SMC-opt"]}
else:
ex, exw = pd.DataFrame(), {}
rids = sorted(set(run.rid))
have = [k for k in ((regime, r, c, N) for r in rids) if k in cells]
if not len(run) or not have:
continue
if len(arms):
arms = arms[arms.rid.isin(rids)]
allrun = pd.concat([run, arms] + ([ex] if len(ex) else []), ignore_index=True)
means = {m: ci.per_rid(allrun, m).mean() for m in TIES}
best = min(means, key=means.get)
warp = {m: np.mean([np.mean(cells[k]["warp"][m]) for k in have]) for m in ("B3b", "B3c", "B3c-R", "B3d", "B3d-Sa")}
warp["Oracle"] = 0.0
for m, col in (("SMC-MAP", "SMC-MAP_warp_rmse_ms"), ("Anchor-LS", "Anchor-LS_warp_rmse_ms")):
if len(adiag) and col in adiag.columns:
warp[m] = adiag[adiag.rid.isin(rids)].groupby("rid")[col].mean().mean()
for name, w in exw.items():
warp[name] = float(np.mean([v for r_, v in w.items() if r_ in rids])) if any(r_ in rids for r_ in w) else np.nan
checks.append({"set": "16-23" if rep else "8-15", "regime": regime, "c": c, "n_train": N,
**{f"max_dwarp_{m}": max(cells[k]["check"][m] for k in have) for m in cells[have[0]]["check"]}})
methods = A1_METHODS + [m for m in ("B3p", "SMC-opt") if m in set(allrun.method)]
for m in methods:
if m not in set(allrun.method):
continue
a = ci.per_rid(allrun, m)
if m in ("B3p", "SMC-opt") and set(a.index) != set(rids):
extra_seen.add(f"{m} incomplete in {'16-23' if rep else '8-15'} {regime} c={c:g} N={N} ({len(a)}/{len(rids)} realizations; not shown)")
continue
if m in ("B3p", "SMC-opt"):
extra_seen.add(f"{m} in {'16-23' if rep else '8-15'} {regime} c={c:g} N={N}")
r = {"set": "16-23" if rep else "8-15", "regime": regime, "c": c, "n_train": N, "method": m,
"arm": {"B3p": "E2", "SMC-opt": "E4"}.get(m, "saved"), "best_tie": best,
"warp_rmse_ms": warp.get(m, np.nan), "band_rmse": float(a.mean()), "n_rid": len(a)}
for ref, lab in (("Oracle", "oracle"), (best, "best")):
if m == ref:
r |= {f"{lab}_{k}": (1.0 if k in ("ratio", "geo_ratio") else np.nan) for k in
("ratio", "geo_ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi")}
continue
iv = ci.intervals(a, ci.per_rid(allrun, ref), rng)
r |= {f"{lab}_{k}": iv[k] for k in ("ratio", "geo_ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi")}
rows.append(r)
df = pd.DataFrame(rows)
(OUT / "a1").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a1" / "a1_point_ties.csv", index=False)
ck = pd.DataFrame(checks)
ck.to_csv(OUT / "a1" / "a1_warp_checks.csv", index=False)
show = df[["set", "regime", "c", "n_train", "method", "warp_rmse_ms", "band_rmse", "oracle_ratio", "oracle_pct_lo",
"oracle_pct_hi", "best_ratio", "best_pct_lo", "best_pct_hi"]].copy()
show["c"] = show.c.map(lambda v: f"{v:g}")
txt = ["## A1. Point ties against the Oracle", "",
"Files: `outputs/gp_review/a1/a1_point_ties.csv` (all three intervals), `a1_warp_checks.csv` (recomputed vs saved warp "
"RMSE). Warp RMSE: mean over training wells and realizations (ms); band RMSE in p.u.; ratios with the primary "
"percentile interval. Best tie per cell = best of B3b, B3c, B3c-R by mean band RMSE.", "",
f"Warp-RMSE reproduction: largest |recomputed - saved| over all cells and methods = "
f"{ck.filter(like='max_dwarp').to_numpy().max():.2e} ms.", "",
f"E2 (B3p) / E4 (SMC-opt) rows present at run time: {', '.join(sorted(extra_seen)) or 'none'}.", "",
md(show), ""]
# compact reading lines
for st in ("8-15", "16-23"):
sub = df[df.set == st]
if sub.empty:
continue
for m in ("SMC-MAP", "Anchor-LS", "B3d-Sa", "B3d"):
s = sub[sub.method == m]
if s.empty:
continue
txt.append(f"- {st}, {m}: ratio to Oracle {s.oracle_ratio.min():.3f}-{s.oracle_ratio.max():.3f}; ratio to best tie "
f"{s.best_ratio.min():.3f}-{s.best_ratio.max():.3f} (CI below 1 in {int((s.best_pct_hi < 1).sum())}/{len(s)}, above in "
f"{int((s.best_pct_lo > 1).sum())}); warp RMSE {s.warp_rmse_ms.min():.2f}-{s.warp_rmse_ms.max():.2f} ms.")
s = sub[sub.method.isin(TIES)].groupby(["regime", "c", "n_train"]).oracle_ratio.min()
txt.append(f"- {st}, best deterministic tie vs Oracle: {s.min():.3f}-{s.max():.3f}; tie warp RMSE "
f"{sub[sub.method.isin(TIES)].warp_rmse_ms.min():.2f}-{sub[sub.method.isin(TIES)].warp_rmse_ms.max():.2f} ms.")
return txt + [""]
# ----------------------------------------------------------------------------------------------------------------
# A2
# ----------------------------------------------------------------------------------------------------------------
def stage_a2() -> list[str]:
rng = np.random.default_rng(0)
rows = []
for regime, c in t2.WIDE16 + t2.NARROW16:
fs = [outputs_dir() / "lambda_limit" / "cells" / f"{t2.tag(regime, rid, c, 16)}.csv" for rid in RIDS]
d = pd.concat([pd.read_csv(f) for f in fs if f.exists()], ignore_index=True)
orc = p2r_cell_rows(regime, c, 16, False)
o = ci.per_rid(orc, "Oracle")
for b in (125, 250, 500):
db = d[d.budget == b]
a, s = ci.per_rid(db, "M2-Sa"), ci.per_rid(db, "B3d-Sa")
iv = ci.intervals(a, s, rng)
rows.append({"regime": regime, "c": c, "n_train": 16, "budget": b, "B3d-Sa": s.mean(), "M2-Sa": a.mean(),
"M2/B3d-Sa": iv["ratio"], "pct_lo": iv["pct_lo"], "pct_hi": iv["pct_hi"],
"B3d-Sa/Oracle500": s.mean() / o.mean(), "M2-Sa/Oracle500": a.mean() / o.mean()})
df = pd.DataFrame(rows)
(OUT / "a2").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a2" / "a2_budgets.csv", index=False)
show = df.copy()
show["c"] = show.c.map(lambda v: f"{v:g}")
return ["## A2. Table 2 at equal budget", "",
"Not available from saved outputs (P2r trained each method at its registered budget only). Reported as is from "
"`outputs/lambda_limit/cells/` (the same trajectories retrained, 5 seeds): B3d-Sa and M2-Sa at 125/250/500 "
"iterations in the 11 T2 cells at N = 16; Oracle at its registered 500 from P2r. The full table is E6. File: "
"`outputs/gp_review/a2/a2_budgets.csv`.", "", md(show), ""]
# ----------------------------------------------------------------------------------------------------------------
# A3
# ----------------------------------------------------------------------------------------------------------------
def stage_a3() -> tuple[list[str], dict]:
from scipy import stats
cells = load_cells(False)
rows = []
for regime, c, N in A3_CELLS:
ks = [(regime, r, c, N) for r in RIDS]
miss = [k for k in ks if k not in cells]
if miss:
raise RuntimeError(f"missing cell files: {miss[:3]}")
cr = {m: np.sum([cells[k]["cross"][m] for k in ks], 0) for m in PRED_METHODS}
for m in A3_METHODS:
hp = np.sum([cells[k]["hpred_s"][m] for k in ks], 0) / np.sum([cells[k]["hpred_n"][m] for k in ks])
hm = cr[m] / cr["Oracle"]
sel = [k for k in A3_BINS if hp[k] >= 0.2]
q = hm[sel] / hp[sel]
g = float(np.exp(np.mean(np.log(q)))) if len(q) and np.all(q > 0) else np.nan
r = {"regime": regime, "c": c, "n_train": N, "method": m, "g": g, "n_bins": len(sel),
"att_pred": 1 - hp[KSTAR], "att_meas": 1 - hm[KSTAR], "powered": bool(1 - hp[KSTAR] >= 0.05),
"agree": bool(np.isfinite(g) and 0.9 <= g <= 1.1),
"delta_rms_ms": float(np.mean([np.mean(cells[k]["delta_rms"][m]) for k in ks]))}
r |= {f"Hpred_{FREQ[k]:.1f}": hp[k] for k in A3_BINS} | {f"Hmeas_{FREQ[k]:.1f}": hm[k] for k in A3_BINS}
rows.append(r)
df = pd.DataFrame(rows)
(OUT / "a3").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a3" / "a3_transfer.csv", index=False)
pw = df[df.powered]
n_pow, n_agree = len(pw), int(pw.agree.sum())
share = n_agree / n_pow if n_pow else float("nan")
sufficient = bool(n_pow >= 6 and n_agree >= 2 * n_pow / 3)
rho, pval = stats.spearmanr(df.att_pred, df.att_meas)
res = {"n_combinations": len(df), "n_powered": n_pow, "n_agree_powered": n_agree, "share_agree": share,
"sufficient": sufficient, "decision": "A3 sufficient (E3 not run)" if sufficient else "A3 not sufficient (run E3)",
"spearman_att": float(rho), "spearman_p": float(pval), "f_star_hz": float(FREQ[KSTAR]),
"bins_hz": [float(FREQ[k]) for k in A3_BINS], "g_nan_powered": int(pw.g.isna().sum()),
"g_powered_median": float(pw.g.median()) if n_pow else None,
"g_powered_range": [float(pw.g.min()), float(pw.g.max())] if n_pow else None}
show = pw[["regime", "c", "n_train", "method", "att_pred", "att_meas", "g", "n_bins", "agree", "delta_rms_ms"]].copy()
show["c"] = show.c.map(lambda v: f"{v:g}")
byc = df.groupby("method").agg(n=("g", "size"), powered=("powered", "sum"), agree_all=("agree", "sum"),
g_median=("g", "median")).reset_index()
byc["agree_powered"] = byc.method.map(pw.groupby("method").agree.sum()).fillna(0).astype(int)
byc = byc[["method", "n", "powered", "agree_powered", "agree_all", "g_median"]]
ar = pw.att_meas / pw.att_pred
upper = [k for k in A3_BINS if FREQ[k] >= 15]
q_up = pw.apply(lambda r: np.exp(np.mean(np.log(np.clip([r[f"Hmeas_{FREQ[k]:.1f}"] / r[f"Hpred_{FREQ[k]:.1f}"]
for k in upper], 1e-9, None)))), axis=1)
res |= {"att_ratio_powered_median": float(ar.median()), "att_meas_lt_pred_powered": int((ar < 1).sum()),
"g_upper_bins_in_band_powered": int(((q_up >= 0.9) & (q_up <= 1.1)).sum())}
(OUT / "a3" / "a3_decision.json").write_text(json.dumps(res, indent=1))
txt = ["## A3. Predicted against measured transfer", "",
f"Files: `outputs/gp_review/a3/a3_transfer.csv` (H_pred and H_meas at every bin), `a3_decision.json`. Bins "
f"{', '.join(f'{f:.2f}' for f in res['bins_hz'])} Hz; f* = {res['f_star_hz']:.2f} Hz. M2-Sa uses uniform weights over "
"the valid bank members (the lambda -> 0 approximation).", "",
f"**Decision: {res['decision']}.** Powered combinations: {n_pow} of {len(df)}; g in [0.9, 1.1] in {n_agree} of them "
f"({share:.2f}; rule: >= 6 powered and >= 2/3). g undefined (a ratio <= 0) in {res['g_nan_powered']} powered "
f"combinations. Spearman correlation of predicted vs measured attenuation 1 - H(f*) over all {len(df)} combinations: "
f"{rho:.2f} (p = {pval:.1e}).", "",
f"Descriptive, not part of the rule: g restricted to the bins >= 15 Hz ({', '.join(f'{FREQ[k]:.2f}' for k in upper)}) "
f"lies in [0.9, 1.1] in {res['g_upper_bins_in_band_powered']} of {n_pow} powered combinations, so the low bins "
f"(H_pred close to 1) do not drive the count. A +-10% band on H is lenient on the attenuation 1 - H, though: at f* "
f"the measured attenuation is smaller than the predicted one in {res['att_meas_lt_pred_powered']} of {n_pow} "
f"powered combinations (median ratio measured/predicted {res['att_ratio_powered_median']:.2f}), i.e. the networks "
"lose less high-frequency content than cos(2 pi f delta) predicts. The Oracle reference has budget 500 against "
"125-500 for the methods (stated caveat).", "", "Per method (all cells):", "", md(byc, 3), "", "Powered combinations:", "",
md(show), ""]
return txt, res
# ----------------------------------------------------------------------------------------------------------------
# A4
# ----------------------------------------------------------------------------------------------------------------
def stage_a4() -> list[str]:
rng = np.random.default_rng(0)
cells = load_cells(False)
rows, spec_rows = [], []
for regime, c, N in A1_CELLS:
ks = [(regime, r, c, N) for r in RIDS]
run = p2r_cell_rows(regime, c, N, False)
means = {m: ci.per_rid(run, m).mean() for m in TIES}
best = min(means, key=means.get)
b6 = pd.concat([pd.DataFrame(cells[k]["band625"]).assign(rid=k[1]) for k in ks], ignore_index=True)
b625 = b6.rename(columns={"band_rmse": "_b", "band625_rmse": "band_rmse"})
iv6 = ci.intervals(ci.per_rid(run, "B3d-Sa"), ci.per_rid(run, best), rng)
iv25 = ci.intervals(ci.per_rid(b625, "B3d-Sa"), ci.per_rid(b625, best), rng)
r6, r25 = iv6["ratio"], iv25["ratio"]
rows.append({"regime": regime, "c": c, "n_train": N, "best_tie": best, "r_ge6": r6, "r_ge6_lo": iv6["pct_lo"],
"r_ge6_hi": iv6["pct_hi"], "r_6_25": r25, "r_6_25_lo": iv25["pct_lo"], "r_6_25_hi": iv25["pct_hi"],
"r_6_25_bca_lo": iv25["bca_lo"], "r_6_25_bca_hi": iv25["bca_hi"], "r_6_25_t_lo": iv25["t_lo"],
"r_6_25_t_hi": iv25["t_hi"], "share_kept": (1 - r25) / (1 - r6) if r6 < 1 else np.nan,
"bandcheck": max(cells[k]["bandcheck"] for k in ks)})
amp = {s: np.mean([cells[k]["amp"][s] for k in ks], 0) for s in ("seismic", "label", "Oracle", "B3d-Sa", best)}
for s, a in amp.items():
pw = a ** 2
tot = pw[FREQ >= 0.5].sum()
spec_rows.append({"regime": regime, "c": c, "n_train": N, "series": "best tie" if s == best else s,
"peak_hz": float(FREQ[1:][np.argmax(a[1:])]),
"share_lt6": pw[(FREQ > 0) & (FREQ < 6)].sum() / tot, "share_6_25": pw[(FREQ >= 6) & (FREQ <= 25)].sum() / tot,
"share_gt25": pw[FREQ > 25].sum() / tot,
**{f"amp_{f:.1f}": v for f, v in zip(FREQ, a)}})
df, sp = pd.DataFrame(rows), pd.DataFrame(spec_rows)
(OUT / "a4").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a4" / "a4_band_ratios.csv", index=False)
sp.to_csv(OUT / "a4" / "a4_spectra.csv", index=False)
show = df[["regime", "c", "n_train", "best_tie", "r_ge6", "r_6_25", "r_6_25_lo", "r_6_25_hi", "share_kept"]].copy()
show["c"] = show.c.map(lambda v: f"{v:g}")
pooled = sp.groupby("series")[["peak_hz", "share_lt6", "share_6_25", "share_gt25"]].mean().reset_index()
seis_txt = []
for reg, g in sp[sp.series == "seismic"].groupby("regime", sort=False):
a = g.filter(like="amp_").mean().to_numpy()
ab = FREQ[(a / a[1:].max() >= 0.1) & (FREQ > 0)]
seis_txt.append(f"{reg} peak {FREQ[1:][np.argmax(a[1:])]:.1f} Hz, >= 10% of peak {ab.min():.1f}-{ab.max():.1f} Hz")
c1 = df[df.c == 1.0]
return ["## A4. Signal band", "",
"Files: `outputs/gp_review/a4/a4_band_ratios.csv` (three intervals), `a4_spectra.csv` (mean amplitude spectra per cell, "
"Hann-tapered 126-sample DFT of the main window; band power shares exclude the DC bin). Band RMSE from the saved "
f"predictions reproduces the cell CSVs to {df.bandcheck.max():.1e} p.u.", "",
md(show), "",
f"Mean power shares over the 12 cells (power of the mean amplitude spectrum, f > 0):", "", md(pooled), "",
"Input seismic at the test wells (mean amplitude spectrum per regime, DC bin excluded): " + "; ".join(seis_txt)
+ ".", "",
f"At c = 1: r_6-25 = {c1.r_6_25.min():.3f}-{c1.r_6_25.max():.3f} vs r_>=6 = {c1.r_ge6.min():.3f}-{c1.r_ge6.max():.3f}; "
f"share of the gain kept in 6-25 Hz {c1.share_kept.min():.2f}-{c1.share_kept.max():.2f}.", ""]
# ----------------------------------------------------------------------------------------------------------------
# A5
# ----------------------------------------------------------------------------------------------------------------
def checks_for(seis: np.ndarray, syn: np.ndarray, mask: np.ndarray) -> dict:
from ml_porosity.data.wavelet import rotate_phase
s, y = seis[mask], syn[mask]
corr = float(np.corrcoef(s, y)[0, 1])
phases = np.arange(-90, 91, 15)
cs = [np.corrcoef(s, rotate_phase(syn, float(p))[mask])[0, 1] for p in phases]
sc, yc = s - s.mean(), y - y.mean()
alpha = float(sc @ yc / (yc @ yc))
S, Rr = np.abs(spec(s)), np.abs(spec(s - alpha * y))
q = Rr / np.maximum(S, 1e-300)
band = lambda a, b: float(np.mean(q[(FREQ >= a) & (FREQ <= b)]))
return {"tie_corr": corr, "res_phase_deg": float(phases[int(np.argmax(cs))]), "res_6_15": band(6, 15),
"res_15_30": band(15, 30), "res_30_50": band(30, 50)}
def a5_job(job) -> tuple[str, float]:
label, rid, out_file = job
set_threads(2)
t0 = time.time()
from ml_porosity.benchmark.data import load_inputs
from ml_porosity.benchmark.protocol import load_protocol
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.smc import phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import synth_for_warps
p = load_protocol(check_inputs=True)
inp = load_inputs(p)
R = inp.realization(rid, None if label == "nominal" else label)
obs, _ = inp.observe(R, 1.0, "R10", 16)
base = P2R / "posterior" / "R10" if label == "nominal" else BENCH / "posterior" / f"R10__{label}"
t = f"r{rid}_c1_n16_s0"
ph = json.loads((base / f"{t}_phase.json").read_text())
smc = np.load(base / f"{t}_particles.npz")
reg, cfg = inp.reg, inp.cfg
sa = float(reg.get("sigma_a_ms", inp.sigma_a))
fac = int(round(R.dt / cfg["fine_dt_ms"]))
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
mask = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
if mask.sum() != L or len(seis[0]) != len(R.t_ext):
raise RuntimeError("unexpected seismic grid")
rows = []
tau0, dtau = R.tau_fine[0], R.tau_fine[1] - R.tau_fine[0]
for i, o in enumerate(obs):
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
tm = Tf.mean(0)
x = (np.asarray(o["tau_k"], float) - tau0) / dtau
j = np.clip(np.floor(x).astype(int), 0, len(R.tau_fine) - 2)
w = np.clip(x - j, 0, 1)
Tk = Tf[:, j] * (1 - w) + Tf[:, j + 1] * w
z2 = float(np.mean((np.asarray(o["t_k"]) - Tk.mean(0)) ** 2 / (sa ** 2 + Tk.var(0)))) if len(j) else np.nan
syn = synth_for_warps(R.tau_fine, o["ai_log"], tm[None], R.t_fine, R.t_ext, wR)[0]
rows.append({"label": label, "rid": rid, "well": o["name"], "n_anchor": len(j), "anchor_z2": z2,
**checks_for(seis[i], syn, mask)})
out_file.parent.mkdir(parents=True, exist_ok=True)
pd.DataFrame(rows).to_csv(out_file, index=False)
return f"{label}_r{rid}", time.time() - t0
def f3_checks() -> tuple[pd.DataFrame | None, str]:
"""Checks 1-2 on F3 from the stored P3 registration bundles (three-well outer folds, sigma_a = 7 ms)."""
try:
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.f3.data import F3Data
from ml_porosity.f3.protocol import load_protocol as f3_protocol
from ml_porosity.registration.smc import phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import synth_for_warps
p = f3_protocol()
r = p["registration"]
rows = []
bundles = sorted(f for f in (outputs_dir() / "p3" / "registration").glob("*_sa7.npz") if f.stem.count("__") == 2)
if len(bundles) != 4:
return None, f"expected 4 three-well bundles, found {len(bundles)}"
for bf in bundles:
meta = json.loads(bf.with_suffix(".json").read_text())
names = tuple(meta["training_wells"])
z = np.load(bf)
if tuple(str(w) for w in z["wells"]) != names:
raise RuntimeError(f"{bf.name}: well order differs")
data = F3Data(p, names)
obs = data.training_observations(names)
fac = int(round(data.dt / r["fine_dt_ms"]))
w0 = statistical_wavelet(np.stack([o["seis"] for o in obs]), data.dt, r["wavelet_ms"])
wf = phase_wavelet(phase_basis(w0, fac), float(z["phase_R"]))
sa = float(meta["sigma_a_ms"])
for o in obs:
ta = np.asarray(z[f"posterior/{o['name']}/tau_at_main"], float) # (P, 126): tau at t_main
ta = ta[np.all(np.isfinite(ta), 1)] # particles covering the window
lo, hi = np.nanmax(ta[:, 0]), np.nanmin(ta[:, -1])
keep = (o["tau_k"] >= lo) & (o["tau_k"] <= hi)
tk = np.stack([np.interp(o["tau_k"][keep], row, data.t_main) for row in ta]) if keep.any() else None
z2 = float(np.mean((o["t_k"][keep] - tk.mean(0)) ** 2 / (sa ** 2 + tk.var(0)))) if keep.any() else np.nan
tb = ta.mean(0)
tbar = np.interp(data.tau, tb, data.t_main)
s0 = (data.t_main[1] - data.t_main[0]) / (tb[1] - tb[0])
s1 = (data.t_main[-1] - data.t_main[-2]) / (tb[-1] - tb[-2])
tbar = np.where(data.tau < tb[0], data.t_main[0] + (data.tau - tb[0]) * s0, tbar)
tbar = np.where(data.tau > tb[-1], data.t_main[-1] + (data.tau - tb[-1]) * s1, tbar)
syn = synth_for_warps(data.tau, o["ai_log"], tbar[None], data.t_fine, data.t, wf)[0]
m = data.main
rows.append({"bundle": bf.stem, "well": o["name"], "n_particles": len(ta), "n_anchor": int(len(o["tau_k"])),
"n_anchor_used": int(keep.sum()),
"anchor_z2": z2, "tie_corr": float(np.corrcoef(o["seis"][m], syn[m])[0, 1])})
return pd.DataFrame(rows), ""
except Exception as e: # noqa: BLE001
return None, f"{type(e).__name__}: {e}"
def a5_jobs(force: bool) -> list:
jobs = []
for label in ["nominal"] + PRESETS:
for rid in RIDS:
f = OUT / "a5" / "cells" / f"{label}_r{rid}.csv"
if force or not f.exists():
jobs.append((label, rid, f))
return jobs
def stage_a5() -> list[str]:
d = pd.concat([pd.read_csv(f) for f in sorted((OUT / "a5" / "cells").glob("*.csv"))], ignore_index=True)
d["abs_phase_deg"] = d.res_phase_deg.abs()
checks = ["anchor_z2", "tie_corr", "res_phase_deg", "abs_phase_deg", "res_6_15", "res_15_30", "res_30_50"]
rm = d.groupby(["label", "rid"])[checks].mean().reset_index()
nom = rm[rm.label == "nominal"]
lo, hi = nom[checks].quantile(0.05), nom[checks].quantile(0.95)
s2 = pd.read_csv(BENCH / "summary" / "s2_h2a.csv")
s2 = s2[(s2.regime == "R10") & (s2.n_train == 16) & (s2.c == 1.0)].set_index("preset")
rows = []
for label in ["nominal"] + PRESETS:
g = rm[rm.label == label]
r = {"preset": label, "smc_mean_ratio_R10_N16": s2.ratio.get(label, np.nan),
"smc_mean_gain_pass": s2.cell_pass.get(label, np.nan)}
nflag = 0
for k in checks:
v = g[k].mean()
out = (g[k] < lo[k]) | (g[k] > hi[k])
flag = bool(v < lo[k] or v > hi[k]) and label != "nominal"
r |= {k: v, f"{k}_flag": flag, f"{k}_n_out": int(out.sum())}
nflag += flag and k != "abs_phase_deg"
r["n_flags"] = nflag
rows.append(r)
df = pd.DataFrame(rows)
(OUT / "a5").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a5" / "a5_flags.csv", index=False)
rng_tab = pd.DataFrame({"check": checks, "nominal_p05": lo.to_numpy(), "nominal_p95": hi.to_numpy()})
f3, why = f3_checks()
if f3 is not None:
f3.to_csv(OUT / "a5" / "a5_f3.csv", index=False)
show = df[["preset", "smc_mean_ratio_R10_N16", "smc_mean_gain_pass", "n_flags"] +
[c for k in checks for c in (k, f"{k}_n_out")]].copy()
flagged = {r.preset: [k for k in checks if k != "abs_phase_deg" and r[f"{k}_flag"]] for _, r in df.iterrows() if r.preset != "nominal"}
failing = [p for p in PRESETS if not bool(s2.cell_pass.get(p, True))]
txt = ["## A5. Truth-free checks", "",
"Files: `outputs/gp_review/a5/a5_flags.csv`, `a5/cells/*.csv` (per well), `a5_f3.csv`. Nominal = P2r particles, R10, "
"c = 1, N = 16, realizations 8-15; presets = `outputs/bench/posterior/R10__<preset>/` at the same c and N. A check "
"flags a preset if the preset's mean over its 8 realizations lies outside the 5-95% range of the 8 nominal "
"realization means; n_out = realizations outside that range. `abs_phase_deg` (mean |residual phase|) is an added "
"descriptive column and is not counted in n_flags.", "", "Nominal 5-95% ranges:", "", md(rng_tab), "", md(show), "",
"Flags per preset: " + "; ".join(f"{p}: {', '.join(v) or 'none'}" for p, v in flagged.items()) + ".", "",
f"Presets where the SMC-mean gain failed at R10, N = 16 (S2 cell rule): {', '.join(failing)}. "
f"Of these, flagged by at least one check: {', '.join(p for p in failing if flagged[p]) or 'none'}; "
f"passing presets flagged: {', '.join(p for p in PRESETS if p not in failing and flagged[p]) or 'none'}.", "",
"Per check (failing presets flagged / passing presets flagged): " + "; ".join(
f"{k} {sum(k in flagged[p] for p in failing)}/{len(failing)}, "
f"{sum(k in flagged[p] for p in PRESETS if p not in failing)}/{len(PRESETS) - len(failing)}"
for k in checks if k != "abs_phase_deg") + ". The nominal residual-phase range is "
f"{lo['res_phase_deg']:.0f}-{hi['res_phase_deg']:.0f} deg on the 15-deg grid, so one non-zero pick in any "
"realization of a preset flags it (a degenerate check here).", ""]
if f3 is None:
txt += [f"F3: not available ({why}).", ""]
else:
txt += ["F3 (stored P3 bundles, three-well outer folds, sigma_a = 7 ms; posterior-mean warp from the mean of tau(t) over "
"the 1024 stored particles, inverted and extended linearly outside the main window; anchors inside the depth "
"range covered by every particle):", "", md(f3), "",
f"F3 means: anchor z^2 {f3.anchor_z2.mean():.2f}, tie correlation {f3.tie_corr.mean():.2f} (nominal synthetic "
f"5-95%: z^2 {lo['anchor_z2']:.2f}-{hi['anchor_z2']:.2f}, correlation {lo['tie_corr']:.2f}-{hi['tie_corr']:.2f}; "
"not comparable as a flag, different data).", ""]
return txt
# ----------------------------------------------------------------------------------------------------------------
# A6
# ----------------------------------------------------------------------------------------------------------------
def stage_a6() -> list[str]:
t3 = pd.read_csv(outputs_dir() / "t3" / "nstar.csv")
f2 = pd.read_csv(outputs_dir() / "referee_r5" / "f2_nstar.csv")
r6 = pd.read_csv(outputs_dir() / "r6" / "a1_nstar.csv")
key = ["regime", "n_train", "sigma_ref"]
df = (t3[key + ["p_better", "icc", "nstar_k_of_n", "nstar_sign"]]
.merge(f2[key + ["nstar_sign", "nstar_wilcoxon", "nstar_t"]].rename(columns={"nstar_sign": "nstar_sign_f2"}), on=key)
.merge(r6[key + ["nstar_calibrated", "power40_calibrated", "ceiling"]], on=key))
(OUT / "a6").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a6" / "a6_nstar.csv", index=False)
pw = pd.read_csv(outputs_dir() / "referee_r5" / "f2_power.csv")
pw.to_csv(OUT / "a6" / "a6_f2_power.csv", index=False)
fmt = lambda v: "none <= 40" if pd.isna(v) else f"{int(v)}"
show = df.copy()
for k in ("nstar_k_of_n", "nstar_sign", "nstar_sign_f2", "nstar_wilcoxon", "nstar_t", "nstar_calibrated"):
show[k] = show[k].map(fmt)
s0 = df[df.sigma_ref == 0.0]
return ["## A6. Blind-well power", "",
"Files: `outputs/gp_review/a6/a6_nstar.csv` (collated), `a6_f2_power.csv` (power curves). n* = smallest number of "
"blind wells with power >= 0.8 on the grid up to 40 ('none <= 40' if never).", "",
"Resampling units: (t3, `outputs/t3/`) indicators per realization x test well x reference draw (64 draws of a "
"linear reference error with sd sigma_ref); power analytic, beta-binomial with the realization-level intra-class "
"correlation; k-of-n with k = ceil(0.75 n) and the nominal one-sided sign test. (F2, `outputs/referee_r5/f2_*`) "
"Monte Carlo, 1000 replicates: realizations drawn with replacement (ceil(n/8) of the 8), all 8 test wells of each "
"with one random reference draw, truncated to n; sign, Wilcoxon and paired t on log ratios. (r6 A1, "
"`outputs/r6/a1_*`) analytic beta-binomial with the t3 ICC and a critical value calibrated for that ICC.", "",
md(show, 3), "",
"Exact reference (sigma_ref = 0): " + "; ".join(
f"{r.regime} N={r.n_train}: sign {fmt(r.nstar_sign)}, Wilcoxon {fmt(r.nstar_wilcoxon)}, t {fmt(r.nstar_t)}, "
f"calibrated sign {fmt(r.nstar_calibrated)}" for r in s0.itertuples()) + ".", ""]
# ----------------------------------------------------------------------------------------------------------------
# A7
# ----------------------------------------------------------------------------------------------------------------
def stage_a7() -> list[str]:
(OUT / "a7").mkdir(parents=True, exist_ok=True)
m3 = pd.read_csv(outputs_dir() / "p3" / "summary" / "metrics.csv")
m3 = m3[(m3.label == "PHIE_DT") & (m3.sigma_a_ms == 7.0) & (m3.members == 15)]
meths = ["B3b", "B3c", "B3c-R", "B3d", "B3d-Sa", "M2-Sa"]
gc = json.loads((outputs_dir() / "p3" / "summary" / "gate_gc.json").read_text())
comp3 = {w["well"]: w["competitor"] for w in gc["per_well"]}
rows = []
for (well, ref), g in m3[m3.method.isin(meths)].groupby(["test_well", "reference"]):
g = g.groupby("method")[["band_rmse", "band_pcc", "rmse"]].mean()
ties = g.loc[[m for m in TIES if m in g.index]]
bt = ties.band_rmse.idxmin()
rows.append({"field": "F3", "split": "nested LOWO", "well": well, "reference": ref, "gate_competitor": comp3.get(well),
"best_tie_by_test": bt,
**{f"{m}_band_rmse": g.band_rmse.get(m, np.nan) for m in meths},
**{f"{m}_band_pcc": g.band_pcc.get(m, np.nan) for m in meths},
"const_rmse": np.nan, "const_band_rmse": np.nan})
m4 = pd.read_csv(outputs_dir() / "p4" / "summary" / "metrics.csv")
m4 = m4[(m4.sigma_a_ms == 7.0) & m4.scored.astype(bool)]
gd = json.loads((outputs_dir() / "p4" / "summary" / "gate_gd.json").read_text())
ph = pd.read_csv(outputs_dir() / "p4" / "posthoc" / "wells.csv")
m4e = m4[m4.seed.astype(str) == "ensemble"]
for (scheme, well, ref), g in m4e.groupby(["scheme", "test_well", "reference"]):
g = g.groupby("method")[["band_rmse", "band_pcc", "rmse"]].mean()
ties = g.loc[[m for m in TIES if m in g.index]]
comp = {w["well"]: w["competitor"] for w in gd["schemes"][scheme]["per_well"]}
p = ph[(ph.scheme == scheme) & (ph.well == well)]
rows.append({"field": "Volve", "split": scheme, "well": well, "reference": ref, "gate_competitor": comp.get(well),
"best_tie_by_test": ties.band_rmse.idxmin(),
**{f"{m}_band_rmse": g.band_rmse.get(m, np.nan) for m in meths},
**{f"{m}_band_pcc": g.band_pcc.get(m, np.nan) for m in meths},
**{f"{m}_rmse": g.rmse.get(m, np.nan) for m in meths},
"const_rmse": float(p.const_rmse.iloc[0]) if len(p) and ref == "calibrated" else np.nan,
"posthoc_B3d-Sa_rmse": float(p["B3d-Sa/rmse"].iloc[0]) if len(p) and ref == "calibrated" else np.nan,
"const_band_rmse": np.nan})
df = pd.DataFrame(rows)
df.to_csv(OUT / "a7" / "a7_wells.csv", index=False)
show = df[["field", "split", "well", "reference", "gate_competitor", "best_tie_by_test", "B3b_band_rmse", "B3c_band_rmse",
"B3c-R_band_rmse", "B3d-Sa_band_rmse", "M2-Sa_band_rmse", "B3d-Sa_band_pcc", "M2-Sa_band_pcc", "const_rmse"]]
cal = df[df.reference == "calibrated"].copy()
cal["bt"] = cal.apply(lambda r: r[f"{r.gate_competitor}_band_rmse"], axis=1)
lines = []
for (fld, sp), g in cal.groupby(["field", "split"]):
lines.append(f"- {fld} {sp} (calibrated reference): SMC mean better than the gate competitor at "
f"{int((g['B3d-Sa_band_rmse'] < g.bt).sum())}/{len(g)} wells, SMC bank at {int((g['M2-Sa_band_rmse'] < g.bt).sum())}/{len(g)}; "
f"band PCC of the SMC bank {g['M2-Sa_band_pcc'].min():.2f}-{g['M2-Sa_band_pcc'].max():.2f}.")
if fld == "Volve":
full = g.apply(lambda r: r["M2-Sa_rmse"] < r[f"{r.gate_competitor}_rmse"], axis=1)
lines.append(f" By full-band RMSE (the G-D gate metric): SMC bank better at {int(full.sum())}/{len(g)} wells "
f"(`gate_gd.json` improved_wells = {gd['schemes'][sp]['improved_wells']}); the band-RMSE count "
"above differs because the gate scored the full band.")
return ["## A7. Field cases per well", "",
f"File: `outputs/gp_review/a7/a7_wells.csv`. F3: `outputs/p3/summary/metrics.csv`, PHIE_DT, sigma_a = 7 ms, the "
f"15-member ensemble row per well (its B3c-R/M2-Sa band RMSE reproduces the gate_gc ratios). Volve: "
"`outputs/p4/summary/metrics.csv`, PHIF, sigma_a = 7 ms, the seed-ensemble row (as the G-D gate and the post hoc "
"file), scored rows only; training-mean constant (full-band RMSE, calibrated reference) from "
"`outputs/p4/posthoc/wells.csv`. 'gate_competitor' = the point tie chosen by validation in the locked gate; "
"'best_tie_by_test' is the best by test band RMSE (descriptive only). No band RMSE exists for the constant "
"(band PCC undefined); no F3 constant is saved. `outputs/referee_r5/f1_wells.csv` is synthetic (P2r wells), "
"not field data, so it is not used here.", "", md(show, 2), "", *lines, ""]
# ----------------------------------------------------------------------------------------------------------------
# A8
# ----------------------------------------------------------------------------------------------------------------
def stage_a8() -> list[str]:
h = pd.read_csv(P2R / "summary" / "h2b.csv")
rows = []
for r in h.itertuples():
run = p2r_cell_rows(r.regime, float(r.c), int(r.n_train), False)
a, b = run[run.method == "M2-Sa"], run[run.method == "B3d-Sa"]
pooled = math.sqrt((a.band_rmse ** 2).mean() / (b.band_rmse ** 2).mean())
meanr = ci.per_rid(run, "M2-Sa").mean() / ci.per_rid(run, "B3d-Sa").mean()
bound = h.loc[r.Index, "bound_1/B"]
rows.append({"regime": r.regime, "c": r.c, "n_train": r.n_train, "wide": r.wide, "ratio_plotted": r.ratio,
"ratio_recomputed": meanr, "ratio_pooled_mse": pooled, "bound_1/B": bound,
"side_plotted": "below" if r.ratio < bound else "at/above",
"side_pooled": "below" if pooled < bound else "at/above"})
df = pd.DataFrame(rows)
df["changes_side"] = df.side_plotted != df.side_pooled
(OUT / "a8").mkdir(parents=True, exist_ok=True)
df.to_csv(OUT / "a8" / "a8_pooled.csv", index=False)
show = df.copy()
show["c"] = show.c.map(lambda v: f"{v:g}")
ch = df[df.changes_side]
return ["## A8. Aggregation in Figure 4b", "",
"File: `outputs/gp_review/a8/a8_pooled.csv`. Plotted value = `h2b.csv` ratio (mean over realizations of per-well band "
"RMSE, M2-Sa / B3d-Sa); pooled = sqrt of the ratio of mean squared band errors over test wells, seeds and "
f"realizations. Largest |plotted - recomputed mean ratio| = {np.abs(df.ratio_plotted - df.ratio_recomputed).max():.1e}.", "",
md(show), "",
f"Points that change side of the plotted bound: {len(ch)} of {len(df)}"
+ (": " + "; ".join(f"{r.regime} c={r.c:g} N={r.n_train} ({r.ratio_plotted:.3f} -> {r.ratio_pooled_mse:.3f}, bound {r['bound_1/B']:.3f})"
for _, r in ch.iterrows()) if len(ch) else "") +
f". |pooled - plotted| up to {np.abs(df.ratio_pooled_mse - df.ratio_plotted).max():.3f}.", ""]
# ----------------------------------------------------------------------------------------------------------------
# A9
# ----------------------------------------------------------------------------------------------------------------
def stage_a9() -> list[str]:
t = pd.read_csv(outputs_dir() / "t2" / "test_ii.csv")
c1 = t[(t.c == 1.0) & (t.n_train == 16)].copy()
band = pd.read_csv(P2R / "summary" / "band_rmse.csv")
band = band[(band.c == 1.0) & (band.n_train == 16)].set_index("setting")
c1["fig3_M2_over_B3dSa"] = [band.loc[r, "M2-Sa"] / band.loc[r, "B3d-Sa"] for r in c1.regime]
c1["within_2.5pct_point"] = (c1.ctl_rml_ratio - 1).abs() <= 0.025
c1["within_2.5pct_ci_hi"] = c1.ctl_rml_hi <= 1.025
c1["D_ctl_ci_contains_0"] = (c1.D_ctl_rml_diff_lo <= 0) & (c1.D_ctl_rml_diff_hi >= 0)
(OUT / "a9").mkdir(parents=True, exist_ok=True)
cols = ["regime", "ctl_pm_ratio", "rml_pm_ratio", "fig3_M2_over_B3dSa", "ctl_rml_ratio", "ctl_rml_lo", "ctl_rml_hi",
"D_ctl_rml_diff", "D_ctl_rml_diff_lo", "D_ctl_rml_diff_hi", "verdict", "within_2.5pct_point", "within_2.5pct_ci_hi",
"D_ctl_ci_contains_0"]
c1[cols].to_csv(OUT / "a9" / "a9_gaussian_bank.csv", index=False)
hits_25, hits_match, quoted = [], [], []
for f in sorted((REPO_ROOT / "paper" / "sections").glob("*.tex")) + [REPO_ROOT / "paper_gp" / "main.tex"]:
for i, line in enumerate(f.read_text().splitlines(), 1):
for m in re.finditer(r"Gaussian bank", line):
rest, heading = line[m.end():], line[m.end():].startswith(".}") # '\emph{Gaussian bank.}' item heading
window = ". ".join((rest[2:] if heading else rest).split(". ")[:2 if heading else 1])
if re.search(r"three of four|3 of 4", window):
(hits_25 if "2.5" in window else hits_match).append(f"{f.relative_to(REPO_ROOT)}:{i}")
quoted += [float(x) for x in re.findall(r"\b0\.\d{3}\b", window)]
n_pt, n_ci, n_d = int(c1["within_2.5pct_point"].sum()), int(c1["within_2.5pct_ci_hi"].sum()), int(c1["D_ctl_ci_contains_0"].sum())
fig_dev = float(np.abs(c1.rml_pm_ratio - c1.fig3_M2_over_B3dSa).max())
typea = c1[c1.D_ctl_ci_contains_0]
expect = sorted(np.round(np.r_[typea.ctl_pm_ratio.to_numpy(), typea.rml_pm_ratio.to_numpy()], 3).tolist())
q_ok = sorted(quoted) == expect
return ["## A9. Gaussian-bank count", "",
"File: `outputs/gp_review/a9/a9_gaussian_bank.csv` (from `outputs/t2/test_ii.csv`, c = 1, N = 16).", "",
md(c1[cols].round(4), 4), "",
f"Recomputed: Gaussian bank / SMC bank within 2.5% by the point ratio in {n_pt} of 4 cells (largest "
f"{c1.ctl_rml_ratio.max():.4f}, R0); upper 95% limit <= 1.025 in {n_ci} of 4; difference interval containing 0 "
f"(the T2 type-A rule, 'matched') in {n_d} of 4 (R0 is the exception).", "",
"- Statements worded as 'matched' / 'most of the gain' in three of four cells ("
+ (", ".join(hits_match) or "none found") + f"): **{'agree' if n_d == 3 else 'disagree'}** with the T2 type-A "
f"count; the ratios quoted there ({', '.join(f'{x:.3f}' for x in quoted) or 'none'}) "
+ ("equal" if q_ok else "do NOT equal") + " the recomputed Gaussian/SMC-mean and SMC-bank/SMC-mean ratios of "
"the type-A cells rounded to three decimals.",
"- Statements worded as 'came within 2.5% of the SMC bank ... in three of four cells' ("
+ (", ".join(hits_25) or "none found") + f"): **{'agree' if n_pt == 3 else 'disagree'}** as worded: within "
f"2.5% holds in {n_pt} of 4 by the point ratio and in {n_ci} of 4 by the upper limit; 'three of four' is the "
"type-A count. Per the declaration, the correction goes to the text (wording, not numbers).",
f"- Figure 3 does not plot the Gaussian bank; its SMC-bank/SMC-mean values agree with `test_ii.csv` (largest "
f"difference {fig_dev:.1e}).", ""]
# ----------------------------------------------------------------------------------------------------------------
DEVIATIONS = [
"Results are written to `outputs/gp_review/a_results.md`, not `docs/research/gp-review-results.md` as the declaration "
"says: the work was done by a worker that may not edit `docs/`; the main session moves or cites them.",
"A3: g is set to undefined (NaN, counted as not agreeing) when any per-bin ratio H_meas/H_pred is <= 0, because "
"the geometric mean is then undefined. The declaration does not cover this case.",
"A3: M2-Sa members get uniform weights over the valid members (the lambda -> 0 approximation the declaration states); "
"H_pred for M2-Sa averages cos(2 pi f delta) over members at each sample, then pools samples, wells and realizations.",
"A3/A4 bins: [6.8, 22.5] Hz on the 126-sample, 4 ms DFT = bins 4-11 (7.94-21.83 Hz); f* = 21.83 Hz.",
"A1: warp RMSE of B3c-R and B3d-Sa is recomputed from the rebuilt cell and checked against the saved P2r/replication "
"diagnostics; B3b, B3c and B3d against `register` diagnostics (a1_warp_checks.csv).",
"A1: E2 (B3p) and E4 (SMC-opt) rows are appended only if their outputs existed at run time (see A1).",
"A4: the best deterministic tie of each cell is chosen by f >= 6 Hz band RMSE (the declared definition) and used for "
"both the f >= 6 Hz and the 6-25 Hz ratios.",
"A5: the nominal cell uses the P2r particles with the realization and observations rebuilt by the benchmark loader "
"(`load_inputs`, preset None; bit-identical to P2r by the benchmark's fingerprint test). The posterior-mean warp is "
"the uniform particle mean of t(tau) (as B3d-Sa). The residual phase rotates the synthetic trace (Hilbert); "
"the residual spectrum removes the least-squares scale alpha on the main window. A column of mean |residual phase| "
"is added (descriptive, not used in the flag count).",
"A5 F3: the stored bundles hold tau(t) at the main-window times, not t(tau). The posterior-mean warp is therefore the "
"inverse of the particle mean of tau(t), extended linearly outside the main window, and anchor z^2 uses only anchors "
"inside the depth range covered by every particle; the wavelet is re-estimated from the training traces "
"(statistical wavelet, as `register_set`) and rotated to the stored phase_R. No registration was rerun.",
"A7: Volve has no band RMSE for the training-mean constant (band PCC undefined); its full-band RMSE is given with the "
"calibrated reference only; F3 has no saved constant. The best point tie is shown both as the gate's validation "
"choice and as the best by test band RMSE (descriptive).",
"A9: the text correction that the declaration calls for is not applied here (this worker may not edit `paper/` or "
"`paper_gp/`); the lines and the recomputed values are listed in A9 for the main session.",
"A1/A3/A4 cell jobs and the A5 jobs ran once (17/11/2026, 02:09-02:36 UTC); afterwards only the aggregation of "
"A3, A4, A5, A7 and A9 was rerun (`--force`, no job recomputed) to add descriptive lines (A4: seismic band given per regime with the DC bin excluded); no table value changed.",
]
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", nargs="+", default=["all"],
choices=["all", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"])
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--force", action="store_true", help="re-aggregate the chosen stages")
ap.add_argument("--force-jobs", action="store_true", help="also recompute the per-cell and A5 jobs")
ap.add_argument("--repro-tables", action="store_true", help="regenerate the archived numeric tables from saved cells")
args = ap.parse_args()
sha = check_declaration()
set_threads(2)
if os.environ.get("CUDA_VISIBLE_DEVICES", None) != "":
os.environ["CUDA_VISIBLE_DEVICES"] = ""
if args.repro_tables:
stage_a1(reproduce_original=True)
for aggregate in (stage_a2, stage_a3, stage_a4, stage_a5, stage_a6, stage_a7, stage_a8, stage_a9):
aggregate()
return
workers = min(args.workers, 4)
stages = ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"] if "all" in args.stage else args.stage
OUT.mkdir(parents=True, exist_ok=True)
t0 = time.time()
if {"a1", "a3", "a4"} & set(stages):
run_pool(cell_job, cell_jobs(args.force_jobs), workers, "cells")
if "a5" in stages:
run_pool(a5_job, a5_jobs(args.force_jobs), workers, "a5")
sec_file = OUT / "a_sections.json"
sections = json.loads(sec_file.read_text()) if sec_file.exists() else {}
a3res = None
fns = {"a1": stage_a1, "a2": stage_a2, "a4": stage_a4, "a5": stage_a5, "a6": stage_a6, "a7": stage_a7, "a8": stage_a8,
"a9": stage_a9}
for s in stages:
marker = OUT / s / f"{s}_done.json"
if marker.exists() and not args.force and s in sections:
print(f"{s}: output exists, skipped", flush=True)
continue
print(f"{s}: aggregating", flush=True)
if s == "a3":
txt, a3res = stage_a3()
else:
txt = fns[s]()
sections[s] = txt
marker.parent.mkdir(parents=True, exist_ok=True)
marker.write_text(json.dumps({"declaration_sha256": sha, "utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}))
sec_file.write_text(json.dumps(sections))
if a3res is None and (OUT / "a3" / "a3_decision.json").exists():
a3res = json.loads((OUT / "a3" / "a3_decision.json").read_text())
head = ["# GP review, Phase 2: analyses A1-A9 (exploratory, post hoc)", "",
f"Declaration `docs/research/gp-review-analyses.md`, SHA-256 `{sha}` (checked at run time). Script "
"`scripts/51_gp_review.py`; outputs `outputs/gp_review/a{1..9}/`. CPU only. Nothing here is a verdict of a locked "
"protocol; no locked file, input or output was changed.", "",
"## Deviations and clarifications", "", *[f"{i}. {d}" for i, d in enumerate(DEVIATIONS, 1)], ""]
if a3res:
head += [f"**A3 decision: {a3res['decision']}** ({a3res['n_powered']} powered, {a3res['n_agree_powered']} with g in "
f"[0.9, 1.1] = {a3res['share_agree']:.2f}; Spearman {a3res['spearman_att']:.2f}).", ""]
body = [line for s in ["a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9"] if s in sections for line in sections[s]]
(OUT / "a_results.md").write_text("\n".join(head + body) + "\n")
print(f"done in {time.time() - t0:.0f} s -> {OUT / 'a_results.md'}", flush=True)
if __name__ == "__main__":
main()