MarkovGPPrior gives linear-time inference for a GP over one axis, rather than , through the Kalman filter and RTS smoother. That recursion needs a Gaussian likelihood. Many geoscience variables are not Gaussian: a day is wet or dry, a satellite counts plume detections, a sensor series has spikes. pyrox_ssm ships four strategies that keep the linear-time recursion for such likelihoods by replacing each non-Gaussian likelihood term with a Gaussian site.
This notebook explains how the four strategies differ, fits all four to three likelihoods (Bernoulli, Poisson and Student-t), compares their fits, convergence and cost, and ends with guidance on which strategy suits which kind of geoscience variable.
Setup¶
Detect Colab and install pyrox-gp[colab] (which pulls in matplotlib and watermark) and pyrox-ssm only when running there. The likelihoods come from pyrox_gp; the Markov prior and the strategies come from pyrox_ssm.
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 time
import warnings
warnings.filterwarnings("ignore", message=r".*IProgress.*")
import jax
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
from pyrox_gp import BernoulliLikelihood, PoissonLikelihood, StudentTLikelihood
from pyrox_ssm import (
ExpectationPropagationMarkov,
GaussNewtonMarkovInference,
LaplaceMarkovInference,
MarkovGPPrior,
MaternSDE,
PosteriorLinearizationMarkov,
)
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.3.0
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. One loop, four ways to refresh a site¶
Every strategy approximates the likelihood term of observation by a Gaussian site in the latent ,
so that the sites look like Gaussian pseudo-observations with noise variance . One iteration then has two steps:
run the Kalman filter and RTS smoother on the pseudo-observations, which gives the marginal posteriors in ;
refresh every site from the likelihood and the current posterior.
The strategies differ only in step 2. Write and for the first and second derivatives of in , and for the cavity, the posterior marginal with site divided out.
| Strategy | Site refresh | Literature |
|---|---|---|
LaplaceMarkovInference | Newton step at the current mean: , , with floor | Nickisch, Solin & Grigorievskiy (2018); Rue, Martino & Chopin (2009) |
GaussNewtonMarkovInference | the same Newton step with a strict floor , so every site keeps a usable precision | Wilkinson, Särkkä & Solin (2023) |
PosteriorLinearizationMarkov | the Newton step with and averaged over the cavity, and , by 20-point Gauss–Hermite quadrature | García-Fernández et al. (2015); Wilkinson, Särkkä & Solin (2023) |
ExpectationPropagationMarkov | match the mean and variance of the tilted distribution , then divide out the cavity | Minka (2001); Wilkinson et al. (2020) |
Laplace and Gauss–Newton look at the likelihood at one point, the current mean; posterior linearisation and EP look at it across the cavity’s spread, which costs a quadrature per site but sees curvature that a point evaluation misses. In pyrox, GaussNewtonMarkovInference is exactly LaplaceMarkovInference with the larger floor; the Gauss–Newton methods of Wilkinson, Särkkä & Solin (2023) reach the same goal, a positive site precision, by approximating the Hessian instead. Posterior linearisation and EP start damped (damping=0.5); Laplace and Gauss–Newton take full steps (damping=1.0) unless told otherwise.
2. Three likelihoods, three geoscience stand-ins¶
All three data sets share one irregular grid of times on and a known latent , so every fit can be scored against the truth.
Bernoulli, logit link: occurrence data, such as whether a day is wet or dry at a rain gauge. with .
Poisson, log link: event counts, such as lightning flashes or fire detections per interval. with .
Student-t: a smooth signal measured by a sensor that sometimes spikes, such as a retrieval contaminated by cloud. with 8 of the 80 values shifted by to , fitted with a Student-t likelihood (, scale 0.1).
N = 80
times = jnp.sort(
jnp.linspace(0.0, 5.0, N) + 0.04 * jax.random.normal(jax.random.PRNGKey(1), (N,))
)
f_bern = 1.5 * jnp.sin(2.0 * times) + 0.3 * jnp.cos(7.0 * times)
y_bern = (
jax.random.uniform(jax.random.PRNGKey(7), (N,)) < jax.nn.sigmoid(f_bern)
).astype(jnp.float64)
f_pois = 1.0 + 1.2 * jnp.sin(1.5 * times)
y_pois = jax.random.poisson(jax.random.PRNGKey(3), jnp.exp(f_pois)).astype(jnp.float64)
f_st = jnp.sin(2.0 * times)
outliers = jax.random.choice(jax.random.PRNGKey(6), N, (8,), replace=False)
shifts = jnp.array([3.0, -3.0, 2.5, -2.5, 4.0, -4.0, 3.5, -3.5])
y_st = (
(f_st + 0.1 * jax.random.normal(jax.random.PRNGKey(5), (N,)))
.at[outliers]
.add(shifts)
)
cases = {
"Bernoulli": {
"likelihood": BernoulliLikelihood(),
"y": y_bern,
"f": f_bern,
"sde": MaternSDE(variance=1.0, lengthscale=0.4, order=1),
},
"Poisson": {
"likelihood": PoissonLikelihood(),
"y": y_pois,
"f": f_pois,
"sde": MaternSDE(variance=1.0, lengthscale=0.8, order=1),
},
"Student-t": {
"likelihood": StudentTLikelihood(df=3.0, scale=0.1),
"y": y_st,
"f": f_st,
"sde": MaternSDE(variance=1.0, lengthscale=0.5, order=1),
},
}
fig, axes = plt.subplots(1, 3, figsize=(14, 3.4))
axes[0].plot(times, jax.nn.sigmoid(f_bern), "k--", lw=1.2, label=r"true $\sigma(f)$")
axes[0].scatter(
times, y_bern, c=y_bern, cmap="coolwarm", s=14, label="wet (1) / dry (0)"
)
axes[0].set_title("Bernoulli: occurrence")
axes[1].plot(times, jnp.exp(f_pois), "k--", lw=1.2, label=r"true rate $e^{f}$")
axes[1].scatter(times, y_pois, s=14, color="C1", label="counts")
axes[1].set_title("Poisson: counts")
is_out = jnp.zeros(N, dtype=bool).at[outliers].set(True)
axes[2].plot(times, f_st, "k--", lw=1.2, label="true signal")
axes[2].scatter(times[~is_out], y_st[~is_out], s=14, color="C2", label="readings")
axes[2].scatter(
times[is_out], y_st[is_out], s=30, marker="x", color="C3", label="spikes"
)
axes[2].set_title("Student-t: readings with spikes")
for ax in axes:
ax.set_xlabel("t")
ax.grid(alpha=0.25)
ax.legend(fontsize=8, loc="lower left")
fig.tight_layout()
plt.show()
3. Fit all four strategies¶
The helper below fits each strategy and records whether it converged, how many filter-smoother iterations it used, its wall time, the RMSE of its posterior mean against the true latent, and its largest gap from the EP posterior mean. Each fit runs its iterations inside one optimistix fixed-point solve, and its wall time includes compiling that solve; read it as relative cost on this machine, not as a benchmark. Every fit also reports log_marginal_approx, but its meaning is strategy-specific, so the tables leave it out.
def default_strategies(max_iter: int = 50) -> dict:
"""The four strategies with their default damping and floors."""
return {
"Laplace": LaplaceMarkovInference(max_iter=max_iter, tol=1e-6),
"Gauss-Newton": GaussNewtonMarkovInference(max_iter=max_iter, tol=1e-6),
"Post. lin.": PosteriorLinearizationMarkov(max_iter=max_iter, tol=1e-6),
"EP": ExpectationPropagationMarkov(max_iter=max_iter, tol=1e-6),
}
def fit_all(case: dict, strategies: dict) -> dict:
"""Fit every strategy to one case; return the fits and a summary per strategy."""
prior = MarkovGPPrior(case["sde"], times)
results = {}
for name, strategy in strategies.items():
t0 = time.perf_counter()
cond = strategy.fit(prior, case["likelihood"], case["y"])
seconds = time.perf_counter() - t0
rmse = float(jnp.sqrt(jnp.mean((cond.q_mean - case["f"]) ** 2)))
results[name] = {"cond": cond, "seconds": seconds, "rmse": rmse}
if "EP" in results:
ep_mean = results["EP"]["cond"].q_mean
for res in results.values():
res["gap_ep"] = float(jnp.max(jnp.abs(res["cond"].q_mean - ep_mean)))
return results
def show(results: dict) -> None:
"""Print one row per strategy."""
print(
f"{'strategy':<16}{'converged':>10}{'iters':>7}{'seconds':>9}{'RMSE':>8}"
f"{'max |m - m_EP|':>16}"
)
for name, res in results.items():
cond = res["cond"]
gap = res.get("gap_ep", float("nan"))
print(
f"{name:<16}{cond.converged!s:>10}{cond.n_iter:>7}{res['seconds']:>9.1f}"
f"{res['rmse']:>8.3f}{gap:>16.4f}"
)
t_star = jnp.linspace(-0.3, 6.5, 300)
colors = {"Laplace": "C0", "Gauss-Newton": "C1", "Post. lin.": "C2", "EP": "C3"}
styles = {"Laplace": "-", "Gauss-Newton": ":", "Post. lin.": "-", "EP": "--"}3.1 Bernoulli: occurrence¶
bern = fit_all(cases["Bernoulli"], default_strategies())
show(bern)
fig, axes = plt.subplots(1, 2, figsize=(13, 3.8))
for name, res in bern.items():
m, v = (np.asarray(a) for a in res["cond"].predict(t_star))
axes[1].plot(
t_star, jax.nn.sigmoid(m), color=colors[name], ls=styles[name], lw=2, label=name
)
if name in ("Laplace", "EP"):
sd = np.sqrt(np.maximum(v, 0.0))
axes[0].fill_between(
t_star, m - 2 * sd, m + 2 * sd, color=colors[name], alpha=0.15
)
axes[0].plot(
t_star,
m,
color=colors[name],
ls=styles[name],
lw=2,
label=f"{name} mean ±2σ",
)
axes[0].plot(times, f_bern, "k--", lw=1, label="true f")
axes[0].set_ylabel("latent f")
axes[0].set_title("Latent posterior: Laplace vs EP")
axes[1].plot(times, jax.nn.sigmoid(f_bern), "k--", lw=1, label=r"true $\sigma(f)$")
axes[1].scatter(times, y_bern, c=y_bern, cmap="coolwarm", s=10, alpha=0.6)
axes[1].set_ylabel("P(wet)")
axes[1].set_ylim(-0.05, 1.05)
axes[1].set_title("Predictive probability, all four strategies")
for ax in axes:
ax.axvline(times[-1], color="grey", ls=":", lw=0.8)
ax.set_xlabel("t")
ax.grid(alpha=0.25)
ax.legend(fontsize=8, loc="lower left")
fig.tight_layout()
plt.show()strategy converged iters seconds RMSE max |m - m_EP|
Laplace True 5 7.1 0.627 0.0603
Gauss-Newton True 5 1.8 0.627 0.0603
Post. lin. True 24 3.2 0.612 0.0013
EP True 24 2.7 0.612 0.0000

