txus commited on
Commit
35f2be5
·
verified ·
1 Parent(s): de807b8

Upload folder using huggingface_hub

Browse files
tests/__pycache__/test_kernels.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (15.5 kB). View file
 
tests/__pycache__/test_spde.cpython-312-pytest-9.1.1.pyc ADDED
Binary file (14.5 kB). View file
 
tests/test_kernels.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Correctness checks for the analytic kernels."""
2
+
3
+ import jax
4
+ import jax.numpy as jnp
5
+ import numpy as np
6
+ import pytest
7
+
8
+ jax.config.update("jax_enable_x64", True)
9
+
10
+ from ballast.kernels import (
11
+ HelmParams,
12
+ k_ext_full,
13
+ k_helm_mat,
14
+ k_thelm_mat,
15
+ matern32_blocks,
16
+ )
17
+
18
+ P = HelmParams(
19
+ phi_ls=0.8, phi_var=0.5, psi_ls=0.5, psi_var=0.5, time_ls=2.5, time_var=1.0
20
+ )
21
+
22
+
23
+ def _m32(t, t2, ls, var):
24
+ """Reference Matern-3/2 written so autodiff is valid (no clipped distance)."""
25
+ r = jnp.abs(t - t2)
26
+ lam = jnp.sqrt(3.0) / ls
27
+ return var * (1 + lam * r) * jnp.exp(-lam * r)
28
+
29
+
30
+ def test_matern32_derivatives_match_autodiff():
31
+ """Analytic d_t, d_t', d^2_tt' blocks agree with autodiff away from t=t'."""
32
+ ts = jnp.array([0.0, 0.3, 1.7, 4.2])
33
+ ts2 = jnp.array([0.5, 2.1, 3.3])
34
+ M = matern32_blocks(ts, ts2, P.time_ls, P.time_var)
35
+
36
+ k = jax.vmap(lambda a: jax.vmap(lambda b: _m32(a, b, P.time_ls, P.time_var))(ts2))(ts)
37
+ dt = jax.grad(_m32, argnums=0)
38
+ dt2 = jax.grad(_m32, argnums=1)
39
+ d2 = jax.grad(jax.grad(_m32, argnums=0), argnums=1)
40
+
41
+ f = lambda g: jax.vmap(lambda a: jax.vmap(lambda b: g(a, b, P.time_ls, P.time_var))(ts2))(ts)
42
+ np.testing.assert_allclose(M[..., 0, 0], k, rtol=1e-10)
43
+ np.testing.assert_allclose(M[..., 1, 0], f(dt), rtol=1e-8)
44
+ np.testing.assert_allclose(M[..., 0, 1], f(dt2), rtol=1e-8)
45
+ np.testing.assert_allclose(M[..., 1, 1], f(d2), rtol=1e-8)
46
+
47
+
48
+ def test_matern32_second_derivative_at_zero():
49
+ """Paper Sec. H.2: d^2_{tt'} k at t=t' must be 3 sigma^2/l^2, not 0.
50
+
51
+ This is the value GPJax-style clipped-distance autodiff silently returns as
52
+ zero; it is also exactly P_inf[1,1] in the SPDE formulation, i.e. Var(d_t f).
53
+ """
54
+ t = jnp.array([1.0])
55
+ M = matern32_blocks(t, t, 1.0, 1.0)
56
+ assert np.isclose(M[0, 0, 1, 1], 3.0)
57
+ M2 = matern32_blocks(t, t, P.time_ls, P.time_var)
58
+ assert np.isclose(M2[0, 0, 1, 1], 3.0 * P.time_var / P.time_ls**2)
59
+
60
+
61
+ def test_matern32_finite_difference():
62
+ """Independent finite-difference check of the mixed second derivative."""
63
+ # h chosen to balance the O(h^2) truncation error of the 4-point stencil
64
+ # against O(eps/h^2) round-off; 1e-5 leaves ~1e-4 relative truncation error
65
+ # on a value of ~5e-3 and would fail a 1e-4 tolerance for benign reasons.
66
+ h = 1e-3
67
+ a, b = 1.0, 2.4
68
+ num = (
69
+ _m32(a + h, b + h, P.time_ls, P.time_var)
70
+ - _m32(a + h, b - h, P.time_ls, P.time_var)
71
+ - _m32(a - h, b + h, P.time_ls, P.time_var)
72
+ + _m32(a - h, b - h, P.time_ls, P.time_var)
73
+ ) / (4 * h * h)
74
+ ana = matern32_blocks(jnp.array([a]), jnp.array([b]), P.time_ls, P.time_var)[0, 0, 1, 1]
75
+ assert np.isclose(num, ana, rtol=1e-4)
76
+
77
+
78
+ def _helm_field_cov_reference(S, S2, p):
79
+ """Helmholtz kernel rebuilt by autodiff of the potential/stream construction.
80
+
81
+ F_1 = d_1 Phi + d_2 Psi, F_2 = d_2 Phi - d_1 Psi, so
82
+ Cov(F_a(x), F_b(x')) is assembled from mixed second derivatives of k_Phi, k_Psi.
83
+ """
84
+ kphi = lambda x, y: p.phi_var * jnp.exp(-0.5 * jnp.sum((x - y) ** 2) / p.phi_ls**2)
85
+ kpsi = lambda x, y: p.psi_var * jnp.exp(-0.5 * jnp.sum((x - y) ** 2) / p.psi_ls**2)
86
+ Hphi = jax.jacfwd(jax.jacrev(kphi, argnums=0), argnums=1)
87
+ Hpsi = jax.jacfwd(jax.jacrev(kpsi, argnums=0), argnums=1)
88
+
89
+ def cov(x, y):
90
+ A, B = Hphi(x, y), Hpsi(x, y)
91
+ return jnp.array(
92
+ [
93
+ [A[0, 0] + B[1, 1], A[0, 1] - B[1, 0]],
94
+ [A[1, 0] - B[0, 1], A[1, 1] + B[0, 0]],
95
+ ]
96
+ )
97
+
98
+ return jax.vmap(lambda x: jax.vmap(lambda y: cov(x, y))(S2))(S)
99
+
100
+
101
+ def test_helmholtz_matches_autodiff_construction():
102
+ S = jnp.array([[0.0, 0.0], [0.4, -0.7], [1.2, 0.3]])
103
+ S2 = jnp.array([[0.1, 0.2], [-0.5, 0.9]])
104
+ ref = _helm_field_cov_reference(S, S2, P) # (3, 2, 2, 2)
105
+ got = k_helm_mat(S, S2, P).reshape(3, 2, 2, 2).transpose(0, 2, 1, 3)
106
+ # got is (i, j, c, c') after the transpose of the (i,c,j,c') flattening
107
+ np.testing.assert_allclose(got.transpose(0, 1, 2, 3), ref, rtol=1e-8, atol=1e-12)
108
+
109
+
110
+ def test_gram_matrices_are_psd():
111
+ key = jax.random.PRNGKey(0)
112
+ S = jax.random.uniform(key, (12, 2), minval=-2, maxval=2)
113
+ t = jnp.linspace(0, 5, 12)
114
+ for K in (k_thelm_mat(S, t, S, t, P), k_ext_full(S, t, P), k_helm_mat(S, S, P)):
115
+ w = jnp.linalg.eigvalsh(0.5 * (K + K.T))
116
+ assert w.min() > -1e-8, f"min eigenvalue {w.min()}"
117
+
118
+
119
+ def test_extended_kernel_blocks_are_consistent():
120
+ """The f-block of the extended kernel is exactly the plain kernel."""
121
+ key = jax.random.PRNGKey(1)
122
+ S = jax.random.uniform(key, (5, 2), minval=-1, maxval=1)
123
+ t = jnp.linspace(0, 3, 5)
124
+ E = k_ext_full(S, t, P).reshape(5, 2, 2, 5, 2, 2)
125
+ plain = k_thelm_mat(S, t, S, t, P).reshape(5, 2, 5, 2)
126
+ np.testing.assert_allclose(E[:, :, 0, :, :, 0], plain, rtol=1e-10)
tests/test_spde.py ADDED
@@ -0,0 +1,176 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Exactness checks for the SPDE formulation -- the machinery behind Claim 2.
2
+
3
+ These are *analytic* comparisons (not Monte Carlo): the SPDE propagation is
4
+ linear-Gaussian, so the joint law it induces over the field at future times can
5
+ be written in closed form and compared to the dense GP built from k_tHelm.
6
+ """
7
+
8
+ import jax
9
+ import jax.numpy as jnp
10
+ import numpy as np
11
+
12
+ jax.config.update("jax_enable_x64", True)
13
+
14
+ from ballast.gp import posterior_ext_state
15
+ from ballast.kernels import HelmParams, k_helm_mat, k_thelm_mat
16
+ from ballast.spde import make_ops, temporal_matrices
17
+
18
+ P = HelmParams(
19
+ phi_ls=0.8, phi_var=0.5, psi_ls=0.5, psi_var=0.5, time_ls=2.5, time_var=1.0
20
+ )
21
+
22
+
23
+ def _grid(n=3):
24
+ xs = jnp.linspace(-1.0, 1.0, n)
25
+ X, Y = jnp.meshgrid(xs, xs, indexing="ij")
26
+ return jnp.stack([X.reshape(-1), Y.reshape(-1)], -1)
27
+
28
+
29
+ def _full_matrices(R, p, dt):
30
+ """Explicit Phi_full = I_{2N} (x) Phi and Q_full = K_space (x) Q for the
31
+ flattened state layout (i, c, b) -> i*4 + c*2 + b."""
32
+ phi, q, pinf = temporal_matrices(p.time_ls, p.time_var, dt)
33
+ Ks = k_helm_mat(R, R, p)
34
+ n2 = Ks.shape[0]
35
+ return (
36
+ jnp.kron(jnp.eye(n2), phi),
37
+ jnp.kron(Ks, q),
38
+ jnp.kron(Ks, pinf),
39
+ )
40
+
41
+
42
+ def _spde_joint_cov(R, p, dt, n_steps, Sigma0, mu0):
43
+ """Joint mean/cov of the f-component at steps 0..n_steps under the SPDE.
44
+
45
+ Propagates the Gaussian analytically:
46
+ mu_{k+1} = Phi_full mu_k
47
+ Var_{k+1} = Phi_full Var_k Phi_full^T + Q_full
48
+ Cov(X_j,X_i) = Phi_full^{j-i} Var_i (j > i)
49
+ """
50
+ Phi_f, Q_f, _ = _full_matrices(R, p, dt)
51
+ d = Phi_f.shape[0]
52
+ mus = [mu0]
53
+ vars_ = [Sigma0]
54
+ for _ in range(n_steps):
55
+ mus.append(Phi_f @ mus[-1])
56
+ vars_.append(Phi_f @ vars_[-1] @ Phi_f.T + Q_f)
57
+
58
+ nT = n_steps + 1
59
+ C = jnp.zeros((nT * d, nT * d))
60
+ for i in range(nT):
61
+ for j in range(nT):
62
+ if j >= i:
63
+ blk = jnp.linalg.matrix_power(Phi_f, j - i) @ vars_[i]
64
+ C = C.at[j * d : (j + 1) * d, i * d : (i + 1) * d].set(blk)
65
+ else:
66
+ blk = vars_[j] @ jnp.linalg.matrix_power(Phi_f, i - j).T
67
+ C = C.at[j * d : (j + 1) * d, i * d : (i + 1) * d].set(blk)
68
+ mu = jnp.concatenate(mus)
69
+ # select the f-component (b = 0) of every (location, velocity component)
70
+ sel = jnp.arange(d).reshape(-1, 2)[:, 0]
71
+ sel_all = jnp.concatenate([sel + k * d for k in range(nT)])
72
+ return mu[sel_all], C[jnp.ix_(sel_all, sel_all)]
73
+
74
+
75
+ def test_prior_matches_dense_gp():
76
+ """SPDE prior started at equilibrium reproduces k_tHelm exactly."""
77
+ R = _grid(3)
78
+ dt, n_steps = 0.37, 4
79
+ _, _, Pinf_full = _full_matrices(R, P, dt)
80
+ d = Pinf_full.shape[0]
81
+ mu, C = _spde_joint_cov(R, P, dt, n_steps, Pinf_full, jnp.zeros(d))
82
+
83
+ times = jnp.arange(n_steps + 1) * dt
84
+ Rr = jnp.tile(R, (n_steps + 1, 1))
85
+ tr = jnp.repeat(times, R.shape[0])
86
+ K = k_thelm_mat(Rr, tr, Rr, tr, P)
87
+
88
+ np.testing.assert_allclose(mu, 0.0, atol=1e-12)
89
+ np.testing.assert_allclose(C, K, rtol=1e-8, atol=1e-10)
90
+
91
+
92
+ def test_posterior_sampling_is_exact_with_nongridded_observations():
93
+ """The Sec. 4.1 scheme is exact: extended-state posterior at t_m + SPDE
94
+ propagation == dense GP posterior at future times, even though the
95
+ observations sit at non-gridded (Lagrangian) locations.
96
+
97
+ This is the core correctness claim of BALLAST's sampler, and the reason it
98
+ can avoid filtering over the observation locations.
99
+ """
100
+ key = jax.random.PRNGKey(0)
101
+ R = _grid(3)
102
+ sigma = 0.1
103
+ dt, n_steps, t_m = 0.37, 4, 1.5
104
+
105
+ # observations at random NON-grid locations, all strictly before t_m
106
+ k1, k2, k3 = jax.random.split(key, 3)
107
+ S_obs = jax.random.uniform(k1, (7, 2), minval=-1.4, maxval=1.4)
108
+ t_obs = jax.random.uniform(k2, (7,), minval=0.0, maxval=t_m)
109
+ y_obs = jax.random.normal(k3, (7, 2))
110
+
111
+ # --- SPDE route: posterior of the extended state at t_m, then propagate
112
+ mean, chol = posterior_ext_state(S_obs, t_obs, y_obs, R, t_m, P, sigma, jitter=0.0)
113
+ Sigma0 = chol @ chol.T
114
+ mu_s, C_s = _spde_joint_cov(R, P, dt, n_steps, Sigma0, mean)
115
+
116
+ # --- dense route: GP posterior directly at R x future times
117
+ times = t_m + jnp.arange(n_steps + 1) * dt
118
+ Rr = jnp.tile(R, (n_steps + 1, 1))
119
+ tr = jnp.repeat(times, R.shape[0])
120
+ K_oo = k_thelm_mat(S_obs, t_obs, S_obs, t_obs, P) + sigma**2 * jnp.eye(14)
121
+ K_ot = k_thelm_mat(S_obs, t_obs, Rr, tr, P)
122
+ K_tt = k_thelm_mat(Rr, tr, Rr, tr, P)
123
+ sol = jnp.linalg.solve(K_oo, K_ot)
124
+ mu_d = sol.T @ y_obs.reshape(-1)
125
+ C_d = K_tt - K_ot.T @ sol
126
+
127
+ np.testing.assert_allclose(mu_s, mu_d, rtol=1e-6, atol=1e-9)
128
+ np.testing.assert_allclose(C_s, C_d, rtol=1e-6, atol=1e-9)
129
+
130
+
131
+ def test_sampler_empirical_moments():
132
+ """End-to-end: the actual sampling code path reproduces the analytic posterior."""
133
+ from ballast.gp import sample_ext_state
134
+ from ballast.spde import propagate
135
+
136
+ key = jax.random.PRNGKey(2)
137
+ R = _grid(2)
138
+ sigma, dt, n_steps, t_m = 0.1, 0.25, 3, 1.0
139
+ ops = make_ops(R, P, dt, jitter=0.0)
140
+
141
+ k1, k2, k3 = jax.random.split(key, 3)
142
+ S_obs = jax.random.uniform(k1, (5, 2), minval=-1.0, maxval=1.0)
143
+ t_obs = jax.random.uniform(k2, (5,), minval=0.0, maxval=t_m)
144
+ y_obs = jax.random.normal(k3, (5, 2))
145
+ mean, chol = posterior_ext_state(S_obs, t_obs, y_obs, R, t_m, P, sigma, jitter=1e-12)
146
+
147
+ n = 40000
148
+ keys = jax.random.split(jax.random.PRNGKey(7), n)
149
+
150
+ def one(k):
151
+ ka, kb = jax.random.split(k)
152
+ X0 = sample_ext_state(ka, mean, chol, R.shape[0])
153
+ return propagate(X0, kb, ops, n_steps)[-1].reshape(-1)
154
+
155
+ draws = jax.vmap(one)(keys)
156
+ emp_mu = draws.mean(0)
157
+ emp_cov = jnp.cov(draws.T)
158
+
159
+ _, C_an = _spde_joint_cov(
160
+ R, P, dt, n_steps, chol @ chol.T, mean
161
+ )
162
+ mu_an, _ = _spde_joint_cov(R, P, dt, n_steps, chol @ chol.T, mean)
163
+ d = 2 * R.shape[0]
164
+ mu_last = mu_an[-d:]
165
+ C_last = C_an[-d:, -d:]
166
+
167
+ # Statistical tolerances: fixed rtol/atol are meaningless here because the
168
+ # small off-diagonal covariance entries are dominated by Monte Carlo noise.
169
+ se_mu = jnp.sqrt(jnp.diag(C_last) / n)
170
+ assert jnp.all(jnp.abs(emp_mu - mu_last) < 5 * se_mu), "sample mean off"
171
+
172
+ # SE of an empirical covariance entry: sqrt((C_ii C_jj + C_ij^2)/n)
173
+ d_ = jnp.diag(C_last)
174
+ se_cov = jnp.sqrt((d_[:, None] * d_[None, :] + C_last**2) / n)
175
+ z = jnp.abs(emp_cov - C_last) / se_cov
176
+ assert z.max() < 5.0, f"max z-score {z.max():.2f} between empirical and analytic cov"