Inference and computation / E128

A hundred thousand sensors: three ways to shrink a Gaussian process, and what each one throws away

Type
Advanced worked example - read, run, modify
Data
Simulated: two temperature fields on a 100 km square whose truth we know (Matérn 3/2 Gaussian fields drawn by circulant embedding), each read once by 100,000 noisy sensors. Real: the 2,535 Argo float profiles of July and August 2025 from the North Atlantic table of E92 (Argo GDAC, CC BY 4.0)
You will learn
Why an exact Gaussian process stops at a few thousand points, and three ways past that: a Hilbert-space GP (pm.gp.HSGP) with its weights integrated out, so that 100,000 readings collapse into one small matrix · a Vecchia / nearest-neighbour likelihood written in JAX, with batched Cholesky factors and a gradient computed block by block · an inducing-point GP (Titsias's collapsed bound), also block by block · fitting four hyperparameters by mode and curvature when one gradient costs a second, and checking that shortcut against NUTS where NUTS is affordable · scoring every method against a known truth: error, coverage, time, memory, and the scales at which the error lives · and one number, the readings per resolution cell, that says in advance which approximation will work

The question

A regional weather service has an unusual problem: too many thermometers. Cars, phones and home weather stations report the air temperature from about 100,000 places in a region 100 km across. Each reading is cheap and noisy, off by about a degree. The service wants the map behind them: the temperature at the places where nobody measured, with an interval that can be trusted.

A Gaussian process is the natural model. The field is a smooth random function, the readings are the field plus noise, and the map is the posterior of the field. The difficulty is arithmetic. An exact GP on $n$ readings needs the $n \times n$ covariance matrix and its Cholesky factor. At $n = 100{,}000$ the matrix alone takes 80 GB, and the factorisation would run for hours, once for every gradient of every step of a sampler. Exact inference stops at a few thousand points.

Three families of approximation get past that, and each makes a different bet about the field.

  • A low rank built from sines. The Hilbert-space GP (Solin and Särkkä 2020; Riutort-Mayol et al. 2022) writes the field as a weighted sum of $M$ fixed sine functions. This is pm.gp.HSGP, the method this series has used since E05. The bet: the field has nothing finer than the shortest sine.
  • A low rank built from points. An inducing-point GP (Snelson and Ghahramani 2006; Titsias 2009) summarises the field by its values at $M$ chosen places. The bet: what happens between those places can be interpolated from them.
  • Neighbours. The Vecchia approximation (Vecchia 1988; Datta, Banerjee, Finley and Gelfand 2016; Katzfuss and Guinness 2021) keeps every reading and drops most of the dependence: each reading is conditioned on a few nearby ones instead of on all the others. The bet: once the neighbours are known, the rest of the map adds little.

The plan for this notebook came with an expectation written into it: the trade between cost and fidelity would be decided at short length-scales, where each approximation smooths away real structure. We treat that as a hypothesis and test it on two fields whose truth we know, one smooth (length-scale 20 km) and one rough (2 km), with every method scored the same way. It turns out to be half right. The two low-rank methods do smooth away real structure, but they do it on the smooth field as well, and their intervals do not admit it. The neighbour method never smooths anything away. Its weakness is the opposite and it appears on the smooth field, where it leaves sensor noise in the map. One number, the count of readings per resolution cell, turns out to say in advance which of the three will work.

Two decisions shape everything that follows, and both are about cost.

The field is integrated out. With Gaussian noise the latent field can be removed from the posterior exactly (the theme of E129), so each method is a likelihood for four numbers: the mean $\mu$, the standard deviation of the field $a$, its length-scale $\ell$ and the noise $\sigma$. Prediction comes afterwards, given those four.

The four numbers are fitted by mode and curvature, not by NUTS. At this size the price of a method is the price of one gradient, and for two of the three it is around a second. NUTS needs thousands of gradients. We fit every row by a Laplace approximation in a few dozen, treat all methods alike, and check the shortcut against NUTS on the one likelihood whose gradient does not depend on $n$.

part question tool
1 What is the truth? two Matérn fields by circulant embedding, exact at the lattice nodes
2 What does exactness cost, and how do we fit four numbers at this size? pm.gp.Marginal on 2,000 readings; Newton steps and a Laplace approximation
3 A low rank from sines pm.gp.HSGP with the weights integrated out, sufficient statistics, a NUTS check
4 Neighbours a Vecchia likelihood in JAX inside a PyMC model, scipy.spatial.cKDTree
5 A low rank from points Titsias's collapsed bound, accumulated block by block
6 The race 26 fits on two fields: error maps, a cost-against-error frontier, hyperparameters
7 Why it came out that way the spectrum of the field against the noise: resolution cells
8 Does the ocean agree? the same four methods on Argo profiles, where the exact GP is affordable
9 Which one, when? the scoreboard and a decision chart
import logging
import sys
import time
import warnings

import jax
import jax.numpy as jnp
import arviz as az
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pymc as pm
import pytensor
import pytensor.tensor as pt
from jax.scipy.linalg import solve_triangular as jax_solve
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import FancyBboxPatch
from matplotlib.ticker import FuncFormatter, LogLocator, NullFormatter
from pymc.sampling.jax import get_jaxified_graph
from scipy import integrate, optimize, stats
from scipy.linalg import cho_solve, cholesky, solve_triangular
from scipy.spatial import cKDTree

from pymc_challenges import data
from pymc_challenges.scoreboard import Scoreboard

jax.config.update("jax_enable_x64", True)

RANDOM_SEED = 128
rng = np.random.default_rng(RANDOM_SEED)
az.style.use("arviz-variat")
plt.rcParams.update({"axes.labelsize": 10, "xtick.labelsize": 9, "ytick.labelsize": 9, "axes.titlesize": 11})
logging.getLogger("pymc").setLevel(logging.WARNING)
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=UserWarning)
pd.set_option("display.width", 180)
pd.set_option("display.max_columns", 30)
pd.set_option("display.max_rows", 80)
T_START = time.time()

INK, MUTED, LIGHT, GRID = "#222222", "#8a8a8a", "#d9d9d9", "#e1e0d9"
BLUE, ORANGE, AQUA, YELLOW, MAGENTA, VIOLET, RED = (
    "#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#6250d6", "#e34948")
DIVERGING = LinearSegmentedColormap.from_list("div", ["#0d366b", "#6da7ec", "#fcfcfb", "#f0a37f", "#8f2d0c"])
COLOR = {"exact": MUTED, "HSGP": BLUE, "Vecchia": ORANGE, "inducing": AQUA}
CI = 0.9                       # every interval in this notebook is a central 90% interval

sb = Scoreboard(ci_prob=CI)    # every fit of the notebook gets a row; each is scored against its own truth


def tidy(ax, grid="y"):
    ax.spines[["top", "right"]].set_visible(False)
    ax.grid(False)
    if grid:
        ax.grid(axis=grid, color=GRID, lw=0.6)
    ax.set_axisbelow(True)

1 · Two fields whose truth we know

To judge a map we need the field itself, at the sensors and between them. So we simulate it, and the simulation has to be honest in two ways. It must not be an approximation of the kind being judged: a truth drawn from a Vecchia model or from a sum of sines would hand that method the win. And we must be able to say exactly what covariance it has.

An exact draw of a Gaussian field at 100,000 scattered points would need the same 80 GB matrix we are trying to avoid. On a regular lattice there is a way round it, circulant embedding (Wood and Chan 1994; Dietrich and Newsam 1997). Wrap a lattice twice as wide as the region onto a torus. The covariance matrix of a stationary field on a torus is diagonalised by the Fourier transform, so its eigenvalues are one FFT of the covariance function, and a draw is one more FFT of white noise scaled by their square roots. If every eigenvalue is non-negative the draw has exactly the covariance we asked for at every pair of nodes of the original region. If a few are slightly negative we set them to zero and measure how far that moves the covariance.