The Bernoulli likelihood is log-concave ( everywhere), so all four strategies converge. Laplace and Gauss–Newton give identical fits: the Bernoulli curvature stays far above both floors here, so the floors never act. Posterior linearisation and EP agree with each other closely, and both differ from Laplace by a few hundredths in the mean: Laplace centres each site on the mode of the likelihood at one point, while the other two average over the cavity. This is the pattern Kuss & Rasmussen (2005) report for GP classification, where EP’s posterior is closer to the MCMC reference than Laplace’s. Laplace pays for its bias with speed: it needs the fewest iterations and no quadrature. Past the dotted line (the last observation) every posterior relaxes to the prior mean of zero and the prior variance, because no observation constrains there.
3.2 Poisson: counts¶
pois = fit_all(cases["Poisson"], default_strategies())
show(pois)
fig, ax = plt.subplots(figsize=(13, 3.6))
for name, res in pois.items():
m, v = (np.asarray(a) for a in res["cond"].predict(t_star))
ax.plot(t_star, np.exp(m), color=colors[name], ls=styles[name], lw=2, label=name)
if name == "EP":
sd = np.sqrt(np.maximum(v, 0.0))
ax.fill_between(
t_star,
np.exp(m - 2 * sd),
np.exp(m + 2 * sd),
color=colors[name],
alpha=0.15,
label="EP ±2σ in f",
)
ax.plot(times, jnp.exp(f_pois), "k--", lw=1, label=r"true rate $e^{f}$")
ax.scatter(times, y_pois, s=12, color="0.4", alpha=0.7, label="counts")
ax.axvline(times[-1], color="grey", ls=":", lw=0.8)
ax.set_xlabel("t")
ax.set_ylabel("rate")
ax.set_title(r"Poisson: posterior rate $e^{m(t)}$")
ax.grid(alpha=0.25)
ax.legend(fontsize=8, loc="upper right", ncol=3)
fig.tight_layout()
plt.show()strategy converged iters seconds RMSE max |m - m_EP|
Laplace True 10 2.3 0.179 0.0607
Gauss-Newton True 10 1.9 0.179 0.0607
Post. lin. True 34 1.7 0.203 0.0263
EP True 29 1.5 0.203 0.0000

