Files
ML-Porosity/scripts/32_t2_mechanism.py
lamlvh 381b5ffb06 Add P6 benchmark code, locked protocol_bench, T2 study
- ml_porosity/benchmark/ runner, scripts 32-35, scripts/run_bench.sh;
  misspec= option in synth_d2 (default path reproduces P2r bit for bit).
- configs/protocol_bench.{yaml,sha256,lock.json} locked 29/10 14:39 UTC
  (sha256 aa763f0a...), configs/d2_synth_bench.yaml.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

outputs/ stays out of git; the repository folder is synced as a whole to
the new server. Main S1 runs are still training at this commit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 01:33:18 +00:00

847 lines
50 KiB
Python
Raw 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.
"""T2 (exploratory): mechanism of the bank gain on the P2r SMC bank (realizations 8–15).
Declared before any computation in docs/research/t2-mechanism.md (SHA-256 in docs/research/t2-mechanism.sha256; byte
copy outputs/t2/declaration_v1.md). Everything under outputs/p2r/ is read-only here; nothing changes a registered
number and no locked protocol is touched. Five tests (declaration §3):
i responsibility-weighted warp error of M2-Sa at the end of training (λ of the protocol; λ ∈ {1, 3} as a declared
diagnostic) against the uniform mean warp of the same 64-member bank (primary) and of all 1024 particles;
ii control bank: 64 Gaussian-process warps with the particles' mean and covariance on the warp grid (no other
information), trained like M2-Sa (RML, λ = 1/τ_c, uniform π, 250 iterations), scored on the test wells;
iii posterior multimodality (2- vs 1-component Gaussian mixture of the per-particle window offset) and the
M2-Sa/B3d-Sa ratio of multimodal vs unimodal (regime, c, rid) units, from the saved predictions;
iv Berkson-vs-classical covariance test of the window offset of B3d-Sa and B3c-R (raw, and anchored to B3b);
v B3d-Sa, M2-Sa and Oracle retrained with budgets [250, 500] on one trajectory.
Stages (--tests): "i", "ii", "v" run the training stage (one job per cell-realization; 6 networks × 5 seeds on the
GPU, with the training set rebuilt exactly as scripts/15 run_cell); "iii", "iv" run the particle stage (CPU, all 30
cells); "summary" aggregates (tables, figures, reproduction check). A job is skipped when its output CSV exists.
scripts/runlog.sh -n t2_train -- scripts/32_t2_mechanism.py --tests i ii v --device cuda:0 --workers 4
scripts/runlog.sh -n t2_particles -- scripts/32_t2_mechanism.py --tests iii iv --workers 4
scripts/runlog.sh -n t2_summary -- scripts/32_t2_mechanism.py --tests summary
→ outputs/t2/
"""
from __future__ import annotations
import argparse
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
import yaml
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
run_d2 = load_script("11_run_d2.py")
sp13 = load_script("13_summarize_p2.py")
RIDS = list(range(8, 16))
SEEDS = [0, 1, 2, 3, 4]
REGIMES = ["R10", "R0", "Rm5", "R0h", "R10tb"]
WIDE16 = [("R0", 1.0), ("R0h", 1.0), ("R10tb", 1.0), ("Rm5", 1.0), ("R0", 2.0), ("Rm5", 2.0), ("R0h", 2.0), ("R10tb", 2.0)]
NARROW16 = [("R10", 0.0), ("R0", 0.0), ("Rm5", 0.0)]
TRAIN_CELLS = [(r, c, 16) for r, c in WIDE16 + NARROW16]
ALL_CELLS = [(r, c, n) for r in REGIMES for c in (0.0, 1.0, 2.0) for n in (4, 16)]
LAM_DIAG = {"1": 1.0, "3": 3.0}
B_PM, B_O = 250, 500
MIN_SLOPE_MS, MAX_ATTEMPTS = 0.05, 1280
MAIN_MS = (600.0, 1100.0)
P2R = outputs_dir() / "p2r"
N_BOOT = 2000
TRAIN_METHODS = ["Oracle", "B3d-Sa", "M2-Sa", "M2-Sa@1", "M2-Sa@3", "Control"]
REG_BUDGET = {"Oracle": 500, "B3d-Sa": 250, "M2-Sa": 250}
def tag(regime: str, rid: int, c: float, N: int) -> str:
return f"{regime}_r{rid}_c{c:g}_n{N}"
def regime_settings() -> dict:
reg = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_p2r.yaml").read_text())["regimes"]
return {k: (v["snr_db"], v["anchor_density"]) for k, v in reg.items()}
# ----------------------------------------------------------------------------------------------------------------
# cell construction (as scripts/15 run_cell)
# ----------------------------------------------------------------------------------------------------------------
def build_cell(regime: str, rid: int, c: float, N: int, P: dict, with_register: bool) -> dict:
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid
from ml_porosity.data.wavelet import statistical_wavelet
from ml_porosity.models.bank_train import zscore_patch
from ml_porosity.registration.labels import antialias, labels_for_warps
from ml_porosity.registration.smc import phase_basis, phase_wavelet
from ml_porosity.registration.tie_likelihood import synth_for_warps
from ml_porosity.registration.ties import tie_b3b, tie_b3c, warp_mean
from ml_porosity.registration.warp_prior import WarpHyper
snr, dens = regime_settings()[regime]
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"]]
R = D2Realization(cfg, rid, hg, WarpHyper(**prior["hyper"]), wav)
sa = cfg["anchors"]["sigma_a_ms"]
obs = [R.observe(w, c, snr, sa, dens) for w in R.pool[:N]]
test = [R.observe(w, c, snr, sa) for w in R.test]
reg = run_d2.reg_settings(P)
post = P2R / "posterior" / regime
t = f"r{rid}_c{c:g}_n{N}_s0"
ph = json.loads((post / f"{t}_phase.json").read_text())
smc = np.load(post / f"{t}_particles.npz")
f, fac = cfg["fine_dt_ms"], 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"])
lab = lambda y, T: labels_for_warps(R.tau_fine, y, np.atleast_2d(T), R.t_main)
wells = []
for i, o in enumerate(obs):
y_aa = antialias(o["phi_log"], f, R.dt)
t_b3b = tie_b3b(o["tau_k"], o["t_k"], R.tau_fine)
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], t_b3b, R.t_fine, R.t_ext, wR)[0]
t3c = tie_b3c(t_b3b, R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
U = smc[f"{o['name']}/estR/g_acf"].astype(float)
Tg = R.grid.t_of_tau(U[:, 0], U[:, 1:]) # (P, n_grid), warp-grid nodes
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine) # (P, n_fine)
tm = warp_mean(Tf, np.zeros(len(Tf))) # the B3d-Sa warp
sub = np.random.default_rng([0, i, 29]).choice(len(Tf), reg["S"], replace=False)
Y = lab(y_aa, Tf[sub])
ok = np.all(np.isfinite(Y), 1)
Y[~ok] = Y[ok][0]
logpi = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
tb_nodes = np.interp(R.grid.tau, R.tau_fine, t_b3b)
K = np.flatnonzero((tb_nodes >= MAIN_MS[0]) & (tb_nodes <= MAIN_MS[1]))
wells.append(dict(i=i, name=o["name"], o=o, y_aa=y_aa, t_b3b=t_b3b, t3c=t3c, U=U, Tg=Tg, Tf=Tf, tm=tm,
sub=sub, Y=Y, ok=ok, logpi=logpi, K=K))
cell = dict(R=R, obs=obs, test=test, reg=reg, ph=ph, wells=wells, lab=lab, snr=snr, dens=dens,
X=np.stack([zscore_patch(o["seis"], R.main) for o in obs]),
Xte=np.stack([zscore_patch(o["seis"], R.main) for o in test]),
yt=100 * np.stack([o["y_true"] for o in test]))
if with_register:
from ml_porosity.registration.pipeline import register
out = register(R, obs, reg, 0)
if ph["phase0"] != out["phase"]:
raise RuntimeError(f"{tag(regime, rid, c, N)}: register phase {out['phase']} differs from scripts/14 {ph['phase0']}")
cell["out"] = out
return cell
def window_offsets(w: dict, R) -> dict:
"""Window-mean offsets (ms) over the nodes K of the well: per particle (a_s) and per method; the node-wise
offsets d_m(τ_k) = t_m(τ_k) − τ_k for the per-sample sensitivity of test iv."""
K = w["K"]
tau_k = R.grid.tau[K]
at = lambda t: np.interp(tau_k, R.tau_fine, t) - tau_k
d = {"true": at(w["o"]["t_of_tau_true"]), "B3b": at(w["t_b3b"]), "B3d-Sa": at(w["tm"]), "B3c-R": at(w["t3c"])}
a_s = (w["Tg"][:, K] - tau_k[None, :]).mean(1)
return {"nodes": d, "a_particles": a_s, "b_particles": w["U"][:, 0], "n_K": len(K),
"a": {m: float(v.mean()) for m, v in d.items()}}
# ----------------------------------------------------------------------------------------------------------------
# training stage (tests i, ii, v)
# ----------------------------------------------------------------------------------------------------------------
def control_bank(w: dict, R, S: int) -> tuple[np.ndarray, dict]:
"""64 warps T̄ + η_s, η_s ~ GP with the particles' covariance on the warp grid (declaration §3 ii)."""
Tg = w["Tg"]
Tbar = Tg.mean(0)
lam, V = np.linalg.eigh(np.cov(Tg.T, ddof=0))
Lm = V * np.sqrt(np.clip(lam, 0.0, None))[None, :]
rng = np.random.default_rng([0, w["i"], 2029])
members, n_rej, attempts = [], 0, 0
while len(members) < S and attempts < MAX_ATTEMPTS:
t = Tbar + Lm @ rng.standard_normal(len(Tbar))
attempts += 1
if np.all(np.diff(t) > MIN_SLOPE_MS):
members.append(t)
else:
n_rej += 1
fallback = len(members) < S
if fallback: # u-space Gaussian draw (monotone by construction)
U = w["U"]
lu, Vu = np.linalg.eigh(np.cov(U.T, ddof=0))
Lu = Vu * np.sqrt(np.clip(lu, 0.0, None))[None, :]
ubar = U.mean(0)
while len(members) < S:
u = ubar + Lu @ rng.standard_normal(len(ubar))
members.append(R.grid.t_of_tau(u[0], u[1:])[0])
Tc_grid = np.stack(members)
Tc = np.stack([np.interp(R.tau_fine, R.grid.tau, t) for t in Tc_grid])
K = w["K"]
info = {"ctl_n_rejected": n_rej, "ctl_attempts": attempts, "ctl_fallback_u": bool(fallback),
"ctl_sd_ratio": float(Tc_grid[:, K].std(0).mean() / Tg[:, K].std(0).mean()),
"ctl_sd_mean_ms": float(Tc_grid[:, K].std(0).mean()), "post_sd_mean_ms": float(Tg[:, K].std(0).mean())}
return Tc, info
def member_errors(T: np.ndarray, R, o: dict) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""τ_s(t) on t_main for every warp of T (NaN outside the domain), τ_true(t) and the per-member RMSE (ms)."""
from ml_porosity.registration.labels import invert_warps
tau_s = invert_warps(T, R.tau_fine, R.t_main)
tau_true = invert_warps(o["t_of_tau_true"][None], R.tau_fine, R.t_main)[0]
e = np.sqrt(np.nanmean((tau_s - tau_true[None]) ** 2, 1))
return tau_s, tau_true, e
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.losses.rml import responsibilities
from ml_porosity.models.bank_train import WIN, train_predict, window_starts_fixed
from ml_porosity.registration.ties import warp_errors, warp_mean
t0 = time.time()
cell = build_cell(regime, rid, c, N, P, with_register=True)
R, out, wells = cell["R"], cell["out"], cell["wells"]
stem = 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)
err = lambda t, o: warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
# banks: Oracle (register), B3d-Sa, M2-Sa (SMC), Control (GP)
spec_oracle = run_d2.method_specs(out, P, ["Oracle"])["Oracle"]
Y_pm = nb(np.stack([cell["lab"](w["y_aa"], w["tm"]) for w in wells]))
Y_rml = nb(np.stack([w["Y"] for w in wells]))
logpi = np.stack([w["logpi"] for w in wells]).astype(np.float32)
ctl_rows, Yc = [], []
for w in wells:
Tc, info = control_bank(w, R, cell["reg"]["S"])
Y = cell["lab"](w["y_aa"], Tc)
ok = np.all(np.isfinite(Y), 1)
Y[~ok] = Y[ok][0]
Yc.append(Y)
_, _, e_ctl = member_errors(Tc, R, w["o"])
_, _, e_smc = member_errors(w["Tf"][w["sub"]], R, w["o"])
ctl_rows.append(key | {"well": w["name"], "lam": lam} | info | {
"ctl_n_valid": int(ok.sum()), "ctl_mean_warp_rmse_ms": err(warp_mean(Tc, np.zeros(len(Tc))), w["o"]),
"ctl_member_err_mean_ms": float(np.nanmean(e_ctl[ok])), "smc_member_err_mean_ms": float(np.nanmean(e_smc[w["ok"]])),
"B3d-Sa_warp_rmse_ms": err(w["tm"], w["o"]), "M2-Sa_n_valid": int(w["ok"].sum())})
w["ctl_logpi"] = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
Y_ctl = nb(np.stack(Yc))
logpi_ctl = np.stack([w["ctl_logpi"] for w in wells]).astype(np.float32)
bank = lambda Y, lp, lam_: {"kind": "bank", "Y": Y, "logpi": lp, "lam": lam_}
specs = {"Oracle": (spec_oracle, [B_PM, B_O]),
"B3d-Sa": (bank(Y_pm, np.zeros((N, 1), np.float32), lam), [B_PM, B_O]),
"M2-Sa": (bank(Y_rml, logpi, lam), [B_PM, B_O]),
**{f"M2-Sa@{k}": (bank(Y_rml, logpi, v), [B_PM]) for k, v in LAM_DIAG.items()},
"Control": (bank(Y_ctl, logpi_ctl, lam), [B_PM])}
# per-well warp quantities of test i (independent of the network)
starts_np = window_starts_fixed(R.t_main.size)
M = np.zeros((len(starts_np), R.t_main.size))
for j, s in enumerate(starts_np):
M[j, s: s + WIN] = 1.0
cnt = M.sum(0)
geo = []
for w in wells:
tau_s, tau_true, e_s = member_errors(w["Tf"][w["sub"]], R, w["o"])
geo.append(dict(tau_s=np.nan_to_num(tau_s), tau_true=tau_true, e_s=e_s,
E_64=err(warp_mean(w["Tf"][w["sub"]], w["logpi"]), w["o"]), E_1024=err(w["tm"], w["o"]),
ebar_u=float(np.nanmean(e_s[w["ok"]]))))
T = lambda a: torch.as_tensor(np.asarray(a), dtype=torch.float32, device=device)
X_t, starts_t = T(cell["X"]), torch.as_tensor(np.tile(starts_np, (N, 1)), device=device)
rows, resp_rows = [], []
for seed in seeds:
for m, (sp, bud) in specs.items():
store = {}
cb = None
if m.startswith("M2-Sa"):
Y_t, lp_t = T(sp["Y"]), T(sp["logpi"])
def cb(step, model, Y_t=Y_t, lp_t=lp_t, lam_=sp["lam"], store=store):
with torch.no_grad():
mu, s = model(X_t)
r = responsibilities(mu[:, 0], s[:, 0], Y_t, lp_t, starts_t, WIN, lam_)
store[step] = r.cpu().numpy().astype(np.float64)
preds = train_predict(cell["X"], cell["Xte"], sp, tcfg, seed, bud, device, on_budget=cb)
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)
for b, r in store.items(): # (N, J, S)
rbar = r.mean(1) # (N, S)
r_i = np.einsum("ji,njs->nis", M, r) / cnt[None, :, None] # (N, L, S)
for w, g in zip(wells, geo):
rb, rs = rbar[w["i"]], r_i[w["i"]]
with np.errstate(divide="ignore"):
logw = np.log(rb)
E_r = err(warp_mean(w["Tf"][w["sub"]], logw), w["o"])
tau_r = np.einsum("is,si->i", rs, g["tau_s"])
E_r_win = float(np.sqrt(np.mean((tau_r - g["tau_true"]) ** 2)))
rj = r[w["i"]]
resp_rows.append(key | {
"seed": seed, "method": m, "lam": sp["lam"], "budget": b, "well": w["name"],
"E_r": E_r, "E_r_win": E_r_win, "E_64": g["E_64"], "E_1024": g["E_1024"],
"ebar_r": float(np.nansum(rb * np.nan_to_num(g["e_s"]))), "ebar_u": g["ebar_u"],
"S_eff": float(1.0 / np.sum(rb ** 2)), "entropy": float(-np.sum(rb[rb > 0] * np.log(rb[rb > 0]))),
"S_eff_win": float(np.mean(1.0 / np.sum(rj ** 2, 1))), "rmax_win": float(np.mean(rj.max(1))),
"n_valid": int(w["ok"].sum())})
pd.DataFrame(ctl_rows).to_csv(out_dir / f"{stem}_ctl.csv", index=False)
pd.DataFrame(resp_rows).to_csv(out_dir / f"{stem}_resp.csv", index=False)
pd.DataFrame(rows).to_csv(out_dir / f"{stem}.csv", index=False) # written last: marks the job as complete
return stem, time.time() - t0
# ----------------------------------------------------------------------------------------------------------------
# particle stage (tests iii, iv)
# ----------------------------------------------------------------------------------------------------------------
def gmm_stats(x: np.ndarray) -> dict:
from sklearn.mixture import GaussianMixture
x = x[:, None]
fit = lambda k: GaussianMixture(k, covariance_type="full", n_init=5, random_state=0, reg_covar=1e-6).fit(x)
g1, g2 = fit(1), fit(2)
mu = g2.means_.ravel()
w = g2.weights_
dbic = float(g1.bic(x) - g2.bic(x))
sep = float(abs(mu[0] - mu[1]))
return {"dbic": dbic, "sep_ms": sep, "w_min": float(w.min()), "sd_ms": float(x.std()),
"multimodal": bool(dbic > 10 and sep > 4.0 and w.min() >= 0.1)}
def particle_job(job) -> tuple[str, float]:
regime, rid, c, N, out_dir, P = job
t0 = time.time()
cell = build_cell(regime, rid, c, N, P, with_register=False)
R = cell["R"]
stem = tag(regime, rid, c, N)
key = dict(regime=regime, rid=rid, c=c, n_train=N)
rows3, rows4, nodes = [], [], {}
for w in cell["wells"]:
off = window_offsets(w, R)
ga, gb = gmm_stats(off["a_particles"]), gmm_stats(off["b_particles"])
rows3.append(key | {"well": w["name"], "n_K": off["n_K"]} | {f"a_{k}": v for k, v in ga.items()}
| {f"b_{k}": v for k, v in gb.items()})
rows4.append(key | {"well": w["name"], "n_K": off["n_K"]} | {f"a_{m}": v for m, v in off["a"].items()})
for m, v in off["nodes"].items():
nodes[f"{w['name']}/{m}"] = v.astype(np.float32)
np.savez_compressed(out_dir / "iv" / f"{stem}.npz", **nodes)
pd.DataFrame(rows3).to_csv(out_dir / "iii" / f"{stem}.csv", index=False)
pd.DataFrame(rows4).to_csv(out_dir / "iv" / f"{stem}.csv", index=False)
return stem, time.time() - t0
# ----------------------------------------------------------------------------------------------------------------
# summary
# ----------------------------------------------------------------------------------------------------------------
def ci(rng, num: np.ndarray, den: np.ndarray | None = None) -> list[float]:
return sp13.boot(np.asarray(num, float), None if den is None else np.asarray(den, float), N_BOOT, rng)
def per_rid(df: pd.DataFrame, col: str = "band_rmse") -> pd.Series:
"""Mean over seeds and test wells per realization (index: rid)."""
return df.groupby("rid")[col].mean()
def registered_cells(cells: list[tuple[str, float, int]]) -> pd.DataFrame:
rows = []
for regime, c, N in cells:
for rid in RIDS:
f = P2R / "train" / regime / "cells" / f"r{rid}_c{c:g}_n{N}.csv"
d = pd.read_csv(f)
d = d[d.budget == d.method.map(REG_BUDGET).fillna(-1)]
rows.append(d.assign(regime=regime))
return pd.concat(rows, ignore_index=True)
def ratio_row(rng, num: pd.DataFrame, den: pd.DataFrame, col: str = "band_rmse") -> dict:
a, b = per_rid(num, col), per_rid(den, col)
a, b = a.align(b, join="inner")
lo, hi = ci(rng, a.to_numpy(), b.to_numpy())
return {"ratio": float(a.mean() / b.mean()), "lo": lo, "hi": hi, "n_rid": int(len(a))}
def diff_row(rng, num: pd.DataFrame, den: pd.DataFrame, col: str = "band_rmse") -> dict:
a, b = per_rid(num, col), per_rid(den, col)
a, b = a.align(b, join="inner")
d = (a - b).to_numpy()
lo, hi = ci(rng, d)
return {"diff": float(d.mean()), "diff_lo": lo, "diff_hi": hi}
def cluster_corr(rng, df: pd.DataFrame, x: str, y: str) -> dict:
"""Pearson correlation with a cluster bootstrap over realizations (declaration §3 iv)."""
r = float(np.corrcoef(df[x], df[y])[0, 1]) if len(df) > 2 else np.nan
rids = df.rid.unique()
groups = {k: g[[x, y]].to_numpy() for k, g in df.groupby("rid")}
boots = []
for _ in range(N_BOOT):
pick = rng.choice(rids, len(rids), replace=True)
v = np.concatenate([groups[k] for k in pick])
boots.append(np.corrcoef(v[:, 0], v[:, 1])[0, 1] if v[:, 0].std() > 0 and v[:, 1].std() > 0 else np.nan)
lo, hi = np.nanpercentile(boots, [2.5, 97.5])
return {"r": r, "lo": float(lo), "hi": float(hi), "n": int(len(df))}
def verdict_iv(rB: dict, rC: dict) -> str:
b0, c0 = rB["lo"] <= 0 <= rB["hi"], rC["lo"] <= 0 <= rC["hi"]
if b0 and not c0:
return "Berkson"
if c0 and not b0:
return "classical"
return "neither (no power)" if b0 and c0 else "neither (no structure)"
def summarize(out: Path, device_note: str) -> None:
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from ml_porosity.eval import figstyle
figstyle.apply()
fig_dir = out / "figures"
fig_dir.mkdir(exist_ok=True)
rng = np.random.default_rng(0)
meta = {"declaration_sha256": (REPO_ROOT / "docs/research/t2-mechanism.sha256").read_text().strip().splitlines(),
"n_boot": N_BOOT, "device": device_note}
md = ["# T2 (exploratory): summary of outputs/t2\n",
"Declared in docs/research/t2-mechanism.md before any computation; nothing here changes a registered number.\n"]
# ---------------------------------------------------------------- training outputs and reproduction check
cell_files = sorted(f for f in (out / "cells").glob("*_n16.csv") if not f.name.endswith(("_ctl.csv", "_resp.csv")))
have_train = len(cell_files) > 0
if have_train:
tr = pd.concat([pd.read_csv(f) for f in cell_files], ignore_index=True)
done = sorted({(r, c, 16) for r, c in tr[["regime", "c"]].drop_duplicates().itertuples(index=False)})
reg = registered_cells(done)
# reproduction: retrained at the registered budget vs registered, per (cell, rid, seed, test_well)
rep = tr[tr.method.isin(REG_BUDGET) & (tr.budget == tr.method.map(REG_BUDGET))]
keys = ["regime", "c", "rid", "seed", "method", "test_well"]
mg = rep.merge(reg[keys + ["band_rmse", "rmse"]], on=keys, suffixes=("", "_reg"))
mg["dev"] = (mg.band_rmse - mg.band_rmse_reg).abs()
sc = {"n_rows": int(len(mg)), "band_rmse_abs_dev_max": float(mg.dev.max()), "band_rmse_abs_dev_mean": float(mg.dev.mean()),
"band_rmse_abs_dev_median": float(mg.dev.median()),
"by_method": {m: {"max": float(d.dev.max()), "mean": float(d.dev.mean())} for m, d in mg.groupby("method")}}
one = mg[(mg.regime == "R0") & (mg.c == 1.0) & (mg.rid == 8) & (mg.seed == 0)]
sc["R0_r8_c1_n16_seed0"] = {m: {"max_abs_dev": float(d.dev.max()), "band_rmse_retrained": float(d.band_rmse.mean()),
"band_rmse_registered": float(d.band_rmse_reg.mean())} for m, d in one.groupby("method")}
# cell-level: retrained vs registered cell means
cm = mg.groupby(["regime", "c", "method"])[["band_rmse", "band_rmse_reg"]].mean()
sc["cell_mean_rel_dev_max"] = float(((cm.band_rmse - cm.band_rmse_reg) / cm.band_rmse_reg).abs().max())
# warp diagnostics vs registered _diag.csv
ctl = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_ctl.csv"))], ignore_index=True)
dg = []
for regime, c, N in done:
for rid in RIDS:
d = pd.read_csv(P2R / "train" / regime / "cells" / f"r{rid}_c{c:g}_n{N}_diag.csv")
dg.append(d.assign(regime=regime))
dg = pd.concat(dg, ignore_index=True)
wd = ctl.merge(dg[["regime", "c", "rid", "well", "B3d-Sa_warp_rmse_ms", "M2-Sa_n_valid", "lam"]],
on=["regime", "c", "rid", "well"], suffixes=("", "_diag"))
sc["warp_rmse_abs_dev_max"] = float((wd["B3d-Sa_warp_rmse_ms"] - wd["B3d-Sa_warp_rmse_ms_diag"]).abs().max())
sc["n_valid_mismatch"] = int((wd["M2-Sa_n_valid"] != wd["M2-Sa_n_valid_diag"]).sum())
sc["lam_abs_dev_max"] = float((wd["lam"] - wd["lam_diag"]).abs().max())
(out / "selfcheck.json").write_text(json.dumps(sc, indent=1))
meta["selfcheck"] = sc
md.append("## Reproduction check (retrained vs registered band RMSE per seed and test well)\n")
md.append(f"rows {sc['n_rows']}; max |dev| {sc['band_rmse_abs_dev_max']:.3e}, mean {sc['band_rmse_abs_dev_mean']:.3e}, "
f"median {sc['band_rmse_abs_dev_median']:.3e}; cell-mean relative dev max {sc['cell_mean_rel_dev_max']:.3e}; "
f"warp RMSE max dev {sc['warp_rmse_abs_dev_max']:.1e} ms; n_valid mismatches {sc['n_valid_mismatch']}; "
f"lambda max dev {sc['lam_abs_dev_max']:.1e}\n")
md.append("R0 r8 c1 n16 seed 0: " + "; ".join(f"{m}: max |dev| {v['max_abs_dev']:.3e}" for m, v in sc["R0_r8_c1_n16_seed0"].items()) + "\n")
# ---------------------------------------------------------------- test ii
rows = []
for regime, c, N in done:
cell = dict(regime=regime, c=c, n_train=N, wide=(regime, c) in WIDE16)
sel = lambda df, m, b: df[(df.regime == regime) & (df.c == c) & (df.method == m) & (df.budget == b)]
ctl_df, pm_reg, rml_reg = sel(tr, "Control", B_PM), sel(reg, "B3d-Sa", B_PM), sel(reg, "M2-Sa", B_PM)
pm_new, rml_new = sel(tr, "B3d-Sa", B_PM), sel(tr, "M2-Sa", B_PM)
r = cell | {f"ctl_pm_{k}": v for k, v in ratio_row(rng, ctl_df, pm_reg).items()}
r |= {f"rml_pm_{k}": v for k, v in ratio_row(rng, rml_reg, pm_reg).items()}
r |= {f"ctl_rml_{k}": v for k, v in ratio_row(rng, ctl_df, rml_reg).items()}
r |= {f"ctl_pm_new_{k}": v for k, v in ratio_row(rng, ctl_df, pm_new).items()}
r |= {f"rml_pm_new_{k}": v for k, v in ratio_row(rng, rml_new, pm_new).items()}
r |= {f"ctl_rml_new_{k}": v for k, v in ratio_row(rng, ctl_df, rml_new).items()}
r |= {f"D_ctl_rml_{k}": v for k, v in diff_row(rng, ctl_df, rml_reg).items()}
r |= {f"ctl_pm_pcc_{k}": v for k, v in ratio_row(rng, ctl_df, pm_reg, "band_pcc").items()}
cd = ctl[(ctl.regime == regime) & (ctl.c == c)]
r |= {"ctl_sd_ratio": float(cd.ctl_sd_ratio.mean()), "ctl_rejected_total": int(cd.ctl_n_rejected.sum()),
"ctl_fallback_wells": int(cd.ctl_fallback_u.sum()), "ctl_member_err_ms": float(cd.ctl_member_err_mean_ms.mean()),
"smc_member_err_ms": float(cd.smc_member_err_mean_ms.mean()), "ctl_mean_warp_rmse_ms": float(cd.ctl_mean_warp_rmse_ms.mean()),
"pm_warp_rmse_ms": float(cd["B3d-Sa_warp_rmse_ms"].mean())}
ctl_gain, ctl_null = r["ctl_pm_hi"] < 1, r["ctl_pm_lo"] <= 1 <= r["ctl_pm_hi"]
rml_gain = r["rml_pm_hi"] < 1
d0, dpos = r["D_ctl_rml_diff_lo"] <= 0 <= r["D_ctl_rml_diff_hi"], r["D_ctl_rml_diff_lo"] > 0
if ctl_gain and d0:
v = "A: consistent with (a)"
elif ctl_null and rml_gain:
v = "B: against (a)"
elif ctl_gain and dpos:
v = "C: partial (a)"
else:
v = "D: undetermined"
r["verdict"] = v
rows.append(r)
t2 = pd.DataFrame(rows)
t2.to_csv(out / "test_ii.csv", index=False)
wide = t2[t2.wide]
meta["test_ii"] = {"verdict_counts_wide": wide.verdict.value_counts().to_dict(),
"narrow_ctl_pm": t2[~t2.wide][["regime", "ctl_pm_ratio", "ctl_pm_lo", "ctl_pm_hi"]].to_dict("records")}
md.append("## Test ii: control bank (GP noise with the posterior covariance) vs B3d-Sa and M2-Sa\n")
md.append(sp13.md(t2[["regime", "c", "wide", "ctl_pm_ratio", "ctl_pm_lo", "ctl_pm_hi", "rml_pm_ratio", "rml_pm_lo", "rml_pm_hi",
"ctl_rml_ratio", "ctl_rml_lo", "ctl_rml_hi", "D_ctl_rml_diff", "D_ctl_rml_diff_lo", "D_ctl_rml_diff_hi",
"ctl_pm_new_ratio", "ctl_sd_ratio", "ctl_member_err_ms", "smc_member_err_ms", "ctl_fallback_wells", "verdict"]]) + "\n")
md.append(f"Wide-cell verdicts: {meta['test_ii']['verdict_counts_wide']}\n")
# ---------------------------------------------------------------- test v
rows = []
for regime, c, N in done:
cell = dict(regime=regime, c=c, n_train=N, wide=(regime, c) in WIDE16)
sel = lambda df, m, b: df[(df.regime == regime) & (df.c == c) & (df.method == m) & (df.budget == b)]
pairs = {"o500_pm500": (sel(tr, "Oracle", B_O), sel(tr, "B3d-Sa", B_O)),
"pm500_pm250": (sel(tr, "B3d-Sa", B_O), sel(tr, "B3d-Sa", B_PM)),
"pm500_pm250reg": (sel(tr, "B3d-Sa", B_O), sel(reg, "B3d-Sa", B_PM)),
"rml500_pm500": (sel(tr, "M2-Sa", B_O), sel(tr, "B3d-Sa", B_O)),
"rml500_rml250": (sel(tr, "M2-Sa", B_O), sel(tr, "M2-Sa", B_PM)),
"o250_pm250": (sel(tr, "Oracle", B_PM), sel(tr, "B3d-Sa", B_PM)),
"o500_o250": (sel(tr, "Oracle", B_O), sel(tr, "Oracle", B_PM)),
"rml250_pm250": (sel(tr, "M2-Sa", B_PM), sel(tr, "B3d-Sa", B_PM)),
"o500_pm250": (sel(tr, "Oracle", B_O), sel(tr, "B3d-Sa", B_PM)),
"o500_pm250reg": (sel(reg, "Oracle", B_O), sel(reg, "B3d-Sa", B_PM)),
"rml250_pm250reg": (sel(reg, "M2-Sa", B_PM), sel(reg, "B3d-Sa", B_PM))}
r = dict(cell)
for k, (a, b) in pairs.items():
r |= {f"{k}_{kk}": v for kk, v in ratio_row(rng, a, b).items() if kk != "n_rid"}
r[f"{k}_pcc"] = ratio_row(rng, a, b, "band_pcc")["ratio"]
g500, g250 = 1 - r["o500_pm500_ratio"], 1 - r["o500_pm250_ratio"]
r["gap_share_training_length"] = float(1 - g500 / g250) if g250 > 0 and g500 > 0 else np.nan
rows.append(r)
t5 = pd.DataFrame(rows)
t5.to_csv(out / "test_v.csv", index=False)
md.append("## Test v: retrained with budgets [250, 500] (ratios of cell-mean band RMSE; CI over realizations)\n")
md.append(sp13.md(t5[["regime", "c", "wide", "o500_pm500_ratio", "o500_pm500_lo", "o500_pm500_hi", "pm500_pm250_ratio", "pm500_pm250_lo",
"pm500_pm250_hi", "rml500_pm500_ratio", "rml500_pm500_lo", "rml500_pm500_hi", "o250_pm250_ratio", "o250_pm250_lo",
"o250_pm250_hi", "rml250_pm250_ratio", "rml250_pm250reg_ratio", "o500_pm250_ratio", "o500_pm250reg_ratio",
"gap_share_training_length"]]) + "\n")
# ---------------------------------------------------------------- test i
rs = pd.concat([pd.read_csv(f) for f in sorted((out / "cells").glob("*_resp.csv"))], ignore_index=True)
rs["d_r"] = rs.E_r - rs.E_64
rs["d_r1024"] = rs.E_r - rs.E_1024
rs["d_win"] = rs.E_r_win - rs.E_64
rs["d_e"] = rs.ebar_r - rs.ebar_u
rows = []
for (regime, c, m, b), d in rs.groupby(["regime", "c", "method", "budget"]):
r = dict(regime=regime, c=c, n_train=16, wide=(regime, c) in WIDE16, method=m, lam=float(d.lam.iloc[0]), budget=b,
n_units=int(len(d)))
for q in ["d_r", "d_r1024", "d_win", "d_e"]:
pr = d.groupby("rid")[q].mean().to_numpy()
lo, hi = ci(rng, pr)
r |= {q: float(pr.mean()), f"{q}_lo": lo, f"{q}_hi": hi, f"share_{q}_neg": float((d[q] < 0).mean())}
r |= {k: float(d[k].mean()) for k in ["E_r", "E_r_win", "E_64", "E_1024", "ebar_r", "ebar_u", "S_eff", "entropy", "S_eff_win", "rmax_win"]}
r["cell_c"] = bool(r["share_d_r_neg"] > 0.5 and r["d_r_hi"] < 0)
rows.append(r)
t1 = pd.DataFrame(rows)
t1.to_csv(out / "test_i.csv", index=False)
v1 = {}
for m, d in t1[t1.wide & (t1.budget == B_PM)].groupby("method"):
v1[m] = {"cells_with_c": int(d.cell_c.sum()), "n_wide_cells": int(len(d)), "evidence_for_c": bool(d.cell_c.sum() >= 5)}
meta["test_i"] = v1
md.append("## Test i: responsibility-weighted warp error (ms) vs the uniform mean warp of the same 64 members\n")
md.append(sp13.md(t1[t1.budget == B_PM][["regime", "c", "wide", "method", "lam", "E_r", "E_64", "E_1024", "E_r_win", "d_r", "d_r_lo", "d_r_hi",
"share_d_r_neg", "d_r1024", "d_win", "d_e", "d_e_lo", "d_e_hi", "S_eff", "entropy", "S_eff_win",
"rmax_win", "cell_c"]]) + "\n")
md.append(f"Wide cells with (c) at budget 250: {v1}\n")
if (t1.budget == B_O).any():
md.append("M2-Sa at 500 iterations (descriptive):\n" + sp13.md(t1[t1.budget == B_O][["regime", "c", "d_r", "d_r_lo", "d_r_hi", "S_eff", "entropy"]]) + "\n")
# figures i, ii, v
fig, axes = plt.subplots(1, 3, figsize=(11, 3.4))
lab_cells = [f"{r} c={c:g}" for r, c in WIDE16 + NARROW16]
for ax, (m, title) in zip(axes, [("M2-Sa", "λ = 1/τ_c (protocol)"), ("M2-Sa@1", "λ = 1"), ("M2-Sa@3", "λ = 3")]):
d = t1[(t1.method == m) & (t1.budget == B_PM)].set_index(t1[(t1.method == m) & (t1.budget == B_PM)].apply(lambda r: f"{r.regime} c={r.c:g}", axis=1))
d = d.reindex([k for k in lab_cells if k in d.index])
y = np.arange(len(d))
ax.errorbar(d.d_r, y, xerr=[d.d_r - d.d_r_lo, d.d_r_hi - d.d_r], fmt="o", color=figstyle.BLUE, label="E_r − E_64")
ax.errorbar(d.d_r1024, y + 0.25, xerr=0, fmt="s", color=figstyle.ORANGE, ms=3, label="E_r − E_1024")
ax.axvline(0, color=figstyle.AXIS, lw=0.8)
ax.set_yticks(y)
ax.set_yticklabels(d.index, fontsize=7)
ax.set_title(title)
ax.set_xlabel("warp error difference (ms)")
axes[0].legend(loc="lower left")
fig.suptitle("Test i: responsibility-weighted warp vs uniform mean warp (95% CI over realizations)", fontsize=9)
fig.tight_layout()
fig.savefig(fig_dir / "t2_i_responsibility.pdf")
plt.close(fig)
fig, ax = plt.subplots(figsize=(6.5, 3.6))
d = t2.set_index(t2.apply(lambda r: f"{r.regime} c={r.c:g}", axis=1)).reindex(lab_cells)
x = np.arange(len(d))
ax.errorbar(x - 0.15, d.rml_pm_ratio, yerr=[d.rml_pm_ratio - d.rml_pm_lo, d.rml_pm_hi - d.rml_pm_ratio], fmt="o", color=figstyle.BLUE, label="M2-Sa / B3d-Sa (registered)")
ax.errorbar(x + 0.15, d.ctl_pm_ratio, yerr=[d.ctl_pm_ratio - d.ctl_pm_lo, d.ctl_pm_hi - d.ctl_pm_ratio], fmt="s", color=figstyle.ORANGE, label="Control bank / B3d-Sa")
ax.axhline(1, color=figstyle.AXIS, lw=0.8)
ax.set_xticks(x)
ax.set_xticklabels(d.index, rotation=45, ha="right", fontsize=7)
ax.set_ylabel("band RMSE ratio")
ax.set_title("Test ii: GP-noise control bank (N = 16; 95% CI over realizations)")
ax.legend()
fig.tight_layout()
fig.savefig(fig_dir / "t2_ii_control.pdf")
plt.close(fig)
fig, ax = plt.subplots(figsize=(6.5, 3.6))
d = t5.set_index(t5.apply(lambda r: f"{r.regime} c={r.c:g}", axis=1)).reindex(lab_cells)
for k, off, col, lab, mk in [("o500_pm250", -0.2, figstyle.BLUE, "Oracle(500) / B3d-Sa(250)", "o"), ("o500_pm500", 0.0, figstyle.ORANGE, "Oracle(500) / B3d-Sa(500)", "s"),
("rml500_pm500", 0.2, figstyle.AQUA, "M2-Sa(500) / B3d-Sa(500)", "^")]:
ax.errorbar(x + off, d[f"{k}_ratio"], yerr=[d[f"{k}_ratio"] - d[f"{k}_lo"], d[f"{k}_hi"] - d[f"{k}_ratio"]], fmt=mk, color=col, label=lab, ms=4)
ax.axhline(1, color=figstyle.AXIS, lw=0.8)
ax.set_xticks(x)
ax.set_xticklabels(d.index, rotation=45, ha="right", fontsize=7)
ax.set_ylabel("band RMSE ratio")
ax.set_title("Test v: training length vs label error (retrained; 95% CI over realizations)")
ax.legend(fontsize=7)
fig.tight_layout()
fig.savefig(fig_dir / "t2_v_budget.pdf")
plt.close(fig)
# ---------------------------------------------------------------- test iii
f3 = sorted((out / "iii").glob("*.csv"))
if f3:
m3 = pd.concat([pd.read_csv(f) for f in f3], ignore_index=True)
share = m3.groupby(["regime", "c", "n_train", "rid"]).agg(m_u=("a_multimodal", "mean"), m_u_b=("b_multimodal", "mean"),
sd_a_ms=("a_sd_ms", "mean"), n_wells=("well", "size")).reset_index()
share.to_csv(out / "test_iii_units.csv", index=False)
cell_share = share.groupby(["regime", "c", "n_train"]).agg(m_u=("m_u", "mean"), m_u_b=("m_u_b", "mean"), units_multimodal=("m_u", lambda s: int((s >= 0.25).sum())),
units_any=("m_u", lambda s: int((s > 0).sum())), sd_a_ms=("sd_a_ms", "mean")).reset_index()
rows, groups = [], None
if have_train:
reg_w = registered_cells([(r, c, 16) for r, c in WIDE16])
u = reg_w[reg_w.method.isin(["M2-Sa", "B3d-Sa"])].groupby(["regime", "c", "rid", "method"]).band_rmse.mean().unstack("method")
u["log_ratio"] = np.log(u["M2-Sa"] / u["B3d-Sa"])
u = u.reset_index().merge(share[share.n_train == 16], on=["regime", "c", "rid"])
u.to_csv(out / "test_iii_wide_units.csv", index=False)
def D_stats(u, thr):
u = u.assign(grp=(u.m_u >= thr) if thr > 0 else (u.m_u > 0))
g1, g0 = u[u.grp], u[~u.grp]
res = {"n_multi": int(len(g1)), "n_uni": int(len(g0)),
"D_unadj": float(g1.log_ratio.mean() - g0.log_ratio.mean()) if len(g1) and len(g0) else np.nan}
both = [k for k, d in u.groupby(["regime", "c"]) if d.grp.any() and (~d.grp).any()]
res["cells_with_both_groups"] = len(both)
def adj(u):
num = den = 0.0
for k, d in u.groupby(["regime", "c"]):
a, b = d[d.grp], d[~d.grp]
if len(a) and len(b):
w = len(a) * len(b) / (len(a) + len(b))
num += w * (a.log_ratio.mean() - b.log_ratio.mean())
den += w
return num / den if den > 0 else np.nan
res["D_adj"] = float(adj(u))
boots_u, boots_a = [], []
for _ in range(N_BOOT):
ub = pd.concat([d.iloc[rng.integers(0, len(d), len(d))] for _, d in u.groupby(["regime", "c"])])
a1, a0 = ub[ub.grp], ub[~ub.grp]
boots_u.append(a1.log_ratio.mean() - a0.log_ratio.mean() if len(a1) and len(a0) else np.nan)
boots_a.append(adj(ub))
res["D_unadj_lo"], res["D_unadj_hi"] = [float(v) for v in np.nanpercentile(boots_u, [2.5, 97.5])] if np.isfinite(boots_u).any() else (np.nan, np.nan)
res["D_adj_lo"], res["D_adj_hi"] = [float(v) for v in np.nanpercentile(boots_a, [2.5, 97.5])] if np.isfinite(boots_a).any() else (np.nan, np.nan)
from scipy import stats
res["spearman_mu_logratio"] = float(stats.spearmanr(u.m_u, u.log_ratio)[0]) if u.m_u.std() > 0 else np.nan
if np.isnan(res["D_adj"]):
res["verdict"] = "confounded with cell (no cell has both groups)" if res["n_multi"] else "no multimodal unit: (b) not testable"
elif res["D_adj_hi"] < 0:
res["verdict"] = "evidence for (b)"
else:
res["verdict"] = "no evidence for (b)"
return res
groups = {"thr0.25": D_stats(u, 0.25), "any": D_stats(u, 0.0)}
within = [{"regime": k[0], "c": k[1], "spearman": float(__import__("scipy").stats.spearmanr(d.m_u, d.log_ratio)[0]) if d.m_u.std() > 0 else np.nan,
"n_multi_0.25": int((d.m_u >= 0.25).sum()), "n_any": int((d.m_u > 0).sum())} for k, d in u.groupby(["regime", "c"])]
pd.DataFrame(within).to_csv(out / "test_iii_within_cells.csv", index=False)
meta["test_iii"] = groups
cell_share.to_csv(out / "test_iii.csv", index=False)
md.append("## Test iii: posterior multimodality (GMM on the window offset; ΔBIC > 10, separation > 4 ms, min weight ≥ 0.1)\n")
md.append(sp13.md(cell_share) + "\n")
if groups:
md.append("Wide cells, N = 16, M2-Sa/B3d-Sa log-ratio of multimodal minus unimodal units:\n")
md.append(sp13.md(pd.DataFrame(groups).T.reset_index().rename(columns={"index": "grouping"})) + "\n")
fig, ax = plt.subplots(figsize=(5.5, 3.4))
if have_train and groups:
for (regime, c), d in u.groupby(["regime", "c"]):
ax.scatter(d.m_u + rng.normal(0, 0.005, len(d)), d.log_ratio, s=14, label=f"{regime} c={c:g}")
ax.axhline(0, color=figstyle.AXIS, lw=0.8)
ax.set_xlabel("share of multimodal training wells in the unit")
ax.set_ylabel("log(band RMSE M2-Sa / B3d-Sa)")
ax.set_title("Test iii: gain vs posterior multimodality (wide cells, N = 16)")
ax.legend(fontsize=6, ncol=2)
fig.tight_layout()
fig.savefig(fig_dir / "t2_iii_multimodal.pdf")
plt.close(fig)
# ---------------------------------------------------------------- test iv
f4 = sorted((out / "iv").glob("*.csv"))
if f4:
m4 = pd.concat([pd.read_csv(f) for f in f4], ignore_index=True)
for m in ["B3d-Sa", "B3c-R"]:
m4[f"e_{m}"] = m4[f"a_{m}"] - m4["a_true"]
m4[f"ah_{m}"] = m4[f"a_{m}"] - m4["a_B3b"]
m4["at_anch"] = m4["a_true"] - m4["a_B3b"]
rows = []
cells = [(r, c, n) for (r, c, n), _ in m4.groupby(["regime", "c", "n_train"])] + [("all", 1.0, 0), ("wide16", 1.0, 16)]
for regime, c, N in cells:
if regime == "all":
d = m4[m4.c == c]
elif regime == "wide16":
d = m4[(m4.n_train == 16) & (m4.c == 1.0) & m4.regime.isin([r for r, cc in WIDE16 if cc == 1.0])]
else:
d = m4[(m4.regime == regime) & (m4.c == c) & (m4.n_train == N)]
for m in ["B3d-Sa", "B3c-R"]:
r = dict(regime=regime, c=c, n_train=N, method=m, n_wells=int(len(d)),
sd_e_ms=float(d[f"e_{m}"].std()), sd_atrue_ms=float(d.a_true.std()), sd_atrue_anch_ms=float(d.at_anch.std()),
rmse_e_ms=float(np.sqrt((d[f"e_{m}"] ** 2).mean())))
rC, rB = cluster_corr(rng, d, f"e_{m}", "a_true"), cluster_corr(rng, d, f"e_{m}", f"a_{m}")
rCa, rBa = cluster_corr(rng, d, f"e_{m}", "at_anch"), cluster_corr(rng, d, f"e_{m}", f"ah_{m}")
r |= {f"raw_rC_{k}": v for k, v in rC.items() if k != "n"} | {f"raw_rB_{k}": v for k, v in rB.items() if k != "n"}
r |= {f"anch_rC_{k}": v for k, v in rCa.items() if k != "n"} | {f"anch_rB_{k}": v for k, v in rBa.items() if k != "n"}
r["raw_var_ratio"] = float(d[f"a_{m}"].var() / d.a_true.var()) if d.a_true.var() > 0 else np.nan
r["anch_var_ratio"] = float(d[f"ah_{m}"].var() / d.at_anch.var()) if d.at_anch.var() > 0 else np.nan
r["verdict_anch"] = verdict_iv(rBa, rCa) if c > 0 else "not used (c = 0)"
r["verdict_raw"] = verdict_iv(rB, rC) if c > 0 else "not used (c = 0)"
rows.append(r)
t4 = pd.DataFrame(rows)
# per-sample sensitivity (node-wise offsets) for the N = 16 cells and the pooled c = 1 set
srows = []
for regime, c, N in [(r, c, n) for r, c, n in ALL_CELLS if n == 16]:
parts = []
for rid in RIDS:
f = out / "iv" / f"{tag(regime, rid, c, N)}.npz"
if not f.exists():
continue
with np.load(f) as z:
wells = sorted({k.split("/")[0] for k in z.files})
for w in wells:
parts.append(pd.DataFrame({"rid": rid, "true": z[f"{w}/true"], "B3b": z[f"{w}/B3b"], "B3d-Sa": z[f"{w}/B3d-Sa"], "B3c-R": z[f"{w}/B3c-R"]}))
if not parts:
continue
d = pd.concat(parts, ignore_index=True)
for m in ["B3d-Sa", "B3c-R"]:
d["e"], d["ah"], d["at"] = d[m] - d["true"], d[m] - d["B3b"], d["true"] - d["B3b"]
rC, rB = cluster_corr(rng, d, "e", "true"), cluster_corr(rng, d, "e", m)
rCa, rBa = cluster_corr(rng, d, "e", "at"), cluster_corr(rng, d, "e", "ah")
srows.append(dict(regime=regime, c=c, n_train=N, method=m, n_samples=int(len(d)),
**{f"raw_rC_{k}": v for k, v in rC.items() if k != "n"}, **{f"raw_rB_{k}": v for k, v in rB.items() if k != "n"},
**{f"anch_rC_{k}": v for k, v in rCa.items() if k != "n"}, **{f"anch_rB_{k}": v for k, v in rBa.items() if k != "n"},
verdict_anch=verdict_iv(rBa, rCa) if c > 0 else "not used (c = 0)",
verdict_raw=verdict_iv(rB, rC) if c > 0 else "not used (c = 0)"))
t4s = pd.DataFrame(srows)
t4.to_csv(out / "test_iv.csv", index=False)
t4s.to_csv(out / "test_iv_persample.csv", index=False)
key_cells = t4[(t4.c == 1.0) & (t4.n_train == 16) | (t4.regime == "all") | (t4.regime == "wide16")]
meta["test_iv"] = {f"{r.regime} c={r.c:g} N={r.n_train} {r.method}": {"anchored": r.verdict_anch, "raw": r.verdict_raw}
for r in key_cells.itertuples()}
md.append("## Test iv: Berkson vs classical (window offset; cluster bootstrap over realizations). anch = anchored to B3b (primary)\n")
md.append(sp13.md(t4[["regime", "c", "n_train", "method", "n_wells", "sd_e_ms", "sd_atrue_ms", "sd_atrue_anch_ms", "anch_rB_r", "anch_rB_lo", "anch_rB_hi",
"anch_rC_r", "anch_rC_lo", "anch_rC_hi", "anch_var_ratio", "verdict_anch", "raw_rB_r", "raw_rB_lo", "raw_rB_hi", "raw_rC_r",
"raw_rC_lo", "raw_rC_hi", "raw_var_ratio", "verdict_raw"]]) + "\n")
md.append("Per-sample sensitivity (node-wise offsets, N = 16):\n")
md.append(sp13.md(t4s[["regime", "c", "method", "n_samples", "anch_rB_r", "anch_rB_lo", "anch_rB_hi", "anch_rC_r", "anch_rC_lo", "anch_rC_hi", "verdict_anch",
"raw_rB_r", "raw_rC_r", "verdict_raw"]]) + "\n")
fig, axes = plt.subplots(1, 2, figsize=(9, 3.6), sharey=True)
d16 = t4[(t4.n_train == 16) & (t4.c > 0) & ~t4.regime.isin(["all", "wide16"])]
for ax, m in zip(axes, ["B3d-Sa", "B3c-R"]):
d = d16[d16.method == m]
labels = [f"{r} c={c:g}" for r, c in zip(d.regime, d.c)]
y = np.arange(len(d))
ax.errorbar(d.anch_rB_r, y - 0.15, xerr=[d.anch_rB_r - d.anch_rB_lo, d.anch_rB_hi - d.anch_rB_r], fmt="o", color=figstyle.BLUE, label="corr(e, â′): 0 under Berkson")
ax.errorbar(d.anch_rC_r, y + 0.15, xerr=[d.anch_rC_r - d.anch_rC_lo, d.anch_rC_hi - d.anch_rC_r], fmt="s", color=figstyle.ORANGE, label="corr(e, a*′): 0 under classical")
ax.axvline(0, color=figstyle.AXIS, lw=0.8)
ax.set_yticks(y)
ax.set_yticklabels(labels, fontsize=7)
ax.set_title(m)
ax.set_xlabel("correlation (anchored offsets)")
axes[0].legend(fontsize=7, loc="lower left")
fig.suptitle("Test iv: error structure of the window offset (N = 16; 95% cluster-bootstrap CI)", fontsize=9)
fig.tight_layout()
fig.savefig(fig_dir / "t2_iv_covariance.pdf")
plt.close(fig)
(out / "meta.json").write_text(json.dumps(meta, indent=1, default=float))
(out / "summary.md").write_text("\n".join(md))
print("\n".join(md))
# ----------------------------------------------------------------------------------------------------------------
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--tests", nargs="+", default=["i", "ii", "iii", "iv", "v", "summary"],
choices=["i", "ii", "iii", "iv", "v", "summary"])
ap.add_argument("--device", default="cuda:0")
ap.add_argument("--workers", type=int, default=4)
ap.add_argument("--out-dir", type=Path, default=None, help="default: outputs/t2")
ap.add_argument("--seeds", type=int, nargs="+", default=SEEDS)
ap.add_argument("--cells", nargs="+", default=None, help="restrict the training stage to these cell tags (regime_c), e.g. R0_1")
ap.add_argument("--rids", type=int, nargs="+", default=RIDS)
args = ap.parse_args()
for k, v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMBA_NUM_THREADS": "2",
"NUMEXPR_NUM_THREADS": "2"}.items():
os.environ.setdefault(k, v)
out = args.out_dir or outputs_dir() / "t2"
for sub in ("cells", "iii", "iv", "figures"):
(out / sub).mkdir(parents=True, exist_ok=True)
P = run_d2.load_protocol(check=True)
if run_d2.check_rids(RIDS, P) is None:
raise SystemExit("protocol_p2r main grid expected")
print("protocol_p2 and protocol_p2r (with inputs) match their locked SHA-256", flush=True)
jobs, fn, workers = [], None, args.workers
if {"i", "ii", "v"} & set(args.tests):
cells = TRAIN_CELLS if args.cells is None else [(r, c, n) for r, c, n in TRAIN_CELLS if f"{r}_{c:g}" in args.cells]
for regime, c, N in cells:
for rid in args.rids:
if not (out / "cells" / f"{tag(regime, rid, c, N)}.csv").exists():
jobs.append((regime, rid, c, N, args.seeds, args.device, out / "cells", P))
fn = train_job
elif {"iii", "iv"} & set(args.tests):
for regime, c, N in ALL_CELLS:
for rid in args.rids:
if not ((out / "iii" / f"{tag(regime, rid, c, N)}.csv").exists() and (out / "iv" / f"{tag(regime, rid, c, N)}.csv").exists()):
jobs.append((regime, rid, c, N, out, P))
fn = particle_job
if fn is not None:
print(f"{len(jobs)} jobs, {workers} workers, device {args.device}", flush=True)
t0 = time.time()
if jobs:
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)
if "summary" in args.tests:
summarize(out, args.device)
if __name__ == "__main__":
os.environ.setdefault("PYTHONHASHSEED", "0")
main()