The field is a Matérn 3/2 process with standard deviation 2 °C around a mean of 1 °C (think of it as the departure of the temperature from this morning's forecast):

$$k(d) = a^2 \left(1 + \frac{\sqrt 3\, d}{\ell}\right) \exp\!\left(-\frac{\sqrt 3\, d}{\ell}\right).$$

We draw it on a lattice of 1,024 by 1,024 nodes, 98 m apart, once with $\ell = 20$ km and once with $\ell = 2$ km. The sensors sit at 100,000 nodes chosen at random, and each reports the field plus Gaussian noise of standard deviation 1 °C. A sub-lattice of 128 by 128 nodes is kept free of sensors: it is where we draw the maps, and its 64 by 64 half is where every method is scored. Coordinates are in kilometres from the centre of the region.

SIDE, N_GRID, N_SENSORS = 100.0, 1024, 100_000        # km, lattice nodes per side, sensors
TRUE = {"mu": 1.0, "amp": 2.0, "sigma": 1.0}          # degrees C: mean, sd of the field, sd of a sensor's error
REGIMES = {"long": 20.0, "short": 2.0}                # the length-scale of each field, km
THETA = ["mu", "amp", "ell", "sigma"]
SQRT3 = np.sqrt(3.0)


def matern32(d, ell):
    """The Matern 3/2 correlation at distance d."""
    a = SQRT3 * d / ell
    return (1 + a) * np.exp(-a)


def simulate_field(ell, rng, pad=2):
    """One draw of a unit-variance Matern 3/2 field on the lattice, by circulant embedding on a torus `pad` times as wide."""
    n, h = N_GRID * pad, SIDE / N_GRID
    lag = np.minimum(np.arange(n), n - np.arange(n)) * h                 # distances on the torus
    target = matern32(np.hypot(lag[:, None], lag[None, :]), ell)
    eig = np.fft.fft2(target).real                                       # eigenvalues of the circulant covariance
    eig = np.clip(eig, 0, None)                                          # tiny negative ones are set to zero ...
    worst = np.abs(np.fft.ifft2(eig).real - target)[:N_GRID, :N_GRID].max()   # ... which moves the covariance by this much
    z = rng.standard_normal((n, n)) + 1j * rng.standard_normal((n, n))
    return np.fft.fft2(np.sqrt(eig / n**2) * z).real[:N_GRID, :N_GRID].copy(), worst


def make_network(ell, rng, sigma=TRUE["sigma"]):
    """A field, 100,000 sensors at lattice nodes drawn at random, and the nodes nobody measures."""
    field, worst = simulate_field(ell, rng)
    field = TRUE["mu"] + TRUE["amp"] * field
    ii, jj = np.divmod(np.arange(N_GRID * N_GRID), N_GRID)
    on_map = (ii % 8 == 4) & (jj % 8 == 4)                               # 128 x 128 nodes kept free of sensors: the map
    on_score = (ii % 16 == 4) & (jj % 16 == 4)                           # 64 x 64 of them: scored with full predictive draws
    node_xy = lambda idx: (np.column_stack([ii[idx], jj[idx]]) + 0.5) * (SIDE / N_GRID) - SIDE / 2
    pick = rng.choice(np.flatnonzero(~on_map), size=N_SENSORS, replace=False)      # random order: Vecchia will use it
    y = field.ravel()[pick] + sigma * rng.standard_normal(N_SENSORS)
    return dict(ell=ell, sigma=sigma, field=field, worst=worst, xy=node_xy(pick), y=y,
                xy_map=node_xy(np.flatnonzero(on_map)), f_map=field.ravel()[on_map],
                xy_score=node_xy(np.flatnonzero(on_score)), f_score=field.ravel()[on_score])


nets = {name: make_network(ell, np.random.default_rng([RANDOM_SEED, i])) for i, (name, ell) in enumerate(REGIMES.items())}
for name, net in nets.items():
    f = (net["field"] - TRUE["mu"]) / TRUE["amp"]
    print(f"{name:>5} field, length-scale {net['ell']:>4.0f} km: covariance within {net['worst']:.1e} of the Matern 3/2 at every lag; "
          f"this draw has mean {net['field'].mean():+.2f} C and sd {net['field'].std():.2f} C; "
          f"{len(net['y']):,} readings, {len(net['f_map']):,} map nodes, {len(net['f_score']):,} of them scored")
 long field, length-scale   20 km: covariance within 6.6e-05 of the Matern 3/2 at every lag; this draw has mean +0.37 C and sd 1.76 C; 100,000 readings, 16,384 map nodes, 4,096 of them scored
short field, length-scale    2 km: covariance within 2.2e-16 of the Matern 3/2 at every lag; this draw has mean +0.96 C and sd 1.99 C; 100,000 readings, 16,384 map nodes, 4,096 of them scored
fig, axes = plt.subplots(2, 3, figsize=(13.5, 8.2), gridspec_kw={"width_ratios": [1.25, 1, 1]})
half = SIDE / 2
for row, (name, net) in zip(axes, nets.items()):
    lim = np.abs(net["field"] - TRUE["mu"]).max()
    kw = dict(cmap=DIVERGING, vmin=TRUE["mu"] - lim, vmax=TRUE["mu"] + lim)
    im = row[0].imshow(net["field"][::2, ::2].T, origin="lower", extent=[-half, half, -half, half], **kw)
    row[0].set_title(f"The {name} field: length-scale {net['ell']:.0f} km", loc="left")
    fig.colorbar(im, ax=row[0], pad=0.02, label="temperature departure (C)")
    x0, y0, w = -5.0, -5.0, 10.0
    row[0].add_patch(plt.Rectangle((x0, y0), w, w, fill=False, ec=INK, lw=1.2))
    h = SIDE / N_GRID
    i0, i1 = int((x0 + half) / h), int((x0 + w + half) / h)
    row[1].imshow(net["field"][i0:i1, i0:i1].T, origin="lower", extent=[x0, x0 + w, y0, y0 + w], **kw)
    row[1].set_title("The truth in the 10 km box", loc="left")
    inside = (np.abs(net["xy"][:, 0]) < w / 2) & (np.abs(net["xy"][:, 1]) < w / 2)
    row[2].scatter(net["xy"][inside, 0], net["xy"][inside, 1], c=net["y"][inside], s=9, lw=0, **kw)
    row[2].set_xlim(x0, x0 + w)
    row[2].set_ylim(y0, y0 + w)
    row[2].set_aspect("equal")
    row[2].set_title(f"The {inside.sum():,} readings in the box", loc="left")
    for ax in row:
        ax.grid(False)
        ax.set_xlabel("km")
    row[0].set_ylabel("km");
Figure

On the left are the two truths over the whole region. The long field has a handful of warm and cool patches, the short field hundreds. In the middle is a 10 km box of each, and on the right are the readings that fall in it, about a thousand of them, ten per square kilometre. In the long field the truth barely changes across the box, and what the sensors show is almost pure noise around it. In the short field the pattern of the truth is still visible through the noise.

The printed lines say what covariance the truth really has. For the short field every eigenvalue of the embedding is non-negative, so the draw is an exact Matérn 3/2 field at the nodes, to rounding. For the long field a few eigenvalues were negative and were set to zero, which moves the covariance by at most 0.00007 of the field's variance at any lag: the long truth is a Matérn 3/2 field to four decimal places. One more thing is worth reading off. This draw of the long field has a standard deviation of 1.8 °C and a mean 0.6 °C below the process mean of 1 °C. That is not an error. A region only five length-scales wide holds a few dozen independent patches, so a single draw says little about the mean and the variance of the process. Any honest method must report wide intervals for $\mu$ and $a$ on this field.

The choice. A truth simulated on a fine lattice by circulant embedding, with sensors at random nodes, and scoring against the true field at nodes no sensor occupies. Rejected: a draw from a finite sum of random sines (it would be an approximation with a tunable error, and close kin to the HSGP), and sensors at arbitrary positions with the field interpolated between nodes (the truth would then carry an interpolation error of its own). What would change our mind: a real network of this size with a licence we could read. We did not find one quickly, and no real network comes with the true field between its sensors. Part 8 uses a registered real dataset of a size where the exact answer is available instead.

2 · What exactness costs, and how to fit four numbers at this size

The exact GP, on what fits

All four models share their priors, which are loose on purpose: the readings will dominate them.

$$\mu \sim \mathrm N(0, 5), \qquad a \sim \mathrm{LogNormal}(0, 1), \qquad \ell \sim \mathrm{LogNormal}(\log 10, 1.5), \qquad \sigma \sim \mathrm{LogNormal}(0, 1).$$

The length-scale prior has its median at 10 km and puts 90% of its mass between 0.85 and 118 km, so it favours neither of our two fields. The exact model is PyMC's own, pm.gp.Marginal: the readings are multivariate normal with covariance $K + \sigma^2 I$. It is the reference for everything else, and it can only be run on a subsample.

def priors(ell_median=10.0):
    mu = pm.Normal("mu", 0.0, 5.0)
    amp = pm.LogNormal("amp", 0.0, 1.0)
    ell = pm.LogNormal("ell", np.log(ell_median), 1.5)
    sigma = pm.LogNormal("sigma", 0.0, 1.0)
    return mu, amp, ell, sigma


def exact_model(X, y, **prior):
    with pm.Model() as model:
        mu, amp, ell, sigma = priors(**prior)
        gp = pm.gp.Marginal(mean_func=pm.gp.mean.Constant(mu), cov_func=amp**2 * pm.gp.cov.Matern32(2, ls=ell))
        gp.marginal_likelihood("y", X=X, y=y, sigma=sigma)
    return model


def pairdist(a, b):
    d2 = (a**2).sum(1)[:, None] + (b**2).sum(1)[None, :] - 2 * a @ b.T
    return np.sqrt(np.maximum(d2, 0))


def predict_exact(theta, X, y, xnew, block=1024):
    """Mean and sd of the field at new points, given the hyperparameters; the new points are taken a block at a time."""
    mu, amp, ell, sigma = theta
    chol = cholesky(amp**2 * matern32(pairdist(X, X), ell) + sigma**2 * np.eye(len(y)), lower=True)
    alpha = solve_triangular(chol, y - mu, lower=True)
    mean, sd = np.empty(len(xnew)), np.empty(len(xnew))
    for s in range(0, len(xnew), block):
        v = solve_triangular(chol, amp**2 * matern32(pairdist(X, xnew[s:s + block]), ell), lower=True)
        mean[s:s + block], sd[s:s + block] = mu + v.T @ alpha, np.sqrt(amp**2 - (v**2).sum(0))
    return mean, sd

Four numbers, one gradient at a time

With the field integrated out, the posterior lives in four dimensions: $\theta = (\mu, \log a, \log \ell, \log\sigma)$. PyMC builds its log density for us, whatever the likelihood, and get_jaxified_graph hands it over as a JAX function that we can differentiate. What we do with that function is our choice, and the choice is forced by a count. NUTS on four well-behaved parameters takes four chains of 1,400 steps with a few gradients each, about 20,000 gradients (we will count them in part 3). At 100,000 readings one gradient of the Vecchia or the inducing-point likelihood costs between a tenth of a second and a second. That is hours per fit, and we have about thirty fits to make.

So we use the oldest approximation there is. Find the mode by Newton's method, take the curvature there, and treat the posterior of $\theta$ as Gaussian with that mean and that inverse curvature (a Laplace approximation, as in E125 and E129). In four dimensions the Hessian costs four extra gradients by finite differences, and Newton's method needs a handful of steps, so a fit costs 15 to 100 gradients instead of 20,000. pymc_extras.fit_laplace (E125) packages the same idea. We write it out because here the gradient is the unit of cost and we want to count every one.

Predictions then average over the uncertainty in $\theta$: we take eight draws of $\theta$ and, for each, forty draws of the field from its Gaussian predictive distribution.

def to_natural(x):
    """(mu, log amp, log ell, log sigma) -> (mu, amp, ell, sigma)."""
    x = np.asarray(x)
    return np.concatenate([x[..., :1], np.exp(x[..., 1:])], axis=-1)


def laplace(model, start, rng, n_draws=2000, tol=1e-3, max_iter=25, h=1e-4):
    """Mode and curvature of the posterior of (mu, log amp, log ell, log sigma): Newton steps on finite-difference Hessians."""
    logp = get_jaxified_graph(inputs=model.value_vars, outputs=[model.logp()])     # the model's log density, as a JAX function
    value_and_grad = jax.jit(jax.value_and_grad(lambda x: logp(x[0], x[1], x[2], x[3])[0]))
    calls = [0]

    def f(x):
        calls[0] += 1
        value, grad = value_and_grad(jnp.asarray(x))
        return float(value), np.asarray(grad)

    t0 = time.perf_counter()
    x = np.asarray(start, dtype=float)
    value, grad = f(x)
    first = time.perf_counter() - t0                                    # the first call pays for the compilation
    for _ in range(max_iter):
        hessian = np.column_stack([(f(x + h * e)[1] - grad) / h for e in np.eye(4)])      # four more gradients
        curvature, vectors = np.linalg.eigh(-(hessian + hessian.T) / 2)
        curvature = np.maximum(np.abs(curvature), 1e-2)                 # a direction that curves the wrong way is flipped
        cov = (vectors / curvature) @ vectors.T
        step = cov @ grad
        if grad @ step < tol:                                           # twice the gain in log density a full step would bring
            break
        step *= min(1.0, 0.7 / np.abs(step).max())                      # never move a parameter by more than a factor of two
        size = 1.0
        while True:
            new_value, new_grad = f(x + size * step)
            if np.isfinite(new_value) and new_value > value:
                break
            size /= 2
        x, value, grad = x + size * step, new_value, new_grad
    seconds = time.perf_counter() - t0
    return dict(mode=x, cov=cov, draws=to_natural(rng.multivariate_normal(x, cov, size=n_draws)), gradients=calls[0],
                seconds=seconds, ms_per_gradient=1e3 * (seconds - first) / max(calls[0] - 1, 1))


def interval_table(fits):
    """Median and 90% interval of each hyperparameter, one row per fit."""
    rows = {}
    for name, draws in fits.items():
        lo, mid, hi = np.quantile(draws, [(1 - CI) / 2, 0.5, (1 + CI) / 2], axis=0)
        rows[name] = {k: f"{mid[i]:.3g} [{lo[i]:.3g}, {hi[i]:.3g}]" for i, k in enumerate(THETA)}
    return pd.DataFrame(rows).T


def predictive_draws(predict, hyper, rng, n_hyper=8, per_hyper=40):
    """Draws of the field at new points: a few hyperparameter draws, and for each the Gaussian predictive given them."""
    out = []
    for theta in hyper[:n_hyper]:
        mean, sd = predict(theta)
        out.append((mean + sd * rng.standard_normal((per_hyper, len(mean)))).astype(np.float32))
    return np.concatenate(out)


START = np.array([0.0, 0.0, np.log(10.0), 0.0])                         # the prior medians
long_net = nets["long"]
demo = rng.choice(N_SENSORS, 2000, replace=False)
demo_fit = laplace(exact_model(long_net["xy"][demo], long_net["y"][demo]), START, rng)
per_gradient = demo_fit["ms_per_gradient"] / 1e3
print(f"exact GP on 2,000 readings of the long field: {demo_fit['gradients']} gradients, {per_gradient * 1e3:.0f} ms each, "
      f"{demo_fit['seconds']:.1f} s in all")
print(f"the same gradient on {N_SENSORS:,} readings, by the cube of the size: {per_gradient * 50**3 / 3600:.1f} hours, "
      f"on a matrix of {N_SENSORS**2 * 8 / 1e9:.0f} GB")
interval_table({"exact on 2,000, Laplace": demo_fit["draws"]})
exact GP on 2,000 readings of the long field: 25 gradients, 179 ms each, 4.7 s in all
the same gradient on 100,000 readings, by the cube of the size: 6.2 hours, on a matrix of 80 GB
mu amp ell sigma
exact on 2,000, Laplace 0.51 [-0.333, 1.37] 1.77 [1.41, 2.19] 16.3 [13.1, 19.9] 0.968 [0.941, 0.995]

The fit took 25 gradients of about 0.2 s each. The same gradient on all 100,000 readings would take six to seven hours and a matrix of 80 GB: the cube of the size is not negotiable.

The table shows what 2,000 readings of the long field can say. The noise is known to 3%. The standard deviation of the field and its length-scale are known to about 20%, and the mean hardly at all, for the reason given above: this region holds few independent patches. Two of the intervals end just short of the truth (19.9 km against 20, and 0.995 °C against 1). A 90% interval does that one time in ten, and for the length-scale there is a second reason, which is a limit of the shortcut. On a subsample the posterior of $a$ and $\ell$ is skewed to the right even on the log scale, and a Gaussian centred at the mode cuts its upper tail. We measured this outside the notebook, on 500 readings of a long field drawn with another seed, where NUTS on the exact GP takes 90 seconds and 21,000 gradients: NUTS gave $\ell$ = 19.0 km with a 90% interval from 14.3 to 26.8, the Laplace approximation 17.6 km from 13.2 to 23.2, and the same pattern for $a$; the mean and the noise agreed. So read the upper ends of the subsample's intervals for $a$ and $\ell$ as somewhat too short. Part 3 repeats the check where it matters more, on all 100,000 readings.

The choice. Every row of this notebook is fitted by mode and curvature in $(\mu, \log a, \log\ell, \log\sigma)$, so that all methods are treated alike and the cost of a fit is a count of gradients. Rejected: NUTS for every row (hours for the Vecchia and inducing-point rows), and NUTS for the cheap rows only (the scoreboard would then compare methods fitted in different ways). What would change our mind: a posterior that is not close to Gaussian in these coordinates. On subsamples it is skewed and we say so; on the full data we check it next.

3 · A low rank from sines: the HSGP, with its weights integrated out

The Hilbert-space GP replaces the field by a finite sum,

$$f(x) \approx \sum_{j=1}^{M} \beta_j\, \phi_j(x), \qquad \beta_j \sim \mathrm N\big(0,\ S(\omega_j)\big),$$

where the $\phi_j$ are products of sines on a box $[-L, L]^2$ a little larger than the region (they are the eigenfunctions of the Laplacian that vanish on the boundary of the box), $\omega_j$ is the frequency of the $j$-th one, and $S$ is the spectral density of the kernel: how much of the field's variance lives at each frequency. The functions do not depend on the hyperparameters. Only the prior variances of the weights do. With $m$ sines per axis there are $M = m^2$ functions in two dimensions.

In earlier notebooks the weights $\beta$ were sampled. Here we integrate them out. The readings are $y = \mu + \Phi\beta + \varepsilon$ with $\Phi$ the $n \times M$ matrix of basis functions at the sensors, so $y \sim \mathrm N(\mu,\ \Phi S \Phi^\top + \sigma^2 I)$, and the two standard identities for a low rank plus a diagonal give, with $r = y - \mu$ and $Z = \Phi^\top\Phi + \sigma^2 S^{-1}$,

$$\log\left|\Phi S \Phi^\top + \sigma^2 I\right| = (n - M)\log\sigma^2 + \log|Z| + \sum_j \log S_j, \qquad r^\top(\Phi S\Phi^\top + \sigma^2 I)^{-1} r = \frac{r^\top r - (\Phi^\top r)^\top Z^{-1}\, \Phi^\top r}{\sigma^2}.$$

Look at where the readings enter: only through $\Phi^\top\Phi$, $\Phi^\top y$, $\Phi^\top 1$ and three sums. None of these depends on a hyperparameter. This is the lesson of E126 in a new place: before reaching for a faster sampler, check whether the likelihood can be made smaller exactly. One pass over the 100,000 readings, in blocks, leaves an $M \times M$ matrix, and from then on a gradient costs one Cholesky factorisation of that matrix, whatever $n$ is. The $n \times M$ matrix $\Phi$ is never held.

pm.gp.HSGP supplies the spectral weights through prior_linearized. The basis we evaluate ourselves, block by block, and check against PyMC's.

def hsgp_basis(xy, m, L):
    """The m x m sine functions of a box [-L, L]^2 (or [-Lx, Lx] x [-Ly, Ly]) at the points xy, in PyMC's order."""
    Lx, Ly = np.broadcast_to(L, 2)
    j = np.arange(1, m + 1) * np.pi / 2                                 # the square root of an eigenvalue is j pi / (2 L)
    px = np.sin(j / Lx * (xy[:, :1] + Lx)) / np.sqrt(Lx)
    py = np.sin(j / Ly * (xy[:, 1:] + Ly)) / np.sqrt(Ly)
    return (py[:, :, None] * px[:, None, :]).reshape(len(xy), m * m)    # the first axis runs fastest


def hsgp_statistics(xy, y, m, L, block=4000):
    """Everything the likelihood needs from the readings: Phi'Phi, Phi'y, Phi'1 and three numbers. One pass, block by block."""
    G, by, b1 = np.zeros((m * m, m * m)), np.zeros(m * m), np.zeros(m * m)
    for s in range(0, len(y), block):
        P = hsgp_basis(xy[s:s + block], m, L)
        G += P.T @ P
        by += P.T @ y[s:s + block]
        b1 += P.sum(0)
    return dict(G=G, by=by, b1=b1, yy=float(y @ y), y1=float(y.sum()), n=len(y))


def hsgp_model(st, m, L, corners, **prior):
    """The HSGP with its m x m weights integrated out: a density of the four hyperparameters, built on the statistics."""
    n, M = st["n"], m * m
    with pm.Model() as model:
        mu, amp, ell, sigma = priors(**prior)
        gp = pm.gp.HSGP(m=[m, m], L=[float(v) for v in np.broadcast_to(L, 2)], cov_func=amp**2 * pm.gp.cov.Matern32(2, ls=ell))
        _, sqrt_psd = gp.prior_linearized(corners)                      # PyMC supplies the spectral weights of the kernel
        S = sqrt_psd**2                                                 # prior variance of each basis function's weight
        chol = pt.linalg.cholesky(st["G"] + pt.diag(sigma**2 / S))
        c = pt.linalg.solve_triangular(chol, st["by"] - mu * st["b1"], lower=True)
        rr = st["yy"] - 2 * mu * st["y1"] + n * mu**2                   # the sum of squared residuals about mu
        logdet = (n - M) * pt.log(sigma**2) + 2 * pt.log(pt.diag(chol)).sum() + pt.log(S).sum()
        pm.Potential("loglik", -0.5 * (n * np.log(2 * np.pi) + logdet + (rr - c @ c) / sigma**2))
        spectral = pytensor.function([amp, ell], S)
    return model, spectral


def predict_hsgp(theta, st, spectral, P_new, block=4096):
    mu, amp, ell, sigma = theta
    chol = cholesky(st["G"] + np.diag(sigma**2 / spectral(amp, ell)), lower=True)
    weights = cho_solve((chol, True), st["by"] - mu * st["b1"])
    sd = np.concatenate([np.sqrt((solve_triangular(chol, P_new[s:s + block].T, lower=True) ** 2).sum(0))
                         for s in range(0, len(P_new), block)])
    return mu + P_new @ weights, sigma * sd


CORNERS = np.array([[-1.0, -1.0], [-1.0, 1.0], [1.0, -1.0], [1.0, 1.0]]) * SIDE / 2

# two checks on 500 readings: the basis against PyMC's, and the statistics form against the dense multivariate normal
check = rng.choice(N_SENSORS, 500, replace=False)
Xc, yc, theta_c = long_net["xy"][check], long_net["y"][check], (0.7, 1.8, 15.0, 0.9)
st = hsgp_statistics(Xc, yc, 6, 90.0)
model, spectral = hsgp_model(st, 6, 90.0, CORNERS)
P = hsgp_basis(Xc, 6, 90.0)
with pm.Model():
    phi_pymc, _ = pm.gp.HSGP(m=[6, 6], L=[90.0, 90.0], cov_func=pm.gp.cov.Matern32(2, ls=10.0)).prior_linearized(np.vstack([CORNERS, Xc]))
dense = stats.multivariate_normal(np.full(500, theta_c[0]), (P * spectral(*theta_c[1:3])) @ P.T + theta_c[3] ** 2 * np.eye(500)).logpdf(yc)
ours = float(pytensor.function(model.free_RVs, model.potentials[0])(*theta_c))
print(f"basis against pm.gp.HSGP: largest difference {np.abs(phi_pymc.eval()[4:] - P).max():.1e}")
print(f"log likelihood on 500 readings: dense {dense:.6f}, from the statistics {ours:.6f}")
basis against pm.gp.HSGP: largest difference 3.5e-18
log likelihood on 500 readings: dense -858.460836, from the statistics -858.460836

Both checks pass to the last digit: our basis is PyMC's, and the likelihood computed from the statistics is the dense multivariate normal.

How many sines?

Riutort-Mayol et al. (2022) give a rule for the two settings of an HSGP: for a Matérn 3/2 kernel with length-scale $\ell$ on a region of half-width $s$, take the box $L = c\,s$ with $c \ge \max(1.2,\ 4.5\,\ell/s)$ and at least $m = 3.42\, c\, s/\ell$ functions per axis. The rule is about reproducing the kernel: with that many functions the covariance of the approximate prior is close to the Matérn's. In two dimensions the count is squared.

def hsgp_rule(ell, half_width):
    """Boundary factor and basis functions per axis for a Matern 3/2, by the rule of Riutort-Mayol et al. (2022)."""
    c = max(1.2, 4.5 * ell / half_width)
    return c, int(np.ceil(3.42 * c / (ell / half_width)))


rule = []
for ell in (40, 20, 10, 5, 2, 1):
    c, m = hsgp_rule(ell, SIDE / 2)
    rule.append({"length-scale (km)": ell, "boundary factor c": round(c, 2), "functions per axis": m, "functions in 2-D": m * m,
                 "basis matrix (GB)": round(N_SENSORS * m * m * 8 / 1e9, 2), "Phi'Phi (GB)": round((m * m) ** 2 * 8 / 1e9, 3)})
pd.DataFrame(rule).set_index("length-scale (km)")
boundary factor c functions per axis functions in 2-D basis matrix (GB) Phi'Phi (GB)
length-scale (km)
40 3.6 16 256 0.20 0.001
20 1.8 16 256 0.20 0.001
10 1.2 21 441 0.35 0.002
5 1.2 42 1764 1.41 0.025
2 1.2 103 10609 8.49 0.900
1 1.2 206 42436 33.95 14.407

The rule asks for 256 functions when the length-scale is 20 km and for 10,609 when it is 2 km. With the statistics trick the $n \times M$ basis matrix (8.5 GB at 2 km) never exists, but the $M \times M$ matrix $\Phi^\top\Phi$ does, and each gradient factorises it: 0.9 GB and a 10,609-dimensional Cholesky at 2 km, 14 GB at 1 km. In two dimensions the HSGP runs out of room quickly as the field gets rougher. We will run it at 8 to 40 functions per axis, 64 to 1,600 in all, on both fields, knowing that for the short field this is far below what the rule asks for.

NUTS, where NUTS is affordable

With 16 functions per axis a gradient costs under a millisecond, whatever $n$ is. Here NUTS is cheap, so this is where we check the Laplace shortcut on the full data. The box comes from the rule, at the length-scale the subsample suggested.

NUTS_ROW = "long · HSGP 16x16, NUTS"
c_demo, m_rule = hsgp_rule(np.median(demo_fit["draws"][:, 2]), SIDE / 2)
L_demo = c_demo * SIDE / 2
st = hsgp_statistics(long_net["xy"], long_net["y"], 16, L_demo)
model, spectral = hsgp_model(st, 16, L_demo, CORNERS)
hsgp_laplace = laplace(model, demo_fit["mode"], rng)
with model:
    with sb.track(NUTS_ROW):
        idata = pm.sample(random_seed=RANDOM_SEED, progressbar=False)
nuts_draws = np.column_stack([idata.posterior[k].values.ravel() for k in THETA])
summary = az.summary(idata, var_names=THETA, round_to=6).astype(float)
nuts_ess, nuts_gradients = summary["ess_bulk"].min(), int(idata.sample_stats["n_steps"].sum())
sb.add(NUTS_ROW, ess=nuts_ess)
print(f"NUTS: {sb.table().loc[NUTS_ROW, 'seconds']:.1f} s, {nuts_gradients:,} gradients after warm-up, smallest ESS {nuts_ess:,.0f}, "
      f"largest r_hat {summary['r_hat'].max():.3f}, {int(idata.sample_stats['diverging'].sum())} divergences")
basis = hsgp_basis(long_net["xy_score"], 16, L_demo)
sb.score(NUTS_ROW, {"field": predictive_draws(lambda th: predict_hsgp(th, st, spectral, basis), rng.permutation(nuts_draws), rng)},
         truth={"field": long_net["f_score"]})
print(f"Laplace: {hsgp_laplace['seconds']:.2f} s, {hsgp_laplace['gradients']} gradients")
interval_table({"HSGP 16x16, NUTS": nuts_draws, "HSGP 16x16, Laplace": hsgp_laplace["draws"]})
NUTS: 10.2 s, 21,208 gradients after warm-up, smallest ESS 1,497, largest r_hat 1.002, 0 divergences
Laplace: 0.14 s, 20 gradients
mu amp ell sigma
HSGP 16x16, NUTS 0.292 [-0.546, 1.08] 2 [1.71, 2.5] 13.1 [10.9, 16.3] 1.01 [1.01, 1.02]
HSGP 16x16, Laplace 0.313 [-0.402, 1.05] 1.92 [1.62, 2.3] 12.7 [10.4, 15.3] 1.01 [1.01, 1.02]

NUTS with PyMC's defaults (nutpie, four chains) takes ten to twelve seconds and 21,000 gradients, with no divergences and an $\hat R$ of 1.00. The Laplace fit takes 20 gradients and a sixth of a second. The two agree on the mean and the noise to the digits shown, and nearly on the rest: the Laplace medians of $a$ and $\ell$ are 3 to 4% lower and its upper limits about 7% shorter, the same right skew as before, much reduced. The predictions do not care. Scored on the held-out truth, the NUTS fit is on the scoreboard with an RMSE of 0.16 °C, and the Laplace fit of the same model in part 6 has 0.17 °C (its box is slightly different, because it is set from a different subsample).

That count of gradients is the number to remember. A method whose gradient costs a millisecond can be sampled. One whose gradient costs half a second cannot, on a laptop, in the time it takes to read this page.

Something else is in the table, and it is the first sign of trouble. The rule said 16 functions per axis are enough for a 20 km length-scale, and the fit reports a length-scale near 13 km with an interval that excludes 20. We come back to it in part 6.

The choice. The HSGP with its weights integrated out and the readings reduced to sufficient statistics, at 8 to 40 functions per axis, in the box the published rule gives. Rejected: sampling the weights (up to 1,600 more dimensions, and every gradient would touch every reading), and the rule's own size for the short field (10,609 functions do not fit). What would change our mind: a likelihood that is not Gaussian. The weights can then no longer be integrated out exactly, and one samples them or approximates the integral, as in E129.

4 · Neighbours: the Vecchia likelihood

Any joint density can be written as a chain of conditionals, $p(y) = \prod_i p(y_i \mid y_1, \dots, y_{i-1})$. That is exact and no cheaper. Vecchia (1988) proposed to shorten the conditioning sets:

$$p(y) \approx \prod_{i=1}^{n} p\big(y_i \mid y_{N(i)}\big), \qquad N(i) = \text{the } m \text{ nearest among the readings before } i.$$

Each factor is a small Gaussian computation on $m + 1$ points, so the cost is $n\, m^3$ instead of $n^3$, and the product is still a proper joint density: the approximation is a model, not a recipe. Nothing is smoothed and no reading is dropped. What is given up is long-range dependence that the neighbours do not carry.

Two choices have to be made. The first is the ordering, since "before" depends on it. Ordering the points along a coordinate, the usual default, does worse than a random order, and a maximin order (each point as far as possible from those before it) does a little better still (Guinness 2018). Our sensors were drawn at random, so the order of the rows is already a random order. The second is what to condition on. We apply the approximation to the readings themselves, noise included, so each factor uses the covariance $K + \sigma^2 I$ of a reading and its neighbours. This is the simplest version and it leaves a likelihood in the same four numbers. E92 uses the same approximation, with 30 neighbours in a maximin order, for a field in space and time.

For each point we build the $(m + 1) \times (m + 1)$ covariance of its neighbours and itself, with the point last. The last row of the Cholesky factor then holds everything we need: its diagonal entry is the conditional standard deviation of the reading given its neighbours, and the last element of the solved residual is the reading's standardised surprise. The factorisations are independent, so they are done thousands at a time by one batched jnp.linalg.cholesky.

Memory decides how the gradient is computed. Reverse-mode differentiation through all the blocks would keep every small matrix alive until the backward pass: at 20 neighbours that is $100{,}000 \times 21^2$ numbers, 353 MB, for each of several intermediate arrays. But the log likelihood is a sum over blocks of points, and the gradient of a sum is the sum of the gradients. So we tell JAX exactly that with jax.custom_vjp: value and gradient are computed one block at a time and added up, and the memory is that of one block. The function enters the PyMC model through pytensor.wrap_jax, as in E129.

Prediction uses the same idea: each new place is conditioned on its $m$ nearest readings.

def earlier_neighbours(xy, m):
    """For each point, the m nearest among the points before it in the row order; -1 where there are fewer than m."""
    n = len(xy)
    nb = np.full((n, m), -1, dtype=np.int32)
    for i in range(1, min(m + 1, n)):
        nb[i, :i] = np.arange(i)
    a = m + 1
    while a < n:                                                        # points a .. 2a-1 search a tree of the first 2a points
        b = min(2 * a, n)
        tree, todo, k = cKDTree(xy[:b]), np.arange(a, b), min(3 * m + 8, b)
        while len(todo):
            _, idx = tree.query(xy[todo], k=k)
            earlier = idx < todo[:, None]
            rank = np.cumsum(earlier, axis=1)
            done = rank[:, -1] >= m                                     # found m earlier points among the k nearest
            nb[todo[done]] = idx[done][(earlier & (rank <= m))[done]].reshape(-1, m)
            todo, k = todo[~done], min(2 * k, b)                        # the others look further
        a = b
    return nb


def jax_matern32(d, ell):
    a = SQRT3 * d / ell
    return (1 + a) * jnp.exp(-a)


def vecchia_loglik(xy, y, nb, block):
    """log p(y) as a sum of n conditionals, each on m earlier neighbours; value and gradient one block of points at a time."""
    n, m = nb.shape
    pad = (-n) % block
    rows = jnp.asarray(np.concatenate([np.arange(n), np.zeros(pad, int)]).reshape(-1, block))
    keep = jnp.asarray(np.concatenate([np.ones(n), np.zeros(pad)]).reshape(-1, block))
    xy_j, y_j, nb_j = jnp.asarray(xy), jnp.asarray(y), jnp.asarray(nb)

    def block_loglik(mu, amp, ell, sigma, row, w):
        nbr = nb_j[row]
        present = jnp.concatenate([nbr >= 0, jnp.ones((block, 1), bool)], axis=1)       # the point itself comes last
        idx = jnp.concatenate([jnp.maximum(nbr, 0), row[:, None]], axis=1)
        pts, r = xy_j[idx], jnp.where(present, y_j[idx] - mu, 0.0)
        d = jnp.sqrt(((pts[:, :, None, :] - pts[:, None, :, :]) ** 2).sum(-1) + 1e-20)
        K = amp**2 * jax_matern32(d, ell) + sigma**2 * jnp.eye(m + 1)
        K = jnp.where(present[:, :, None] & present[:, None, :], K, jnp.eye(m + 1))     # a missing neighbour drops out
        chol = jnp.linalg.cholesky(K)                                                   # `block` small factorisations at once
        z = jax_solve(chol, r[..., None], lower=True)[..., 0]
        # the last row of each factor holds the conditional sd of the point given its neighbours, and its residual
        return (w * -0.5 * (jnp.log(2 * jnp.pi) + 2 * jnp.log(chol[:, -1, -1]) + z[:, -1] ** 2)).sum()

    block_grad = jax.value_and_grad(block_loglik, argnums=(0, 1, 2, 3))

    @jax.custom_vjp
    def loglik(mu, amp, ell, sigma):
        return jax.lax.map(lambda a: block_loglik(mu, amp, ell, sigma, *a), (rows, keep)).sum()

    def value_and_gradient(mu, amp, ell, sigma):                        # the gradient of a sum, one block at a time
        values, grads = jax.lax.map(lambda a: block_grad(mu, amp, ell, sigma, *a), (rows, keep))
        return values.sum(), tuple(g.sum() for g in grads)

    loglik.defvjp(value_and_gradient, lambda grads, ct: tuple(ct * g for g in grads))
    return loglik


def vecchia_model(xy, y, nb, block, **prior):
    with pm.Model() as model:
        mu, amp, ell, sigma = priors(**prior)
        pm.Potential("loglik", pytensor.wrap_jax(vecchia_loglik(xy, y, nb, block))(mu, amp, ell, sigma))
    return model


_PREDICTOR = {}


def predict_vecchia(theta, xy, y, tree, xnew, m):
    """Each new point conditioned on its m nearest readings."""
    block = 1024 if m <= 20 else 256 if m <= 60 else 128             # keeps a block of m x m matrices near 15 MB
    if m not in _PREDICTOR:
        def one(pts, r, x0, th):
            mu, amp, ell, sigma = th
            d = jnp.sqrt(((pts[:, None, :] - pts[None, :, :]) ** 2).sum(-1) + 1e-20)
            chol = jnp.linalg.cholesky(amp**2 * jax_matern32(d, ell) + sigma**2 * jnp.eye(m))
            v = jax_solve(chol, amp**2 * jax_matern32(jnp.sqrt(((pts - x0) ** 2).sum(-1) + 1e-20), ell), lower=True)
            return mu + v @ jax_solve(chol, r - mu, lower=True), jnp.sqrt(amp**2 - v @ v)
        _PREDICTOR[m] = jax.jit(lambda P, R, X0, th: jax.lax.map(lambda a: jax.vmap(one, (0, 0, 0, None))(*a, th), (P, R, X0)))
    idx = tree.query(xnew, k=m)[1]
    n = len(xnew)
    pad = (-n) % block
    idx = np.concatenate([idx, np.zeros((pad, m), int)])
    x0 = np.concatenate([xnew, np.zeros((pad, 2))])
    mean, sd = _PREDICTOR[m](jnp.asarray(xy[idx].reshape(-1, block, m, 2)), jnp.asarray(y[idx].reshape(-1, block, m)),
                             jnp.asarray(x0.reshape(-1, block, 2)), jnp.asarray(theta))
    return np.asarray(mean).ravel()[:n], np.asarray(sd).ravel()[:n]


# two checks: the neighbour search against brute force, and "every earlier point is a neighbour" against the exact likelihood
Xn = long_net["xy"][:2000]
nb = earlier_neighbours(Xn, 10)
D = pairdist(Xn, Xn)
wrong = sum(not np.allclose(np.sort(D[i, :i])[:10], np.sort(D[i, nb[i]]), atol=1e-9) for i in range(11, 2000, 13))
Xc, yc = Xc[:300], yc[:300]
exact = stats.multivariate_normal(np.full(300, theta_c[0]), theta_c[1] ** 2 * matern32(pairdist(Xc, Xc), theta_c[2])
                                  + theta_c[3] ** 2 * np.eye(300)).logpdf(yc)
full = float(vecchia_loglik(Xc, yc, earlier_neighbours(Xc, 299), 100)(*map(jnp.asarray, theta_c)))
del D
print(f"neighbour sets that differ from brute force, of {len(range(11, 2000, 13))} checked: {wrong}")
print(f"log likelihood on 300 readings: exact {exact:.8f}, Vecchia with 299 neighbours {full:.8f}")
neighbour sets that differ from brute force, of 153 checked: 0
log likelihood on 300 readings: exact -482.19596880, Vecchia with 299 neighbours -482.19596880

Both checks pass. The neighbour sets are the ones a brute-force search finds, and with every earlier point as a neighbour the Vecchia likelihood is the exact one to eight decimal places, as it must be.

The choice. The readings in their random order, each conditioned on its $m$ nearest predecessors, with $m$ = 5, 10 and 20; value and gradient in blocks, by a hand-written rule. Rejected: a maximin ordering (better in principle, and one more algorithm to write and check, for a gain over a random order that we did not measure), and plain reverse-mode differentiation (several arrays of 353 MB each at 20 neighbours). What would change our mind: a field with strong dependence at long range that neighbours do not carry. Part 6 finds exactly that on the long field.

5 · A low rank from points: inducing points and Titsias's bound

The third method summarises the field by its values $u$ at $M$ inducing points $z_1, \dots, z_M$. If the field elsewhere is taken to be its interpolation from $u$, the covariance of the readings becomes $Q + \sigma^2 I$ with the low-rank matrix $Q = K_{fu} K_{uu}^{-1} K_{uf}$. Titsias (2009) derived this as a variational approximation and showed that the right objective is not the likelihood of that low-rank model alone but a lower bound on the exact log likelihood,

$$\log p(y) \ \ge\ \log \mathrm N\big(y \mid \mu,\ Q + \sigma^2 I\big) - \frac{1}{2\sigma^2}\, \mathrm{tr}\big(K_{ff} - Q\big).$$

The second term is the variance of the field that the inducing points cannot explain, summed over the readings, and it is charged as a penalty. pm.gp.MarginalApprox(approx="VFE") is this bound. The older FITC approximation (Snelson and Ghahramani 2006), approx="FITC" in PyMC, puts the unexplained variance on the diagonal of the covariance instead. We run the bound only.

The algebra is the same low rank plus diagonal as for the HSGP, with one costly difference. The matrix $K_{uf}$ of covariances between inducing points and readings depends on the length-scale, so nothing can be computed once and for all: every gradient touches every reading, at a cost of $n M^2$. Two things can still be saved. The amplitude factors out of the kernel, so the sums over readings that the bound needs, $C_{uf} C_{fu}$, $C_{uf}\, y$ and $C_{uf} 1$ with $C$ the correlation, depend on $\ell$ alone. And they are sums over readings, so they can be accumulated block by block together with their derivative in $\ell$, which keeps the memory at one block of $C$ instead of the whole $n \times M$ matrix. The inducing points sit on a regular $k \times k$ grid over the region.

def inducing_grid(k):
    g = (np.arange(k) + 0.5) / k * SIDE - SIDE / 2
    return np.column_stack([a.ravel() for a in np.meshgrid(g, g, indexing="ij")])


def jax_dist(a, b):
    return jnp.sqrt(((a[:, None, :] - b[None, :, :]) ** 2).sum(-1) + 1e-20)


def vfe_statistics(xy, y, xu, block=4000):
    """C_uf C_fu, C_uf y and C_uf 1 for a length-scale, accumulated block by block, with their slope in the length-scale."""
    n, M = len(y), len(xu)
    pad = (-n) % block
    xy_b = jnp.asarray(np.concatenate([xy, np.zeros((pad, 2))]).reshape(-1, block, 2))
    y_b = jnp.asarray(np.concatenate([y, np.zeros(pad)]).reshape(-1, block))
    w_b = jnp.asarray(np.concatenate([np.ones(n), np.zeros(pad)]).reshape(-1, block))
    xu_j = jnp.asarray(xu)
    zeros = (jnp.zeros((M, M)), jnp.zeros(M), jnp.zeros(M))

    def raw(ell):
        def add(acc, a):
            x, yb, w = a
            C = jax_matern32(jax_dist(x, xu_j), ell) * w[:, None]       # correlations of a block with the inducing points
            return (acc[0] + C.T @ C, acc[1] + C.T @ yb, acc[2] + C.sum(0)), None
        return jax.lax.scan(add, zeros, (xy_b, y_b, w_b))[0]

    def with_slope(ell):
        def add(acc, a):
            (S, sy, s1), (dS, dsy, ds1) = acc
            x, yb, w = a
            arg = SQRT3 * jax_dist(x, xu_j) / ell
            decay = jnp.exp(-arg) * w[:, None]
            C, dC = (1 + arg) * decay, arg**2 * decay / ell             # the correlation and its derivative in ell
            return ((S + C.T @ C, sy + C.T @ yb, s1 + C.sum(0)), (dS + dC.T @ C, dsy + dC.T @ yb, ds1 + dC.sum(0))), None
        total, (dS, dsy, ds1) = jax.lax.scan(add, (zeros, zeros), (xy_b, y_b, w_b))[0]
        return total, (dS + dS.T, dsy, ds1)

    @jax.custom_vjp
    def statistics(ell):
        return raw(ell)

    statistics.defvjp(with_slope, lambda slope, ct: (sum((c * s).sum() for c, s in zip(ct, slope)),))
    return statistics, jax.jit(raw)


def vfe_loglik(xy, y, xu, block=4000, jitter=1e-6):
    """Titsias's collapsed bound on log p(y), with M inducing points at xu."""
    n, M = len(y), len(xu)
    statistics, raw = vfe_statistics(xy, y, xu, block)
    xu_j, yy, y1 = jnp.asarray(xu), float(y @ y), float(y.sum())

    def loglik(mu, amp, ell, sigma):
        C1, cy, c1 = statistics(ell)
        chol_u = jnp.linalg.cholesky(jax_matern32(jax_dist(xu_j, xu_j), ell) + jitter / amp**2 * jnp.eye(M))
        AAt = (amp / sigma) ** 2 * jax_solve(chol_u, jax_solve(chol_u, C1, lower=True).T, lower=True)
        chol_b = jnp.linalg.cholesky(jnp.eye(M) + AAt)
        c = jax_solve(chol_b, amp / sigma**2 * jax_solve(chol_u, cy - mu * c1, lower=True), lower=True)
        rr = yy - 2 * mu * y1 + n * mu**2
        fit = -0.5 * (n * jnp.log(2 * jnp.pi * sigma**2) + 2 * jnp.log(jnp.diag(chol_b)).sum() + rr / sigma**2 - c @ c)
        return fit - 0.5 * (n * amp**2 / sigma**2 - jnp.trace(AAt))      # the trace term: the variance the inducing points miss
    return loglik, raw


def vfe_model(xy, y, xu, block=4000, **prior):
    loglik, raw = vfe_loglik(xy, y, xu, block)
    with pm.Model() as model:
        mu, amp, ell, sigma = priors(**prior)
        pm.Potential("loglik", pytensor.wrap_jax(loglik)(mu, amp, ell, sigma))
    return model, raw


def predict_vfe(theta, raw, xu, xnew, jitter=1e-6, block=4096):
    mu, amp, ell, sigma = theta
    C1, cy, c1 = (np.asarray(a) for a in raw(jnp.asarray(float(ell))))   # one more pass over the readings
    M = len(xu)
    chol_u = cholesky(matern32(pairdist(xu, xu), ell) + jitter / amp**2 * np.eye(M), lower=True)
    AAt = (amp / sigma) ** 2 * solve_triangular(chol_u, solve_triangular(chol_u, C1, lower=True).T, lower=True)
    chol_b = cholesky(np.eye(M) + AAt, lower=True)
    c = solve_triangular(chol_b, amp / sigma**2 * solve_triangular(chol_u, cy - mu * c1, lower=True), lower=True)
    mean, sd = np.empty(len(xnew)), np.empty(len(xnew))
    for s in range(0, len(xnew), block):
        v1 = solve_triangular(chol_u, amp * matern32(pairdist(xu, xnew[s:s + block]), ell), lower=True)
        v2 = solve_triangular(chol_b, v1, lower=True)
        mean[s:s + block], sd[s:s + block] = mu + v2.T @ c, np.sqrt(amp**2 - (v1**2).sum(0) + (v2**2).sum(0))
    return mean, sd


# the check: PyMC's own inducing-point likelihood on 2,000 readings and 64 inducing points
Xc, yc, xu = long_net["xy"][demo], long_net["y"][demo], inducing_grid(8)
ours = float(vfe_loglik(Xc, yc, xu, block=500)[0](*map(jnp.asarray, theta_c)))
with pm.Model() as model:
    gp = pm.gp.MarginalApprox(mean_func=pm.gp.mean.Constant(theta_c[0]), cov_func=theta_c[1] ** 2 * pm.gp.cov.Matern32(2, ls=theta_c[2]),
                              approx="VFE")
    gp.marginal_likelihood("y", X=Xc, Xu=xu, y=yc, sigma=theta_c[3])
    theirs = float(model.compile_logp()({}))
print(f"collapsed bound on 2,000 readings with 64 inducing points: pm.gp.MarginalApprox {theirs:.6f}, block by block {ours:.6f}")
collapsed bound on 2,000 readings with 64 inducing points: pm.gp.MarginalApprox -3557.553912, block by block -3557.553912

The two numbers agree to six decimal places, so the block-by-block version is PyMC's bound.

Is pm.gp.MarginalApprox itself usable at this size in PyMC 6.3.2? We measured it outside the notebook, under the same 3 GB cap, on the 100,000 readings: it builds the whole $n \times M$ matrix in the graph, and one gradient took 0.28 s with a peak of 1.7 GB at 144 inducing points, 0.82 s and 2.8 GB at 324, and the process was killed at the cap with 576. So it is usable up to about 300 inducing points. The version above runs 576 within the same cap (part 6), because it never holds more than one block of the matrix.

The choice. Titsias's bound with inducing points on a grid of 64 to 576, the statistics accumulated in blocks. Rejected: pm.gp.MarginalApprox at full size (memory), FITC (a second objective to derive in blocks, with a reputation for the opposite bias in the noise; Bauer, van der Wilk and Rasmussen 2016), and learning the inducing locations (hundreds of extra parameters in a notebook that counts gradients). We also leave out the SPDE approach of Lindgren, Rue and Lindström (2011), which replaces the Matérn field by a sparse Gaussian Markov random field on a mesh: it needs a sparse Cholesky factorisation with a gradient, which we would have had to write. What would change our mind: inputs in more than two or three dimensions, where neither a grid of sines nor a mesh is available and inducing points are the method left standing.

6 · The race

Each field now gets thirteen fits: the exact GP on a subsample of 2,000, the HSGP at five sizes, the Vecchia likelihood at three and inducing points at four. Two more rows reuse the last Vecchia fit with more neighbours at prediction only, an idea we explain below. Every fit is timed and watched by the scoreboard, starts from the mode of the subsample fit or of the previous size, and is scored against the true field at the 4,096 nodes of the scoring lattice. The HSGP box is set by the published rule at the length-scale the subsample found. For one setting of each method we also keep the map on all 16,384 free nodes.

HSGP_M, VECCHIA_M, VECCHIA_PREDICT, INDUCING_K = (8, 16, 24, 32, 40), ((5, 10_000), (10, 5_000), (20, 2_500)), (60, 120), (8, 12, 18, 24)
HEADLINE = ["exact on 2,000", "HSGP 32x32", "Vecchia 20", "inducing 576"]
fits, maps, settings = {}, {}, {}


def finish(regime, name, kind, size, fit, predict, net):
    """Score a fit on the 64 x 64 lattice, and keep its hyperparameter draws and, for the headline settings, its map."""
    row = f"{regime} · {name}"
    sb.score(row, {"field": predictive_draws(lambda th: predict(th, net["xy_score"]), fit["draws"], rng)}, truth={"field": net["f_score"]})
    fits[row] = fit["draws"]
    settings[row] = dict(regime=regime, family=kind, size=size, gradients=fit["gradients"], ms_per_gradient=fit["ms_per_gradient"])
    if name in HEADLINE:
        maps[row] = predict(to_natural(fit["mode"]), net["xy_map"])[0]
    jax.clear_caches()                                                  # compiled functions carry their data: let them go


def race(regime):
    net = nets[regime]
    xy, y = net["xy"], net["y"]
    # exact, on a subsample
    sub = rng.choice(N_SENSORS, 2000, replace=False)
    with sb.track(f"{regime} · exact on 2,000"):
        exact = laplace(exact_model(xy[sub], y[sub]), START, rng)
        finish(regime, "exact on 2,000", "exact", 2000, exact, lambda th, new: predict_exact(th, xy[sub], y[sub], new), net)
    # HSGP: the boundary from the published rule at the subsample's length-scale
    c, m_rule = hsgp_rule(np.exp(exact["mode"][2]), SIDE / 2)
    L, start = c * SIDE / 2, exact["mode"]
    for m in HSGP_M:
        with sb.track(f"{regime} · HSGP {m}x{m}"):
            st = hsgp_statistics(xy, y, m, L)
            model, spectral = hsgp_model(st, m, L, CORNERS)
            fit = laplace(model, start, rng)
            basis = {len(new): hsgp_basis(new, m, L) for new in (net["xy_score"], net["xy_map"])[:1 + (m == 32)]}
            finish(regime, f"HSGP {m}x{m}", "HSGP", m * m, fit, lambda th, new: predict_hsgp(th, st, spectral, basis[len(new)]), net)
        start = fit["mode"]
    # Vecchia: the readings are already in random order
    tree, start = cKDTree(xy), exact["mode"]
    for m, block in VECCHIA_M:
        with sb.track(f"{regime} · Vecchia {m}"):
            fit = laplace(vecchia_model(xy, y, earlier_neighbours(xy, m), block), start, rng)
            finish(regime, f"Vecchia {m}", "Vecchia", m, fit, lambda th, new: predict_vecchia(th, xy, y, tree, new, m), net)
        start = fit["mode"]
    for m in VECCHIA_PREDICT:                                           # the last fit, with more neighbours at prediction only
        with sb.track(f"{regime} · Vecchia 20, {m} to predict"):
            finish(regime, f"Vecchia 20, {m} to predict", "Vecchia", m, fit, lambda th, new: predict_vecchia(th, xy, y, tree, new, m), net)
        sb.add(f"{regime} · Vecchia 20, {m} to predict",
               seconds=sb.table().loc[f"{regime} · Vecchia 20, {m} to predict", "seconds"] + sb.table().loc[f"{regime} · Vecchia 20", "seconds"])
    # inducing points on a k x k grid
    start = exact["mode"]
    for k in INDUCING_K:
        xu = inducing_grid(k)
        with sb.track(f"{regime} · inducing {k * k}"):
            model, raw = vfe_model(xy, y, xu)
            fit = laplace(model, start, rng)
            finish(regime, f"inducing {k * k}", "inducing", k * k, fit, lambda th, new: predict_vfe(th, raw, xu, new), net)
        start = fit["mode"]
    return dict(c=c, m_rule=m_rule, L=L)


t0 = time.perf_counter()
geometry = {regime: race(regime) for regime in REGIMES}
race_seconds = time.perf_counter() - t0
for regime, g in geometry.items():
    print(f"{regime} field: HSGP boundary factor {g['c']:.2f} (box half-width {g['L']:.0f} km); the rule asks for {g['m_rule']} functions per axis")
board = sb.table()
print(f"{len(fits)} rows (26 fits) in {race_seconds:.0f} s; largest peak memory {board['peak_gb'].max():.2f} GB")
long field: HSGP boundary factor 1.60 (box half-width 80 km); the rule asks for 16 functions per axis
short field: HSGP boundary factor 1.20 (box half-width 60 km); the rule asks for 99 functions per axis
30 rows (26 fits) in 191 s; largest peak memory 2.01 GB

The whole race takes about three minutes and never holds more than about 2 GB. Before the results, the costs. The table has one row per fit.

runs = board.join(pd.DataFrame(settings).T).drop(index=NUTS_ROW)
runs[["size", "gradients"]] = runs[["size", "gradients"]].astype(int)
runs["ms_per_gradient"] = runs["ms_per_gradient"].astype(float)
runs["NUTS would take (min)"] = runs["ms_per_gradient"] * nuts_gradients / 6e4       # the gradients NUTS used on the HSGP above
runs[["seconds", "added_gb", "rmse", "coverage", "width", "gradients", "ms_per_gradient", "NUTS would take (min)"]].round(
    {"seconds": 1, "added_gb": 2, "rmse": 3, "coverage": 3, "width": 2, "ms_per_gradient": 1, "NUTS would take (min)": 1})
seconds added_gb rmse coverage width gradients ms_per_gradient NUTS would take (min)
method
long · exact on 2,000 7.9 0.48 0.288 0.915 1.01 30 185.1 65.4
long · HSGP 8x8 0.3 0.00 0.373 0.097 0.08 80 0.1 0.0
long · HSGP 16x16 0.4 0.01 0.171 0.311 0.14 90 0.6 0.2
long · HSGP 24x24 0.6 0.02 0.130 0.490 0.17 20 4.0 1.4
long · HSGP 32x32 1.8 0.09 0.104 0.685 0.21 15 22.4 7.9
long · HSGP 40x40 3.2 0.24 0.096 0.783 0.24 15 79.4 28.1
long · Vecchia 5 1.6 0.01 0.429 0.899 1.41 20 47.4 16.8
long · Vecchia 10 2.8 0.04 0.314 0.890 1.02 15 131.1 46.3
long · Vecchia 20 8.3 0.27 0.225 0.901 0.73 15 466.8 165.0
long · Vecchia 20, 60 to predict 9.1 0.00 0.136 0.892 0.44 15 466.8 165.0
long · Vecchia 20, 120 to predict 10.8 0.03 0.105 0.899 0.34 15 466.8 165.0
long · inducing 64 1.6 0.02 0.408 0.317 0.33 40 25.0 8.8
long · inducing 144 5.0 0.00 0.212 0.552 0.31 33 128.0 45.2
long · inducing 324 17.6 0.04 0.129 0.722 0.28 45 337.2 119.2
long · inducing 576 26.2 0.03 0.106 0.806 0.28 25 851.0 300.8
short · exact on 2,000 9.6 0.45 1.300 0.886 4.04 35 207.0 73.2
short · HSGP 8x8 0.3 0.00 1.780 0.034 0.17 35 0.1 0.0
short · HSGP 16x16 0.4 0.02 1.482 0.075 0.29 55 0.6 0.2
short · HSGP 24x24 0.6 0.01 1.261 0.119 0.38 25 4.0 1.4
short · HSGP 32x32 2.2 0.24 1.054 0.172 0.44 40 22.9 8.1
short · HSGP 40x40 4.1 0.01 0.870 0.221 0.49 25 78.8 27.8
short · Vecchia 5 1.3 0.04 0.499 0.901 1.61 15 46.9 16.6
short · Vecchia 10 2.7 0.07 0.409 0.887 1.30 15 128.9 45.6
short · Vecchia 20 5.9 0.00 0.375 0.887 1.20 10 468.3 165.5
short · Vecchia 20, 60 to predict 6.7 0.00 0.367 0.885 1.16 10 468.3 165.5
short · Vecchia 20, 120 to predict 8.5 0.00 0.364 0.881 1.16 10 468.3 165.5
short · inducing 64 2.1 0.01 1.771 0.132 0.60 55 25.9 9.1
short · inducing 144 11.0 0.00 1.639 0.159 0.68 80 126.7 44.8
short · inducing 324 34.7 0.09 1.431 0.218 0.81 95 339.0 119.8
short · inducing 576 31.8 0.13 1.237 0.290 0.92 30 880.5 311.2

Read the last three columns first. A fit needs 10 to 100 gradients. One gradient costs a tenth of a millisecond for the smallest HSGP and a full second for 576 inducing points, a factor of ten thousand. The last column multiplies that price by the 21,000 gradients NUTS used in part 3: a quarter of an hour or less for the HSGP up to 32 functions per axis, about an hour for the exact GP on 2,000 readings, nearly three hours for Vecchia with 20 neighbours, five for 576 inducing points. The three approximations differ in where $n$ sits. For the HSGP it is paid once, before the first gradient. For Vecchia every gradient costs $n\,m^3$, and for inducing points $n\,M^2$.

Memory is not what separates them. No fit added more than about half a gigabyte, because every likelihood here is computed in blocks, and the largest increments belong to the exact GP on 2,000 readings and its 32 MB matrices.

The long field

One reference line is needed before the picture. Nobody can run the exact GP on 100,000 readings, but its error can be estimated. If the sensors were a continuum with the same density, the posterior mean would be a linear filter with a known gain at each frequency, and its error variance would be an integral of the field's spectrum against the noise (the "equivalent kernel" argument; Sollich and Williams 2005). Part 7 explains the formula. It is slightly optimistic, since real sensors are scattered unevenly, and we use it as a floor.

def matern32_spectrum(w, amp, ell):
    """Spectral density of the 2-D Matern 3/2 at angular frequency w (rad/km); it integrates to amp^2 over the plane / (2 pi)^2."""
    return amp**2 * 6 * np.pi * SQRT3**3 / ell**3 * (3 / ell**2 + w**2) ** -2.5


def dense_limit(amp, ell, sigma, density):
    """Readings as a continuum: the error sd of the exact posterior mean, and the frequency where signal meets noise."""
    noise = sigma**2 / density                                          # white noise of this spectral density, C^2 km^2
    spectrum = lambda w: matern32_spectrum(w, amp, ell)
    variance = integrate.quad(lambda w: spectrum(w) * noise / (spectrum(w) + noise) * w / (2 * np.pi), 0, np.inf, limit=200)[0]
    return np.sqrt(variance), optimize.brentq(lambda w: spectrum(w) - noise, 1e-6, 1e3)


DENSITY = N_SENSORS / SIDE**2
limits = {regime: dense_limit(TRUE["amp"], ell, TRUE["sigma"], DENSITY) for regime, ell in REGIMES.items()}
for regime, (floor, w_star) in limits.items():
    best = runs[runs["regime"] == regime]["rmse"]
    print(f"{regime} field: an exact GP on all readings would err by about {floor:.3f} C (continuum of sensors); "
          f"the best row here, {best.idxmin().split(' · ')[1]}, errs by {best.min():.3f} C")


def lost_by_scale(estimate, truth, n_bins=12):
    """Share of the truth's variance missing from a 128 x 128 map, by wavelength (error spectrum over truth spectrum)."""
    n = int(np.sqrt(len(truth)))
    window = np.outer(np.hanning(n), np.hanning(n))
    power = lambda a: np.abs(np.fft.fft2(a.reshape(n, n) * window)) ** 2
    k = 2 * np.pi * np.fft.fftfreq(n, d=SIDE / n)
    kk = np.hypot(k[:, None], k[None, :]).ravel()
    edges = np.geomspace(2 * np.pi / 50, np.pi / (SIDE / n), n_bins + 1)                 # wavelengths from 50 km to two map nodes
    which = np.digitize(kk, edges)
    err, sig = power(estimate - truth).ravel(), power(truth - truth.mean()).ravel()
    share = np.array([err[which == i].sum() / sig[which == i].sum() for i in range(1, n_bins + 1)])
    return 2 * np.pi / np.sqrt(edges[:-1] * edges[1:]), share


def race_figure(regime):
    net, rows = nets[regime], runs[runs["regime"] == regime]
    fig = plt.figure(figsize=(14.5, 8.9))
    outer = fig.add_gridspec(2, 1, height_ratios=[1, 1.05], hspace=0.3)
    top = outer[0].subgridspec(1, 5, width_ratios=[1, 1, 1, 1, 0.04], wspace=0.18)
    grid = outer[1].subgridspec(1, 3, width_ratios=[1.9, 1, 1], wspace=0.24)
    scale = 2.5 * rows.loc[[f"{regime} · {name}" for name in HEADLINE], "rmse"].median()
    for i, name in enumerate(HEADLINE):
        ax = fig.add_subplot(top[0, i])
        error = (maps[f"{regime} · {name}"] - net["f_map"]).reshape(128, 128)
        im = ax.imshow(error.T, origin="lower", extent=[-SIDE / 2, SIDE / 2] * 2, cmap=DIVERGING, vmin=-scale, vmax=scale)
        ax.set_title(f"{name}\nmap error, rms {np.sqrt(np.mean(error**2)):.2f} C", loc="left", fontsize=10)
        ax.grid(False)
        ax.set_xticks([-40, 0, 40])
        ax.set_yticks([-40, 0, 40])
        ax.set_xlabel("km")
    fig.colorbar(im, cax=fig.add_subplot(top[0, 4]), label="posterior mean minus truth (C)")

    ax, ax_cover = fig.add_subplot(grid[0, 0]), fig.add_subplot(grid[0, 1])
    for kind, group in rows.groupby("family", sort=False):
        fitted = ~group.index.str.contains("to predict")
        for a, column in ((ax, "rmse"), (ax_cover, "coverage")):
            a.plot(group["seconds"], group[column], "-", color=COLOR[kind], lw=1.2, zorder=2)
            a.scatter(group["seconds"][fitted], group[column][fitted], s=38, color=COLOR[kind], zorder=3, label=kind)
            a.scatter(group["seconds"][~fitted], group[column][~fitted], s=38, facecolor="white", edgecolor=COLOR[kind], lw=1.5, zorder=3)
        for row, r in group.iterrows():
            label = {"exact": "2,000 readings", "HSGP": f"{int(np.sqrt(r['size']))}x{int(np.sqrt(r['size']))}"}.get(kind, f"{r['size']}")
            ax.annotate(label, (r["seconds"], r["rmse"]), xytext=(4, 4), textcoords="offset points", fontsize=7.5, color=COLOR[kind])
    ax.axhline(limits[regime][0], color=INK, ls="--", lw=1)
    ax.text(0.99, limits[regime][0], "exact GP on all readings (continuum estimate)  ", transform=ax.get_yaxis_transform(), ha="right", va="bottom",
            fontsize=8, color=INK)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlabel("seconds: fit and prediction")
    ax.set_ylabel("RMSE against the true field (C)")
    ax.set_title("Cost against error: every setting of every method", loc="left")
    ax.legend(frameon=False, fontsize=8.5, loc="upper right" if regime == "long" else "center left")
    tidy(ax, "both")
    ax_cover.axhline(CI, color=INK, ls="--", lw=1)
    ax_cover.set_xscale("log")
    ax_cover.set_ylim(0, 1.02)
    ax_cover.set_xlabel("seconds: fit and prediction")
    ax_cover.set_title("Coverage of 90% intervals", loc="left")
    tidy(ax_cover)

    ax = fig.add_subplot(grid[0, 2])
    for name in HEADLINE:
        wavelength, share = lost_by_scale(maps[f"{regime} · {name}"], net["f_map"])
        ax.plot(wavelength, share, "-o", ms=3.5, lw=1.4, color=COLOR[name.split()[0]], label=name)
    ax.axhline(1, color=MUTED, lw=0.8)
    ax.axvline(2 * np.pi / limits[regime][1], color=INK, ls=":", lw=1)
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlim(50, 1.5)
    ax.set_ylim(3e-3, 300)
    ax.set_xticks([40, 20, 10, 5, 2], ["40", "20", "10", "5", "2"])
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel("wavelength (km)")
    ax.set_title("Error variance over the truth's,\nby scale", loc="left")
    tidy(ax)
    fig.suptitle(f"The {regime} field (length-scale {net['ell']:.0f} km)", x=0.07, y=0.965, ha="left", fontsize=13, fontweight="bold")
    return fig


race_figure("long");
long field: an exact GP on all readings would err by about 0.089 C (continuum of sensors); the best row here, HSGP 40x40, errs by 0.096 C
short field: an exact GP on all readings would err by about 0.345 C (continuum of sensors); the best row here, Vecchia 20, 120 to predict, errs by 0.364 C
Figure

Top row: where the error lives in space. The colour scale is shared. The exact GP on 2,000 readings has the largest errors, in broad patches: with one reading per 5 square kilometres it cannot see anything smaller. The HSGP and the inducing points have small errors in smooth blobs a few kilometres across. The Vecchia map is different in kind. Its error is speckle, pixel by pixel.

Bottom left: cost against error. Every setting of every method is a point, and the dashed line is the estimate for the exact GP on everything, 0.089 °C. The HSGP owns the frontier: 0.10 °C in two seconds at 32 functions per axis, 0.096 °C in under four seconds at 40. Inducing points trace the same curve ten to thirty times further to the right, reaching 0.11 °C at 576 points after half a minute. Vecchia with 5, 10 and 20 neighbours is far above both, at 0.43, 0.31 and 0.23 °C, and the exact GP on a subsample is worse still at 0.29 °C for eight seconds.

Bottom middle: coverage, and here the ranking turns over. The Vecchia intervals cover the truth 89 to 90% of the time at every setting, and so does the subsample. The HSGP covers 10% of the time at 8 functions per axis, 69% at 32 and 78% at 40, and inducing points go from 32% to 81%. The two methods with the best maps are the two whose intervals cannot be trusted.

Bottom right: where the error lives in scale. For each method we take the spectrum of its map error and divide it by the spectrum of the truth, wavelength by wavelength. A value of 1 means the map has none of the truth's structure at that scale: it has been smoothed away. A value above 1 means the map contains something at that scale that is not in the truth. The dotted line is the wavelength below which noise outweighs signal, 7.3 km on this field (part 7). At wavelengths of 20 km and more all three approximations miss less than 2% of the truth's variance. To the right of the dotted line the two low-rank methods sit at exactly 1. They return nothing below about 7 km, which costs little here because the readings could resolve little more. The Vecchia line climbs to 50. At scales of 2 to 3 km its map carries fifty times the variance of the truth: it is sensor noise that 20 neighbours were too few to average away.

So on the long field the hypothesis we started from points the wrong way. Nothing real is smoothed away by the neighbour method. Its trouble is that it does not smooth enough. An exact GP would average over every reading within a few kilometres of a place, about 130 of them (part 7 again), and Vecchia with 20 neighbours averages over 20.

That suggests a repair that costs almost nothing. The likelihood needs $n$ small factorisations per gradient, but a prediction needs one per new place and no gradient at all. So we keep the fit with 20 neighbours and predict with 60 or 120. These are the open circles. With 120 neighbours at prediction the error falls from 0.23 to 0.105 °C, level with the HSGP at 32 functions per axis and with 576 inducing points, the coverage stays at 90%, and the extra cost is three seconds.

The choice. On the long field: the HSGP at 32 to 40 functions per axis if only the map matters, Vecchia fitted with 20 neighbours and predicted with 120 if the intervals matter too. Rejected: the kernel rule for the HSGP's size (16 per axis: an error of 0.17 °C and 31% coverage), inducing points (the HSGP's answer at ten times its price or more), and the exact GP on a subsample (three times the error). What would change our mind: a need for honest intervals from the HSGP. More functions help, but slowly, and each step costs the cube of their number.