The Poisson likelihood with a log link is also log-concave (), and the picture repeats: everything converges, Laplace and Gauss–Newton coincide, and posterior linearisation and EP sit together a few hundredths away from them. With counts this large the likelihood is close to Gaussian in , so the choice of strategy matters little; it matters more for sparse counts, where many zeros make the likelihood strongly skewed.
3.3 Student-t: readings with spikes¶
st = fit_all(cases["Student-t"], default_strategies())
show(st)
def plot_student_t(results: dict, title: str) -> None:
"""Posterior means of every strategy against the spiky readings."""
fig, ax = plt.subplots(figsize=(13, 3.8))
for name, res in results.items():
m, _ = (np.asarray(a) for a in res["cond"].predict(t_star))
ax.plot(
t_star,
m,
color=colors.get(name.split(",")[0], "C4"),
ls=styles.get(name.split(",")[0], "-"),
lw=2,
label=name,
)
ax.plot(times, f_st, "k--", lw=1, label="true signal")
ax.scatter(times[~is_out], y_st[~is_out], s=12, color="0.4", alpha=0.7)
ax.scatter(times[is_out], y_st[is_out], s=30, marker="x", color="C3")
ax.set_ylim(-5, 5)
ax.set_xlabel("t")
ax.set_title(title)
ax.grid(alpha=0.25)
ax.legend(fontsize=8, loc="lower left", ncol=3)
fig.tight_layout()
plt.show()
plot_student_t(st, "Student-t with default settings: posterior means (clipped to ±5)")strategy converged iters seconds RMSE max |m - m_EP|
Laplace True 21 3.1 0.072 0.0208
Gauss-Newton True 23 1.9 0.072 0.0208
Post. lin. False 50 2.3 0.071 0.1671
EP False 50 1.6 0.070 0.0000

