ballast-repro / tests /test_spde.py
txus's picture
Upload folder using huggingface_hub
35f2be5 verified
Raw
History Blame Contribute Delete
6.53 kB
"""Exactness checks for the SPDE formulation -- the machinery behind Claim 2.
These are *analytic* comparisons (not Monte Carlo): the SPDE propagation is
linear-Gaussian, so the joint law it induces over the field at future times can
be written in closed form and compared to the dense GP built from k_tHelm.
"""
import jax
import jax.numpy as jnp
import numpy as np
jax.config.update("jax_enable_x64", True)
from ballast.gp import posterior_ext_state
from ballast.kernels import HelmParams, k_helm_mat, k_thelm_mat
from ballast.spde import make_ops, temporal_matrices
P = HelmParams(
phi_ls=0.8, phi_var=0.5, psi_ls=0.5, psi_var=0.5, time_ls=2.5, time_var=1.0
)
def _grid(n=3):
xs = jnp.linspace(-1.0, 1.0, n)
X, Y = jnp.meshgrid(xs, xs, indexing="ij")
return jnp.stack([X.reshape(-1), Y.reshape(-1)], -1)
def _full_matrices(R, p, dt):
"""Explicit Phi_full = I_{2N} (x) Phi and Q_full = K_space (x) Q for the
flattened state layout (i, c, b) -> i*4 + c*2 + b."""
phi, q, pinf = temporal_matrices(p.time_ls, p.time_var, dt)
Ks = k_helm_mat(R, R, p)
n2 = Ks.shape[0]
return (
jnp.kron(jnp.eye(n2), phi),
jnp.kron(Ks, q),
jnp.kron(Ks, pinf),
)
def _spde_joint_cov(R, p, dt, n_steps, Sigma0, mu0):
"""Joint mean/cov of the f-component at steps 0..n_steps under the SPDE.
Propagates the Gaussian analytically:
mu_{k+1} = Phi_full mu_k
Var_{k+1} = Phi_full Var_k Phi_full^T + Q_full
Cov(X_j,X_i) = Phi_full^{j-i} Var_i (j > i)
"""
Phi_f, Q_f, _ = _full_matrices(R, p, dt)
d = Phi_f.shape[0]
mus = [mu0]
vars_ = [Sigma0]
for _ in range(n_steps):
mus.append(Phi_f @ mus[-1])
vars_.append(Phi_f @ vars_[-1] @ Phi_f.T + Q_f)
nT = n_steps + 1
C = jnp.zeros((nT * d, nT * d))
for i in range(nT):
for j in range(nT):
if j >= i:
blk = jnp.linalg.matrix_power(Phi_f, j - i) @ vars_[i]
C = C.at[j * d : (j + 1) * d, i * d : (i + 1) * d].set(blk)
else:
blk = vars_[j] @ jnp.linalg.matrix_power(Phi_f, i - j).T
C = C.at[j * d : (j + 1) * d, i * d : (i + 1) * d].set(blk)
mu = jnp.concatenate(mus)
# select the f-component (b = 0) of every (location, velocity component)
sel = jnp.arange(d).reshape(-1, 2)[:, 0]
sel_all = jnp.concatenate([sel + k * d for k in range(nT)])
return mu[sel_all], C[jnp.ix_(sel_all, sel_all)]
def test_prior_matches_dense_gp():
"""SPDE prior started at equilibrium reproduces k_tHelm exactly."""
R = _grid(3)
dt, n_steps = 0.37, 4
_, _, Pinf_full = _full_matrices(R, P, dt)
d = Pinf_full.shape[0]
mu, C = _spde_joint_cov(R, P, dt, n_steps, Pinf_full, jnp.zeros(d))
times = jnp.arange(n_steps + 1) * dt
Rr = jnp.tile(R, (n_steps + 1, 1))
tr = jnp.repeat(times, R.shape[0])
K = k_thelm_mat(Rr, tr, Rr, tr, P)
np.testing.assert_allclose(mu, 0.0, atol=1e-12)
np.testing.assert_allclose(C, K, rtol=1e-8, atol=1e-10)
def test_posterior_sampling_is_exact_with_nongridded_observations():
"""The Sec. 4.1 scheme is exact: extended-state posterior at t_m + SPDE
propagation == dense GP posterior at future times, even though the
observations sit at non-gridded (Lagrangian) locations.
This is the core correctness claim of BALLAST's sampler, and the reason it
can avoid filtering over the observation locations.
"""
key = jax.random.PRNGKey(0)
R = _grid(3)
sigma = 0.1
dt, n_steps, t_m = 0.37, 4, 1.5
# observations at random NON-grid locations, all strictly before t_m
k1, k2, k3 = jax.random.split(key, 3)
S_obs = jax.random.uniform(k1, (7, 2), minval=-1.4, maxval=1.4)
t_obs = jax.random.uniform(k2, (7,), minval=0.0, maxval=t_m)
y_obs = jax.random.normal(k3, (7, 2))
# --- SPDE route: posterior of the extended state at t_m, then propagate
mean, chol = posterior_ext_state(S_obs, t_obs, y_obs, R, t_m, P, sigma, jitter=0.0)
Sigma0 = chol @ chol.T
mu_s, C_s = _spde_joint_cov(R, P, dt, n_steps, Sigma0, mean)
# --- dense route: GP posterior directly at R x future times
times = t_m + jnp.arange(n_steps + 1) * dt
Rr = jnp.tile(R, (n_steps + 1, 1))
tr = jnp.repeat(times, R.shape[0])
K_oo = k_thelm_mat(S_obs, t_obs, S_obs, t_obs, P) + sigma**2 * jnp.eye(14)
K_ot = k_thelm_mat(S_obs, t_obs, Rr, tr, P)
K_tt = k_thelm_mat(Rr, tr, Rr, tr, P)
sol = jnp.linalg.solve(K_oo, K_ot)
mu_d = sol.T @ y_obs.reshape(-1)
C_d = K_tt - K_ot.T @ sol
np.testing.assert_allclose(mu_s, mu_d, rtol=1e-6, atol=1e-9)
np.testing.assert_allclose(C_s, C_d, rtol=1e-6, atol=1e-9)
def test_sampler_empirical_moments():
"""End-to-end: the actual sampling code path reproduces the analytic posterior."""
from ballast.gp import sample_ext_state
from ballast.spde import propagate
key = jax.random.PRNGKey(2)
R = _grid(2)
sigma, dt, n_steps, t_m = 0.1, 0.25, 3, 1.0
ops = make_ops(R, P, dt, jitter=0.0)
k1, k2, k3 = jax.random.split(key, 3)
S_obs = jax.random.uniform(k1, (5, 2), minval=-1.0, maxval=1.0)
t_obs = jax.random.uniform(k2, (5,), minval=0.0, maxval=t_m)
y_obs = jax.random.normal(k3, (5, 2))
mean, chol = posterior_ext_state(S_obs, t_obs, y_obs, R, t_m, P, sigma, jitter=1e-12)
n = 40000
keys = jax.random.split(jax.random.PRNGKey(7), n)
def one(k):
ka, kb = jax.random.split(k)
X0 = sample_ext_state(ka, mean, chol, R.shape[0])
return propagate(X0, kb, ops, n_steps)[-1].reshape(-1)
draws = jax.vmap(one)(keys)
emp_mu = draws.mean(0)
emp_cov = jnp.cov(draws.T)
_, C_an = _spde_joint_cov(
R, P, dt, n_steps, chol @ chol.T, mean
)
mu_an, _ = _spde_joint_cov(R, P, dt, n_steps, chol @ chol.T, mean)
d = 2 * R.shape[0]
mu_last = mu_an[-d:]
C_last = C_an[-d:, -d:]
# Statistical tolerances: fixed rtol/atol are meaningless here because the
# small off-diagonal covariance entries are dominated by Monte Carlo noise.
se_mu = jnp.sqrt(jnp.diag(C_last) / n)
assert jnp.all(jnp.abs(emp_mu - mu_last) < 5 * se_mu), "sample mean off"
# SE of an empirical covariance entry: sqrt((C_ii C_jj + C_ij^2)/n)
d_ = jnp.diag(C_last)
se_cov = jnp.sqrt((d_[:, None] * d_[None, :] + C_last**2) / n)
z = jnp.abs(emp_cov - C_last) / se_cov
assert z.max() < 5.0, f"max z-score {z.max():.2f} between empirical and analytic cov"