The short field

race_figure("short");
Figure

On the rough field the picture is the one the hypothesis predicted for the low-rank methods, and it is stark. Vecchia with 20 neighbours has an error of 0.37 °C, close to the floor of 0.345 °C, in six or seven seconds, with 89% coverage, and more neighbours at prediction add almost nothing (0.36 °C with 120): on this field a resolution cell holds about nine readings and 20 neighbours are already more than enough. The best HSGP, with 1,600 functions, has an error of 0.87 °C and 22% coverage. The best inducing-point fit, after half a minute, has 1.24 °C and 29%: no better than ignoring 98% of the data and running the exact GP on 2,000 readings, which gives 1.30 °C with 89% coverage.

The maps show why. The errors of the two low-rank methods are the field itself at every scale below 7 to 8 km: in the bottom right panel their lines jump to 1 there, while the truth has most of its variance at those scales. The Vecchia line stays below 1 down to 2 km, the limit of what these readings can resolve.

The choice. On the short field: Vecchia, with 10 to 20 neighbours. Rejected: everything else. What would change our mind: nothing at this density of sensors. A low-rank method would need about 11,000 basis functions here.

The four numbers

A map is one output of these models. The other is the hyperparameters, and a scientist may care about them more: how rough is the field, how noisy are the sensors? The next figure shows each fit's 90% interval for each of the four numbers against the truth (dashed). An interval that misses the truth is drawn pale, with a hollow marker. The table under it has the numbers.

