This notebook is the first installment of pyrox’s Markov-GP track. It introduces MaternSDE — the state-space representation of the Matern- kernel for — and verifies, end-to-end, that the SDE formulation and the dense kernel describe the same Gaussian process. Once a kernel is in state-space form, GP inference on a 1-D grid drops from Cholesky to Kalman filtering, where is the SDE state dimension.
Subsequent notebooks (issues #37 finish, #38) will compose SDE kernels, run Kalman / RTS smoothing, and expose MarkovGPPrior for NumPyro models. This one stays focused on the representation layer: math, identities, and visual sanity checks.
Background — from kernel to SDE¶
Any stationary GP kernel on whose spectral density is rational in admits an exact, finite-dimensional state-space representation as a linear time-invariant SDE
with white-noise driver of spectral density and stationary state covariance solving the continuous Lyapunov equation
Discretising at non-uniform observation times with gives the discrete-time linear-Gaussian model
with and . The recovered continuous autocovariance is for , which we will verify against the dense Matern kernel below.
Matern- companion form¶
For Matern- with and , the state has dimension and is the companion matrix of . Concretely:
| Order | Closed-form kernel | |||
|---|---|---|---|---|
| 0 | 1/2 | 1 | ||
| 1 | 3/2 | 2 | ||
| 2 | 5/2 | 3 |
MaternSDE ships these three orders. Composition rules (sum / product), CosineSDE, PeriodicSDE, and the Kalman-based MarkovGPPrior follow in subsequent PRs.
Setup¶
Detect Colab and install pyrox-gp[colab] (which pulls in matplotlib and watermark) only when running there.
import subprocess
import sys
try:
import google.colab # noqa: F401
IN_COLAB = True
except ImportError:
IN_COLAB = False
if IN_COLAB:
subprocess.run(
[
sys.executable,
"-m",
"pip",
"install",
"-q",
"pyrox @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox",
"pyrox-gp[colab] @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox-gp",
"pyrox-ssm @ git+https://github.com/jejjohnson/pyrox@main#subdirectory=packages/pyrox-ssm",
],
check=True,
)import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import jax.random as jr
import jax.scipy.linalg as jsl
import matplotlib.pyplot as plt
import numpy as np
from kernellib.functional import matern_kernel
from pyrox_ssm import MaternSDE
jax.config.update("jax_enable_x64", True)import importlib.util
try:
from IPython import get_ipython
ipython = get_ipython()
except ImportError:
ipython = None
if ipython is not None and importlib.util.find_spec("watermark") is not None:
ipython.run_line_magic("load_ext", "watermark")
ipython.run_line_magic("watermark", "-v -m -p jax,equinox,numpyro,pyrox,matplotlib")
else:
print("watermark extension not installed; skipping reproducibility readout.")Python implementation: CPython
Python version : 3.13.12
IPython version : 9.13.0
jax : 0.10.2
equinox : 0.13.8
numpyro : 0.21.0
pyrox : 0.2.1
matplotlib: 3.10.9
Compiler : Clang 21.1.4
OS : Linux
Release : 6.8.0-1044-azure
Machine : x86_64
Processor : x86_64
CPU cores : 16
Architecture: 64bit
1. Inspecting the SDE parameters¶
A MaternSDE(variance, lengthscale, order) produces a closed-form tuple via sde_params(). We instantiate one kernel per order and print the structural matrices alongside two structural identities:
Variance recovery: .
Lyapunov closure: .
sigma2 = 1.0
ell = 0.5
sdes = {p: MaternSDE(variance=sigma2, lengthscale=ell, order=p) for p in (0, 1, 2)}
for p, sde in sdes.items():
F, L, H, Q_c, P_inf = sde.sde_params()
var_rec = float((H @ P_inf @ H.T).squeeze())
lyap = F @ P_inf + P_inf @ F.T + L @ Q_c @ L.T
print(
f"--- Matern-{2 * sde.order + 1}/2 (order p = {p}, state dim d = {sde.state_dim}) ---"
)
print(f"F =\n{np.asarray(F)}")
print(
f"H = {np.asarray(H).ravel()}, L^T = {np.asarray(L).ravel()}, Q_c = {float(Q_c.squeeze()):.4f}"
)
print(f"P_inf =\n{np.asarray(P_inf)}")
print(f"H P_inf H^T = {var_rec:.6f} (expected sigma^2 = {sigma2})")
print(
f"||F P_inf + P_inf F^T + L Q_c L^T||_inf = {float(jnp.max(jnp.abs(lyap))):.2e}"
)
print()--- Matern-1/2 (order p = 0, state dim d = 1) ---
F =
[[-2.]]
H = [1.], L^T = [1.], Q_c = 4.0000
P_inf =
[[1.]]
H P_inf H^T = 1.000000 (expected sigma^2 = 1.0)
||F P_inf + P_inf F^T + L Q_c L^T||_inf = 0.00e+00
--- Matern-3/2 (order p = 1, state dim d = 2) ---
F =
[[ 0. 1. ]
[-12. -6.92820323]]
H = [1. 0.], L^T = [0. 1.], Q_c = 166.2769
P_inf =
[[ 1. 0.]
[ 0. 12.]]
H P_inf H^T = 1.000000 (expected sigma^2 = 1.0)
||F P_inf + P_inf F^T + L Q_c L^T||_inf = 0.00e+00
--- Matern-5/2 (order p = 2, state dim d = 3) ---
F =
[[ 0. 1. 0. ]
[ 0. 0. 1. ]
[-89.4427191 -60. -13.41640786]]
H = [1. 0. 0.], L^T = [0. 0. 1.], Q_c = 9540.5567
P_inf =
[[ 1. 0. -6.66666667]
[ 0. 6.66666667 0. ]
[ -6.66666667 0. 400. ]]
H P_inf H^T = 1.000000 (expected sigma^2 = 1.0)
||F P_inf + P_inf F^T + L Q_c L^T||_inf = 5.68e-14
Both invariants hold to machine precision in float64. The variance-recovery identity says the SDE state encodes the GP value plus derivative-like coordinates; the Lyapunov identity says the stationary state covariance is consistent with the drift and the diffusion .
2. SDE autocovariance vs. dense Matern kernel¶
The continuous-time stationary autocovariance recovered from the SDE is
This must equal the dense Matern Gram value at lag . We compute both on a fine grid and overlay them.
def sde_autocov(sde: MaternSDE, taus: jnp.ndarray) -> jnp.ndarray:
F, _L, H, _Q_c, P_inf = sde.sde_params()
def _k(tau: jnp.ndarray) -> jnp.ndarray:
return (H @ jsl.expm(F * tau) @ P_inf @ H.T).squeeze()
return jax.vmap(_k)(taus)
taus = jnp.linspace(0.0, 2.5, 201)
X = taus[:, None]
X0 = jnp.zeros((1, 1))
fig, axes = plt.subplots(1, 3, figsize=(13.5, 3.6), sharey=True)
for ax, (p, sde) in zip(axes, sdes.items(), strict=False):
k_sde = sde_autocov(sde, taus)
k_dense = matern_kernel(
X, X0, jnp.asarray(sigma2), jnp.asarray(ell), nu=p + 0.5
).squeeze()
ax.plot(taus, k_dense, label="dense Matern", lw=2.4, alpha=0.85)
ax.plot(taus, k_sde, "--", label=r"$H \exp(F\tau) P_\infty H^\top$", lw=1.7)
err = float(jnp.max(jnp.abs(k_sde - k_dense)))
ax.set_title(rf"Matern-{2 * sde.order + 1}/2 (max abs err: {err:.1e})")
ax.set_xlabel(r"lag $\tau$")
ax.grid(alpha=0.25)
axes[0].set_ylabel(r"$k(\tau)$")
axes[0].legend(frameon=False, loc="upper right")
fig.suptitle("SDE autocovariance recovers the dense Matern kernel")
fig.tight_layout()
plt.show()
All three orders agree to numerical precision. The SDE is not an approximation of the Matern kernel — for it is an exact reformulation.
3. Discretisation: and as functions of ¶
Given a time step , the discrete-time transition is and the process-noise covariance is . Two endpoints are worth checking:
As , and (no time elapsed, no uncertainty added).
As , (the dynamics decay back to the stationary distribution) and so (the next state is independent of the previous one and has the stationary distribution).
We plot and the trace of over a log-spaced range of step sizes.
dts = jnp.geomspace(1e-3, 5e1, 200)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6))
for p, sde in sdes.items():
A, Q = sde.discretise_sequence(dts)
A_norm = jnp.linalg.norm(A, ord=2, axis=(1, 2))
Q_trace = jnp.einsum("nii->n", Q)
_, _, _, _, P_inf = sde.sde_params()
P_inf_trace = float(jnp.trace(P_inf))
label = rf"$\nu = {p}+1/2$"
axes[0].plot(dts, A_norm, label=label, lw=1.8)
axes[1].plot(dts, Q_trace, label=label, lw=1.8)
axes[1].axhline(
P_inf_trace, color=axes[1].lines[-1].get_color(), ls=":", alpha=0.55
)
for ax in axes:
ax.set_xscale("log")
ax.set_xlabel(r"step size $\Delta t$")
ax.grid(alpha=0.25)
axes[0].set_ylabel(r"$\|A(\Delta t)\|_2$")
axes[0].set_title(r"Transition matrix decay: $A \to 0$ as $\Delta t \to \infty$")
axes[1].set_ylabel(r"$\mathrm{tr}\,Q(\Delta t)$")
axes[1].set_title(r"Process noise growth: $Q \to P_\infty$ as $\Delta t \to \infty$")
axes[1].legend(frameon=False, loc="lower right")
fig.tight_layout()
plt.show()
Dotted horizontal lines mark for each order — the asymptote relaxes onto. Higher-order Materns relax slower (more oscillatory state coordinates carry inertia), but the limit is the same.
4. Sample paths via forward simulation of the discrete-time SDE¶
We can draw GP sample paths without ever forming a dense Gram matrix. The recipe is the standard linear-Gaussian forward simulation of the discrete state-space model:
Sample .
For : sample with .
Read out .
All work is local in time; no Cholesky. We compare paths drawn this way against paths drawn from the dense Matern Cholesky for the same time grid.
def sample_sde_paths(
sde: MaternSDE,
times: jnp.ndarray,
n_paths: int,
key: jax.Array,
) -> jnp.ndarray:
"""Forward-simulate ``n_paths`` realisations of the discrete state-space model."""
_F, _L, H, _Q_c, P_inf = sde.sde_params()
d = sde.state_dim
dts = jnp.diff(times)
A_all, Q_all = sde.discretise_sequence(dts)
L_inf = jnp.linalg.cholesky(P_inf + 1e-10 * jnp.eye(d))
L_step = jnp.linalg.cholesky(Q_all + 1e-10 * jnp.eye(d)[None])
key_init, key_step = jr.split(key)
x0 = L_inf @ jr.normal(key_init, (d, n_paths)) # (d, n_paths)
eps = jr.normal(key_step, (dts.shape[0], d, n_paths))
def step(
x_prev: jnp.ndarray, inputs: tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]
) -> tuple[jnp.ndarray, jnp.ndarray]:
A_k, L_k, eps_k = inputs
x_next = A_k @ x_prev + L_k @ eps_k
return x_next, x_next
_, xs = jax.lax.scan(step, x0, (A_all, L_step, eps))
states = jnp.concatenate([x0[None], xs], axis=0) # (N, d, n_paths)
f_paths = jnp.einsum("ij,njp->np", H, states) # (N, n_paths)
return f_paths
def sample_dense_paths(
sde: MaternSDE,
times: jnp.ndarray,
n_paths: int,
key: jax.Array,
) -> jnp.ndarray:
X = times[:, None]
K = matern_kernel(X, X, sde.variance, sde.lengthscale, nu=sde.order + 0.5)
K = K + 1e-8 * jnp.eye(X.shape[0])
L = jnp.linalg.cholesky(K)
return L @ jr.normal(key, (X.shape[0], n_paths))
N = 320
times = jnp.linspace(0.0, 4.0, N)
n_paths = 4
seed = 0
fig, axes = plt.subplots(3, 2, figsize=(12, 7.5), sharex=True)
for row, (_p, sde) in enumerate(sdes.items()):
sde_paths = sample_sde_paths(sde, times, n_paths, jr.PRNGKey(seed))
dense_paths = sample_dense_paths(sde, times, n_paths, jr.PRNGKey(seed + 1))
for j in range(n_paths):
axes[row, 0].plot(times, sde_paths[:, j], lw=1.2, alpha=0.85)
axes[row, 1].plot(times, dense_paths[:, j], lw=1.2, alpha=0.85)
axes[row, 0].set_ylabel(rf"Matern-{2 * sde.order + 1}/2")
for ax in axes[row]:
ax.grid(alpha=0.2)
ax.axhline(0.0, color="k", lw=0.4, alpha=0.4)
axes[0, 0].set_title("SDE forward-simulation paths")
axes[0, 1].set_title("Dense Matern Cholesky paths")
for ax in axes[-1]:
ax.set_xlabel("t")
fig.suptitle("Same statistics, different generation path")
fig.tight_layout()
plt.show()
Each row pairs the same kernel order; the seeds differ across columns so the realisations are independent draws. Visually the rougher Matern-1/2 paths sit on top, the smoother Matern-5/2 paths at the bottom, with the SDE and dense columns indistinguishable in their statistical character. The variances and correlation lengths match by construction.
5. Empirical covariance of SDE samples matches the analytic kernel¶
A stronger check than visual matching: estimate the covariance from many SDE-simulated paths and compare to the closed-form Matern Gram on the same grid.
n_mc = 2000
mc_times = jnp.linspace(0.0, 2.0, 41)
fig, axes = plt.subplots(1, 3, figsize=(13.5, 4.0))
for ax, (p, sde) in zip(axes, sdes.items(), strict=False):
paths = sample_sde_paths(sde, mc_times, n_mc, jr.PRNGKey(11 + p)) # (N, n_mc)
paths_centered = paths - paths.mean(axis=1, keepdims=True)
C_emp = (paths_centered @ paths_centered.T) / (n_mc - 1)
K_true = matern_kernel(
mc_times[:, None],
mc_times[:, None],
sde.variance,
sde.lengthscale,
nu=sde.order + 0.5,
)
ax.plot(
mc_times, jnp.diag(C_emp), label=r"$\widehat{\mathrm{Var}}\,f(t)$ (MC)", lw=1.7
)
ax.plot(mc_times, jnp.diag(K_true), "--", label=r"$\sigma^2$", lw=1.4)
ax.plot(
mc_times,
C_emp[:, 0],
lw=1.7,
label=r"$\widehat{\mathrm{Cov}}\,(f(0), f(t))$ (MC)",
)
ax.plot(mc_times, K_true[:, 0], "--", lw=1.4, label=r"$k(t, 0)$")
ax.set_title(rf"Matern-{2 * sde.order + 1}/2 ({n_mc} paths)")
ax.set_xlabel("t")
ax.grid(alpha=0.25)
axes[0].legend(frameon=False, loc="upper right", fontsize=8)
fig.suptitle(
"Empirical covariance from SDE samples agrees with the analytic Matern kernel"
)
fig.tight_layout()
plt.show()
Solid lines are Monte-Carlo estimates from forward simulations; dashed lines are the closed-form values. They overlap to the precision afforded by 2000 samples.
6. The kernel zoo — primitives and composition rules¶
Matern alone is enough to cover smooth time series, but real signals usually have more structure: a fixed offset, a carrier oscillation, an annual cycle, a quasi-periodic modulation. State-space form scales gracefully here too — every additional kernel is another small block in the state, not another factor of in inference cost.
This section walks through the four new primitive / composition kernels added on top of MaternSDE:
| Class | Math | State dim |
|---|---|---|
ConstantSDE(σ²) | 1 | |
CosineSDE(σ², ω) | 2 | |
PeriodicSDE(σ², ℓ, T, J) | MacKay periodic, Fourier-truncated to harmonics | |
SumSDE((k₁, …)) | ||
ProductSDE(k₁, k₂) | ||
QuasiPeriodicSDE(matern, periodic) | thin wrapper for ProductSDE |
SumSDE is block-diagonal in , , and , with the readouts concatenated. ProductSDE uses Kronecker-sum drift and Kronecker-product readout / stationary covariance , . The diffusion is a sum of two Kronecker terms — see the ProductSDE docstring for the full formula.
from kernellib.functional import periodic_kernel
from pyrox_ssm import (
ConstantSDE,
CosineSDE,
PeriodicSDE,
ProductSDE,
QuasiPeriodicSDE,
SumSDE,
)6.1 Building blocks: ConstantSDE, CosineSDE, PeriodicSDE¶
We instantiate one of each, draw a few sample paths via the same forward-simulation recipe used for Matern in §4, and overlay the SDE autocovariance against a dense reference where one is available. PeriodicSDE uses n_harmonics = 7 — enough to match the MacKay periodic kernel to better than 1e-4 in the typical hyperparameter regime.
const = ConstantSDE(variance=0.6)
cos = CosineSDE(variance=1.0, frequency=2.0 * jnp.pi) # period 1
per = PeriodicSDE(variance=1.0, lengthscale=1.0, period=1.0, n_harmonics=7)
primitives = {"ConstantSDE": const, "CosineSDE": cos, "PeriodicSDE": per}
times_demo = jnp.linspace(0.0, 4.0, 320)
fig, axes = plt.subplots(3, 2, figsize=(13, 7.8), sharex="col")
for row, (name, sde) in enumerate(primitives.items()):
paths = sample_sde_paths(sde, times_demo, n_paths=4, key=jr.PRNGKey(7 + row))
for j in range(4):
axes[row, 0].plot(times_demo, paths[:, j], lw=1.1, alpha=0.85)
axes[row, 0].set_ylabel(name)
axes[row, 0].grid(alpha=0.25)
axes[row, 0].axhline(0.0, color="k", lw=0.4, alpha=0.4)
F, _L, H, _Q_c, P_inf = sde.sde_params()
taus_demo = jnp.linspace(0.0, 4.0, 401)
K_sde = jax.vmap(
lambda t, F=F, H=H, P_inf=P_inf: (H @ jsl.expm(F * t) @ P_inf @ H.T).squeeze()
)(taus_demo)
axes[row, 1].plot(taus_demo, K_sde, lw=1.8, label="SDE autocov", color="C0")
if name == "ConstantSDE":
axes[row, 1].axhline(0.6, ls="--", lw=1.3, color="C3", label=r"$\sigma^2$")
elif name == "CosineSDE":
axes[row, 1].plot(
taus_demo,
jnp.cos(2.0 * jnp.pi * taus_demo),
"--",
lw=1.3,
label=r"$\sigma^2 \cos(\omega\tau)$",
)
else:
K_dense = periodic_kernel(
taus_demo[:, None],
jnp.zeros((1, 1)),
jnp.asarray(1.0),
jnp.asarray(1.0),
jnp.asarray(1.0),
).squeeze()
axes[row, 1].plot(taus_demo, K_dense, "--", lw=1.3, label="MacKay periodic")
axes[row, 1].grid(alpha=0.25)
axes[row, 1].legend(frameon=False, loc="upper right", fontsize=8)
axes[0, 0].set_title("Sample paths")
axes[0, 1].set_title("Autocovariance vs reference")
for ax in axes[-1]:
ax.set_xlabel("t" if ax is axes[-1, 0] else r"lag $\tau$")
fig.suptitle("Primitive SDE kernels: paths and autocovariance")
fig.tight_layout()
plt.show()
ConstantSDEpaths are flat realisations: each draw is a single Gaussian random variable replicated across time. The autocovariance is the constant .CosineSDEpaths are pure sinusoids with random amplitude and phase. The covariance oscillates exactly as .PeriodicSDEpaths are smooth, period-aware, and not sinusoidal — they live in the function space of the MacKay periodic kernel. Truncating the Fourier expansion at matches the dense kernel within plotting precision.
6.2 Composition: trend + offset via SumSDE¶
A common modelling pattern is “smooth trend on top of a fixed offset”. With dense kernels this is one line: RBF + Constant. In state-space form it’s exactly the same — just SumSDE. The block-diagonal construction keeps each component’s state space disjoint, so the cost is purely additive ().
trend = SumSDE(
(
MaternSDE(variance=0.7, lengthscale=0.8, order=1),
ConstantSDE(variance=0.4),
)
)
print(f"SumSDE state dim: {trend.state_dim} (= 2 + 1)")
paths = sample_sde_paths(trend, times_demo, n_paths=6, key=jr.PRNGKey(33))
fig, axes = plt.subplots(1, 2, figsize=(12, 3.6))
for j in range(6):
axes[0].plot(times_demo, paths[:, j], lw=1.1, alpha=0.85)
axes[0].set_title("MaternSDE-3/2 + ConstantSDE — sample paths")
axes[0].set_xlabel("t")
axes[0].grid(alpha=0.25)
F, _L, H, _Q_c, P_inf = trend.sde_params()
taus_demo = jnp.linspace(0.0, 3.0, 301)
K_sum = jax.vmap(lambda t: (H @ jsl.expm(F * t) @ P_inf @ H.T).squeeze())(taus_demo)
K_truth = (
matern_kernel(
taus_demo[:, None],
jnp.zeros((1, 1)),
jnp.asarray(0.7),
jnp.asarray(0.8),
nu=1.5,
).squeeze()
+ 0.4
)
axes[1].plot(taus_demo, K_sum, lw=2.2, label=r"$H \exp(F\tau) P_\infty H^\top$")
axes[1].plot(taus_demo, K_truth, "--", lw=1.3, label=r"$k_M(\tau) + \sigma_C^2$")
axes[1].set_title("Autocovariance: SumSDE matches dense sum")
axes[1].set_xlabel(r"lag $\tau$")
axes[1].grid(alpha=0.25)
axes[1].legend(frameon=False, loc="upper right")
fig.tight_layout()
plt.show()SumSDE state dim: 3 (= 2 + 1)

