"""Alternative confidence intervals for the main ratios and the anchor-mean comparison (declared in docs/research/referee-r5-ci.md, hashed before the first run; outside every lock and the reproduction archives). Reads saved runs only; nothing is trained. python scripts/43_referee_r5_ci.py """ from __future__ import annotations import hashlib import json import math import time import numpy as np import pandas as pd from scipy import stats from ml_porosity.paths import REPO_ROOT DECL = REPO_ROOT / "docs" / "research" / "referee-r5-ci.md" SHA = REPO_ROOT / "docs" / "research" / "referee-r5-ci.sha256" OUT = REPO_ROOT / "outputs" / "referee_r5" P2R = REPO_ROOT / "outputs" / "p2r" BENCH = REPO_ROOT / "outputs" / "bench" POINT = ["B3b", "B3c", "B3c-R"] BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250} def per_rid(run: pd.DataFrame, m: str) -> pd.Series: return run[run.method == m].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean() def intervals(a: pd.Series, b: pd.Series, rng) -> dict: b = b.reindex(a.index) x, y = a.to_numpy(), b.to_numpy() r = x / y ratio = float(x.mean() / y.mean()) idx = rng.integers(0, len(x), (2000, len(x))) bs = x[idx].mean(1) / y[idx].mean(1) pl, ph = np.percentile(bs, [2.5, 97.5]) res = stats.bootstrap((x, y), lambda u, v, axis=-1: u.mean(axis) / v.mean(axis), paired=True, vectorized=True, n_resamples=9999, method="BCa", random_state=0, confidence_level=0.95) lr = np.log(r) se = lr.std(ddof=1) / math.sqrt(len(lr)) t = stats.t.ppf(0.975, len(lr) - 1) return {"ratio": ratio, "geo_ratio": float(np.exp(lr.mean())), "pct_lo": pl, "pct_hi": ph, "bca_lo": float(res.confidence_interval.low), "bca_hi": float(res.confidence_interval.high), "t_lo": float(np.exp(lr.mean() - t * se)), "t_hi": float(np.exp(lr.mean() + t * se)), "per_rid": ";".join(f"{v:.3f}" for v in r), "n_rid": len(x)} def main() -> None: want = SHA.read_text().split()[0] got = hashlib.sha256(DECL.read_bytes()).hexdigest() if got != want: raise SystemExit(f"declaration hash mismatch {got}") from ml_porosity.benchmark.protocol import load_protocol from ml_porosity.benchmark.summary import load_study t0 = time.time() OUT.mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(0) p = load_protocol(check_inputs=False) p2r = pd.concat([pd.read_csv(P2R / "train" / g / "runs.csv").assign(regime=g) for g in ["R10", "R0", "Rm5", "R0h", "R10tb"]], ignore_index=True) p2r = p2r[p2r.method.map(BUD).notna()] s1 = load_study(p, BENCH, "S1")[1] s2 = load_study(p, BENCH, "S2")[1] h2b = pd.read_csv(P2R / "summary" / "h2b.csv") rows = [] def add(group, label, run, cand, ref, thr=None): if ref is None: pt = [m for m in POINT if m in set(run.method)] ref = min(pt, key=lambda m: run[run.method == m].band_rmse.mean()) iv = intervals(per_rid(run, cand), per_rid(run, ref), rng) rows.append({"group": group, "cell": label, "cand": cand, "ref": ref, "threshold": thr} | iv) sel = lambda run, **kw: run[np.logical_and.reduce([np.isclose(run[k], v) if isinstance(v, float) else (run[k] == v) for k, v in kw.items()])] for reg in ["R10", "R0", "Rm5"]: for N in (4, 16): add("H2a", f"{reg} c1 N{N}", sel(p2r, regime=reg, c=1.0, n_train=N), "B3d-Sa", None, 0.90) add("C2 vs anchor mean", f"{reg} c1 N{N}", sel(p2r, regime=reg, c=1.0, n_train=N), "B3d-Sa", "B3d") for r in h2b[(h2b.n_train == 16) & h2b.wide].itertuples(): add("H2b", f"{r.regime} c{r.c:g} N16", sel(p2r, regime=r.regime, c=float(r.c), n_train=16), "M2-Sa", "B3d-Sa") for N in (4, 16): add("S1-H1", f"R10 c1.5 N{N}", sel(s1, regime="R10", c=1.5, n_train=N), "B3d-Sa", None, 0.90) add("S2-H1 drift", f"R10 dr_L1 c1 N{N}", sel(s2, regime="R10", preset="dr_L1", c=1.0, n_train=N), "B3d-Sa", None, 0.90) for reg in ["R10", "Rm5"]: for pr in sorted(s2.preset.dropna().unique()): g = sel(s2, regime=reg, preset=pr, c=1.0) if set(g.n_train) >= {4, 16}: add("S2-H2", f"{reg} {pr}", g, "M2-Sa", "B3d-Sa", 1.02) df = pd.DataFrame(rows) # reproduction check against the published percentile intervals (H2b, all cells) chk = [] for r in h2b[(h2b.n_train == 16) & h2b.wide].itertuples(): x = df[(df.group == "H2b") & (df.cell == f"{r.regime} c{r.c:g} N16")].iloc[0] chk.append(max(abs(x.pct_lo - r.ratio_lo), abs(x.pct_hi - r.ratio_hi))) def verdict(lo, hi, thr): t = 1.0 if (thr is None or pd.isna(thr)) else thr return "below" if hi < t else ("above" if lo > t else "contains") for m in ("pct", "bca", "t"): df[f"{m}_vs_thr"] = [verdict(r[f"{m}_lo"], r[f"{m}_hi"], r.threshold) for _, r in df.iterrows()] df[f"{m}_vs_1"] = [verdict(r[f"{m}_lo"], r[f"{m}_hi"], None) for _, r in df.iterrows()] df.to_csv(OUT / "c1_intervals.csv", index=False) summ = {} for m in ("bca", "t"): summ[m] = {"changes_vs_1": int((df[f"{m}_vs_1"] != df["pct_vs_1"]).sum()), "changes_vs_threshold": int((df[f"{m}_vs_thr"] != df["pct_vs_thr"]).sum()), "n": len(df), "cells_changed": df[(df[f"{m}_vs_1"] != df["pct_vs_1"]) | (df[f"{m}_vs_thr"] != df["pct_vs_thr"])].apply(lambda r: f"{r.group} {r.cell}", axis=1).tolist()} pd.set_option("display.width", 250) print(df[["group", "cell", "ref", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "threshold"]].round(3).to_string()) print(json.dumps(summ, indent=1)) # C2 zero-drift ratios to the Oracle z = [] for reg in ["R10", "R0", "Rm5"]: for N in (4, 16): g = sel(p2r, regime=reg, c=0.0, n_train=N) o = g[g.method == "Oracle"].band_rmse.mean() z.append({"regime": reg, "n_train": N} | {m: g[g.method == m].band_rmse.mean() / o for m in ["B3b", "B3c", "B3c-R", "B3d", "B3d-Sa"]}) zd = pd.DataFrame(z) zd.to_csv(OUT / "c2_zero_drift_vs_oracle.csv", index=False) print(zd.round(3).to_string()) (OUT / "meta.json").write_text(json.dumps({"declaration_sha256": got, "published_pct_reproduction_max_abs_diff": max(chk), "summary": summ, "seconds": time.time() - t0}, indent=1)) print("repro max diff", max(chk)) if __name__ == "__main__": main()