"""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()