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>
This commit is contained in:
846
scripts/32_t2_mechanism.py
Normal file
846
scripts/32_t2_mechanism.py
Normal file
@@ -0,0 +1,846 @@
|
||||
"""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()
|
||||
496
scripts/33_bench_generator_qc.py
Normal file
496
scripts/33_bench_generator_qc.py
Normal file
@@ -0,0 +1,496 @@
|
||||
"""Generator QC for the S2 misspecification presets (phase P6, item p6-gen; CPU only, about one minute).
|
||||
|
||||
For one dev realization (default 902) and every preset of configs/d2_synth_bench.yaml, quantify what the preset changes
|
||||
relative to the nominal generator (common random numbers, so every difference is the misspecification itself):
|
||||
|
||||
rock physics relative RMS change of the clean seismic and of the true AI log (main window), per-unit shifts;
|
||||
wavelet stationary true wavelet vs nominal: best constant-phase fit (1° grid) and its correlation, peak
|
||||
frequency, 90 % power band; for constant Q the effective wavelet at 600 / 850 / 1100 ms;
|
||||
drift RMS and maximum of t_true,misspec − t_true,nominal over the main window, achieved jump at the step
|
||||
horizon, jitter RMS, monotone repairs; anchor-only Laplace tie (MAP-II hyperparameters as in
|
||||
protocol_p2, N = 4, c = 1, σ_a = 7 ms) warp RMSE against the truth;
|
||||
all axes model error seen by the registration at the TRUE warp: RMS of (seismic predicted by the nominal
|
||||
forward model − actual clean seismic) relative to the signal RMS, after the profiled amplitude α,
|
||||
(i) with the nominal F3 wavelet and (ii) with the best member of the registration's wavelet family
|
||||
(statistical wavelet from the clean train traces + constant phase on the 15° grid), as SNR-equivalent
|
||||
dB next to the regime noise levels (R10: 10 dB, Rm5: −5 dB).
|
||||
|
||||
Outputs: <out>/generator_qc.json and <out>/generator_qc.png (default outputs/bench/dev/). Dev realizations only.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= OMP_NUM_THREADS=4 .venv/bin/python scripts/33_bench_generator_qc.py --rid 902 [--sweep]
|
||||
|
||||
--smc (GPU, or --device cpu as a fallback when the GPUs are full): the registration itself for every preset, as in protocol_p2r (pipeline.register → statistical wavelet,
|
||||
MAP-II hyperparameters, B3c/B3d ties; SMC tie posterior with the phase_R wavelet, γ = 1/κ, P particles) on the first
|
||||
N train wells at the given regimes, c = 1. Reports phase_R, SMC warp RMSE / 90 % coverage / width, posterior residual
|
||||
correlation and the B3c/B3d warp RMSE per preset → <out>/smc_qc_rid<rid>.json. One worker; about 1–3 min per cell.
|
||||
|
||||
OMP_NUM_THREADS=4 .venv/bin/python scripts/33_bench_generator_qc.py --rid 902 --skip-qc --smc --device cuda:1 \
|
||||
--regimes R10 Rm5 --n-train 4 --particles 1024
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import datetime as dt
|
||||
import hashlib
|
||||
import importlib.util
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import scipy
|
||||
import yaml
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
|
||||
from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid, preset_misspec # noqa: E402
|
||||
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet # noqa: E402
|
||||
from ml_porosity.registration.pipeline import PHASES, fit_cell_hyper # noqa: E402
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, synth_for_warps # noqa: E402
|
||||
from ml_porosity.registration.ties import warp_errors # noqa: E402
|
||||
from ml_porosity.registration.warp_prior import WarpHyper, laplace_posterior # noqa: E402
|
||||
|
||||
DEV_RIDS = (902, 903, 904, 905)
|
||||
C, SIGMA_A, N_LAPLACE = 1.0, 7.0, 4
|
||||
NOISE_REL = {"R10": 10 ** (-10 / 20), "Rm5": 10 ** (5 / 20)} # noise RMS / signal RMS at the regime SNR
|
||||
PALETTE = {"nominal": "#52514e", "rp": "#2a78d6", "wv": "#eb6834", "dr": "#1baf7a"}
|
||||
SERIES = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100"]
|
||||
|
||||
|
||||
def sha256(p: Path) -> str:
|
||||
return hashlib.sha256(p.read_bytes()).hexdigest()
|
||||
|
||||
|
||||
def rel_rms(a: np.ndarray, ref: np.ndarray) -> float:
|
||||
return float(np.sqrt(np.mean((a - ref) ** 2)) / np.sqrt(np.mean(ref ** 2)))
|
||||
|
||||
|
||||
def snr_db(rel: float) -> float:
|
||||
return float(-20.0 * np.log10(max(rel, 1e-12)))
|
||||
|
||||
|
||||
def wavelet_stats(w: np.ndarray, dt_ms: float, w_ref: np.ndarray) -> dict:
|
||||
"""Peak frequency, 90 % power band and the best constant-phase fit of w_ref to w (1° grid)."""
|
||||
f = np.fft.rfftfreq(8192, dt_ms / 1000.0)
|
||||
p = np.abs(np.fft.rfft(w, 8192)) ** 2
|
||||
cum = np.cumsum(p) / p.sum()
|
||||
if len(w_ref) != len(w): # centre-pad the shorter one (Q kernels are longer than the wavelet)
|
||||
n = max(len(w), len(w_ref))
|
||||
pad = lambda v: np.pad(v, ((n - len(v)) // 2, (n - len(v)) // 2))
|
||||
w, w_ref = pad(w), pad(w_ref)
|
||||
phases = np.arange(-180.0, 180.0, 1.0)
|
||||
cc = np.array([np.corrcoef(rotate_phase(w_ref, ph), w)[0, 1] for ph in phases])
|
||||
k = int(np.argmax(cc))
|
||||
return {"peak_hz": float(f[np.argmax(p)]), "f05_hz": float(f[np.searchsorted(cum, 0.05)]),
|
||||
"f95_hz": float(f[np.searchsorted(cum, 0.95)]), "best_const_phase_deg": float(phases[k]),
|
||||
"corr_at_best_phase": float(cc[k]), "resid_after_best_phase": float(np.sqrt(max(0.0, 1 - cc[k] ** 2)))}
|
||||
|
||||
|
||||
def model_errors(R, obs: list[dict], w_fine: np.ndarray) -> np.ndarray:
|
||||
"""Per well: relative RMS of (clean centre trace − α·synthetic) at the true warp, α ≥ 0 profiled."""
|
||||
out = []
|
||||
for o in obs:
|
||||
s = o["seis"][o["seis"].shape[0] // 2].astype(float)
|
||||
syn = synth_for_warps(R.tau_fine, o["ai_log"], o["t_of_tau_true"], R.t_fine, R.t_ext, w_fine)[0]
|
||||
a = max(float(syn @ s / max(syn @ syn, 1e-30)), 0.0)
|
||||
out.append(rel_rms(a * syn, s))
|
||||
return np.array(out)
|
||||
|
||||
|
||||
def in_family_error(R, obs: list[dict], wavelet_ms: float) -> dict:
|
||||
"""Best member of the registration's wavelet family at the true warp: statistical wavelet from the clean train
|
||||
traces, constant phase on the 15° grid chosen as in pipeline.register (maximal profiled likelihood summed over
|
||||
wells), then the per-well model error."""
|
||||
fac = int(round(R.dt / R.cfg["fine_dt_ms"]))
|
||||
seis = np.stack([o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs])
|
||||
w0 = statistical_wavelet(seis, R.dt, wavelet_ms)
|
||||
errs = {float(ph): model_errors(R, obs, fine_wavelet(rotate_phase(w0, ph), fac)) for ph in PHASES}
|
||||
score = {ph: -0.5 * len(R.t_ext) * np.sum(np.log(e ** 2)) for ph, e in errs.items()}
|
||||
best = max(score, key=score.get)
|
||||
e = errs[best]
|
||||
return {"phase_deg": best, "err_mean": float(e.mean()), "err_min": float(e.min()), "err_max": float(e.max()),
|
||||
"snr_equiv_db": snr_db(float(e.mean())), "statistical_wavelet": wavelet_stats(w0, R.dt, R.wavelet_nominal)}
|
||||
|
||||
|
||||
def laplace_tie(R, obs: list[dict], reg: dict) -> dict:
|
||||
"""Anchor-only tie under the registration's prior (MAP-II for m_g, σ_g, ℓ; σ_a, σ_b fixed): Laplace mean warp
|
||||
RMSE against the truth over the main window, per well."""
|
||||
h, info = fit_cell_hyper(R, obs, reg, seed=0)
|
||||
rmse, z = [], []
|
||||
for o in obs:
|
||||
mu, S, _, _ = laplace_posterior(R.grid, h, o["tau_k"], o["t_k"] - o["tau_k"])
|
||||
T = R.grid.t_of_tau(mu[0], mu[1:], tau=R.tau_fine)
|
||||
rmse.append(warp_errors(T, R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"])
|
||||
# standardised error of the warp on the grid nodes inside the main window (posterior sd from S)
|
||||
sel = (R.grid.tau >= R.t_main[0]) & (R.grid.tau <= R.t_main[-1])
|
||||
A = np.hstack([np.ones((R.grid.n, 1)), R.grid.Q]) # linearised t(τ) − τ ≈ A u on the grid
|
||||
sd = np.sqrt(np.maximum(np.einsum("ij,jk,ik->i", A, S, A), 1e-12))
|
||||
t_true = R.true_warp_grid(next(w for w in R.wells if w.name == o["name"]), C)
|
||||
z.append(float(np.sqrt(np.mean(((R.grid.t_of_tau(mu[0], mu[1:])[0] - t_true) / sd)[sel] ** 2))))
|
||||
return {"hyper_fit": h.as_dict(), "log_marginal": float(info["log_marginal"]), "at_bound": info["at_bound"],
|
||||
"warp_rmse_ms_mean": float(np.mean(rmse)), "warp_rmse_ms_max": float(np.max(rmse)),
|
||||
"z_rms_mean": float(np.mean(z))}
|
||||
|
||||
|
||||
def qc_preset(R, R0, reg: dict, wavelet_ms: float) -> dict:
|
||||
obs = [R.observe(w, C, None, SIGMA_A) for w in R.pool]
|
||||
obs0 = [R0.observe(w, C, None, SIGMA_A) for w in R0.pool]
|
||||
main_tau = (R.tau_fine >= R.t_main[0]) & (R.tau_fine <= R.t_main[-1])
|
||||
out = {"active": R.misspec_active, "misspec_info": R.misspec_info}
|
||||
# seismic and model error (all axes)
|
||||
out["seis_rel_change_main"] = float(np.mean([rel_rms(o["seis"][4][R.main], o0["seis"][4][R.main])
|
||||
for o, o0 in zip(obs, obs0)]))
|
||||
e_nom = model_errors(R, obs, R.w_fine_nominal)
|
||||
out["model_err_nominal_wavelet"] = {"err_mean": float(e_nom.mean()), "err_max": float(e_nom.max()),
|
||||
"snr_equiv_db": snr_db(float(e_nom.mean()))}
|
||||
out["model_err_in_family"] = in_family_error(R, obs, wavelet_ms)
|
||||
# rock physics
|
||||
if "rock_physics" in R.misspec_active:
|
||||
ai_rel, lnai = [], []
|
||||
for w, o in zip(R.pool, obs):
|
||||
ai_t = R.ai_log_true(w, o)
|
||||
ai_rel.append(rel_rms(ai_t[main_tau], o["ai_log"][main_tau]))
|
||||
lnai.append(float(np.sqrt(np.mean((np.log(ai_t) - np.log(o["ai_log"]))[main_tau] ** 2))))
|
||||
out["rock_physics"] = {"ai_rel_rms_change_main": float(np.mean(ai_rel)), "ln_ai_rms_change_main": float(np.mean(lnai)),
|
||||
"unit_dt_intercept_shift": None if R.unit_dt_shift is None else
|
||||
[float(v) for v in R.unit_dt_shift]}
|
||||
# wavelet
|
||||
if "wavelet" in R.misspec_active:
|
||||
d = R.cfg["fine_dt_ms"]
|
||||
wv = {"stationary": wavelet_stats(R.w_fine, d, R.w_fine_nominal)}
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
wv["Q_at_t"] = {str(int(t)): wavelet_stats(R.true_wavelet_at(t), d, R.w_fine_nominal) for t in (600, 850, 1100)}
|
||||
out["wavelet"] = wv
|
||||
# drift
|
||||
if "drift" in R.misspec_active:
|
||||
dr = R.misspec["drift"]
|
||||
diff = np.array([o["t_of_tau_true"] - o0["t_of_tau_true"] for o, o0 in zip(obs, obs0)])
|
||||
tau_main = (R.tau_fine >= 600) & (R.tau_fine <= 1100)
|
||||
d = {"warp_diff_rms_main_ms": float(np.sqrt(np.mean(diff[:, tau_main] ** 2))),
|
||||
"warp_diff_max_ms": float(np.abs(diff).max()),
|
||||
"true_hyper": R.drift_true.as_dict(), "nominal_hyper": R.drift.as_dict()}
|
||||
if dr["step_ms"] != 0.0:
|
||||
k = R.cfg["horizons"].index(dr["step_horizon"])
|
||||
jumps, tau_hs = [], []
|
||||
for w, o, o0, df in zip(R.pool, obs, obs0, diff):
|
||||
t_h = R.hg.at(w.il, w.xl)[k]
|
||||
tau_h = np.interp(t_h, o0["t_of_tau_true"], R.tau_fine)
|
||||
jumps.append(float(np.interp(tau_h + dr["step_width_ms"] + 12, R.tau_fine, df) - np.interp(tau_h - 8, R.tau_fine, df)))
|
||||
tau_hs.append(float(tau_h))
|
||||
d["step"] = {"jump_ms_mean": float(np.mean(jumps)), "jump_ms_min": float(np.min(jumps)), "jump_ms_max": float(np.max(jumps)),
|
||||
"tau_h_ms_range": [float(np.min(tau_hs)), float(np.max(tau_hs))],
|
||||
"g_anomaly_mean": float(np.mean([np.max(o["g"] - o0["g"]) for o, o0 in zip(obs, obs0)]))}
|
||||
if dr["jitter_sd_ms"] > 0:
|
||||
jit = np.array([o["t_of_tau_true"] - np.interp(R.tau_fine, R.grid.tau, R.grid.t_of_tau(o["b"], o["g"])[0]) for o in obs])
|
||||
d["jitter_rms_ms"] = float(np.sqrt(np.mean(jit ** 2)))
|
||||
d["laplace_tie_N4"] = laplace_tie(R, obs[:N_LAPLACE], reg)
|
||||
out["drift"] = d
|
||||
return out
|
||||
|
||||
|
||||
SWEEP = { # single-knob settings for the level choice on dev (--sweep)
|
||||
"rock_physics.unit_dt_intercept_sd": [0.025, 0.05, 0.1, 0.15],
|
||||
"rock_physics.dt_slope_factor": [0.85, 1.3],
|
||||
"wavelet.minphase_frac": [0.25, 0.5, 0.75, 1.0],
|
||||
"wavelet.Q": [40.0, 80.0, 160.0],
|
||||
"wavelet.peak_freq_factor": [0.8, 1.2],
|
||||
"wavelet.delay_ms": [2.0, 4.0],
|
||||
"drift.step_ms": [4.0, 8.0, 16.0],
|
||||
"drift.jitter_sd_ms": [0.5, 1.0, 2.0],
|
||||
"drift.sigma_b_factor": [2.0, 3.0, 5.0],
|
||||
"drift.sigma_g_factor": [1.5, 2.0],
|
||||
"drift.ell_factor": [0.5, 0.25],
|
||||
}
|
||||
|
||||
|
||||
def run_sweep(build, R0, reg: dict, out: Path) -> None:
|
||||
"""Model error and (for drift) the anchor-only tie for each single-knob setting of SWEEP; one line per setting."""
|
||||
rows = []
|
||||
for key, values in SWEEP.items():
|
||||
axis, k = key.split(".")
|
||||
for v in values:
|
||||
t1 = time.time()
|
||||
R = build({axis: {k: v}})
|
||||
r = qc_preset(R, R0, reg, reg["wavelet_ms"])
|
||||
row = {"axis": axis, "key": k, "value": v, "seis_rel_change_main": r["seis_rel_change_main"],
|
||||
"model_err_nominal_wavelet": r["model_err_nominal_wavelet"]["err_mean"],
|
||||
"model_err_in_family": r["model_err_in_family"]["err_mean"],
|
||||
"snr_equiv_db": r["model_err_in_family"]["snr_equiv_db"], "phase_deg": r["model_err_in_family"]["phase_deg"]}
|
||||
if axis == "drift":
|
||||
d = r["drift"]
|
||||
row |= {"warp_diff_rms_main_ms": d["warp_diff_rms_main_ms"], "laplace_warp_rmse_ms": d["laplace_tie_N4"]["warp_rmse_ms_mean"],
|
||||
"laplace_z_rms": d["laplace_tie_N4"]["z_rms_mean"], "monotone_repairs": r["misspec_info"]["monotone_repairs"]}
|
||||
if axis == "wavelet":
|
||||
row |= {"corr_best_const_phase": r["wavelet"]["stationary"]["corr_at_best_phase"]}
|
||||
rows.append(row)
|
||||
extra = (f" warp diff {row['warp_diff_rms_main_ms']:.2f} ms, Laplace RMSE {row['laplace_warp_rmse_ms']:.2f} ms, z {row['laplace_z_rms']:.2f}"
|
||||
if axis == "drift" else "")
|
||||
print(f"sweep {key} = {v:<6g} in-family error {row['model_err_in_family']:.3f} ({row['snr_equiv_db']:.1f} dB, phase {row['phase_deg']:.0f}°)"
|
||||
f"{extra} | {time.time() - t1:.1f} s", flush=True)
|
||||
(out / "generator_sweep.json").write_text(json.dumps({"rid": R0.rid, "c": C, "sigma_a_ms": SIGMA_A, "rows": rows}, indent=1) + "\n")
|
||||
|
||||
|
||||
def smc_cell(R, reg: dict, st: dict, N: int, n_part: int, device: str, mem_gb: float, seed: int = 0) -> dict:
|
||||
"""Registration of one cell (first N train wells, c = 1) as in protocol_p2r: pipeline.register (CPU), then the SMC
|
||||
tie posterior on `device` with the phase_R wavelet and γ = 1/κ (g_acf). Returns per-well diagnostics."""
|
||||
from ml_porosity.registration.pipeline import register
|
||||
from ml_porosity.registration.sampler import sample_warps
|
||||
from ml_porosity.registration.smc import TiePosterior, gamma_acf, phase_basis, phase_wavelet, residual_kappa
|
||||
|
||||
if device == "cpu": # numpy SMC (as scripts/14 with --device cpu)
|
||||
from ml_porosity.registration.smc import smc_fit_phase, smc_tie_posterior
|
||||
wrap = lambda T: T
|
||||
else:
|
||||
import torch
|
||||
from ml_porosity.registration.smc_torch import TiePosteriorTorch, smc_fit_phase, smc_tie_posterior
|
||||
|
||||
dev = torch.device(device)
|
||||
if dev.type == "cuda": # cap: exceeding it makes this job OOM rather than others
|
||||
total = torch.cuda.get_device_properties(dev).total_memory
|
||||
torch.cuda.set_per_process_memory_fraction(min(1.0, mem_gb * 2**30 / total), dev)
|
||||
wrap = lambda T: TiePosteriorTorch(T, device)
|
||||
obs = [R.observe(w, C, st["snr_db"], SIGMA_A, st["anchor_density"]) for w in R.pool[:N]]
|
||||
t0 = time.time()
|
||||
out = register(R, obs, reg, seed)
|
||||
t_reg = time.time() - t0
|
||||
h = WarpHyper(**out["hyper"])
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
mm = (R.t_ext >= R.t_main[0]) & (R.t_ext <= R.t_main[-1])
|
||||
ncc = lambda a, b: float(np.corrcoef(a[mm], b[mm])[0, 1])
|
||||
B = phase_basis(statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"]), int(round(R.dt / R.cfg["fine_dt_ms"])))
|
||||
Ts, Z0s = [], []
|
||||
for i, o in enumerate(obs):
|
||||
smp = sample_warps(R.grid, h, o["tau_k"], o["t_k"], n_part, reg["g_max"], np.random.default_rng([seed, i, 13]))
|
||||
Ts.append(wrap(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, phase_wavelet(B, out["phase"]), seis[i], (R.t_main[0], R.t_main[-1]))))
|
||||
Z0s.append(Ts[-1].z(smp["u"]))
|
||||
t0 = time.time()
|
||||
phase_r, ph = smc_fit_phase(Ts, Z0s, B, out["phase"], [seed, 19])
|
||||
t_phase = time.time() - t0
|
||||
rows = []
|
||||
t0 = time.time()
|
||||
for i, o in enumerate(obs):
|
||||
T = Ts[i].with_wavelet(phase_wavelet(B, phase_r))
|
||||
_, l0 = T.parts(Z0s[i])
|
||||
gk = gamma_acf(T, Z0s[i], l0)
|
||||
res = smc_tie_posterior(T, Z0s[i], [gk], np.random.default_rng([seed, i, 17]))
|
||||
U = T.u(res["Z"][float(gk)])
|
||||
Tf = R.grid.t_of_tau(U[:, 0], U[:, 1:], tau=R.tau_fine)
|
||||
e = warp_errors(Tf, R.tau_fine, o["t_of_tau_true"], R.t_main)
|
||||
syn_m = T.synth(U.mean(0)[None])[0]
|
||||
d = out["diag"][i]
|
||||
rows.append({"well": o["name"], "gamma": float(gk), "kappa0": float(1.0 / gk), "logZ": float(res["logZ"][float(gk)]),
|
||||
"n_stages": len(res["stages"]), "r_post": ncc(syn_m, seis[i]), "kappa_post": float(residual_kappa(syn_m, seis[i])),
|
||||
"B3c_warp_rmse_ms": d["B3c_warp_rmse_ms"], "B3d_warp_rmse_ms": d["B3d_warp_rmse_ms"],
|
||||
"M2old_warp_rmse_ms": d["M2_warp_rmse_ms"]} | {f"SMC_{k}": float(v) for k, v in e.items()})
|
||||
keys = ["SMC_warp_rmse_ms", "SMC_warp_cov90", "SMC_warp_width90_ms", "r_post", "kappa_post", "B3c_warp_rmse_ms", "B3d_warp_rmse_ms"]
|
||||
return {"phase0": out["phase"], "phase_R": phase_r, "phase_edge": ph["edge"], "hyper": out["hyper"], "lam": out["lam"],
|
||||
"tau_c": out["tau_c"], "wells": rows, "mean": {k: float(np.mean([r[k] for r in rows])) for k in keys},
|
||||
"time_s": {"register": t_reg, "phase": t_phase, "smc": time.time() - t0}}
|
||||
|
||||
|
||||
def run_smc(build, cfg: dict, reg: dict, names: list[str], regimes: list[str], N: int, n_part: int, device: str,
|
||||
mem_gb: float, out: Path, rid: int) -> None:
|
||||
path = out / f"smc_qc_rid{rid}.json"
|
||||
results = json.loads(path.read_text()) if path.exists() else {}
|
||||
results["meta"] = {"rid": rid, "c": C, "sigma_a_ms": SIGMA_A, "n_train": N, "particles": n_part, "device": device,
|
||||
"arm": "estR (statistical wavelet, phase_R), gamma = 1/kappa (g_acf)", "updated": dt.datetime.now().isoformat(timespec="seconds")}
|
||||
for regime in regimes:
|
||||
st = cfg["regimes"][regime]
|
||||
results.setdefault(regime, {})
|
||||
for name in ["nominal"] + names:
|
||||
if name in results[regime]:
|
||||
continue # resume
|
||||
t1 = time.time()
|
||||
R = build(preset_misspec(cfg, name))
|
||||
r = smc_cell(R, reg, st, N, n_part, device, mem_gb)
|
||||
r["active"] = R.misspec_active
|
||||
results[regime][name] = r
|
||||
path.write_text(json.dumps(results, indent=1) + "\n")
|
||||
m = r["mean"]
|
||||
print(f"smc {regime} {name:8s} phase0 {r['phase0']:5.0f}° phase_R {r['phase_R']:5.0f}° | SMC warp RMSE {m['SMC_warp_rmse_ms']:.2f} ms "
|
||||
f"cov90 {m['SMC_warp_cov90']:.2f} width90 {m['SMC_warp_width90_ms']:.1f} ms r_post {m['r_post']:.3f} | B3c {m['B3c_warp_rmse_ms']:.2f} "
|
||||
f"B3d {m['B3d_warp_rmse_ms']:.2f} ms | {time.time() - t1:.0f} s", flush=True)
|
||||
|
||||
|
||||
def make_figure(R0, builds: dict, results: dict, out_png: Path) -> None:
|
||||
import matplotlib
|
||||
matplotlib.use("Agg")
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
plt.rcParams.update({"font.size": 8.5, "axes.titlesize": 9, "axes.labelsize": 8.5, "legend.fontsize": 7.5,
|
||||
"axes.edgecolor": "#c3c2b7", "axes.spines.top": False, "axes.spines.right": False,
|
||||
"text.color": "#0b0b0b", "axes.labelcolor": "#0b0b0b", "xtick.color": "#52514e", "ytick.color": "#52514e"})
|
||||
fig, axes = plt.subplots(2, 3, figsize=(13, 7.4), constrained_layout=True)
|
||||
names = list(results["presets"])
|
||||
by_axis = {ax: [n for n in names if n.startswith(ax)] for ax in ("rp", "wv", "dr")}
|
||||
w0 = R0.pool[0]
|
||||
o0 = R0.observe(w0, C, None, SIGMA_A)
|
||||
main_tau = (R0.tau_fine >= 600) & (R0.tau_fine <= 1100)
|
||||
|
||||
# (a) rock physics: ln(AI_true / AI_nominal) along the log (pool well 0)
|
||||
ax = axes[0, 0]
|
||||
for col, n in zip(SERIES, by_axis["rp"]):
|
||||
R = builds[n]
|
||||
o = R.observe(R.pool[0], C, None, SIGMA_A)
|
||||
ax.plot(R.tau_fine[main_tau], np.log(R.ai_log_true(R.pool[0], o) / o["ai_log"])[main_tau], color=col, lw=1.2, label=n)
|
||||
ax.axhline(0, color="#c3c2b7", lw=0.8)
|
||||
ax.set(xlabel="τ (ms)", ylabel="ln(AI_true / AI_nominal)", title=f"(a) Rock physics: true vs nominal AI along the log ({w0.name})")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (b) wavelets in time
|
||||
ax = axes[0, 1]
|
||||
tf = (np.arange(len(R0.w_fine)) - len(R0.w_fine) // 2) * R0.cfg["fine_dt_ms"]
|
||||
ax.plot(tf, R0.w_fine, color=PALETTE["nominal"], lw=1.6, label="nominal (zero phase)")
|
||||
for col, n in zip(SERIES, by_axis["wv"]):
|
||||
R = builds[n]
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
k = R.true_wavelet_at(1100.0)
|
||||
tk = (np.arange(len(k)) - len(k) // 2) * R.cfg["fine_dt_ms"]
|
||||
ax.plot(tk, k / np.abs(k).max(), color=col, lw=1.2, ls="--", label=f"{n} at 1100 ms")
|
||||
else:
|
||||
ax.plot(tf, R.w_fine, color=col, lw=1.2, label=n)
|
||||
ax.set(xlim=(-70, 70), xlabel="time (ms)", ylabel="amplitude (unit peak)", title="(b) Stationary true wavelets (and Q kernel)")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (c) amplitude spectra
|
||||
ax = axes[0, 2]
|
||||
f = np.fft.rfftfreq(8192, R0.cfg["fine_dt_ms"] / 1000.0)
|
||||
spec = lambda w: np.abs(np.fft.rfft(w, 8192)) / np.abs(np.fft.rfft(w, 8192)).max()
|
||||
ax.plot(f, spec(R0.w_fine), color=PALETTE["nominal"], lw=1.6, label="nominal")
|
||||
for col, n in zip(SERIES, by_axis["wv"]):
|
||||
R = builds[n]
|
||||
if R.misspec["wavelet"]["Q"] is not None:
|
||||
for t, ls in ((600.0, ":"), (1100.0, "--")):
|
||||
ax.plot(f, spec(R.true_wavelet_at(t)), color=col, lw=1.2, ls=ls, label=f"{n} at {int(t)} ms")
|
||||
else:
|
||||
ax.plot(f, spec(R.w_fine), color=col, lw=1.2, label=n)
|
||||
ax.set(xlim=(0, 125), xlabel="frequency (Hz)", ylabel="normalised amplitude", title="(c) Amplitude spectra")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (d) drift: warp change
|
||||
ax = axes[1, 0]
|
||||
for col, n in zip(SERIES, by_axis["dr"]):
|
||||
R = builds[n]
|
||||
o = R.observe(R.pool[0], C, None, SIGMA_A)
|
||||
ax.plot(R.tau_fine, o["t_of_tau_true"] - o0["t_of_tau_true"], color=col, lw=1.2, label=n)
|
||||
ax.axvspan(600, 1100, color="#f0efec", zorder=0)
|
||||
ax.set(xlabel="τ (ms)", ylabel="t_true,misspec − t_true,nominal (ms)", title=f"(d) Drift: change of the true warp ({w0.name}, c = 1)")
|
||||
ax.legend(frameon=False)
|
||||
|
||||
# (e) model error at the true warp, in-family best (SNR-equivalent dB)
|
||||
ax = axes[1, 1]
|
||||
labels = ["nominal"] + names
|
||||
vals = [results["nominal"]["model_err_in_family"]["snr_equiv_db"]] + [results["presets"][n]["model_err_in_family"]["snr_equiv_db"] for n in names]
|
||||
cols = [PALETTE["nominal"]] + [SERIES[0]] * len(names)
|
||||
x = np.arange(len(labels))
|
||||
ax.bar(x, vals, color=cols, width=0.7)
|
||||
for xi, v in zip(x, vals):
|
||||
ax.text(xi, v + 0.6, f"{v:.1f}", ha="center", va="bottom", fontsize=7, color="#0b0b0b")
|
||||
for reg, ls in (("R10", "--"), ("Rm5", ":")):
|
||||
ax.axhline(snr_db(NOISE_REL[reg]), color="#52514e", lw=0.9, ls=ls)
|
||||
ax.text(len(labels) - 0.5, snr_db(NOISE_REL[reg]) + 0.4, f"{reg} noise", ha="right", fontsize=7, color="#52514e")
|
||||
ax.set(xticks=x, xticklabels=labels, ylabel="SNR-equivalent of the model error (dB)",
|
||||
title="(e) Model error at the true warp, best in-family wavelet")
|
||||
ax.tick_params(axis="x", rotation=45)
|
||||
|
||||
# (f) anchor-only Laplace tie (N = 4)
|
||||
ax = axes[1, 2]
|
||||
lab = ["nominal"] + by_axis["dr"]
|
||||
rm = [results["nominal"]["laplace_tie_N4"]["warp_rmse_ms_mean"]] + [results["presets"][n]["drift"]["laplace_tie_N4"]["warp_rmse_ms_mean"] for n in by_axis["dr"]]
|
||||
zr = [results["nominal"]["laplace_tie_N4"]["z_rms_mean"]] + [results["presets"][n]["drift"]["laplace_tie_N4"]["z_rms_mean"] for n in by_axis["dr"]]
|
||||
x = np.arange(len(lab))
|
||||
ax.bar(x, rm, color=[PALETTE["nominal"]] + [SERIES[0]] * len(by_axis["dr"]), width=0.6)
|
||||
for xi, v, z in zip(x, rm, zr):
|
||||
ax.text(xi, v + 0.05, f"{v:.2f} ms\nz RMS {z:.1f}", ha="center", va="bottom", fontsize=7, color="#0b0b0b")
|
||||
ax.set(xticks=x, xticklabels=lab, ylabel="warp RMSE of the Laplace mean (ms)", ylim=(0, max(rm) * 1.35),
|
||||
title="(f) Anchor-only tie under the registration prior (N = 4)")
|
||||
fig.suptitle(f"D2 generator QC, dev realization {R0.rid}: misspecification presets vs nominal (common random numbers)", fontsize=10)
|
||||
fig.savefig(out_png, dpi=160)
|
||||
plt.close(fig)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--rid", type=int, default=902, help="dev realization (902–905)")
|
||||
ap.add_argument("--config", default="configs/d2_synth_bench.yaml")
|
||||
ap.add_argument("--inputs-from", default="configs/protocol_p2r.yaml", help="protocol whose inputs (warp prior, wavelet) are used")
|
||||
ap.add_argument("--reg-from", default="configs/protocol_p2.yaml", help="protocol whose registration block is used for the anchor-only tie")
|
||||
ap.add_argument("--out", default="outputs/bench/dev")
|
||||
ap.add_argument("--presets", nargs="*", default=None, help="subset of preset names (default: all)")
|
||||
ap.add_argument("--sweep", action="store_true", help="also evaluate the single-knob settings of SWEEP → generator_sweep.json")
|
||||
ap.add_argument("--skip-qc", action="store_true", help="skip the light QC and the figure")
|
||||
ap.add_argument("--smc", action="store_true", help="run the registration + SMC tie posterior per preset (GPU) → smc_qc_rid<rid>.json")
|
||||
ap.add_argument("--device", default="cuda:1")
|
||||
ap.add_argument("--regimes", nargs="*", default=["R10", "Rm5"])
|
||||
ap.add_argument("--n-train", type=int, default=4)
|
||||
ap.add_argument("--particles", type=int, default=1024)
|
||||
ap.add_argument("--gpu-mem-gb", type=float, default=2.0, help="per-process GPU memory cap (GiB)")
|
||||
a = ap.parse_args()
|
||||
if a.rid not in DEV_RIDS:
|
||||
raise SystemExit(f"generator QC runs on dev realizations {DEV_RIDS} only (got {a.rid})")
|
||||
|
||||
cfg = yaml.safe_load((REPO_ROOT / a.config).read_text())
|
||||
P = yaml.safe_load((REPO_ROOT / a.inputs_from).read_text())
|
||||
spec = importlib.util.spec_from_file_location("run_d2", REPO_ROOT / "scripts" / "11_run_d2.py")
|
||||
run_d2 = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(run_d2)
|
||||
reg = run_d2.reg_settings(yaml.safe_load((REPO_ROOT / a.reg_from).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"]]
|
||||
build = lambda ms: D2Realization(cfg, a.rid, hg, WarpHyper(**prior["hyper"]), wav, misspec=ms)
|
||||
|
||||
out = REPO_ROOT / a.out
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
names = a.presets or list(cfg["misspec_presets"])
|
||||
if a.smc:
|
||||
run_smc(build, cfg, reg, names, a.regimes, a.n_train, a.particles, a.device, a.gpu_mem_gb, out, a.rid)
|
||||
if a.skip_qc:
|
||||
return
|
||||
t0 = time.time()
|
||||
R0 = build(None)
|
||||
obs0 = [R0.observe(w, C, None, SIGMA_A) for w in R0.pool]
|
||||
e_nom = model_errors(R0, obs0, R0.w_fine_nominal)
|
||||
results = {"nominal": {"model_err_nominal_wavelet": {"err_mean": float(e_nom.mean()), "err_max": float(e_nom.max()),
|
||||
"snr_equiv_db": snr_db(float(e_nom.mean()))},
|
||||
"model_err_in_family": in_family_error(R0, obs0, reg["wavelet_ms"]),
|
||||
"laplace_tie_N4": laplace_tie(R0, obs0[:N_LAPLACE], reg),
|
||||
"wavelet": wavelet_stats(R0.w_fine, cfg["fine_dt_ms"], R0.w_fine_nominal)},
|
||||
"presets": {}}
|
||||
builds = {}
|
||||
for name in names:
|
||||
t1 = time.time()
|
||||
R = build(preset_misspec(cfg, name))
|
||||
builds[name] = R
|
||||
results["presets"][name] = {"spec": cfg["misspec_presets"][name]} | qc_preset(R, R0, reg, reg["wavelet_ms"])
|
||||
results["presets"][name]["time_s"] = time.time() - t1
|
||||
r = results["presets"][name]
|
||||
print(f"{name:6s} seis change {r['seis_rel_change_main']:.3f} | model error nominal-wavelet {r['model_err_nominal_wavelet']['err_mean']:.3f} "
|
||||
f"({r['model_err_nominal_wavelet']['snr_equiv_db']:.1f} dB), in-family {r['model_err_in_family']['err_mean']:.3f} "
|
||||
f"({r['model_err_in_family']['snr_equiv_db']:.1f} dB, phase {r['model_err_in_family']['phase_deg']:.0f}°) | {r['time_s']:.1f} s", flush=True)
|
||||
results["meta"] = {
|
||||
"created": dt.datetime.now().isoformat(timespec="seconds"), "rid": a.rid, "c": C, "sigma_a_ms": SIGMA_A,
|
||||
"wells": "16 pool wells (train pool); Laplace tie on the first 4", "snr": "clean seismic (snr_db = None)",
|
||||
"config": {"path": a.config, "sha256": sha256(REPO_ROOT / a.config)},
|
||||
"inputs": {k: {"path": P["inputs"][k]["path"], "sha256": sha256(REPO_ROOT / P["inputs"][k]["path"])} for k in ("warp_prior", "wavelet")},
|
||||
"registration": {"from": a.reg_from, **{k: reg[k] for k in ("sigma_a_ms", "sigma_b_ms", "hyperprior", "wavelet_ms", "g_max")}},
|
||||
"noise_rel_rms": NOISE_REL, "noise_snr_equiv_db": {k: snr_db(v) for k, v in NOISE_REL.items()},
|
||||
"env": {"numpy": np.__version__, "scipy": scipy.__version__, "python": platform.python_version()},
|
||||
"time_s": time.time() - t0,
|
||||
}
|
||||
(out / "generator_qc.json").write_text(json.dumps(results, indent=1) + "\n")
|
||||
make_figure(R0, builds, results, out / "generator_qc.png")
|
||||
if a.sweep:
|
||||
run_sweep(build, R0, reg, out)
|
||||
print(f"nominal: model error nominal-wavelet {e_nom.mean():.3f}, in-family {results['nominal']['model_err_in_family']['err_mean']:.3f} "
|
||||
f"({results['nominal']['model_err_in_family']['snr_equiv_db']:.1f} dB); Laplace N=4 warp RMSE "
|
||||
f"{results['nominal']['laplace_tie_N4']['warp_rmse_ms_mean']:.2f} ms; total {time.time() - t0:.0f} s → {out}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
86
scripts/34_run_bench.py
Normal file
86
scripts/34_run_bench.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""protocol_bench runner (configs/protocol_bench.yaml): status | lock | posterior | train | summarize | repro | dev-budgets.
|
||||
|
||||
python scripts/34_run_bench.py lock # first lock (refuses if results exist)
|
||||
python scripts/34_run_bench.py posterior --studies S1 S2 --device cuda:0 --workers 4 --gpu-mem-gb 6
|
||||
python scripts/34_run_bench.py train --studies S1 S2 S3 S4 S8 --device cuda:1 --workers 4
|
||||
python scripts/34_run_bench.py summarize # outputs/bench/summary/
|
||||
python scripts/34_run_bench.py repro --device cuda:0 # P2r reproduction cell → outputs/bench/repro/
|
||||
python scripts/34_run_bench.py posterior train --dev --rids 902 903 --studies S2 --presets rp_L1 ... # dev only
|
||||
python scripts/34_run_bench.py dev-budgets --device cuda:0 # TCN budgets on dev 902–905 (R10, c = 1)
|
||||
|
||||
Main realizations 8–15 run only after the lock; --dev restricts to realizations 900–905 and writes under
|
||||
outputs/bench/dev; repro writes under outputs/bench/repro. --regimes / --presets / --rids filter the planned cells
|
||||
(a partial run is resumed, never a different design). Threads default to 2 per worker (OMP/MKL/OPENBLAS).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
|
||||
for _k, _v in {"OMP_NUM_THREADS": "2", "MKL_NUM_THREADS": "2", "OPENBLAS_NUM_THREADS": "2", "NUMEXPR_NUM_THREADS": "2",
|
||||
"NUMBA_NUM_THREADS": "2", "PYTHONHASHSEED": "0", "PYTHONUTF8": "1", "CUBLAS_WORKSPACE_CONFIG": ":4096:8"}.items():
|
||||
os.environ.setdefault(_k, _v)
|
||||
|
||||
STAGES = ["status", "lock", "posterior", "train", "summarize", "repro", "dev-budgets", "all"]
|
||||
|
||||
|
||||
def main() -> None:
|
||||
from ml_porosity.benchmark.cells import bench_root
|
||||
from ml_porosity.benchmark.protocol import freeze, load_protocol
|
||||
from ml_porosity.benchmark.runner import run, status
|
||||
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("stages", nargs="+", choices=STAGES)
|
||||
ap.add_argument("--studies", nargs="+", default=["S1", "S2", "S3", "S4", "S8"], choices=["S1", "S2", "S3", "S4", "S8"])
|
||||
ap.add_argument("--device", default="cuda:0")
|
||||
ap.add_argument("--workers", type=int, default=4)
|
||||
ap.add_argument("--threads", type=int, default=int(os.environ.get("THREADS", "2")))
|
||||
ap.add_argument("--gpu-mem-gb", type=float, default=6.0, help="per-worker CUDA allocation cap for the SMC (GiB)")
|
||||
ap.add_argument("--dev", action="store_true", help="dev realizations only → outputs/bench/dev")
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=None)
|
||||
ap.add_argument("--regimes", nargs="+", default=None)
|
||||
ap.add_argument("--presets", nargs="+", default=None, help="S2 presets to run (default: all main presets)")
|
||||
ap.add_argument("--controls", action="store_true", help="S2: also the control presets rp_C, wv_C")
|
||||
ap.add_argument("--seeds", type=int, nargs="+", default=None, help="dev only: network seeds (default: protocol)")
|
||||
ap.add_argument("--drift", type=float, nargs="+", default=None, help="dev only: drift factors c (overrides the study grid)")
|
||||
ap.add_argument("--n-train", type=int, nargs="+", default=None, help="dev only: N (overrides the study grid)")
|
||||
ap.add_argument("--n-boot", type=int, default=2000)
|
||||
args = ap.parse_args()
|
||||
if args.workers < 1:
|
||||
ap.error("--workers must be positive")
|
||||
if (args.seeds or args.drift or args.n_train) and not args.dev:
|
||||
ap.error("--seeds, --drift and --n-train are dev options")
|
||||
grid = {"drift_factors": args.drift, "n_train": args.n_train} if (args.drift or args.n_train) else None
|
||||
p = load_protocol()
|
||||
mode = "dev" if args.dev else "main"
|
||||
stages = ["posterior", "train", "summarize"] if args.stages == ["all"] else args.stages
|
||||
try:
|
||||
for stage in stages:
|
||||
if stage == "status":
|
||||
print(status(bench_root(dev=args.dev)))
|
||||
elif stage == "lock":
|
||||
print(freeze())
|
||||
elif stage in ("posterior", "train"):
|
||||
run(stage, p, args.studies, args.device, args.workers, args.gpu_mem_gb, args.threads, mode, rids=args.rids,
|
||||
regimes=args.regimes, presets=args.presets, controls=args.controls, seeds=args.seeds, grid=grid)
|
||||
elif stage == "repro":
|
||||
from ml_porosity.benchmark.repro import compare
|
||||
for st in ("posterior", "train"):
|
||||
run(st, p, [], args.device, 1, args.gpu_mem_gb, args.threads, "repro")
|
||||
print(compare(p))
|
||||
elif stage == "summarize":
|
||||
from ml_porosity.benchmark.summary import summarize
|
||||
summarize(p, bench_root(dev=args.dev), args.n_boot, dev=args.dev)
|
||||
elif stage == "dev-budgets":
|
||||
from ml_porosity.benchmark.devbudgets import dev_budgets
|
||||
print(dev_budgets(p, args.device, args.workers, args.gpu_mem_gb, args.threads, rids=args.rids))
|
||||
except Exception:
|
||||
traceback.print_exc()
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
135
scripts/35_bench_calibration.py
Normal file
135
scripts/35_bench_calibration.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""S2 level calibration table (phase P6, protocol_bench): tabulate the dev SMC diagnostics of every candidate preset.
|
||||
|
||||
CUDA_VISIBLE_DEVICES= .venv/bin/python scripts/35_bench_calibration.py [--rids 902 903 904 905] [--out outputs/bench/dev]
|
||||
|
||||
Reads outputs/bench/dev/smc_qc_rid<rid>.json (scripts/33 --smc: N = 4, c = 1, R10 and Rm5, P = 1024, estR, γ = 1/κ,
|
||||
single-checkpoint SMC) and outputs/bench/dev/generator_qc.json / generator_sweep.json (in-family model error), and
|
||||
writes calibration.csv (one row per preset × regime, mean over the listed realizations and wells) and calibration.md.
|
||||
Columns: in-family model error (relative RMS; ratio to the regime noise), SMC warp RMSE, coverage90, σ_post
|
||||
(width90/3.29), overconfidence (warp RMSE / σ_post), phase_R, |phase_R − phase0|, B3c and B3d warp RMSE, r_post,
|
||||
and the declared L1/L2 targets of configs/protocol_bench.yaml calibration.procedure. Dev only; no main realization.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
import yaml
|
||||
|
||||
from ml_porosity.paths import REPO_ROOT
|
||||
|
||||
NOISE = {"R10": 10 ** (-10 / 20), "Rm5": 10 ** (5 / 20), "R0": 1.0} # relative noise RMS of the regimes
|
||||
Z90 = 3.29
|
||||
|
||||
|
||||
def in_family_errors(out: Path) -> dict[str, float]:
|
||||
"""Best in-family model error keyed by the json of the active knobs (generator_qc.json presets, the nominal entry
|
||||
and the single-knob rows of generator_sweep.json when they carry a spec/active block)."""
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec
|
||||
|
||||
err = {}
|
||||
f = out / "generator_qc.json"
|
||||
if f.exists():
|
||||
q = json.loads(f.read_text())
|
||||
err["{}"] = float(q["nominal"]["model_err_in_family"]["err_mean"])
|
||||
for d in q.get("presets", {}).values():
|
||||
if "active" in d and "model_err_in_family" in d:
|
||||
err[json.dumps(d["active"], sort_keys=True)] = float(d["model_err_in_family"]["err_mean"])
|
||||
f = out / "generator_sweep.json"
|
||||
if f.exists():
|
||||
for r in json.loads(f.read_text()).get("rows", []):
|
||||
if "model_err_in_family" not in r:
|
||||
continue
|
||||
act = r.get("active")
|
||||
if act is None and "spec" in r:
|
||||
act = active_axes(normalize_misspec({k: v for k, v in r["spec"].items() if k != "note"}))
|
||||
if act is None and {"axis", "key", "value"} <= set(r):
|
||||
act = active_axes(normalize_misspec({r["axis"]: {r["key"]: r["value"]}}))
|
||||
if act is not None:
|
||||
e = r["model_err_in_family"]
|
||||
err.setdefault(json.dumps(act, sort_keys=True), float(e["err_mean"] if isinstance(e, dict) else e))
|
||||
return err
|
||||
|
||||
|
||||
def load_smc(out: Path, rids: list[int]) -> pd.DataFrame:
|
||||
rows = []
|
||||
for rid in rids:
|
||||
f = out / f"smc_qc_rid{rid}.json"
|
||||
if not f.exists():
|
||||
continue
|
||||
q = json.loads(f.read_text())
|
||||
for regime, presets in q.items():
|
||||
if regime == "meta":
|
||||
continue
|
||||
for name, r in presets.items():
|
||||
m = r["mean"]
|
||||
rows.append({"rid": rid, "regime": regime, "preset": name, "phase0": r["phase0"], "phase_R": r["phase_R"],
|
||||
"dphase": abs(r["phase_R"] - r["phase0"]), "phase_edge": r["phase_edge"],
|
||||
"smc_warp_rmse_ms": m["SMC_warp_rmse_ms"], "cov90": m["SMC_warp_cov90"],
|
||||
"sigma_post_ms": m["SMC_warp_width90_ms"] / Z90, "r_post": m["r_post"], "kappa_post": m["kappa_post"],
|
||||
"b3c_warp_rmse_ms": m["B3c_warp_rmse_ms"], "b3d_warp_rmse_ms": m["B3d_warp_rmse_ms"],
|
||||
"lam": r["lam"], "time_s": sum(r["time_s"].values()), "active": json.dumps(r.get("active", {}), sort_keys=True)})
|
||||
return pd.DataFrame(rows)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--rids", type=int, nargs="+", default=[902, 903, 904, 905])
|
||||
ap.add_argument("--out", type=Path, default=REPO_ROOT / "outputs" / "bench" / "dev")
|
||||
a = ap.parse_args()
|
||||
if any(r < 900 for r in a.rids):
|
||||
raise SystemExit("dev realizations only")
|
||||
df = load_smc(a.out, a.rids)
|
||||
if df.empty:
|
||||
raise SystemExit("no smc_qc_rid*.json found")
|
||||
err = in_family_errors(a.out)
|
||||
cfg = yaml.safe_load((REPO_ROOT / "configs" / "d2_synth_bench.yaml").read_text())
|
||||
presets = cfg["misspec_presets"]
|
||||
# Rows are identified by their active knobs, not by the name stored in the json: preset names were redefined on
|
||||
# 29/10 (e.g. wv_L1 was minphase 1.0 on rid 902 and is minphase 0.5 now). Main-preset names win, then cand_*.
|
||||
from ml_porosity.data.synth_d2 import active_axes, normalize_misspec, preset_misspec
|
||||
main = [n for n in presets if not n.startswith("cand_")]
|
||||
by_active = {}
|
||||
for n in main + [n for n in presets if n.startswith("cand_")]:
|
||||
by_active.setdefault(json.dumps(active_axes(normalize_misspec(preset_misspec(cfg, n))), sort_keys=True), n)
|
||||
df["stored_name"] = df.preset
|
||||
df["preset"] = [("nominal" if a == "{}" else by_active.get(a, f"{n} (old definition)")) for a, n in zip(df.active, df.stored_name)]
|
||||
df = df.drop_duplicates(["rid", "regime", "active"]) # the same knobs run twice on one rid under two names
|
||||
df["overconfidence"] = df.smc_warp_rmse_ms / df.sigma_post_ms
|
||||
nom = df[df.preset == "nominal"].set_index(["rid", "regime"])
|
||||
df = df.join(nom[["smc_warp_rmse_ms", "cov90", "sigma_post_ms"]].rename(columns=lambda c: c + "_nom"), on=["rid", "regime"])
|
||||
df["warp_rmse_ratio_to_nominal"] = df.smc_warp_rmse_ms / df.smc_warp_rmse_ms_nom
|
||||
df["smc_beats_b3c"] = df.smc_warp_rmse_ms < df.b3c_warp_rmse_ms
|
||||
agg = df.groupby(["preset", "regime", "active"]).agg(n_rid=("rid", "nunique"), smc_warp_rmse_ms=("smc_warp_rmse_ms", "mean"),
|
||||
ratio_to_nominal=("warp_rmse_ratio_to_nominal", "mean"), cov90=("cov90", "mean"),
|
||||
sigma_post_ms=("sigma_post_ms", "mean"), overconfidence=("overconfidence", "mean"),
|
||||
dphase_deg=("dphase", "mean"), phase_R=("phase_R", "mean"),
|
||||
b3c_warp_rmse_ms=("b3c_warp_rmse_ms", "mean"), b3d_warp_rmse_ms=("b3d_warp_rmse_ms", "mean"),
|
||||
smc_beats_b3c_frac=("smc_beats_b3c", "mean"), r_post=("r_post", "mean"),
|
||||
time_s=("time_s", "mean")).reset_index()
|
||||
agg["in_family_err"] = agg.active.map(lambda a: err.get(a, np.nan))
|
||||
agg["err_over_noise"] = agg.in_family_err / agg.regime.map(NOISE)
|
||||
agg["note"] = agg.preset.map(lambda n: presets.get(n, {}).get("note", "nominal" if n == "nominal" else ""))
|
||||
agg["axis"] = agg.preset.map(lambda n: "nominal" if n == "nominal" else next((p for p in n.split("_") if p in ("rp", "wv", "dr")), "?"))
|
||||
agg = agg.sort_values(["regime", "axis", "preset"]).reset_index(drop=True)
|
||||
agg.to_csv(a.out / "calibration.csv", index=False)
|
||||
cols = ["regime", "axis", "preset", "active", "n_rid", "in_family_err", "err_over_noise", "smc_warp_rmse_ms", "ratio_to_nominal", "cov90",
|
||||
"sigma_post_ms", "overconfidence", "dphase_deg", "b3c_warp_rmse_ms", "smc_beats_b3c_frac", "r_post"]
|
||||
L = ["# S2 level calibration (dev; N = 4, c = 1, P = 1024, estR, γ = 1/κ; single-checkpoint SMC of scripts/33)", "",
|
||||
f"Realizations: {sorted(df.rid.unique().tolist())}. Means over realizations × 4 train wells. in_family_err from generator_qc.json "
|
||||
"(rid 902; NaN for presets without a light-QC entry). Declared targets (protocol calibration.procedure): L1 — err/noise(R10) "
|
||||
"0.5–1.0 and SMC still ahead of B3c at R10; L2 — err/noise(R10) 1.5–2 with coverage90 < 0.5 at R10 or warp RMSE ≥ 2 × nominal.", "",
|
||||
agg[cols].to_markdown(index=False, floatfmt=".3f"), "", "## Per realization", "",
|
||||
df[["rid", "regime", "preset", "stored_name", "smc_warp_rmse_ms", "cov90", "sigma_post_ms", "dphase", "b3c_warp_rmse_ms", "r_post"]]
|
||||
.sort_values(["regime", "preset", "rid"]).to_markdown(index=False, floatfmt=".3f"), ""]
|
||||
(a.out / "calibration.md").write_text("\n".join(L))
|
||||
pd.set_option("display.width", 250)
|
||||
print(agg[cols].round(3).to_string())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
41
scripts/run_bench.sh
Executable file
41
scripts/run_bench.sh
Executable file
@@ -0,0 +1,41 @@
|
||||
#!/usr/bin/env bash
|
||||
# protocol_bench (configs/protocol_bench.yaml) driver on the Linux GPU server: every stage is wrapped by
|
||||
# ml_porosity.runlog (logs/runs/<ts>_bench_<stage>/, logs/index.csv) and is restartable (completed jobs are skipped
|
||||
# by fingerprint and checksum). Long runs: detach with `setsid nohup scripts/run_bench.sh ... > logs/bench_<x>.out 2>&1 &`.
|
||||
# scripts/run_bench.sh lock # first lock (after the review of the draft)
|
||||
# STUDIES="S1" DEVICE=cuda:0 WORKERS=4 scripts/run_bench.sh posterior train
|
||||
# STUDIES="S3 S4 S8" DEVICE=cuda:1 scripts/run_bench.sh train
|
||||
# scripts/run_bench.sh summarize | status | repro
|
||||
# DEV=1 RIDS="902 903" STUDIES="S2" PRESETS="rp_L1 wv_L1" scripts/run_bench.sh posterior train # dev (never a result)
|
||||
# Env: DEVICE (default cuda:0), WORKERS (4), THREADS per worker (2), MEM_GB per SMC worker (6), STUDIES, REGIMES,
|
||||
# PRESETS, RIDS, DEV (1 → --dev), CONTROLS (1 → S2 controls), EXTRA (extra arguments).
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
PY="${PY:-.venv/bin/python}"
|
||||
DEVICE="${DEVICE:-cuda:0}"
|
||||
WORKERS="${WORKERS:-4}"
|
||||
THREADS="${THREADS:-2}"
|
||||
MEM_GB="${MEM_GB:-6}"
|
||||
STUDIES="${STUDIES:-S1 S2 S3 S4 S8}"
|
||||
export OMP_NUM_THREADS=$THREADS MKL_NUM_THREADS=$THREADS OPENBLAS_NUM_THREADS=$THREADS NUMEXPR_NUM_THREADS=$THREADS \
|
||||
NUMBA_NUM_THREADS=$THREADS PYTHONHASHSEED=0 PYTHONUTF8=1 CUBLAS_WORKSPACE_CONFIG=:4096:8
|
||||
args=(--device "$DEVICE" --workers "$WORKERS" --threads "$THREADS" --gpu-mem-gb "$MEM_GB")
|
||||
# shellcheck disable=SC2206
|
||||
args+=(--studies $STUDIES)
|
||||
[[ -n "${REGIMES:-}" ]] && args+=(--regimes $REGIMES)
|
||||
[[ -n "${PRESETS:-}" ]] && args+=(--presets $PRESETS)
|
||||
[[ -n "${RIDS:-}" ]] && args+=(--rids $RIDS)
|
||||
[[ "${DEV:-0}" == "1" ]] && args+=(--dev)
|
||||
[[ "${CONTROLS:-0}" == "1" ]] && args+=(--controls)
|
||||
[[ -n "${EXTRA:-}" ]] && args+=($EXTRA)
|
||||
tag="$(echo "$STUDIES" | tr ' ' '+')"
|
||||
[[ "${DEV:-0}" == "1" ]] && tag="dev_$tag"
|
||||
for stage in "${@:-status}"; do
|
||||
case "$stage" in
|
||||
status|lock|summarize|repro)
|
||||
"$PY" -m ml_porosity.runlog -n "bench_${stage}" -- "$PY" scripts/34_run_bench.py "$stage" "${args[@]}" ;;
|
||||
posterior|train|dev-budgets)
|
||||
"$PY" -m ml_porosity.runlog -n "bench_${stage}_${tag}_${DEVICE//:/}" -- "$PY" scripts/34_run_bench.py "$stage" "${args[@]}" ;;
|
||||
*) echo "unknown stage: $stage" >&2; exit 2 ;;
|
||||
esac
|
||||
done
|
||||
Reference in New Issue
Block a user