"""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}//, 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/.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//... s44.P2R = REP # point_warps reads the tempering gamma from REP/posterior//... 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()