"""QC of D2 against F3 (plan §5.1, §5.5): label, anchor and drift statistics; figure of one example well. Labels on the extended 400–1300 ms window, 4 ms grid. F3: calibrated PHIE_DT of the 4 wells (linear in DT). D2: anti-aliased φ of the central trace in true time, all wells (8 test + 16 pool) of the main realizations. Per-well statistics: residual std after a linear trend, std of the > 6 Hz band, τ_c (rml.effective_lambda), PSD slope over 10–80 Hz (log–log, Hann periodogram of the residual). Drift: max − min range of t − τ at the anchors in the extended window (F3: TD markers as in scripts/09; D2: true warp at unit boundaries, no pick noise) and anchors per well. python scripts/10_build_d2.py → outputs/d2/qc.json, outputs/figures/p2_d2_qc.png """ from __future__ import annotations import importlib.util import json import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt import numpy as np import yaml from scipy import signal from ml_porosity.data.synth_d2 import D2Realization, load_horizon_grid from ml_porosity.eval import figstyle as fs from ml_porosity.eval.metrics import split_bands from ml_porosity.losses.rml import effective_lambda from ml_porosity.paths import REPO_ROOT, outputs_dir from ml_porosity.registration.labels import antialias from ml_porosity.registration.warp_prior import WarpHyper STATS = {"resid_std": "residual std (linear trend)", "band_std": "std of > 6 Hz band", "tau_c": "τ_c (samples)", "psd_slope": "PSD slope 10–80 Hz"} def label_stats(y: np.ndarray, dt: float = 4.0, f_c: float = 6.0) -> dict: k = np.arange(len(y)) res = y - np.polyval(np.polyfit(k, y, 1), k) f, P = signal.periodogram(res, fs=1000.0 / dt, window="hann") m = (f >= 10) & (f <= 80) return {"resid_std": float(res.std()), "band_std": float(split_bands(y, f_c, dt)[1].std()), "tau_c": effective_lambda([y], f_c, dt)[1], "psd_slope": float(np.polyfit(np.log10(f[m]), np.log10(P[m]), 1)[0])} def summary(v) -> dict: v = np.asarray(v, dtype=float) return {"n": int(len(v)), "median": float(np.median(v)), "q05": float(np.quantile(v, 0.05)), "q95": float(np.quantile(v, 0.95)), "min": float(v.min()), "max": float(v.max())} def f3_side() -> dict: spec = importlib.util.spec_from_file_location("fit09", REPO_ROOT / "scripts" / "09_fit_warp_prior_f3.py") fit09 = importlib.util.module_from_spec(spec) spec.loader.exec_module(fit09) cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml")) z = np.load(outputs_dir() / "f3_wells.npz", allow_pickle=True) out = {} for w in fit09.f3_anchor_wells(cfg): y = z[f"{w['name']}/calibrated/PHIE_DT"].astype(float) out[w["name"]] = label_stats(y) | {"n_anchors": int(len(w["tau_k"])), "drift_range_ms": float(np.ptp(w["d_k"]))} return out def main() -> None: P = yaml.safe_load(open(REPO_ROOT / "configs" / "protocol_p2.yaml")) cfg = yaml.safe_load(open(REPO_ROOT / P["inputs"]["d2_config"]["path"])) 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"]] drift = WarpHyper(**prior["hyper"]) cs = [c for c in P["grid"]["drift_factors"] if c > 0] sa, f = cfg["anchors"]["sigma_a_ms"], cfg["fine_dt_ms"] d2 = {k: [] for k in STATS} | {"n_anchors": [], **{f"drift_range_ms_c{c:g}": [] for c in cs}, **{f"max_abs_g_c{c:g}": [] for c in cs}} example = None for rid in P["grid"]["realizations"]: R = D2Realization(cfg, rid, hg, drift, wav) win = (R.grid.tau >= R.t_ext[0]) & (R.grid.tau <= R.t_ext[-1]) for w in R.wells: y = np.interp(R.t_ext, R.t_fine, antialias(w.phi_t, f, R.dt)) for k, v in label_stats(y).items(): d2[k].append(v) for c in cs: o = R.observe(w, c, P["grid"]["snr_db"], sa) d2[f"drift_range_ms_c{c:g}"].append(float(np.ptp(w.boundaries_t - o["tau_k"]))) d2[f"max_abs_g_c{c:g}"].append(float(np.abs(o["g"][win]).max())) d2["n_anchors"].append(len(w.boundaries_t)) if example is None: w = R.pool[0] example = {"R": R, "w": w, "obs": {c: R.observe(w, c, P["grid"]["snr_db"], sa) for c in cs}} print(f"realization {rid}: {len(R.wells)} wells", flush=True) f3 = f3_side() qc = {"window_ms": cfg["ext_window_ms"], "realizations": P["grid"]["realizations"], "d2": {k: summary(v) for k, v in d2.items()}, "f3": f3, "f3_range": {k: [min(w[k] for w in f3.values()), max(w[k] for w in f3.values())] for k in list(STATS) + ["n_anchors", "drift_range_ms"]}} out = outputs_dir() / "d2" out.mkdir(parents=True, exist_ok=True) (out / "qc.json").write_text(json.dumps(qc, indent=1, ensure_ascii=False)) for k in list(STATS) + ["n_anchors"]: s = qc["d2"][k] print(f"{k:12s} D2 median {s['median']:.4g} [5–95%: {s['q05']:.4g}, {s['q95']:.4g}] F3 {qc['f3_range'][k]}") for c in cs: s = qc["d2"][f"drift_range_ms_c{c:g}"] print(f"drift c={c:g}: D2 median {s['median']:.1f} ms [{s['q05']:.1f}, {s['q95']:.1f}] F3 {qc['f3_range']['drift_range_ms']}") plot(example, d2, f3, cs, outputs_dir() / "figures" / "p2_d2_qc.png") def plot(ex, d2, f3, cs, path) -> None: fs.apply() R, w, obs = ex["R"], ex["w"], ex["obs"] fig = plt.figure(figsize=(12, 6.4)) gs = fig.add_gridspec(2, 4, height_ratios=[1.15, 1], hspace=0.55, wspace=0.35) ax = fig.add_subplot(gs[0, :2]) m = (R.t_fine >= R.t_ext[0]) & (R.t_fine <= R.t_ext[-1]) o1 = obs[1.0] if 1.0 in obs else obs[cs[0]] ax.plot(R.t_fine[m], 100 * w.phi_t[m], color=fs.INK, lw=1.0, label="true φ in t") sel = (o1["tau_fine"] >= R.t_ext[0]) & (o1["tau_fine"] <= R.t_ext[-1]) ax.plot(o1["tau_fine"][sel], 100 * o1["phi_log"][sel], color=fs.ORANGE, lw=1.0, label="log placed at τ (no tie, c = 1)") ax.axvspan(*R.t_main[[0, -1]], color=fs.GRID, alpha=0.5, lw=0) ax.text(R.t_main[0] + 5, ax.get_ylim()[1], "main window", va="top", fontsize=8, color=fs.INK2) ax.set(xlabel="time (ms)", ylabel="φ (p.u.)", title=f"(a) Example well {w.name}, realization {R.rid}") ax.legend(loc="lower left") ax = fig.add_subplot(gs[0, 2]) gt = R.grid.tau for c, col in zip(cs, fs.ORDINAL_BLUE): o = obs[c] dd = np.interp(gt, o["tau_fine"], o["t_of_tau_true"]) - gt k = (gt >= R.t_ext[0]) & (gt <= R.t_ext[-1]) ax.plot(gt[k], dd[k], color=col, lw=1.5) ax.annotate(f"c = {c:g}", (gt[k][-1], dd[k][-1]), xytext=(3, 0), textcoords="offset points", va="center", fontsize=8, color=fs.INK2) ax.plot(o1["tau_k"], o1["t_k"] - o1["tau_k"], "o", ms=4, mfc=fs.SURFACE, mec=fs.INK, mew=1.0, label="anchor (c = 1, σ_a = 7 ms)") ax.set(xlabel="τ sonic (ms)", ylabel="t − τ (ms)", title="(b) True warp and anchors") ax.set_xlim(R.t_ext[0], R.t_ext[-1] + 120) lo, hi = ax.get_ylim() ax.set_ylim(lo, hi + 0.25 * (hi - lo)) ax.legend(loc="upper left") ax = fig.add_subplot(gs[0, 3]) mid = w.seis_clean.shape[0] // 2 ax.plot(R.t_ext, o1["seis"][mid], color=fs.INK, lw=0.9, label="SNR 10 dB") ax.plot(R.t_ext, w.seis_clean[mid], color=fs.BLUE, lw=0.9, label="noise-free") ax.set(xlabel="time (ms)", title="(c) Central seismic trace", yticks=[]) ax.legend(loc="lower left") rng = np.random.default_rng(0) for j, (k, lab) in enumerate(STATS.items()): ax = fig.add_subplot(gs[1, j]) v = np.asarray(d2[k]) x = rng.uniform(-0.18, 0.18, len(v)) ax.plot(x, v, "o", ms=2.5, color=fs.BLUE, alpha=0.35, mec="none") q = np.quantile(v, [0.05, 0.5, 0.95]) ax.plot([0.28, 0.28], q[[0, 2]], color=fs.INK2, lw=1.2) ax.plot([0.22, 0.34], [q[1], q[1]], color=fs.INK2, lw=1.2) fv = [f3[n][k] for n in f3] ax.plot(np.full(len(fv), 1.0), fv, "D", ms=6, color=fs.ORANGE, mec=fs.SURFACE, mew=1.0) ax.set_xticks([0, 1], [f"D2 ({len(v)} wells)", "F3 (4 wells)"]) ax.set_xlim(-0.5, 1.5) ax.grid(axis="x", visible=False) ax.set_title(f"({'defg'[j]}) {lab}") fig.suptitle("D2 vs F3: labels over 400–1300 ms (F3: PHIE_DT, linear in DT); D2 shown with median and 5–95% range", x=0.06, ha="left", fontsize=10, color=fs.INK2) path.parent.mkdir(exist_ok=True) fig.savefig(path, dpi=140, bbox_inches="tight") print("→", path) if __name__ == "__main__": main()