Sample paths show the Matern wiggle riding on independently-drawn constant offsets — exactly the prior we wanted. The autocovariance recovers to machine precision.
6.3 Composition: damped oscillation via ProductSDE¶
The product of a Matern and a Cosine is the subband Matern kernel — a stationary kernel whose spectral density is centred on a non-zero carrier . It’s the right prior for narrowband oscillatory signals (audio harmonics, geophysical resonances, modulated sensor traces). State dim is — for Matern-3/2 × Cosine that’s .
damped = ProductSDE(
MaternSDE(variance=1.0, lengthscale=0.6, order=1),
CosineSDE(variance=1.0, frequency=2.0 * jnp.pi * 1.5), # 1.5 Hz carrier
)
print(f"ProductSDE state dim: {damped.state_dim}")
paths = sample_sde_paths(damped, times_demo, n_paths=4, key=jr.PRNGKey(101))
fig, axes = plt.subplots(1, 2, figsize=(12, 3.6))
for j in range(4):
axes[0].plot(times_demo, paths[:, j], lw=1.1, alpha=0.85)
axes[0].set_title("MaternSDE-3/2 x CosineSDE — sample paths")
axes[0].set_xlabel("t")
axes[0].grid(alpha=0.25)
F, _L, H, _Q_c, P_inf = damped.sde_params()
taus_demo = jnp.linspace(0.0, 2.0, 401)
K_prod = jax.vmap(lambda t: (H @ jsl.expm(F * t) @ P_inf @ H.T).squeeze())(taus_demo)
K_m = matern_kernel(
taus_demo[:, None], jnp.zeros((1, 1)), jnp.asarray(1.0), jnp.asarray(0.6), nu=1.5
).squeeze()
K_c = jnp.cos(2.0 * jnp.pi * 1.5 * taus_demo)
axes[1].plot(taus_demo, K_prod, lw=2.2, label=r"ProductSDE autocov")
axes[1].plot(
taus_demo,
K_m * K_c,
"--",
lw=1.3,
label=r"$k_{\rm Matern}(\tau)\,\cos(\omega_0\tau)$",
)
axes[1].set_title("Autocovariance: ProductSDE matches dense product")
axes[1].set_xlabel(r"lag $\tau$")
axes[1].grid(alpha=0.25)
axes[1].legend(frameon=False, loc="upper right")
fig.tight_layout()
plt.show()ProductSDE state dim: 4

