Replicate Experiment 2 on new realizations; test sigma_a at -5 dB

Exploratory analyses declared and hashed before computing
(docs/research/r6-replication.md, sha256 13b8b943...), outside every lock:
- Replication on realizations 16-23: the SMC-mean gain over the best
  deterministic tie is 7-19% (8-22% before); the per-regime verdicts are
  unchanged; the SMC mode beats the best tie in 10/10 cells; the bank passes
  2/3 wide cells; a Gaussian bank is within 2%.
- Misspecified anchor uncertainty at -5 dB: 0/2 cells at both 3.5 and 14 ms.
- Mechanism at sigma_a = 3.5 ms: the refitted drift prior becomes rougher
  (length scale 10-15 vs 80-90 ms); with fixed hyperparameters the
  posterior does not narrow.
- Calibrated sign test, F-11 T2 under four references, coverage at equal
  training length.

Paper: Sec. 6.3 and tab:sigmaa, abstract, introduction, conclusions,
Sec. 3.3, 4.1, tab:lessons, limitations, App. B and C. Docs synced; the
user dropped all date deadlines on 11/11/2026. No verdict, threshold or
protocol changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-12 04:49:53 +00:00
parent 760dbfea4f
commit d0d2cd3c82
24 changed files with 1091 additions and 64 deletions

View File