fig, axes = plt.subplots(2, 4, figsize=(14.5, 8.2), sharey="row")
panels = [("mu", "mean (C)", TRUE["mu"]), ("amp", "sd of the field (C)", TRUE["amp"]), ("ell", "length-scale (km)", None),
          ("sigma", "sd of a sensor's error (C)", TRUE["sigma"])]
for row_axes, regime in zip(axes, REGIMES):
    rows = runs[(runs["regime"] == regime) & ~runs.index.str.contains("to predict")]
    for ax, (key, label, truth) in zip(row_axes, panels):
        truth = REGIMES[regime] if truth is None else truth
        for y, (row, r) in enumerate(rows.iloc[::-1].iterrows()):
            lo, mid, hi = np.quantile(fits[row][:, THETA.index(key)], [(1 - CI) / 2, 0.5, (1 + CI) / 2])
            ax.plot([lo, hi], [y, y], color=COLOR[r["family"]], lw=2.2, alpha=1 if lo <= truth <= hi else 0.45)
            ax.plot(mid, y, "o", ms=4.5, color=COLOR[r["family"]], mfc=COLOR[r["family"]] if lo <= truth <= hi else "white")
        ax.axvline(truth, color=INK, ls="--", lw=1)
        if key in ("amp", "ell"):
            ax.set_xscale("log")
            ax.xaxis.set_major_locator(LogLocator(subs=(1, 2, 5)))
            ax.xaxis.set_major_formatter(FuncFormatter(lambda v, _: f"{v:g}"))
            ax.xaxis.set_minor_formatter(NullFormatter())
        ax.set_xlabel(label)
        tidy(ax, "x")
    row_axes[0].set_yticks(range(len(rows)), [row.split(" · ")[1] for row in rows.index[::-1]], fontsize=8.5)
    row_axes[0].set_title(f"The {regime} field: the four numbers each fit reports", loc="left")
