"""Point ties with the same information as the SMC posterior (declared in docs/research/point-tie-arm.md, hashed before the first run; exploratory; outside every lock and the reproduction archives). Arms (labels at one warp, S = 1, backbone and 250 iterations of B3d-Sa): SMC-MAP the saved SMC particle with the highest tempered log target log p(u|anchor) + gamma * l(u) Anchor-LS the mode (Laplace/Gauss-Newton optimum) of the anchor-only posterior, TiePosterior.mu B3d-Sa is retrained at seed 0 as a reproduction check. CUDA_VISIBLE_DEVICES=0 .venv/bin/python scripts/44_point_tie_arm.py --stage all --workers 4 --device cuda:0 -> outputs/point_tie/{cells/*.csv, ratios.csv, selfcheck.json, 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" / "point-tie-arm.md" DECL_HASH = REPO_ROOT / "docs" / "research" / "point-tie-arm.sha256" OUT = outputs_dir() / "point_tie" P2R = outputs_dir() / "p2r" REGIMES, CS, NS = ["R10", "R0", "Rm5"], [0.0, 1.0], [4, 16] BUDGET = 250 ARMS = ["SMC-MAP", "Anchor-LS"] POINT = ["B3b", "B3c", "B3c-R"] REG_BUD = {"B3b": 125, "B3c": 250, "B3c-R": 500, "B3d": 250, "B3d-Sa": 250, "M2-Sa": 250} 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 def point_warps(cell: dict, regime: str, rid: int, c: float, N: int) -> dict: """Per well: the SMC-MAP and Anchor-LS warps (fine grid).""" from ml_porosity.data.wavelet import statistical_wavelet from ml_porosity.registration.smc import TiePosterior, phase_basis, phase_wavelet from ml_porosity.registration.warp_prior import WarpHyper R, obs, reg, ph, out = cell["R"], cell["obs"], cell["reg"], cell["ph"], cell["out"] h = WarpHyper(**out["hyper"]) cfg = R.cfg fac = int(round(R.dt / 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") res = {} for i, (o, w) in enumerate(zip(obs, cell["wells"])): 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"]) base, ll = T.parts(T.z(w["U"])) score = np.where(np.isfinite(base) & np.isfinite(ll), base + gamma * ll, -np.inf) k = int(np.argmax(score)) t_map = w["Tf"][k] t_ls = R.grid.t_of_tau(T.mu[0], T.mu[1:], tau=R.tau_fine) res[o["name"]] = {"SMC-MAP": t_map, "Anchor-LS": t_ls, "k": k, "gamma": gamma, "map_rank_frac_ll": float((ll < ll[k]).mean())} return res def train_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 from ml_porosity.registration.ties import warp_errors t0 = time.time() cell = t2.build_cell(regime, rid, c, N, P, with_register=True) R, out, wells = cell["R"], 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) - m0) / s0).astype(np.float32) pw = point_warps(cell, regime, rid, c, N) specs, diag = {}, [] for arm in ARMS: Y = nb(np.stack([cell["lab"](w["y_aa"], pw[w["name"]][arm]) for w in wells])) specs[arm] = {"kind": "bank", "Y": Y, "logpi": np.zeros((N, 1), np.float32), "lam": lam} specs["B3d-Sa"] = {"kind": "bank", "Y": nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells])), "logpi": np.zeros((N, 1), np.float32), "lam": lam} for w in wells: o = w["o"] err = lambda t: warp_errors(np.atleast_2d(t), R.tau_fine, 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"]), "Anchor-LS_warp_rmse_ms": err(pw[w["name"]]["Anchor-LS"]), "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: continue preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, [BUDGET], device) for b, (mu, sg) in preds.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) 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 def registered_runs() -> pd.DataFrame: parts = [] for reg in REGIMES: d = pd.read_csv(P2R / "train" / reg / "runs.csv") d = d[d.method.isin(REG_BUD) & d.c.isin(CS) & d.n_train.isin(NS)] parts.append(d.assign(regime=reg)) return pd.concat(parts, ignore_index=True) def summarize(out: Path) -> None: files = sorted(f for f in (out / "cells").glob("*.csv") if not f.name.endswith("_diag.csv")) new = pd.concat([pd.read_csv(f) for f in files], ignore_index=True) new = new.groupby(["regime", "rid", "c", "n_train", "method", "seed"], as_index=False).band_rmse.mean() new = new.rename(columns={"n_train": "n_train"}) reg = registered_runs()[["regime", "rid", "c", "n_train", "method", "seed", "band_rmse"]] # reproduction check a = new[new.method == "B3d-Sa"].merge(reg[reg.method == "B3d-Sa"], on=["regime", "rid", "c", "n_train", "seed"], suffixes=("", "_reg")) sc = {"n_rows": int(len(a)), "n_expected": int((new.method == "B3d-Sa").sum()), "band_rmse_abs_dev_max": float((a.band_rmse - a.band_rmse_reg).abs().max())} (out / "selfcheck.json").write_text(json.dumps(sc, indent=1)) allr = pd.concat([reg, new[new.method.isin(ARMS)]], ignore_index=True) rng = np.random.default_rng(0) rows = [] pairs = {"A": ("B3d-Sa", "SMC-MAP"), "B": ("SMC-MAP", "best"), "C": ("Anchor-LS", "best"), "D": ("B3d-Sa", "Anchor-LS"), "E": ("SMC-MAP", "Anchor-LS"), "F": ("M2-Sa", "SMC-MAP")} for (regime, c, N), g in allr.groupby(["regime", "c", "n_train"]): best = min(POINT, key=lambda m: g[g.method == m].band_rmse.mean()) for tag, (x, y) in pairs.items(): y = best if y == "best" else y sx = g[g.method == x].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean() sy = g[g.method == y].groupby(["rid", "seed"]).band_rmse.mean().groupby("rid").mean() if len(sx) < 8 or len(sy) < 8: continue rows.append({"cmp": tag, "regime": regime, "c": c, "n_train": N, "num": x, "den": y} | ci.intervals(sx, sy, rng)) df = pd.DataFrame(rows) for m in ("pct", "bca", "t"): df[f"{m}_vs_1"] = ["below" if r[f"{m}_hi"] < 1 else ("above" if r[f"{m}_lo"] > 1 else "contains") for _, r in df.iterrows()] df.to_csv(out / "ratios.csv", index=False) # zero-drift ratios to the Oracle and warp errors dg = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_diag.csv"))], ignore_index=True) dg.groupby(["regime", "c", "n_train"])[["SMC-MAP_warp_rmse_ms", "Anchor-LS_warp_rmse_ms", "B3d-Sa_warp_rmse_ms", "map_rank_frac_ll"]].mean().to_csv(out / "warp_errors.csv") pd.set_option("display.width", 250) cols = ["cmp", "regime", "c", "n_train", "num", "den", "ratio", "pct_lo", "pct_hi", "bca_lo", "bca_hi", "t_lo", "t_hi"] txt = ["# point-tie arm", "", json.dumps(sc), "", df[cols].round(3).to_markdown(index=False), "", "warp errors (ms) and rank of the MAP particle among the particles' log-likelihoods:", "", pd.read_csv(out / "warp_errors.csv").round(3).to_markdown(index=False)] (out / "summary.md").write_text("\n".join(txt)) print("\n".join(txt)) def main() -> None: ap = argparse.ArgumentParser() ap.add_argument("--stage", choices=["train", "summary", "all"], default="all") ap.add_argument("--device", default="cuda:0") ap.add_argument("--workers", type=int, default=4) ap.add_argument("--seeds", type=int, nargs="+", default=t2.SEEDS) ap.add_argument("--rids", type=int, nargs="+", default=t2.RIDS) args = ap.parse_args() for k in ("OMP_NUM_THREADS", "MKL_NUM_THREADS", "OPENBLAS_NUM_THREADS", "NUMBA_NUM_THREADS", "NUMEXPR_NUM_THREADS"): os.environ.setdefault(k, "2") sha = check_declaration() (OUT / "cells").mkdir(parents=True, exist_ok=True) P = run_d2.load_protocol(check=True) print(f"declaration {sha[:12]} and the locked protocols match", flush=True) if args.stage in ("train", "all"): jobs = [(r, rid, c, N, args.seeds, args.device, OUT / "cells", P) for r in REGIMES for c in CS for N in NS for rid in args.rids if not (OUT / "cells" / f"{t2.tag(r, rid, c, N)}.csv").exists()] print(f"{len(jobs)} jobs, {args.workers} workers, device {args.device}", flush=True) t0 = time.time() if jobs: with ProcessPoolExecutor(args.workers, mp_context=get_context("spawn")) as ex: futs = {ex.submit(train_job, 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) if args.stage in ("summary", "all"): summarize(OUT) if __name__ == "__main__": os.environ.setdefault("PYTHONHASHSEED", "0") main()