@@ -0,0 +1,331 @@
"""R6 B1 and B2 (declared in docs/research/r6-replication.md, hashed before the realizations were generated; outside every
lock and the reproduction archives).
B1 replicates Experiment 2 on realizations 16-23 (never generated before the declaration). Posteriors and the seven
registered methods come from the locked scripts 14 and 15 (outputs/replication/{posterior,train}/<regime>/, see
scripts/run_r6.sh); this script adds
--stage fingerprints SHA-256 fingerprints of realizations 16-23 (as tests/test_d2_misspec.py) -> fingerprints.json
--stage arms SMC-MAP, Anchor-LS (scripts/44) and Ctl-GP (scripts/32 control_bank) at 250 iterations, seeds 0-4,
plus B3d-Sa at seed 0 as a reproduction check of the scripts/15 rows -> arms/<cell>.csv
--stage summary the declared readings R-H2a, R-H2b, R-MAP, R-Ctl, R-ALS (B1) and the sigma_a arm at -5 dB (B2)
-> summary/{h2a.csv, h2b.csv, ratios.csv, sigma_a.csv, verdict.json, summary.md}
CUDA_VISIBLE_DEVICES=0 .venv/bin/python scripts/46_r6_replication.py --stage arms --workers 2 --device cuda:0
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import math
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
for _k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ.setdefault(_k, "2")
import numpy as np
import pandas as pd
from ml_porosity.paths import REPO_ROOT, outputs_dir
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
REP = outputs_dir() / "replication"
t2 = load_script("32_t2_mechanism.py")
s44 = load_script("44_point_tie_arm.py")
s18 = load_script("18_summarize_p2r.py")
ci = s44.ci
run_d2 = t2.run_d2
t2.P2R = REP # build_cell reads REP/posterior/<regime>/...
s44.P2R = REP # point_warps reads the tempering gamma from REP/posterior/<regime>/...
DECL = REPO_ROOT / "docs" / "research" / "r6-replication.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "r6-replication.sha256"
RIDS = list(range(16, 24))
SEEDS = [0, 1, 2, 3, 4]
NS = [4, 16]
C1_REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
C0_REGIMES = ["R10", "R0", "Rm5"]
CELLS = [(r, 1.0, n) for r in C1_REGIMES for n in NS] + [(r, 0.0, n) for r in C0_REGIMES for n in NS]
H2A_REGIMES = ["R10", "R0", "Rm5"]
POINT = list(s18.POINT_TIES) # B3b, B3c, B3c-R
BUDGET = 250
ARMS = ["SMC-MAP", "Anchor-LS", "Ctl-GP"]
SA_ARMS = ["Rm5_sa3.5", "Rm5_sa14"]
N_BOOT = 2000
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")
return actual
# ------------------------------------------------------------------------------------------------- fingerprints
def stage_fingerprints(P: dict) -> None:
"""Same definition as tests/test_d2_misspec.py (fields of every well; observations of the test wells and the
first four pool wells at c = 0, 1, 2, 10 dB, sigma_a = 7 ms, full anchors)."""
import scipy
import yaml
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.registration.warp_prior import WarpHyper
sha = lambda chunks: (lambda h: ([h.update(np.ascontiguousarray(np.asarray(a)).tobytes()) for a in chunks], h.hexdigest())[1])(hashlib.sha256())
fields = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a")
keys = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true")
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
out = {"meta": {"numpy": np.__version__, "scipy": scipy.__version__, "d2_config": P["inputs"]["d2_config"]["path"],
"declaration": check_declaration()}, "rids": {}}
for rid in RIDS:
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
obs = [R.observe(w, c, 10, 7.0, "full") for c in (0.0, 1.0, 2.0) for w in R.test + R.pool[:4]]
out["rids"][str(rid)] = {"wells": {k: sha(getattr(w, k) for w in R.wells) for k in fields},
"obs": {k: sha(o[k] for o in obs) for k in keys}}
print(f"fingerprint r{rid}", flush=True)
(REP / "fingerprints.json").write_text(json.dumps(out, indent=1))
# --------------------------------------------------------------------------------------------------------- arms
def arms_job(job) -> tuple[str, float]:
regime, rid, c, N, seeds, device, P = job
import torch
torch.set_num_threads(2)
from ml_porosity.models.bank_train import train_predict
t0 = time.time()
cell = t2.build_cell(regime, rid, c, N, P, with_register=True)
R, out, wells = cell["R"], cell["out"], cell["wells"]
stem = t2.tag(regime, rid, c, N)
key = dict(regime=regime, rid=rid, c=c, n_train=N)
m0, s0 = out["norm"]
lam = out["lam"]
tcfg = P["training"]["model"] | P["training"]["optimizer"]
f_c = P["metrics"]["bands"]["f_c_hz"]
nb = lambda a: ((np.asarray(a) - m0) / s0).astype(np.float32)
pw = s44.point_warps(cell, regime, rid, c, N)
bank = lambda Y, lp: {"kind": "bank", "Y": Y, "logpi": lp, "lam": lam}
one = np.zeros((N, 1), np.float32)
specs = {arm: bank(nb(np.stack([cell["lab"](w["y_aa"], pw[w["name"]][arm]) for w in wells])), one)
for arm in ("SMC-MAP", "Anchor-LS")}
Yc, lpc, diag = [], [], []
for w in wells:
Tc, info = t2.control_bank(w, R, cell["reg"]["S"])
Y = cell["lab"](w["y_aa"], Tc)
ok = np.all(np.isfinite(Y), 1)
Y[~ok] = Y[ok][0]
Yc.append(Y)
lpc.append(np.where(ok, 0.0, -np.inf) - np.log(ok.sum()))
from ml_porosity.registration.ties import warp_errors
err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, w["o"]["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
diag.append(key | {"well": w["name"], "SMC-MAP_warp_rmse_ms": err(pw[w["name"]]["SMC-MAP"]),
"Anchor-LS_warp_rmse_ms": err(pw[w["name"]]["Anchor-LS"]), "B3d-Sa_warp_rmse_ms": err(w["tm"]),
"map_rank_frac_ll": pw[w["name"]]["map_rank_frac_ll"], "ctl_n_valid": int(ok.sum())} | info)
specs["Ctl-GP"] = bank(nb(np.stack(Yc)), np.stack(lpc).astype(np.float32))
specs["B3d-Sa"] = bank(nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])), one)
rows = []
for seed in seeds:
for m, sp in specs.items():
if m == "B3d-Sa" and seed != 0:
continue
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [BUDGET], device)
for b, (mu, sg) in preds.items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for wt, r in zip(R.test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": wt.name} | r)
d = REP / "arms"
pd.DataFrame(diag).to_csv(d / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(d / f"{stem}.csv", index=False) # written last: marks the job complete
return stem, time.time() - t0
def stage_arms(P: dict, device: str, workers: int) -> None:
(REP / "arms").mkdir(parents=True, exist_ok=True)
ready = lambda r, rid, c, n: (REP / "posterior" / r / f"r{rid}_c{c:g}_n{n}_s0_particles.npz").exists()
jobs = [(r, rid, c, n, SEEDS, device, P) for (r, c, n) in CELLS for rid in RIDS
if ready(r, rid, c, n) and not (REP / "arms" / f"{t2.tag(r, rid, c, n)}.csv").exists()]
print(f"{len(jobs)} arm jobs, {workers} workers, device {device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(arms_job, j): j[:4] 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)
# ------------------------------------------------------------------------------------------------------ summary
def h2a_readings(runs: dict, rng) -> tuple[pd.DataFrame, dict]:
rows, out = [], {}
sets = {"point_ties": POINT, "with_B3d": POINT + ["B3d"]}
for reg in H2A_REGIMES:
if reg not in runs:
continue
for cand in ("B3d-Sa", "M2-Sa"):
for sname, comp in sets.items():
cells, gv = s18.h2a_cells(runs[reg], cand, comp, rng, N_BOOT)
c1 = cells[cells.c == 1.0]
complete = bool(len(cells) == 4 and (cells.n_rid == len(RIDS)).all() and (cells.n_seed == len(SEEDS)).all())
passed = bool(len(c1) == 2 and c1.cell_pass.all() and gv["zero_drift_guard"])
out[f"{reg}/{cand}/{sname}"] = {"c1_cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}",
"zero_drift_ratio_per_N": gv["zero_drift_ratio_per_N"],
"zero_drift_guard": gv["zero_drift_guard"], "regime_pass": passed,
"complete": complete}
rows.append(cells.assign(regime=reg, candidate=cand, competitors=sname))
return (pd.concat(rows, ignore_index=True) if rows else pd.DataFrame()), out
def h2b_readings(runs: dict, sp: pd.DataFrame, rng) -> tuple[pd.DataFrame, dict]:
from scipy.stats import spearmanr
rows = []
for reg in C1_REGIMES:
if reg not in runs:
continue
for (c, N), g in runs[reg].groupby(["c", "n_train"]):
rows.append({"regime": reg, "c": c, "n_train": N} | s18.pair_cell(g, "M2-Sa", "B3d-Sa", rng, N_BOOT))
t = pd.DataFrame(rows)
if t.empty:
return t, {}
t = t.merge(sp.rename(columns={"setting": "regime"})[["regime", "c", "n_train", "sigma_post_ms"]], on=["regime", "c", "n_train"], how="left")
t["wide"] = t.sigma_post_ms >= s18.WIDE_MS
out = {}
for N, g in t.groupby("n_train"):
wide = g[g.wide]
need = math.ceil(s18.WIDE_FRAC * len(wide) - 1e-9)
out[f"n{N}"] = {"wide_cells": len(wide), "wide_pass": int(wide.cell_pass.sum()),
"test_a_pass": bool(len(wide) > 0 and wide.cell_pass.sum() >= need),
"spearman_sigma_ratio": float(spearmanr(g.sigma_post_ms, g.ratio).statistic) if len(g) > 2 else None,
"role": "primary" if N == 16 else "reported only"}
return t, out
def stage_summary() -> None:
S = REP / "summary"
S.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(0)
runs = s18.load_runs(REP)
sp = s18.sigma_post(REP)
sp.to_csv(S / "sigma_post.csv", index=False)
verdict: dict = {"declaration": check_declaration()}
h2a_tab, verdict["R-H2a"] = h2a_readings(runs, rng)
h2a_tab.to_csv(S / "h2a.csv", index=False)
h2b_tab, verdict["R-H2b"] = h2b_readings(runs, sp, rng)
h2b_tab.to_csv(S / "h2b.csv", index=False)
# B2: sigma_a arm at -5 dB (rule of scripts/18 sigma_a_arm)
sa_rows = []
for name in SA_ARMS:
if name in runs:
cells, _ = s18.h2a_cells(runs[name], "B3d-Sa", POINT, rng, N_BOOT)
c1 = cells[cells.c == 1.0]
verdict.setdefault("B2", {})[name] = {"cells_pass": f"{int(c1.cell_pass.sum())}/{len(c1)}",
"pass": bool(len(c1) == 2 and c1.cell_pass.all()),
"ratio_per_N": {int(r.n_train): float(r.ratio) for r in c1.itertuples()}}
sa_rows.append(c1.assign(setting=name))
if sa_rows:
pd.concat(sa_rows, ignore_index=True).to_csv(S / "sigma_a.csv", index=False)
# arms: reproduction check and ratios
files = sorted(f for f in (REP / "arms").glob("*.csv") if not f.name.endswith("_diag.csv")) if (REP / "arms").exists() else []
ratio_df = pd.DataFrame()
if files:
new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
new = new.groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
reg = pd.concat([d.assign(regime=k) for k, d in runs.items() if k in C1_REGIMES], ignore_index=True)
reg = reg.groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
a = new[new.method == "B3d-Sa"].merge(reg[reg.method == "B3d-Sa"], on=["regime", "rid", "c", "n_train", "seed"], suffixes=("", "_reg"))
dev = float((a.band_rmse - a.band_rmse_reg).abs().max()) if len(a) else float("nan")
verdict["arms_selfcheck"] = {"n_rows": int(len(a)), "n_expected": int((new.method == "B3d-Sa").sum()),
"band_rmse_abs_dev_max": dev, "ok": bool(len(a) and dev <= 1e-6)}
allr = pd.concat([reg, new[new.method.isin(ARMS)]], ignore_index=True)
pairs = {"A": ("B3d-Sa", "SMC-MAP"), "B": ("SMC-MAP", "best"), "C": ("Anchor-LS", "best"), "D": ("B3d-Sa", "best"),
"F": ("M2-Sa", "SMC-MAP"), "G": ("M2-Sa", "Ctl-GP"), "H": ("Ctl-GP", "B3d-Sa"), "I": ("M2-Sa", "B3d-Sa")}
rows = []
for (regime, c, N), g in allr.groupby(["regime", "c", "n_train"]):
best = min(POINT, key=lambda m: g[g.method == m].band_rmse.mean())
per = {m: g[g.method == m].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean() for m in g.method.unique()}
for tag, (x, y) in pairs.items():
y = best if y == "best" else y
if x not in per or y not in per or len(per[x]) < len(RIDS) or len(per[y]) < len(RIDS):
continue
rows.append({"cmp": tag, "regime": regime, "c": c, "n_train": N, "num": x, "den": y, "best": best}
| ci.intervals(per[x], per[y], rng))
if all(m in per for m in ("B3d-Sa", "M2-Sa", "Ctl-GP")):
pm, rml, ctl = per["B3d-Sa"].mean(), per["M2-Sa"].mean(), per["Ctl-GP"].mean()
rows.append({"cmp": "gain_frac_ctl", "regime": regime, "c": c, "n_train": N, "num": "Ctl-GP", "den": "M2-Sa",
"ratio": float((pm - ctl) / (pm - rml)) if pm != rml else float("nan")})
ratio_df = pd.DataFrame(rows)
ratio_df.to_csv(S / "ratios.csv", index=False)
A = ratio_df[ratio_df.cmp == "A"]
B = ratio_df[(ratio_df.cmp == "B") & (ratio_df.c == 1.0)]
verdict["R-MAP"] = {"averaging_at_most_3pct": bool(len(A) and (A.ratio >= 0.97).all()),
"A_ratio_range": [float(A.ratio.min()), float(A.ratio.max())] if len(A) else None,
"mode_beats_best_tie_c1": bool(len(B) and (B.ratio < 1).all()),
"B_ratio_range_c1": [float(B.ratio.min()), float(B.ratio.max())] if len(B) else None,
"n_cells_A": int(len(A)), "n_cells_B_c1": int(len(B))}
dg = [pd.read_csv(f) for f in sorted((REP / "arms").glob("*_diag.csv"))]
if dg:
pd.concat(dg, ignore_index=True).groupby(["regime", "c", "n_train"])[
["SMC-MAP_warp_rmse_ms", "Anchor-LS_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "map_rank_frac_ll", "ctl_sd_ratio"]
].mean().to_csv(S / "arm_warp_errors.csv")
(S / "verdict.json").write_text(json.dumps(verdict, indent=1, default=str))
pd.set_option("display.width", 250)
txt = ["# R6 replication (realizations 16-23) and sigma_a arm at -5 dB", "", "```json", json.dumps(verdict, indent=1, default=str), "```", "",
"## sigma_post", "", sp.round(3).to_markdown(index=False), ""]
if len(h2a_tab):
cols = ["regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "seeds_improve",
"rids_improve", "cell_pass"]
txt += ["## R-H2a cells", "", h2a_tab[cols].round(3).to_markdown(index=False), ""]
if len(h2b_tab):
txt += ["## R-H2b cells (M2-Sa / B3d-Sa)", "", h2b_tab.drop(columns=["ratio_lo", "ratio_hi"], errors="ignore").round(3).to_markdown(index=False), ""]
if sa_rows:
txt += ["## B2 sigma_a arm at -5 dB (B3d-Sa vs point ties)", "",
pd.read_csv(S / "sigma_a.csv")[["setting", "n_train", "best", "ratio", "ratio_lo", "ratio_hi", "seeds_improve",
"rids_improve", "cell_pass"]].round(3).to_markdown(index=False), ""]
if len(ratio_df):
cols = [c for c in ["cmp", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi"] if c in ratio_df]
txt += ["## Ratios of band RMSE (arms)", "", ratio_df[cols].round(3).to_markdown(index=False), ""]
if (S / "arm_warp_errors.csv").exists():
txt += ["## Warp errors of the arms (ms)", "", pd.read_csv(S / "arm_warp_errors.csv").round(3).to_markdown(index=False), ""]
(S / "summary.md").write_text("\n".join(txt) + "\n")
print("\n".join(txt))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=["fingerprints", "arms", "summary"], required=True)
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=2)
args = ap.parse_args()
sha = check_declaration()
P = run_d2.load_protocol(check=True)
if run_d2.check_rids(RIDS, P) is not None:
raise SystemExit("realizations 16-23 must be outside the protocol_p2r grid")
print(f"declaration {sha[:12]}; protocol_p2 and its inputs match the locked hash", flush=True)
REP.mkdir(parents=True, exist_ok=True)
if args.stage == "fingerprints":
stage_fingerprints(P)
elif args.stage == "arms":
stage_arms(P, args.device, args.workers)
else:
stage_summary()
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

View File

@@ -0,0 +1,183 @@
"""R6 B3 (declared in docs/research/r6-replication.md, hashed before the first run; exploratory; outside every lock and the
reproduction archives): why sigma_a = 3.5 ms widens the SMC posterior at 10 dB.
--stage hyper CPU: MAP-II drift hyperparameters (m_g, sigma_g, ell) of pipeline.fit_cell_hyper at sigma_a = 3.5, 7, 14 ms
for R10, c = 1, N = 4 and 16, realizations 8-15 -> outputs/replication/hyper_sigma_a.csv
--stage post GPU: the SMC posterior of the locked scripts/14 run_job at sigma_a = 3.5 ms with (m_g, sigma_g, ell) taken
from the sigma_a = 7 ms fit. fit_cell_hyper is replaced in this process only; no locked file is edited.
-> outputs/replication/posterior/R10_sa3.5_fixhyper/
--stage summary sigma_post, warp RMSE and warp coverage90 of the fixed-hyper, refitted and nominal posteriors
-> outputs/replication/fixhyper_summary.{csv,md}
CUDA_VISIBLE_DEVICES=0 .venv/bin/python scripts/47_r6_fixed_hyper.py --stage all --device cuda:0 --gpu-mem-gb 1.5
"""
from __future__ import annotations
import argparse
import dataclasses
import hashlib
import importlib.util
import json
import os
import time
for _k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ.setdefault(_k, "2")
import numpy as np
import pandas as pd
import yaml
from ml_porosity.paths import REPO_ROOT, outputs_dir
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
s14 = load_script("14_diag_posterior.py")
s18 = load_script("18_summarize_p2r.py")
run_d2 = s14.run_d2
DECL = REPO_ROOT / "docs" / "research" / "r6-replication.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "r6-replication.sha256"
OUT = outputs_dir() / "replication"
P2R = outputs_dir() / "p2r"
RIDS = list(range(8, 16))
NS = [4, 16]
SA_GRID = [3.5, 7.0, 14.0]
SA_TEST, SA_NOMINAL = 3.5, 7.0
SNR, DENS = 10.0, "full"
POST_DIR = OUT / "posterior" / "R10_sa3.5_fixhyper"
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")
return actual
def cell_obs(rid: int, N: int, P: dict):
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.registration.warp_prior import WarpHyper
cfg = yaml.safe_load((REPO_ROOT / P["inputs"]["d2_config"]["path"]).read_text())
hg = load_horizon_grid(cfg["horizons"], REPO_ROOT / cfg["horizon_cache"])
prior = json.loads((REPO_ROOT / P["inputs"]["warp_prior"]["path"]).read_text())["fits"][P["inputs"]["warp_prior"]["fit"]]
wav = np.load(REPO_ROOT / P["inputs"]["wavelet"]["path"])[P["inputs"]["wavelet"]["key"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
obs = [R.observe(w, 1.0, SNR, cfg["anchors"]["sigma_a_ms"], DENS) for w in R.pool[:N]]
return R, obs
def stage_hyper(P: dict) -> None:
from ml_porosity.registration import pipeline
rows = []
for rid in RIDS:
for N in NS:
R, obs = cell_obs(rid, N, P)
for sa in SA_GRID:
reg = run_d2.reg_settings(P) | {"sigma_a_ms": sa}
h, info = pipeline.fit_cell_hyper(R, obs, reg, 0)
rows.append(dict(rid=rid, n_train=N, sigma_a_reg=sa, **h.as_dict(),
log_marginal=float(info["log_marginal"]), at_bound=str(info["at_bound"])))
print(f"hyper r{rid} N{N} done", flush=True)
df = pd.DataFrame(rows)
df.to_csv(OUT / "hyper_sigma_a.csv", index=False)
print(df.groupby(["n_train", "sigma_a_reg"])[["m_g", "sigma_g", "ell_ms"]].agg(["mean", "min", "max"]).round(4).to_string())
def stage_post(P: dict, device: str, mem_gb: float) -> None:
from ml_porosity.registration import pipeline
orig = pipeline.fit_cell_hyper
used = []
def fixed(R, obs, reg, seed=0):
h, info = orig(R, obs, reg | {"sigma_a_ms": SA_NOMINAL}, seed)
h = dataclasses.replace(h, sigma_a_ms=reg["sigma_a_ms"])
used.append(h.as_dict())
return h, info
pipeline.fit_cell_hyper = fixed
POST_DIR.mkdir(parents=True, exist_ok=True)
st = {"snr_db": SNR, "anchor_density": DENS, "sigma_a_reg": SA_TEST, "wavelets": ["estR"], "smc_seed": None}
jobs = [(rid, 1.0, N, 0, 1024, P, POST_DIR, device, mem_gb, st) for N in sorted(NS, reverse=True) for rid in RIDS
if not (POST_DIR / f"{s14.job_tag(rid, 1.0, N, 0)}.csv").exists()]
print(f"{len(jobs)} posterior jobs (fixed hyperparameters), device {device}", flush=True)
t0 = time.time()
for i, j in enumerate(jobs, 1):
used.clear()
s14.run_job(j)
tag = s14.job_tag(j[0], j[1], j[2], j[3])
(POST_DIR / f"{tag}_hyper.json").write_text(json.dumps(used, indent=1))
print(f"[{i}/{len(jobs)}] {tag} done ({time.time() - t0:.0f} s)", flush=True)
pipeline.fit_cell_hyper = orig
def stage_summary() -> None:
rows = []
for name, d in [("nominal sigma_a 7", P2R / "posterior" / "R10"), ("sigma_a 3.5 refit", P2R / "posterior" / "R10_sa3.5"),
("sigma_a 3.5 fixed hyper", POST_DIR), ("sigma_a 14 refit", P2R / "posterior" / "R10_sa14")]:
for N in NS:
for rid in RIDS:
f = d / f"r{rid}_c1_n{N}_s0.csv"
if not f.exists():
continue
g = pd.read_csv(f)
g = g[(g.method == "SMC_g_acf") & (g.wavelet == "estR")]
rows.append(dict(setting=name, n_train=N, rid=rid, sigma_post_ms=float(g.warp_width90_ms.mean() / s18.Z90),
warp_rmse_ms=float(g.warp_rmse_ms.mean()), warp_cov90=float(g.warp_cov90.mean())))
df = pd.DataFrame(rows)
df.to_csv(OUT / "fixhyper_cells.csv", index=False)
s = df.groupby(["setting", "n_train"]).agg(n_rid=("rid", "nunique"), sigma_post_ms=("sigma_post_ms", "mean"),
warp_rmse_ms=("warp_rmse_ms", "mean"), warp_cov90=("warp_cov90", "mean")).reset_index()
s.to_csv(OUT / "fixhyper_summary.csv", index=False)
fx = s[s.setting == "sigma_a 3.5 fixed hyper"]
if len(fx) == len(NS) and (fx.n_rid == len(RIDS)).all():
sp = fx.sigma_post_ms
reading = ("drift-prior refit" if (sp <= 1.0).all() else "anchor-likelihood interaction" if (sp >= 2.0).all() else "both")
else:
reading = "incomplete"
txt = ["# R6 B3: sigma_a = 3.5 ms with fixed drift hyperparameters", "",
"sigma_post = mean 90% warp width / 3.29 (as scripts/18), SMC_g_acf, estR; mean over train wells then realizations.", "",
s.round(3).to_markdown(index=False), "", f"Declared reading: **{reading}**"]
hp = OUT / "hyper_sigma_a.csv"
if hp.exists():
h = pd.read_csv(hp).groupby(["n_train", "sigma_a_reg"])[["m_g", "sigma_g", "ell_ms", "log_marginal"]].mean()
txt += ["", "MAP-II drift hyperparameters (mean over realizations 8-15):", "", h.round(4).to_markdown()]
(OUT / "fixhyper_summary.md").write_text("\n".join(txt) + "\n")
(OUT / "fixhyper_reading.json").write_text(json.dumps({"reading": reading}, indent=1))
print("\n".join(txt))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=["hyper", "post", "summary", "all"], default="all")
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--gpu-mem-gb", type=float, default=1.5)
args = ap.parse_args()
sha = check_declaration()
P = run_d2.load_protocol(check=True)
if run_d2.check_rids(RIDS, P) is None:
raise SystemExit("expected the protocol_p2r main grid")
print(f"declaration {sha[:12]}; protocol_p2 and protocol_p2r with their inputs match the locked hashes", flush=True)
OUT.mkdir(parents=True, exist_ok=True)
if args.stage in ("hyper", "all"):
stage_hyper(P)
if args.stage in ("post", "all"):
stage_post(P, args.device, args.gpu_mem_gb)
if args.stage in ("summary", "all"):
stage_summary()
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

171
scripts/48_r6_cheap.py Normal file
View File

@@ -0,0 +1,171 @@
"""R6 A1-A3 (declared in docs/research/r6-replication.md, hashed before the first run; outside every lock and the
reproduction archives). CPU only, reads existing outputs.
A1 cluster-calibrated sign test for the blind-well power of T3 (outputs/t3/cells.csv, nstar.csv)
A2 reference sensitivity at F-11 T2, the only Volve well with a VSP (outputs/p4/summary/metrics.csv; descriptive, post hoc)
A3 90% coverage of single networks at equal training length (outputs/lambda_limit, outputs/p2r; descriptive, post hoc)
.venv/bin/python scripts/48_r6_cheap.py -> outputs/r6/{a1_*.csv, a2_*.csv, a3_*.csv, summary.md}
"""
from __future__ import annotations
import hashlib
import json
import os
for _k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
os.environ.setdefault(_k, "2")
import numpy as np
import pandas as pd
from scipy import stats
from ml_porosity.paths import REPO_ROOT, outputs_dir
DECL = REPO_ROOT / "docs" / "research" / "r6-replication.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "r6-replication.sha256"
OUT = outputs_dir() / "r6"
ALPHA, POWER = 0.05, 0.80
N_GRID = np.arange(4, 41)
RHO_GRID = [0.0, 0.05, 0.1, 0.2, 0.3, 0.45]
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")
return actual
# ------------------------------------------------------------------------------------------------------------ A1
def sf(k: int | None, n: int, p: float, rho: float) -> float:
"""P(X >= k), X ~ beta-binomial(n, mean p, ICC rho) (binomial at rho = 0); as scripts/27 pass_prob. k = None: the
test can never reject (no critical value at this n), so the rejection probability is 0."""
if k is None:
return 0.0
if rho <= 1e-9:
return float(stats.binom.sf(k - 1, n, p))
a, b = p * (1 / rho - 1), (1 - p) * (1 / rho - 1)
return float(stats.betabinom.sf(k - 1, n, a, b))
def k_crit(n: int, rho: float) -> int | None:
for k in range(n + 1):
if sf(k, n, 0.5, rho) <= ALPHA:
return k
return None
def ceiling(p: float, rho: float) -> float:
"""lim_{n->inf} power of the calibrated test: P(B > q_rho), B ~ Beta(mean p, ICC rho), q_rho the 0.95 quantile of the null Beta."""
if rho <= 1e-9:
return 1.0 if p > 0.5 else 0.0
s = 1 / rho - 1
q = stats.beta.ppf(1 - ALPHA, 0.5 * s, 0.5 * s)
return float(stats.beta.sf(q, p * s, (1 - p) * s))
def fmt(v) -> str:
return "none" if v is None or (isinstance(v, float) and np.isnan(v)) else f"{int(v)}"
def a1() -> list[str]:
size = []
for rho in RHO_GRID:
for n in N_GRID:
kn, kc = k_crit(int(n), 0.0), k_crit(int(n), rho)
size.append(dict(rho=rho, n=int(n), k_nominal=kn, size_nominal=sf(kn, int(n), 0.5, rho),
k_calibrated=kc, size_calibrated=sf(kc, int(n), 0.5, rho)))
size = pd.DataFrame(size)
size.to_csv(OUT / "a1_size.csv", index=False)
cells = pd.read_csv(outputs_dir() / "t3" / "cells.csv")
nstar_pub = pd.read_csv(outputs_dir() / "t3" / "nstar.csv")[["regime", "n_train", "sigma_ref", "nstar_sign"]]
rows, curves = [], []
for r in cells.itertuples():
pw = []
for n in N_GRID:
kc = k_crit(int(n), r.icc)
pwr = sf(kc, int(n), r.p_better, r.icc)
kn = k_crit(int(n), 0.0)
pw.append(pwr)
curves.append(dict(regime=r.regime, n_train=r.n_train, sigma_ref=r.sigma_ref, n_test=int(n), k_calibrated=kc,
power_calibrated=pwr, size_nominal=sf(kn, int(n), 0.5, r.icc)))
ok = [int(n) for n, p in zip(N_GRID, pw) if p >= POWER]
rows.append(dict(regime=r.regime, n_train=r.n_train, sigma_ref=r.sigma_ref, p_better=r.p_better, icc=r.icc,
nstar_calibrated=min(ok) if ok else None, power40_calibrated=pw[-1], ceiling=ceiling(r.p_better, r.icc),
size_nominal_n10=sf(k_crit(10, 0.0), 10, 0.5, r.icc), size_nominal_n20=sf(k_crit(20, 0.0), 20, 0.5, r.icc)))
res = pd.DataFrame(rows).merge(nstar_pub, on=["regime", "n_train", "sigma_ref"])
res.to_csv(OUT / "a1_nstar.csv", index=False)
pd.DataFrame(curves).to_csv(OUT / "a1_power.csv", index=False)
show = size[size.n.isin([5, 10, 20, 40])].pivot(index="rho", columns="n", values="size_nominal")
zero = res[res.sigma_ref == 0.0]
txt = ["## A1: sign test calibrated for within-realization correlation", "",
"Size of the nominal sign test (alpha = 0.05) under a beta-binomial null with ICC rho:", "",
show.round(3).to_markdown(), "",
"Blind wells for 80% power, nominal (published) vs calibrated critical value, and the n -> infinity ceiling:", "",
res[["regime", "n_train", "sigma_ref", "p_better", "icc", "nstar_sign", "nstar_calibrated", "power40_calibrated",
"ceiling"]].round(3).to_markdown(index=False), "",
"Exact reference (sigma_ref = 0), n* nominal -> calibrated (none = 80% not reached by 40 wells): "
+ "; ".join(f"{r.regime} N={r.n_train}: {fmt(r.nstar_sign)} -> {fmt(r.nstar_calibrated)} (ceiling {r.ceiling:.2f})"
for r in zero.itertuples())]
return txt
# ------------------------------------------------------------------------------------------------------------ A2
def a2() -> list[str]:
d = pd.read_csv(outputs_dir() / "p4" / "summary" / "metrics.csv")
d = d[(d.test_well == "F-11 T2") & (d.sigma_a_ms == 7.0) & (d.seed.astype(str) == "ensemble") & d.scored]
t = d.pivot_table(index=["scheme", "reference"], columns="method", values="rmse", aggfunc="mean")
n = d.groupby(["scheme", "reference"]).n.first()
t = t.assign(n_samples=n)
t.to_csv(OUT / "a2_f11t2.csv")
meth = [m for m in ["B3b", "B3c", "B3c-R", "B3d-Sa", "M2-Sa"] if m in t]
span_ref = t[meth].groupby(level="scheme").agg(lambda s: s.max() - s.min()) # per method, across references
span_meth = (t[meth].max(1) - t[meth].min(1)).rename("range_across_methods")
rank = t[meth].rank(axis=1).astype(int)
txt = ["## A2: F-11 T2 (the only Volve well with a VSP), ensemble RMSE (p.u.) by reference, sigma_a = 7 ms", "",
t.round(3).to_markdown(), "", "Range across references, per method:", "", span_ref.round(3).to_markdown(), "",
"Range across methods, per reference:", "", span_meth.round(3).to_markdown(), "", "Rank (1 = best):", "",
rank.to_markdown()]
return txt
# ------------------------------------------------------------------------------------------------------------ A3
def a3() -> list[str]:
files = [f for f in sorted((outputs_dir() / "lambda_limit" / "cells").glob("*.csv")) if not f.name.endswith("_seff.csv")]
L = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
L = L[L.method.isin(["B3d-Sa", "M2-Sa"])]
per = L.groupby(["regime", "c", "n_train", "method", "budget", "rid", "seed"]).coverage_90.mean().reset_index()
cells = sorted(set(map(tuple, L[["regime", "c", "n_train"]].drop_duplicates().to_numpy().tolist())))
o = []
for regime in sorted({c[0] for c in cells}):
r = pd.read_csv(outputs_dir() / "p2r" / "train" / regime / "runs.csv")
r = r[r.method == "Oracle"].assign(regime=regime, budget=500)
o.append(r)
O = pd.concat(o, ignore_index=True)
O = O[[tuple(x) in cells for x in O[["regime", "c", "n_train"]].to_numpy().tolist()]]
O = O.groupby(["regime", "c", "n_train", "method", "budget", "rid", "seed"]).coverage_90.mean().reset_index()
allc = pd.concat([per, O], ignore_index=True)
tab = allc.groupby(["regime", "c", "n_train", "method", "budget"]).coverage_90.mean().unstack(["method", "budget"])
tab.to_csv(OUT / "a3_coverage90.csv")
rng = allc.groupby(["method", "budget"]).coverage_90.mean()
by = allc.groupby(["regime", "c", "n_train", "method", "budget"]).coverage_90.mean().groupby(["method", "budget"]).agg(["min", "max"])
txt = ["## A3: 90% coverage of single networks (mean over test wells, seeds, realizations), N = 16", "",
f"Cells: {len(cells)} (those of the lambda-limit arm; no 10 dB c = 1 cell). Oracle: 500 iterations from P2r.", "",
tab.round(3).to_markdown(), "", "Range over cells:", "", by.round(3).to_markdown(), "",
"Mean over cells:", "", rng.round(3).to_markdown()]
return txt
def main() -> None:
sha = check_declaration()
OUT.mkdir(parents=True, exist_ok=True)
txt = [f"# R6 cheap analyses (declaration {sha[:12]})", ""] + a1() + [""] + a2() + [""] + a3()
(OUT / "summary.md").write_text("\n".join(txt) + "\n")
print("\n".join(txt))
if __name__ == "__main__":
main()

66
scripts/run_r6.sh Executable file
View File

@@ -0,0 +1,66 @@
#!/usr/bin/env bash
# R6 (declared in docs/research/r6-replication.md, hashed before the first run; outside every lock).
# scripts/run_r6.sh fingerprints # B1: fingerprints of realizations 16-23 (before any training)
# scripts/run_r6.sh b3 # B3: sigma_a = 3.5 ms with fixed drift hyperparameters (scripts/47)
# scripts/run_r6.sh c1 R10 R0 Rm5 # B1: c = 1 posteriors + the seven registered methods, realizations 16-23
# scripts/run_r6.sh c0 R10 R0 Rm5 # B1: c = 0 (zero-drift guard of H2a)
# scripts/run_r6.sh sa # B2: Rm5, sigma_a,reg 3.5 and 14 ms, realizations 8-15
# scripts/run_r6.sh arms # B1: SMC-MAP, Anchor-LS, Ctl-GP (scripts/46)
# scripts/run_r6.sh summary # scripts/46 summary -> outputs/replication/summary/
# Posteriors and training use the locked scripts 14 and 15 with the arguments of scripts/run_p2r_main.sh (no
# --save-preds); both skip jobs that already have a CSV, so any stage can be restarted with the same command.
set -euo pipefail
cd "$(dirname "$0")/.."
PY="${PY:-.venv/bin/python}"
DEVICE="${DEVICE:-cuda:0}"
WORKERS="${WORKERS:-2}"
THREADS="${THREADS:-2}"
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
NUMBA_NUM_THREADS=$THREADS VECLIB_MAXIMUM_THREADS=$THREADS
OUT=outputs/replication
BUDGETS=outputs/p2/diag/train/budgets.json
post() { # rids snr dens c-list out [extra]
local rids="$1" snr="$2" dens="$3" cs="$4" out="$5"; shift 5
"$PY" scripts/14_diag_posterior.py --rids $rids --n 4 16 --seeds 0 --particles 1024 --wavelets estR \
--device "$DEVICE" --workers "$WORKERS" --gpu-mem-gb 1.5 --c $cs --snr "$snr" --anchor-density "$dens" \
--out-dir "$OUT/posterior/$out" "$@"
}
train() {
local rids="$1" snr="$2" dens="$3" cs="$4" out="$5"; shift 5
"$PY" scripts/15_diag_train.py --rids $rids --n 4 16 --seeds 0 1 2 3 4 --reg-seed 0 --device "$DEVICE" \
--workers "$WORKERS" --variants a --methods Oracle B3b B3c B3c-R B3d B3d-Sa M2-Sa --budgets-from "$BUDGETS" \
--c $cs --snr "$snr" --anchor-density "$dens" --post-dir "$OUT/posterior/$out" --out-dir "$OUT/train/$out" "$@"
}
regime() {
"$PY" -c "import sys, yaml; r = yaml.safe_load(open('configs/d2_synth_p2r.yaml'))['regimes'][sys.argv[1]]; \
print(r['snr_db'], r['anchor_density'])" "$1"
}
NEW="16 17 18 19 20 21 22 23"
OLD="8 9 10 11 12 13 14 15"
stage="$1"; shift
echo "== r6 $stage $* ($(date -u +%FT%TZ))"
case "$stage" in
fingerprints) CUDA_VISIBLE_DEVICES= "$PY" scripts/46_r6_replication.py --stage fingerprints ;;
b3)
CUDA_VISIBLE_DEVICES= "$PY" scripts/47_r6_fixed_hyper.py --stage hyper
"$PY" scripts/47_r6_fixed_hyper.py --stage post --device "$DEVICE" --gpu-mem-gb 1.5
CUDA_VISIBLE_DEVICES= "$PY" scripts/47_r6_fixed_hyper.py --stage summary ;;
c1|c0)
[[ -f "$OUT/fingerprints.json" ]] || { echo "run the fingerprints stage first" >&2; exit 1; }
c=${stage#c}
for r in "$@"; do
read -r snr dens <<< "$(regime "$r")"
post "$NEW" "$snr" "$dens" "$c" "$r"
train "$NEW" "$snr" "$dens" "$c" "$r"
done ;;
sa)
read -r snr dens <<< "$(regime Rm5)"
for sa in 3.5 14; do
post "$OLD" "$snr" "$dens" 1 "Rm5_sa$sa" --sigma-a-reg "$sa"
train "$OLD" "$snr" "$dens" 1 "Rm5_sa$sa" --sigma-a-reg "$sa"
done ;;
arms) "$PY" scripts/46_r6_replication.py --stage arms --device "$DEVICE" --workers "$WORKERS" ;;
summary) CUDA_VISIBLE_DEVICES= "$PY" scripts/46_r6_replication.py --stage summary ;;
*) echo "unknown stage: $stage" >&2; exit 2 ;;
esac
echo "== r6 $stage $* done ($(date -u +%FT%TZ))"