Files
ML-Porosity/tests/test_registration.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

263 lines
12 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.
import numpy as np
import pytest
from ml_porosity.data.wavelet import convolve_same, ricker, rotate_phase
from ml_porosity.registration.labels import invert_warps, labels_for_warps
from ml_porosity.registration.sampler import ess, sample_warps, temper
from ml_porosity.registration.smc import (TiePosterior, ess_moves, next_gamma, phase_basis, phase_wavelet,
residual_kappa, smc_fit_phase, smc_tie_posterior)
from ml_porosity.registration.tie_likelihood import (fine_wavelet, fit_phase, phase_loglik, profile_loglik,
synth_for_warps)
from ml_porosity.registration.ties import clean_monotone, tie_b3a, tie_b3b, warp_errors
from ml_porosity.registration.warp_prior import WarpGrid, WarpHyper, kernel_matrix
PHASES = np.arange(-180, 180, 15)
def test_invert_warps_linear_map():
tau = np.arange(400.0, 1300.1, 4.0)
t_out = np.array([350.0, 600.0, 1000.0, 1500.0])
T = invert_warps(np.stack([1.1 * tau + 5, tau - 20]), tau, t_out)
np.testing.assert_allclose(T[0, 1:3], (t_out[1:3] - 5) / 1.1)
np.testing.assert_allclose(T[1, 1:3], t_out[1:3] + 20)
assert np.isnan(T[:, [0, 3]]).all()
def test_labels_for_shifted_warps():
tau = np.arange(400.0, 1300.1, 0.5)
t_out = np.arange(600.0, 1100.1, 4.0)
lab = labels_for_warps(tau, np.sin(tau / 30.0), np.stack([tau, tau + 8.0]), t_out)
np.testing.assert_allclose(lab[0], np.sin(t_out / 30.0), atol=1e-12)
np.testing.assert_allclose(lab[1], np.sin((t_out - 8.0) / 30.0), atol=1e-12)
def test_sample_warps_honour_tight_anchors():
grid = WarpGrid(400.0, 1300.0, 4.0)
h = WarpHyper(m_g=0.0, sigma_g=0.1, ell_ms=70.0, sigma_b_ms=20.0, sigma_a_ms=0.5)
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ np.random.default_rng(3).standard_normal(grid.n)
b = 15.0
tau_k = np.array([450.0, 610.0, 800.0, 950.0, 1200.0])
t_k = grid.t_of_tau(b, g, tau_k)[0]
out = sample_warps(grid, h, tau_k, t_k, n_samples=32, g_max=1.0, rng=np.random.default_rng(0))
T = grid.t_of_tau(out["b"], out["g"], tau_k)
assert np.sqrt(np.mean((T - t_k) ** 2)) < 2 * h.sigma_a_ms # posterior ≈ σ_a; prior ≥ σ_b = 20 ms
mid = np.array([530.0, 875.0, 1075.0])
err = np.abs(grid.t_of_tau(out["b"], out["g"], mid).mean(0) - grid.t_of_tau(b, g, mid)[0])
assert err.max() < 0.5 * h.sigma_b_ms
def test_temper_equal_loglik_keeps_gamma_one():
lw, g, e = temper(np.full(64, -3.0))
assert g == 1.0 and e == pytest.approx(64)
np.testing.assert_allclose(lw, -np.log(64))
def test_temper_largest_gamma_with_target_ess():
ll = 50 * np.random.default_rng(0).standard_normal(64)
lw, g, e = temper(ll, min_frac=0.25, tol=1e-3)
assert 0.0 < g < 1.0 and e >= 16 - 1e-9
assert ess((g + 1e-3) * ll) < 16
np.testing.assert_allclose(lw, g * ll - np.logaddexp.reduce(g * ll))
def test_clean_monotone_and_point_ties():
tau_k = np.array([800.0, 500.0, 600.0, 700.0, 1000.0])
t_k = np.array([820.0, 510.0, 620.0, 615.0, 1030.0])
tk, ttk = clean_monotone(tau_k, t_k)
assert len(tk) == 4 and np.all(np.diff(tk) > 0) and np.all(np.diff(ttk) > 0)
tau = np.arange(400.0, 1300.1, 0.5)
np.testing.assert_allclose(tie_b3a(tau_k, t_k, tau), tau + 10.0)
t = tie_b3b(tau_k, t_k, tau)
assert np.all(np.diff(t) > 0)
np.testing.assert_allclose(np.interp(tk, tau, t), ttk, atol=1e-6)
def test_warp_errors_perfect_and_bracketing():
tau = np.arange(400.0, 1300.1, 1.0)
t_true = tau + 10.0
t_eval = np.arange(600.0, 1100.1, 4.0)
assert warp_errors(t_true[None], tau, t_true, t_eval)["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9)
e = warp_errors(t_true[None] + np.linspace(-5, 5, 21)[:, None], tau, t_true, t_eval)
assert e["warp_rmse_ms"] == pytest.approx(0.0, abs=1e-9) and e["warp_cov90"] == 1.0
assert e["warp_width90_ms"] == pytest.approx(9.0)
def synth(seed, n=300):
rng = np.random.default_rng(seed)
return convolve_same(rng.standard_normal(n) * (rng.random(n) < 0.3), ricker(30))
def test_profile_loglik_respects_polarity():
s = synth(0)
seis = s + 0.05 * s.std() * np.random.default_rng(1).standard_normal(len(s))
ll = profile_loglik(np.stack([s, -s, 2.0 * s]), seis)
assert ll[0] > ll[1]
assert ll[2] == pytest.approx(ll[0])
@pytest.mark.parametrize("phase", [0, 45, -90])
def test_fit_phase_recovers_constant_rotation(phase):
rng = np.random.default_rng(2)
ll, ok = [], []
for w in range(2):
s = synth(10 + w)
seis = rotate_phase(s, phase) + 0.1 * s.std() * rng.standard_normal(len(s))
bank = np.stack([np.roll(s, k) for k in (-1, 0, 1)]) # warp samples around the true warp
ll.append(phase_loglik(bank, seis, PHASES))
ok.append(np.ones(3, bool))
assert PHASES[fit_phase(ll, ok, PHASES)] == phase
def tie_toy(seed: int = 0, phase: float = 0.0) -> dict:
"""A toy well: true warp drawn from the prior, blocky AI, seismic = synthetic (30 Hz Ricker rotated by `phase`)
+ 10% white noise, 4 anchors with σ_a = 3 ms."""
rng = np.random.default_rng(seed)
grid = WarpGrid(400.0, 1000.0, 4.0)
h = WarpHyper(m_g=0.0, sigma_g=0.05, ell_ms=80.0, sigma_b_ms=20.0, sigma_a_ms=3.0)
K = kernel_matrix(grid.tau, grid.tau, h.sigma_g, h.ell_ms, h.kernel)
g = np.linalg.cholesky(K + 1e-8 * np.eye(grid.n)) @ rng.standard_normal(grid.n)
tau_fine = np.arange(grid.tau[0], grid.tau[-1] + 0.25, 0.5)
ai = np.exp(np.cumsum(0.1 * rng.standard_normal(len(tau_fine)) * (rng.random(len(tau_fine)) < 0.04)))
t_fine, t_out = np.arange(300.0, 1100.0, 0.5), np.arange(500.0, 900.1, 4.0)
w_fine = fine_wavelet(rotate_phase(ricker(30), phase), 8)
tau_k = np.linspace(450.0, 950.0, 4)
t_k = grid.t_of_tau(5.0, g, tau_k)[0] + h.sigma_a_ms * rng.standard_normal(4)
t_true = grid.t_of_tau(5.0, g, tau=tau_fine)[0]
s = synth_for_warps(tau_fine, ai, t_true, t_fine, t_out, w_fine)[0]
seis = s + 0.1 * s.std() * rng.standard_normal(len(s))
T = TiePosterior(grid, h, tau_k, t_k, 1.0, tau_fine, ai, t_fine, t_out, w_fine, seis, (t_out[0], t_out[-1]))
return dict(grid=grid, h=h, T=T, tau_fine=tau_fine, ai=ai, t_fine=t_fine, t_out=t_out, w_fine=w_fine,
tau_k=tau_k, t_k=t_k, t_true=t_true)
def anchor_samples(d: dict, n: int, seed: int) -> np.ndarray:
return sample_warps(d["grid"], d["h"], d["tau_k"], d["t_k"], n, 1.0, np.random.default_rng(seed))["u"]
def test_tie_posterior_synth_matches_synth_for_warps():
d = tie_toy()
T, U = d["T"], anchor_samples(d, 8, 1)
np.testing.assert_allclose(T.u(T.z(U)), U, atol=1e-8)
Tf = d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"])
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)): # also a longer wavelet
ref = synth_for_warps(d["tau_fine"], d["ai"], Tf, d["t_fine"], d["t_out"], w)
np.testing.assert_allclose(T.with_wavelet(w).synth(U), ref, rtol=1e-9, atol=1e-12)
np.testing.assert_array_equal(T.w_fine, d["w_fine"])
def test_residual_kappa_white_vs_band_limited_noise():
rng = np.random.default_rng(4)
s = synth(20, n=2000)
nb = convolve_same(rng.standard_normal(len(s)), ricker(30))
assert residual_kappa(s, s + 0.5 * s.std() * rng.standard_normal(len(s))) < 1.2
assert residual_kappa(s, s + 0.5 * s.std() * nb / nb.std()) > 1.5
def test_next_gamma_largest_step_with_target_ess():
ll = 30 * np.random.default_rng(5).standard_normal(128)
g = next_gamma(ll, 0.2, 1.0, 0.5)
assert 0.2 < g < 1.0 and ess((g - 0.2) * ll) >= 64 - 1e-6
assert ess((g - 0.2 + 1e-3) * ll) < 64
assert next_gamma(np.zeros(128), 0.2, 0.7) == 0.7
@pytest.mark.parametrize("phase", [-45, 0, 30, 90])
def test_phase_basis_is_exact_rotation(phase):
w0 = ricker(30)
np.testing.assert_allclose(phase_wavelet(phase_basis(w0, 8), phase), fine_wavelet(rotate_phase(w0, phase), 8),
atol=1e-12)
def test_smc_concentrates_on_true_warp():
d = tie_toy(seed=2)
T, U0 = d["T"], anchor_samples(d, 64, 3)
res = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
err = lambda U: warp_errors(d["grid"].t_of_tau(U[:, 0], U[:, 1:], tau=d["tau_fine"]), d["tau_fine"],
d["t_true"], d["t_out"])["warp_rmse_ms"]
assert err(T.u(res["Z"][1.0])) < 0.5 * err(U0)
assert np.all(np.isfinite(T.parts(res["Z"][1.0])[0]))
assert res["stages"][-1]["gamma"] == 1.0 and all(s["ess"] >= 32 - 1e-6 for s in res["stages"])
assert np.isfinite(res["logZ"][0.3]) and np.isfinite(res["logZ"][1.0])
def test_smc_fit_phase_recovers_rotation():
wells = [tie_toy(seed=s, phase=30.0) for s in (5, 6)]
Z0s = [d["T"].z(anchor_samples(d, 32, i)) for i, d in enumerate(wells)]
phi, info = smc_fit_phase([d["T"] for d in wells], Z0s, phase_basis(ricker(30), 8), 0.0, [0])
assert abs(phi - 30.0) < 10.0 and not info["edge"]
def torch_tie(T):
torch = pytest.importorskip("torch")
from ml_porosity.registration.smc_torch import TiePosteriorTorch
return TiePosteriorTorch(T, "cuda:1" if torch.cuda.device_count() > 1 else "cpu")
def test_torch_tie_posterior_matches_cpu():
d = tie_toy()
T = d["T"]
G = torch_tie(T)
Z = T.z(anchor_samples(d, 8, 1))
Z = np.vstack([Z, 40.0 * Z[:2]]) # two particles violate |g| ≤ g_max
for w in (d["w_fine"], fine_wavelet(rotate_phase(ricker(25, length_ms=200.0), 40.0), 8)):
Tw, Gw = T.with_wavelet(w), G.with_wavelet(w)
np.testing.assert_allclose(Gw.synth(T.u(Z)), Tw.synth(T.u(Z)), rtol=1e-9, atol=1e-12)
(bc, lc), (bg, lg) = Tw.parts(Z), Gw.parts(Z)
assert not np.isfinite(bc[-2:]).any()
np.testing.assert_array_equal(np.isfinite(bg), np.isfinite(bc))
np.testing.assert_array_equal(np.isfinite(lg), np.isfinite(lc))
ok = np.isfinite(bc)
np.testing.assert_allclose(bg[ok], bc[ok], rtol=1e-10)
np.testing.assert_allclose(lg[ok], lc[ok], rtol=1e-10)
assert Gw.n_eval == Tw.n_eval
np.testing.assert_allclose(Gw.reference(Z[:8].mean(0), 0.5)[1], Tw.reference(Z[:8].mean(0), 0.5)[1],
rtol=1e-9, atol=1e-12)
def test_torch_ess_moves_match_cpu():
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
T = d["T"]
G = torch_tie(T)
Z = T.z(anchor_samples(d, 32, 3))
base, ll = T.parts(Z)
ref = T.reference(Z.mean(0), 0.3)
oc = ess_moves(T, Z, base, ll, 0.3, ref, 3, np.random.default_rng(7))
og = smc_torch.ess_moves(G, *map(G.tensor, (Z, base, ll)), 0.3, tuple(map(G.tensor, ref)), 3,
np.random.default_rng(7))
for a, b in zip(oc[:3], og[:3]):
np.testing.assert_allclose(b.cpu().numpy(), a, rtol=1e-8, atol=1e-10)
assert og[3] == oc[3]
def test_torch_ess_moves_memory_bounded():
"""Each call captures a new CUDA graph; retained memory must not grow with the number of calls."""
torch = pytest.importorskip("torch")
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
G = torch_tie(d["T"])
if G.device.type != "cuda":
pytest.skip("requires CUDA")
Z = G.tensor(d["T"].z(anchor_samples(d, 32, 3)))
base, ll = G.parts_t(Z)
ref = G.reference_t(Z.mean(0), 0.3)
run = lambda: smc_torch.ess_moves(G, Z, base, ll, 0.3, ref, 1, np.random.default_rng(0))
run()
r0 = torch.cuda.memory_reserved(G.device)
for _ in range(5):
run()
assert torch.cuda.memory_reserved(G.device) == r0
def test_torch_smc_matches_cpu():
from ml_porosity.registration import smc_torch
d = tie_toy(seed=2)
T, U0 = d["T"], anchor_samples(d, 64, 3)
rc = smc_tie_posterior(T, T.z(U0), [0.3, 1.0], np.random.default_rng(4))
rg = smc_torch.smc_tie_posterior(torch_tie(T), T.z(U0), [0.3, 1.0], np.random.default_rng(4))
np.testing.assert_allclose([s["gamma"] for s in rg["stages"]], [s["gamma"] for s in rc["stages"]], rtol=1e-9)
for g in (0.3, 1.0):
assert rg["logZ"][g] == pytest.approx(rc["logZ"][g], rel=1e-9)
np.testing.assert_allclose(rg["Z"][g], rc["Z"][g], atol=1e-7)