Address simulated referee reports: same-information point ties, wording, benchmark sigma_a stress

- Exploratory analyses, each declared and hashed before computing and kept
  outside every lock: sharpening transfer, permutation null of the decision
  rules and a truth-free warp check (script 42); BCa and t intervals and the
  comparison with the anchor-only mean (43); point ties with the same
  information as the SMC posterior, SMC-MAP and Anchor-LS (44); a powered
  independence test for the Berkson structure and sign, Wilcoxon and paired-t
  power for the number of blind wells (45).
- Findings: the mode of the SMC posterior already gives most of the gain over
  deterministic ties and averaging adds at most 3%; no sharpening was seen
  and the tie error is not independent of the data; paired tests need 25-50%
  fewer blind wells than the sign test.
- Paper: "hash-locked" replaces "pre-registered"; Berkson sharpening is a
  prediction that failed where testable; new Sec. 3.3 on the benchmark
  package; abstract, introduction, Secs. 5-7, App. C and conclusions revised;
  eight further verified references.
- Benchmark package: two anchor-uncertainty settings (R10__sa3.5, R10__sa14);
  658 tasks, 1316 content hashes (no earlier hash changed), 46,320 reference
  runs.
- Reproduction package: post-review outputs archived, six new verify steps;
  the clean-room check passes 18/18 steps with no differing file.
- Record the Fable (R4) and Opus (R5) referee reports.

No verdict, threshold or locked protocol changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 14:47:07 +00:00
parent 894fbdfc59
commit 760dbfea4f
46 changed files with 4768 additions and 124 deletions

View File

