Files
ML-Porosity/scripts/47_r6_fixed_hyper.py
lamlvh d0d2cd3c82 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>
2026-11-12 04:49:53 +00:00

184 lines
8.2 KiB
Python

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