The paths are oscillations whose envelope drifts on the Matern lengthscale — a damped carrier signal. The product autocovariance matches to numerical precision (the slight curvature of the envelope reflects the Matern factor).
6.4 Quasi-periodic kernels — modulated periodic structure¶
The classic “stellar” prior: a periodic signal whose amplitude drifts slowly over time. Mathematically it’s — a ProductSDE of two stationary kernels. QuasiPeriodicSDE is just a thin convenience wrapper that documents the standard recipe.
qp = QuasiPeriodicSDE(
MaternSDE(variance=1.0, lengthscale=2.5, order=1), # slow envelope (long ell)
PeriodicSDE(variance=1.0, lengthscale=1.0, period=0.6, n_harmonics=5),
)
print(f"QuasiPeriodicSDE state dim: {qp.state_dim} (= 2 * (1 + 2*5))")
paths = sample_sde_paths(qp, times_demo, n_paths=4, key=jr.PRNGKey(57))
fig, ax = plt.subplots(1, 1, figsize=(13, 3.4))
for j in range(4):
ax.plot(times_demo, paths[:, j], lw=1.1, alpha=0.85)
ax.set_title(
"QuasiPeriodicSDE: Matern-3/2 (ell=2.5) x Periodic (period=0.6, J=5) — modulated cycles"
)
ax.set_xlabel("t")
ax.axhline(0.0, color="k", lw=0.4, alpha=0.4)
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()QuasiPeriodicSDE state dim: 24 (= 2 * (1 + 2*5))

