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,36 @@
"""Labels per warp sample (plan §4.3): y^(s)(t_i) = (𝒜φ)(τ^(s)(t_i)).
Logs live on the uniform fine τ grid (sonic time). 𝒜 is a zero-phase low-pass filter applied before 4 ms
sampling (as in resample.log_to_time); τ^(s) is the inverse map of t(·; u^(s)), which exists because t is
monotone.
"""
from __future__ import annotations
import numpy as np
from scipy import signal
def antialias(y: np.ndarray, d_fine_ms: float, out_dt_ms: float = 4.0, cutoff_frac: float = 0.8,
order: int = 6) -> np.ndarray:
"""Low-pass filter at cutoff_frac·Nyquist of the out_dt_ms grid (default 100 Hz for 4 ms)."""
fc = cutoff_frac * 500.0 / out_dt_ms
sos = signal.butter(order, fc, fs=1000.0 / d_fine_ms, output="sos")
return signal.sosfiltfilt(sos, y, padtype="even")
def invert_warps(t_of_tau: np.ndarray, tau: np.ndarray, t_out: np.ndarray) -> np.ndarray:
"""τ(t_out) for each warp sample; t_of_tau (S, n) strictly increasing on the tau grid. NaN outside the
domain."""
t_of_tau = np.atleast_2d(t_of_tau)
out = np.empty((len(t_of_tau), len(t_out)))
for s, ts in enumerate(t_of_tau):
out[s] = np.interp(t_out, ts, tau, left=np.nan, right=np.nan)
return out
def labels_for_warps(tau_fine: np.ndarray, y_filtered: np.ndarray, t_of_tau_fine: np.ndarray,
t_out: np.ndarray) -> np.ndarray:
"""(S, L): labels at t_out for each warp. y_filtered is the log after `antialias` on tau_fine."""
tau_at = invert_warps(t_of_tau_fine, tau_fine, t_out)
return np.where(np.isfinite(tau_at), np.interp(np.nan_to_num(tau_at), tau_fine, y_filtered), np.nan)

View 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

View File

@@ -0,0 +1,104 @@
"""Warp posterior sampling: elliptical slice sampling (Murray, Adams & MacKay 2010) around the linearised
Gaussian posterior, plus tempered importance weights and ESS (plan §4.1–4.2, §4.8).
Exact target: p(u | anchor) ∝ N(u; μ0, Σ0) · Π_k N(d_k; b + F(τ_k; g), σ_a²) · 1{|g| ≤ g_max},
where F uses e^g − 1. Rewritten as N(u; μ_lin, Σ_lin) · exp(L(u)), L = exact log-lik − linearised log-lik
(+ constraints), so elliptical slice sampling uses the linearised posterior (Gauss–Newton at the MAP) as the
"prior" and L as the likelihood.
"""
from __future__ import annotations
import numpy as np
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior, prior_moments
def _ess_step(f, loglik_f, chol, mu, loglik, rng):
nu = mu + chol @ rng.standard_normal(len(mu))
log_y = loglik_f + np.log(rng.uniform())
th = rng.uniform(0, 2 * np.pi)
lo, hi = th - 2 * np.pi, th
for _ in range(200):
fp = mu + (f - mu) * np.cos(th) + (nu - mu) * np.sin(th)
lp = loglik(fp)
if lp > log_y:
return fp, lp
if th < 0:
lo = th
else:
hi = th
th = rng.uniform(lo, hi)
return f, loglik_f
def elliptical_slice(mu, cov, loglik, n_samples, rng, n_chains=4, burn=40, thin=4, init=None):
"""Elliptical slice sampling with prior N(mu, cov). Returns (n_samples, d). Chains start from init (if given)
or mu."""
chol = np.linalg.cholesky(cov + 1e-9 * np.eye(len(mu)) * max(np.trace(cov) / len(mu), 1e-12))
per = int(np.ceil(n_samples / n_chains))
out = []
for c in range(n_chains):
f = mu.copy() if init is None else init.copy()
lf = loglik(f)
if not np.isfinite(lf):
f, lf = mu.copy(), loglik(mu)
for it in range(burn + per * thin):
f, lf = _ess_step(f, lf, chol, mu, loglik, rng)
if it >= burn and (it - burn) % thin == thin - 1:
out.append(f.copy())
return np.array(out[:n_samples])
def sample_warps(grid: WarpGrid, h: WarpHyper, tau_k, t_k, n_samples: int = 64, g_max: float = 0.15,
rng=None, **kw) -> dict:
"""Samples (b, g) from the warp posterior conditioned on anchors (τ_k, t_k). No anchors ⇒ prior samples
(truncated at g_max). Returns {"u": (S, n+1), "b", "g", "mu_lin", "cov_lin"}."""
rng = rng or np.random.default_rng(0)
tau_k = np.asarray(tau_k, dtype=float)
d_k = np.asarray(t_k, dtype=float) - tau_k
if tau_k.size:
mu, cov, A, off = laplace_posterior(grid, h, tau_k, d_k)
P = interp_matrix(tau_k, grid.tau) @ grid.Q
else:
mu, cov = prior_moments(grid, h)
s2 = h.sigma_a_ms**2
def loglik(u):
g = u[1:]
if np.max(np.abs(g)) > g_max:
return -np.inf
if not tau_k.size:
return 0.0
exact = u[0] + P @ np.expm1(g)
lin = A @ u + off
return float(-0.5 * (np.sum((d_k - exact) ** 2) - np.sum((d_k - lin) ** 2)) / s2)
init = mu.copy()
init[1:] = np.clip(init[1:], -0.9 * g_max, 0.9 * g_max)
u = elliptical_slice(mu, cov, loglik, n_samples, rng, init=init, **kw)
return {"u": u, "b": u[:, 0], "g": u[:, 1:], "mu_lin": mu, "cov_lin": cov}
def ess(logw: np.ndarray) -> float:
w = np.exp(logw - np.max(logw))
return float(w.sum() ** 2 / np.sum(w**2))
def temper(loglik: np.ndarray, min_frac: float = 0.25, tol: float = 1e-3) -> tuple[np.ndarray, float, float]:
"""Weights π_s ∝ p_s^γ with the largest γ ∈ [0, 1] such that ESS ≥ min_frac·S (bisection).
Returns (normalised log π, γ, ESS)."""
ll = np.asarray(loglik, dtype=float)
S = len(ll)
target = min_frac * S
if ess(ll) >= target:
g = 1.0
else:
lo, hi = 0.0, 1.0
while hi - lo > tol:
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
g = lo
lw = g * ll
lw = lw - np.logaddexp.reduce(lw)
return lw, g, ess(lw)

View File

