Upload folder using huggingface_hub
Browse files- ballast/__init__.py +0 -0
- ballast/__pycache__/__init__.cpython-312.pyc +0 -0
- ballast/__pycache__/experiment.cpython-312.pyc +0 -0
- ballast/__pycache__/gp.cpython-312.pyc +0 -0
- ballast/__pycache__/kernels.cpython-312.pyc +0 -0
- ballast/__pycache__/policies.cpython-312.pyc +0 -0
- ballast/__pycache__/spde.cpython-312.pyc +0 -0
- ballast/__pycache__/trajectory.cpython-312.pyc +0 -0
- ballast/experiment.py +289 -0
- ballast/gp.py +197 -0
- ballast/kernels.py +187 -0
- ballast/policies.py +257 -0
- ballast/spde.py +119 -0
- ballast/trajectory.py +138 -0
ballast/__init__.py
ADDED
|
File without changes
|
ballast/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (147 Bytes). View file
|
|
|
ballast/__pycache__/experiment.cpython-312.pyc
ADDED
|
Binary file (16.2 kB). View file
|
|
|
ballast/__pycache__/gp.cpython-312.pyc
ADDED
|
Binary file (10.4 kB). View file
|
|
|
ballast/__pycache__/kernels.cpython-312.pyc
ADDED
|
Binary file (9.8 kB). View file
|
|
|
ballast/__pycache__/policies.cpython-312.pyc
ADDED
|
Binary file (12.6 kB). View file
|
|
|
ballast/__pycache__/spde.cpython-312.pyc
ADDED
|
Binary file (6.97 kB). View file
|
|
|
ballast/__pycache__/trajectory.cpython-312.pyc
ADDED
|
Binary file (8.73 kB). View file
|
|
|
ballast/experiment.py
ADDED
|
@@ -0,0 +1,289 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Active-learning campaign driver (paper Sec. 5.2 / 5.3).
|
| 2 |
+
|
| 3 |
+
A campaign deploys M Lagrangian observers, one every `deploy_every` units of
|
| 4 |
+
time, the first uniformly at random and the rest by the policy under test. Each
|
| 5 |
+
observer is advected by the *ground-truth* field from its release until the
|
| 6 |
+
terminal time T (or until it leaves the region) and measures every delta_obs.
|
| 7 |
+
|
| 8 |
+
Performance after m deployments is the average L2 error of the GP posterior
|
| 9 |
+
predictive mean field over the spatial grid and the full set of deployment
|
| 10 |
+
times, using all data those m observers collect over the whole campaign -- i.e.
|
| 11 |
+
"what would this campaign have bought me if I had stopped at m drifters".
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
from dataclasses import dataclass, field
|
| 17 |
+
from typing import Callable
|
| 18 |
+
|
| 19 |
+
import jax
|
| 20 |
+
import jax.numpy as jnp
|
| 21 |
+
import numpy as np
|
| 22 |
+
from scipy.optimize import minimize
|
| 23 |
+
|
| 24 |
+
from .gp import log_marginal_likelihood, posterior_ext_state, posterior_mean_field
|
| 25 |
+
from .kernels import HelmParams
|
| 26 |
+
from .policies import (
|
| 27 |
+
ballast_sample_utilities,
|
| 28 |
+
dist_sep_scores,
|
| 29 |
+
eig_utilities,
|
| 30 |
+
sobol_indices,
|
| 31 |
+
)
|
| 32 |
+
from .spde import make_ops, prior_sample
|
| 33 |
+
from .trajectory import Grid, advect, observe
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@dataclass
|
| 37 |
+
class Config:
|
| 38 |
+
T: float = 10.0
|
| 39 |
+
dt: float = 0.01
|
| 40 |
+
obs_every: int = 5 # delta_obs = 0.05
|
| 41 |
+
deploy_every: float = 0.5
|
| 42 |
+
n_deploy: int = 20 # 1 initial + 19 policy-chosen
|
| 43 |
+
sigma_obs: float = 0.1
|
| 44 |
+
n_samples: int = 20 # BALLAST J
|
| 45 |
+
grid_nx: int = 25
|
| 46 |
+
grid_ny: int = 25
|
| 47 |
+
x_lo: float = -2.0
|
| 48 |
+
x_hi: float = 2.0
|
| 49 |
+
y_lo: float = -2.0
|
| 50 |
+
y_hi: float = 2.0
|
| 51 |
+
chunk: int = 64
|
| 52 |
+
|
| 53 |
+
@property
|
| 54 |
+
def n_obs_total(self) -> int:
|
| 55 |
+
return int(round(self.T / self.dt)) // self.obs_every
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def obs_dt(self) -> float:
|
| 59 |
+
return self.dt * self.obs_every
|
| 60 |
+
|
| 61 |
+
def grid(self) -> Grid:
|
| 62 |
+
return Grid(
|
| 63 |
+
jnp.linspace(self.x_lo, self.x_hi, self.grid_nx),
|
| 64 |
+
jnp.linspace(self.y_lo, self.y_hi, self.grid_ny),
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
SYNTH_PARAMS = HelmParams(
|
| 69 |
+
phi_ls=0.8, phi_var=0.5, psi_ls=0.5, psi_var=0.5, time_ls=2.5, time_var=1.0
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
# Sec. H.3 optimisation bounds ("uniform priors with finite support")
|
| 73 |
+
SYNTH_BOUNDS = [(0.1, 1.0), (0.1, 1.0), (0.1, 1.0), (0.1, 1.0), (0.1, 3.0), (0.1, 3.0)]
|
| 74 |
+
SUNTANS_BOUNDS = [(0.1, 5.0), (10.0, 20.0), (0.1, 1.0), (0.1, 5.0), (0.1, 3.0), (10.0, 20.0)]
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def make_ground_truth(key, cfg: Config, p: HelmParams) -> jnp.ndarray:
|
| 78 |
+
"""Draw a synthetic ground-truth field from the temporal Helmholtz GP.
|
| 79 |
+
|
| 80 |
+
Exact draw via the SPDE prior (dense sampling of 25*25*1001 space-time points
|
| 81 |
+
would be a ~1.25M-dimensional Gaussian).
|
| 82 |
+
"""
|
| 83 |
+
grid = cfg.grid()
|
| 84 |
+
ops = make_ops(grid.R, p, cfg.dt)
|
| 85 |
+
n_steps = int(round(cfg.T / cfg.dt))
|
| 86 |
+
return prior_sample(key, grid.R, ops, n_steps)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def optimise_hypers(
|
| 90 |
+
S, t, y, cfg: Config, bounds, init: HelmParams, opt_noise: bool = True
|
| 91 |
+
):
|
| 92 |
+
"""L-BFGS-B fit of the GP hyperparameters (Algorithm 2 step 5, Sec. H.3).
|
| 93 |
+
|
| 94 |
+
Optimises in the natural parameterisation with box bounds, as the paper
|
| 95 |
+
describes ("manually-set bounds ... to mimic uniform priors with finite
|
| 96 |
+
support"). Falls back to the initial values if the optimiser fails.
|
| 97 |
+
"""
|
| 98 |
+
b = list(bounds) + ([(0.01, 1.0)] if opt_noise else [])
|
| 99 |
+
x0 = np.array(list(np.asarray(init.as_array())) + ([cfg.sigma_obs] if opt_noise else []))
|
| 100 |
+
x0 = np.clip(x0, [lo for lo, _ in b], [hi for _, hi in b])
|
| 101 |
+
|
| 102 |
+
def obj(x):
|
| 103 |
+
x = jnp.asarray(x)
|
| 104 |
+
p = HelmParams.from_array(x[:6])
|
| 105 |
+
sig = x[6] if opt_noise else cfg.sigma_obs
|
| 106 |
+
return -log_marginal_likelihood(p, S, t, y, sig)
|
| 107 |
+
|
| 108 |
+
vg = jax.jit(jax.value_and_grad(obj))
|
| 109 |
+
|
| 110 |
+
def f(x):
|
| 111 |
+
v, g = vg(jnp.asarray(x))
|
| 112 |
+
return float(v), np.asarray(g, dtype=np.float64)
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
res = minimize(f, x0, jac=True, method="L-BFGS-B", bounds=b,
|
| 116 |
+
options={"maxiter": 60})
|
| 117 |
+
xs = np.clip(res.x, [lo for lo, _ in b], [hi for _, hi in b])
|
| 118 |
+
except Exception:
|
| 119 |
+
xs = x0
|
| 120 |
+
p = HelmParams.from_array(jnp.asarray(xs[:6]))
|
| 121 |
+
sig = float(xs[6]) if opt_noise else cfg.sigma_obs
|
| 122 |
+
return p, sig
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def run_campaign(
|
| 126 |
+
key,
|
| 127 |
+
cfg: Config,
|
| 128 |
+
gt_fields: jnp.ndarray,
|
| 129 |
+
policy: str,
|
| 130 |
+
true_params: HelmParams,
|
| 131 |
+
bounds=None,
|
| 132 |
+
eval_params: HelmParams | None = None,
|
| 133 |
+
seed_offset: int = 0,
|
| 134 |
+
):
|
| 135 |
+
"""Run one campaign. Returns dict with the per-deployment error curve.
|
| 136 |
+
|
| 137 |
+
`eval_params` (default: true_params) are the hyperparameters used for the
|
| 138 |
+
*evaluation* GP. Held fixed across policies so the comparison measures the
|
| 139 |
+
quality of the data collected, not of the fitted model.
|
| 140 |
+
"""
|
| 141 |
+
grid = cfg.grid()
|
| 142 |
+
eval_params = eval_params or true_params
|
| 143 |
+
n_obs_tot = cfg.n_obs_total
|
| 144 |
+
ops_true = make_ops(grid.R, true_params, cfg.dt)
|
| 145 |
+
|
| 146 |
+
# global observation times: 0.05, 0.10, ..., T
|
| 147 |
+
tg = cfg.obs_dt * (1 + jnp.arange(n_obs_tot))
|
| 148 |
+
|
| 149 |
+
pos_all = np.zeros((cfg.n_deploy, n_obs_tot, 2)) # reported (cell-centre) locations
|
| 150 |
+
raw_all = np.zeros((cfg.n_deploy, n_obs_tot, 2)) # true physical positions
|
| 151 |
+
val_all = np.zeros((cfg.n_deploy, n_obs_tot), dtype=bool)
|
| 152 |
+
y_all = np.zeros((cfg.n_deploy, n_obs_tot, 2))
|
| 153 |
+
placements = []
|
| 154 |
+
errors = []
|
| 155 |
+
|
| 156 |
+
t_eval = cfg.deploy_every * jnp.arange(cfg.n_deploy)
|
| 157 |
+
|
| 158 |
+
for m in range(cfg.n_deploy):
|
| 159 |
+
t_m = m * cfg.deploy_every
|
| 160 |
+
k_m = int(round(t_m / cfg.dt))
|
| 161 |
+
key, kp, ks, ko = jax.random.split(key, 4)
|
| 162 |
+
|
| 163 |
+
# ---- data available at decision time (strictly before/at t_m)
|
| 164 |
+
past = val_all & (np.asarray(tg)[None, :] <= t_m + 1e-9)
|
| 165 |
+
S_obs = jnp.asarray(pos_all[past])
|
| 166 |
+
t_obs = jnp.asarray(np.broadcast_to(np.asarray(tg)[None, :], past.shape)[past])
|
| 167 |
+
y_obs = jnp.asarray(y_all[past])
|
| 168 |
+
|
| 169 |
+
# ---- choose the placement
|
| 170 |
+
if m == 0:
|
| 171 |
+
idx = int(jax.random.randint(kp, (), 0, grid.n))
|
| 172 |
+
elif policy == "unif":
|
| 173 |
+
idx = int(jax.random.randint(kp, (), 0, grid.n))
|
| 174 |
+
elif policy == "sobol":
|
| 175 |
+
idx = int(sobol_indices(grid, cfg.n_deploy, seed_offset)[m])
|
| 176 |
+
else:
|
| 177 |
+
exist_idx = np.arange(m)
|
| 178 |
+
j_at = int(round(t_m / cfg.obs_dt)) - 1 # obs index whose time is t_m
|
| 179 |
+
# project from the drifters' true positions, not their reported cells
|
| 180 |
+
exist_pos = jnp.asarray(raw_all[exist_idx, j_at])
|
| 181 |
+
exist_live = jnp.asarray(val_all[exist_idx, j_at])
|
| 182 |
+
# drifters that already left contribute nothing: park them outside
|
| 183 |
+
exist_pos = jnp.where(
|
| 184 |
+
exist_live[:, None], exist_pos, jnp.array([1e6, 1e6])
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
p_pol, sig_pol = true_params, cfg.sigma_obs
|
| 188 |
+
if policy == "ballast_opt":
|
| 189 |
+
p_pol, sig_pol = optimise_hypers(
|
| 190 |
+
S_obs, t_obs, y_obs, cfg, bounds, true_params
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
if policy == "eig":
|
| 194 |
+
sc = eig_utilities(grid, S_obs, t_obs, t_m, p_pol, sig_pol, cfg.chunk)
|
| 195 |
+
else:
|
| 196 |
+
ops_pol = ops_true if policy != "ballast_opt" else make_ops(
|
| 197 |
+
grid.R, p_pol, cfg.dt
|
| 198 |
+
)
|
| 199 |
+
mean, chol = posterior_ext_state(
|
| 200 |
+
S_obs, t_obs, y_obs, grid.R, t_m, p_pol, sig_pol
|
| 201 |
+
)
|
| 202 |
+
if policy == "dist_sep":
|
| 203 |
+
sc = dist_sep_scores(
|
| 204 |
+
ks, grid, ops_pol, mean, chol, exist_pos, S_obs, t_m,
|
| 205 |
+
cfg.T, cfg.dt, cfg.obs_every, cfg.n_samples,
|
| 206 |
+
)
|
| 207 |
+
else: # ballast_true / ballast_opt
|
| 208 |
+
u = ballast_sample_utilities(
|
| 209 |
+
ks, grid, ops_pol, S_obs, t_obs, mean, chol, exist_pos,
|
| 210 |
+
t_m, cfg.T, cfg.dt, cfg.obs_every, p_pol, sig_pol,
|
| 211 |
+
cfg.n_samples, cfg.chunk,
|
| 212 |
+
)
|
| 213 |
+
sc = jnp.mean(u, axis=0)
|
| 214 |
+
idx = int(jnp.argmax(sc))
|
| 215 |
+
|
| 216 |
+
s_new = grid.R[idx]
|
| 217 |
+
placements.append((float(s_new[0]), float(s_new[1]), t_m))
|
| 218 |
+
|
| 219 |
+
# ---- advect the new drifter through the TRUE field until T
|
| 220 |
+
pos, valid, tidx = advect(
|
| 221 |
+
grid, gt_fields[k_m:], s_new[None, :],
|
| 222 |
+
jnp.ones(1, dtype=bool), cfg.dt, cfg.obs_every,
|
| 223 |
+
)
|
| 224 |
+
yv = observe(ko, grid, gt_fields[k_m:], pos, valid, tidx, cfg.sigma_obs)
|
| 225 |
+
j0 = int(round(t_m / cfg.obs_dt))
|
| 226 |
+
n_here = pos.shape[0]
|
| 227 |
+
# a drifter reports its cell's velocity, i.e. f(cell centre, t) + noise
|
| 228 |
+
pos_all[m, j0 : j0 + n_here] = np.asarray(grid.snap(pos)[:, 0, :])
|
| 229 |
+
raw_all[m, j0 : j0 + n_here] = np.asarray(pos[:, 0, :])
|
| 230 |
+
val_all[m, j0 : j0 + n_here] = np.asarray(valid[:, 0])
|
| 231 |
+
y_all[m, j0 : j0 + n_here] = np.asarray(yv[:, 0, :])
|
| 232 |
+
|
| 233 |
+
# ---- evaluate: all data from the m+1 drifters over the whole campaign
|
| 234 |
+
sel = val_all[: m + 1]
|
| 235 |
+
S_e = jnp.asarray(pos_all[: m + 1][sel])
|
| 236 |
+
t_e = jnp.asarray(np.broadcast_to(np.asarray(tg)[None, :], sel.shape)[sel])
|
| 237 |
+
y_e = jnp.asarray(y_all[: m + 1][sel])
|
| 238 |
+
mu = posterior_mean_field(
|
| 239 |
+
S_e, t_e, y_e, grid.R, t_eval, eval_params, cfg.sigma_obs
|
| 240 |
+
)
|
| 241 |
+
gt_at_eval = gt_fields[(jnp.round(t_eval / cfg.dt)).astype(int)]
|
| 242 |
+
err = float(jnp.mean(jnp.linalg.norm(mu - gt_at_eval, axis=-1)))
|
| 243 |
+
errors.append(err)
|
| 244 |
+
|
| 245 |
+
return {
|
| 246 |
+
"policy": policy,
|
| 247 |
+
"errors": errors,
|
| 248 |
+
"placements": placements,
|
| 249 |
+
"n_obs": int(val_all.sum()),
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# --------------------------------------------------------------------------
|
| 254 |
+
# Iso-performance (Sec. 5.2): how many drifters a policy saves vs UNIF
|
| 255 |
+
# --------------------------------------------------------------------------
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def iso_performance(err_policy: np.ndarray, err_unif: np.ndarray) -> np.ndarray:
|
| 259 |
+
"""Drifters saved at each iteration, relative to the uniform benchmark.
|
| 260 |
+
|
| 261 |
+
At iteration m the uniform benchmark reaches error e = err_unif[m]. We find
|
| 262 |
+
the (interpolated, fractional) number of drifters n the policy needs to reach
|
| 263 |
+
the same error and report m - n: positive means the policy needed fewer.
|
| 264 |
+
|
| 265 |
+
Both curves are made monotone non-increasing first (running minimum): the
|
| 266 |
+
error curve of a single run is noisy, and "the number of drifters needed to
|
| 267 |
+
reach accuracy e" is only well defined for a best-so-far curve.
|
| 268 |
+
"""
|
| 269 |
+
a = np.minimum.accumulate(np.asarray(err_policy, dtype=float))
|
| 270 |
+
b = np.minimum.accumulate(np.asarray(err_unif, dtype=float))
|
| 271 |
+
n = len(a)
|
| 272 |
+
idx = np.arange(1, n + 1, dtype=float) # number of drifters deployed
|
| 273 |
+
out = np.full(n, np.nan)
|
| 274 |
+
for m in range(n):
|
| 275 |
+
target = b[m]
|
| 276 |
+
hit = np.where(a <= target)[0]
|
| 277 |
+
if len(hit) == 0:
|
| 278 |
+
# policy never reaches it: cap at the full budget (conservative)
|
| 279 |
+
out[m] = idx[m] - (n + 1)
|
| 280 |
+
continue
|
| 281 |
+
k = hit[0]
|
| 282 |
+
if k == 0:
|
| 283 |
+
out[m] = idx[m] - 1.0
|
| 284 |
+
else:
|
| 285 |
+
# linear interpolation in drifter count between k-1 and k
|
| 286 |
+
e0, e1 = a[k - 1], a[k]
|
| 287 |
+
frac = 0.0 if e0 == e1 else (e0 - target) / (e0 - e1)
|
| 288 |
+
out[m] = idx[m] - (idx[k - 1] + frac)
|
| 289 |
+
return out
|
ballast/gp.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GP regression, posterior sampling and information-gain utilities.
|
| 2 |
+
|
| 3 |
+
Implements paper Sec. B.1 (regression), C.1 (the cheap EIG reformulation
|
| 4 |
+
logdet(I + sigma^-2 K(X)), which is what eq. (3)/(5) actually mean -- see note
|
| 5 |
+
below), and E.2 (rank-q Gram determinant updates, which the paper states is
|
| 6 |
+
"the default for the computation in this work").
|
| 7 |
+
|
| 8 |
+
Note on eq. (5). The main text writes the utility as
|
| 9 |
+
logdet(I + sigma_obs^2 K(X))
|
| 10 |
+
but App. C.1 derives
|
| 11 |
+
IG = 1/2 logdet(I + sigma_obs^{-2} K(X)),
|
| 12 |
+
i.e. the noise variance enters *inversely* (more noise -> less information). The
|
| 13 |
+
main-text form is a sign-of-exponent typo; we implement the App. C.1 form. With
|
| 14 |
+
sigma_obs = 0.1 the two differ by a factor 1e4 inside the logdet and would order
|
| 15 |
+
candidates differently, so this matters. Constant factors of 1/2 do not affect
|
| 16 |
+
the argmax and are dropped, but we keep them consistent across policies.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import jax
|
| 22 |
+
import jax.numpy as jnp
|
| 23 |
+
from jax.scipy.linalg import cho_factor, cho_solve, solve_triangular
|
| 24 |
+
|
| 25 |
+
from .kernels import HelmParams, k_ext_cross, k_ext_full, k_thelm_mat
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _expand_mask(mask: jnp.ndarray) -> jnp.ndarray:
|
| 29 |
+
"""(..., n) point mask -> (..., 2n) row mask (2 velocity components/point)."""
|
| 30 |
+
return jnp.repeat(mask, 2, axis=-1)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def noise_gram(
|
| 34 |
+
S: jnp.ndarray, t: jnp.ndarray, p: HelmParams, sigma: float, mask=None
|
| 35 |
+
) -> jnp.ndarray:
|
| 36 |
+
"""M = I + sigma^-2 K(X), with invalid points replaced by identity rows.
|
| 37 |
+
|
| 38 |
+
Masking out point i (row/col -> e_i) leaves logdet(M) equal to the logdet of
|
| 39 |
+
the submatrix over valid points, so variable-length trajectories can be
|
| 40 |
+
batched at fixed shape.
|
| 41 |
+
"""
|
| 42 |
+
K = k_thelm_mat(S, t, S, t, p)
|
| 43 |
+
n = K.shape[0]
|
| 44 |
+
M = jnp.eye(n) + K / sigma**2
|
| 45 |
+
if mask is not None:
|
| 46 |
+
m = _expand_mask(mask).astype(M.dtype)
|
| 47 |
+
M = M * m[:, None] * m[None, :]
|
| 48 |
+
M = M + jnp.diag(1.0 - m)
|
| 49 |
+
return M
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def logdet_chol(M: jnp.ndarray) -> jnp.ndarray:
|
| 53 |
+
L = jnp.linalg.cholesky(M)
|
| 54 |
+
return 2.0 * jnp.sum(jnp.log(jnp.diagonal(L, axis1=-2, axis2=-1)), axis=-1)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# --------------------------------------------------------------------------
|
| 58 |
+
# Regression
|
| 59 |
+
# --------------------------------------------------------------------------
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def log_marginal_likelihood(
|
| 63 |
+
p: HelmParams, S: jnp.ndarray, t: jnp.ndarray, y: jnp.ndarray, sigma: float
|
| 64 |
+
) -> jnp.ndarray:
|
| 65 |
+
"""Log marginal likelihood of the plain (non-extended) temporal Helmholtz GP.
|
| 66 |
+
|
| 67 |
+
y is (n, 2) velocity observations; flattened point-major/component-minor.
|
| 68 |
+
"""
|
| 69 |
+
K = k_thelm_mat(S, t, S, t, p)
|
| 70 |
+
n = K.shape[0]
|
| 71 |
+
A = K + (sigma**2) * jnp.eye(n)
|
| 72 |
+
c, low = cho_factor(A)
|
| 73 |
+
yy = y.reshape(-1)
|
| 74 |
+
alpha = cho_solve((c, low), yy)
|
| 75 |
+
ld = 2.0 * jnp.sum(jnp.log(jnp.diag(c)))
|
| 76 |
+
return -0.5 * yy @ alpha - 0.5 * ld - 0.5 * n * jnp.log(2 * jnp.pi)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def posterior_mean_field(
|
| 80 |
+
S: jnp.ndarray,
|
| 81 |
+
t: jnp.ndarray,
|
| 82 |
+
y: jnp.ndarray,
|
| 83 |
+
R: jnp.ndarray,
|
| 84 |
+
t_eval: jnp.ndarray,
|
| 85 |
+
p: HelmParams,
|
| 86 |
+
sigma: float,
|
| 87 |
+
) -> jnp.ndarray:
|
| 88 |
+
"""Posterior predictive mean of the velocity field on R x t_eval.
|
| 89 |
+
|
| 90 |
+
Returns (n_teval, N_space, 2). Used for the performance metric of Sec. 5.2:
|
| 91 |
+
average L2 error of the posterior mean field over the spatial grid and the
|
| 92 |
+
full set of deployment times.
|
| 93 |
+
"""
|
| 94 |
+
K = k_thelm_mat(S, t, S, t, p)
|
| 95 |
+
A = K + (sigma**2) * jnp.eye(K.shape[0])
|
| 96 |
+
c, low = cho_factor(A)
|
| 97 |
+
alpha = cho_solve((c, low), y.reshape(-1))
|
| 98 |
+
|
| 99 |
+
N = R.shape[0]
|
| 100 |
+
Rr = jnp.tile(R, (t_eval.shape[0], 1)) # (nt*N, 2)
|
| 101 |
+
tr = jnp.repeat(t_eval, N)
|
| 102 |
+
Kx = k_thelm_mat(S, t, Rr, tr, p) # (2n, 2*nt*N)
|
| 103 |
+
mu = Kx.T @ alpha
|
| 104 |
+
return mu.reshape(t_eval.shape[0], N, 2)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def posterior_ext_state(
|
| 108 |
+
S: jnp.ndarray,
|
| 109 |
+
t: jnp.ndarray,
|
| 110 |
+
y: jnp.ndarray,
|
| 111 |
+
R: jnp.ndarray,
|
| 112 |
+
t_m: float,
|
| 113 |
+
p: HelmParams,
|
| 114 |
+
sigma: float,
|
| 115 |
+
jitter: float = 1e-8,
|
| 116 |
+
):
|
| 117 |
+
"""Posterior of the extended state f(R, t_m) = [f, d_t f]^T given D_m.
|
| 118 |
+
|
| 119 |
+
This is step 6/8 of Algorithm 2: regress with the *extended* GP using a
|
| 120 |
+
standard dense GP, then hand the draw to the SPDE propagator. Observations
|
| 121 |
+
only ever touch the f-block; the d_t f block is reached through the
|
| 122 |
+
cross-covariance d_{t'} k_tHelm.
|
| 123 |
+
|
| 124 |
+
Returns (mean (4N,), chol of covariance (4N, 4N)).
|
| 125 |
+
"""
|
| 126 |
+
K = k_thelm_mat(S, t, S, t, p)
|
| 127 |
+
A = K + (sigma**2) * jnp.eye(K.shape[0])
|
| 128 |
+
c, low = cho_factor(A)
|
| 129 |
+
|
| 130 |
+
N = R.shape[0]
|
| 131 |
+
tvec = jnp.full((N,), t_m)
|
| 132 |
+
K_ot = k_ext_cross(S, t, R, tvec, p) # (2n, 4N)
|
| 133 |
+
K_tt = k_ext_full(R, tvec, p) # (4N, 4N)
|
| 134 |
+
|
| 135 |
+
mean = K_ot.T @ cho_solve((c, low), y.reshape(-1))
|
| 136 |
+
cov = K_tt - K_ot.T @ cho_solve((c, low), K_ot)
|
| 137 |
+
cov = 0.5 * (cov + cov.T) + jitter * jnp.eye(cov.shape[0])
|
| 138 |
+
return mean, jnp.linalg.cholesky(cov)
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def sample_ext_state(key, mean, cov_chol, n_space: int) -> jnp.ndarray:
|
| 142 |
+
"""Draw an extended state and reshape to the SPDE layout (2N_space, 2)."""
|
| 143 |
+
z = jax.random.normal(key, mean.shape, dtype=mean.dtype)
|
| 144 |
+
x = mean + cov_chol @ z
|
| 145 |
+
return x.reshape(2 * n_space, 2)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# --------------------------------------------------------------------------
|
| 149 |
+
# Utilities (information gain)
|
| 150 |
+
# --------------------------------------------------------------------------
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def base_factor(
|
| 154 |
+
S: jnp.ndarray, t: jnp.ndarray, p: HelmParams, sigma: float, mask=None
|
| 155 |
+
):
|
| 156 |
+
"""Cholesky factor and logdet of A = I + sigma^-2 K(Z) for the fixed base set Z."""
|
| 157 |
+
A = noise_gram(S, t, p, sigma, mask)
|
| 158 |
+
L = jnp.linalg.cholesky(A)
|
| 159 |
+
return L, 2.0 * jnp.sum(jnp.log(jnp.diag(L)))
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def rank_q_logdet(
|
| 163 |
+
L_base: jnp.ndarray,
|
| 164 |
+
logdet_base: jnp.ndarray,
|
| 165 |
+
S_base: jnp.ndarray,
|
| 166 |
+
t_base: jnp.ndarray,
|
| 167 |
+
base_mask: jnp.ndarray | None,
|
| 168 |
+
S_new: jnp.ndarray,
|
| 169 |
+
t_new: jnp.ndarray,
|
| 170 |
+
new_mask: jnp.ndarray,
|
| 171 |
+
p: HelmParams,
|
| 172 |
+
sigma: float,
|
| 173 |
+
) -> jnp.ndarray:
|
| 174 |
+
"""logdet(I + sigma^-2 K(Z u P)) via the App. E.2 block-determinant update.
|
| 175 |
+
|
| 176 |
+
det [[A, B], [B^T, D]] = det(A) det(D - B^T A^{-1} B)
|
| 177 |
+
|
| 178 |
+
with A = I + sigma^-2 K(Z) already factorised (independent of the candidate),
|
| 179 |
+
B = sigma^-2 K(Z, P), D = I + sigma^-2 K(P). Cost is O(n^2 q + q^3) per
|
| 180 |
+
candidate instead of O((n+q)^3), which is what makes the 625-candidate x
|
| 181 |
+
20-sample inner loop of Algorithm 2 affordable.
|
| 182 |
+
|
| 183 |
+
Masked-out new points contribute e_i rows to the Schur complement and hence
|
| 184 |
+
nothing to the logdet.
|
| 185 |
+
"""
|
| 186 |
+
B = k_thelm_mat(S_base, t_base, S_new, t_new, p) / sigma**2 # (2n, 2q)
|
| 187 |
+
D = noise_gram(S_new, t_new, p, sigma, new_mask) # (2q, 2q)
|
| 188 |
+
|
| 189 |
+
mnew = _expand_mask(new_mask).astype(B.dtype)
|
| 190 |
+
B = B * mnew[None, :]
|
| 191 |
+
if base_mask is not None:
|
| 192 |
+
B = B * _expand_mask(base_mask).astype(B.dtype)[:, None]
|
| 193 |
+
|
| 194 |
+
V = solve_triangular(L_base, B, lower=True) # (2n, 2q)
|
| 195 |
+
Sc = D - V.T @ V
|
| 196 |
+
# keep the masked rows/cols exactly e_i (V columns there are already zero)
|
| 197 |
+
return logdet_base + logdet_chol(Sc)
|
ballast/kernels.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Kernels for the temporal Helmholtz GP of BALLAST (arXiv 2509.26005).
|
| 2 |
+
|
| 3 |
+
The surrogate is a separable, vector-output, spatio-temporal GP
|
| 4 |
+
|
| 5 |
+
k_tHelm((s,t),(s',t')) = k_Helm(s,s') * k_time(t,t')
|
| 6 |
+
|
| 7 |
+
with k_Helm the Helmholtz kernel of Berlinghieri et al. (2023) (paper Sec. B.2)
|
| 8 |
+
built from two independent RBF kernels (potential Phi, stream Psi), and k_time a
|
| 9 |
+
Matern-3/2 kernel (paper Sec. 2.2).
|
| 10 |
+
|
| 11 |
+
Section 4.1 of the paper additionally needs the *extended* GP f = [f, d_t f]^T,
|
| 12 |
+
whose kernel is the 2x2 block matrix of temporal derivatives of k_tHelm. Because
|
| 13 |
+
k_tHelm is separable, all t-derivatives act on the Matern-3/2 factor only.
|
| 14 |
+
|
| 15 |
+
Everything is implemented **analytically**. The paper (Sec. H.2) warns that
|
| 16 |
+
autodiff through a Matern kernel written with a clipped distance
|
| 17 |
+
(`sqrt(max(sum((x-y)**2), 1e-36))`, as in GPJax) gives d^2_{tt'}k = 0 at t=t'
|
| 18 |
+
instead of the correct 3*sigma^2/l^2; the analytic form has no such problem.
|
| 19 |
+
`tests/test_kernels.py` checks these derivatives against finite differences.
|
| 20 |
+
|
| 21 |
+
Index layout
|
| 22 |
+
------------
|
| 23 |
+
Spatial-velocity blocks are flattened point-major / component-minor:
|
| 24 |
+
row index of a velocity vector at point i, component c -> i*2 + c
|
| 25 |
+
The extended state adds the [f, d_t f] axis last:
|
| 26 |
+
(i, c, a) -> i*4 + c*2 + a with a=0 -> f, a=1 -> d_t f
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
from __future__ import annotations
|
| 30 |
+
|
| 31 |
+
from typing import NamedTuple
|
| 32 |
+
|
| 33 |
+
import jax
|
| 34 |
+
import jax.numpy as jnp
|
| 35 |
+
|
| 36 |
+
SQRT3 = jnp.sqrt(3.0)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class HelmParams(NamedTuple):
|
| 40 |
+
"""Hyperparameters of the temporal Helmholtz GP."""
|
| 41 |
+
|
| 42 |
+
phi_ls: jnp.ndarray # potential kernel lengthscale
|
| 43 |
+
phi_var: jnp.ndarray # potential kernel variance
|
| 44 |
+
psi_ls: jnp.ndarray # stream kernel lengthscale
|
| 45 |
+
psi_var: jnp.ndarray # stream kernel variance
|
| 46 |
+
time_ls: jnp.ndarray # Matern-3/2 temporal lengthscale
|
| 47 |
+
time_var: jnp.ndarray # Matern-3/2 temporal variance
|
| 48 |
+
|
| 49 |
+
def as_array(self) -> jnp.ndarray:
|
| 50 |
+
return jnp.stack(
|
| 51 |
+
[
|
| 52 |
+
jnp.asarray(self.phi_ls),
|
| 53 |
+
jnp.asarray(self.phi_var),
|
| 54 |
+
jnp.asarray(self.psi_ls),
|
| 55 |
+
jnp.asarray(self.psi_var),
|
| 56 |
+
jnp.asarray(self.time_ls),
|
| 57 |
+
jnp.asarray(self.time_var),
|
| 58 |
+
]
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def from_array(a: jnp.ndarray) -> "HelmParams":
|
| 63 |
+
return HelmParams(a[0], a[1], a[2], a[3], a[4], a[5])
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# --------------------------------------------------------------------------
|
| 67 |
+
# Spatial: Helmholtz kernel
|
| 68 |
+
# --------------------------------------------------------------------------
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _rbf_hess(S: jnp.ndarray, S2: jnp.ndarray, ls, var) -> jnp.ndarray:
|
| 72 |
+
"""Mixed second derivatives of an RBF kernel.
|
| 73 |
+
|
| 74 |
+
Returns H with H[i, j, a, b] = d^2 / (d x_a d x'_b) k(S_i, S2_j), which for
|
| 75 |
+
k = var * exp(-|d|^2 / (2 l^2)), d = x - x', equals
|
| 76 |
+
|
| 77 |
+
k * (delta_ab / l^2 - d_a d_b / l^4).
|
| 78 |
+
"""
|
| 79 |
+
d = S[:, None, :] - S2[None, :, :] # (N, M, 2)
|
| 80 |
+
sq = jnp.sum(d**2, axis=-1) # (N, M)
|
| 81 |
+
k = var * jnp.exp(-0.5 * sq / ls**2) # (N, M)
|
| 82 |
+
eye = jnp.eye(2)
|
| 83 |
+
outer = d[..., :, None] * d[..., None, :] # (N, M, 2, 2)
|
| 84 |
+
return k[..., None, None] * (eye / ls**2 - outer / ls**4)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def k_helm(S: jnp.ndarray, S2: jnp.ndarray, p: HelmParams) -> jnp.ndarray:
|
| 88 |
+
"""Helmholtz kernel (paper Sec. B.2), returned as (N, M, 2, 2).
|
| 89 |
+
|
| 90 |
+
F = grad(Phi) + rot(Psi) with rot(Psi) = (d_2 Psi, -d_1 Psi), so
|
| 91 |
+
|
| 92 |
+
K[0,0] = d^2_{x1 x1'} k_Phi + d^2_{x2 x2'} k_Psi
|
| 93 |
+
K[0,1] = d^2_{x1 x2'} k_Phi - d^2_{x2 x1'} k_Psi
|
| 94 |
+
K[1,0] = d^2_{x2 x1'} k_Phi - d^2_{x1 x2'} k_Psi
|
| 95 |
+
K[1,1] = d^2_{x2 x2'} k_Phi + d^2_{x1 x1'} k_Psi
|
| 96 |
+
"""
|
| 97 |
+
A = _rbf_hess(S, S2, p.phi_ls, p.phi_var) # potential
|
| 98 |
+
B = _rbf_hess(S, S2, p.psi_ls, p.psi_var) # stream
|
| 99 |
+
k00 = A[..., 0, 0] + B[..., 1, 1]
|
| 100 |
+
k01 = A[..., 0, 1] - B[..., 1, 0]
|
| 101 |
+
k10 = A[..., 1, 0] - B[..., 0, 1]
|
| 102 |
+
k11 = A[..., 1, 1] + B[..., 0, 0]
|
| 103 |
+
return jnp.stack(
|
| 104 |
+
[jnp.stack([k00, k01], -1), jnp.stack([k10, k11], -1)], axis=-2
|
| 105 |
+
) # (N, M, 2, 2)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def k_helm_mat(S: jnp.ndarray, S2: jnp.ndarray, p: HelmParams) -> jnp.ndarray:
|
| 109 |
+
"""Helmholtz Gram matrix flattened to (2N, 2M), point-major/component-minor."""
|
| 110 |
+
K = k_helm(S, S2, p) # (N, M, 2, 2)
|
| 111 |
+
N, M = K.shape[0], K.shape[1]
|
| 112 |
+
return jnp.transpose(K, (0, 2, 1, 3)).reshape(2 * N, 2 * M)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# --------------------------------------------------------------------------
|
| 116 |
+
# Temporal: Matern-3/2 and its derivative blocks
|
| 117 |
+
# --------------------------------------------------------------------------
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def matern32_blocks(t: jnp.ndarray, t2: jnp.ndarray, ls, var) -> jnp.ndarray:
|
| 121 |
+
"""Matern-3/2 kernel and its t/t' derivatives, as (N, M, 2, 2).
|
| 122 |
+
|
| 123 |
+
With lam = sqrt(3)/l, tau = t - t':
|
| 124 |
+
|
| 125 |
+
M[0,0] = k = var (1 + lam|tau|) exp(-lam|tau|)
|
| 126 |
+
M[0,1] = d_{t'} k = var lam^2 tau exp(-lam|tau|)
|
| 127 |
+
M[1,0] = d_{t} k = -var lam^2 tau exp(-lam|tau|)
|
| 128 |
+
M[1,1] = d^2_{t t'} k = var lam^2 (1 - lam|tau|) exp(-lam|tau|)
|
| 129 |
+
|
| 130 |
+
Note M[1,1] at tau=0 is var*lam^2 = 3 var / l^2 (= 3 for var=l=1), the value
|
| 131 |
+
the paper's Sec. H.2 flags as being silently zeroed by clipped-distance
|
| 132 |
+
autodiff implementations. It also equals P_inf[1,1] in the SPDE formulation
|
| 133 |
+
(spde.py), i.e. Var(d_t f) -- an internal consistency check of the two views.
|
| 134 |
+
"""
|
| 135 |
+
lam = SQRT3 / ls
|
| 136 |
+
tau = t[:, None] - t2[None, :]
|
| 137 |
+
a = jnp.abs(tau)
|
| 138 |
+
e = jnp.exp(-lam * a)
|
| 139 |
+
k = var * (1.0 + lam * a) * e
|
| 140 |
+
dk = var * lam**2 * tau * e # d_{t'} k
|
| 141 |
+
d2k = var * lam**2 * (1.0 - lam * a) * e
|
| 142 |
+
return jnp.stack(
|
| 143 |
+
[jnp.stack([k, dk], -1), jnp.stack([-dk, d2k], -1)], axis=-2
|
| 144 |
+
) # (N, M, 2, 2)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
# --------------------------------------------------------------------------
|
| 148 |
+
# Full temporal-Helmholtz kernel (plain and extended)
|
| 149 |
+
# --------------------------------------------------------------------------
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def k_thelm_mat(
|
| 153 |
+
S: jnp.ndarray, t: jnp.ndarray, S2: jnp.ndarray, t2: jnp.ndarray, p: HelmParams
|
| 154 |
+
) -> jnp.ndarray:
|
| 155 |
+
"""Plain k_tHelm Gram matrix between (S,t) and (S2,t2). Shape (2N, 2M)."""
|
| 156 |
+
KS = k_helm(S, S2, p) # (N, M, 2, 2)
|
| 157 |
+
kt = matern32_blocks(t, t2, p.time_ls, p.time_var)[..., 0, 0] # (N, M)
|
| 158 |
+
K = KS * kt[..., None, None]
|
| 159 |
+
N, M = K.shape[0], K.shape[1]
|
| 160 |
+
return jnp.transpose(K, (0, 2, 1, 3)).reshape(2 * N, 2 * M)
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def k_ext_cross(
|
| 164 |
+
S: jnp.ndarray, t: jnp.ndarray, S2: jnp.ndarray, t2: jnp.ndarray, p: HelmParams
|
| 165 |
+
) -> jnp.ndarray:
|
| 166 |
+
"""Cov between plain observations at (S,t) and the *extended* state at (S2,t2).
|
| 167 |
+
|
| 168 |
+
Returns (2N, 4M): rows index (obs point, velocity component), columns index
|
| 169 |
+
(test point, velocity component, [f, d_t f]).
|
| 170 |
+
"""
|
| 171 |
+
KS = k_helm(S, S2, p) # (N, M, 2, 2)
|
| 172 |
+
Mt = matern32_blocks(t, t2, p.time_ls, p.time_var) # (N, M, 2, 2)
|
| 173 |
+
# observation is the f-component (a=0); test keeps both b in {f, d_t f}
|
| 174 |
+
K = KS[..., :, :, None] * Mt[:, :, None, None, 0, :] # (N, M, 2, 2, 2)
|
| 175 |
+
N, M = K.shape[0], K.shape[1]
|
| 176 |
+
# (N, c, M, c', b) -> (2N, 4M)
|
| 177 |
+
return jnp.transpose(K, (0, 2, 1, 3, 4)).reshape(2 * N, 4 * M)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def k_ext_full(S: jnp.ndarray, t: jnp.ndarray, p: HelmParams) -> jnp.ndarray:
|
| 181 |
+
"""Covariance of the extended state f = [f, d_t f]^T at (S,t). Shape (4N, 4N)."""
|
| 182 |
+
KS = k_helm(S, S, p) # (N, N, 2, 2)
|
| 183 |
+
Mt = matern32_blocks(t, t, p.time_ls, p.time_var) # (N, N, 2, 2)
|
| 184 |
+
K = KS[..., :, :, None, None] * Mt[:, :, None, None, :, :] # (N,N,2,2,2,2)
|
| 185 |
+
N = K.shape[0]
|
| 186 |
+
# (i, c, a, j, c', b) -> (4N, 4N)
|
| 187 |
+
return jnp.transpose(K, (0, 2, 4, 1, 3, 5)).reshape(4 * N, 4 * N)
|
ballast/policies.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The six placement policies of paper Sec. H.3, and the BALLAST utility.
|
| 2 |
+
|
| 3 |
+
UNIF, SOBOL, DIST-SEP, EIG, BALLAST-true, BALLAST-opt.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
|
| 8 |
+
import functools
|
| 9 |
+
|
| 10 |
+
import jax
|
| 11 |
+
import jax.numpy as jnp
|
| 12 |
+
import numpy as np
|
| 13 |
+
from scipy.stats import qmc
|
| 14 |
+
|
| 15 |
+
from .gp import base_factor, rank_q_logdet, posterior_ext_state, sample_ext_state
|
| 16 |
+
from .kernels import HelmParams
|
| 17 |
+
from .spde import SpdeOps, propagate
|
| 18 |
+
from .trajectory import Grid, advect
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# --------------------------------------------------------------------------
|
| 22 |
+
# Sampling posterior fields + projecting trajectories (Algorithm 2, steps 7-13)
|
| 23 |
+
# --------------------------------------------------------------------------
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def sample_and_project(
|
| 27 |
+
key,
|
| 28 |
+
grid: Grid,
|
| 29 |
+
ops: SpdeOps,
|
| 30 |
+
ext_mean,
|
| 31 |
+
ext_chol,
|
| 32 |
+
exist_pos: jnp.ndarray,
|
| 33 |
+
t_m: float,
|
| 34 |
+
n_steps: int,
|
| 35 |
+
dt: float,
|
| 36 |
+
obs_every: int,
|
| 37 |
+
):
|
| 38 |
+
"""One BALLAST sample: draw f(R,t_m)|D_m, propagate to T, advect everything.
|
| 39 |
+
|
| 40 |
+
Particles are [all N_space candidate placements] ++ [existing drifters at
|
| 41 |
+
their current positions]. Returns positions/validity of both groups plus the
|
| 42 |
+
observation times.
|
| 43 |
+
"""
|
| 44 |
+
ka, kb = jax.random.split(key)
|
| 45 |
+
X0 = sample_ext_state(ka, ext_mean, ext_chol, grid.n)
|
| 46 |
+
fields = propagate(X0, kb, ops, n_steps) # (n_steps+1, N, 2)
|
| 47 |
+
|
| 48 |
+
s0 = jnp.concatenate([grid.R, exist_pos], axis=0)
|
| 49 |
+
active0 = jnp.ones(s0.shape[0], dtype=bool)
|
| 50 |
+
pos, valid, tidx = advect(grid, fields, s0, active0, dt, obs_every)
|
| 51 |
+
t_traj = t_m + tidx * dt
|
| 52 |
+
n_cand = grid.n
|
| 53 |
+
# Future observations land at cell centres (see Grid.snap): the utility must
|
| 54 |
+
# score the locations the drifter will actually report, not its exact path.
|
| 55 |
+
spos = grid.snap(pos)
|
| 56 |
+
return (
|
| 57 |
+
spos[:, :n_cand, :],
|
| 58 |
+
valid[:, :n_cand],
|
| 59 |
+
spos[:, n_cand:, :],
|
| 60 |
+
valid[:, n_cand:],
|
| 61 |
+
t_traj,
|
| 62 |
+
pos,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ballast_sample_utilities(
|
| 67 |
+
key,
|
| 68 |
+
grid: Grid,
|
| 69 |
+
ops: SpdeOps,
|
| 70 |
+
S_obs,
|
| 71 |
+
t_obs,
|
| 72 |
+
ext_mean,
|
| 73 |
+
ext_chol,
|
| 74 |
+
exist_pos,
|
| 75 |
+
t_m: float,
|
| 76 |
+
T: float,
|
| 77 |
+
dt: float,
|
| 78 |
+
obs_every: int,
|
| 79 |
+
p: HelmParams,
|
| 80 |
+
sigma: float,
|
| 81 |
+
n_samples: int,
|
| 82 |
+
chunk: int = 64,
|
| 83 |
+
):
|
| 84 |
+
"""Per-sample BALLAST utilities: returns (n_samples, N_space).
|
| 85 |
+
|
| 86 |
+
utils[j, i] = logdet(I + sigma^-2 K(X_m u P_j(s_exist) u P_j(R_i)))
|
| 87 |
+
|
| 88 |
+
Structured for the App. E.2 rank-q update: the base set X_m u P_j(s_exist)
|
| 89 |
+
does not depend on the candidate, so its Cholesky is computed once per
|
| 90 |
+
sample and reused across all N_space candidates. Averaging over j gives
|
| 91 |
+
eq. (5); keeping the per-sample axis is what makes the J-ablation of Sec. 5.1
|
| 92 |
+
computable from a single J=200 run.
|
| 93 |
+
"""
|
| 94 |
+
n_steps = int(round((T - t_m) / dt))
|
| 95 |
+
keys = jax.random.split(key, n_samples)
|
| 96 |
+
out = []
|
| 97 |
+
for j in range(n_samples):
|
| 98 |
+
cpos, cval, epos, eval_, t_traj, _ = sample_and_project(
|
| 99 |
+
keys[j], grid, ops, ext_mean, ext_chol, exist_pos, t_m, n_steps, dt, obs_every
|
| 100 |
+
)
|
| 101 |
+
# base = past observations ++ projected trajectories of existing drifters
|
| 102 |
+
n_e = epos.shape[1]
|
| 103 |
+
S_base = jnp.concatenate([S_obs, epos.reshape(-1, 2)], axis=0)
|
| 104 |
+
t_base = jnp.concatenate(
|
| 105 |
+
[t_obs, jnp.repeat(t_traj[:, None], n_e, axis=1).reshape(-1)], axis=0
|
| 106 |
+
)
|
| 107 |
+
m_base = jnp.concatenate(
|
| 108 |
+
[jnp.ones(S_obs.shape[0], dtype=bool), eval_.reshape(-1)], axis=0
|
| 109 |
+
)
|
| 110 |
+
L, ld = base_factor(S_base, t_base, p, sigma, m_base)
|
| 111 |
+
|
| 112 |
+
def one(i):
|
| 113 |
+
return rank_q_logdet(
|
| 114 |
+
L, ld, S_base, t_base, m_base,
|
| 115 |
+
cpos[:, i, :], t_traj, cval[:, i], p, sigma,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
vals = jnp.concatenate(
|
| 119 |
+
[jax.vmap(one)(jnp.arange(a, min(a + chunk, grid.n)))
|
| 120 |
+
for a in range(0, grid.n, chunk)]
|
| 121 |
+
)
|
| 122 |
+
out.append(vals)
|
| 123 |
+
return jnp.stack(out)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def true_field_utilities(
|
| 127 |
+
grid: Grid,
|
| 128 |
+
true_fields: jnp.ndarray,
|
| 129 |
+
S_obs,
|
| 130 |
+
t_obs,
|
| 131 |
+
exist_pos,
|
| 132 |
+
t_m: float,
|
| 133 |
+
dt: float,
|
| 134 |
+
obs_every: int,
|
| 135 |
+
p: HelmParams,
|
| 136 |
+
sigma: float,
|
| 137 |
+
chunk: int = 64,
|
| 138 |
+
):
|
| 139 |
+
"""B(s; true): utilities with trajectories simulated in the ground-truth field.
|
| 140 |
+
|
| 141 |
+
Used only for the Gap_Full diagnostic of the Sec. G.1 ablation (and never by
|
| 142 |
+
any policy -- it is not implementable without knowing the true field).
|
| 143 |
+
`true_fields` must already be sliced to [t_m, T].
|
| 144 |
+
"""
|
| 145 |
+
s0 = jnp.concatenate([grid.R, exist_pos], axis=0)
|
| 146 |
+
pos, valid, tidx = advect(
|
| 147 |
+
grid, true_fields, s0, jnp.ones(s0.shape[0], dtype=bool), dt, obs_every
|
| 148 |
+
)
|
| 149 |
+
t_traj = t_m + tidx * dt
|
| 150 |
+
n_cand = grid.n
|
| 151 |
+
pos = grid.snap(pos) # observations are reported at cell centres
|
| 152 |
+
cpos, cval = pos[:, :n_cand, :], valid[:, :n_cand]
|
| 153 |
+
epos, eval_ = pos[:, n_cand:, :], valid[:, n_cand:]
|
| 154 |
+
|
| 155 |
+
n_e = epos.shape[1]
|
| 156 |
+
S_base = jnp.concatenate([S_obs, epos.reshape(-1, 2)], axis=0)
|
| 157 |
+
t_base = jnp.concatenate(
|
| 158 |
+
[t_obs, jnp.repeat(t_traj[:, None], n_e, axis=1).reshape(-1)], axis=0
|
| 159 |
+
)
|
| 160 |
+
m_base = jnp.concatenate(
|
| 161 |
+
[jnp.ones(S_obs.shape[0], dtype=bool), eval_.reshape(-1)], axis=0
|
| 162 |
+
)
|
| 163 |
+
L, ld = base_factor(S_base, t_base, p, sigma, m_base)
|
| 164 |
+
|
| 165 |
+
def one(i):
|
| 166 |
+
return rank_q_logdet(
|
| 167 |
+
L, ld, S_base, t_base, m_base, cpos[:, i, :], t_traj, cval[:, i], p, sigma
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
return jnp.concatenate(
|
| 171 |
+
[jax.vmap(one)(jnp.arange(a, min(a + chunk, grid.n)))
|
| 172 |
+
for a in range(0, grid.n, chunk)]
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# --------------------------------------------------------------------------
|
| 177 |
+
# EIG (paper eq. 3): no look-ahead, only the initial placement location
|
| 178 |
+
# --------------------------------------------------------------------------
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def eig_utilities(
|
| 182 |
+
grid: Grid, S_obs, t_obs, t_m: float, p: HelmParams, sigma: float, chunk: int = 128
|
| 183 |
+
):
|
| 184 |
+
"""logdet(I + sigma^-2 K(X_n u {(s, t_n)})) for every candidate s."""
|
| 185 |
+
L, ld = base_factor(S_obs, t_obs, p, sigma, None)
|
| 186 |
+
tv = jnp.array([t_m])
|
| 187 |
+
|
| 188 |
+
def one(i):
|
| 189 |
+
return rank_q_logdet(
|
| 190 |
+
L, ld, S_obs, t_obs, None,
|
| 191 |
+
grid.R[i][None, :], tv, jnp.ones(1, dtype=bool), p, sigma,
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
return jnp.concatenate(
|
| 195 |
+
[jax.vmap(one)(jnp.arange(a, min(a + chunk, grid.n)))
|
| 196 |
+
for a in range(0, grid.n, chunk)]
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# --------------------------------------------------------------------------
|
| 201 |
+
# DIST-SEP (paper Sec. H.3, adapted from Chen et al. 2024b)
|
| 202 |
+
# --------------------------------------------------------------------------
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def dist_sep_scores(
|
| 206 |
+
key,
|
| 207 |
+
grid: Grid,
|
| 208 |
+
ops: SpdeOps,
|
| 209 |
+
ext_mean,
|
| 210 |
+
ext_chol,
|
| 211 |
+
exist_pos,
|
| 212 |
+
S_obs,
|
| 213 |
+
t_m: float,
|
| 214 |
+
T: float,
|
| 215 |
+
dt: float,
|
| 216 |
+
obs_every: int,
|
| 217 |
+
n_samples: int,
|
| 218 |
+
):
|
| 219 |
+
"""Rank-average of (i) expected drifter path length and (ii) separation.
|
| 220 |
+
|
| 221 |
+
(i) total distance travelled, averaged over BALLAST posterior samples;
|
| 222 |
+
(ii) negative Euclidean distance to the closest existing observation
|
| 223 |
+
location. Both are converted to ranks and averaged, then maximised.
|
| 224 |
+
"""
|
| 225 |
+
n_steps = int(round((T - t_m) / dt))
|
| 226 |
+
keys = jax.random.split(key, n_samples)
|
| 227 |
+
lengths = []
|
| 228 |
+
for j in range(n_samples):
|
| 229 |
+
_, cval, _, _, _, raw = sample_and_project(
|
| 230 |
+
keys[j], grid, ops, ext_mean, ext_chol, exist_pos, t_m, n_steps, dt, obs_every
|
| 231 |
+
)
|
| 232 |
+
# distance travelled uses the true (unsnapped) path
|
| 233 |
+
cpos = raw[:, : grid.n, :]
|
| 234 |
+
step = jnp.linalg.norm(cpos[1:] - cpos[:-1], axis=-1) # (n_obs-1, N)
|
| 235 |
+
ok = cval[1:] & cval[:-1]
|
| 236 |
+
lengths.append(jnp.sum(jnp.where(ok, step, 0.0), axis=0))
|
| 237 |
+
length = jnp.mean(jnp.stack(lengths), axis=0) # (N,)
|
| 238 |
+
|
| 239 |
+
d = jnp.linalg.norm(grid.R[:, None, :] - S_obs[None, :, :], axis=-1)
|
| 240 |
+
separation = -jnp.min(d, axis=1) # negative distance to closest observation
|
| 241 |
+
|
| 242 |
+
r1 = jnp.argsort(jnp.argsort(length))
|
| 243 |
+
r2 = jnp.argsort(jnp.argsort(separation))
|
| 244 |
+
return 0.5 * (r1 + r2)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
# --------------------------------------------------------------------------
|
| 248 |
+
# Space-filling designs
|
| 249 |
+
# --------------------------------------------------------------------------
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def sobol_indices(grid: Grid, n: int, seed: int) -> np.ndarray:
|
| 253 |
+
"""Scrambled Sobol points on [0,1)^2 mapped to grid cell indices (Sec. H.3)."""
|
| 254 |
+
pts = qmc.Sobol(d=2, scramble=True, seed=seed).random(n)
|
| 255 |
+
ix = np.clip((pts[:, 0] * grid.nx).astype(int), 0, grid.nx - 1)
|
| 256 |
+
iy = np.clip((pts[:, 1] * grid.ny).astype(int), 0, grid.ny - 1)
|
| 257 |
+
return ix * grid.ny + iy
|
ballast/spde.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""SPDE / state-space formulation of the separable spatio-temporal GP (paper Sec. 4.1, App. F).
|
| 2 |
+
|
| 3 |
+
For a separable kernel k = k_space(s,s') * k_time(t,t') with k_time Matern-3/2,
|
| 4 |
+
the extended field f(R,t) = [f(R,t), d_t f(R,t)]^T solves the linear SPDE
|
| 5 |
+
|
| 6 |
+
d/dt f(R,t) = (I_space (x) F) f(R,t) + (I_space (x) L) w(t)
|
| 7 |
+
|
| 8 |
+
driven by white noise with spectral density K_space (x) Q_c (paper F.2), giving
|
| 9 |
+
the *exact* discrete-time transition
|
| 10 |
+
|
| 11 |
+
f_{k+1} = (I (x) Phi) f_k + e_k, e_k ~ N(0, K_space (x) Q).
|
| 12 |
+
|
| 13 |
+
Why the paper's sampling scheme is exact (this is the crux of Claim 2)
|
| 14 |
+
---------------------------------------------------------------------
|
| 15 |
+
The dynamics are *pointwise in space*: the SDE at location s is driven only by
|
| 16 |
+
w(s, .) and never by the field at another location. Hence f(R, t > t_m) is a
|
| 17 |
+
deterministic function of the extended state f(R, t_m) and the future noise
|
| 18 |
+
{w(R, u) : u > t_m}, and that future noise is independent of everything at times
|
| 19 |
+
<= t_m. So for observations D_m taken at times <= t_m -- even at *non-gridded*
|
| 20 |
+
Lagrangian locations --
|
| 21 |
+
|
| 22 |
+
f(R, t > t_m) _||_ D_m | f(R, t_m).
|
| 23 |
+
|
| 24 |
+
Therefore drawing the initial condition f(R,t_m) | D_m from the extended dense GP
|
| 25 |
+
posterior and propagating it with the SPDE gives exact posterior samples, while
|
| 26 |
+
never filtering over the observation locations. `tests/test_spde.py` verifies
|
| 27 |
+
this against a dense GP built over the full space-time test set.
|
| 28 |
+
|
| 29 |
+
State layout: X has shape (2*N_space, 2). Rows are (location, velocity
|
| 30 |
+
component) point-major/component-minor; columns are [f, d_t f].
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
from typing import NamedTuple
|
| 36 |
+
|
| 37 |
+
import jax
|
| 38 |
+
import jax.numpy as jnp
|
| 39 |
+
|
| 40 |
+
from .kernels import SQRT3, HelmParams, k_helm_mat
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class SpdeOps(NamedTuple):
|
| 44 |
+
phi: jnp.ndarray # (2, 2) one-step transition e^{F dt}
|
| 45 |
+
L_Q: jnp.ndarray # (2, 2) chol of process noise Q
|
| 46 |
+
L_Pinf: jnp.ndarray # (2, 2) chol of stationary covariance P_inf
|
| 47 |
+
L_space: jnp.ndarray # (2N, 2N) chol of the spatial Helmholtz Gram
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def temporal_matrices(time_ls, time_var, dt: float):
|
| 51 |
+
"""Phi = exp(F dt), Q = P_inf - Phi P_inf Phi^T, P_inf (paper F.1).
|
| 52 |
+
|
| 53 |
+
F = [[0, 1], [-lam^2, -2 lam]] with lam = sqrt(3)/l is -lam*I + N with N
|
| 54 |
+
nilpotent (N^2 = 0), so exp(F dt) = e^{-lam dt} (I + N dt) in closed form.
|
| 55 |
+
"""
|
| 56 |
+
lam = SQRT3 / time_ls
|
| 57 |
+
e = jnp.exp(-lam * dt)
|
| 58 |
+
phi = e * jnp.array(
|
| 59 |
+
[[1.0 + lam * dt, dt], [-(lam**2) * dt, 1.0 - lam * dt]]
|
| 60 |
+
)
|
| 61 |
+
pinf = jnp.array([[time_var, 0.0], [0.0, lam**2 * time_var]])
|
| 62 |
+
q = pinf - phi @ pinf @ phi.T
|
| 63 |
+
return phi, q, pinf
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def make_ops(R: jnp.ndarray, p: HelmParams, dt: float, jitter: float = 1e-8) -> SpdeOps:
|
| 67 |
+
"""Build the SPDE operators for spatial grid R (N, 2)."""
|
| 68 |
+
phi, q, pinf = temporal_matrices(p.time_ls, p.time_var, dt)
|
| 69 |
+
Ks = k_helm_mat(R, R, p)
|
| 70 |
+
Ks = Ks + jitter * jnp.eye(Ks.shape[0])
|
| 71 |
+
return SpdeOps(
|
| 72 |
+
phi=phi,
|
| 73 |
+
L_Q=jnp.linalg.cholesky(q + jitter * jnp.eye(2)),
|
| 74 |
+
L_Pinf=jnp.linalg.cholesky(pinf),
|
| 75 |
+
L_space=jnp.linalg.cholesky(Ks),
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _step(X, key, ops):
|
| 80 |
+
"""One exact transition: X <- X Phi^T + L_space Z L_Q^T.
|
| 81 |
+
|
| 82 |
+
Cov(E_ia, E_jb) = (L_space L_space^T)_ij (L_Q L_Q^T)_ab = K_space_ij Q_ab,
|
| 83 |
+
i.e. vec(E) ~ N(0, K_space (x) Q) as required (App. E.1 Kronecker Cholesky).
|
| 84 |
+
"""
|
| 85 |
+
Z = jax.random.normal(key, X.shape, dtype=X.dtype)
|
| 86 |
+
return X @ ops.phi.T + ops.L_space @ Z @ ops.L_Q.T
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def propagate(X0: jnp.ndarray, key, ops: SpdeOps, n_steps: int) -> jnp.ndarray:
|
| 90 |
+
"""Propagate an extended state n_steps times.
|
| 91 |
+
|
| 92 |
+
Returns the *velocity* field history of shape (n_steps + 1, N, 2), i.e. only
|
| 93 |
+
the f-component of the extended state at each step (including the initial).
|
| 94 |
+
"""
|
| 95 |
+
keys = jax.random.split(key, n_steps)
|
| 96 |
+
|
| 97 |
+
def body(X, k):
|
| 98 |
+
Xn = _step(X, k, ops)
|
| 99 |
+
return Xn, Xn[:, 0]
|
| 100 |
+
|
| 101 |
+
_, hist = jax.lax.scan(body, X0, keys)
|
| 102 |
+
out = jnp.concatenate([X0[None, :, 0], hist], axis=0) # (n_steps+1, 2N)
|
| 103 |
+
return out.reshape(n_steps + 1, -1, 2)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def prior_sample(key, R: jnp.ndarray, ops: SpdeOps, n_steps: int) -> jnp.ndarray:
|
| 107 |
+
"""Exact prior sample of the temporal Helmholtz GP on R over a time grid.
|
| 108 |
+
|
| 109 |
+
Starts from the stationary distribution f(R,0) ~ N(0, K_space (x) P_inf) and
|
| 110 |
+
propagates. Cost is O((2 N_space)^2 N_t) (paper F.4) versus O((2 N_space
|
| 111 |
+
N_t)^3) for a dense draw -- this is what makes generating the 25x25x1001
|
| 112 |
+
synthetic ground-truth fields of Sec. 5.2 tractable at all.
|
| 113 |
+
|
| 114 |
+
Returns velocity fields (n_steps + 1, N, 2).
|
| 115 |
+
"""
|
| 116 |
+
k0, k1 = jax.random.split(key)
|
| 117 |
+
Z = jax.random.normal(k0, (ops.L_space.shape[0], 2), dtype=R.dtype)
|
| 118 |
+
X0 = ops.L_space @ Z @ ops.L_Pinf.T
|
| 119 |
+
return propagate(X0, k1, ops, n_steps)
|
ballast/trajectory.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lagrangian observer advection and observation model (paper Sec. H.1).
|
| 2 |
+
|
| 3 |
+
An observer released at (s, t) is advected by Euler discretisation
|
| 4 |
+
|
| 5 |
+
s_{n+1} = s_n + delta_t V(s_n, t_n), t_{n+1} = t_n + delta_t
|
| 6 |
+
|
| 7 |
+
with delta_t = 0.01. The field is only known on the spatial grid, so V(s, t) is
|
| 8 |
+
piecewise constant over grid cells ("the velocity at a spatial location will be
|
| 9 |
+
that of the grid cell containing the location"). The observer is terminated as
|
| 10 |
+
soon as it leaves the region. Observations are taken every delta_obs = 0.05 with
|
| 11 |
+
i.i.d. N(0, 0.1^2) noise.
|
| 12 |
+
|
| 13 |
+
Everything is batched over particles and written for fixed shapes: a particle
|
| 14 |
+
that has left the region is frozen and flagged invalid, and downstream Gram
|
| 15 |
+
matrices mask it out (see gp.noise_gram).
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import jax
|
| 21 |
+
import jax.numpy as jnp
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class Grid:
|
| 25 |
+
"""Regular (or mildly uneven) rectangular grid with piecewise-constant lookup.
|
| 26 |
+
|
| 27 |
+
Cell centres are R = outer product of `xs` and `ys` in row-major order
|
| 28 |
+
(index = ix * ny + iy), matching the spatial layout used everywhere else.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, xs: jnp.ndarray, ys: jnp.ndarray):
|
| 32 |
+
self.xs = jnp.asarray(xs)
|
| 33 |
+
self.ys = jnp.asarray(ys)
|
| 34 |
+
self.nx = self.xs.shape[0]
|
| 35 |
+
self.ny = self.ys.shape[0]
|
| 36 |
+
self.n = self.nx * self.ny
|
| 37 |
+
# cell edges: midpoints between centres, extended to the outer half-cells
|
| 38 |
+
self.x_edges = self._edges(self.xs)
|
| 39 |
+
self.y_edges = self._edges(self.ys)
|
| 40 |
+
X, Y = jnp.meshgrid(self.xs, self.ys, indexing="ij")
|
| 41 |
+
self.R = jnp.stack([X.reshape(-1), Y.reshape(-1)], axis=-1) # (n, 2)
|
| 42 |
+
|
| 43 |
+
@staticmethod
|
| 44 |
+
def _edges(c: jnp.ndarray) -> jnp.ndarray:
|
| 45 |
+
mid = 0.5 * (c[1:] + c[:-1])
|
| 46 |
+
lo = c[0] - (mid[0] - c[0])
|
| 47 |
+
hi = c[-1] + (c[-1] - mid[-1])
|
| 48 |
+
return jnp.concatenate([jnp.array([lo]), mid, jnp.array([hi])])
|
| 49 |
+
|
| 50 |
+
def inside(self, s: jnp.ndarray) -> jnp.ndarray:
|
| 51 |
+
"""(..., 2) -> (...) bool: is the point within the region's outer edges?"""
|
| 52 |
+
return (
|
| 53 |
+
(s[..., 0] >= self.x_edges[0])
|
| 54 |
+
& (s[..., 0] <= self.x_edges[-1])
|
| 55 |
+
& (s[..., 1] >= self.y_edges[0])
|
| 56 |
+
& (s[..., 1] <= self.y_edges[-1])
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
def cell_index(self, s: jnp.ndarray) -> jnp.ndarray:
|
| 60 |
+
"""(..., 2) -> (...) flat index of the containing cell (clipped at borders)."""
|
| 61 |
+
ix = jnp.clip(jnp.searchsorted(self.x_edges, s[..., 0]) - 1, 0, self.nx - 1)
|
| 62 |
+
iy = jnp.clip(jnp.searchsorted(self.y_edges, s[..., 1]) - 1, 0, self.ny - 1)
|
| 63 |
+
return ix * self.ny + iy
|
| 64 |
+
|
| 65 |
+
def lookup(self, field: jnp.ndarray, s: jnp.ndarray) -> jnp.ndarray:
|
| 66 |
+
"""field (n, 2) at points s (..., 2) -> (..., 2), piecewise constant."""
|
| 67 |
+
return field[self.cell_index(s)]
|
| 68 |
+
|
| 69 |
+
def snap(self, s: jnp.ndarray) -> jnp.ndarray:
|
| 70 |
+
"""Snap points to the centre of their containing cell.
|
| 71 |
+
|
| 72 |
+
The ground-truth field exists only on the grid, and a drifter measures
|
| 73 |
+
"the velocity of the grid cell containing the location" (paper Sec. H.1).
|
| 74 |
+
That measurement is therefore a noisy observation of f at the *cell
|
| 75 |
+
centre*, and is what the GP must be conditioned on.
|
| 76 |
+
|
| 77 |
+
Regressing it at the drifter's exact position instead is misspecified:
|
| 78 |
+
for the Sec. 5.2 setup the within-cell field variation has sd ~0.29
|
| 79 |
+
(cell 0.167 wide vs stream lengthscale 0.5), i.e. ~3x the assumed
|
| 80 |
+
sigma_obs = 0.1. Feeding that mismatch to a GP that believes the noise is
|
| 81 |
+
0.1 makes it interpolate discretisation error: the posterior mean
|
| 82 |
+
overshoots to ~3x the true field range and the field error rises above
|
| 83 |
+
the prior as drifters are added. Snapping removes the misspecification
|
| 84 |
+
exactly and restores the expected monotone error decay.
|
| 85 |
+
"""
|
| 86 |
+
return self.R[self.cell_index(s)]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def advect(
|
| 90 |
+
grid: Grid,
|
| 91 |
+
fields: jnp.ndarray,
|
| 92 |
+
s0: jnp.ndarray,
|
| 93 |
+
active0: jnp.ndarray,
|
| 94 |
+
dt: float,
|
| 95 |
+
obs_every: int,
|
| 96 |
+
):
|
| 97 |
+
"""Advect particles through a time-varying field and record observations.
|
| 98 |
+
|
| 99 |
+
Parameters
|
| 100 |
+
----------
|
| 101 |
+
fields : (n_steps + 1, n_cells, 2) velocity field history, fields[k] is the
|
| 102 |
+
field at time t_start + k*dt.
|
| 103 |
+
s0 : (P, 2) initial positions.
|
| 104 |
+
active0 : (P,) bool, whether each particle exists at all.
|
| 105 |
+
|
| 106 |
+
Returns
|
| 107 |
+
-------
|
| 108 |
+
pos : (n_obs, P, 2) observation positions, n_obs = n_steps // obs_every
|
| 109 |
+
valid : (n_obs, P) bool, observation is inside the region and the particle
|
| 110 |
+
had not yet left
|
| 111 |
+
tidx : (n_obs,) int, step index of each observation
|
| 112 |
+
|
| 113 |
+
Observations are recorded at steps obs_every, 2*obs_every, ... The release
|
| 114 |
+
instant itself is not an observation; the first measurement is one
|
| 115 |
+
observation interval after deployment.
|
| 116 |
+
"""
|
| 117 |
+
n_steps = fields.shape[0] - 1
|
| 118 |
+
|
| 119 |
+
def body(carry, k):
|
| 120 |
+
s, alive = carry
|
| 121 |
+
v = grid.lookup(fields[k], s)
|
| 122 |
+
s_new = jnp.where(alive[:, None], s + dt * v, s)
|
| 123 |
+
alive_new = alive & grid.inside(s_new)
|
| 124 |
+
return (s_new, alive_new), (s_new, alive_new)
|
| 125 |
+
|
| 126 |
+
(_, _), (traj, alive_hist) = jax.lax.scan(
|
| 127 |
+
body, (s0, active0 & grid.inside(s0)), jnp.arange(n_steps)
|
| 128 |
+
)
|
| 129 |
+
# traj[k] is the position after step k+1, i.e. at time t_start + (k+1)*dt
|
| 130 |
+
sel = jnp.arange(obs_every - 1, n_steps, obs_every)
|
| 131 |
+
return traj[sel], alive_hist[sel], sel + 1
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def observe(key, grid: Grid, fields: jnp.ndarray, pos, valid, tidx, noise_sd: float):
|
| 135 |
+
"""Sample noisy velocity measurements at the recorded observation points."""
|
| 136 |
+
v = jax.vmap(lambda f, s: grid.lookup(f, s))(fields[tidx], pos)
|
| 137 |
+
eps = noise_sd * jax.random.normal(key, v.shape, dtype=v.dtype)
|
| 138 |
+
return jnp.where(valid[..., None], v + eps, 0.0)
|