Add P6 benchmark code, locked protocol_bench, T2 study and lock inputs

- 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.
- The eight protocol_bench inputs force-added from outputs/ (warp prior,
  wavelets, horizon cache, budgets) so load_protocol() and summarize work
  after a fresh clone. The 102 P2r reference artifacts (1.4 GB of particle
  npz) are not in git; they are only checked by posterior/train stages.
- T2 mechanism declaration and results; operations/p6_supervisor.py.
- Docs, report and paper edits of 29/10.

Main S1 runs are still training at this commit; results follow.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 01:06:59 +00:00
parent 0cfe202a8b
commit f3c30517fa
51 changed files with 6529 additions and 58 deletions

View 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()