Each draw shows a clear period of about 0.6 time units, but the amplitude drifts on a slow Matern timescale — short bursts of high-amplitude oscillation followed by quiescent stretches, exactly the prior class used for stellar light curves and modulated seasonal signals.
7. From the kernel zoo to geoscience signals¶
Section 6 showed that every class above is an exact state-space kernel. This section is about when to reach for each one. The useful question is rarely “which kernel is best” but three narrower ones: what does the variable’s power spectrum look like, along which axis (time, a transect, a spatial field) is the kernel defined, and how was the variable sampled. We read each class through its spectrum, map it to geophysical signals where the literature motivates that choice, and end with the successes and failures to look out for.
7.1 Every SDE kernel is a statement about a spectrum¶
A stationary SDE with readout is a linear filter driven by white noise, so its output has the power spectral density
and the Wiener–Khinchin theorem returns the kernel as (Särkkä & Solin, 2019). Three facts follow, and they are most of what you need to choose a kernel.
Matern sets a knee and a slope. For Matern-, with . The spectrum is flat below the knee and falls as above it: slopes of -2, -4 and -6 for orders . The lengthscale places the knee; the order sets how fast high-frequency variance dies, which is the same thing as how many derivatives the paths have.
Sums add spectra.
SumSDEputs each component’s variance in its own band, which is why decompositions such as trend + seasonal cycle + anomaly are natural in this form.Products move spectra. Multiplying a kernel by convolves its spectrum with lines at , so
ProductSDE(MaternSDE, CosineSDE)is a band centred on whose width is set by the Matern knee .QuasiPeriodicSDEplaces one such band at every harmonic .CosineSDE,PeriodicSDEandConstantSDEon their own carry no diffusion (): all their variance sits on exact lines at , at , or at .
The helper below evaluates from sde_params() directly and checks two of these facts numerically: that recovers the Matern variance, and that the spectrum of a SumSDE equals the sum of its components’ spectra.
def sde_psd(sde, omegas: jnp.ndarray) -> jnp.ndarray:
"""Power spectral density of a stationary SDE kernel at angular frequencies ``omegas``."""
F, L, H, Q_c, _P_inf = sde.sde_params()
d = F.shape[0]
LQL = L @ jnp.atleast_2d(Q_c) @ L.T
def one(w: jnp.ndarray) -> jnp.ndarray:
G = jnp.linalg.solve(1j * w * jnp.eye(d) - F, jnp.eye(d))
return jnp.real(H @ G @ LQL @ G.conj().T @ H.T).squeeze()
return jax.vmap(one)(omegas)
omega_grid = jnp.linspace(-2000.0, 2000.0, 800_001)
for p in (0, 1, 2):
sde = MaternSDE(variance=sigma2, lengthscale=ell, order=p)
var = jnp.trapezoid(sde_psd(sde, omega_grid), omega_grid) / (2.0 * jnp.pi)
print(
f"Matern-{2 * p + 1}/2: (1/2pi) * integral of S = {float(var):.4f} (variance = {sigma2})"
)Matern-1/2: (1/2pi) * integral of S = 0.9994 (variance = 1.0)
Matern-3/2: (1/2pi) * integral of S = 1.0000 (variance = 1.0)
Matern-5/2: (1/2pi) * integral of S = 1.0000 (variance = 1.0)
The Matern-1/2 integral comes out slightly low only because its tail extends past the finite grid; the smoother orders converge to the variance.
The left panel below shows the knee-and-slope picture for the three Matern orders. The right panel is a schematic spectrum assembled from blocks, each placed in the band where the literature in §7.2 uses it: a red-noise anomaly, a seasonal cycle with drifting amplitude, an intraseasonal 40–50 day band and four tidal lines. It is not one real variable (sea level, winds and sea-surface temperature are mixed for illustration), and the variances are chosen for display. Frequencies are in cycles per day, .
days_per_year = 365.25
red_noise = MaternSDE(variance=0.5, lengthscale=30.0, order=0)
seasonal = QuasiPeriodicSDE(
MaternSDE(variance=1.0, lengthscale=5.0 * days_per_year, order=1),
PeriodicSDE(variance=1.0, lengthscale=1.0, period=days_per_year, n_harmonics=4),
)
intraseasonal = ProductSDE(
MaternSDE(variance=0.3, lengthscale=60.0, order=1),
CosineSDE(variance=1.0, frequency=2.0 * jnp.pi / 45.0),
)
blocks = {
"Matern-1/2 red noise, ell = 30 d": red_noise,
"QuasiPeriodic seasonal cycle": seasonal,
"Matern-3/2 x Cosine, 45 d band": intraseasonal,
}
schematic = SumSDE(tuple(blocks.values()))
# Tidal constituent periods in hours (M2, S2, K1, O1), as in classical harmonic analysis.
tides_h = {"M2": 12.4206, "S2": 12.0000, "K1": 23.9345, "O1": 25.8193}
tide_var = {"M2": 0.6, "S2": 0.25, "K1": 0.2, "O1": 0.15}
cpd = jnp.logspace(-4, jnp.log10(3.0), 1500) # cycles per day
omega = 2.0 * jnp.pi * cpd
S_parts = {name: sde_psd(sde, omega) for name, sde in blocks.items()}
S_sum = sde_psd(schematic, omega)
rel = jnp.max(jnp.abs(S_sum - sum(S_parts.values())) / S_sum)
print(
f"SumSDE state dim: {schematic.state_dim}; max rel |S_sum - sum of parts| = {float(rel):.1e}"
)
fig, axes = plt.subplots(1, 2, figsize=(13, 4.4))
w = jnp.logspace(-2, 2.5, 400)
for p in (0, 1, 2):
sde = MaternSDE(variance=1.0, lengthscale=1.0, order=p)
axes[0].loglog(w, sde_psd(sde, w), lw=1.8, label=f"Matern-{2 * p + 1}/2")
for slope, x0, y0 in ((-2, 30.0, 4e-3), (-4, 30.0, 1.5e-6), (-6, 30.0, 2.5e-9)):
xs = jnp.array([x0, 8 * x0])
axes[0].loglog(xs, y0 * (xs / x0) ** slope, "k:", lw=1.0)
axes[0].text(
xs[-1] * 1.1, y0 * 8.0**slope, rf"$\omega^{{{slope}}}$", fontsize=9, va="center"
)
axes[0].set_xlabel(r"angular frequency $\omega$ ($\ell = 1$)")
axes[0].set_ylabel(r"$S(\omega)$")
axes[0].set_title("Matern: flat below the knee, power law above it")
axes[0].grid(alpha=0.25, which="both")
axes[0].legend(frameon=False, loc="lower left")
for name, S in S_parts.items():
axes[1].loglog(cpd, S, "--", lw=1.1, alpha=0.9, label=name)
axes[1].loglog(cpd, S_sum, color="k", lw=1.8, label="SumSDE of the three")
y_top = float(S_sum.max())
for name, period_h in tides_h.items():
f_t = 24.0 / period_h
axes[1].vlines(f_t, 1e-6, tide_var[name] * y_top, color="C3", lw=1.6)
axes[1].text(0.85, 0.5 * y_top, "K1, O1", color="C3", fontsize=8, ha="right")
axes[1].text(2.2, 0.5 * y_top, "M2,\nS2", color="C3", fontsize=8, ha="left")
axes[1].plot([], [], color="C3", lw=1.6, label="CosineSDE lines (tides)")
axes[1].set_ylim(1e-6, 30 * y_top)
axes[1].set_xlabel("frequency (cycles per day)")
axes[1].set_title("Schematic: a geophysical spectrum built from blocks")
axes[1].grid(alpha=0.25, which="both")
axes[1].legend(frameon=False, loc="lower left", fontsize=8)
fig.tight_layout()
plt.show()SumSDE state dim: 25; max rel |S_sum - sum of parts| = 4.8e-16