fitted = [row for row in runs.index if "to predict" not in row]
recovery = interval_table({row: fits[row] for row in fitted})
covered = pd.DataFrame({row: {key: bool(np.quantile(fits[row][:, i], (1 - CI) / 2) <= (REGIMES[runs.loc[row, "regime"]] if key == "ell" else TRUE[key])
                                        <= np.quantile(fits[row][:, i], (1 + CI) / 2)) for i, key in enumerate(THETA)} for row in fitted}).T
covered["regime"], covered["family"] = runs["regime"], runs["family"]
print(f"truth: mu {TRUE['mu']:g}, amp {TRUE['amp']:g}, ell {REGIMES['long']:g} (long) and {REGIMES['short']:g} (short), sigma {TRUE['sigma']:g}")
print(recovery.join(runs[["size", "gradients"]]).to_string())
print("\nshare of fits whose 90% interval holds the true value:")
print(covered.groupby(["regime", "family"], sort=False)[THETA].mean().round(2));
truth: mu 1, amp 2, ell 20 (long) and 2 (short), sigma 1
                                            mu                  amp                ell                sigma  size  gradients
long · exact on 2,000     0.563 [-0.442, 1.48]    1.86 [1.44, 2.36]  17.8 [14.1, 22.2]   1.01 [0.981, 1.04]  2000         30
long · HSGP 8x8              10.4 [8.51, 12.3]    8.33 [6.63, 10.4]    19.2 [14.8, 25]    1.07 [1.06, 1.07]    64         80
long · HSGP 16x16         0.395 [-0.262, 1.09]    2.33 [2.05, 2.64]   9.1 [7.43, 11.1]    1.01 [1.01, 1.02]   256         90
long · HSGP 24x24         0.733 [-0.213, 1.72]    1.92 [1.55, 2.36]    17.6 [14.8, 21]       1.01 [1, 1.01]   576         20
long · HSGP 32x32         0.812 [-0.282, 1.89]    1.98 [1.55, 2.52]  19.5 [16.2, 23.4]      1 [0.999, 1.01]  1024         15
long · HSGP 40x40         0.759 [-0.333, 1.86]    2.09 [1.62, 2.66]  20.9 [17.3, 25.1]      1 [0.998, 1.01]  1600         15
long · Vecchia 5          0.306 [0.215, 0.402]    1.77 [1.72, 1.82]  18.7 [15.5, 22.5]     0.999 [0.995, 1]     5         20
long · Vecchia 10         0.321 [0.142, 0.515]    1.76 [1.67, 1.85]  16.9 [14.7, 19.3]         1 [0.996, 1]    10         15
long · Vecchia 20        0.213 [-0.199, 0.617]     1.85 [1.65, 2.1]    19 [16.4, 21.9]     0.999 [0.996, 1]    20         15
long · inducing 64        -1.02 [-2.93, 0.901]     2.63 [2.1, 3.26]  72.4 [61.9, 83.9]    1.08 [1.08, 1.09]    64         40
long · inducing 144            -1 [-6.7, 4.64]    6.85 [5.14, 9.29]   95.8 [78.6, 117]    1.02 [1.02, 1.03]   144         33
long · inducing 324        0.764 [-2.35, 4.13]    4.09 [2.84, 6.02]    51.4 [40, 66.3]    1.01 [1.01, 1.01]   324         45
long · inducing 576         1.22 [-1.34, 3.71]    3.27 [2.25, 4.81]    37.5 [29.2, 49]          1 [1, 1.01]   576         25
short · exact on 2,000      0.99 [0.808, 1.17]    2.02 [1.93, 2.12]  2.07 [1.88, 2.26]  0.987 [0.908, 1.07]  2000         35
short · HSGP 8x8        -0.751 [-0.984, -0.52]    1.89 [1.55, 2.28]  12.1 [9.16, 15.6]    2.04 [2.04, 2.05]    64         35
short · HSGP 16x16         0.933 [0.675, 1.17]     3.9 [2.89, 5.38]   1.69 [1.1, 2.54]      1.8 [1.79, 1.8]   256         55
short · HSGP 24x24           1.09 [0.38, 1.78]    7.44 [6.98, 7.94]  2.65 [2.26, 3.09]    1.61 [1.61, 1.62]   576         25
short · HSGP 32x32          1.01 [0.851, 1.18]    3.66 [3.22, 4.15]  1.15 [0.945, 1.4]    1.45 [1.45, 1.46]  1024         40
short · HSGP 40x40         0.993 [0.821, 1.16]    2.53 [2.42, 2.64]  1.73 [1.59, 1.89]    1.32 [1.32, 1.33]  1600         25
short · Vecchia 5          0.942 [0.819, 1.06]       2 [1.95, 2.05]  2.09 [2.01, 2.17]     0.999 [0.995, 1]     5         15
short · Vecchia 10          1.02 [0.873, 1.16]    1.98 [1.92, 2.05]   2.03 [1.96, 2.1]     0.999 [0.995, 1]    10         15
short · Vecchia 20         0.979 [0.855, 1.11]    2.01 [1.94, 2.08]   2.03 [1.97, 2.1]     0.998 [0.994, 1]    20         10
short · inducing 64       0.026 [-0.163, 0.21]  0.474 [0.44, 0.508]      13 [12.1, 14]    2.04 [2.04, 2.05]    64         55
short · inducing 144      -10.3 [-13.4, -7.01]    3.23 [2.63, 3.93]  32.9 [28.5, 37.8]    1.93 [1.92, 1.94]   144         80
short · inducing 324         1.59 [0.19, 3.01]    3.17 [2.65, 3.81]  18.9 [16.7, 21.5]    1.77 [1.76, 1.77]   324         95
short · inducing 576         4.06 [2.15, 5.96]    4.16 [3.45, 5.08]  15.8 [13.8, 18.1]    1.61 [1.61, 1.62]   576         30

