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:
122
ml_porosity/registration/pipeline.py
Normal file
122
ml_porosity/registration/pipeline.py
Normal file
@@ -0,0 +1,122 @@
|
||||
"""Registration of the training wells of one D2 cell (plan §4.1–4.3, §5.3).
|
||||
|
||||
Uses training-well data only: warp hyperparameters (MAP-II on the training anchors), statistical wavelet from the
|
||||
centre trace + constant phase maximising the marginal likelihood over the posterior warp samples, posterior warp
|
||||
samples, physical M2 weights, label banks for each method, λ = 1/τ_c, and warp diagnostics against the true warp
|
||||
(for reporting only, not used for selection).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import numpy as np
|
||||
|
||||
from ml_porosity.data.wavelet import rotate_phase, statistical_wavelet
|
||||
from ml_porosity.losses.rml import effective_lambda
|
||||
from ml_porosity.registration.labels import antialias, labels_for_warps
|
||||
from ml_porosity.registration.sampler import ess, sample_warps, temper
|
||||
from ml_porosity.registration.tie_likelihood import fine_wavelet, fit_phase, phase_loglik, synth_for_warps
|
||||
from ml_porosity.registration.ties import tie_b3a, tie_b3b, tie_b3c, warp_errors, warp_mean
|
||||
from ml_porosity.registration.warp_prior import WarpHyper, fit_hyper
|
||||
|
||||
|
||||
def fit_cell_hyper(R, obs: list[dict], reg: dict, seed: int = 0) -> tuple[WarpHyper, dict]:
|
||||
"""MAP-II for (m_g, σ_g, ℓ); σ_a, σ_b fixed; log-normal hyperprior (median, log sd) for σ_g, ℓ."""
|
||||
wells = [{"grid": R.grid, "tau_k": o["tau_k"], "d_k": o["t_k"] - o["tau_k"]} for o in obs]
|
||||
hp = reg["hyperprior"]
|
||||
init = WarpHyper(0.0, hp["sigma_g"][0], hp["ell_ms"][0], reg["sigma_b_ms"], reg["sigma_a_ms"], reg["kernel"])
|
||||
return fit_hyper(wells, init, fixed={"sigma_a_ms": reg["sigma_a_ms"], "sigma_b_ms": reg["sigma_b_ms"]},
|
||||
hyperprior={k: (np.log(m), s) for k, (m, s) in hp.items()}, n_starts=reg["hyper_starts"],
|
||||
seed=seed)
|
||||
|
||||
|
||||
def label_norm(R, obs: list[dict]) -> tuple[float, float]:
|
||||
"""Mean/standard deviation of the (anti-aliased) φ log over τ ∈ main window — independent of the tie,
|
||||
so all methods use the same normalisation."""
|
||||
m0, m1 = R.cfg["main_window_ms"]
|
||||
sel = (R.tau_fine >= m0) & (R.tau_fine <= m1)
|
||||
v = np.concatenate([antialias(o["phi_log"], R.cfg["fine_dt_ms"], R.dt)[sel] for o in obs])
|
||||
return float(v.mean()), float(v.std())
|
||||
|
||||
|
||||
PHASES = np.arange(-180, 180, 15)
|
||||
|
||||
|
||||
def register(R, obs: list[dict], reg: dict, seed: int, prior: WarpHyper | None = None) -> dict:
|
||||
"""prior = None: with anchors; returns banks for Oracle, B3a–d, B4 (±K shift bank), M1, M2.
|
||||
prior given: anchor-free variant (H4) — M1/M2 only, samples from the prior, zero-phase wavelet (the true phase
|
||||
of D2, i.e. favourable to the anchor-free variant).
|
||||
|
||||
banks[m]: (N, S_m, L) labels on t_main; logpi[m]: (N, S_m)."""
|
||||
f = R.cfg["fine_dt_ms"]
|
||||
fac = int(round(R.dt / f))
|
||||
anchors = prior is None
|
||||
seis = [o["seis"][o["seis"].shape[0] // 2].astype(float) for o in obs]
|
||||
w0 = statistical_wavelet(np.stack(seis), R.dt, reg["wavelet_ms"])
|
||||
out = {"wells": [o["name"] for o in obs], "diag": [], "norm": label_norm(R, obs)}
|
||||
if anchors:
|
||||
h, info = fit_cell_hyper(R, obs, reg, seed)
|
||||
out["hyper_info"] = {k: info[k] for k in ("log_marginal", "at_bound")}
|
||||
else:
|
||||
h = prior
|
||||
out["hyper"] = h.as_dict()
|
||||
|
||||
# warp samples, labels and physical log-likelihood per constant phase for every well; one phase per cell
|
||||
lab = lambda y_aa, T, t=R.t_main: labels_for_warps(R.tau_fine, y_aa, np.atleast_2d(T), t)
|
||||
w0_fine = fine_wavelet(w0, fac)
|
||||
T_all, Y_all, ok_all, LL = [], [], [], []
|
||||
for i, o in enumerate(obs):
|
||||
rng = np.random.default_rng([seed, i, 11])
|
||||
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
|
||||
smp = sample_warps(R.grid, h, tk, ttk, reg["S"], reg["g_max"], rng)
|
||||
T = R.grid.t_of_tau(smp["b"], smp["g"], tau=R.tau_fine)
|
||||
Y = lab(antialias(o["phi_log"], f, R.dt), T)
|
||||
ok = np.all(np.isfinite(Y), 1) # valid domain: keep only warps covering the whole main window
|
||||
Y[~ok] = Y[ok][0]
|
||||
T_all.append(T)
|
||||
Y_all.append(Y)
|
||||
ok_all.append(ok)
|
||||
LL.append(phase_loglik(synth_for_warps(R.tau_fine, o["ai_log"], T, R.t_fine, R.t_ext, w0_fine), seis[i], PHASES))
|
||||
k = fit_phase(LL, ok_all, PHASES) if anchors else int(np.flatnonzero(PHASES == 0)[0])
|
||||
out["phase"] = float(PHASES[k])
|
||||
w_fine = fine_wavelet(rotate_phase(w0, PHASES[k]), fac)
|
||||
|
||||
K = reg["shift_K"]
|
||||
t_wide = np.arange(R.t_main[0] - K * R.dt, R.t_main[-1] + K * R.dt + R.dt / 2, R.dt)
|
||||
L = len(R.t_main)
|
||||
names = ["Oracle", "B3a", "B3b", "B3c", "B3d", "B4", "M1", "M2"] if anchors else ["M1", "M2"]
|
||||
banks = {m: [] for m in names}
|
||||
logpi = {"M1": [], "M2": []}
|
||||
for i, o in enumerate(obs):
|
||||
T, Y, ok, ll = T_all[i], Y_all[i], ok_all[i], LL[i][k]
|
||||
tk, ttk = (o["tau_k"], o["t_k"]) if anchors else (np.zeros(0), np.zeros(0))
|
||||
lp2, gam, ess2 = temper(np.where(ok, ll, -np.inf), reg["ess_min_frac"])
|
||||
lp1 = np.where(ok, 0.0, -np.inf) - np.log(ok.sum())
|
||||
d = {"well": o["name"], "n_anchor": int(len(tk)), "n_valid": int(ok.sum()), "gamma": gam,
|
||||
"ess": ess2, "ess_gamma1": ess(np.where(ok, ll, -np.inf))}
|
||||
d |= {f"M1_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main).items()}
|
||||
d |= {f"M2_{k_}": v for k_, v in warp_errors(T[ok], R.tau_fine, o["t_of_tau_true"], R.t_main, lp2[ok]).items()}
|
||||
banks["M1"].append(Y)
|
||||
banks["M2"].append(Y)
|
||||
logpi["M1"].append(lp1)
|
||||
logpi["M2"].append(lp2)
|
||||
if anchors:
|
||||
y_aa = antialias(o["phi_log"], f, R.dt)
|
||||
ties = {"Oracle": o["t_of_tau_true"], "B3a": tie_b3a(tk, ttk, R.tau_fine), "B3b": tie_b3b(tk, ttk, R.tau_fine)}
|
||||
syn_b = synth_for_warps(R.tau_fine, o["ai_log"], ties["B3b"], R.t_fine, R.t_ext, w_fine)[0]
|
||||
ties["B3c"] = tie_b3c(ties["B3b"], R.tau_fine, syn_b, seis[i], R.t_ext, R.dt)
|
||||
ties["B3d"] = warp_mean(T[ok], lp2[ok])
|
||||
for m, t in ties.items():
|
||||
banks[m].append(lab(y_aa, t))
|
||||
if m != "Oracle":
|
||||
d[f"{m}_warp_rmse_ms"] = warp_errors(t[None], R.tau_fine, o["t_of_tau_true"], R.t_main)["warp_rmse_ms"]
|
||||
yw = lab(y_aa, ties["B3b"], t_wide)[0]
|
||||
banks["B4"].append(np.stack([yw[K + j: K + j + L] for j in range(-K, K + 1)]))
|
||||
out["diag"].append(d)
|
||||
out["banks"] = {m: np.stack(v).astype(np.float32) for m, v in banks.items()}
|
||||
out["logpi"] = {m: np.stack(v).astype(np.float32) for m, v in logpi.items()}
|
||||
if anchors:
|
||||
ref = [b[0] for b in out["banks"]["B3b"]]
|
||||
else: # no point tie: M2-weighted mean label as a proxy
|
||||
ref = [np.exp(lp) @ Yb for lp, Yb in zip(out["logpi"]["M2"], out["banks"]["M2"])]
|
||||
out["lam"], out["tau_c"] = effective_lambda(ref, dt_ms=R.dt)
|
||||
return out
|
||||
Reference in New Issue
Block a user