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