Files
ML-Porosity/ml_porosity/registration/sampler.py
lamlvh cee2ff0859 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>
2026-10-27 06:03:33 +00:00

105 lines
4.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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)