"""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