share of fits whose 90% interval holds the true value:
                   mu   amp   ell  sigma
regime family                           
long   exact     1.00  1.00  1.00    1.0
       HSGP      0.80  0.60  0.80    0.4
       Vecchia   0.00  0.33  0.67    1.0
       inducing  0.75  0.00  0.00    0.0
short  exact     1.00  1.00  1.00    1.0
       HSGP      0.80  0.20  0.20    0.0
       Vecchia   1.00  1.00  0.67    1.0
       inducing  0.25  0.00  0.00    0.0
Figure

The exact GP on a subsample is right about all four numbers on both fields, with wide intervals on the long field and narrow ones on the short field. Throwing away 98% of the readings costs the map; it does not corrupt the parameters.

Vecchia is right about the noise everywhere and about everything on the short field, with intervals a few per cent wide (with 5 neighbours its interval for the length-scale, 2.01 to 2.17 km, just misses 2). On the long field it fails in one instructive way: its interval for the mean is two to ten times narrower than the subsample's and misses the truth at every setting. A model that drops long-range dependence believes that 100,000 readings pin down the mean of the process, when they only pin down the mean of this draw (0.4 °C). Its intervals for $a$ at 5 and 10 neighbours are too narrow for the same reason. Both widen as neighbours are added, in the right direction and too slowly.

The low-rank methods distort the parameters in both regimes, and in the same direction for the noise: variance that the basis cannot carry has to go somewhere, and it goes into $\sigma$. On the short field the HSGP reports a sensor noise between 1.3 and 2.0 °C and the inducing points between 1.6 and 2.0 °C, against a truth of 1.0, with intervals a hundredth of a degree wide. Inducing points also overstate the length-scale every time, by a factor of 2 to 5 on the long field and 6 to 16 on the short one: the bound rewards a field that the inducing points can represent. This is the known behaviour of the collapsed bound (Bauer et al. 2016), and here it is far outside its own intervals. On the long field the damage is smaller and shrinks with the rank, but the 16 functions per axis that the kernel rule recommended still give a length-scale of 9 km with an interval that excludes 20.

The last printed table counts, for each method and field, the share of its fits whose interval holds the truth.

7 · Why it came out that way: resolution cells

All of the above follows from one picture. A stationary field has a spectrum $S(\omega)$: its variance per unit of spatial frequency. For the Matérn 3/2 in two dimensions,

$$S(\omega) = a^2\, \frac{6\pi\, 3^{3/2}}{\ell^3} \left(\frac{3}{\ell^2} + \omega^2\right)^{-5/2},$$

flat up to $\omega \approx \sqrt 3/\ell$ and falling as $\omega^{-5}$ beyond. Independent sensor errors of variance $\sigma^2$ at a density of $\rho$ sensors per unit area act like white noise with the flat spectrum $\sigma^2/\rho$. More sensors or better sensors lower that floor. Where the field's spectrum is above the floor the readings can resolve the field, and where it is below they cannot. The crossing is at a frequency $\omega^*$, a wavelength $2\pi/\omega^*$.

Call a square of half that wavelength a resolution cell. The region contains $A\,(\omega^*/\pi)^2$ of them, and that number is the number of things the data can tell us about the field. It is also, roughly, the rank a low-rank method needs, whatever its basis. And $n$ divided by it, the readings per cell, is the number of readings an exact GP averages to estimate one of those things, so it is the number of neighbours Vecchia needs. Since their product is $n$,

$$\text{rank needed} \times \text{neighbours needed} \approx n,$$

a problem that is easy for one family is hard for the other. The same picture gives the error of the exact GP used as the floor above: at each frequency the best linear estimate keeps a share $S/(S + \sigma^2/\rho)$ of the signal, which leaves an error variance of $\int S\,(\sigma^2/\rho)/(S + \sigma^2/\rho)\ d^2\omega / (2\pi)^2$.

def resolution(amp, ell, sigma, density, area):
    """Wavelength where signal meets noise, the number of cells of that size in the region, and the readings per cell."""
    floor, w_star = dense_limit(amp, ell, sigma, density)
    cells = area * (w_star / np.pi) ** 2                                # one cell is half a wavelength on a side
    return {"an exact GP would err by (C)": floor, "signal meets noise at wavelength (km)": 2 * np.pi / w_star,
            "resolution cells": cells, "readings per cell": density * area / cells}


cells = pd.DataFrame({f"{regime} field": resolution(TRUE["amp"], ell, TRUE["sigma"], DENSITY, SIDE**2) for regime, ell in REGIMES.items()})
for regime, g in geometry.items():
    cells.loc["HSGP 32x32 stops at wavelength (km)", f"{regime} field"] = 4 * g["L"] / 32      # highest frequency: 32 pi / (2 L)
cells.loc["inducing 576: two grid steps (km)"] = 2 * SIDE / 24
cells.loc["Vecchia 20 reaches out to (km)"] = np.sqrt(20 / (np.pi * DENSITY))
cells.round(3)
long field short field
an exact GP would err by (C) 0.089 0.345
signal meets noise at wavelength (km) 7.284 1.881
resolution cells 753.921 11309.374
readings per cell 132.640 8.842
HSGP 32x32 stops at wavelength (km) 9.999 7.500
inducing 576: two grid steps (km) 8.333 8.333
Vecchia 20 reaches out to (km) 0.798 0.798

The long field has about 750 cells with 130 readings in each. The readings resolve wavelengths down to 7.3 km. The HSGP with 32 functions per axis stops at 10 km and the grid of 576 inducing points at 8.3 km: both are just short of what the data can resolve, which is why they land 15 to 20% above the floor, why their intervals are too narrow (the part of the field beyond their reach is simply absent from the model, so it is absent from the uncertainty), and why the kernel rule's 16 functions per axis, which stop at 20 km, were far too few. The rule protects the prior. With ten sensors per square kilometre the posterior has structure at scales well below the length-scale, and the rank has to follow the cells. Vecchia with 20 neighbours reaches 0.8 km and averages 20 readings where 130 are available.

The short field has 11,300 cells with nine readings in each. Twenty neighbours are more than a cell holds, so Vecchia is near the floor. A low-rank method would need a rank of about 11,000, seven times the largest we ran.

The figure shows the same thing. The shaded area is what the readings can resolve, and the dashed lines mark where each low-rank method stops.

fig, axes = plt.subplots(1, 2, figsize=(13.5, 4.3), sharey=True)
wavelength = np.geomspace(100, 0.8, 300)
noise = TRUE["sigma"] ** 2 / DENSITY
for ax, (regime, ell) in zip(axes, REGIMES.items()):
    spectrum = matern32_spectrum(2 * np.pi / wavelength, TRUE["amp"], ell)
    ax.plot(wavelength, spectrum, color=INK, lw=1.8, label="the field")
    ax.axhline(noise, color=RED, lw=1.4, label="sensor noise, per unit area")
    ax.fill_between(wavelength, noise, spectrum, where=spectrum > noise, color=YELLOW, alpha=0.25, lw=0, label="what the readings can resolve")
    for name, cut, color, height in (("HSGP 32x32", 4 * geometry[regime]["L"] / 32, BLUE, 3e3), ("inducing 576", 2 * SIDE / 24, AQUA, 2e2)):
        ax.axvline(cut, color=color, lw=1.6, ls="--")
        ax.text(cut, height, f" {name}\n stops here", color=color, fontsize=8.5, va="top", ha="left")
    star = cells.loc["signal meets noise at wavelength (km)", f"{regime} field"]
    ax.annotate(f"{star:.1f} km", (star, noise), xytext=(0, -26), textcoords="offset points", ha="center", fontsize=9, color=INK,
                arrowprops=dict(arrowstyle="-", color=INK, lw=0.8))
    ax.set_xscale("log")
    ax.set_yscale("log")
    ax.set_xlim(100, 0.8)
    ax.set_ylim(1e-3, 5e3)
    ax.set_xticks([100, 40, 20, 10, 5, 2, 1], ["100", "40", "20", "10", "5", "2", "1"])
    ax.xaxis.set_minor_formatter(NullFormatter())
    ax.set_xlabel("wavelength (km)")
    ax.set_title(f"The {regime} field: {cells.loc['resolution cells', f'{regime} field']:,.0f} cells, "
                 f"{cells.loc['readings per cell', f'{regime} field']:.0f} readings in each", loc="left")
    tidy(ax)
