P2 diagnosis on dev, P3 dev experiments, lock protocol_p3

- P2: SMC tie posterior (numpy + torch), RML/soft-DTW losses, bank training,
  D2 synthetic generator, scripts 09-13, protocol_p2 (locked) and its outcome
  (G-B failed; H1 not rejected, H3 rejected, H4 not rejected).
- Diagnosis on dev realizations 900/901 only (scripts 14-17, run_p3_dev.sh):
  posterior screen, SMC stability (P = 1024, K = 1), sigma_a misspecification
  stress and training, H3 with the SMC posterior, F3 placement on sigma_post.
- protocol_p3: H2 split into H2a (posterior-mean labels vs point ties) and
  H2b (RML vs posterior mean as a function of sigma_post); H3 descriptive only;
  sigma_a arm; new D2 config d2_synth_p3.yaml; main grid on realizations 8-15.
  Locked by configs/protocol_p3.sha256 and tag protocol-p3.
- runlog: per-run logs and runtime index (logs/index.csv).
- Docs: plan §12 items 10-11, theory, technical overview, report; wording
  aligned with Gunning & Glinsky (2006): the tie posterior is not claimed as new.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-27 06:03:33 +00:00
parent a76e61398a
commit cee2ff0859
84 changed files with 8793 additions and 460 deletions

View File

@@ -0,0 +1,103 @@
"""Fit the GP warp prior (plan §4.1) on the F3 anchors and run a leave-one-anchor-out check (§5.4).
python scripts/09_fit_warp_prior_f3.py
τ = integrated DT passing through the first TD marker (as for the base of the calibrated TDR); anchors = TD markers
in the extended 400–1300 ms window; d_k = t_k − τ_k. Type-II ML fit on all 4 wells (used to calibrate the D2 drift)
and on each LOWO fold (3 train wells). Outputs: outputs/p2/warp_prior_f3.json, figures/p2_f3_drift.png.
"""
from __future__ import annotations
import json
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
import yaml
from ml_porosity.data.las_io import load_well
from ml_porosity.data.tdr import sonic_tdr
from ml_porosity.paths import REPO_ROOT, outputs_dir
from ml_porosity.registration.warp_prior import (WarpGrid, WarpHyper, fit_hyper, linear_posterior,
loao_zscores)
TAU_RANGE = (300.0, 1400.0)
def f3_anchor_wells(cfg: dict) -> list[dict]:
e0, e1 = cfg["ext_window_ms"]
out = []
for name in cfg["wells"]:
w = load_well(name)
cs = w.checkshot
base = sonic_tdr(w.md, w.curve("DT"), md0=cs.md.iloc[0], t0_ms=cs.twt_ms.iloc[0])
tk = cs.twt_ms.to_numpy()
tau = base.time_at(cs.md.to_numpy())
m = (tk >= e0) & (tk <= e1)
out.append({"name": name, "grid": WarpGrid(*TAU_RANGE, 4.0), "tau_k": tau[m], "d_k": tk[m] - tau[m]})
return out
def z_summary(z: np.ndarray) -> dict:
return {"n": int(len(z)), "mean_z2": round(float(np.mean(z**2)), 3),
"coverage_90": round(float(np.mean(np.abs(z) < 1.6449)), 3),
"max_abs_z": round(float(np.max(np.abs(z))), 2)}
def main() -> None:
cfg = yaml.safe_load(open(REPO_ROOT / "configs" / "d1_f3.yaml"))
wells = f3_anchor_wells(cfg)
# The "tau" and "note" strings below are written verbatim into warp_prior_f3.json, whose SHA-256 is locked in
# protocol_p2/protocol_p3; they are deliberately left untranslated so that a re-run reproduces the locked file.
res = {"tau": "sonic_tdr qua marker TD đầu tiên", "anchors_window_ms": cfg["ext_window_ms"],
"tau_range_ms": TAU_RANGE, "n_anchors": {w["name"]: int(len(w["tau_k"])) for w in wells}, "fits": {}}
for kern in ["matern32", "se"]:
h, info = fit_hyper(wells, WarpHyper(kernel=kern), n_starts=8)
z = loao_zscores(wells, h)
folds = {}
for i, w in enumerate(wells):
hi, _ = fit_hyper([v for j, v in enumerate(wells) if j != i], WarpHyper(kernel=kern), n_starts=6)
zi = loao_zscores([w], hi)[0]
folds[w["name"]] = {"hyper": hi.as_dict(), "loao_test_well": z_summary(zi)}
res["fits"][kern] = {"hyper": h.as_dict(), "log_marginal": round(info["log_marginal"], 3),
"at_bound": info["at_bound"],
"loao": z_summary(np.concatenate(z)) | {"per_well": {w["name"]: z_summary(zw) for w, zw in zip(wells, z)}},
"lowo_folds": folds}
print(kern, h, "logML", round(info["log_marginal"], 2), "LOAO", z_summary(np.concatenate(z)))
best = max(res["fits"], key=lambda k: res["fits"][k]["log_marginal"])
res["selected_kernel"] = "matern32"
res["note"] = ("Chọn Matérn-3/2 (chốt trước trong configs/d2_synth.yaml) — log-marginal hai kernel chênh "
f"{abs(res['fits']['matern32']['log_marginal'] - res['fits']['se']['log_marginal']):.2f} "
f"(cao hơn: {best}).")
out = outputs_dir() / "p2"
out.mkdir(parents=True, exist_ok=True)
(out / "warp_prior_f3.json").write_text(json.dumps(res, indent=2, ensure_ascii=False))
h = WarpHyper(**res["fits"]["matern32"]["hyper"])
fig, axes = plt.subplots(1, 4, figsize=(14, 4), sharey=True)
for ax, w in zip(axes, wells):
grid = w["grid"]
mu, S = linear_posterior(grid, h, w["tau_k"], w["d_k"])
A = grid.anchor_operator(grid.tau)
m = A @ mu
sd = np.sqrt(np.einsum("ij,jk,ik->i", A, S, A))
ax.fill_between(grid.tau, m - 2 * sd, m + 2 * sd, color="C0", alpha=0.25, label="±2σ posterior")
ax.plot(grid.tau, m, "C0", label="posterior mean")
ax.plot(w["tau_k"], w["d_k"], "ko", ms=3, label="anchor")
ax.set_title(w["name"])
ax.set_xlabel("τ sonic (ms)")
ax.set_xlim(380, 1320)
axes[0].set_ylabel("t − τ (ms)")
axes[0].legend(fontsize=7)
fig.suptitle(f"F3 drift under the GP prior (Matérn-3/2, σ_g={h.sigma_g:.3f}, ℓ={h.ell_ms:.0f} ms, σ_a={h.sigma_a_ms:.2f} ms)")
fig.tight_layout()
(outputs_dir() / "figures").mkdir(exist_ok=True)
fig.savefig(outputs_dir() / "figures" / "p2_f3_drift.png", dpi=130)
print("→", out / "warp_prior_f3.json")
if __name__ == "__main__":
main()