Files
ML-Porosity/scripts/48_r6_cheap.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

172 lines
8.7 KiB
Python

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