@@ -64,6 +64,7 @@ RUN = ["setting", "c", "n_train", "rid", "seed", "method"]
PRED = re.compile(r"r(\d+)_c([\d.]+)_n(\d+)_s(\d+)")
WIDE_MS = 1.5 # rules.wide of protocol_bench
N_BOOT = 2000
SIGMA_A_STRESS = (3.5, 14.0) # σ_a stated in the task file of the settings R10__sa3.5 and R10__sa14 (true value 7 ms)
# ---------------------------------------------------------------- tasks
@@ -76,6 +77,9 @@ def settings(p: dict) -> list[dict]:
for r in st["S2"]["regimes"] for axis in st["S2"]["presets"].values() for pr in axis]
out += [dict(setting=f"{r}__s8d{d:g}", regime=r, preset="nominal", delta_ms=float(d), cs=st["S8"]["drift_factors"])
for r in st["S8"]["regimes"] for d in st["S8"]["delta_ms"]]
# σ_a stress (added 10/11/2026, after review): the data are those of R10, c = 1; the task file states the wrong σ_a
out += [dict(setting=f"R10__sa{v:g}", regime="R10", preset="nominal", delta_ms=None, cs=[1.0], sigma_a_stated=v, tag=f"sa{v:g}")
for v in SIGMA_A_STRESS]
return out
@@ -83,7 +87,7 @@ def task_arrays(inp, R, s: dict, c: float) -> tuple[dict, dict]:
reg = inp.regime(s["regime"])
obs, test = inp.observe(R, c, s["regime"], len(R.pool))
task = {"rid": np.int64(R.rid), "c": np.float64(c), "snr_db": np.float64(reg["snr_db"]),
"anchor_density": np.array(reg["anchor_density"]), "sigma_a_ms": np.float64(inp.sigma_a),
"anchor_density": np.array(reg["anchor_density"]), "sigma_a_ms": np.float64(s.get("sigma_a_stated", inp.sigma_a)),
"t_seis_ms": R.t_ext, "t_label_ms": R.t_main, "tau_ms": R.tau_fine,
"train_names": np.array([o["name"] for o in obs]), "train_seis": np.stack([o["seis"] for o in obs]),
"train_phi_log": np.stack([o["phi_log"] for o in obs]), "train_ai_log": np.stack([o["ai_log"] for o in obs]),
@@ -133,7 +137,10 @@ def analyst(p: dict, inp) -> dict:
"patch": "3 × 3 traces around each well: inline offset −1..1 (outer) × crossline offset −1..1 "
"(inner); the centre trace is index 4; labels refer to the centre trace"},
"anchors": {"sigma_a_ms": inp.sigma_a,
"model": "unit-boundary picks: anchor_tau_ms exact on the log, anchor_t_ms = true time + N(0, σ_a²)"},
"model": "unit-boundary picks: anchor_tau_ms exact on the log, anchor_t_ms = true time + N(0, σ_a²)",
"note": "the σ_a to use is the `sigma_a_ms` of the task file; it equals sigma_a_ms here except in the settings "
"R10__sa3.5 and R10__sa14, where it is deliberately wrong (the picks were generated with the value "
"given here)"},
"rock_physics_nominal": {"phi_dt": [synth_d2.PHI_DT_A, synth_d2.PHI_DT_B], "rhob": [synth_d2.RHO_0, synth_d2.RHO_1],
"formula": "DT = (φ − A)/B µs/m; RHOB = ρ0 − ρ1·φ kg/m³; AI = RHOB·1e6/DT; "
"train_ai_log = AI(train_phi_log)"},
@@ -170,7 +177,7 @@ def generate(a) -> None:
(out / d / rel).parent.mkdir(parents=True, exist_ok=True)
np.savez_compressed(out / d / rel, **arr)
files[f"{d}/{rel}"] = content_sha(arr)
rows.append({"split": sp, "setting": s["setting"], "regime": s["regime"], "preset": s["preset"],
rows.append({"split": sp, "setting": s["setting"], "regime": s["regime"], "preset": s.get("tag", s["preset"]),
"delta_ms": s["delta_ms"], "c": float(c), "rid": rid, "snr_db": float(task["snr_db"]),
"anchor_density": str(task["anchor_density"]), "n_pool": len(task["train_names"]),
"n_test": len(task["test_names"]), "n_anchors": len(task["anchor_tau_ms"]),
@@ -238,6 +245,9 @@ def setting_of(df: pd.DataFrame) -> pd.Series:
def reference_runs(p: dict) -> pd.DataFrame:
parts = [S.p2r_runs(p).assign(study="P2r")]
for v in SIGMA_A_STRESS: # P2r σ_a arm: methods registered with σ_a = v on data generated with 7 ms
f = REPO_ROOT / p["reference"]["p2r"]["root"] / "train" / f"R10_sa{v:g}" / "runs.csv"
parts.append(pd.read_csv(f).assign(regime="R10", preset=f"sa{v:g}", study="P2r-sa"))
for st in ("S1", "S2", "S3", "S4", "S8"):
parts.append(S.load_study(p, bench_root(), st)[1].assign(study=st))
df = pd.concat(parts, ignore_index=True)
@@ -251,6 +261,7 @@ def reference_runs(p: dict) -> pd.DataFrame:
def sigma_post(p: dict) -> pd.DataFrame:
a = pd.read_csv(REPO_ROOT / p["reference"]["p2r"]["root"] / "summary" / "sigma_post.csv")
a["setting"] = a["setting"].str.replace("_sa", "__sa", regex=False)
d = bench_root() / "posterior"
b = S.sigma_post_table({x.name: x for x in sorted(d.iterdir()) if x.is_dir()})
cols = ["setting", "c", "n_train", "sigma_post_ms", "warp_rmse_ms", "warp_cov90"]

View File

@@ -138,6 +138,15 @@ RULES = [
("bench/s[12348]/train/*.json", "f3_results", "scripts/34_run_bench.py train"),
("bench/posterior/*.csv", "f3_results", "scripts/34_run_bench.py posterior"),
("bench/posterior/*.json", "f3_results", "scripts/34_run_bench.py posterior"),
# exploratory analyses after review (outside every lock; declared in docs/research/ and hashed before running)
("referee_r4/meta.json", None, ""),
("referee_r4/tmp/*", None, ""),
("referee_r4/*", "f3_results", "scripts/42_referee_r4.py"),
("referee_r5/meta*.json", None, ""),
("referee_r5/*", "f3_results", "scripts/43_referee_r5_ci.py, scripts/45_referee_r5_followups.py"),
("lambda_limit/*", "f3_results", "scripts/41_lambda_limit.py"),
("point_tie/*", "f3_results", "scripts/44_point_tie_arm.py"),
("band_spectra/*", "f3_results", "scripts/40_band_spectra.py"),
# P3 F3 field test (protocol_f3; reproduce from tag protocol-f3)
("p3/summary/predictions.npz", "f3_predictions", "scripts/20_summarize_f3.py"),
("p3/summary/*", "f3_results", "scripts/20_summarize_f3.py"),
@@ -179,6 +188,12 @@ STEPS = [
("bench_summarize", ["scripts/34_run_bench.py", "summarize"], "files"),
("bench_verdicts", ["scripts/36_bench_verdicts.py"], "files"),
("bench_tables", ["scripts/37_bench_package.py", "tables", "--out", "outputs/bench/package"], "files"),
("referee_r4_b1", ["scripts/42_referee_r4.py", "--stage", "b1"], "files"),
("referee_r4_b2", ["scripts/42_referee_r4.py", "--stage", "b2"], "files"),
("referee_r5_ci", ["scripts/43_referee_r5_ci.py"], "files"),
("referee_r5_f2", ["scripts/45_referee_r5_followups.py", "--stage", "f2"], "files"),
("lambda_limit_summary", ["scripts/41_lambda_limit.py", "--stage", "summary"], "files"),
("point_tie_summary", ["scripts/44_point_tie_arm.py", "--stage", "summary"], "files"),
("figures_main", ["scripts/22_paper_figures.py"], "figures"),
("figures_bench", ["scripts/38_bench_figures.py"], "figures"),
("s8_flipband", ["scripts/38_bench_figures.py", "--flipband"], "stdout"),

390
scripts/42_referee_r4.py Normal file
View File

@@ -0,0 +1,390 @@
"""Three exploratory analyses requested by simulated referee R4 (declared in docs/research/referee-r4-analyses.md,
hashed before the first run; outside every lock and the reproduction archives).
B1 transfer of the posterior-mean network relative to the Oracle network (test of Berkson sharpening)
B2 null pass probability of the decision rules under label permutation
B3 truth-free disagreement between the SMC mean warp and a correlation tie
Reads saved predictions, runs, particles and phase files only; B3 regenerates the locked synthetic realizations to
rebuild the correlation-tie warps. No network is trained.
python scripts/42_referee_r4.py --stage all [--workers 8]
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import itertools
import json
import math
import os
import time
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
from pathlib import Path
import numpy as np
import pandas as pd
from ml_porosity.paths import REPO_ROOT
DECL = REPO_ROOT / "docs" / "research" / "referee-r4-analyses.md"
DECL_SHA = REPO_ROOT / "docs" / "research" / "referee-r4-analyses.sha256"
OUT = REPO_ROOT / "outputs" / "referee_r4"
P2R = REPO_ROOT / "outputs" / "p2r"
BENCH = REPO_ROOT / "outputs" / "bench"
NFFT, DT_S, F_MIN, F_HI = 256, 0.004, 6.0, 15.0
P2R_BUDGET = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
POINT_TIES = ["B3b", "B3c", "B3c-R"]
RATIO_MAX, DPCC_MIN, SEED_FRAC = 0.90, 0.05, 4 / 5
def check_declaration() -> str:
want = DECL_SHA.read_text().split()[0]
got = hashlib.sha256(DECL.read_bytes()).hexdigest()
if got != want:
raise SystemExit(f"declaration hash mismatch: {got} != {want}")
return got
def cross_spectrum(Y: np.ndarray, P: np.ndarray) -> np.ndarray:
"""As scripts/12_h1_blur.py: Hann taper, per-well mean removed, summed over wells."""
w = np.hanning(Y.shape[1])
Fy = np.fft.rfft((Y - Y.mean(1, keepdims=True)) * w, NFFT)
Fp = np.fft.rfft((P - P.mean(1, keepdims=True)) * w, NFFT)
return np.real(np.conj(Fy) * Fp).sum(0)
# ---------------------------------------------------------------- B1
def cell_spectra(files: list[Path], methods: dict[str, int]) -> dict[str, dict[int, np.ndarray]]:
"""S[method][rid] = cross-spectrum summed over test wells and seeds (one realization per file)."""
S = {m: {} for m in methods}
for f in files:
rid = int(f.name.split("_")[0][1:])
with np.load(f) as z:
Y = z["y_true"].astype(float)
for m, b in methods.items():
keys = [k for k in z.files if k.startswith(f"{m}/s") and k.endswith(f"/b{b}/mu")]
if keys:
S[m][rid] = sum(cross_spectrum(Y, z[k].astype(float)) for k in keys)
return S
def transfer_stats(S: dict, m: str, rids: list[int], sigma: float, f: np.ndarray) -> dict:
So = sum(S["Oracle"][r] for r in rids)
Sm = sum(S[m][r] for r in rids)
band = f >= F_MIN
use = band & (So >= 0.1 * So[band].max())
H = Sm / So
gm = lambda sel: float(np.exp(np.mean(np.log(np.clip(H[sel], 1e-3, None))))) if sel.any() else float("nan")
bk = np.exp(2 * np.pi ** 2 * (sigma / 1000.0) ** 2 * f ** 2)
return {"r": gm(use), "r_hi": gm(use & (f >= F_HI)), "n_freq": int(use.sum()),
"f_lo": float(f[use].min()), "f_hi": float(f[use].max()),
"r_Bk": float(np.exp(np.mean(np.log(bk[use])))), "r_Bk_hi": float(np.exp(np.mean(np.log(bk[use & (f >= F_HI)])))) if (use & (f >= F_HI)).any() else float("nan")}
def b1(n_boot: int = 2000) -> pd.DataFrame:
f = np.fft.rfftfreq(NFFT, DT_S)
sp_s1 = pd.read_csv(BENCH / "summary" / "s1_cells.csv")
sp_p2r = pd.read_csv(P2R / "summary" / "sigma_post.csv").rename(columns={"setting": "regime"})
rows = []
jobs = []
for reg in ["R10", "R0", "Rm5", "R0h", "R10tb"]:
d = BENCH / "s1" / "train" / reg / "cells"
for c, N in sorted({(float(p.stem.split("_")[1][1:]), int(p.stem.split("_")[2][1:])) for p in d.glob("r*_c*_n*.npz")}):
files = sorted(d.glob(f"r*_c{c:g}_n{N}.npz"))
primary = (c, N) in {(1.0, 8), (1.5, 16)}
jobs.append(("S1", reg, c, N, files, {"Oracle": 500, "B3d-Sa": 500, "M2-Sa": 500, "B3d-Sa@250": 250}, primary))
d = P2R / "train" / reg / "cells"
for c in (0, 1, 2):
for N in (4, 16):
files = sorted(d.glob(f"r*_c{c}_n{N}.npz"))
if files:
jobs.append(("P2r", reg, float(c), N, files, dict(P2R_BUDGET), False))
for study, reg, c, N, files, methods, primary in jobs:
real = {m.split("@")[0]: b for m, b in methods.items() if "@" not in m}
S = cell_spectra(files, real)
if "B3d-Sa@250" in methods:
S["B3d-Sa@250"] = cell_spectra(files, {"B3d-Sa": 250})["B3d-Sa"]
if study == "S1":
s = sp_s1[(sp_s1.regime == reg) & np.isclose(sp_s1.c, c) & (sp_s1.n_train == N)].sigma_post_ms
else:
s = sp_p2r[(sp_p2r.regime == reg) & np.isclose(sp_p2r.c, c) & (sp_p2r.n_train == N)].sigma_post_ms
sigma = float(s.iloc[0]) if len(s) else float("nan")
cand = ["B3d-Sa", "M2-Sa"] + (["B3d-Sa@250"] if study == "S1" else [])
if study == "P2r":
best = None
runs = pd.read_csv(P2R / "train" / reg / "runs.csv")
g = runs[np.isclose(runs.c, c) & (runs.n_train == N) & runs.method.isin(POINT_TIES)]
if len(g):
best = g.groupby("method").band_rmse.mean().idxmin()
cand.append(best)
for m in cand:
rids = sorted(set(S["Oracle"]) & set(S[m]))
if not rids:
continue
st = transfer_stats(S, m, rids, sigma, f)
rng = np.random.default_rng(0)
bs = np.array([[transfer_stats(S, m, list(rng.choice(rids, len(rids))), sigma, f)[k] for k in ("r", "r_hi")]
for _ in range(n_boot)])
lo, hi = np.nanpercentile(bs, [2.5, 97.5], axis=0)
rows.append({"study": study, "regime": reg, "c": c, "n_train": N, "primary": primary,
"method": m, "budget": methods.get(m),
"oracle_budget": 500, "sigma_post_ms": sigma, "n_rid": len(rids)}
| st | {"r_lo": lo[0], "r_hi_ci": hi[0], "rhi_lo": lo[1], "rhi_hi": hi[1]})
df = pd.DataFrame(rows)
def reading(r):
if r.r_lo > 1:
return "sharpening"
if r.r_hi_ci < 1:
return "blur"
return "not detected"
df["reading"] = df.apply(reading, axis=1)
df["half_ci"] = (df.r_hi_ci - df.r_lo) / 2
df["powered"] = (df.r_Bk - 1) > df.half_ci
return df
# ---------------------------------------------------------------- B2
def grids(run: pd.DataFrame, cand: str, ref: str) -> tuple[np.ndarray, np.ndarray, list[int]]:
"""(rid, seed) grids of band RMSE and band PCC: arrays of shape (2, n_rid, n_seed) for (cand, ref)."""
a = run[run.method == cand].pivot_table(index="rid", columns="seed", values=["band_rmse", "band_pcc"])
b = run[run.method == ref].pivot_table(index="rid", columns="seed", values=["band_rmse", "band_pcc"]).reindex_like(a)
if a.isna().any().any() or b.isna().any().any():
raise SystemExit(f"incomplete grid for {cand} vs {ref}")
R = np.stack([a["band_rmse"].to_numpy(), b["band_rmse"].to_numpy()])
P = np.stack([a["band_pcc"].to_numpy(), b["band_pcc"].to_numpy()])
return R, P, a.index.tolist()
def rule_pass(R: np.ndarray, P: np.ndarray, kind: str, flip: np.ndarray | None = None) -> np.ndarray:
"""R, P: (2, n_rid, n_seed) for (cand, ref). flip: (K, n_rid, n_seed) booleans, True swaps the methods in that
unit. Returns (K,) pass flags of the protocol_p2 cell rule ('cell') or the 'better' rule."""
if flip is None:
flip = np.zeros((1,) + R.shape[1:], bool)
ra = np.where(flip, R[1], R[0]); rb = np.where(flip, R[0], R[1])
pa = np.where(flip, P[1], P[0]); pb = np.where(flip, P[0], P[1])
def imp(axis):
xa, xb, ya, yb = ra.mean(axis), rb.mean(axis), pa.mean(axis), pb.mean(axis)
if kind == "cell":
return (xa <= RATIO_MAX * xb) | (ya >= yb + DPCC_MIN)
return xa < xb
s, r = imp(1), imp(2) # per seed (mean over rids), per rid (mean over seeds)
n_s, n_r = R.shape[2], R.shape[1]
return (s.sum(1) >= math.ceil(SEED_FRAC * n_s - 1e-9)) & (r.sum(1) > n_r / 2)
def null_probs(cells: list[tuple], n_mc: int = 20000, need: int | None = None) -> dict:
"""cells: list of (R, P, kind, rids). Joint pass probability for all cells under (a) realization-level swaps
(exact enumeration; one swap vector shared by the cells) and (b) unit-level swaps (Monte Carlo, independent)."""
rids = sorted(set().union(*[set(c[3]) for c in cells]))
combos = np.array(list(itertools.product([False, True], repeat=len(rids))))
res_a, res_b, obs = [], [], []
rng = np.random.default_rng(1)
for R, P, kind, rr in cells:
idx = [rids.index(r) for r in rr]
fa = np.repeat(combos[:, idx][:, :, None], R.shape[2], axis=2)
res_a.append(rule_pass(R, P, kind, fa))
res_b.append(rule_pass(R, P, kind, rng.random((n_mc,) + R.shape[1:]) < 0.5))
obs.append(bool(rule_pass(R, P, kind)[0]))
A, B = np.array(res_a), np.array(res_b)
need = len(cells) if need is None else need # verdict passes if at least `need` cells pass
return {"observed": sum(obs) >= need, "need": need, "observed_cells": obs,
"p_rid": float((A.sum(0) >= need).mean()), "p_unit": float((B.sum(0) >= need).mean()),
"p_rid_cells": A.mean(1).tolist(), "p_unit_cells": B.mean(1).tolist()}
def b2(n_mc: int) -> tuple[pd.DataFrame, dict]:
from ml_porosity.benchmark.protocol import load_protocol
from ml_porosity.benchmark.summary import load_study
p = load_protocol(check_inputs=False)
p2r = pd.concat([pd.read_csv(P2R / "train" / reg / "runs.csv").assign(regime=reg)
for reg in ["R10", "R0", "Rm5", "R0h", "R10tb"]], ignore_index=True)
p2r = p2r[p2r.method.map(P2R_BUDGET).notna()]
s1 = pd.concat([p2r, load_study(p, BENCH, "S1")[1]], ignore_index=True)
s2 = load_study(p, BENCH, "S2")[1]
s4 = load_study(p, BENCH, "S4")[1]
s8 = load_study(p, BENCH, "S8")[1]
h2b = pd.read_csv(P2R / "summary" / "h2b.csv")
def best_of(run, comp):
return run[run.method.isin(comp)].groupby("method").band_rmse.mean().idxmin()
def sel(run, **kw):
m = np.ones(len(run), bool)
for k, v in kw.items():
m &= np.isclose(run[k], v) if isinstance(v, float) else (run[k] == v).to_numpy()
return run[m]
verdicts = {}
def add(name, specs, need=None):
cells, desc = [], []
for run, cand, comp, kind, label in specs:
ref = comp if isinstance(comp, str) else best_of(run, comp)
R, P, rr = grids(run, cand, ref)
cells.append((R, P, kind, rr))
desc.append({"cell": label, "cand": cand, "ref": ref, "kind": kind, "n_rid": R.shape[1], "n_seed": R.shape[2],
"ratio": float(R[0].mean() / R[1].mean()), "dpcc": float(P[0].mean() - P[1].mean())})
res = null_probs(cells, n_mc, need)
for d, o, pa, pb in zip(desc, res["observed_cells"], res["p_rid_cells"], res["p_unit_cells"]):
d |= {"observed_pass": o, "p_rid": pa, "p_unit": pb}
verdicts[name] = {"observed": res["observed"], "need": res["need"], "p_rid": res["p_rid"], "p_unit": res["p_unit"], "cells": desc}
for reg in ["R10", "R0", "Rm5"]:
add(f"P2r-H2a/{reg}", [(sel(p2r, regime=reg, c=1.0, n_train=N), "B3d-Sa", POINT_TIES, "cell", f"{reg} c1 N{N}") for N in (4, 16)])
wide = h2b[(h2b.n_train == 16) & h2b.wide]
add("P2r-H2b(a)", [(sel(p2r, regime=r.regime, c=float(r.c), n_train=16), "M2-Sa", "B3d-Sa", "better", f"{r.regime} c{r.c:g} N16")
for r in wide.itertuples()], need=math.ceil(2 / 3 * len(wide) - 1e-9))
add("S1-H1", [(sel(s1, regime="R10", c=1.5, n_train=N), "B3d-Sa", POINT_TIES, "cell", f"R10 c1.5 N{N}") for N in (4, 16)])
add("S2-H1/drift", [(sel(s2, regime="R10", preset="dr_L1", c=1.0, n_train=N), "B3d-Sa", POINT_TIES, "cell", f"R10 dr_L1 c1 N{N}") for N in (4, 16)])
add("S4-H1", [(sel(s4, regime="R10", c=1.0, n_train=N), "B3d-Sa-TCN", [f"{m}-TCN" for m in POINT_TIES], "cell", f"R10 TCN c1 N{N}") for N in (4, 16)])
add("S4-H2", [(sel(s4, regime=reg, c=1.0, n_train=16), "M2-Sa-TCN", "B3d-Sa-TCN", "better", f"{reg} TCN c1 N16") for reg in ("Rm5", "R0h")])
add("S8-H2", [(sel(s8, regime=reg, delta_ms=float(d), n_train=16), "BK2", "PM2", "better", f"{reg} d{d} N16")
for reg in ("R10", "Rm5") for d in (16, 32)])
rows = [{"verdict": k} | c for k, v in verdicts.items() for c in v["cells"]]
return pd.DataFrame(rows), verdicts
# ---------------------------------------------------------------- B3
def b3_job(job) -> list[dict]:
rid, preset, cells = job
os.environ.setdefault("OMP_NUM_THREADS", "2")
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 import pipeline as pl
from ml_porosity.registration.smc import phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_errors, warp_mean
p = load_protocol(check_inputs=False)
inp = load_inputs(p)
R = inp.realization(rid, None if preset == "nominal" else preset)
reg = inp.reg
f = R.cfg["fine_dt_ms"]
fac = int(round(R.dt / f))
rows = []
for regime, N, post, diagf, postcsv in cells:
obs, _ = inp.observe(R, 1.0, regime, N)
ph = json.loads(Path(str(post).replace("_particles.npz", "_phase.json")).read_text())
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
w0 = statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"])
w_c = pl.fine_wavelet(pl.rotate_phase(w0, ph["phase0"]), fac)
w_r = phase_wavelet(phase_basis(w0, fac), ph["phase_R"])
smc = np.load(post)
diag = pd.read_csv(diagf).set_index("well")
pc = pd.read_csv(postcsv)
pc = pc[(pc.method == "B3c") & (pc.wavelet == "est")].set_index("well")
for i, o in enumerate(obs):
t_b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
tc = tie_b3c(t_b, R.tau_fine, synth_for_warps(R.tau_fine, o["ai_log"], t_b, R.t_fine, R.t_ext, w_c)[0], seis[i], R.t_ext, R.dt)
tr = tie_b3c(t_b, R.tau_fine, synth_for_warps(R.tau_fine, o["ai_log"], t_b, R.t_fine, R.t_ext, w_r)[0], seis[i], R.t_ext, R.dt)
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
tm = warp_mean(R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine), np.zeros(len(U)))
e = lambda t, ref: warp_errors(t[None], R.tau_fine, ref, R.t_main)["warp_rmse_ms"]
row = {"rid": rid, "preset": preset, "regime": regime, "n_train": N, "well": o["name"],
"D": e(tm, tc), "D_R": e(tm, tr), "E_pm": e(tm, o["t_of_tau_true"]),
"E_c": e(tc, o["t_of_tau_true"]), "E_cR": e(tr, o["t_of_tau_true"])}
row["chk_pm"] = row["E_pm"] - float(diag.loc[o["name"], "B3d-Sa_warp_rmse_ms"])
row["chk_cR"] = row["E_cR"] - float(diag.loc[o["name"], "B3c-R_warp_rmse_ms"])
row["chk_c"] = row["E_c"] - float(pc.loc[o["name"], "warp_rmse_ms"])
rows.append(row)
return rows
def b3(workers: int, n_boot: int = 2000) -> tuple[pd.DataFrame, pd.DataFrame]:
presets = ["nominal", "rp_L1", "rp_L2", "wv_L1", "wv_L2", "wv_Q", "dr_L1", "dr_L2"]
jobs = []
for rid in range(8, 16):
for pr in presets:
cells = []
for regime in ("R10", "Rm5"):
for N in (4, 16):
if pr == "nominal":
base = P2R / "posterior" / regime / f"r{rid}_c1_n{N}_s0"
diagf = None
dg = pd.read_csv(P2R / "train" / regime / "diag.csv")
dg = dg[(dg.rid == rid) & np.isclose(dg.c, 1.0) & (dg.n_train == N)]
diagf = OUT / "tmp" / f"diag_{regime}_r{rid}_n{N}.csv"
diagf.parent.mkdir(parents=True, exist_ok=True)
dg.to_csv(diagf, index=False)
else:
base = BENCH / "posterior" / f"{regime}__{pr}" / f"r{rid}_c1_n{N}_s0"
diagf = BENCH / "s2" / "train" / f"{regime}__{pr}" / "cells" / f"r{rid}_c1_n{N}_diag.csv"
cells.append((regime, N, Path(f"{base}_particles.npz"), diagf, Path(f"{base}.csv")))
jobs.append((rid, pr, cells))
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
rows = [r for res in ex.map(b3_job, jobs) for r in res]
w = pd.DataFrame(rows)
from scipy.stats import spearmanr
per = w.groupby(["regime", "n_train", "preset", "rid"])[["D", "D_R", "E_pm", "E_c"]].mean().reset_index()
summ = []
rng = np.random.default_rng(2)
for (regime, N), g in per.groupby(["regime", "n_train"]):
nom = g[g.preset == "nominal"].set_index("rid")
for pr, h in g.groupby("preset"):
h = h.set_index("rid").reindex(nom.index)
row = {"regime": regime, "n_train": N, "preset": pr, "D_mean": h.D.mean(), "D_R_mean": h.D_R.mean(),
"E_pm_mean": h.E_pm.mean(), "E_c_mean": h.E_c.mean(), "D_ratio_vs_nominal": h.D.mean() / nom.D.mean()}
bs = []
for _ in range(n_boot):
k = rng.choice(nom.index, len(nom))
bs.append(h.D.loc[k].mean() / nom.D.loc[k].mean())
row["ratio_lo"], row["ratio_hi"] = np.percentile(bs, [2.5, 97.5])
ww = w[(w.regime == regime) & (w.n_train == N) & (w.preset == pr)]
row["rho_D_Epm"], row["p_D_Epm"] = spearmanr(ww.D, ww.E_pm)
row["rho_D_Epm_minus_Ec"], row["p_D_Epm_minus_Ec"] = spearmanr(ww.D, ww.E_pm - ww.E_c)
row["n_wells"] = len(ww)
summ.append(row)
return w, pd.DataFrame(summ)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", default="all", choices=["all", "b1", "b2", "b3"])
ap.add_argument("--workers", type=int, default=8)
ap.add_argument("--n-mc", type=int, default=20000)
args = ap.parse_args()
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
os.environ.setdefault(k, "2")
sha = check_declaration()
OUT.mkdir(parents=True, exist_ok=True)
meta = {"declaration_sha256": sha, "started_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}
t0 = time.time()
if args.stage in ("all", "b1"):
d = b1()
d.to_csv(OUT / "b1_transfer.csv", index=False)
print(d[d.primary].to_string(), flush=True)
meta["b1_seconds"] = time.time() - t0
if args.stage in ("all", "b2"):
t = time.time()
d, v = b2(args.n_mc)
d.to_csv(OUT / "b2_null.csv", index=False)
(OUT / "b2_null.json").write_text(json.dumps(v, indent=1, default=float))
print(d.to_string(), flush=True)
print({k: (x["observed"], x["p_rid"], x["p_unit"]) for k, x in v.items()}, flush=True)
meta["b2_seconds"] = time.time() - t
if args.stage in ("all", "b3"):
t = time.time()
w, s = b3(args.workers)
w.to_csv(OUT / "b3_wells.csv", index=False)
s.to_csv(OUT / "b3_summary.csv", index=False)
chk = {k: float(w[k].abs().max()) for k in ("chk_pm", "chk_cR", "chk_c")}
meta["b3_selfcheck_max_abs_ms"] = chk
print(chk, flush=True)
print(s.to_string(), flush=True)
meta["b3_seconds"] = time.time() - t
meta["finished_utc"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
prev = json.loads((OUT / "meta.json").read_text()) if (OUT / "meta.json").exists() else {}
(OUT / "meta.json").write_text(json.dumps(prev | meta, indent=1))
if __name__ == "__main__":
main()

131
scripts/43_referee_r5_ci.py Normal file
View File

@@ -0,0 +1,131 @@
"""Alternative confidence intervals for the main ratios and the anchor-mean comparison (declared in
docs/research/referee-r5-ci.md, hashed before the first run; outside every lock and the reproduction archives).
Reads saved runs only; nothing is trained.
python scripts/43_referee_r5_ci.py
"""
from __future__ import annotations
import hashlib
import json
import math
import time
import numpy as np
import pandas as pd
from scipy import stats
from ml_porosity.paths import REPO_ROOT
DECL = REPO_ROOT / "docs" / "research" / "referee-r5-ci.md"
SHA = REPO_ROOT / "docs" / "research" / "referee-r5-ci.sha256"
OUT = REPO_ROOT / "outputs" / "referee_r5"
P2R = REPO_ROOT / "outputs" / "p2r"
BENCH = REPO_ROOT / "outputs" / "bench"
POINT = ["B3b", "B3c", "B3c-R"]
BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
def per_rid(run: pd.DataFrame, m: str) -> pd.Series:
return run[run.method == m].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean()
def intervals(a: pd.Series, b: pd.Series, rng) -> dict:
b = b.reindex(a.index)
x, y = a.to_numpy(), b.to_numpy()
r = x / y
ratio = float(x.mean() / y.mean())
idx = rng.integers(0, len(x), (2000, len(x)))
bs = x[idx].mean(1) / y[idx].mean(1)
pl, ph = np.percentile(bs, [2.5, 97.5])
res = stats.bootstrap((x, y), lambda u, v, axis=-1: u.mean(axis) / v.mean(axis), paired=True, vectorized=True,
n_resamples=9999, method="BCa", random_state=0, confidence_level=0.95)
lr = np.log(r)
se = lr.std(ddof=1) / math.sqrt(len(lr))
t = stats.t.ppf(0.975, len(lr) - 1)
return {"ratio": ratio, "geo_ratio": float(np.exp(lr.mean())), "pct_lo": pl, "pct_hi": ph,
"bca_lo": float(res.confidence_interval.low), "bca_hi": float(res.confidence_interval.high),
"t_lo": float(np.exp(lr.mean() - t * se)), "t_hi": float(np.exp(lr.mean() + t * se)),
"per_rid": ";".join(f"{v:.3f}" for v in r), "n_rid": len(x)}
def main() -> None:
want = SHA.read_text().split()[0]
got = hashlib.sha256(DECL.read_bytes()).hexdigest()
if got != want:
raise SystemExit(f"declaration hash mismatch {got}")
from ml_porosity.benchmark.protocol import load_protocol
from ml_porosity.benchmark.summary import load_study
t0 = time.time()
OUT.mkdir(parents=True, exist_ok=True)
rng = np.random.default_rng(0)
p = load_protocol(check_inputs=False)
p2r = pd.concat([pd.read_csv(P2R / "train" / g / "runs.csv").assign(regime=g) for g in ["R10", "R0", "Rm5", "R0h", "R10tb"]], ignore_index=True)
p2r = p2r[p2r.method.map(BUD).notna()]
s1 = load_study(p, BENCH, "S1")[1]
s2 = load_study(p, BENCH, "S2")[1]
h2b = pd.read_csv(P2R / "summary" / "h2b.csv")
rows = []
def add(group, label, run, cand, ref, thr=None):
if ref is None:
pt = [m for m in POINT if m in set(run.method)]
ref = min(pt, key=lambda m: run[run.method == m].band_rmse.mean())
iv = intervals(per_rid(run, cand), per_rid(run, ref), rng)
rows.append({"group": group, "cell": label, "cand": cand, "ref": ref, "threshold": thr} | iv)
sel = lambda run, **kw: run[np.logical_and.reduce([np.isclose(run[k], v) if isinstance(v, float) else (run[k] == v) for k, v in kw.items()])]
for reg in ["R10", "R0", "Rm5"]:
for N in (4, 16):
add("H2a", f"{reg} c1 N{N}", sel(p2r, regime=reg, c=1.0, n_train=N), "B3d-Sa", None, 0.90)
add("C2 vs anchor mean", f"{reg} c1 N{N}", sel(p2r, regime=reg, c=1.0, n_train=N), "B3d-Sa", "B3d")
for r in h2b[(h2b.n_train == 16) & h2b.wide].itertuples():
add("H2b", f"{r.regime} c{r.c:g} N16", sel(p2r, regime=r.regime, c=float(r.c), n_train=16), "M2-Sa", "B3d-Sa")
for N in (4, 16):
add("S1-H1", f"R10 c1.5 N{N}", sel(s1, regime="R10", c=1.5, n_train=N), "B3d-Sa", None, 0.90)
add("S2-H1 drift", f"R10 dr_L1 c1 N{N}", sel(s2, regime="R10", preset="dr_L1", c=1.0, n_train=N), "B3d-Sa", None, 0.90)
for reg in ["R10", "Rm5"]:
for pr in sorted(s2.preset.dropna().unique()):
g = sel(s2, regime=reg, preset=pr, c=1.0)
if set(g.n_train) >= {4, 16}:
add("S2-H2", f"{reg} {pr}", g, "M2-Sa", "B3d-Sa", 1.02)
df = pd.DataFrame(rows)
# reproduction check against the published percentile intervals (H2b, all cells)
chk = []
for r in h2b[(h2b.n_train == 16) & h2b.wide].itertuples():
x = df[(df.group == "H2b") & (df.cell == f"{r.regime} c{r.c:g} N16")].iloc[0]
chk.append(max(abs(x.pct_lo - r.ratio_lo), abs(x.pct_hi - r.ratio_hi)))
def verdict(lo, hi, thr):
t = 1.0 if (thr is None or pd.isna(thr)) else thr
return "below" if hi < t else ("above" if lo > t else "contains")
for m in ("pct", "bca", "t"):
df[f"{m}_vs_thr"] = [verdict(r[f"{m}_lo"], r[f"{m}_hi"], r.threshold) for _, r in df.iterrows()]
df[f"{m}_vs_1"] = [verdict(r[f"{m}_lo"], r[f"{m}_hi"], None) for _, r in df.iterrows()]
df.to_csv(OUT / "c1_intervals.csv", index=False)
summ = {}
for m in ("bca", "t"):
summ[m] = {"changes_vs_1": int((df[f"{m}_vs_1"] != df["pct_vs_1"]).sum()),
"changes_vs_threshold": int((df[f"{m}_vs_thr"] != df["pct_vs_thr"]).sum()), "n": len(df),
"cells_changed": df[(df[f"{m}_vs_1"] != df["pct_vs_1"]) | (df[f"{m}_vs_thr"] != df["pct_vs_thr"])].apply(lambda r: f"{r.group} {r.cell}", axis=1).tolist()}
pd.set_option("display.width", 250)
print(df[["group", "cell", "ref", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "threshold"]].round(3).to_string())
print(json.dumps(summ, indent=1))
# C2 zero-drift ratios to the Oracle
z = []
for reg in ["R10", "R0", "Rm5"]:
for N in (4, 16):
g = sel(p2r, regime=reg, c=0.0, n_train=N)
o = g[g.method == "Oracle"].band_rmse.mean()
z.append({"regime": reg, "n_train": N} | {m: g[g.method == m].band_rmse.mean() / o for m in ["B3b", "B3c", "B3c-R", "B3d", "B3d-Sa"]})
zd = pd.DataFrame(z)
zd.to_csv(OUT / "c2_zero_drift_vs_oracle.csv", index=False)
print(zd.round(3).to_string())
(OUT / "meta.json").write_text(json.dumps({"declaration_sha256": got, "published_pct_reproduction_max_abs_diff": max(chk), "summary": summ,
"seconds": time.time() - t0}, indent=1))
print("repro max diff", max(chk))
if __name__ == "__main__":
main()

217
scripts/44_point_tie_arm.py Normal file
View File

@@ -0,0 +1,217 @@
"""Point ties with the same information as the SMC posterior (declared in docs/research/point-tie-arm.md, hashed
before the first run; exploratory; outside every lock and the reproduction archives).
Arms (labels at one warp, S = 1, backbone and 250 iterations of B3d-Sa):
SMC-MAP the saved SMC particle with the highest tempered log target log p(u|anchor) + gamma * l(u)
Anchor-LS the mode (Laplace/Gauss-Newton optimum) of the anchor-only posterior, TiePosterior.mu
B3d-Sa is retrained at seed 0 as a reproduction check.
CUDA_VISIBLE_DEVICES=0 .venv/bin/python scripts/44_point_tie_arm.py --stage all --workers 4 --device cuda:0
-> outputs/point_tie/{cells/*.csv, ratios.csv, selfcheck.json, summary.md}
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
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
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
DECL = REPO_ROOT / "docs" / "research" / "point-tie-arm.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "point-tie-arm.sha256"
OUT = outputs_dir() / "point_tie"
P2R = outputs_dir() / "p2r"
REGIMES, CS, NS = ["R10", "R0", "Rm5"], [0.0, 1.0], [4, 16]
BUDGET = 250
ARMS = ["SMC-MAP", "Anchor-LS"]
POINT = ["B3b", "B3c", "B3c-R"]
REG_BUD = {"B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
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 point_warps(cell: dict, regime: str, rid: int, c: float, N: int) -> dict:
"""Per well: the SMC-MAP and Anchor-LS warps (fine grid)."""
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.registration.smc import TiePosterior, phase_basis, phase_wavelet
from ml_porosity.registration.warp_prior import WarpHyper
R, obs, reg, ph, out = cell["R"], cell["obs"], cell["reg"], cell["ph"], cell["out"]
h = WarpHyper(**out["hyper"])
cfg = R.cfg
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"])
pc = pd.read_csv(P2R / "posterior" / regime / f"r{rid}_c{c:g}_n{N}_s0.csv")
pc = pc[(pc.method == "SMC_g_acf") & (pc.wavelet == "estR")].set_index("well")
res = {}
for i, (o, w) in enumerate(zip(obs, cell["wells"])):
T = TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine, R.t_ext, wR,
seis[i], (R.t_main[0], R.t_main[-1]))
gamma = float(pc.loc[o["name"], "gamma"])
base, ll = T.parts(T.z(w["U"]))
score = np.where(np.isfinite(base) & np.isfinite(ll), base + gamma * ll, -np.inf)
k = int(np.argmax(score))
t_map = w["Tf"][k]
t_ls = R.grid.t_of_tau(T.mu[0], T.mu[1:], tau=R.tau_fine)
res[o["name"]] = {"SMC-MAP": t_map, "Anchor-LS": t_ls, "k": k, "gamma": gamma,
"map_rank_frac_ll": float((ll < ll[k]).mean())}
return res
def train_job(job) -> tuple[str, float]:
regime, rid, c, N, seeds, device, out_dir, P = job
import torch
torch.set_num_threads(2)
from ml_porosity.models.bank_train import train_predict
from ml_porosity.registration.ties import warp_errors
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 = point_warps(cell, regime, rid, c, N)
specs, diag = {}, []
for arm in ARMS:
Y = nb(np.stack([cell["lab"](w["y_aa"], pw[w["name"]][arm]) for w in wells]))
specs[arm] = {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1), np.float32), "lam": lam}
specs["B3d-Sa"] = {"kind": "bank", "Y": nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])),
"logpi": np.zeros((N, 1), np.float32), "lam": lam}
for w in wells:
o = w["o"]
err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, 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"]})
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)
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job complete
return stem, time.time() - t0
def registered_runs() -> pd.DataFrame:
parts = []
for reg in REGIMES:
d = pd.read_csv(P2R / "train" / reg / "runs.csv")
d = d[d.method.isin(REG_BUD) & d.c.isin(CS) & d.n_train.isin(NS)]
parts.append(d.assign(regime=reg))
return pd.concat(parts, ignore_index=True)
def summarize(out: Path) -> None:
files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv"))
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()
new = new.rename(columns={"n_train": "n_train"})
reg = registered_runs()[["regime", "rid", "c", "n_train", "method", "seed", "band_rmse"]]
# reproduction check
a = new[new.method == "B3d-Sa"].merge(reg[reg.method == "B3d-Sa"], on=["regime", "rid", "c", "n_train", "seed"], suffixes=("", "_reg"))
sc = {"n_rows": int(len(a)), "n_expected": int((new.method == "B3d-Sa").sum()),
"band_rmse_abs_dev_max": float((a.band_rmse - a.band_rmse_reg).abs().max())}
(out / "selfcheck.json").write_text(json.dumps(sc, indent=1))
allr = pd.concat([reg, new[new.method.isin(ARMS)]], ignore_index=True)
rng = np.random.default_rng(0)
rows = []
pairs = {"A": ("B3d-Sa", "SMC-MAP"), "B": ("SMC-MAP", "best"), "C": ("Anchor-LS", "best"), "D": ("B3d-Sa", "Anchor-LS"),
"E": ("SMC-MAP", "Anchor-LS"), "F": ("M2-Sa", "SMC-MAP")}
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())
for tag, (x, y) in pairs.items():
y = best if y == "best" else y
sx = g[g.method == x].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean()
sy = g[g.method == y].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean()
if len(sx) < 8 or len(sy) < 8:
continue
rows.append({"cmp": tag, "regime": regime, "c": c, "n_train": N, "num": x, "den": y} | ci.intervals(sx, sy, rng))
df = pd.DataFrame(rows)
for m in ("pct", "bca", "t"):
df[f"{m}_vs_1"] = ["below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains") for _, r in df.iterrows()]
df.to_csv(out / "ratios.csv", index=False)
# zero-drift ratios to the Oracle and warp errors
dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True)
dg.groupby(["regime", "c", "n_train"])[["SMC-MAP_warp_rmse_ms", "Anchor-LS_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "map_rank_frac_ll"]].mean().to_csv(out / "warp_errors.csv")
pd.set_option("display.width", 250)
cols = ["cmp", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi"]
txt = ["# point-tie arm", "", json.dumps(sc), "", df[cols].round(3).to_markdown(index=False), "",
"warp errors (ms) and rank of the MAP particle among the particles' log-likelihoods:", "",
pd.read_csv(out / "warp_errors.csv").round(3).to_markdown(index=False)]
(out / "summary.md").write_text("\n".join(txt))
print("\n".join(txt))
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=["train", "summary", "all"], default="all")
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--seeds", type=int, nargs="+", default=t2.SEEDS)
ap.add_argument("--rids", type=int, nargs="+", default=t2.RIDS)
args = ap.parse_args()
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ.setdefault(k, "2")
sha = check_declaration()
(OUT / "cells").mkdir(parents=True, exist_ok=True)
P = run_d2.load_protocol(check=True)
print(f"declaration {sha[:12]} and the locked protocols match", flush=True)
if args.stage in ("train", "all"):
jobs = [(r, rid, c, N, args.seeds, args.device, OUT / "cells", P) for r in REGIMES for c in CS for N in NS for rid in args.rids
if not (OUT / "cells" / f"{t2.tag(r, rid, c, N)}.csv").exists()]
print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(train_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)
if args.stage in ("summary", "all"):
summarize(OUT)
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()

View File

@@ -0,0 +1,146 @@
"""F1 (powered independence test for the Berkson structure) and F2 (sign, Wilcoxon and paired-t power for the number of
blind wells). Declared in docs/research/referee-r5-followups.md, hashed before the first run; exploratory; outside every
lock and the reproduction archives. Reads saved data only; nothing is trained.
python scripts/45_referee_r5_followups.py [--workers 12]
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import math
import os
import time
from concurrent.futures import ProcessPoolExecutor
from multiprocessing import get_context
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" / "referee-r5-followups.md"
SHA = REPO_ROOT / "docs" / "research" / "referee-r5-followups.sha256"
OUT = outputs_dir() / "referee_r5"
REGIMES, CS = ["R10", "R0", "Rm5", "R0h", "R10tb"], [1.0, 2.0]
def load_script(name: str):
spec = importlib.util.spec_from_file_location("s" + name[:2], REPO_ROOT / "scripts" / name)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
return mod
def f1_job(job) -> list[dict]:
regime, c, rid = job
t2 = load_script("32_t2_mechanism.py")
P = t2.run_d2.load_protocol(check=True)
cell = t2.build_cell(regime, rid, c, 16, P, with_register=False)
R, rows = cell["R"], []
for w in cell["wells"]:
off = t2.window_offsets(w, R)
a_true, a_pm = off["a"]["true"], off["a"]["B3d-Sa"]
ap = off["a_particles"]
rows.append({"regime": regime, "c": c, "rid": rid, "well": w["name"], "e": a_true - a_pm, "sigma_post": float(ap.std()),
"a_pm": a_pm, "cover90": float(np.quantile(ap, 0.05) <= a_true <= np.quantile(ap, 0.95))})
return rows
def spear(d: pd.DataFrame, x: str, y: str) -> float:
return float(stats.spearmanr(d[x], d[y]).statistic)
def f1(workers: int, n_boot: int = 2000) -> tuple[pd.DataFrame, pd.DataFrame]:
jobs = [(r, c, rid) for r in REGIMES for c in CS for rid in range(8, 16)]
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
rows = [r for res in ex.map(f1_job, jobs) for r in res]
w = pd.DataFrame(rows).assign(abs_e=lambda d: d.e.abs(), abs_a=lambda d: d.a_pm.abs())
rng = np.random.default_rng(0)
out = []
for (regime, c), g in w.groupby(["regime", "c"]):
groups = {rid: d for rid, d in g.groupby("rid")}
rid_list = list(groups)
b1, b2 = [], []
for _ in range(n_boot):
d = pd.concat([groups[r] for r in rng.choice(rid_list, len(rid_list))])
b1.append(spear(d, "abs_e", "sigma_post"))
b2.append(spear(d, "abs_e", "abs_a"))
out.append({"regime": regime, "c": c, "n_wells": len(g), "rho_abse_sigma": spear(g, "abs_e", "sigma_post"),
"rho_abse_sigma_lo": np.nanpercentile(b1, 2.5), "rho_abse_sigma_hi": np.nanpercentile(b1, 97.5),
"rho_abse_abshat": spear(g, "abs_e", "abs_a"), "rho_abshat_lo": np.nanpercentile(b2, 2.5),
"rho_abshat_hi": np.nanpercentile(b2, 97.5), "cv_sigma_post": float(g.sigma_post.std() / g.sigma_post.mean()),
"cover90": float(g.cover90.mean()), "mean_sigma_post": float(g.sigma_post.mean()),
"rmse_e": float(np.sqrt((g.e ** 2).mean()))})
s = pd.DataFrame(out)
s["independence_rejected"] = (s.rho_abse_sigma_lo > 0) | (s.cv_sigma_post > 0.25)
return w, s
def f2() -> pd.DataFrame:
ind = pd.read_csv(OUT.parent / "t3" / "indicators.csv.gz")
rng = np.random.default_rng(1)
ns = [4, 6, 8, 10, 12, 16, 20, 24, 30, 40]
rows = []
for (regime, n_train, sr), g in ind.groupby(["regime", "n_train", "sigma_ref"]):
lr = {rid: {well: d.ratio.apply(math.log).to_numpy() for well, d in dd.groupby("well")} for rid, dd in g.groupby("rid")}
rids = list(lr)
row = {"regime": regime, "n_train": n_train, "sigma_ref": sr}
for n in ns:
hits = {"sign": 0, "wilcoxon": 0, "t": 0}
for _ in range(1000):
pick = rng.choice(rids, math.ceil(n / 8))
x = np.array([rng.choice(lr[r][wl]) for r in pick for wl in lr[r]])[:n]
hits["sign"] += stats.binomtest(int((x < 0).sum()), n, 0.5, alternative="greater").pvalue < 0.05
if np.all(x == x[0]):
continue
hits["wilcoxon"] += stats.wilcoxon(x, alternative="less").pvalue < 0.05
hits["t"] += stats.ttest_1samp(x, 0.0, alternative="less").pvalue < 0.05
for k, v in hits.items():
row[f"pow_{k}_{n}"] = v / 1000
rows.append(row)
df = pd.DataFrame(rows)
nstar = []
for r in df.itertuples():
d = r._asdict()
e = {"regime": r.regime, "n_train": r.n_train, "sigma_ref": r.sigma_ref}
for k in ("sign", "wilcoxon", "t"):
ok = [n for n in ns if d[f"pow_{k}_{n}"] >= 0.8]
e[f"nstar_{k}"] = min(ok) if ok else None
nstar.append(e)
return df, pd.DataFrame(nstar)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=12)
ap.add_argument("--stage", choices=["all", "f1", "f2"], default="all", help="f1 needs the SMC particle files, which are not in the archives")
args = ap.parse_args()
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS"):
os.environ.setdefault(k, "2")
got = hashlib.sha256(DECL.read_bytes()).hexdigest()
if got != SHA.read_text().split()[0]:
raise SystemExit("declaration hash mismatch")
OUT.mkdir(parents=True, exist_ok=True)
t0 = time.time()
pd.set_option("display.width", 250)
if args.stage in ("all", "f1"):
w, s = f1(args.workers)
w.to_csv(OUT / "f1_wells.csv", index=False)
s.to_csv(OUT / "f1_summary.csv", index=False)
print(s.round(3).to_string(index=False), flush=True)
t1 = time.time()
if args.stage in ("all", "f2"):
p, ns = f2()
p.to_csv(OUT / "f2_power.csv", index=False)
ns.to_csv(OUT / "f2_nstar.csv", index=False)
print(ns.to_string(index=False))
(OUT / "meta_followups.json").write_text(json.dumps({"declaration_sha256": got, "f1_seconds": t1 - t0, "f2_seconds": time.time() - t1}, indent=1))
if __name__ == "__main__":
main()