Reading the right panel from low to high frequency: the red-noise block is flat at periods longer than its 30-day memory and falls as beyond it; the seasonal block puts narrow peaks at one cycle per year and its harmonics, broadened only slightly because its amplitude envelope drifts over five years, plus a hump at periods longer than about five years from the periodic kernel’s constant () term riding on the same envelope; the intraseasonal block is a single hump around 1/45 cycles per day; the tides are exact lines because their frequencies are fixed by astronomy. The SumSDE curve is the sum of the dashed ones to round-off, as printed above.
7.2 Which class for which signal¶
| Class | Spectrum | Reach for it when | Geoscience example | Literature |
|---|---|---|---|---|
MaternSDE, order 0 (Ornstein–Uhlenbeck) | flat, then | the signal is rough and mean-reverting with one memory time | SST anomalies integrating weather noise; the red-noise null hypothesis for climate spectra | Hasselmann (1976); Frankignoul & Hasselmann (1977) |
MaternSDE, orders 1 and 2 | flat, then or | the paths should be once or twice differentiable; the default for smooth physical fields | a slowly varying trend; interpolating a smooth state between sparse observations | Stein (1999); Rasmussen & Williams (2006) |
ConstantSDE | all variance at | a level that is unknown but fixed over the record | a station, instrument or retrieval offset | — |
SumSDE of CosineSDEs | lines at known | the frequencies are fixed by physics and only amplitude and phase are unknown | tidal constituents M2, S2, K1, O1 in a tide-gauge or altimetry record | Pawlowicz et al. (2002) |
PeriodicSDE | lines at | a cycle repeats with a fixed, non-sinusoidal shape | a climatological diurnal or seasonal cycle | Solin & Särkkä (2014) |
QuasiPeriodicSDE | bands at | the cycle repeats but its amplitude and shape drift | the seasonal cycle of atmospheric CO₂ at Mauna Loa | Rasmussen & Williams (2006, §5.4.3) |
ProductSDE(MaternSDE, CosineSDE) | one band at , width | variability is concentrated in one band around a single frequency, with a phase that wanders | the 40–50 day Madden–Julian oscillation in tropical winds | Madden & Julian (1971); Foreman-Mackey et al. (2017) |
SumSDE of the above | the sum | you want the posterior of each component, not only of the total | trend + seasonal + anomaly + noise decompositions | Rasmussen & Williams (2006, §5.4.3) |
Two of these deserve a sentence each. Hasselmann’s stochastic climate model treats a slow component (ocean temperature) as integrating fast weather forcing against a restoring feedback, which is exactly the Ornstein–Uhlenbeck SDE, so Matern-1/2 is the physically motivated null model for a mixed-layer anomaly rather than an arbitrary choice. The Mauna Loa CO₂ model in Rasmussen & Williams is a dense-GP sum of a long-term smooth trend, a periodic-times-decay seasonal term, medium-term irregularities and noise; in state-space form the same decomposition is SumSDE((MaternSDE(..., order=2), QuasiPeriodicSDE(...), MaternSDE(..., order=1))) plus a Gaussian likelihood, at linear cost in the record length. Their squared-exponential and rational-quadratic terms have no finite-dimensional SDE, which is why Matern blocks stand in for them here. Foreman-Mackey et al. reach the same band-limited class from the other direction: their celerite kernels are mixtures of stochastically driven damped harmonic oscillators, the stellar-variability analogue of the Matern × Cosine block.
7.3 Time, space and the axis a kernel lives on¶
Every kernel in this notebook is defined on one axis. That axis is usually time, and time is where the state-space form is strongest: it is causal, and irregular time stamps are handled exactly, because discretise_sequence takes each separately. Satellite overpasses with cloud gaps, or a buoy that drops out for a month, need no gridding or interpolation.
A one-dimensional spatial coordinate works the same way: distance along an altimeter ground track, an aircraft or ship transect, or altitude in a vertical profile. The Markov property then runs along the transect; the filter has a direction, but the smoother uses both sides, so the posterior does not.
For a field over 2-D or 3-D space and time there are two standard routes. The first keeps the SDE in time and puts a spatial kernel across locations, , so the Kalman state holds the whole spatial field at each time step (Särkkä, Solin & Hartikainen, 2013; Hamelijnck et al., 2021). The second writes a spatial Matern field as the solution of a stochastic PDE and discretises it into a sparse Gaussian Markov random field (Lindgren, Rue & Lindström, 2011); in pyrox that route belongs to pyrox_lgm. The limitation of the first route is separability: a product kernel cannot represent a signal that propagates, such as the annual-period westward Rossby waves that Schlax & Chelton (1994) found in North Atlantic altimetry. Propagating signals need a non-separable space-time covariance (Gneiting, 2002).
7.4 Successes and failures to look out for¶
Where these kernels do well.
Long, irregularly sampled records: the cost is , decades of hourly data are routine, and gaps cost nothing.
Decompositions: with a
SumSDE, the smoother returns the posterior of each block (trend, season, anomaly) separately, so the components are interpretable without fitting them one after another.Known frequencies: when physics fixes , as for tides, a
CosineSDEblock constrains the signal far more tightly than any flexible kernel could.
What to look out for.
Smoothness mismatch. The squared-exponential (RBF) kernel has no finite-dimensional SDE and only an approximate state-space form (Hartikainen & Särkkä, 2010); Stein (1999) argues it is too smooth for most physical processes anyway. Matern is available only for , so check the observed spectral slope before choosing the order: an inertial-range turbulent signal, whose spectrum falls as (Kolmogorov, 1941), is rougher than even Matern-1/2.
Variance and lengthscale trade off. Under denser sampling of a fixed record, the variance and lengthscale of a Matern kernel cannot both be estimated consistently; only a combination of them can (Zhang, 2004). A short record constrains the slow components poorly, so put priors on and interpret the fitted variance together with it.
Aliasing. A signal sampled less often than twice per period appears at a false, lower frequency. A
CosineSDEat the true frequency still fits aliased data correctly, because it is evaluated at the true time stamps; a flexible kernel that lets the data choose the frequency will fit the alias instead. The figure below shows the classic case.A strictly periodic kernel where the cycle drifts.
PeriodicSDEon its own has no diffusion: once its amplitude and phase are drawn, the cycle repeats exactly, so a cycle whose length or phase wanders lies outside its prior. Multiplying by a Matérn envelope removes that constraint: in bothQuasiPeriodicSDEand Matern ×CosineSDEthe envelope broadens the spectral lines and lets phase coherence decay over the envelope’s lengthscale (each nonzero harmonic ofQuasiPeriodicSDEis itself a Matern × Cosine band). Choose between the two by harmonic content.QuasiPeriodicSDEkeeps the periodic kernel’s harmonics, for a non-sinusoidal cycle such as a seasonal cycle with a sharp peak; Matern ×CosineSDEis a single band, for a near-sinusoidal oscillation such as the Madden–Julian oscillation.State dimension. Sharp cycle features need more harmonics (Solin & Särkkä, 2014), and a product multiplies state dimensions: Matern-5/2 ×
PeriodicSDEwith has , so each filter step costs about 633.Non-stationary or non-Gaussian variables. All these kernels are stationary. A trend whose rate changes needs a long-lengthscale Matern trend block, not a stationary anomaly kernel. Precipitation, counts and positive concentrations need a non-Gaussian likelihood on a latent Markov GP, which the non-Gaussian Markov notebook covers.
# TOPEX/Poseidon's exact-repeat period, used by Schlax & Chelton (1994).
repeat_days = 9.9156
def alias_period_days(period_h: float, dt_days: float) -> float:
"""Apparent period of a sinusoid of ``period_h`` hours sampled every ``dt_days`` days."""
f = 24.0 / period_h # cycles per day
cycles_per_sample = f * dt_days
f_alias = abs(cycles_per_sample - round(cycles_per_sample)) / dt_days
return 1.0 / f_alias
for name, period_h in tides_h.items():
print(
f"{name}: true period {period_h:7.4f} h -> alias period {alias_period_days(period_h, repeat_days):6.1f} d"
)
t_fine = jnp.arange(0.0, 300.0, 1.0 / 48.0) # half-hourly, 300 days
t_obs = jnp.arange(0.0, 300.0, repeat_days)
omega_m2 = 2.0 * jnp.pi * 24.0 / tides_h["M2"]
m2_true = jnp.cos(omega_m2 * t_fine)
m2_obs = jnp.cos(omega_m2 * t_obs)
p_alias = alias_period_days(tides_h["M2"], repeat_days)
# The alias is the sinusoid at the folded frequency that passes through the samples.
m2_alias = jnp.cos(2.0 * jnp.pi * t_fine / p_alias)
fig, ax = plt.subplots(1, 1, figsize=(13, 3.4))
ax.plot(
t_fine,
m2_true,
color="0.75",
lw=0.3,
label="M2 tide (12.42 h), sampled half-hourly",
)
ax.plot(
t_fine,
m2_alias,
color="C0",
lw=1.6,
label=f"what the samples show: a {p_alias:.1f}-day oscillation",
)
ax.plot(t_obs, m2_obs, "o", color="C3", ms=6, label=f"samples every {repeat_days} d")
ax.set_xlabel("time (days)")
ax.set_title("Aliasing: a 12.42-hour tide sampled on a 9.92-day repeat orbit")
ax.legend(frameon=False, loc="upper right", fontsize=8, ncol=3)
ax.set_ylim(-1.5, 1.9)
ax.grid(alpha=0.25)
fig.tight_layout()
plt.show()M2: true period 12.4206 h -> alias period 62.1 d
S2: true period 12.0000 h -> alias period 58.7 d
K1: true period 23.9345 h -> alias period 173.2 d
O1: true period 25.8193 h -> alias period 45.7 d

