Files
ML-Porosity/scripts/52_gp_experiments.py
lamlvh eff975cc96 Address simulated GP referee reports: E1-E6 and A1-A9 (exploratory), theory scope, per-well field and anchor-error tables, scorer v1.1, paper_gp and response letter
Experiments declared and hashed before computing (docs/research/gp-review-*.md). The SMC-mean gain holds against a practitioner tie, all budgets and a same-target point tie, but is lost at anchor errors of 2 ms or less and reverses with per-well bulk error. No locked protocol, verdict or threshold changed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 11:20:54 +00:00

549 lines
30 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""GP review, Phase 3: experiments E4, E5, E6 (and E3 if A3 is not sufficient). Declared in
docs/research/gp-review-experiments.md and hashed before the first run; exploratory; outside every lock and the
reproduction archives. The locked scripts 14, 15, 18 and 32 are imported unchanged; the only in-process replacement is
the budget list of `train_predict` in the E6 workers (as declared). E2 and E1 live in scripts 53 and 54.
E4 point tie optimizing the SMC target (L-BFGS-B from the 4 best saved particles), labels at the optimum, NLL, 250
E5 posterior-mean labels (64-member bank mean; 1024-particle mean) trained with the Gaussian likelihood
E6 the seven registered methods of Experiment 2 at 125/250/500 iterations (equal budget)
.venv/bin/python scripts/52_gp_experiments.py --stage e5 --workers 5 --device cuda:0
.venv/bin/python scripts/52_gp_experiments.py --stage e6 --workers 5 --device cuda:0
.venv/bin/python scripts/52_gp_experiments.py --stage e4 --workers 4 --device cuda:0
.venv/bin/python scripts/52_gp_experiments.py --stage summary # -> outputs/gp_review/e{4,5,6}/summary.md
"""
from __future__ import annotations
import argparse
import hashlib
import importlib.util
import json
import os
import time
from concurrent.futures import ProcessPoolExecutor, as_completed
from multiprocessing import get_context
from pathlib import Path
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
t2 = load_script("32_t2_mechanism.py")
ci = load_script("43_referee_r5_ci.py")
run_d2 = t2.run_d2
DECL = REPO_ROOT / "docs" / "research" / "gp-review-experiments.md"
DECL_HASH = REPO_ROOT / "docs" / "research" / "gp-review-experiments.sha256"
OUT = outputs_dir() / "gp_review"
P2R = outputs_dir() / "p2r"
LAMLIM = outputs_dir() / "lambda_limit"
POINT_TIE = outputs_dir() / "point_tie"
RIDS = list(range(8, 16))
SEEDS = [0, 1, 2, 3, 4]
H2A_REGIMES, CS, NS = ["R10", "R0", "Rm5"], [0.0, 1.0], [4, 16]
E_BUDGETS = [125, 250, 500]
PRIMARY = 250
REG_BUD = {"Oracle": 500, "B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250}
SEVEN = list(REG_BUD)
POINT = ["B3b", "B3c", "B3c-R"]
WIDE = [(r, c) for r, c in t2.WIDE16]
NARROW = [(r, c) for r, c in t2.NARROW16]
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 ({actual[:12]} != {expected[:12]})")
return actual
def set_threads(n: int = 2) -> None:
for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"):
os.environ.setdefault(k, str(n))
def bank(Y, logpi, lam) -> dict:
return {"kind": "bank", "Y": np.asarray(Y, np.float32), "logpi": np.asarray(logpi, np.float32), "lam": lam}
def score_rows(cell, key, m, preds, s0, m0, f_c) -> list[dict]:
rows = []
for b, (mu, sg) in preds.items():
mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0
for wt, r in zip(cell["R"].test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)):
rows.append(key | {"method": m, "budget": b, "test_well": wt.name} | r)
return rows
def run_pool(fn, jobs, workers: int, label: str) -> None:
print(f"{label}: {len(jobs)} jobs, {workers} workers", flush=True)
if not jobs:
return
t0 = time.time()
with ProcessPoolExecutor(workers, mp_context=get_context("spawn")) as ex:
futs = {ex.submit(fn, 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)
# ----------------------------------------------------------------------------------------------------------------
# E5: posterior-mean labels with the Gaussian likelihood
# ----------------------------------------------------------------------------------------------------------------
def e5_job(job) -> tuple[str, float]:
regime, rid, c, N, seeds, device, out_dir, 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)
out, wells = 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, np.float64) - m0) / s0).astype(np.float32)
Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])) # B3d-Sa: label at the mean warp
Y_rml = nb(np.stack([w["Y"] for w in wells])) # (N, 64, L) M2-Sa bank
logpi = np.stack([w["logpi"] for w in wells]).astype(np.float64)
Y_mean = (Y_rml.astype(np.float64) * np.exp(logpi)[:, :, None]).sum(1) # label of Mean-MSE (scripts/41)
diag, Y_1024 = [], []
for w in wells:
Yall = cell["lab"](w["y_aa"], w["Tf"]) # (1024, L), all saved particles
ok = np.all(np.isfinite(Yall), 1)
y1024 = Yall[ok].mean(0)
Y_1024.append(y1024)
ypm = cell["lab"](w["y_aa"], w["tm"])[0]
y64 = Y_mean[w["i"]] * s0 + m0
rms = lambda a, b: float(100 * np.sqrt(np.mean((a - b) ** 2)))
diag.append(key | {"well": w["name"], "n_valid_1024": int(ok.sum()), "n_valid_64": int(w["ok"].sum()),
"rms_mean64_vs_pm_pu": rms(y64, ypm), "rms_mean1024_vs_pm_pu": rms(y1024, ypm),
"rms_mean64_vs_mean1024_pu": rms(y64, y1024)})
Y_1024 = nb(np.stack(Y_1024))
z1 = np.zeros((N, 1))
specs = {"Mean-NLL": bank(Y_mean[:, None, :], z1, lam), "Mean-NLL-1024": bank(Y_1024[:, None, :], z1, lam),
"B3d-Sa": bank(Y_pm, z1, lam)}
rows = []
for seed in seeds:
for m, sp in specs.items():
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, E_BUDGETS, device)
rows += [r | {"seed": seed} for r in score_rows(cell, key, m, preds, s0, m0, f_c)]
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job complete
return stem, time.time() - t0
# ----------------------------------------------------------------------------------------------------------------
# E6: equal budgets through the locked scripts/15 run_cell
# ----------------------------------------------------------------------------------------------------------------
def e6_job(job) -> tuple[str, float]:
regime, rid, c, N, seeds, device, cell_dir, P = job
import ml_porosity.models.bank_train as bt
orig = bt.train_predict
if not getattr(orig, "_gp_review_patched", False):
def train_predict(X, Xte, spec, cfg, seed, budgets, device, on_budget=None):
return orig(X, Xte, spec, cfg, seed, list(E_BUDGETS), device, on_budget=on_budget)
train_predict._gp_review_patched = True
bt.train_predict = train_predict # declared replacement: the budget list only
s15 = load_script("15_diag_train.py")
snr, dens = t2.regime_settings()[regime]
st = {"snr_db": snr, "anchor_density": dens, "sigma_a_reg": None, "variants": ["a"], "methods": SEVEN,
"save_preds": True, "budgets": None}
_, dt = s15.run_cell((rid, c, N, seeds, 0, P, device, P2R / "posterior" / regime, cell_dir, st))
return f"{regime}/r{rid}_c{c:g}_n{N}", dt
# ----------------------------------------------------------------------------------------------------------------
# E4: point tie optimizing the SMC target
# ----------------------------------------------------------------------------------------------------------------
def optimize_target(T, gamma: float, Z0s: np.ndarray, h: float = 1e-3, maxiter: int = 200) -> list:
"""L-BFGS-B on −F, F(z) = log p(u|anchor) + gamma * l(u), forward-difference gradient in one batched call."""
from scipy.optimize import minimize
d = Z0s.shape[1]
E = np.eye(d) * h
def F(Zb):
base, ll = T.parts(Zb)
f = base + gamma * ll
return np.where(np.isfinite(f), f, -np.inf)
def fg(z):
f = F(np.vstack([z[None, :], z[None, :] + E]))
f0, fp = f[0], f[1:]
if not np.isfinite(f0):
return 1e12, np.zeros(d)
g = (fp - f0) / h
bad = np.flatnonzero(~np.isfinite(fp))
if bad.size:
fm = F(z[None, :] - E[bad])
g[bad] = np.where(np.isfinite(fm), (f0 - fm) / h, 0.0)
return -f0, -g
res = []
for z0 in Z0s:
r = minimize(fg, z0.astype(float), jac=True, method="L-BFGS-B",
options={"maxiter": maxiter, "ftol": 1e-9, "gtol": 1e-6})
res.append(r)
return res
def e4_job(job) -> tuple[str, float]:
regime, rid, c, N, seeds, device, out_dir, P = job
import torch
torch.set_num_threads(2)
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.models.bank_train import train_predict
from ml_porosity.registration.smc import TiePosterior, phase_basis, phase_wavelet
from ml_porosity.registration.ties import warp_errors
from ml_porosity.registration.warp_prior import WarpHyper
t0 = time.time()
cell = t2.build_cell(regime, rid, c, N, P, with_register=True)
R, obs, reg, ph, out, wells = cell["R"], cell["obs"], cell["reg"], cell["ph"], 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, np.float64) - m0) / s0).astype(np.float32)
h = WarpHyper(**out["hyper"])
fac = int(round(R.dt / R.cfg["fine_dt_ms"]))
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
wR = phase_wavelet(phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), fac), ph["phase_R"])
pc = pd.read_csv(P2R / "posterior" / regime / f"r{rid}_c{c:g}_n{N}_s0.csv")
pc = pc[(pc.method == "SMC_g_acf") & (pc.wavelet == "estR")].set_index("well")
diag, lab_opt, lab_map = [], [], []
for i, (o, w) in enumerate(zip(obs, wells)):
tw = time.time()
T = TiePosterior(R.grid, h, o["tau_k"], o["t_k"], reg["g_max"], R.tau_fine, o["ai_log"], R.t_fine, R.t_ext, wR,
seis[i], (R.t_main[0], R.t_main[-1]))
gamma = float(pc.loc[o["name"], "gamma"])
Z = T.z(w["U"])
base, ll = T.parts(Z)
F0 = np.where(np.isfinite(base) & np.isfinite(ll), base + gamma * ll, -np.inf)
k_map = int(np.argmax(F0)) # SMC-MAP of scripts/44
fin = np.flatnonzero(np.isfinite(F0))
_, first = np.unique(Z[fin], axis=0, return_index=True) # distinct saved particles
cand = fin[first]
starts = cand[np.argsort(-F0[cand])][:4]
res = optimize_target(T, gamma, Z[starts])
pool = [(F0[k], Z[k], "start") for k in starts] + [(-r.fun, r.x, "opt") for r in res if r.fun < 1e11]
f_best, z_best, src = max(pool, key=lambda p: p[0])
b_best, l_best = T.parts(z_best[None, :])
f_chk = float(b_best[0] + gamma * l_best[0])
u = T.u(z_best[None, :])[0]
t_opt = R.grid.t_of_tau(u[0], u[1:], tau=R.tau_fine)[0]
t_map = w["Tf"][k_map]
err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
y_opt = cell["lab"](w["y_aa"], t_opt)[0]
if not np.all(np.isfinite(y_opt)):
raise RuntimeError(f"{stem} {o['name']}: label at the optimum is not finite")
lab_opt.append(y_opt)
lab_map.append(cell["lab"](w["y_aa"], t_map)[0])
diag.append(key | {"well": o["name"], "gamma": gamma, "F_map": float(F0[k_map]), "F_opt": f_chk,
"dF": f_chk - float(F0[k_map]), "base_map": float(base[k_map]), "ll_map": float(ll[k_map]),
"base_opt": float(b_best[0]), "ll_opt": float(l_best[0]), "source": src,
"n_starts": int(len(starts)), "n_improved": int(sum(-r.fun > F0[k] + 1e-9 for r, k in zip(res, starts))),
"nit_max": int(max(r.nit for r in res)), "nfev_sum": int(sum(r.nfev for r in res)),
"converged": int(sum(bool(r.success) for r in res)),
"z_dist_opt_map": float(np.linalg.norm(z_best - Z[k_map])),
"SMC-opt_warp_rmse_ms": err(t_opt), "SMC-MAP_warp_rmse_ms": err(t_map),
"B3d-Sa_warp_rmse_ms": err(w["tm"]), "seconds": time.time() - tw})
z1 = np.zeros((N, 1))
specs = {"SMC-opt": bank(nb(np.stack(lab_opt))[:, None, :], z1, lam),
"SMC-MAP": bank(nb(np.stack(lab_map))[:, None, :], z1, lam)}
rows = []
for seed in seeds:
for m, sp in specs.items():
if m == "SMC-MAP" and seed != 0: # reproduction check of scripts/44 at seed 0
continue
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [PRIMARY], device)
rows += [r | {"seed": seed} for r in score_rows(cell, key, m, preds, s0, m0, f_c)]
pd.DataFrame(diag).to_csv(out_dir / f"{stem}_diag.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False)
return stem, time.time() - t0
# ----------------------------------------------------------------------------------------------------------------
# summaries
# ----------------------------------------------------------------------------------------------------------------
def side(r: dict, m: str = "pct") -> str:
return "below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains")
def ratio_table(runs: pd.DataFrame, pairs: dict, cells, rng, budget_col: str | None = None) -> pd.DataFrame:
"""runs: per (regime, c, n_train, rid, seed, method[, budget]) band_rmse. pairs: tag -> (num, den | 'best')."""
rows = []
groups = ["regime", "c", "n_train"] + ([budget_col] if budget_col else [])
for k, g in runs.groupby(groups):
if (k[0], k[1], k[2]) not in cells:
continue
have = set(g.method)
best = min((m for m in POINT if m in have), key=lambda m: g[g.method == m].band_rmse.mean(), default=None)
for tag, (x, y) in pairs.items():
y = best if y == "best" else y
if x not in have or y not in have:
continue
sx, sy = ci.per_rid(g, x), ci.per_rid(g, y)
if len(sx) < len(RIDS) or len(sy) < len(RIDS):
continue
r = ci.intervals(sx, sy, rng)
rows.append(dict(zip(groups, k)) | {"cmp": tag, "num": x, "den": y} | r)
df = pd.DataFrame(rows)
for m in ("pct", "bca", "t"):
df[f"{m}_vs_1"] = [side(r, m) for _, r in df.iterrows()]
return df
def per_run(cells_csv: list[Path], extra: tuple = ()) -> pd.DataFrame:
d = pd.concat([pd.read_csv(f) for f in cells_csv], ignore_index=True)
keys = ["regime", "rid", "c", "n_train", "method", "seed", "budget", *extra]
num = [c for c in d.columns if c not in keys + ["test_well"] and pd.api.types.is_numeric_dtype(d[c])]
return d.groupby(keys, as_index=False)[num].mean()
def three_way(df: pd.DataFrame, tag: str, cells, need: int, words: tuple[str, str, str]) -> dict:
d = df[(df.cmp == tag) & df.apply(lambda r: (r.regime, r.c) in cells, axis=1)]
nb, na = int((d.pct_vs_1 == "below").sum()), int((d.pct_vs_1 == "above").sum())
reading = words[0] if nb >= need else (words[1] if na >= need else words[2])
return {"n_cells": int(len(d)), "ci_below_1": nb, "ci_above_1": na, "rule": f">= {need} of {len(cells)}",
"reading": reading, "ratio_range": [float(d.ratio.min()), float(d.ratio.max())] if len(d) else None}
def summary_e5(rng) -> None:
out = OUT / "e5"
files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv"))
if not files:
print("E5: no cells yet")
return
new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
cells = sorted({(r, c) for r, c in new[["regime", "c"]].drop_duplicates().itertuples(index=False)})
reg = t2.registered_cells([(r, c, 16) for r, c in cells])
keys = ["regime", "c", "rid", "seed", "method", "test_well"]
rep = new[(new.method == "B3d-Sa") & (new.budget == PRIMARY)]
mg = rep.merge(reg[keys + ["band_rmse", "rmse", "nll"]], on=keys, suffixes=("", "_reg"))
dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in ("band_rmse", "rmse", "nll"))
sc = {"n_rows": int(len(mg)), "n_expected": int(len(rep)), "abs_dev_max": dev, "pass": bool(len(mg) == len(rep) and dev <= 1e-9)}
ll = [f for f in sorted((LAMLIM / "cells").glob("*_n16.csv")) if not f.name.endswith("_seff.csv")]
old = pd.concat([pd.read_csv(f) for f in ll], ignore_index=True)
old = old[old.method.isin(["M2-Sa", "Bank-lam0", "Mean-MSE"])]
allr = pd.concat([new, old], ignore_index=True)
runs = allr.groupby(["regime", "rid", "c", "n_train", "method", "seed", "budget"], as_index=False)[
["band_rmse", "rmse", "coverage_90", "mean_sigma", "nll"]].mean()
pairs = {"R5a": ("Mean-NLL", "B3d-Sa"), "R5b": ("Mean-NLL", "Mean-MSE"), "R5c": ("M2-Sa", "Mean-NLL"),
"D1": ("Bank-lam0", "Mean-NLL"), "D2": ("Mean-NLL-1024", "Mean-NLL")}
df = ratio_table(runs, pairs, set((r, c, 16) for r, c in cells), rng, budget_col="budget")
df.to_csv(out / "ratios.csv", index=False)
d250 = df[df.budget == PRIMARY]
complete = all((r, c) in cells for r, c in WIDE)
reading = {"selfcheck": sc, "complete_wide": complete} | ({
"R5a_label": three_way(d250, "R5a", WIDE, 5, ("the mean of labels is better", "the label at the mean warp is better", "no consistent difference")),
"R5b_loss": three_way(d250, "R5b", WIDE, 5, ("NLL better", "MSE better", "no consistent difference")),
"R5c_bank": three_way(d250, "R5c", WIDE, 5, ("bank better", "mean label better", "no consistent difference"))}
if sc["pass"] and complete else {"note": "reproduction check failed or wide cells incomplete; ratios not read"})
(out / "reading.json").write_text(json.dumps(reading, indent=1))
cov = runs[runs.budget == PRIMARY].groupby(["regime", "c", "method"])[["coverage_90", "mean_sigma", "band_rmse"]].mean().reset_index()
cov.to_csv(out / "coverage.csv", index=False)
dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True)
lab = dg.groupby(["regime", "c"])[["rms_mean64_vs_pm_pu", "rms_mean1024_vs_pm_pu", "rms_mean64_vs_mean1024_pu", "n_valid_1024"]].mean().reset_index()
lab.to_csv(out / "label_distance.csv", index=False)
cols = ["cmp", "regime", "c", "budget", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"]
txt = ["# E5: posterior-mean labels with the Gaussian likelihood (exploratory)", "", "```", json.dumps(reading, indent=1), "```", "",
"## Ratios at 250 iterations", "", d250[cols].round(3).to_markdown(index=False), "",
"## Coverage90, mean sigma and band RMSE at 250 iterations", "", cov.round(3).to_markdown(index=False), "",
"## Label distances (p.u., main window)", "", lab.round(3).to_markdown(index=False), "",
"## Ratios at 125 and 500 iterations", "", df[df.budget != PRIMARY][cols].round(3).to_markdown(index=False)]
(out / "summary.md").write_text("\n".join(txt))
print("\n".join(txt[:6]))
def summary_e6(rng) -> None:
out = OUT / "e6"
s18 = load_script("18_summarize_p2r.py")
parts, rep_rows = [], []
for regime in H2A_REGIMES:
cd = out / regime / "cells"
files = sorted(f for f in cd.glob("r*_c*_n*.csv") if not f.name.endswith("_diag.csv")) if cd.exists() else []
for f in files:
d = pd.read_csv(f).assign(regime=regime)
parts.append(d)
r = pd.read_csv(P2R / "train" / regime / "cells" / f.name)
r = r[r.method.isin(SEVEN) & (r.budget == r.method.map(REG_BUD))]
mg = d.merge(r, on=["seed", "method", "budget", "test_well"], suffixes=("", "_reg"))
met = [c for c in r.columns if c not in ("rid", "c", "n_train", "seed", "method", "budget", "test_well")]
dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in met)
rep_rows.append({"regime": regime, "cell": f.stem, "n_rows": len(mg), "n_expected": len(r), "abs_dev_max": dev})
if not parts:
print("E6: no cells yet")
return
rep = pd.DataFrame(rep_rows)
rep.to_csv(out / "reproduction.csv", index=False)
sc = {"n_cells": int(len(rep)), "rows_ok": bool((rep.n_rows == rep.n_expected).all()),
"abs_dev_max": float(rep.abs_dev_max.max()), "pass": bool((rep.n_rows == rep.n_expected).all() and rep.abs_dev_max.max() <= 1e-9)}
d = pd.concat(parts, ignore_index=True)
num = [c for c in d.columns if c not in ("regime", "rid", "c", "n_train", "seed", "method", "budget", "test_well")
and pd.api.types.is_numeric_dtype(d[c])]
runs = d.groupby(["regime", "rid", "c", "n_train", "method", "seed", "budget"], as_index=False)[num].mean()
runs.to_csv(out / "runs.csv", index=False)
sets = {"point_ties": POINT, "with_B3d": POINT + ["B3d"]}
rows, ver = [], {}
for b in E_BUDGETS:
for regime in H2A_REGIMES:
run = runs[(runs.regime == regime) & (runs.budget == b)].drop(columns=["regime", "budget"])
if run.empty:
continue
for cand in ("B3d-Sa", "M2-Sa"):
for sname, comp in sets.items():
cells, gv = s18.h2a_cells(run, cand, comp, rng, N_BOOT)
c1 = cells[cells.c == 1.0]
ver[f"b{b}/{regime}/{cand}/{sname}"] = {"c1_pass": int(c1.cell_pass.sum()), "c1_cells": int(len(c1)),
"zero_drift_macro_ratio": gv["zero_drift_macro_ratio"],
"zero_drift_guard": gv["zero_drift_guard"]}
rows.append(cells.assign(budget=b, regime=regime, candidate=cand, competitors=sname))
tab = pd.concat(rows, ignore_index=True)
tab.to_csv(out / "h2a_by_budget.csv", index=False)
k = {b: sum(v["c1_pass"] for kk, v in ver.items() if kk.startswith(f"b{b}/") and kk.endswith("/B3d-Sa/point_ties"))
for b in E_BUDGETS}
complete = len(tab[(tab.candidate == "B3d-Sa") & (tab.competitors == "point_ties")]) == 3 * len(E_BUDGETS) * len(CS) * len(NS)
if sc["pass"] and complete:
reading = ("budget-robust" if all(v >= 5 for v in k.values())
else ("budget-dependent" if any(v <= 3 for v in k.values()) else "partly robust"))
else:
reading = "not read (reproduction check failed or grid incomplete)"
res = {"selfcheck": sc, "complete": complete, "k_b": k, "reading": reading, "per_budget": ver}
(out / "reading.json").write_text(json.dumps(res, indent=1, default=float))
mean = runs.groupby(["regime", "c", "n_train", "method", "budget"]).band_rmse.mean().unstack("budget").reset_index()
mean.to_csv(out / "band_rmse_by_budget.csv", index=False)
cols = ["budget", "regime", "candidate", "competitors", "c", "n_train", "best", "ratio", "ratio_lo", "ratio_hi",
"seeds_improve", "rids_improve", "cell_pass"]
txt = ["# E6: equal-budget table (exploratory)", "", "```", json.dumps({kk: res[kk] for kk in ("selfcheck", "complete", "k_b", "reading")},
indent=1, default=float), "```", "", "## H2a cell rule per budget", "", tab[cols].round(3).to_markdown(index=False), "",
"## Mean band RMSE (p.u.) per budget", "", mean.round(3).to_markdown(index=False)]
(out / "summary.md").write_text("\n".join(txt))
print("\n".join(txt[:8]))
def summary_e4(rng) -> None:
out = OUT / "e4"
files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv"))
if not files:
print("E4: no cells yet")
return
new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True)
pt = pd.concat([pd.read_csv(f) for f in sorted((POINT_TIE / "cells").glob("*.csv")) if not f.name.endswith("_diag.csv")],
ignore_index=True)
keys = ["regime", "rid", "c", "n_train", "seed", "method", "test_well"]
a = new[new.method == "SMC-MAP"].merge(pt[pt.method == "SMC-MAP"], on=keys, suffixes=("", "_pt"))
sc = {"n_rows": int(len(a)), "n_expected": int((new.method == "SMC-MAP").sum()),
"abs_dev_max": float((a.band_rmse - a.band_rmse_pt).abs().max()) if len(a) else None}
sc["pass"] = bool(sc["n_rows"] == sc["n_expected"] and sc["abs_dev_max"] is not None and sc["abs_dev_max"] <= 1e-9)
regs = []
for regime in H2A_REGIMES:
r = pd.read_csv(P2R / "train" / regime / "runs.csv")
regs.append(r[r.method.isin(SEVEN) & r.c.isin(CS) & r.n_train.isin(NS)].assign(regime=regime))
reg = pd.concat(regs, ignore_index=True)[["regime", "rid", "c", "n_train", "method", "seed", "band_rmse"]]
ptr = pt[pt.method.isin(["SMC-MAP", "Anchor-LS"])].groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
opt = new[new.method == "SMC-opt"].groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean()
runs = pd.concat([reg, ptr, opt], ignore_index=True)
pairs = {"E4-1": ("SMC-opt", "best"), "E4-2": ("B3d-Sa", "SMC-opt"), "E4-3": ("SMC-opt", "SMC-MAP"),
"E4-4": ("SMC-opt", "Anchor-LS")}
cells12 = {(r, c, n) for r in H2A_REGIMES for c in CS for n in NS}
df = ratio_table(runs, pairs, cells12, rng)
df.to_csv(out / "ratios.csv", index=False)
n = lambda tag, s: int((df[df.cmp == tag].pct_vs_1 == s).sum())
e3 = df[df.cmp == "E4-3"]
complete = len(df[df.cmp == "E4-1"]) == 12
reading = {"selfcheck_smc_map_seed0": sc, "complete": complete}
if complete:
reading |= {
"R4a": {"ci_below_1": n("E4-1", "below"), "rule": ">= 10 of 12",
"reading": "the target, not the sampler, carries the gain over deterministic ties" if n("E4-1", "below") >= 10 else "not supported"},
"R4b": {"ci_below_1": n("E4-2", "below"), "ci_above_1": n("E4-2", "above"), "rule": ">= 6 of 12",
"reading": ("posterior averaging improves on the optimized point" if n("E4-2", "below") >= 6 else
("the optimized point is better than averaging" if n("E4-2", "above") >= 6 else "no consistent difference"))},
"R4c": {"in_0.98_1.02": int(((e3.ratio >= 0.98) & (e3.ratio <= 1.02)).sum()), "rule": ">= 10 of 12",
"reading": "optimizing beyond the best particle changes little" if ((e3.ratio >= 0.98) & (e3.ratio <= 1.02)).sum() >= 10 else "not supported"}}
(out / "reading.json").write_text(json.dumps(reading, indent=1))
dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True)
wd = dg.groupby(["regime", "c", "n_train"]).agg(dF_mean=("dF", "mean"), dF_median=("dF", "median"), z_dist=("z_dist_opt_map", "mean"),
opt_warp=("SMC-opt_warp_rmse_ms", "mean"), map_warp=("SMC-MAP_warp_rmse_ms", "mean"),
pm_warp=("B3d-Sa_warp_rmse_ms", "mean"), frac_opt_source=("source", lambda s: float((s == "opt").mean())),
converged=("converged", "mean")).reset_index()
wd.to_csv(out / "optimizer.csv", index=False)
cols = ["cmp", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"]
txt = ["# E4: point tie optimizing the SMC target (exploratory)", "", "```", json.dumps(reading, indent=1), "```", "",
"## Ratios (budget 250 for SMC-opt; registered budgets otherwise)", "", df[cols].round(3).to_markdown(index=False), "",
"## Optimizer and warp RMSE (ms), mean over training wells and realizations", "", wd.round(3).to_markdown(index=False)]
(out / "summary.md").write_text("\n".join(txt))
print("\n".join(txt[:6]))
# ----------------------------------------------------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--stage", choices=["e5", "e6", "e4", "summary"], required=True)
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--rids", type=int, nargs="+", default=RIDS)
args = ap.parse_args()
set_threads()
sha = check_declaration()
P = run_d2.load_protocol(check=True)
print(f"declaration {sha[:12]} and the locked protocols match ({time.strftime('%FT%TZ', time.gmtime())})", flush=True)
if args.stage == "e5":
d = OUT / "e5" / "cells"
d.mkdir(parents=True, exist_ok=True)
jobs = [(r, rid, c, 16, SEEDS, args.device, d, P) for r, c in WIDE + NARROW for rid in args.rids
if not (d / f"{t2.tag(r, rid, c, 16)}.csv").exists()]
run_pool(e5_job, jobs, args.workers, "E5")
elif args.stage == "e6":
jobs = []
for r in H2A_REGIMES:
d = OUT / "e6" / r / "cells"
d.mkdir(parents=True, exist_ok=True)
jobs += [(r, rid, c, n, SEEDS, args.device, d, P) for c in CS for n in NS for rid in args.rids
if not (d / f"r{rid}_c{c:g}_n{n}.csv").exists()]
jobs.sort(key=lambda j: -j[3])
run_pool(e6_job, jobs, args.workers, "E6")
elif args.stage == "e4":
d = OUT / "e4" / "cells"
d.mkdir(parents=True, exist_ok=True)
jobs = [(r, rid, c, n, SEEDS, args.device, d, P) for r in H2A_REGIMES for c in CS for n in NS for rid in args.rids
if not (d / f"{t2.tag(r, rid, c, n)}.csv").exists()]
jobs.sort(key=lambda j: -j[3])
run_pool(e4_job, jobs, args.workers, "E4")
else:
for f in (summary_e5, summary_e6, summary_e4):
f(np.random.default_rng(0))
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()