axes[0].set_ylabel("variance per unit of frequency (C$^2$ km$^2$)")
axes[0].legend(frameon=False, fontsize=8.5, loc="lower left");
Figure

One number, tested

If readings per cell is the number that matters, it should predict the ranking on fields we have not looked at, and it should not matter how a field comes to have many or few readings per cell. We draw five more fields: length-scales of 10, 5 and 1 km with the same sensors, and length-scales of 20 and 5 km read by sensors three times as noisy. For each of the seven fields we plug the true hyperparameters into one setting of each method and score the map. That isolates the error of the approximation from the error of its fit.

def rmse(estimate, truth):
    return float(np.sqrt(np.mean((estimate - truth) ** 2)))


def hsgp_frequency(m, L):
    """The frequency of each basis function of a square box (the kernel's spectrum is evaluated there)."""
    j = np.arange(1, m + 1) * np.pi / (2 * L)
    return np.hypot(*np.meshgrid(j, j)).ravel()


def with_true_hyperparameters(net):
    """One setting per method with the true hyperparameters plugged in: the error of the approximation itself."""
    theta = (TRUE["mu"], TRUE["amp"], net["ell"], net["sigma"])
    xy, y, new, truth = net["xy"], net["y"], net["xy_score"], net["f_score"]
    out = resolution(TRUE["amp"], net["ell"], net["sigma"], DENSITY, SIDE**2)
    sub = rng.choice(N_SENSORS, 2000, replace=False)
    out["exact on 2,000"] = rmse(predict_exact(theta, xy[sub], y[sub], new)[0], truth)
    L = hsgp_rule(net["ell"], SIDE / 2)[0] * SIDE / 2
    frequency = hsgp_frequency(32, L)
    out["HSGP 32x32"] = rmse(predict_hsgp(theta, hsgp_statistics(xy, y, 32, L), lambda amp, ell: matern32_spectrum(frequency, amp, ell),
                                          hsgp_basis(new, 32, L))[0], truth)
    tree = cKDTree(xy)
    for m in (20, 120):
        out[f"Vecchia {m}"] = rmse(predict_vecchia(theta, xy, y, tree, new, m)[0], truth)
    xu = inducing_grid(24)
    out["inducing 576"] = rmse(predict_vfe(theta, vfe_statistics(xy, y, xu)[1], xu, new)[0], truth)
    return out


CASES = [(20.0, 3.0), (20.0, 1.0), (10.0, 1.0), (5.0, 3.0), (5.0, 1.0), (2.0, 1.0), (1.0, 1.0)]      # length-scale (km), noise sd (C)
sweep, worst = {}, 0.0
for i, (ell, noise_sd) in enumerate(CASES):
    regime = {v: k for k, v in REGIMES.items()}.get(ell) if noise_sd == TRUE["sigma"] else None
    net = nets[regime] if regime else make_network(ell, np.random.default_rng([RANDOM_SEED, 10 + i]), sigma=noise_sd)
    worst = max(worst, net["worst"])
    sweep[f"{ell:g} km" + (f", noise {noise_sd:g} C" if noise_sd != TRUE["sigma"] else "")] = with_true_hyperparameters(net)
    jax.clear_caches()
del net
print(f"largest departure of a simulated covariance from the Matern 3/2: {worst:.1e}")
sweep = pd.DataFrame(sweep).T.sort_values("readings per cell", ascending=False)
sweep.index.name = "field"
sweep.round({"an exact GP would err by (C)": 3, "signal meets noise at wavelength (km)": 1, "resolution cells": 0, "readings per cell": 0,
             "exact on 2,000": 3, "HSGP 32x32": 3, "Vecchia 20": 3, "Vecchia 120": 3, "inducing 576": 3})
largest departure of a simulated covariance from the Matern 3/2: 6.6e-05
an exact GP would err by (C) signal meets noise at wavelength (km) resolution cells readings per cell exact on 2,000 HSGP 32x32 Vecchia 20 Vecchia 120 inducing 576
field
20 km, noise 3 C 0.170 11.4 309.0 324.0 0.628 0.179 0.650 0.282 0.178
20 km 0.089 7.3 754.0 133.0 0.284 0.114 0.225 0.104 0.103
5 km, noise 3 C 0.384 5.1 1547.0 65.0 1.162 0.468 0.638 0.391 0.552
10 km 0.134 4.8 1719.0 58.0 0.438 0.168 0.229 0.140 0.213
5 km 0.202 3.2 3898.0 26.0 0.734 0.402 0.250 0.213 0.541
2 km 0.345 1.9 11309.0 9.0 1.280 1.054 0.374 0.363 1.258
1 km 0.514 1.3 24688.0 4.0 1.744 1.631 0.558 0.549 1.791

The check on the simulator passes for the new fields as well. We read this table as a picture in part 9, where it becomes the decision chart.

8 · Does the ocean agree?

A real case, at a size where the exact answer exists. The Argo programme keeps about 4,000 floats drifting in the world ocean, each surfacing every ten days with a temperature profile. E92 built a table of the North Atlantic profiles of 2023 to 2025, reduced to the temperature at 100 dbar minus a local climatology. We take the 2,535 profiles of July and August 2025 as one snapshot in two dimensions and set a fifth of them aside. With about 2,000 profiles to fit, the exact GP costs a few seconds, so here we can measure what part 6 could only estimate: how far each approximation is from the exact answer.

Two caveats. Coordinates are kilometres on a flat map centred on the data, which misstates east-west distances by up to a quarter at the northern and southern edges. And two months of a moving ocean are treated as one field, so whatever changed within them is counted as noise. Neither affects a comparison of four ways of computing the same model.

data.describe("argo_natl_t100")
argo = data.load("argo_natl_t100")
argo["time"] = pd.to_datetime(argo["time"])
summer = argo[(argo["time"] >= "2025-07-01") & (argo["time"] < "2025-09-01")].reset_index(drop=True)
lat0, lon0 = summer["lat"].mean(), summer["lon"].mean()
ocean_xy = np.column_stack([(summer["lon"] - lon0) * 111.2 * np.cos(np.deg2rad(lat0)), (summer["lat"] - lat0) * 111.2])   # km
ocean_xy -= (ocean_xy.max(0) + ocean_xy.min(0)) / 2
anomaly = summer["anom"].to_numpy()
held = rng.random(len(anomaly)) < 0.2
Xo, yo, Xh, yh = ocean_xy[~held], anomaly[~held], ocean_xy[held], anomaly[held]
half_box = (ocean_xy.max(0) - ocean_xy.min(0)) / 2
print(f"\n{len(summer):,} profiles of July and August 2025 over {2 * half_box[0]:,.0f} km by {2 * half_box[1]:,.0f} km; "
      f"anomalies have sd {anomaly.std():.2f} C; {len(yo):,} to fit, {len(yh)} held out")
