Files
ML-Porosity/scripts/45_referee_r5_followups.py
lamlvh 760dbfea4f 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>
2026-11-10 14:47:07 +00:00

147 lines
6.3 KiB
Python

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