"""GP review E1 (declared in docs/research/gp-review-experiments.md, hashed before realizations 24-31 were generated; exploratory; outside every lock and the reproduction archives): the true anchor error varies, with and without a per-well bulk component, and the registration states sigma_a correctly or at 7 ms. Anchor data model: t_k = boundary time + sigma_true * eps_k + beta_w, eps_k the realization's own draws (eps_a) and beta_w = sigma_B * z_w, z_w ~ N(0, 1) from default_rng([rid, crc32(well name), 2417]). It is implemented by replacing D2Realization.observe in the worker process (only the anchor times change). Conditions with "-fix" fit the drift hyperparameters at sigma_a = 7 ms and then set sigma_a to sigma_reg (the pattern of scripts/47). Every other step runs through the locked scripts/14 run_job and scripts/15 run_cell, unchanged. --stage fingerprints SHA-256 fingerprints of realizations 24-31 (as scripts/46) and a check of the replacement -> outputs/gp_review/e1/{fingerprints.json, patch_check.json}; required before any posterior --stage post 1024-particle posteriors (estR), R10, c = 1, N = 4, 16 -> e1//posterior/R10/ --stage train the seven registered methods at their registered budgets, seeds 0-4 -> e1//train/R10/cells/ --stage arms SMC-MAP (budget 250, seeds 0-4) and B3d-Sa at seed 0 (reproduction check) -> e1//arms/ --stage b3p B3p (E2 selection and budget) once per anchor model (it does not use sigma_reg) -> e1/b3p// --stage summary P1-P5 and the declared readings -> e1/summary/ Every stage skips jobs whose CSV exists. """ from __future__ import annotations import argparse import dataclasses import hashlib import importlib.util import json import math import os import time import zlib from concurrent.futures import ProcessPoolExecutor, as_completed from multiprocessing import get_context from pathlib import Path 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 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" ROOT = outputs_dir() / "gp_review" / "e1" E2 = outputs_dir() / "gp_review" / "e2" BUDGETS_JSON = outputs_dir() / "p2" / "diag" / "train" / "budgets.json" RIDS = list(range(24, 32)) NS = [16, 4] C = 1.0 SNR, DENS = 10.0, "full" SEEDS = [0, 1, 2, 3, 4] PARTICLES = 1024 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"] ARM_BUDGET = 250 BULK_SEED = 2417 N_BOOT = 2000 # condition -> (sigma_true, sigma_B, sigma_reg, drift hyperparameters) CONDITIONS = { "iid7-reg7": (7.0, 0.0, 7.0, "refit"), "iid4-reg4": (4.0, 0.0, 4.0, "refit"), "iid4-reg7": (4.0, 0.0, 7.0, "refit"), "iid2-reg2": (2.0, 0.0, 2.0, "refit"), "iid2-reg7": (2.0, 0.0, 7.0, "refit"), "iid1-reg1": (1.0, 0.0, 1.0, "refit"), "iid1-reg7": (1.0, 0.0, 7.0, "refit"), "bulk-reg2": (2.0, 5.0, 2.0, "refit"), "bulk-reg5.4": (2.0, 5.0, math.sqrt(29.0), "refit"), "bulk-reg7": (2.0, 5.0, 7.0, "refit"), "iid2-reg2-fix": (2.0, 0.0, 2.0, "fix"), "bulk-reg2-fix": (2.0, 5.0, 2.0, "fix"), } ANCHOR_MODELS = {"iid7": (7.0, 0.0), "iid4": (4.0, 0.0), "iid2": (2.0, 0.0), "iid1": (1.0, 0.0), "bulk": (2.0, 5.0)} P5_PAIRS = {"iid4": ("iid4-reg7", "iid4-reg4"), "iid2": ("iid2-reg7", "iid2-reg2"), "iid1": ("iid1-reg7", "iid1-reg1"), "bulk": ("bulk-reg7", "bulk-reg5.4")} S1 = ["iid4-reg7", "iid2-reg7", "iid1-reg7"] S2 = ["iid4-reg4", "iid2-reg2", "iid1-reg1"] S3 = {"2": "bulk-reg2", "5.39": "bulk-reg5.4", "7": "bulk-reg7"} def anchor_model(cond: str) -> str: s_true, s_b = CONDITIONS[cond][:2] return next(k for k, v in ANCHOR_MODELS.items() if v == (s_true, s_b)) def cdir(cond: str) -> Path: return ROOT / cond 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 # ---------------------------------------------------------------------------------------------------------------- # in-process replacements (declared): D2Realization.observe (anchor times only), pipeline.fit_cell_hyper ("-fix") # ---------------------------------------------------------------------------------------------------------------- LOG = {"anchors": [], "hyper": []} def bulk_z(rid: int, name: str) -> float: return float(np.random.default_rng([rid, zlib.crc32(name.encode()), BULK_SEED]).standard_normal()) def patch_observe(s_true: float, s_b: float) -> None: from ml_porosity.data import synth_d2 D = synth_d2.D2Realization if not hasattr(D, "_gp_orig_observe"): D._gp_orig_observe = D.observe orig = D._gp_orig_observe def observe(self, w, c, snr_db, sigma_a_ms, anchor_density="full"): o = orig(self, w, c, snr_db, s_true, anchor_density) beta = s_b * bulk_z(self.rid, w.name) if s_b > 0 else 0.0 if s_b > 0: o["t_k"] = o["t_k"] + beta LOG["anchors"].append({"well": w.name, "beta_ms": beta, "n_anchor": int(len(o["t_k"]))}) return o D.observe = observe def patch(cond: str, reg_settings: bool = False) -> None: """Apply the replacements of `cond` in this process (idempotent; resets every earlier condition).""" from ml_porosity.registration import pipeline s_true, s_b, s_reg, hyp = CONDITIONS[cond] patch_observe(s_true, s_b) if not hasattr(pipeline, "_gp_orig_fit"): pipeline._gp_orig_fit = pipeline.fit_cell_hyper orig = pipeline._gp_orig_fit def fit(R, obs, reg, seed=0): if hyp == "fix": h, info = orig(R, obs, reg | {"sigma_a_ms": 7.0}, seed) h = dataclasses.replace(h, sigma_a_ms=reg["sigma_a_ms"]) else: h, info = orig(R, obs, reg, seed) LOG["hyper"].append(h.as_dict() | {"sigma_a_reg_in": float(reg["sigma_a_ms"]), "mode": hyp}) return h, info pipeline.fit_cell_hyper = fit if not hasattr(run_d2, "_gp_orig_reg"): run_d2._gp_orig_reg = run_d2.reg_settings if reg_settings: # build_cell/register of the arms stage: registration sigma_a run_d2.reg_settings = lambda P: run_d2._gp_orig_reg(P) | {"sigma_a_ms": s_reg} else: run_d2.reg_settings = run_d2._gp_orig_reg def st_post(cond: str) -> dict: return {"snr_db": SNR, "anchor_density": DENS, "sigma_a_reg": CONDITIONS[cond][2], "wavelets": ["estR"], "smc_seed": None} def st_train(cond: str) -> dict: bud = json.loads(BUDGETS_JSON.read_text()) assert all(int(bud[m]) == b for m, b in REG_BUD.items()), "budgets.json differs from the registered budgets" return {"snr_db": SNR, "anchor_density": DENS, "sigma_a_reg": CONDITIONS[cond][2], "variants": ["a"], "methods": SEVEN, "save_preds": True, "budgets": {m: int(bud[m]) for m in SEVEN}} # ---------------------------------------------------------------------------------------------------------------- # fingerprints and replacement check # ---------------------------------------------------------------------------------------------------------------- def realization(P: dict, rid: int): import yaml 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"]] return D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav) def stage_fingerprints(P: dict) -> None: """Fingerprints with the unmodified observe (definition of scripts/46), then the replacement check.""" import scipy from ml_porosity.data import synth_d2 ROOT.mkdir(parents=True, exist_ok=True) if (ROOT / "fingerprints.json").exists(): print("fingerprints.json exists; not rewritten") else: if any((ROOT / c / "posterior").exists() for c in CONDITIONS): raise SystemExit("posteriors exist without fingerprints.json") sha = lambda chunks: (lambda h: ([h.update(np.ascontiguousarray(np.asarray(a)).tobytes()) for a in chunks], h.hexdigest())[1])(hashlib.sha256()) fields = ("seis_clean", "noise_unit", "phi_t", "z_g", "z_b", "boundaries_t", "eps_a") keys = ("seis", "phi_log", "ai_log", "tau_k", "t_k", "b", "g", "t_of_tau_true", "y_true") out = {"meta": {"numpy": np.__version__, "scipy": scipy.__version__, "d2_config": P["inputs"]["d2_config"]["path"], "declaration": check_declaration(), "written_utc": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())}, "rids": {}} for rid in RIDS: R = realization(P, rid) obs = [R.observe(w, c, 10, 7.0, "full") for c in (0.0, 1.0, 2.0) for w in R.test + R.pool[:4]] out["rids"][str(rid)] = {"wells": {k: sha(getattr(w, k) for w in R.wells) for k in fields}, "obs": {k: sha(o[k] for o in obs) for k in keys}} print(f"fingerprint r{rid}", flush=True) (ROOT / "fingerprints.json").write_text(json.dumps(out, indent=1)) # replacement check: iid7 reproduces observe bit for bit; the bulk model adds one constant per well; other # fields never change D = synth_d2.D2Realization orig = getattr(D, "_gp_orig_observe", D.observe) chk = {"rids": {}} ok_all = True for rid in RIDS[:2]: R = realization(P, rid) wells = R.pool[:16] base7 = [orig(R, w, C, SNR, 7.0, DENS) for w in wells] base2 = [orig(R, w, C, SNR, 2.0, DENS) for w in wells] patch_observe(7.0, 0.0) p7 = [R.observe(w, C, SNR, 7.0, DENS) for w in wells] patch_observe(2.0, 5.0) pb = [R.observe(w, C, SNR, 7.0, DENS) for w in wells] same7 = all(all(np.array_equal(np.asarray(a[k]), np.asarray(b[k])) for k in a if k != "name") for a, b in zip(base7, p7)) others = all(all(np.array_equal(np.asarray(a[k]), np.asarray(b[k])) for k in a if k not in ("name", "t_k")) for a, b in zip(base2, pb)) offs = [np.unique(np.round(b["t_k"] - a["t_k"], 9)) for a, b in zip(base2, pb)] const = all(len(u) == 1 for u in offs) betas = [float(u[0]) for u in offs] want = [5.0 * bulk_z(rid, w.name) for w in wells] match = bool(np.allclose(betas, want, atol=1e-9)) ok = same7 and others and const and match ok_all &= ok chk["rids"][str(rid)] = {"iid7_identical": same7, "bulk_other_fields_identical": others, "bulk_constant_per_well": const, "bulk_offsets_match": match, "beta_ms": [round(b, 4) for b in betas], "beta_sd_ms": float(np.std(betas, ddof=1))} chk["pass"] = bool(ok_all) (ROOT / "patch_check.json").write_text(json.dumps(chk, indent=1)) print(json.dumps(chk, indent=1)) if not ok_all: raise SystemExit("replacement check failed") # ---------------------------------------------------------------------------------------------------------------- # jobs (each worker applies the replacements of its job's condition) # ---------------------------------------------------------------------------------------------------------------- def post_job(job) -> tuple[str, float]: cond, rid, N, P, device, mem_gb = job patch(cond) s14 = load_script("14_diag_posterior.py") d = cdir(cond) / "posterior" / "R10" LOG["anchors"].clear(), LOG["hyper"].clear() t0 = time.time() tag = s14.job_tag(rid, C, N, 0) s14.run_job((rid, C, N, 0, PARTICLES, P, d, device, mem_gb, st_post(cond))) (d / f"{tag}_e1.json").write_text(json.dumps({"condition": cond, "hyper": LOG["hyper"], "anchors": LOG["anchors"]}, indent=1)) return f"{cond}/{tag}", time.time() - t0 def train_job(job) -> tuple[str, float]: cond, rid, N, P, device = job patch(cond) s15 = load_script("15_diag_train.py") d = cdir(cond) / "train" / "R10" / "cells" _, dt = s15.run_cell((rid, C, N, SEEDS, 0, P, device, cdir(cond) / "posterior" / "R10", d, st_train(cond))) return f"{cond}/r{rid}_c1_n{N}", dt def arms_job(job) -> tuple[str, float]: cond, rid, N, P, device = job import torch torch.set_num_threads(2) from ml_porosity.models.bank_train import train_predict from ml_porosity.registration.ties import warp_errors patch(cond, reg_settings=True) s44 = load_script("44_point_tie_arm.py") t2.P2R = cdir(cond) # build_cell reads /posterior/R10/ s44.P2R = cdir(cond) # point_warps reads the tempering gamma there t0 = time.time() cell = t2.build_cell("R10", rid, C, N, P, with_register=True) R, out, wells = cell["R"], cell["out"], cell["wells"] if abs(cell["reg"]["sigma_a_ms"] - CONDITIONS[cond][2]) > 1e-12: raise RuntimeError("registration sigma_a was not applied") stem = f"r{rid}_c1_n{N}" key = dict(condition=cond, regime="R10", 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) - m0) / s0).astype(np.float32) pw = s44.point_warps(cell, "R10", rid, C, N) one = np.zeros((N, 1), np.float32) bank = lambda Y: {"kind": "bank", "Y": Y, "logpi": one, "lam": lam} specs = {"SMC-MAP": bank(nb(np.stack([cell["lab"](w["y_aa"], pw[w["name"]]["SMC-MAP"]) for w in wells]))), "B3d-Sa": bank(nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])))} diag = [] for w in wells: err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, w["o"]["t_of_tau_true"], R.t_main)["warp_rmse_ms"] diag.append(key | {"well": w["name"], "SMC-MAP_warp_rmse_ms": err(pw[w["name"]]["SMC-MAP"]), "B3d-Sa_warp_rmse_ms": err(w["tm"]), "map_rank_frac_ll": pw[w["name"]]["map_rank_frac_ll"]}) rows = [] for seed in SEEDS: for m, sp in specs.items(): if m == "B3d-Sa" and seed != 0: # reproduction check of the scripts/15 rows continue for b, (mu, sg) in train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [ARM_BUDGET], device).items(): mu_p, sg_p = 100 * (mu * s0 + m0), 100 * sg * s0 for wt, r in zip(R.test, run_d2.evaluate(cell["yt"], mu_p, sg_p, f_c)): rows.append(key | {"seed": seed, "method": m, "budget": b, "test_well": wt.name} | r) d = cdir(cond) / "arms" pd.DataFrame(diag).to_csv(d / f"{stem}_diag.csv", index=False) pd.DataFrame(rows).to_csv(d / f"{stem}.csv", index=False) # written last: marks the job complete return f"{cond}/{stem}", time.time() - t0 def b3p_job(job) -> tuple[str, float]: amodel, rid, N, P, device = job import torch torch.set_num_threads(2) patch_observe(*ANCHOR_MODELS[amodel]) s53 = load_script("53_gp_practitioner_tie.py") t0 = time.time() k = s53.selected()["R10"] budget = int(json.loads((E2 / "budget.json").read_text())["B3p"]) cell = s53.make_cell("R10", rid, C, N, P, snr=SNR, dens=DENS) key = {"anchor_model": amodel, "regime": "R10", "rid": rid, "c": C, "n_train": N} rows, diag = s53.train_cell(cell, k, SEEDS, [budget], device, P, key) d = ROOT / "b3p" / amodel stem = f"r{rid}_c1_n{N}" pd.DataFrame(diag).to_csv(d / f"{stem}_diag.csv", index=False) pd.DataFrame(rows).to_csv(d / f"{stem}.csv", index=False) return f"b3p/{amodel}/{stem}", time.time() - t0 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) 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) def interleave(conds, rids) -> list[tuple]: """Long jobs (N = 16) first; conditions interleaved so that partial results cover every condition.""" return [(cond, rid, N) for N in NS for rid in rids for cond in conds] # ---------------------------------------------------------------------------------------------------------------- # summary # ---------------------------------------------------------------------------------------------------------------- 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 load_runs() -> pd.DataFrame: parts = [] for cond in CONDITIONS: cd = cdir(cond) / "train" / "R10" / "cells" for f in sorted(cd.glob("r*_c*_n*.csv")) if cd.exists() else []: if f.name.endswith("_diag.csv"): continue d = pd.read_csv(f) parts.append(d[d.method.isin(SEVEN) & (d.budget == d.method.map(REG_BUD))].assign(condition=cond)) ad = cdir(cond) / "arms" for f in sorted(ad.glob("r*_c*_n*.csv")) if ad.exists() else []: if f.name.endswith("_diag.csv"): continue d = pd.read_csv(f) parts.append(d[d.method == "SMC-MAP"].drop(columns=["regime"], errors="ignore")) bd = ROOT / "b3p" / anchor_model(cond) for f in sorted(bd.glob("r*_c*_n*.csv")) if bd.exists() else []: if f.name.endswith("_diag.csv"): continue d = pd.read_csv(f) parts.append(d.drop(columns=["regime", "anchor_model"], errors="ignore").assign(condition=cond)) if not parts: return pd.DataFrame() d = pd.concat(parts, ignore_index=True) keys = ["condition", "rid", "c", "n_train", "method", "seed", "budget"] 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 selfcheck() -> dict: rows = [] for cond in CONDITIONS: ad = cdir(cond) / "arms" for f in sorted(ad.glob("r*_c*_n*.csv")) if ad.exists() else []: if f.name.endswith("_diag.csv"): continue a = pd.read_csv(f) a = a[(a.method == "B3d-Sa") & (a.seed == 0)] t = cdir(cond) / "train" / "R10" / "cells" / f.name if not t.exists(): continue r = pd.read_csv(t) r = r[(r.method == "B3d-Sa") & (r.seed == 0) & (r.budget == ARM_BUDGET)] mg = a.merge(r, on=["test_well"], suffixes=("", "_reg")) dev = max(float((mg[c] - mg[f"{c}_reg"]).abs().max()) for c in ("band_rmse", "rmse", "nll")) rows.append({"condition": cond, "cell": f.stem, "n": len(mg), "abs_dev_max": dev}) if not rows: return {"n_cells": 0} d = pd.DataFrame(rows) return {"n_cells": int(len(d)), "n_pass": int((d.abs_dev_max <= 1e-9).sum()), "abs_dev_max": float(d.abs_dev_max.max())} def posterior_table() -> pd.DataFrame: rows = [] for cond in CONDITIONS: d = cdir(cond) / "posterior" / "R10" for f in sorted(d.glob("r*_c1_n*_s0.csv")) if d.exists() else []: g = pd.read_csv(f) smc = g[(g.method == "SMC_g_acf") & (g.wavelet == "estR")] row = {"condition": cond, "rid": int(g.rid.iloc[0]), "n_train": int(g.n_train.iloc[0]), "SMC_warp_rmse_ms": float(smc.warp_rmse_ms.mean()), "SMC_cov90": float(smc.warp_cov90.mean()), "SMC_width90_ms": float(smc.warp_width90_ms.mean())} for m in ("B3b", "B3c", "B3d"): row[f"{m}_warp_rmse_ms"] = float(g[(g.method == m) & (g.wavelet == "est")].warp_rmse_ms.mean()) e = d / f.name.replace(".csv", "_e1.json") if e.exists(): h = json.loads(e.read_text())["hyper"] if h: row |= {f"hyp_{k}": h[-1][k] for k in ("m_g", "sigma_g", "ell_ms", "sigma_a_ms") if k in h[-1]} rows.append(row) return pd.DataFrame(rows) def stage_summary() -> None: out = ROOT / "summary" out.mkdir(parents=True, exist_ok=True) rng = np.random.default_rng(20261117) runs = load_runs() if runs.empty: print("E1: no cells yet") return sc = selfcheck() rat = [] for (cond, N), g in runs.groupby(["condition", "n_train"]): have = set(g.method) mean = lambda m: g[g.method == m].band_rmse.mean() sets = {"point_ties": POINT, "with_B3p": POINT + ["B3p"], "with_B3d": POINT + ["B3d"], "with_B3d_B3p": POINT + ["B3d", "B3p"]} pairs = {} for sname, comp in sets.items(): if set(comp) <= have: pairs[f"P1/{sname}"] = ("B3d-Sa", min(comp, key=mean)) pairs[f"P1-M2/{sname}"] = ("M2-Sa", min(comp, key=mean)) pairs[f"P1-MAP/{sname}"] = ("SMC-MAP", min(comp, key=mean)) pairs |= {"P2": ("B3d-Sa", "B3d"), "P3": ("M2-Sa", "B3d-Sa"), "MAP/B3d-Sa": ("SMC-MAP", "B3d-Sa"), "Oracle/B3d-Sa": ("Oracle", "B3d-Sa")} for tag, (x, y) in pairs.items(): 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 rat.append({"condition": cond, "n_train": N, "cmp": tag, "num": x, "den": y} | ci.intervals(sx, sy, rng)) for pname, (a, b) in P5_PAIRS.items(): # paired over realizations, same anchors for N in NS: ga = runs[(runs.condition == a) & (runs.n_train == N)] gb = runs[(runs.condition == b) & (runs.n_train == N)] for m in ("B3d-Sa", "M2-Sa", "SMC-MAP"): sa, sb = ci.per_rid(ga, m), ci.per_rid(gb, m) if len(sa) == len(RIDS) and len(sb) == len(RIDS): rat.append({"condition": f"{a}|{b}", "n_train": N, "cmp": f"P5/{pname}", "num": f"{m}@{a}", "den": f"{m}@{b}"} | ci.intervals(sa, sb, rng)) df = pd.DataFrame(rat) for m in ("pct", "bca", "t"): df[f"{m}_vs_1"] = [side(r, m) for _, r in df.iterrows()] df.to_csv(out / "ratios.csv", index=False) def reading(cond: str, tag: str) -> str: d = df[(df.condition == cond) & (df.cmp == tag)] if len(d) < len(NS): return "incomplete" s = set(d.pct_vs_1) if s == {"below"}: return "gain holds" if "above" in s: return "reversed" if s == {"contains"}: return "gain lost" return "partial" readings = {} for sname in ("point_ties", "with_B3p", "with_B3d", "with_B3d_B3p"): tag = f"P1/{sname}" r = {cond: reading(cond, tag) for cond in CONDITIONS} st = lambda conds: ("incomplete" if any(r[c] == "incomplete" for c in conds) else "holds" if all(r[c] == "gain holds" for c in conds) else "does not hold") readings[sname] = {"per_condition": r, "S1_more_accurate_than_assumed": st(S1), "S2_sigma_a_stated_correctly": st(S2), "S3_bulk": {k: st([c]) for k, c in S3.items()}} pt = posterior_table() if not pt.empty: pt.to_csv(out / "posterior_cells.csv", index=False) p4 = pt.groupby(["condition", "n_train"]).mean(numeric_only=True).drop(columns=["rid"]).reset_index() p4["n_rid"] = pt.groupby(["condition", "n_train"]).rid.nunique().values p4.to_csv(out / "p4_posterior.csv", index=False) else: p4 = pd.DataFrame() warp = [] for cond in CONDITIONS: for sub, cols in (("train/R10/cells", ["B3c-R_warp_rmse_ms", "B3d-Sa_warp_rmse_ms"]), ("arms", ["SMC-MAP_warp_rmse_ms"])): d = cdir(cond) / sub for f in sorted(d.glob("*_diag.csv")) if d.exists() else []: g = pd.read_csv(f) for c_ in cols: if c_ in g: warp.append({"condition": cond, "n_train": int(g.n_train.iloc[0]), "rid": int(g.rid.iloc[0]), "method": c_.replace("_warp_rmse_ms", ""), "warp_rmse_ms": float(g[c_].mean())}) d = ROOT / "b3p" / anchor_model(cond) for f in sorted(d.glob("*_diag.csv")) if d.exists() else []: g = pd.read_csv(f) warp.append({"condition": cond, "n_train": int(g.n_train.iloc[0]), "rid": int(g.rid.iloc[0]), "method": "B3p", "warp_rmse_ms": float(g.B3p_warp_rmse_ms.mean())}) wt = pd.DataFrame(warp) if not wt.empty: wt = wt.groupby(["condition", "n_train", "method"]).warp_rmse_ms.mean().unstack("method").reset_index() wt.to_csv(out / "warp_rmse.csv", index=False) means = runs.groupby(["condition", "n_train", "method"]).agg(band_rmse=("band_rmse", "mean"), n_rid=("rid", "nunique"), coverage_90=("coverage_90", "mean")).reset_index() means.to_csv(out / "means.csv", index=False) verdict = {"selfcheck_B3d-Sa_seed0": sc, "readings": readings, "complete": {cond: {int(N): int(runs[(runs.condition == cond) & (runs.n_train == N) & (runs.method == "B3d-Sa")].rid.nunique()) for N in NS} for cond in CONDITIONS}} (out / "verdict.json").write_text(json.dumps(verdict, indent=1)) cols = ["condition", "n_train", "cmp", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi", "pct_vs_1"] order = {c: i for i, c in enumerate(CONDITIONS)} key = lambda s: s.map(lambda v: order.get(v, 99)) if s.name == "condition" else s txt = ["# E1: anchor-noise misspecification on realizations 24-31 (exploratory)", "", "Declared in docs/research/gp-review-experiments.md (E1). R10, c = 1, registration seed 0, training seeds 0-4.", "Ratios: mean band RMSE over realizations; intervals: percentile bootstrap over the 8 realizations (primary), BCa, t.", "", "```", json.dumps(verdict, indent=1), "```", ""] for title, pat in (("P1: SMC mean against the best deterministic tie", "P1/"), ("P1 for M2-Sa and SMC-MAP", "P1-"), ("P2, P3 and others", "P2|P3|MAP/|Oracle/"), ("P5: misstated sigma_reg (paired)", "P5/")): d = df[df.cmp.str.contains(pat) & ~(df.cmp.str.startswith("P1-") if pat == "P1/" else False)] if len(d): txt += [f"## {title}", "", d.sort_values(["condition", "cmp", "n_train"], key=key)[cols].round(3).to_markdown(index=False), ""] if len(p4): txt += ["## P4: SMC posterior and point-tie warp RMSE (ms, training wells, main window)", "", p4.round(3).to_markdown(index=False), ""] if not wt.empty: txt += ["## Warp RMSE of the methods trained here (ms)", "", wt.round(3).to_markdown(index=False), ""] txt += ["## Mean band RMSE (p.u.)", "", means.pivot_table(index=["condition", "n_train"], columns="method", values="band_rmse").round(4).to_markdown(), ""] (out / "summary.md").write_text("\n".join(txt)) print("\n".join(txt[:8])) # ---------------------------------------------------------------------------------------------------------------- def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--stage", choices=["fingerprints", "post", "train", "arms", "b3p", "summary"], required=True) ap.add_argument("--device", default="cuda:0") ap.add_argument("--workers", type=int, default=4) ap.add_argument("--gpu-mem-gb", type=float, default=1.5) ap.add_argument("--conds", nargs="+", default=list(CONDITIONS), choices=list(CONDITIONS)) ap.add_argument("--rids", type=int, nargs="+", default=RIDS) args = ap.parse_args() sha = check_declaration() P = run_d2.load_protocol(check=True) print(f"declaration {sha[:12]} and protocol_p2 match ({time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())})", flush=True) if args.stage == "fingerprints": stage_fingerprints(P) return if args.stage == "summary": stage_summary() return if not (ROOT / "fingerprints.json").exists() or not json.loads((ROOT / "patch_check.json").read_text())["pass"]: raise SystemExit("run --stage fingerprints first (fingerprints and replacement check)") rids = [r for r in args.rids if r in RIDS] if args.stage == "post": jobs = [] for cond, rid, N in interleave(args.conds, rids): d = cdir(cond) / "posterior" / "R10" d.mkdir(parents=True, exist_ok=True) if not (d / f"r{rid}_c1_n{N}_s0.csv").exists(): jobs.append((cond, rid, N, P, args.device, args.gpu_mem_gb)) run_pool(post_job, jobs, args.workers, "E1 posteriors") elif args.stage == "train": jobs = [] for cond, rid, N in interleave(args.conds, rids): d = cdir(cond) / "train" / "R10" / "cells" d.mkdir(parents=True, exist_ok=True) ready = (cdir(cond) / "posterior" / "R10" / f"r{rid}_c1_n{N}_s0.csv").exists() if ready and not (d / f"r{rid}_c1_n{N}.csv").exists(): jobs.append((cond, rid, N, P, args.device)) run_pool(train_job, jobs, args.workers, "E1 training (seven registered methods)") elif args.stage == "arms": jobs = [] for cond, rid, N in interleave(args.conds, rids): d = cdir(cond) / "arms" d.mkdir(parents=True, exist_ok=True) ready = (cdir(cond) / "posterior" / "R10" / f"r{rid}_c1_n{N}_s0.csv").exists() if ready and not (d / f"r{rid}_c1_n{N}.csv").exists(): jobs.append((cond, rid, N, P, args.device)) run_pool(arms_job, jobs, args.workers, "E1 arms (SMC-MAP)") elif args.stage == "b3p": if not (E2 / "budget.json").exists() or not (E2 / "selected.json").exists(): raise SystemExit("E2 select and budget must finish first") amodels = sorted({anchor_model(c) for c in args.conds}) jobs = [] for am in amodels: d = ROOT / "b3p" / am d.mkdir(parents=True, exist_ok=True) jobs += [(am, rid, N, P, args.device) for N in NS for rid in rids if not (d / f"r{rid}_c1_n{N}.csv").exists()] run_pool(b3p_job, jobs, args.workers, "E1 B3p") if __name__ == "__main__": main()