Every sample lies on the slow curve, so from the samples alone a 62-day oscillation and a 12.42-hour tide are indistinguishable. All the aliases printed above except K1’s are shorter than 90 days, as Schlax & Chelton (1994) show for this orbit, so they sit in the same band as real intraseasonal ocean variability. The defence is the one in item 3: put the tide in the model as CosineSDE blocks at the astronomical frequencies and evaluate them at the true observation times.
What this PR ships and what comes next¶
PR 1 (issue #37 partial, #112 — already merged). The SDEKernel protocol and the MaternSDE family for .
This PR (issue #37 finish). The kernel zoo on top of MaternSDE:
Primitives:
ConstantSDE,CosineSDE(closed-form rotationdiscretise),PeriodicSDE(Solin & Sarkka 2014, Fourier-truncated MacKay periodic kernel via a stable log-space Bessel helper).Composition rules:
SumSDE(block-diagonal) andProductSDE(Kronecker-sum drift, Kronecker-product readout / stationary covariance, with the diffusion matrix derived from the Lyapunov identity).Convenience:
QuasiPeriodicSDEas a documentedProductSDE(MaternSDE, PeriodicSDE).
Next up — issue #38. MarkovGPPrior plus the Kalman filter / RTS smoother. Once that lands, every kernel above can be plugged directly into a NumPyro model with linear-time temporal inference: f = numpyro.sample("f", MarkovGPPrior(QuasiPeriodicSDE(...), times)).
References.
Sarkka, S. & Solin, A. (2019). Applied Stochastic Differential Equations. Cambridge University Press, Ch. 12.
Hartikainen, J. & Sarkka, S. (2010). Kalman Filtering and Smoothing Solutions to Temporal Gaussian Process Regression Models. IEEE MLSP.
Solin, A. & Sarkka, S. (2014). Explicit Link Between Periodic Covariance Functions and State Space Models. AISTATS.
Wilkinson, W. J., Sarkka, S. & Solin, A. (2023). Bayes-Newton Methods for Approximate Bayesian Inference with PSD Guarantees. JMLR 24(83).
Hasselmann, K. (1976). Stochastic climate models. Part I. Theory. Tellus 28(6), 473–485.
Frankignoul, C. & Hasselmann, K. (1977). Stochastic climate models. Part II. Application to sea-surface temperature anomalies and thermocline variability. Tellus 29(4), 289–305.
Stein, M. L. (1999). Interpolation of Spatial Data: Some Theory for Kriging. Springer.
Rasmussen, C. E. & Williams, C. K. I. (2006). Gaussian Processes for Machine Learning. MIT Press, §5.4.3.
Pawlowicz, R., Beardsley, B. & Lentz, S. (2002). Classical tidal harmonic analysis including error estimates in MATLAB using T_TIDE. Computers & Geosciences 28(8), 929–937.
Madden, R. A. & Julian, P. R. (1971). Detection of a 40–50 day oscillation in the zonal wind in the tropical Pacific. Journal of the Atmospheric Sciences 28, 702–708.
Foreman-Mackey, D., Agol, E., Ambikasaran, S. & Angus, R. (2017). Fast and scalable Gaussian process modeling with applications to astronomical time series. The Astronomical Journal 154, 220.
Särkkä, S., Solin, A. & Hartikainen, J. (2013). Spatiotemporal learning via infinite-dimensional Bayesian filtering and smoothing. IEEE Signal Processing Magazine 30(4), 51–61.
Hamelijnck, O., Wilkinson, W. J., Loppi, N., Solin, A. & Damoulas, T. (2021). Spatio-temporal variational Gaussian processes. NeurIPS 34.
Lindgren, F., Rue, H. & Lindström, J. (2011). An explicit link between Gaussian fields and Gaussian Markov random fields: the stochastic partial differential equation approach. JRSS B 73(4), 423–498.
Schlax, M. G. & Chelton, D. B. (1994). Aliased tidal errors in TOPEX/POSEIDON sea surface height data. Journal of Geophysical Research 99(C12). doi:10.1029/94JC01925.
Gneiting, T. (2002). Nonseparable, stationary covariance functions for space–time data. JASA 97(458), 590–600.
Kolmogorov, A. N. (1941). The local structure of turbulence in incompressible viscous fluid for very large Reynolds numbers. Doklady Akademii Nauk SSSR 30, 301–305.
Zhang, H. (2004). Inconsistent estimation and asymptotically equal interpolations in model-based geostatistics. JASA 99(465), 250–261.