@@ -0,0 +1,288 @@
"""Warp posterior conditioned on anchors and seismic via SMC tempering (post-G-B diagnostic, plan §4.2, §9).
protocol_p2 draws S = 64 samples from the anchor posterior and then weights them by π ∝ p(s | u)^γ; the ESS at
γ = 1 collapses to ≈ 1, so the rule ESS ≥ S/4 forces γ down to 0.02–0.11 and the samples carry almost no seismic
information. Here we sample directly from
π_γ(u) ∝ p(u | anchor) · p(s | u)^γ
by SMC tempering (Del Moral, Doucet & Jasra 2006): start from anchor-posterior samples (sampler.sample_warps),
increase γ in adaptive steps that keep ESS ≥ P/2, apply systematic resampling, then move the particles by
elliptical slice sampling with a Gaussian reference q (Gauss–Newton approximation of π_γ around the particle mean,
inflated) and "likelihood" π_γ/q — this leaves π_γ exactly invariant for any q with full support.
Whitened coordinates z: u = μ_lin + L z with Σ_lin = L Lᵀ (linearised anchor posterior), so
log p(u | anchor) = −½‖z‖² + L_a(u) + const, with L_a as in sampler.sample_warps.
γ (power likelihood): −(n/2) log RSS treats the residual as white; band-limited noise and wavelet error make it
over-count information. Matching the curvature to the sandwich variance of the score gives γ = 1/κ,
κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k), where ρ_r is the residual ACF and ρ_d is the ACF of the time derivative of the
synthetic (residual_kappa).
Constant wavelet phase (smc_fit_phase): fit_phase in protocol_p2 takes log mean exp ℓ over S anchor-posterior
samples at γ = 1 — essentially a max over a sample that is off by a few ms per well, so the phase compensates for
warp error. Here we maximise Σ_w log Z_w(φ) with Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du, where log Z_w
is estimated by the SMC itself for each phase on a grid.
"""
from __future__ import annotations
import copy
import numpy as np
from scipy.linalg import solve_triangular
from ml_porosity.data.wavelet import rotate_phase
from ml_porosity.registration.sampler import ess
from ml_porosity.registration.tie_likelihood import fine_wavelet, forward_fine, profile_loglik
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, interp_matrix, laplace_posterior
def residual_kappa(syn: np.ndarray, seis: np.ndarray, max_lag: int = 16) -> float:
"""κ = Σ_{|k| ≤ K} ρ_r(k) ρ_d(k) ≥ 1: score-variance inflation factor under correlated residuals (r = residual
after profiling α ≥ 0, d = time derivative of the synthetic). A white residual gives κ ≈ 1."""
a = max(float(syn @ seis) / max(float(syn @ syn), 1e-30), 0.0)
def acf(x):
x = x - x.mean()
c = np.correlate(x, x, "full")[len(x) - 1: len(x) + max_lag]
return c / c[0]
rr, rd = acf(seis - a * syn), acf(np.gradient(syn))
return max(1.0, 1.0 + 2.0 * float(np.sum(rr[1:] * rd[1:])))
class TiePosterior:
"""π_γ for one well in z coordinates; synthetics are computed for many particles at once.
t(τ) is piecewise linear between warp-grid nodes (as in WarpGrid.t_of_tau with a fine tau), so the inverse map
τ(t) is also piecewise linear and AI as a function of t is obtained exactly by two interpolations; t_fine is
cropped to the seismic window ± half a wavelet (result identical to tie_likelihood.synth_for_warps)."""
def __init__(self, grid: WarpGrid, h: WarpHyper, tau_k, t_k, g_max: float, tau_fine: np.ndarray,
ai_log: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray, seis: np.ndarray,
t_cover: tuple[float, float] | None = None):
tau_k = np.asarray(tau_k, dtype=float)
if tau_k.size == 0:
raise ValueError("anchors required")
self.d_k = np.asarray(t_k, dtype=float) - tau_k
self.mu, cov, self.A, self.off = laplace_posterior(grid, h, tau_k, self.d_k)
jit = 1e-9 * max(np.trace(cov) / len(self.mu), 1e-12) # as in sampler.elliptical_slice
self.Lc = np.linalg.cholesky(cov + jit * np.eye(len(self.mu)))
self.P = interp_matrix(tau_k, grid.tau) @ grid.Q
self.s2a, self.g_max = h.sigma_a_ms**2, g_max
self.tau_g, self.QT = grid.tau, grid.Q.T
self.tau_fine, self.ai_log, self.t_fine = tau_fine, ai_log, t_fine
self.t_out, self.seis = t_out, np.asarray(seis, dtype=float)
self._set_wavelet(w_fine)
self.cover = t_cover
self.n_eval = 0
def _set_wavelet(self, w_fine: np.ndarray) -> None:
self.w_fine = np.asarray(w_fine, dtype=float)
m = (len(self.w_fine) // 2 + 2) * (self.t_fine[1] - self.t_fine[0])
self.t_crop = self.t_fine[(self.t_fine >= self.t_out[0] - m) & (self.t_fine <= self.t_out[-1] + m)]
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosterior":
"""Copy with a different wavelet (keeps the anchor posterior; Laplace is not recomputed)."""
T = copy.copy(self)
T._set_wavelet(w_fine)
T.n_eval = 0
return T
def u(self, Z: np.ndarray) -> np.ndarray:
return self.mu + np.atleast_2d(Z) @ self.Lc.T
def z(self, U: np.ndarray) -> np.ndarray:
return solve_triangular(self.Lc, (np.atleast_2d(U) - self.mu).T, lower=True).T
def t_grid(self, U: np.ndarray) -> np.ndarray:
U = np.atleast_2d(U)
return self.tau_g + U[:, :1] + np.expm1(U[:, 1:]) @ self.QT
def synth(self, U: np.ndarray) -> np.ndarray:
ai = np.stack([np.interp(np.interp(self.t_crop, t, self.tau_g), self.tau_fine, self.ai_log)
for t in self.t_grid(U)])
self.n_eval += len(ai)
return forward_fine(ai, self.t_crop, self.t_out, self.w_fine)
def loglik(self, U: np.ndarray) -> np.ndarray:
return profile_loglik(self.synth(U), self.seis)
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""(log p(u | anchor) + const, ℓ_s(u)) for each row of Z; −inf for particles that violate |g| ≤ g_max or do
not cover t_cover."""
Z = np.atleast_2d(Z)
U = self.u(Z)
g = U[:, 1:]
exact = U[:, :1] + np.expm1(g) @ self.P.T
lin = U @ self.A.T + self.off
la = -0.5 * (np.sum((self.d_k - exact) ** 2, 1) - np.sum((self.d_k - lin) ** 2, 1)) / self.s2a
ok = np.max(np.abs(g), 1) <= self.g_max
if self.cover is not None:
tg = self.t_grid(U)
ok &= (tg[:, 0] <= self.cover[0]) & (tg[:, -1] >= self.cover[1])
ls = np.full(len(Z), -np.inf)
if ok.any():
ls[ok] = self.loglik(U[ok])
return np.where(ok, -0.5 * np.sum(Z**2, 1) + la, -np.inf), ls
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
"""Gaussian reference q = N(m, Λ⁻¹), Λ = I + γ G / infl, G = α̂² JᵀJ / σ̂² (Gauss–Newton of −ℓ_s at m, J by
finite differences in z). Returns (m, L) with Λ = L Lᵀ. The Cholesky factor is unique and continuous in G, so
samples of q with the same seed do not depend on the basis eigh would pick in a degenerate eigenspace (warp
nodes outside the seismic window give zero columns of J) — the condition for smc_torch to match this version
up to rounding error."""
syn = self.synth(self.u(np.vstack([m, m + eps * np.eye(len(m))])))
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
a = max(float(s0 @ self.seis) / max(float(s0 @ s0), 1e-30), 0.0)
s2 = float(np.sum((self.seis - a * s0) ** 2)) / len(self.seis)
return m, np.linalg.cholesky(np.eye(len(m)) + (gamma / infl) * a**2 * (J.T @ J) / s2)
def systematic_resample(logw: np.ndarray, rng) -> np.ndarray:
w = np.exp(logw - np.max(logw))
c = np.cumsum(w / w.sum())
c[-1] = 1.0
return np.searchsorted(c, (rng.uniform() + np.arange(len(w))) / len(w))
def next_gamma(ll: np.ndarray, g0: float, g1: float, min_frac: float = 0.5, n_iter: int = 50) -> float:
"""Largest γ ∈ (g0, g1] such that the ESS of the incremental weights (γ − g0)·ℓ stays ≥ min_frac·P (bisection)."""
target = min_frac * len(ll)
if ess((g1 - g0) * ll) >= target:
return g1
lo, hi = 0.0, g1 - g0
for _ in range(n_iter):
mid = 0.5 * (lo + hi)
lo, hi = (mid, hi) if ess(mid * ll) >= target else (lo, mid)
return g0 + max(lo, 1e-12)
def ess_moves(T: TiePosterior, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60):
"""n_moves elliptical slice steps for all particles simultaneously; the "prior" is q = ref, the "likelihood" is
π_γ / q. Returns (Z, base, ll, mean number of shrinkages per step)."""
m, L = ref
logq = lambda X: -0.5 * np.sum(((X - m) @ L) ** 2, 1)
comb = lambda b, l: np.where(np.isfinite(b), b + gamma * l, -np.inf)
Z, base, ll = Z.copy(), base.copy(), ll.copy()
Lq = comb(base, ll) - logq(Z)
P, d = Z.shape
shrink = 0
for _ in range(n_moves):
nu = m + solve_triangular(L, rng.standard_normal((P, d)).T, lower=True, trans="T").T
log_y = Lq + np.log(rng.uniform(size=P))
th = rng.uniform(0.0, 2 * np.pi, P)
lo, hi = th - 2 * np.pi, th.copy()
act = np.arange(P)
for _ in range(max_iter):
if act.size == 0:
break
c, s = np.cos(th[act])[:, None], np.sin(th[act])[:, None]
zp = m + (Z[act] - m) * c + (nu[act] - m) * s
b, l = T.parts(zp)
lq = comb(b, l) - logq(zp)
acc = lq > log_y[act]
i = act[acc]
Z[i], base[i], ll[i], Lq[i] = zp[acc], b[acc], l[acc], lq[acc]
rej = act[~acc]
neg = th[rej] < 0
lo[rej[neg]] = th[rej[neg]]
hi[rej[~neg]] = th[rej[~neg]]
th[rej] = rng.uniform(lo[rej], hi[rej])
shrink += rej.size
act = rej
return Z, base, ll, shrink / (P * n_moves)
def smc_tie_posterior(T: TiePosterior, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
"""SMC tempering from Z0 (P, d) — anchor-posterior samples in z coordinates (γ = 0) — through increasing γ
checkpoints.
Returns {"Z": {γ: (P, d)}, "ll": {γ: (P,)}, "logZ": {γ: log Ẑ_γ}, "stages": [...]}: at each checkpoint, the
equally weighted particles after the move step and the estimate of log ∫ p(u | anchor) p(s | u)^γ du (product of
the mean incremental weights); stages records γ, the ESS before resampling, the number of distinct particles
after resampling, the mean number of shrinkages, and the RMS jump in z."""
Z = np.atleast_2d(Z0).copy()
base, ll = T.parts(Z)
if not np.all(np.isfinite(base)):
raise ValueError("initial samples violate the constraints")
g, logZ = 0.0, 0.0
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
for gk in sorted(set(float(x) for x in checkpoints)):
while g < gk:
g_new = next_gamma(ll, g, gk, min_frac)
logw = (g_new - g) * ll
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
idx = systematic_resample(logw, rng)
Z, base, ll = Z[idx], base[idx], ll[idx]
Zb = Z.copy()
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference(Z.mean(0), g_new, infl), n_moves, rng)
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
"shrink": sh, "jump_z": float(np.sqrt(np.mean((Z - Zb) ** 2)))})
g = g_new
if len(out["stages"]) >= max_stages:
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.copy(), ll.copy(), logZ
return out
def phase_basis(w0: np.ndarray, factor: int) -> np.ndarray:
"""(2, n_fine): fine wavelet of w0 and of w0 rotated by 90°. rotate_phase(w, φ) = cos φ·w + sin φ·rotate_phase(w,
90°) and fine_wavelet is linear, so the fine wavelet at phase φ is cos φ·B[0] + sin φ·B[1] (exact, not an
approximation)."""
return np.stack([fine_wavelet(w0, factor), fine_wavelet(rotate_phase(w0, 90.0), factor)])
def phase_wavelet(B: np.ndarray, phase_deg: float) -> np.ndarray:
p = np.deg2rad(phase_deg)
return np.cos(p) * B[0] + np.sin(p) * B[1]
def gamma_acf(T: TiePosterior, Z: np.ndarray, ll: np.ndarray) -> float:
"""γ = 1/κ, with κ evaluated at the particle with the largest ℓ_s."""
return 1.0 / residual_kappa(T.synth(T.u(Z[int(np.argmax(ll))]))[0], T.seis)
def smc_fit_phase(Ts: list[TiePosterior], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
step: float = 15.0, half_width: int = 3, max_extra: int = 6, run=smc_tie_posterior,
**smc_kw) -> tuple[float, dict]:
"""Common constant phase for the training wells: maximise Σ_w log Z_w(φ),
Z_w(φ) = ∫ p(u | anchor) p(s_w | u, φ)^{γ_w} du.
log Z_w(φ) is taken from the SMC itself (smc_tie_posterior from anchor-posterior samples Z0s[w] up to γ_w; the
same random stream for every φ to reduce the variance of differences). γ_w = 1/κ_w (gamma_acf) is computed once
at phase φ0 so that all φ are compared at the same γ. Grid φ0 + step·k, |k| ≤ half_width; when the argmax lies on
the boundary, one node is added on that side (at most max_extra times); finally refined by a parabola through
the argmax and its two neighbours. Importance sampling from the particles of one phase to another is unusable:
ℓ changes by ~8 nat/5° after tempering, so ESS ≈ 1. Ts may use any wavelet; run is the SMC function (smc_torch
for GPU). Returns (φ̂ ∈ [−180, 180), info)."""
gam = []
for T0, Z0 in zip(Ts, Z0s):
T = T0.with_wavelet(phase_wavelet(B, phase0))
gam.append(gamma_acf(T, Z0, T.parts(Z0)[1]))
lz = {}
def evaluate(phi: float) -> None:
lz[phi] = np.array([run(T0.with_wavelet(phase_wavelet(B, phi)), Z0, [g],
np.random.default_rng([*seed, i]), **smc_kw)["logZ"][g]
for i, (T0, Z0, g) in enumerate(zip(Ts, Z0s, gam))])
for k in range(-half_width, half_width + 1):
evaluate(float(phase0) + step * k)
for _ in range(max_extra):
phis = sorted(lz)
j = int(np.argmax([lz[p].sum() for p in phis]))
if 0 < j < len(phis) - 1:
break
evaluate(phis[j] + (step if j > 0 else -step))
phis = np.array(sorted(lz))
s = np.array([lz[p].sum() for p in phis])
j = int(np.argmax(s))
phi = phis[j]
edge = not 0 < j < len(phis) - 1
if not edge and s[j - 1] - 2 * s[j] + s[j + 1] < 0:
phi += 0.5 * step * (s[j - 1] - s[j + 1]) / (s[j - 1] - 2 * s[j] + s[j + 1])
info = {"gamma": gam, "phases": phis.tolist(), "logZ": [lz[p].tolist() for p in phis], "edge": edge}
return float((phi + 180.0) % 360.0 - 180.0), info

View File

@@ -0,0 +1,301 @@
"""The SMC warp posterior of smc.py on GPU (torch, float64).
Same algorithm and same random stream: all random numbers are still drawn from the numpy Generator in exactly the
order of smc.py (γ and resampling stay on the CPU); synthetics, likelihood, particle π_γ, the Gaussian reference and
the whole elliptical slice shrinkage loop run batched on the device, with no host synchronisation inside each
shrinkage step (ess_moves). With the same seed, results match the CPU version up to rounding error, unless an
accept/reject decision falls exactly within that error — the chain then diverges but keeps the same distribution.
Synthetic: piecewise-linear warp inversion by batched searchsorted, AI interpolation, reflectivity, then the 'same'
convolution and interpolation to t_out are merged into one fixed (n_r, L) matrix per wavelet (conv_interp_matrix).
"""
from __future__ import annotations
import copy
import numpy as np
import torch
from ml_porosity.registration import smc
from ml_porosity.registration.sampler import ess
from ml_porosity.registration.smc import TiePosterior, next_gamma, systematic_resample
F64 = torch.float64
def interp_weights(x: np.ndarray, xp: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""(j, w) with np.interp(x, xp, f) = (1 − w)·f[j] + w·f[j + 1]; clamped at both ends as in np.interp."""
j = np.clip(np.searchsorted(xp, x, side="right") - 1, 0, len(xp) - 2)
return j, np.clip((x - xp[j]) / (xp[j + 1] - xp[j]), 0.0, 1.0)
def conv_interp_matrix(w_fine: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray) -> np.ndarray:
"""M (n_r, L) with tie_likelihood.forward_fine(ai, t_fine, t_out, w_fine) = r(ai) @ M: scipy's 'same'
convolution (the segment starting at (n_w − 1) // 2 of the full convolution), then interpolation from the
midpoints to t_out."""
n_r, n_w = len(t_fine) - 1, len(w_fine)
j, w = interp_weights(t_out, 0.5 * (t_fine[1:] + t_fine[:-1]))
i = np.arange(n_r)[:, None]
def col(jj):
k = jj[None, :] + (n_w - 1) // 2 - i
return np.where((k >= 0) & (k < n_w), w_fine[np.clip(k, 0, n_w - 1)], 0.0)
return (1.0 - w) * col(j) + w * col(j + 1)
def interp_t(x: torch.Tensor, xp: torch.Tensor, fp: torch.Tensor) -> torch.Tensor:
"""Batched np.interp: x (P, n); xp (P, m) (each row increasing) or (m,); fp (m,)."""
j = (torch.searchsorted(xp, x, right=True) - 1).clamp_(0, xp.shape[-1] - 2)
x0, x1 = (xp[j], xp[j + 1]) if xp.dim() == 1 else (xp.gather(1, j), xp.gather(1, j + 1))
w = ((x - x0) / (x1 - x0)).clamp_(0.0, 1.0)
return fp[j] + w * (fp[j + 1] - fp[j])
def profile_loglik_t(syn: torch.Tensor, seis: torch.Tensor) -> torch.Tensor:
"""tie_likelihood.profile_loglik on tensors."""
a = torch.clamp(syn @ seis / torch.clamp((syn**2).sum(1), min=1e-30), min=0.0)
return -0.5 * len(seis) * torch.log(((seis - a[:, None] * syn) ** 2).sum(1))
class TiePosteriorTorch:
"""TiePosterior with synthetics, likelihood and π_γ computed in batches on `device`. The numpy methods (u, z,
synth, loglik, parts, reference, with_wavelet, n_eval, seis) keep the TiePosterior interface so that
smc.gamma_acf, smc.smc_fit_phase and scripts/14 can be shared; the *_t versions take/return device tensors."""
def __init__(self, T: TiePosterior, device):
self.cpu, self.device = T, torch.device(device)
if self.device.type == "cuda":
torch.cuda.set_device(self.device) # implicit-device operations also go to the right GPU
f = self.tensor
self.mu, self.Lc, self.Pk, self.A, self.off, self.d_k = map(f, (T.mu, T.Lc, T.P, T.A, T.off, T.d_k))
self.tau_g, self.QT, self.tau_fine, self.ai_log = map(f, (T.tau_g, T.QT, T.tau_fine, T.ai_log))
self.seis_t = f(T.seis)
self._set_wavelet()
self._cnt = torch.zeros((), dtype=torch.int64, device=self.device)
def tensor(self, x) -> torch.Tensor:
return torch.as_tensor(np.asarray(x, dtype=float), dtype=F64, device=self.device)
def _set_wavelet(self) -> None:
self.t_crop = self.tensor(self.cpu.t_crop)
self.M = self.tensor(conv_interp_matrix(self.cpu.w_fine, self.cpu.t_crop, self.cpu.t_out))
def with_wavelet(self, w_fine: np.ndarray) -> "TiePosteriorTorch":
T = copy.copy(self)
T.cpu = self.cpu.with_wavelet(w_fine)
T._set_wavelet()
T._cnt = torch.zeros_like(self._cnt)
return T
@property
def seis(self) -> np.ndarray:
return self.cpu.seis
@property
def w_fine(self) -> np.ndarray:
return self.cpu.w_fine
@property
def n_eval(self) -> int:
"""Number of synthetics computed (as in TiePosterior: parts counts only valid particles)."""
return int(self._cnt)
@n_eval.setter
def n_eval(self, v: int) -> None:
self._cnt.fill_(int(v))
def u_t(self, Z: torch.Tensor) -> torch.Tensor:
return self.mu + Z @ self.Lc.T
def _synth_tg(self, tg: torch.Tensor) -> torch.Tensor:
"""(P, L) from t at the warp-grid nodes (P, n_g)."""
tau = interp_t(self.t_crop.expand(len(tg), -1).contiguous(), tg.contiguous(), self.tau_g)
ai = interp_t(tau, self.tau_fine, self.ai_log)
return ((ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])) @ self.M
def synth_t(self, U: torch.Tensor) -> torch.Tensor:
self._cnt += len(U)
return self._synth_tg(self.tau_g + U[:, :1] + torch.expm1(U[:, 1:]) @ self.QT)
def parts_t(self, Z: torch.Tensor, mask: torch.Tensor | None = None) -> tuple[torch.Tensor, torch.Tensor]:
"""TiePosterior.parts on tensors, without host synchronisation. Synthetics are computed for all rows and
violating particles are then masked (cheaper than filtering on the GPU); `mask` (bool, optional) marks the rows
actually needed — only these are counted in n_eval."""
U = self.u_t(Z)
g = U[:, 1:]
eg = torch.expm1(g)
exact = U[:, :1] + eg @ self.Pk.T
lin = U @ self.A.T + self.off
la = -0.5 * (((self.d_k - exact) ** 2).sum(1) - ((self.d_k - lin) ** 2).sum(1)) / self.cpu.s2a
tg = self.tau_g + U[:, :1] + eg @ self.QT
ok = g.abs().amax(1) <= self.cpu.g_max
if self.cpu.cover is not None:
ok &= (tg[:, 0] <= self.cpu.cover[0]) & (tg[:, -1] >= self.cpu.cover[1])
self._cnt += (ok if mask is None else ok & mask).sum()
ls = profile_loglik_t(self._synth_tg(tg), self.seis_t)
return torch.where(ok, -0.5 * (Z**2).sum(1) + la, -np.inf), torch.where(ok, ls, -np.inf)
def reference_t(self, m: torch.Tensor, gamma: float, infl: float = 2.0, eps: float = 0.05):
"""TiePosterior.reference on the device. Returns tensors (m, L)."""
eye = torch.eye(len(m), dtype=F64, device=self.device)
syn = self.synth_t(self.u_t(torch.cat([m[None], m + eps * eye])))
s0, J = syn[0], (syn[1:] - syn[0]).T / eps
a = max(float(s0 @ self.seis_t) / max(float(s0 @ s0), 1e-30), 0.0)
s2 = float(((self.seis_t - a * s0) ** 2).sum()) / len(self.seis_t)
return m, torch.linalg.cholesky(eye + (gamma / infl) * a**2 * (J.T @ J) / s2)
def u(self, Z: np.ndarray) -> np.ndarray:
return self.cpu.u(Z)
def z(self, U: np.ndarray) -> np.ndarray:
return self.cpu.z(U)
def t_grid(self, U: np.ndarray) -> np.ndarray:
return self.cpu.t_grid(U)
def synth(self, U: np.ndarray) -> np.ndarray:
return self.synth_t(self.tensor(np.atleast_2d(U))).cpu().numpy()
def loglik(self, U: np.ndarray) -> np.ndarray:
return profile_loglik_t(self.synth_t(self.tensor(np.atleast_2d(U))), self.seis_t).cpu().numpy()
def parts(self, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
b, ls = self.parts_t(self.tensor(np.atleast_2d(Z)))
return b.cpu().numpy(), ls.cpu().numpy()
def reference(self, m: np.ndarray, gamma: float, infl: float = 2.0, eps: float = 0.05):
return tuple(x.cpu().numpy() for x in self.reference_t(self.tensor(m), gamma, infl, eps))
_LAST_GRAPH: dict = {}
def cuda_graph(fn, device: torch.device):
"""Capture fn() — no arguments, no host synchronisation, only in-place writes into pre-allocated tensors — as a
CUDA graph; returns the replay function. fn is run once beforehand for warm-up (cuBLAS workspace, ...), so that
run must be free of side effects.
All graphs on a device share one stream and the memory pool of the graph captured before them: the pool of a
discarded graph is returned to the device only on empty_cache, so recapturing every SMC stage with a fresh pool
would hold unbounded memory. The previous graph is kept until the new one has been captured (the shared pool must
still have a user, on the host side too) and is never replayed again — sharing a pool is safe only when at most
one graph is still replayed at any time; ess_moves drops its graph when done. capture_begin is called directly
instead of torch.cuda.graph, which empties the memory cache on every capture."""
side, prev = _LAST_GRAPH.get(device) or (torch.cuda.Stream(device), None)
side.wait_stream(torch.cuda.current_stream(device))
graph = torch.cuda.CUDAGraph()
with torch.cuda.stream(side):
fn()
graph.capture_begin(pool=None if prev is None else prev.pool(), capture_error_mode="thread_local")
try:
fn()
finally:
graph.capture_end()
torch.cuda.current_stream(device).wait_stream(side)
_LAST_GRAPH[device] = side, graph
return graph.replay
def ess_moves(T: TiePosteriorTorch, Z, base, ll, gamma: float, ref, n_moves: int, rng, max_iter: int = 60,
check_every: int = 4):
"""smc.ess_moves with Z, base, ll, ref as device tensors, without host synchronisation in the shrinkage loop.
Each shrinkage step evaluates all P particles and masks those already accepted (on the GPU one call costs almost
the same regardless of P), writing in place into fixed state, so on CUDA the whole step is captured as one graph.
Random numbers are still drawn on the CPU in exactly the order of the numpy version: ξ, u, initial angle, then
the shrinkages — uniform(lo, hi) = lo + (hi − lo)·U with U the next number in the stream, so a pool of U(0, 1) is
drawn in advance, the particles rejected at each step take numbers in index order, and the Generator is then
reset and advanced by exactly the number used. The host reads the device only every `check_every` steps to check
whether any particle remains unaccepted."""
m, L = ref
dev = Z.device
logq = lambda X: -0.5 * (((X - m) @ L) ** 2).sum(1)
comb = lambda b, l: torch.where(torch.isfinite(b), b + gamma * l, -np.inf)
Z, base, ll = Z.clone(), base.clone(), ll.clone()
Lq = comb(base, ll) - logq(Z)
P, d = Z.shape
nu = torch.zeros_like(Z)
log_y, th, lo, hi = (torch.zeros_like(ll) for _ in range(4))
pool = torch.zeros(P * max_iter, dtype=F64, device=dev)
act = torch.zeros(P, dtype=torch.bool, device=dev)
used = torch.zeros((), dtype=torch.int64, device=dev)
def step(): # act all False: no change
zp = m + (Z - m) * torch.cos(th)[:, None] + (nu - m) * torch.sin(th)[:, None]
b, l = T.parts_t(zp, act)
lq = comb(b, l) - logq(zp)
up = lq > log_y
acc, rej = act & up, act & ~up
Z.copy_(torch.where(acc[:, None], zp, Z))
for x, y in ((base, b), (ll, l), (Lq, lq)):
x.copy_(torch.where(acc, y, x))
neg = th < 0
lo.copy_(torch.where(rej & neg, th, lo))
hi.copy_(torch.where(rej & ~neg, th, hi))
u = pool[(used + rej.cumsum(0) - 1).clamp_(0, len(pool) - 1)]
th.copy_(torch.where(rej, lo + (hi - lo) * u, th))
used.add_(rej.sum())
act.copy_(rej)
cuda = dev.type == "cuda"
run = cuda_graph(step, dev) if cuda else step
shrink = 0
for _ in range(n_moves):
head = [rng.standard_normal(P * d), np.log(rng.uniform(size=P)), rng.uniform(0.0, 2 * np.pi, P)]
state = rng.bit_generator.state
buf = torch.from_numpy(np.concatenate(head + [rng.random(P * max_iter)]))
buf = (buf.pin_memory() if cuda else buf).to(dev, non_blocking=True)
xi, log_u, th0, pool0 = torch.split(buf, [P * d, P, P, P * max_iter])
nu.copy_(m + torch.linalg.solve_triangular(L.T, xi.view(P, d).T, upper=True).T)
log_y.copy_(Lq + log_u)
for x, y in ((th, th0), (lo, th0 - 2 * np.pi), (hi, th0), (pool, pool0)):
x.copy_(y)
act.fill_(True)
used.zero_()
for it in range(1, max_iter + 1):
run()
if it % check_every == 0 or it == max_iter:
n_act, n_used = torch.stack([act.sum(), used]).tolist()
if n_act == 0:
break
rng.bit_generator.state = state
rng.random(n_used)
shrink += n_used
return Z, base, ll, shrink / (P * n_moves)
def smc_tie_posterior(T: TiePosteriorTorch, Z0: np.ndarray, checkpoints, rng, min_frac: float = 0.5,
n_moves: int = 8, infl: float = 2.0, max_stages: int = 500) -> dict:
"""smc.smc_tie_posterior on the device; numpy in/out as in the CPU version."""
Z = T.tensor(np.atleast_2d(Z0))
base, ll = T.parts_t(Z)
if not bool(torch.isfinite(base).all()):
raise ValueError("initial samples violate the constraints")
g, logZ = 0.0, 0.0
out = {"Z": {}, "ll": {}, "logZ": {}, "stages": []}
for gk in sorted(set(float(x) for x in checkpoints)):
while g < gk:
ll_np = ll.cpu().numpy()
g_new = next_gamma(ll_np, g, gk, min_frac)
logw = (g_new - g) * ll_np
logZ += float(np.logaddexp.reduce(logw)) - np.log(len(logw))
idx = systematic_resample(logw, rng)
idx_t = torch.from_numpy(idx).to(Z.device)
Z, base, ll = Z[idx_t], base[idx_t], ll[idx_t]
Zb = Z.clone()
Z, base, ll, sh = ess_moves(T, Z, base, ll, g_new, T.reference_t(Z.mean(0), g_new, infl), n_moves, rng)
out["stages"].append({"gamma": g_new, "ess": ess(logw), "n_unique": int(np.unique(idx).size),
"shrink": sh, "jump_z": float(torch.sqrt(torch.mean((Z - Zb) ** 2)))})
g = g_new
if len(out["stages"]) >= max_stages:
raise RuntimeError(f"exceeded {max_stages} tempering stages (γ = {g:.4g})")
out["Z"][gk], out["ll"][gk], out["logZ"][gk] = Z.cpu().numpy(), ll.cpu().numpy(), logZ
return out
def smc_fit_phase(Ts: list[TiePosteriorTorch], Z0s: list[np.ndarray], B: np.ndarray, phase0: float, seed: list[int],
**kw) -> tuple[float, dict]:
"""smc.smc_fit_phase with the SMC run on the device."""
return smc.smc_fit_phase(Ts, Z0s, B, phase0, seed, run=smc_tie_posterior, **kw)

View File

@@ -0,0 +1,66 @@
"""Physical well-tie likelihood (plan §4.2): p(s | g) = N(s; α W r(g), σ_n² I).
Forward model shared by the D2 generator and the M2 weights: AI on a fine time axis → reflectivity at the
sample midpoints → convolution with the fine wavelet → interpolation to the 4 ms sample times. α and σ_n² are
profiled out: log p = −(n/2)·log RSS(α̂). Weights π_s ∝ p_s^γ with γ chosen by sampler.temper (ESS ≥ S/4).
Constant wavelet phase: maximum marginal likelihood over the posterior warp samples (fit_phase).
"""
from __future__ import annotations
import numpy as np
from scipy import signal
from ml_porosity.data.wavelet import rotate_phase
def fine_wavelet(w: np.ndarray, factor: int) -> np.ndarray:
"""Band-limited interpolation of the wavelet (odd length, centred) onto a grid `factor` times finer; keeps the
centre."""
wf = signal.resample_poly(w, factor, 1)
n = len(w) // 2
return wf[: 2 * n * factor + 1]
def forward_fine(ai: np.ndarray, t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
"""Synthetic seismic at t_out from AI on the uniform fine time grid t_fine. ai (..., nf) → (..., L)."""
ai = np.atleast_2d(ai)
r = (ai[:, 1:] - ai[:, :-1]) / (ai[:, 1:] + ai[:, :-1])
s = signal.fftconvolve(r, w_fine[None, :], mode="same", axes=1)
tm = 0.5 * (t_fine[1:] + t_fine[:-1])
return np.stack([np.interp(t_out, tm, si) for si in s])
def synth_for_warps(tau_fine: np.ndarray, ai_log: np.ndarray, t_of_tau_fine: np.ndarray,
t_fine: np.ndarray, t_out: np.ndarray, w_fine: np.ndarray) -> np.ndarray:
"""(S, L): synthetic for each warp. The AI log (τ axis) is mapped to the t axis by each warp sample."""
t_of_tau_fine = np.atleast_2d(t_of_tau_fine)
ai_t = np.stack([np.interp(t_fine, ts, ai_log) for ts in t_of_tau_fine])
return forward_fine(ai_t, t_fine, t_out, w_fine)
def profile_loglik(syn: np.ndarray, seis: np.ndarray) -> np.ndarray:
"""log p_s = −(n/2)·log RSS_s after profiling out α_s ≥ 0 (constrained least squares; synthetic and seismic
follow the same polarity convention, so phases φ and φ + 180° no longer give the same likelihood) and σ_n²."""
syn = np.atleast_2d(syn)
a = np.maximum(syn @ seis / np.maximum(np.sum(syn**2, 1), 1e-30), 0.0)
rss = np.sum((seis[None, :] - a[:, None] * syn) ** 2, 1)
return -0.5 * len(seis) * np.log(rss)
def phase_loglik(syn0: np.ndarray, seis: np.ndarray, phases=np.arange(-180, 180, 15)) -> np.ndarray:
"""(P, S): log p_s for each constant phase. syn0 (S, L) is the synthetic with the zero-phase wavelet; phase
rotation commutes with convolution, so only the synthetic needs to be rotated."""
return np.stack([profile_loglik(rotate_phase(np.atleast_2d(syn0), p), seis) for p in phases])
def fit_phase(ll_list: list[np.ndarray], valid_list: list[np.ndarray], phases=np.arange(-180, 180, 15)) -> int:
"""Phase maximising the marginal likelihood Σ_w log mean_s p(s_w | g_ws, φ) over the (anchor) posterior warp
samples of each training well; ll_list[w] (P, S) from phase_loglik. Returns the phase index in `phases`.
Correlation against a single point tie is unusable: a tie error of a few ms already reduces ncc to ~0.1 and
the estimated phase is almost random."""
from scipy.special import logsumexp
score = sum(logsumexp(ll[:, ok], axis=1) - np.log(ok.sum()) for ll, ok in zip(ll_list, valid_list))
return int(np.argmax(score))

View File

@@ -0,0 +1,93 @@
"""Point ties for B3a–d on D2 (plan §5.3) and warp-error diagnostics.
Every tie returns t(τ) on the fine τ grid (strictly increasing), so that `labels_for_warps` can be shared:
- B3a: single-point tie at the shallowest anchor, t = τ + (t_0 − τ_0) — analogous to the thesis's "integrated DT
hung at the first marker" (no drift correction).
- B3b: marker-calibrated sonic (tdr.calibrate_to_anchors) after removing anchors that break monotonicity.
- B3c: B3b + local shifts from synthetic–seismic correlation (synthetic.local_shifts), as in a manual tie.
- B3d: M2-weighted mean warp, Σ_s π_s t_s(τ) (the plan states MAP; the mean is more stable than the MAP over a
finite importance sample — recorded as a deviation in protocol_p2).
"""
from __future__ import annotations
import numpy as np
from ml_porosity.data.synthetic import local_shifts
from ml_porosity.data.tdr import TDR, calibrate_to_anchors
from ml_porosity.registration.labels import invert_warps
def clean_monotone(tau_k, t_k) -> tuple[np.ndarray, np.ndarray]:
"""Longest strictly increasing subsequence of (τ_k, t_k) sorted by τ (pick noise can make t non-monotone)."""
o = np.argsort(tau_k)
tau, t = np.asarray(tau_k, float)[o], np.asarray(t_k, float)[o]
n = len(t)
if n == 0:
return tau, t
best, prev = np.ones(n, int), np.full(n, -1)
for i in range(n):
for j in range(i):
if t[j] < t[i] and tau[j] < tau[i] and best[j] + 1 > best[i]:
best[i], prev[i] = best[j] + 1, j
k, keep = int(np.argmax(best)), []
while k >= 0:
keep.append(k)
k = prev[k]
keep = keep[::-1]
return tau[keep], t[keep]
def tie_b3a(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
k = int(np.argmin(tau_k))
return tau + (t_k[k] - tau_k[k])
def tie_b3b(tau_k, t_k, tau: np.ndarray) -> np.ndarray:
tk, ttk = clean_monotone(tau_k, t_k)
if len(tk) < 2:
return tie_b3a(tk, ttk, tau) if len(tk) else tau.copy()
return calibrate_to_anchors(TDR(tau, tau, "sonic"), tk, ttk).time_at(tau)
def tie_b3c(t_b3b: np.ndarray, tau: np.ndarray, syn: np.ndarray, seis: np.ndarray, t_out: np.ndarray,
dt_ms: float = 4.0, r_min: float = 0.3, smooth: int = 3, **kw) -> np.ndarray:
"""syn: synthetic under the B3b tie on t_out; seis: centre trace on t_out. Shifts s(t) (positive = synthetic
must be later) from windows with r ≥ r_min, smoothed by a moving average over `smooth` windows, then
t(τ) = t_B3b(τ) + s(t_B3b(τ)); strict monotonicity is enforced (dt/dτ ≥ 0.05)."""
c, s, r = local_shifts(syn, seis, dt_ms, **kw)
ok = r >= r_min
if ok.sum() == 0:
return t_b3b.copy()
tc, sc = t_out[c[ok]], s[ok]
if smooth > 1 and len(sc) >= smooth:
sc = np.convolve(np.pad(sc, smooth // 2, mode="edge"), np.ones(smooth) / smooth, "valid")
t = t_b3b + np.interp(t_b3b, tc, sc)
return np.maximum.accumulate(t - 0.05 * tau) + 0.05 * tau
def warp_mean(t_of_tau: np.ndarray, logw: np.ndarray) -> np.ndarray:
w = np.exp(logw - np.max(logw))
return (w / w.sum()) @ np.atleast_2d(t_of_tau)
def warp_errors(t_of_tau: np.ndarray, tau: np.ndarray, t_true_of_tau: np.ndarray, t_eval: np.ndarray,
logw: np.ndarray | None = None) -> dict:
"""Warp error in τ(t) on t_eval (ms). One warp: RMSE. Several warps: RMSE of the weighted mean,
90% coverage (weighted 5–95% quantiles) and mean interval width."""
tau_true = invert_warps(t_true_of_tau, tau, t_eval)[0]
T = invert_warps(t_of_tau, tau, t_eval)
if len(T) == 1:
return {"warp_rmse_ms": float(np.sqrt(np.nanmean((T[0] - tau_true) ** 2)))}
w = np.ones(len(T)) if logw is None else np.exp(logw - np.max(logw))
w = w / w.sum()
mean = w @ T
o = np.argsort(T, 0)
cw = np.cumsum(w[o], 0)
Ts = np.take_along_axis(T, o, 0)
lo = Ts[np.argmax(cw >= 0.05, 0), np.arange(T.shape[1])]
hi = Ts[np.argmax(cw >= 0.95, 0), np.arange(T.shape[1])]
return {"warp_rmse_ms": float(np.sqrt(np.mean((mean - tau_true) ** 2))),
"warp_cov90": float(np.mean((tau_true >= lo) & (tau_true <= hi))),
"warp_width90_ms": float(np.mean(hi - lo))}

View File

@@ -0,0 +1,243 @@
"""GP log-slowness warp prior conditioned on anchors (plan §4.1).
The reference axis τ is sonic time (integrated DT, ms) and t is seismic time (ms):
t(τ) = τ + b + ∫_{τ0}^{τ} (e^{g(τ')} − 1) dτ', g ~ GP(m_g, k_{σ_g, ℓ}), b ~ N(0, σ_b²)
Anchors (markers with TWT): t_k = t(τ_k) + ε_k, ε_k ~ N(0, σ_a²). Writing dt/dτ = e^g is equivalent to the
depth form in the plan (dt/dz = 2·DT·e^g) since dτ/dz = 2·DT. g is defined on a uniform τ grid; the integral is
the trapezoid rule on that grid (the same quadrature for the linearised version e^g − 1 ≈ g and the exact one),
so the difference between the two comes only from the nonlinearity of e^g.
Latent vector u = [b, g_1..g_n]. The linearised Gaussian posterior serves as the proposal for elliptical slice
sampling (sampler.py). Hyperparameters (m_g, σ_g, ℓ, σ_b, σ_a) are fitted by type-II maximum likelihood on the
anchors of the training wells (empirical Bayes).
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
import numpy as np
from scipy import optimize
from scipy.linalg import cho_factor, cho_solve
@dataclass
class WarpHyper:
m_g: float = 0.0
sigma_g: float = 0.03
ell_ms: float = 200.0
sigma_b_ms: float = 30.0
sigma_a_ms: float = 4.0
kernel: str = "matern32"
def scaled(self, c: float) -> WarpHyper:
"""Drift scaled by a factor c (used for the ×c drift grid of D2): g → c·g, b → c·b."""
return WarpHyper(c * self.m_g, c * self.sigma_g, self.ell_ms, c * self.sigma_b_ms, self.sigma_a_ms, self.kernel)
def as_dict(self) -> dict:
return asdict(self)
def kernel_matrix(x: np.ndarray, y: np.ndarray, sigma: float, ell: float, kind: str = "matern32") -> np.ndarray:
r = np.abs(np.asarray(x)[:, None] - np.asarray(y)[None, :]) / ell
if kind == "matern32":
a = np.sqrt(3.0) * r
return sigma**2 * (1.0 + a) * np.exp(-a)
if kind == "se":
return sigma**2 * np.exp(-0.5 * r**2)
raise ValueError(kind)
def cumtrapz_matrix(n: int, dx: float) -> np.ndarray:
"""Q with (Q f)_i = ∫_{x_0}^{x_i} f by the trapezoid rule on a uniform grid."""
Q = np.zeros((n, n))
for i in range(1, n):
Q[i, :i + 1] = dx
Q[i, 0] = Q[i, i] = dx / 2
return Q
def interp_matrix(x: np.ndarray, grid: np.ndarray) -> np.ndarray:
"""P with P f = linear interpolation of f (on grid) at x. x must lie within grid."""
x = np.asarray(x, dtype=float)
P = np.zeros((len(x), len(grid)))
j = np.clip(np.searchsorted(grid, x) - 1, 0, len(grid) - 2)
w = (x - grid[j]) / (grid[j + 1] - grid[j])
P[np.arange(len(x)), j] = 1 - w
P[np.arange(len(x)), j + 1] = w
return P
class WarpGrid:
"""τ grid of one well and the associated linear operators."""
def __init__(self, tau0: float, tau1: float, dtau: float = 4.0):
n = int(np.ceil((tau1 - tau0) / dtau)) + 1
self.tau = tau0 + dtau * np.arange(n)
self.dtau = dtau
self.Q = cumtrapz_matrix(n, dtau)
@property
def n(self) -> int:
return len(self.tau)
def t_of_tau(self, b, g, tau=None) -> np.ndarray:
"""t(τ) for samples (b, g); b scalar or (S,), g (n,) or (S, n). Returns (S, ·) on the grid or
at tau (linear interpolation; tau must lie within the grid)."""
g = np.atleast_2d(g)
t = self.tau[None, :] + np.reshape(b, (-1, 1)) + np.expm1(g) @ self.Q.T
if tau is not None:
t = t @ interp_matrix(tau, self.tau).T
return t
def anchor_operator(self, tau_k: np.ndarray) -> np.ndarray:
"""A with t(τ_k) − τ_k ≈ A u (linearised), u = [b, g]."""
C = interp_matrix(tau_k, self.tau) @ self.Q
return np.hstack([np.ones((len(tau_k), 1)), C])
def prior_moments(grid: WarpGrid, h: WarpHyper) -> tuple[np.ndarray, np.ndarray]:
mu = np.concatenate([[0.0], np.full(grid.n, h.m_g)])
S = np.zeros((grid.n + 1, grid.n + 1))
S[0, 0] = h.sigma_b_ms**2
S[1:, 1:] = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
S[1:, 1:] += 1e-10 * np.eye(grid.n)
return mu, S
def linearize(grid: WarpGrid, tau_k: np.ndarray, g0: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""t(τ_k) − τ_k ≈ A u + off, linearising e^g − 1 at g0. g0 = 0 gives A = anchor_operator, off = 0."""
C = interp_matrix(tau_k, grid.tau) @ grid.Q
e = np.exp(g0)
return np.hstack([np.ones((len(tau_k), 1)), C * e[None, :]]), C @ (e - 1.0 - e * g0)
def linear_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, g0=None) -> tuple[np.ndarray, np.ndarray]:
"""Gaussian posterior of u = [b, g] given d_k = t_k − τ_k ≈ A u + off + ε (linearised at g0,
default 0). Without anchors: returns the prior."""
mu, S = prior_moments(grid, h)
tau_k = np.asarray(tau_k, dtype=float)
if tau_k.size == 0:
return mu, S
A, off = linearize(grid, tau_k, np.zeros(grid.n) if g0 is None else g0)
SA = S @ A.T
G = A @ SA + h.sigma_a_ms**2 * np.eye(len(tau_k))
cf = cho_factor(G)
mu_p = mu + SA @ cho_solve(cf, np.asarray(d_k) - off - A @ mu)
S_p = S - SA @ cho_solve(cf, SA.T)
return mu_p, 0.5 * (S_p + S_p.T)
def laplace_posterior(grid: WarpGrid, h: WarpHyper, tau_k, d_k, n_iter: int = 8, tol: float = 1e-7):
"""Gauss–Newton: iterated linearisation at the posterior mean; converges to the MAP of the exact posterior
(ignoring the g_max constraint). Returns (mu, S, A, off) with A, off the linearisation at mu."""
g0 = np.full(grid.n, h.m_g)
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
for _ in range(n_iter):
if np.max(np.abs(mu[1:] - g0)) < tol:
break
g0 = mu[1:].copy()
mu, S = linear_posterior(grid, h, tau_k, d_k, g0)
A, off = linearize(grid, np.asarray(tau_k, dtype=float), g0)
return mu, S, A, off
# ---------------------------------------------------------------- type-II maximum likelihood
def _marginal_cov(C: np.ndarray, Kgg: np.ndarray, h: WarpHyper) -> np.ndarray:
n = C.shape[0]
return h.sigma_b_ms**2 * np.ones((n, n)) + C @ Kgg @ C.T + h.sigma_a_ms**2 * np.eye(n)
def log_marginal(wells: list[dict], h: WarpHyper) -> float:
"""Σ_w log N(d_w; C_w m_g 1, σ_b² 11ᵀ + C_w K C_wᵀ + σ_a² I). wells[i] = {"grid", "tau_k", "d_k"}."""
total = 0.0
for w in wells:
grid: WarpGrid = w["grid"]
C = interp_matrix(w["tau_k"], grid.tau) @ grid.Q
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
V = _marginal_cov(C, K, h)
r = np.asarray(w["d_k"]) - h.m_g * C.sum(1)
try:
cf = cho_factor(V)
except np.linalg.LinAlgError:
return -np.inf
total += -0.5 * r @ cho_solve(cf, r) - np.log(np.diag(cf[0])).sum() - 0.5 * len(r) * np.log(2 * np.pi)
return float(total)
_FREE = ("m_g", "sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms")
_LOG = {"sigma_g", "ell_ms", "sigma_b_ms", "sigma_a_ms"}
def fit_hyper(
wells: list[dict],
init: WarpHyper | None = None,
fixed: dict | None = None,
bounds: dict | None = None,
hyperprior: dict | None = None,
n_starts: int = 8,
seed: int = 0,
) -> tuple[WarpHyper, dict]:
"""Type-II ML (or MAP-II if a hyperprior is given) for the hyperparameters that are not fixed.
hyperprior[name] = (mean, sd) of the parameter on the log scale (σ, ℓ) or the original scale (m_g).
Returns (best hyperparameters, info containing the log-marginal and the starting points)."""
init = init or WarpHyper()
fixed = fixed or {}
hyperprior = hyperprior or {}
bnd = {"m_g": (-0.2, 0.2), "sigma_g": (1e-4, 0.3), "ell_ms": (10.0, 3000.0),
"sigma_b_ms": (0.5, 200.0), "sigma_a_ms": (0.2, 50.0)} | (bounds or {})
free = [k for k in _FREE if k not in fixed]
to_x = lambda k, v: np.log(v) if k in _LOG else v
from_x = lambda k, x: float(np.exp(x)) if k in _LOG else float(x)
lo = np.array([to_x(k, bnd[k][0]) for k in free])
hi = np.array([to_x(k, bnd[k][1]) for k in free])
def make(x):
vals = asdict(init) | fixed | {k: from_x(k, xi) for k, xi in zip(free, x)}
return WarpHyper(**vals)
def obj(x):
h = make(x)
lp = log_marginal(wells, h)
for k, xi in zip(free, x):
if k in hyperprior:
m, s = hyperprior[k]
lp += -0.5 * ((xi - m) / s) ** 2
return -lp if np.isfinite(lp) else 1e12
rng = np.random.default_rng(seed)
x0s = [np.clip([to_x(k, getattr(init, k)) for k in free], lo, hi)]
x0s += [lo + (hi - lo) * rng.uniform(0.15, 0.85, len(free)) for _ in range(n_starts - 1)]
best, starts = None, []
for x0 in x0s:
res = optimize.minimize(obj, x0, method="L-BFGS-B", bounds=list(zip(lo, hi)))
starts.append(float(-res.fun))
if best is None or res.fun < best.fun:
best = res
h = make(best.x)
return h, {"log_marginal": log_marginal(wells, h), "objective": float(-best.fun), "starts": starts,
"free": free, "at_bound": [k for k, xi, a, b in zip(free, best.x, lo, hi) if min(xi - a, b - xi) < 1e-3]}
def loao_zscores(wells: list[dict], h: WarpHyper) -> list[np.ndarray]:
"""Leave-one-anchor-out: z-score of d_k under the (linearised) posterior prediction from the remaining
anchors of the same well (plan §5.4). Returns a list of z arrays, one per well."""
out = []
for w in wells:
grid: WarpGrid = w["grid"]
tk, dk = np.asarray(w["tau_k"]), np.asarray(w["d_k"])
A = grid.anchor_operator(tk)
z = np.empty(len(tk))
for k in range(len(tk)):
keep = np.arange(len(tk)) != k
mu, S = linear_posterior(grid, h, tk[keep], dk[keep])
m = A[k] @ mu
v = A[k] @ S @ A[k] + h.sigma_a_ms**2
z[k] = (dk[k] - m) / np.sqrt(v)
out.append(z)
return out