Here the strategies part ways. The Student-t log-likelihood is not log-concave: for a reading far from the current mean, . Laplace and Gauss–Newton then floor the site precision to , so the site contributes its full gradient to with almost no curvature to balance it. On these readings they still converge with full steps, in 21 and 23 iterations, and their means track the true signal through the spikes. Posterior linearisation and EP average the curvature over the cavity and reach the same RMSE, but neither meets the tolerance within 50 iterations, and at that point their means still differ by up to 0.17.
The cell below gives posterior linearisation and EP 100 iterations.
remedies = {
"Post. lin., 100 iterations": PosteriorLinearizationMarkov(max_iter=100, tol=1e-6),
"EP, 100 iterations": ExpectationPropagationMarkov(max_iter=100, tol=1e-6),
}
st_fixed = fit_all(cases["Student-t"], remedies)
show(st_fixed)
plot_student_t(st_fixed, "Student-t after the remedies: posterior means")strategy converged iters seconds RMSE max |m - m_EP|
Post. lin., 100 iterations True 94 1.5 0.071 nan
EP, 100 iterations True 62 1.9 0.070 nan

With more iterations both converge, posterior linearisation in 94 and EP in 62, at the same RMSE as before. Robust regression with a Student-t likelihood is a known hard case for every approximation: Jylänki, Vanhatalo & Vehtari (2011) show that EP itself can fail to converge on it and needs damping or a double-loop scheme, which is why pyrox’s EP starts damped. If a Newton strategy oscillates on such data instead, lower its damping.
4. Convergence and cost¶
Every strategy costs one filter-smoother pass per iteration, for iterations. Posterior linearisation and EP add a 20-node Gauss–Hermite quadrature per site, which is and small next to the smoother for this . Iterations therefore drive the cost, and the iteration count depends on the likelihood and on the damping far more than on the strategy’s per-step work. At 80 points the wall time is dominated by compilation, so it does not follow the iteration counts.
summary = {
"Bernoulli": bern,
"Poisson": pois,
"Student-t": st,
"Student-t, remedies": st_fixed,
}
fig, axes = plt.subplots(1, 2, figsize=(13, 3.8))
offset = 0
labels, positions = [], []
for case_name, results in summary.items():
for k, (name, res) in enumerate(results.items()):
x = offset + k
base = name.split(",")[0]
hatch = "" if res["cond"].converged else "//"
for ax, value in zip(axes, (res["cond"].n_iter, res["seconds"]), strict=True):
ax.bar(
x,
value,
color=colors.get(base, "C4"),
hatch=hatch,
edgecolor="k",
lw=0.4,
)
positions.append(offset + (len(results) - 1) / 2)
labels.append(case_name)
offset += len(results) + 1
for ax, ylabel in zip(
axes, ("filter-smoother iterations", "wall time (s)"), strict=True
):
ax.set_xticks(positions, labels)
ax.set_ylabel(ylabel)
ax.grid(alpha=0.25, axis="y")
handles = [plt.Rectangle((0, 0), 1, 1, color=c) for c in colors.values()]
handles.append(
plt.Rectangle((0, 0), 1, 1, facecolor="white", edgecolor="k", hatch="//")
)
axes[0].legend(
handles, [*colors.keys(), "did not converge"], fontsize=8, loc="upper left"
)
axes[0].set_title("Iterations per fit")
axes[1].set_title("Wall time per fit (including compilation)")
fig.tight_layout()
plt.show()
On the log-concave cases Laplace and Gauss–Newton converge in the fewest iterations, because a full Newton step is the right step when the curvature is trustworthy; the damped posterior linearisation and EP take three to five times as many. On the Student-t case the undamped Newton strategies again converge first, in about 20 iterations, while posterior linearisation and EP need more than the default 50. Wall time stays between 1.5 and 7.1 s per fit and does not follow the iteration counts, because compilation dominates at this size.
5. Which strategy for which geoscience variable¶
The deciding property is whether the log-likelihood is concave in . If it is, every strategy converges and the choice trades speed (Laplace) against accuracy of the posterior moments (posterior linearisation, EP). If it is not, no strategy is guaranteed to converge, so check converged and be ready to raise max_iter or lower damping.
| Variable | Likelihood | Log-concave in ? | Suggested strategy | Literature |
|---|---|---|---|---|
| Precipitation occurrence (wet or dry day) | Bernoulli, logit link | yes | Laplace for speed; EP or posterior linearisation when the probabilities themselves matter | Stern & Coe (1984); Kuss & Rasmussen (2005) |
| Event counts: lightning flashes, fire detections, plume detections per overpass | Poisson, log link (a log-Gaussian Cox process in time) | yes | Laplace, as in INLA; EP for sparse counts with many zeros | Møller, Syversveen & Waagepetersen (1998); Rue, Martino & Chopin (2009) |
| Sensor or retrieval series with spikes (cloud contamination, instrument glitches) | Student-t | no | Laplace converged fastest here; EP with more iterations; check converged either way | Jylänki, Vanhatalo & Vehtari (2011) |
| Any of the above with gaps (cloudy days, outages) | any, with mask= | — | any; a masked site holds zero naturals and the filter skips it | — |
Where these strategies do well.
Long records: each iteration is linear in , so a decade of daily occurrence data or hourly counts is routine.
Gaps: every strategy’s
fittakesmask=, so missing days need no imputation, and a masked fit equals the fit with those days removed.Forecasts:
predictextends past the last observation and relaxes to the prior, which is the honest answer for a stationary kernel.
What to look out for.
Non-log-concave likelihoods. The Student-t case has sites with positive curvature, and no strategy is guaranteed to converge on it; here posterior linearisation and EP needed more than 50 iterations. Check
converged, raisemax_iter, and lowerdampingif a strategy oscillates.Laplace bias for binary data. Laplace’s posterior mean is shrunk relative to EP’s (Kuss & Rasmussen, 2005). If you threshold predicted probabilities, for example to forecast wet days, the difference shows up in calibration.
Gauss–Newton is a floor in pyrox, not a different Hessian. On log-concave likelihoods it is identical to Laplace; its floor only changes sites whose curvature falls below 10-3.
log_marginal_approxis not comparable across strategies. Each strategy reports its own quantity, so do not use it to choose between them; compare predictions instead.The latent must be scalar per time. All four strategies take a scalar-latent likelihood, one per observation.
Summary¶
All four strategies run the same filter-smoother loop and differ only in how they refresh each Gaussian site: at one point (Laplace, Gauss–Newton) or averaged over the cavity (posterior linearisation, EP).
On log-concave likelihoods (Bernoulli, Poisson) all four converge; Laplace and Gauss–Newton need the fewest iterations, and posterior linearisation and EP agree closely with each other.
On the non-log-concave Student-t likelihood, undamped Laplace and Gauss–Newton converge in about 20 iterations, while posterior linearisation and EP need more than the default 50; all four track the signal through the spikes.
References.
García-Fernández, Á. F., Svensson, L., Morelande, M. R. & Särkkä, S. (2015). Posterior linearization filter: principles and implementation using sigma points. IEEE Transactions on Signal Processing 63(20), 5561–5573.
Jylänki, P., Vanhatalo, J. & Vehtari, A. (2011). Robust Gaussian process regression with a Student-t likelihood. JMLR 12, 3227–3257.
Kuss, M. & Rasmussen, C. E. (2005). Assessing approximate inference for binary Gaussian process classification. JMLR 6, 1679–1704.
Minka, T. P. (2001). Expectation propagation for approximate Bayesian inference. UAI.
Møller, J., Syversveen, A. R. & Waagepetersen, R. P. (1998). Log Gaussian Cox processes. Scandinavian Journal of Statistics 25(3), 451–482.
Nickisch, H., Solin, A. & Grigorievskiy, A. (2018). State space Gaussian processes with non-Gaussian likelihood. ICML, PMLR 80, 3789–3798.
Rue, H., Martino, S. & Chopin, N. (2009). Approximate Bayesian inference for latent Gaussian models by using integrated nested Laplace approximations. JRSS B 71(2), 319–392.
Stern, R. D. & Coe, R. (1984). A model fitting analysis of daily rainfall data. JRSS A 147(1), 1–34.
Wilkinson, W. J., Chang, P. E., Andersen, M. R. & Solin, A. (2020). State space expectation propagation: efficient inference schemes for temporal Gaussian processes. ICML, PMLR 119, 10270–10281.
Wilkinson, W. J., Särkkä, S. & Solin, A. (2023). Bayes-Newton methods for approximate Bayesian inference with PSD guarantees. JMLR 24(83).