argo_natl_t100: One row per ascending profile in the open North Atlantic, 20-55N, 80W-0 (land, Mediterranean, Gulf of St Lawrence, Caribbean and North Sea removed), 2023-2025, 40,343 rows: float_id, cycle, mode (R real-time, A adjusted, D delayed-mode; adjusted columns for A and D, raw for R, good flags only), time (UTC, ISO), lat, lon, t100 (C, linear interpolation to 100 dbar between the two good levels either side, at most 20 dbar apart), clim (C, the 2015-2022 climatology of `argo_natl_t100_climatology` at the profile's place and day), anom (t100 - clim), gap_dbar.
  source: Argo float data and metadata from the Global Data Assembly Centre (Argo GDAC), SEANOE, https://doi.org/10.17882/42182, CC BY 4.0, read through the Ifremer ERDDAP mirror (dataset ArgoFloats) on 2026-11-02. These data were collected and made freely available by the International Argo Program and the national programs that contribute to it (https://argo.ucsd.edu, https://www.ocean-ops.org). The Argo Program is part of the Global Ocean Observing System. Changed: reduced to one 100 dbar value per profile and a local climatology added. DERIVED by tools/build_e92_data.py (pull, derive, climatology) - keep the cached file; a re-pull differs, as delayed-mode corrections keep arriving.
  url:    https://doi.org/10.17882/42182

2,535 profiles of July and August 2025 over 6,499 km by 3,886 km; anomalies have sd 1.86 C; 2,021 to fit, 514 held out
OCEAN_PRIOR = dict(ell_median=300.0)
ocean_start = np.array([0.0, 0.0, np.log(300.0), 0.0])
ocean_fits, ocean_means, ocean_cost = {}, {}, {}


def ocean_finish(name, fit, predict):
    """Score against the held-out READINGS (so the sensor noise is added to the predictive sd), and keep the predictive mean."""
    row = f"ocean · {name}"

    def reading(theta):
        mean, sd = predict(theta)
        return mean, np.hypot(sd, theta[3])

    sb.score(row, {"reading": predictive_draws(reading, fit["draws"], rng)}, truth={"reading": yh})
    ocean_fits[name], ocean_means[name] = fit["draws"], predict(to_natural(fit["mode"]))[0]
    ocean_cost[name] = dict(gradients=fit["gradients"], ms_per_gradient=fit["ms_per_gradient"])


OCEAN_EXACT = f"exact on all {len(yo):,}"
with sb.track(f"ocean · {OCEAN_EXACT}"):
    ocean_exact = laplace(exact_model(Xo, yo, **OCEAN_PRIOR), ocean_start, rng)
    ocean_finish(OCEAN_EXACT, ocean_exact, lambda th: predict_exact(th, Xo, yo, Xh))
ocean_area = 4 * half_box.prod()
ocean_cells = resolution(*to_natural(ocean_exact["mode"])[1:], len(yo) / ocean_area, ocean_area)
print(f"at the exact fit's mode: {ocean_cells['resolution cells']:,.0f} resolution cells, {ocean_cells['readings per cell']:.1f} profiles in each")
ocean_c = max(1.2, 4.5 * np.exp(ocean_exact["mode"][2]) / half_box.min())
ocean_L, ocean_corners = ocean_c * half_box, CORNERS / (SIDE / 2) * half_box
with sb.track("ocean · HSGP 32x32"):
    st = hsgp_statistics(Xo, yo, 32, ocean_L)
    model, spectral = hsgp_model(st, 32, ocean_L, ocean_corners, **OCEAN_PRIOR)
    fit = laplace(model, ocean_exact["mode"], rng)
    basis = hsgp_basis(Xh, 32, ocean_L)
    ocean_finish("HSGP 32x32", fit, lambda th: predict_hsgp(th, st, spectral, basis))
ocean_tree = cKDTree(Xo)
with sb.track("ocean · Vecchia 20"):
    fit = laplace(vecchia_model(Xo, yo, earlier_neighbours(Xo, 20), 500, **OCEAN_PRIOR), ocean_exact["mode"], rng)
    ocean_finish("Vecchia 20", fit, lambda th: predict_vecchia(th, Xo, yo, ocean_tree, Xh, 20))
ocean_xu = Xo[rng.choice(len(yo), 576, replace=False)]                  # inducing points at 576 of the profiles
with sb.track("ocean · inducing 576"):
    model, raw = vfe_model(Xo, yo, ocean_xu, block=500, **OCEAN_PRIOR)
    fit = laplace(model, ocean_exact["mode"], rng)
    ocean_finish("inducing 576", fit, lambda th: predict_vfe(th, raw, ocean_xu, Xh))
jax.clear_caches()

ocean = sb.table().filter(like="ocean · ", axis=0)[["seconds", "rmse", "coverage", "width"]]
ocean.index = [row.split(" · ")[1] for row in ocean.index]
ocean["rms distance from the exact map (C)"] = [rmse(ocean_means[name], ocean_means[OCEAN_EXACT]) for name in ocean.index]
ocean = ocean.join(pd.DataFrame(ocean_cost).T).join(interval_table(ocean_fits))
ocean.round({"seconds": 1, "rmse": 3, "coverage": 3, "width": 2, "rms distance from the exact map (C)": 3, "ms_per_gradient": 1})
at the exact fit's mode: 2,271 resolution cells, 0.9 profiles in each
seconds rmse coverage width rms distance from the exact map (C) gradients ms_per_gradient mu amp ell sigma
exact on all 2,021 6.9 1.482 0.909 3.83 0.000 25.0 239.1 0.138 [-0.0179, 0.288] 1.68 [1.6, 1.77] 80.1 [70.5, 90.7] 0.8 [0.738, 0.862]
HSGP 32x32 0.8 1.460 0.905 4.15 0.556 20.0 23.4 0.16 [-0.0234, 0.331] 1.73 [1.58, 1.9] 101 [82.9, 122] 1.15 [1.11, 1.18]
Vecchia 20 0.5 1.476 0.909 3.78 0.018 10.0 11.4 0.136 [-0.0243, 0.297] 1.69 [1.6, 1.78] 79.6 [70.5, 90.3] 0.795 [0.738, 0.854]
inducing 576 1.7 1.582 0.905 4.55 0.707 30.0 39.0 0.144 [-0.151, 0.432] 1.28 [1.15, 1.43] 272 [235, 313] 1.29 [1.25, 1.32]
fig, axes = plt.subplots(1, 4, figsize=(16, 4.8), gridspec_kw={"width_ratios": [3.6, 1, 1, 1], "wspace": 0.34})
ax = axes[0]
lim = np.quantile(np.abs(yo), 0.98)
pts = ax.scatter(Xo[:, 0], Xo[:, 1], c=yo, s=11, lw=0, cmap=DIVERGING, vmin=-lim, vmax=lim)
ax.scatter(Xh[:, 0], Xh[:, 1], s=9, facecolor="none", edgecolor=MUTED, lw=0.45, label="held out")
ax.set_aspect("equal")
ax.grid(False)
ax.set_xlabel("km east of the centre")
ax.set_ylabel("km north")
ax.legend(frameon=False, fontsize=8.5, loc="upper left")
ax.set_title("Argo profiles, July and August 2025:\ntemperature anomaly at 100 dbar", loc="left")
fig.colorbar(pts, ax=ax, pad=0.02, label="C")
exact_mean = ocean_means[OCEAN_EXACT]
for ax, name in zip(axes[1:], ("HSGP 32x32", "Vecchia 20", "inducing 576")):
    ax.plot([-12, 8], [-12, 8], color=MUTED, lw=0.8)
    ax.scatter(exact_mean, ocean_means[name], s=7, color=COLOR[name.split()[0]], lw=0, alpha=0.7)
    ax.set_xlim(-12, 8)
    ax.set_ylim(-12, 8)
    ax.set_xlabel("the exact GP's prediction (C)")
    ax.set_title(f"{name}\n{ocean.loc[name, 'rms distance from the exact map (C)']:.2f} C from the exact map", loc="left", fontsize=10)
    ax.set_aspect("equal")
    tidy(ax, "both")
axes[1].set_ylabel("the approximation's prediction\nat a held-out profile (C)");
Figure

The exact GP finds a length-scale of about 80 km and a noise of 0.8 °C. On a region 6,500 km by 3,900 km sampled once every 100 km or so, the formula of part 7 gives about 2,300 resolution cells with one profile in each. That is the short regime, more extreme than our rough field.

Vecchia with 20 neighbours reproduces the exact GP: the same four hyperparameters to two digits, and predictions at the held-out profiles within 0.02 °C of the exact ones, in half a second against six. E92 found the same on these floats with a kernel in space and time: 30 neighbours matched its exact fit.

The two low-rank methods do not. Their predictions are 0.6 and 0.7 °C away from the exact GP's, their noise is 1.15 and 1.3 °C against 0.8, and the inducing points report a length-scale of 270 km.

And yet, in the first columns, the HSGP has the same error against the held-out readings as the exact GP, 1.46 against 1.48 °C, the inducing points are only 7% worse, and all four cover 90 to 91% of those readings. This is the caution the simulated fields could not give us. A held-out reading is the field plus noise plus everything the model does not describe (the anomalies near the Gulf Stream are far from Gaussian), and against that target an over-smoothed map with inflated noise scores as well as the exact one. Its intervals are honest about readings because the noise it invented covers what it smoothed away. They say nothing reliable about the field. On real data, held-out error and coverage would not have told the HSGP from the exact GP. The distance from an exact fit, on a subsample small enough to allow one, does.

The choice. For the ocean snapshot, Vecchia. Rejected: the HSGP and inducing points, which change the scientific answer (the noise, the length-scale) while leaving the held-out score untouched. What would change our mind: a question that only needs the broad pattern, for which a few hundred sines would be enough and much faster to sample.

9 · Which one, when?

The scoreboard

Every fit of the notebook is a row: wall time, memory, the error and coverage against the truth it was scored on (the true field for the two simulated fields, the held-out readings for the ocean), and the width of its intervals. The fits are Laplace approximations, whose draws are independent, so they claim no effective sample size. The one NUTS run has its own.

scoreboard = sb.table()
scoreboard.round({"seconds": 1, "peak_gb": 2, "added_gb": 2, "ess": 0, "ess_per_s": 1, "rmse": 3, "coverage": 3, "width": 2})
seconds peak_gb added_gb ess ess_per_s rmse coverage width
method
long · HSGP 16x16, NUTS 10.2 0.82 0.11 1497.0 146.6 0.164 0.339 0.14
long · exact on 2,000 7.9 1.61 0.48 NaN NaN 0.288 0.915 1.01
long · HSGP 8x8 0.3 1.61 0.00 NaN NaN 0.373 0.097 0.08
long · HSGP 16x16 0.4 1.62 0.01 NaN NaN 0.171 0.311 0.14
long · HSGP 24x24 0.6 1.64 0.02 NaN NaN 0.130 0.490 0.17
long · HSGP 32x32 1.8 1.73 0.09 NaN NaN 0.104 0.685 0.21
long · HSGP 40x40 3.2 1.96 0.24 NaN NaN 0.096 0.783 0.24
long · Vecchia 5 1.6 1.97 0.01 NaN NaN 0.429 0.899 1.41
long · Vecchia 10 2.8 2.01 0.04 NaN NaN 0.314 0.890 1.02
long · Vecchia 20 8.3 1.27 0.27 NaN NaN 0.225 0.901 0.73
long · Vecchia 20, 60 to predict 9.1 1.26 0.00 NaN NaN 0.136 0.892 0.44
long · Vecchia 20, 120 to predict 10.8 1.30 0.03 NaN NaN 0.105 0.899 0.34
long · inducing 64 1.6 1.31 0.02 NaN NaN 0.408 0.317 0.33
long · inducing 144 5.0 1.32 0.00 NaN NaN 0.212 0.552 0.31
long · inducing 324 17.6 1.36 0.04 NaN NaN 0.129 0.722 0.28
long · inducing 576 26.2 1.39 0.03 NaN NaN 0.106 0.806 0.28
short · exact on 2,000 9.6 1.84 0.45 NaN NaN 1.300 0.886 4.04
short · HSGP 8x8 0.3 1.55 0.00 NaN NaN 1.780 0.034 0.17
short · HSGP 16x16 0.4 1.57 0.02 NaN NaN 1.482 0.075 0.29
short · HSGP 24x24 0.6 1.58 0.01 NaN NaN 1.261 0.119 0.38
short · HSGP 32x32 2.2 1.81 0.24 NaN NaN 1.054 0.172 0.44
short · HSGP 40x40 4.1 1.82 0.01 NaN NaN 0.870 0.221 0.49
short · Vecchia 5 1.3 1.86 0.04 NaN NaN 0.499 0.901 1.61
short · Vecchia 10 2.7 1.66 0.07 NaN NaN 0.409 0.887 1.30
short · Vecchia 20 5.9 1.66 0.00 NaN NaN 0.375 0.887 1.20
short · Vecchia 20, 60 to predict 6.7 1.66 0.00 NaN NaN 0.367 0.885 1.16
short · Vecchia 20, 120 to predict 8.5 1.39 0.00 NaN NaN 0.364 0.881 1.16
short · inducing 64 2.1 1.40 0.01 NaN NaN 1.771 0.132 0.60
short · inducing 144 11.0 1.40 0.00 NaN NaN 1.639 0.159 0.68
short · inducing 324 34.7 1.24 0.09 NaN NaN 1.431 0.218 0.81
short · inducing 576 31.8 1.37 0.13 NaN NaN 1.237 0.290 0.92
ocean · exact on all 2,021 6.9 1.89 0.17 NaN NaN 1.482 0.909 3.83
ocean · HSGP 32x32 0.8 1.95 0.05 NaN NaN 1.460 0.905 4.15
ocean · Vecchia 20 0.5 1.96 0.01 NaN NaN 1.476 0.909 3.78
ocean · inducing 576 1.7 1.99 0.03 NaN NaN 1.582 0.905 4.55
headline = Scoreboard(ci_prob=CI)                                       # the same numbers, one setting per method, for the bars
for regime in REGIMES:
    for name in ("exact on 2,000", "HSGP 32x32", "Vecchia 20", "Vecchia 20, 120 to predict", "inducing 576"):
        headline.add(f"{regime} · {name}", **scoreboard.loc[f"{regime} · {name}"].dropna())
    if regime == "long":
        headline.add(NUTS_ROW, **scoreboard.loc[NUTS_ROW].dropna())
for row in scoreboard.filter(like="ocean · ", axis=0).index:
    headline.add(row, **scoreboard.loc[row].dropna())
headline.plot(highlight=[row for row in headline.table().index if "Vecchia" in row]);
Figure

The bars show one setting per method. Three things stand out. Time: on 100,000 readings everything here runs in seconds to half a minute, and the single NUTS run in ten seconds, because the latent field never appears. Memory: every row peaks near 2 GB or below, including the kernel's own baseline of about 1 GB; the blocked likelihoods add little. And honesty: on the simulated fields the coverage column separates the methods more sharply than the error column does. The highlighted rows (Vecchia) and the exact GP on a subsample sit on the nominal line everywhere. The low-rank rows fall short of it in proportion to what they cannot represent.

The decision chart

The left panel is the test of part 7: seven fields, the true hyperparameters plugged in, and each method's error as a multiple of the estimate for the exact GP. The fields are ordered by readings per resolution cell.

fig, (ax, chart) = plt.subplots(1, 2, figsize=(14.5, 5.6), gridspec_kw={"width_ratios": [1.15, 1]})
per_cell = sweep["readings per cell"]
for name, color, style in (("exact on 2,000", MUTED, "-"), ("HSGP 32x32", BLUE, "-"), ("inducing 576", AQUA, "-"), ("Vecchia 20", ORANGE, "-"),
                           ("Vecchia 120", ORANGE, "--")):
    ax.plot(per_cell, sweep[name] / sweep["an exact GP would err by (C)"], style, marker="o", ms=4.5, lw=1.6, color=color,
            mfc="white" if style == "--" else color, label=name + (" (at prediction)" if name == "Vecchia 120" else ""))
ax.axhline(1, color=INK, lw=1, ls=":")
previous = np.inf
for label, x in per_cell.items():
    crowded = previous / x < 1.3                                        # two fields with nearly the same readings per cell
    ax.text(x, 0.76 if crowded else 0.9, label.replace(", noise", "\nnoise"), ha="center", va="top", fontsize=7.5, color=INK,
            linespacing=1.1)
    previous = x
ax.set_xscale("log")
ax.set_yscale("log")
ax.set_xlim(per_cell.max() * 2.6, per_cell.min() / 1.5)
ax.set_ylim(0.66, 8)
ax.set_yticks([1, 1.5, 2, 3, 5], ["1", "1.5", "2", "3", "5"])
ax.yaxis.set_minor_formatter(NullFormatter())
ax.set_xlabel("readings per resolution cell   (many: smooth field or noisy sensors;  few: rough field or sparse sensors)")
ax.set_ylabel("RMSE over the exact GP's (continuum estimate)")
ax.set_title("True hyperparameters plugged in: how far each approximation is from exact", loc="left")
ax.legend(frameon=False, fontsize=8.5, loc="upper center", ncol=2)
tidy(ax, "both")

BOXES = [
    (BLUE, "Few cells: a smooth field, or noisy or sparse readings",
     "HSGP. One pass over the readings, then every gradient is free of n,\nso NUTS is affordable. Take the rank from the cells, not from the\nkernel rule, and check coverage: what the basis drops, it does not report."),
    (ORANGE, "Few readings per cell: a rough field, densely or sparsely sensed",
     "Vecchia, with about as many neighbours as there are readings in a\ncell. Calibrated at every setting here, and it recovered the\nhyperparameters that both low-rank methods distorted."),
    (VIOLET, "Many cells and many readings in each",
     "No cheap answer. Vecchia fitted with few neighbours and predicted\nwith many is the practical one; its cost grows with the cube of the\nneighbours, at prediction only."),
    (AQUA, "Inputs that are not a low-dimensional box, or a kernel with no spectrum",
     "Inducing points. They need the same rank as the HSGP, pay n M$^2$ at\nevery gradient, and the fitted noise and length-scale drift upwards\nwhen the rank is short."),
    (MUTED, "A few thousand readings",
     "The exact GP. Nothing to approximate, and its hyperparameters were\nright on both fields. Subsampling to get there costs the map, not them."),
]
for i, (color, when, what) in enumerate(BOXES):
    y = 4 - i
    chart.add_patch(FancyBboxPatch((0.02, y + 0.06), 0.96, 0.88, boxstyle="round,pad=0.01,rounding_size=0.06", fc="white", ec=color, lw=1.6))
    chart.add_patch(plt.Rectangle((0.02, y + 0.06), 0.022, 0.88, color=color, lw=0))
    chart.text(0.065, y + 0.8, when, fontsize=9.6, fontweight="bold", color=INK, va="center")
    chart.text(0.065, y + 0.38, what, fontsize=8.6, color=INK, va="center", linespacing=1.3)
chart.set_xlim(0, 1)
chart.set_ylim(0, 5)
chart.axis("off")
chart.set_title("When to reach for which", loc="left");
Figure

The curves cross where the picture of part 7 says they should. With more than a hundred readings per cell (on the left) the low-rank methods are within 5 to 30% of exact and Vecchia with 20 neighbours is 2.5 to 4 times worse. With fewer than ten (on the right) Vecchia is within 10% and the low-rank methods are three to four times worse, no better than a subsample. The crossing is between 26 and 60 readings per cell, a little above the 20 neighbours used. Vecchia with 120 neighbours at prediction is within 2 to 17% of exact on six fields and falls behind (1.7 times) only on the one with 320 readings per cell, where 120 neighbours are again too few.

The two fields with noisier sensors are the test of the "one number" claim, and they fall on the same curves as the others. The 5 km field read by sensors three times as noisy has 65 readings per cell, close to the 58 of the 10 km field, and every method scores on it as it does on the 10 km field: 1.2 against 1.3 times the floor for the HSGP, 1.4 against 1.6 for inducing points, 1.7 against 1.7 for Vecchia with 20 neighbours. It is the readings per cell that decide, not the length-scale alone.

The estimate in the denominator is the continuum formula, which is a little optimistic, so "1" in this panel is slightly out of reach for any method.

print(f"total run time: {(time.time() - T_START) / 60:.1f} minutes")
total run time: 3.9 minutes

Summary

  • An exact GP stops at a few thousand readings; three approximations go to 100,000 in seconds. One gradient of the exact likelihood on 2,000 readings costs 0.2 s and would cost six hours and 80 GB on 100,000. With the field integrated out and every likelihood computed in blocks, 26 fits on 100,000 readings took about three minutes and 2 GB. The limit: Gaussian noise. With counts or censoring the field cannot be integrated out exactly (E129).
  • Where $n$ sits in the cost decides what inference is affordable. The HSGP pays for $n$ once (its 100,000 readings collapse exactly into an $M \times M$ matrix), then a gradient costs 0.1 to 90 ms. Vecchia pays $n\,m^3$ per gradient (0.5 s at 20 neighbours) and inducing points $n\,M^2$ (1 s at 576). NUTS needed 21,000 gradients: ten seconds for a small HSGP, hours for the others. We fitted every row by mode and curvature in 10 to 100 gradients. Against NUTS on the full data that shortcut was 3 to 4% low on the medians of $a$ and $\ell$ and 7% short on their upper limits; on a subsample of 500 it was 7% and 13%.
  • The hypothesis was half right. We expected each approximation to smooth away real structure at short length-scales. The low-rank methods do, and not only there: on the rough field their error was 0.87 to 1.8 °C against 0.37 °C for Vecchia, and on the smooth field they were accurate (0.10 °C) but covered the truth 10 to 80% of the time instead of 90%. Vecchia never smoothed anything away. It failed the other way, on the smooth field, by leaving sensor noise in the map (0.23 °C with 20 neighbours, against 0.10 °C), while keeping 90% coverage throughout.
  • The published rule for the HSGP's size is about the kernel, not about the data. It asked for 16 functions per axis on the smooth field; that gave an error of 0.17 °C, 31% coverage and a length-scale of 9 km for a truth of 20. With dense sensors the posterior has structure well below the length-scale, and the rank must follow the number of resolution cells (750 here).
  • Low rank corrupts the hyperparameters; neighbours mostly do not. Variance a basis cannot carry is reported as sensor noise: 1.3 to 2.0 °C for a truth of 1.0 on the rough field, with intervals a hundredth of a degree wide, and inducing points overstated the length-scale by a factor of 2 to 16. Vecchia recovered all four numbers on the rough field at 10 and 20 neighbours. On the smooth field its interval for the mean was two to ten times too narrow and missed the truth.
  • Readings per resolution cell say which method will work. The readings resolve the field down to the wavelength where its spectrum meets the noise floor $\sigma^2/\rho$. The number of cells of that size is the rank a low-rank method needs, the readings per cell are the neighbours Vecchia needs, and their product is $n$. On seven fields the ranking followed that number, whether it was changed through the length-scale or through the noise: low rank won above a hundred readings per cell, neighbours below ten. Limit: the formula is for a stationary field with a known spectrum; on real data it is a guide for a first guess.
  • More neighbours at prediction than in the fit. Fitting Vecchia with 20 neighbours and predicting with 120 brought it within 2 to 17% of the exact GP's estimated error on six of seven fields, for three extra seconds, and it was the only setting that was accurate and calibrated at both length-scales. Limit: it does not repair the too-narrow interval for the mean.
  • Held-out readings barely told the methods apart on the ocean. On 2,535 Argo profiles the HSGP had the same held-out error as the exact GP (1.46 against 1.48 °C) and all four methods the same coverage, while the low-rank maps were 0.6 to 0.7 °C from the exact GP's and their noise 45 to 60% too large. Vecchia with 20 neighbours matched the exact GP to 0.02 °C. Limit: one snapshot, one kernel, a flat-map projection.

Try it yourself

  1. Give the HSGP what the cells ask for. On the long field, raise HSGP_M to 48 and 56 functions per axis (the statistics pass takes a few seconds and each gradient up to a second) and watch the coverage in race_figure("long"). Does it reach 90% when the highest sine passes the 7.3 km of part 7? Then add the variance the basis drops, amp**2 - (basis**2) @ spectral(amp, ell), to the predictive variance in predict_hsgp. Does it restore the coverage on the long field? On the short field it makes the intervals several degrees wide: explain why, from the fitted amp.
  2. Change the ordering. earlier_neighbours uses the row order. Sort the sensors by their first coordinate before calling race("long") and compare the Vecchia rows: the error, and above all the interval for the mean. Then write a maximin ordering (repeatedly pick the point farthest from those already picked; a coarse version on a 2 km grid of cells is enough) and see whether the interval for the mean recovers.
  3. Move the noise floor. In make_network, thin the sensors to 10,000 or make them five times more precise, recompute resolution(...), and predict from the cells and the readings per cell which method wins before you run race. Then check the prediction against the scoreboard.