SSM API¶
pyrox-ssm is the package whose inference recurses in time: pyrox-gp solves over all N points at once, pyrox-lgm solves one sparse precision, and pyrox_ssm runs a filter and smoother over the time axis. It holds the Markov-GP track (moved from pyrox-gp; the old pyrox_gp names raise an ImportError naming their new home) and re-exports gaussx's SDE kernels. Its likelihoods are any pyrox.likelihoods.Likelihood (the pyrox-gp ones work unchanged) and its sparse guides any pyrox.likelihoods.Guide with predict and kl_divergence.
State-space (SDE) kernels¶
Stationary 1-D kernels expressed as linear time-invariant SDEs. Once in
state-space form, GP inference on a 1-D grid reduces to Kalman filtering
in O(N d^3) instead of O(N^3) Cholesky. The protocol exposes
sde_params() -> (F, L, H, Q_c, P_inf) and discretise(dt) -> (A_k, Q_k)
for downstream Kalman / RTS use.
import jax.numpy as jnp
from pyrox_ssm import (
ConstantSDE, CosineSDE, MaternSDE, PeriodicSDE,
ProductSDE, QuasiPeriodicSDE, SumSDE,
)
# Primitive kernels
matern = MaternSDE(variance=1.0, lengthscale=0.5, order=1) # nu = 3/2
cos = CosineSDE(variance=1.0, frequency=2.0)
const = ConstantSDE(variance=0.3)
per = PeriodicSDE(variance=1.0, lengthscale=1.0, period=2.0, n_harmonics=7)
# Composition: trend + offset
trend = SumSDE((matern, const)) # state dim = 2 + 1 = 3
# Composition: damped oscillation (Matern x Cosine)
damped = ProductSDE(matern, cos) # state dim = 2 * 2 = 4
# Quasi-periodic (Matern x Periodic) — convenience wrapper around ProductSDE
qp = QuasiPeriodicSDE(matern, per) # state dim = 2 * 15 = 30
Non-stationary priors¶
Every kernel above is stationary: the process is started in its
stationary distribution, so the filter seeds from P_inf and
sde_autocovariance reports K(tau).
IntegratedWienerSDE is not. At
order=1 it is the local linear trend — smooth, and linear unless the
data push back, with no lengthscale to choose — and its marginal
variance grows without bound, so there is no P_inf at all. It reports
stationary = False and sde_params().P_inf = None, and the filter
starts from an explicit initial covariance instead:
import jax.numpy as jnp
from pyrox_ssm import IntegratedWienerSDE, MarkovGPPrior
trend = IntegratedWienerSDE(diffusion=1e-4) # state = [level, slope]
prior = MarkovGPPrior(trend, times) # diffuse default P_0
# ... or state what is known before the first observation:
prior = MarkovGPPrior(trend, times, init_cov=jnp.diag(jnp.array([1e2, 1.0])))
Filtering, smoothing, prediction and the site-based non-Gaussian
strategies all work; the dense paths (log_prob
and markov_gp_sample) raise, because
K_ij = H exp(F |t_i - t_j|) P_inf H^T is a function of the lag alone,
while a non-stationary covariance depends on both times.
A SumSDE may mix the two — a trend plus a stationary seasonal — and
starts from the block-diagonal of its components' initial covariances.
SDEKernel
¶
Bases: Module
Abstract state-space form of a kernel k(τ): a linear SDE.
k(τ) = H exp(F_c τ) Σ_x,∞ Hᵀ, τ ≥ 0
Subclasses implement sde_params, which returns (F_c, L_c, H, Q_c,
Σ_x,∞). The default discretise takes the matrix exponential of the
drift; subclasses may override it with a closed form.
Examples:
Every kernel in the zoo is an SDEKernel:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(0.5), order=2
... )
>>> isinstance(kernel, gaussx.SDEKernel), kernel.state_dim
(True, 3)
Discretise over a stack of steps Δt_1:T:
>>> transitions, noises = kernel.discretise_sequence(jnp.array([0.1, 0.2]))
>>> transitions.shape, noises.shape
((2, 3, 3), (2, 3, 3))
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 | |
state_dim: int
abstractmethod
property
¶
State length D_x.
stationary: bool
property
¶
Whether the process has a stationary distribution.
True for every kernel in the zoo, which is why that is the
default; a non-stationary kernel such as
gaussx.IntegratedWienerSDE overrides it. Consumers should
branch on this rather than on sde_params().P_inf is None:
the two are different questions, since a stationary kernel may
report P_inf=None when it has no closed form for Σ_x,∞ (a
learned drift, say).
sde_params() -> SDEParams
abstractmethod
¶
Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) of the SDE.
Returns:
| Type | Description |
|---|---|
SDEParams
|
The |
initial_covariance() -> Float[Array, 'd d']
¶
Covariance Σ_x,0 of the state at the first time point.
Σ_x,0 = Σ_x,∞
A stationary kernel is assumed started in its stationary distribution, so the default returns Σ_x,∞ and existing kernels need no change. A non-stationary kernel has no such limit to start from and must override this with an explicit choice.
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Initial state covariance Σ_x,0. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Discretise the SDE over one step Δt.
F_t = exp(F_c Δt)
Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ
When sde_params() returns P_inf=None (a kernel with no
closed-form stationary covariance, such as one whose drift is a
learned parameter) this falls back to gaussx.discretize_mfd,
which recovers both F_t and Σ_η,t from one matrix exponential and
is well defined for every F_c. The fallback is chosen at trace
time from a static None check, so kernels that do supply
Σ_x,∞ keep the stationary route and its precision exactly.
Subclasses may override with closed-form expressions.
Algorithm
- Without Σ_x,∞, form B_c = L_c Q_c L_cᵀ and return
gaussx.discretize_mfd(F_c, B_c, Δt). - Otherwise exponentiate the drift, F_t = exp(F_c Δt).
- Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ and symmetrise it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt ≥ 0. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
discretise_sequence(dt: Float[Array, ' N']) -> tuple[Float[Array, 'N d d'], Float[Array, 'N d d']]
¶
Discretise the SDE over a stack of steps Δt_1:T, one per step.
F_t = exp(F_c Δt_t), Σ_η,t, t = 1, …, T
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, ' N']
|
Time steps Δt_1:T. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'N d d'], Float[Array, 'N d d']]
|
Tuple |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
SDEParams
¶
Bases: NamedTuple
Continuous-time matrices (F_c, L_c, H, Q_c, Σ_x,∞) of a linear SDE.
dx(t) = F_c x(t) dt + L_c db(t), db(t) ~ 𝒩(0, Q_c dt),
f(t) = H x(t),
F_c Σ_x,∞ + Σ_x,∞ F_cᵀ + L_c Q_c L_cᵀ = 0
Attributes:
| Name | Type | Description |
|---|---|---|
F |
Float[Array, 'd d']
|
Drift matrix F_c. |
L |
Float[Array, 'd s']
|
Diffusion (noise-effect) matrix L_c. |
H |
Float[Array, '1 d']
|
Measurement row H. |
Q_c |
Float[Array, 's s']
|
White-noise spectral density Q_c. |
P_inf |
Float[Array, 'd d'] | None
|
Stationary covariance Σ_x,∞, or |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(1.0), order=1
... )
>>> params = kernel.sde_params()
>>> params.F.shape, params.L.shape, params.H.shape, params.Q_c.shape
((2, 2), (2, 1), (1, 2), (1, 1))
The stationary covariance solves the Lyapunov equation:
>>> lyapunov = (
... params.F @ params.P_inf
... + params.P_inf @ params.F.T
... + params.L @ params.Q_c @ params.L.T
... )
>>> bool(jnp.allclose(lyapunov, 0.0, atol=1e-4))
True
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
MaternSDE
¶
Bases: SDEKernel
State-space form of the Matérn kernel of order p, smoothness p + ½.
k_Matérn-1/2(τ) = σ_k² exp(−λ|τ|), λ = 1/ℓ
k_Matérn-3/2(τ) = σ_k² (1 + λ|τ|) exp(−λ|τ|), λ = √3/ℓ
k_Matérn-5/2(τ) = σ_k² (1 + λ|τ| + λ²τ²/3) exp(−λ|τ|), λ = √5/ℓ
The state x(t) = [f(t), f^(1)(t), …, f^(p)(t)] stacks f and its first p derivatives, so D_x = p + 1. The drift F_c is a companion matrix whose p + 1 eigenvalues all equal −λ, the noise enters the top derivative and Q_c = σ_k² (2λ)^(2p+1) (p!)² / (2p)!.
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
Float[Array, '']
|
Kernel variance σ_k². |
lengthscale |
Float[Array, '']
|
Lengthscale ℓ. |
order |
int
|
Order p ∈ {0, 1, 2}, for Matérn-1/2, -3/2 and -5/2. |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.MaternSDE(
... variance=jnp.asarray(2.0), lengthscale=jnp.asarray(0.5), order=1
... )
>>> kernel.state_dim, kernel.sde_params().F.shape
(2, (2, 2))
The SDE reproduces the kernel, here at τ = 0 and τ = ℓ:
>>> lags = jnp.array([0.0, 0.5])
>>> rate = jnp.sqrt(3.0) / 0.5
>>> expected = 2.0 * (1.0 + rate * lags) * jnp.exp(-rate * lags)
>>> got = gaussx.sde_autocovariance(kernel, lags)
>>> bool(jnp.allclose(got, expected, atol=1e-5))
True
Only orders 0, 1 and 2 have a state-space form here:
>>> gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(1.0), order=3
... ).sde_params()
Traceback (most recent call last):
...
ValueError: Unsupported Matern order 3; must be 0, 1, or 2
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_matern.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 | |
state_dim: int
property
¶
State length D_x = p + 1.
sde_params() -> SDEParams
¶
Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) for order p.
Returns:
| Type | Description |
|---|---|
SDEParams
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_matern.py
ConstantSDE
¶
Bases: SDEKernel
State-space form of the constant kernel k(τ) = σ_k².
A degenerate SDE with one state, no drift and no diffusion: the state keeps the value it starts with, drawn from the stationary variance σ_k². Discretised over any step, the transition is 1 and the model error 0.
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
Float[Array, '']
|
Kernel variance σ_k². |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.ConstantSDE(variance=jnp.asarray(2.0))
>>> kernel.state_dim, kernel.sde_params().P_inf.shape
(1, (1, 1))
>>> bool(jnp.allclose(kernel.sde_params().P_inf, 2.0))
True
Any step leaves the state unchanged:
>>> transition, process_noise = kernel.discretise(jnp.asarray(0.5))
>>> bool(jnp.allclose(transition, 1.0)), bool(jnp.allclose(process_noise, 0.0))
(True, True)
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_constant.py
state_dim: int
property
¶
State length D_x = 1.
sde_params() -> SDEParams
¶
Continuous-time parameters: zero drift and diffusion, variance σ_k².
Returns:
| Type | Description |
|---|---|
SDEParams
|
|
SDEParams
|
the stationary covariance |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_constant.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Closed-form discretisation: transition 1 and model error 0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt; unused, since nothing changes over time. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
covariance Σ_η. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_constant.py
CosineSDE
¶
Bases: SDEKernel
State-space form of the cosine kernel k(τ) = σ_k² cos(ω₀ τ).
F_c = [[0, −ω₀], [ω₀, 0]], L_c = 0, H = [1, 0], Q_c = 0,
Σ_x,∞ = σ_k² I₂
A two-state rotation SDE, D_x = 2.
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
Float[Array, '']
|
Kernel variance σ_k². |
frequency |
Float[Array, '']
|
Angular frequency ω₀. |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.CosineSDE(
... variance=jnp.asarray(2.0), frequency=jnp.asarray(3.0)
... )
>>> lags = jnp.array([0.0, 0.4])
>>> got = gaussx.sde_autocovariance(kernel, lags)
>>> bool(jnp.allclose(got, 2.0 * jnp.cos(3.0 * lags), atol=1e-5))
True
A step rotates the state and adds no noise:
>>> transition, noise = kernel.discretise(jnp.asarray(0.4))
>>> bool(jnp.allclose(transition @ transition.T, jnp.eye(2), atol=1e-6))
True
>>> bool(jnp.all(noise == 0.0))
True
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
state_dim: int
property
¶
State length D_x = 2.
sde_params() -> SDEParams
¶
Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞).
Returns:
| Type | Description |
|---|---|
SDEParams
|
|
SDEParams
|
Q_c = 0 and Σ_x,∞ = σ_k² I₂. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Closed-form discretisation: a rotation by ω₀ Δt and no noise.
F_t = [[cos ω₀Δt, −sin ω₀Δt], [sin ω₀Δt, cos ω₀Δt]], Σ_η,t = 0
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t = 0. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
PeriodicSDE
¶
Bases: SDEKernel
State-space form of the periodic (MacKay) kernel, as J + 1 harmonics.
k(τ) = σ_k² exp(−2 sin²(ω₀τ/2) / ℓ²), ω₀ = 2π / T_period
≈ ∑_{j=0}^{J} q_j cos(j ω₀ τ)
q₀ = σ_k² e^{−ℓ⁻²} I₀(ℓ⁻²), q_j = 2σ_k² e^{−ℓ⁻²} I_j(ℓ⁻²), j ≥ 1
with I_j the modified Bessel function of the first kind and J the number of harmonics (Solin & Särkkä, 2014). Each harmonic j = 0, …, J is a two-state rotation block at frequency j ω₀ with stationary covariance q_j I₂; the constant j = 0 block has zero drift. The state length is D_x = 2(J + 1).
Short lengthscales put more of the variance into high harmonics, so they need more terms: use J ≳ 3/ℓ, with ℓ in units of the period. At ℓ = 0.2 the default 6 harmonics carry about 81% of the variance, and 20 carry 99.99%.
Attributes:
| Name | Type | Description |
|---|---|---|
variance |
Float[Array, '']
|
Kernel variance σ_k². |
lengthscale |
Float[Array, '']
|
Lengthscale ℓ. |
period |
Float[Array, '']
|
Period T_period. |
n_harmonics |
int
|
Number of harmonics J (truncation order). |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.PeriodicSDE(
... variance=jnp.asarray(1.5),
... lengthscale=jnp.asarray(1.0),
... period=jnp.asarray(2.0),
... n_harmonics=8,
... )
>>> kernel.state_dim
18
The truncated series matches the kernel:
>>> lags = jnp.array([0.0, 0.3, 1.1])
>>> exact = 1.5 * jnp.exp(-2.0 * jnp.sin(jnp.pi * lags / 2.0) ** 2)
>>> got = gaussx.sde_autocovariance(kernel, lags)
>>> bool(jnp.allclose(got, exact, atol=1e-5))
True
One full period returns every block to its start:
>>> transition, _ = kernel.discretise(jnp.asarray(2.0))
>>> bool(jnp.allclose(transition, jnp.eye(18), atol=1e-5))
True
References
Solin, A. & Särkkä, S. (2014). Explicit link between periodic covariance functions and state space models. AISTATS.
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 | |
state_dim: int
property
¶
State length D_x = 2(J + 1).
sde_params() -> SDEParams
¶
Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞).
F_c = blockdiag_j([[0, −jω₀], [jω₀, 0]]), L_c = 0, Q_c = 0
H = [1, 0, 1, 0, …, 1, 0], Σ_x,∞ = blockdiag_j(q_j I₂)
Returns:
| Type | Description |
|---|---|
SDEParams
|
The |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Closed form: block-diagonal rotations, the identity for j = 0.
F_t = blockdiag_j([[cos jω₀Δt, −sin jω₀Δt],
[sin jω₀Δt, cos jω₀Δt]]), Σ_η,t = 0
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t = 0. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
IntegratedWienerSDE
¶
Bases: SDEKernel
State-space form of the p-times integrated Wiener process.
df^(p)(t) = db(t), db(t) ~ 𝒩(0, Q_c dt)
F_c = [[0, I_p], [0, 0]], L_c = e_p, H = e₀ᵀ
with state x(t) = [f(t), f^(1)(t), …, f^(p)(t)], D_x = p + 1, and e_i the
i-th unit vector. The top derivative is white noise and every lower
component is its integral; at p = 1 this is the local linear trend
prior. F_c is nilpotent, which is what makes the process
non-stationary: its marginal variance grows without bound, so no
Σ_x,∞ exists and sde_params reports P_inf=None. discretise is
overridden with the exact closed form and never needs one, but the
filter has to be started from an explicit initial_covariance Σ_x,0.
That non-stationarity is the point: unlike a Matérn prior, the local linear trend commits to no lengthscale. It is smooth and linear unless the data push back, so a long record may drift without the model asserting a scale on which it must revert.
Attributes:
| Name | Type | Description |
|---|---|---|
diffusion |
Float[Array, '']
|
White-noise spectral density Q_c driving the top derivative. Must be non-negative: Σ_η,t is linear in it, so a negative value returns something that is not a covariance. Like every hyperparameter in the kernel zoo this is assumed rather than checked; constrain it with a positive transform when it is learned. |
order |
int
|
Number of integrations p. |
P_0 |
Float[Array, 'd d'] | None
|
Initial state covariance Σ_x,0. A modelling choice rather
than something the kernel can derive; |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.IntegratedWienerSDE(diffusion=jnp.asarray(2.0))
>>> kernel.state_dim, kernel.stationary, kernel.sde_params().P_inf
(2, False, None)
The local linear trend at Δt = 1: F_t = [[1, 1], [0, 1]] and Σ_η,t = Q_c [[1/3, 1/2], [1/2, 1]]:
>>> transition, noise = kernel.discretise(jnp.asarray(1.0))
>>> bool(jnp.allclose(transition, jnp.array([[1.0, 1.0], [0.0, 1.0]])))
True
>>> bool(jnp.allclose(noise, 2.0 * jnp.array([[1 / 3, 0.5], [0.5, 1.0]])))
True
A negative order is rejected at construction:
>>> gaussx.IntegratedWienerSDE(
... diffusion=jnp.asarray(1.0), order=-1
... )
Traceback (most recent call last):
...
ValueError: IntegratedWienerSDE order must be non-negative
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
state_dim: int
property
¶
State length D_x = p + 1.
stationary: bool
property
¶
False: the marginal variance grows without bound.
sde_params() -> SDEParams
¶
Continuous-time parameters (F_c, L_c, H, Q_c), with no Σ_x,∞.
F_c = [[0, I_p], [0, 0]], L_c = e_p, H = e₀ᵀ
The drift is nilpotent, so no stationary covariance exists; see
initial_covariance for what starts the filter instead.
Returns:
| Type | Description |
|---|---|
SDEParams
|
|
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
initial_covariance() -> Float[Array, 'd d']
¶
Initial state covariance Σ_x,0: the P_0 field, or κ I.
Σ_x,0 = κ I, κ = 1/√ε_mach (when ``P_0`` is ``None``)
The diffuse default sets κ from the dtype's precision through
_default_diffuse_variance; a vaguer prior than that is not merely
wasteful but actively wrong, since the Kalman update cancels it to
a zero-variance first estimate.
Pass a P_0 to encode what is actually known about the level
and its derivatives at the first time point, e.g. diag(κ, s²) for
a vague level and a slope of scale s. Do so in particular when the
observation noise is large: the default is diffuse relative to an
observation-noise variance of order one, not relative to every
scale.
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Initial state covariance Σ_x,0. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Closed-form discretisation, with no matrix exponential and no Σ_x,∞.
[F_t]_ij = Δt^(j−i) / (j−i)!, j ≥ i, else 0
[Σ_η,t]_ij = Q_c Δt^(2p+1−i−j) / ((p−i)! (p−j)! (2p+1−i−j))
with i, j = 0, …, p. The drift is nilpotent, so its exponential
terminates; at p = 1 this is the familiar F_t = [[1, Δt], [0, 1]]
and Σ_η,t = Q_c [[Δt³/3, Δt²/2], [Δt²/2, Δt]]. Both are exact, so
this route is cheaper and more accurate than the
gaussx.discretize_mfd fallback the P_inf=None base
implementation would otherwise take.
Algorithm
- Check Δt ≥ 0 with
equinox.error_if. - Form the 2p + 2 distinct powers Δt⁰, …, Δt^(2p+1) once.
- Build the static coefficient tables 1/(j−i)! and 1/((p−i)! (p−j)! (2p+1−i−j)) on the host.
- Gather the powers by a static index table and scale.
Note
The coefficients carry 1/(p−i)!, which outruns float64 from
roughly order=90 up and underflows to zero there (XLA
flushes the subnormals in between). Nothing is silently wrong,
since the entries are zero rather than garbage, but a prior
that integrates white noise ninety times is not a numerically
meaningful object in any dtype.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt. Must be non-negative: a negative step would
return a Σ_η,t that is not a covariance (at p = 1 it is
negative definite), rather than the harmless reverse-time
transition the sign might suggest. Checked with
|
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 | |
SumSDE
¶
Bases: SDEKernel
Sum of independent SDE kernels, stacked block-diagonally.
k(τ) = ∑_i k^(i)(τ)
F_c = blockdiag_i(F_c^(i)), L_c = blockdiag_i(L_c^(i)),
Q_c = blockdiag_i(Q_c^(i)), Σ_x,∞ = blockdiag_i(Σ_x,∞^(i)),
H = [H^(1), …, H^(n)]
Attributes:
| Name | Type | Description |
|---|---|---|
kernels |
tuple[SDEKernel, ...]
|
Component kernels k^(1), …, k^(n). |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> matern = gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(0.5), order=1
... )
>>> cosine = gaussx.CosineSDE(
... variance=jnp.asarray(0.5), frequency=jnp.asarray(2.0)
... )
>>> kernel = gaussx.SumSDE(kernels=(matern, cosine))
>>> kernel.state_dim
4
The sum's kernel is the sum of the kernels:
>>> lags = jnp.array([0.0, 0.7])
>>> total = gaussx.sde_autocovariance(kernel, lags)
>>> parts = gaussx.sde_autocovariance(
... matern, lags
... ) + gaussx.sde_autocovariance(cosine, lags)
>>> bool(jnp.allclose(total, parts, atol=1e-5))
True
A non-stationary component makes the sum non-stationary:
>>> trend = gaussx.IntegratedWienerSDE(diffusion=jnp.asarray(1.0))
>>> gaussx.SumSDE(kernels=(trend, matern)).stationary
False
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
state_dim: int
property
¶
State length D_x = ∑_i D_x^(i).
stationary: bool
property
¶
Stationary only if every component is.
initial_covariance() -> Float[Array, 'd d']
¶
Block-diagonal initial covariance Σ_x,0 = blockdiag_i(Σ_x,0^(i)).
The components are independent, so their initial covariances stack block-diagonally, which lets a sum mix stationary and non-stationary components (a local linear trend plus a Matérn seasonal, say), each started from its own.
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Initial state covariance Σ_x,0. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
sde_params() -> SDEParams
¶
Block-diagonal continuous-time parameters of the sum.
F_c = blockdiag_i(F_c^(i)), L_c = blockdiag_i(L_c^(i)),
Q_c = blockdiag_i(Q_c^(i)), H = [H^(1), …, H^(n)],
Σ_x,∞ = blockdiag_i(Σ_x,∞^(i)), or ``None`` if any is ``None``
Returns:
| Type | Description |
|---|---|
SDEParams
|
The |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Block-diagonal stack of each component's own discretisation.
F_t = blockdiag_i(F_t^(i)), Σ_η,t = blockdiag_i(Σ_η,t^(i))
The components are independent, so F_t and Σ_η,t are
block-diagonal. Each block keeps its component's exact route
(closed form, stationary Σ_x,∞ − F_t Σ_x,∞ F_tᵀ, or MFD only where
needed) instead of exponentiating the whole sum, which, with one
non-stationary component, sent everything through
discretize_mfd at ~27× the cost (gh-318).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
ProductSDE
¶
Bases: SDEKernel
Product of two SDE kernels, by Kronecker composition.
k(τ) = k^(1)(τ) k^(2)(τ)
F_c = F_c^(1) ⊕ F_c^(2) = F_c^(1) ⊗ I + I ⊗ F_c^(2)
Σ_x,∞ = Σ_x,∞^(1) ⊗ Σ_x,∞^(2), H = H^(1) ⊗ H^(2)
Both factors need a stationary covariance; see sde_params.
Attributes:
| Name | Type | Description |
|---|---|---|
kernel1 |
SDEKernel
|
First factor k^(1). |
kernel2 |
SDEKernel
|
Second factor k^(2). |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> matern = gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(0.5), order=1
... )
>>> cosine = gaussx.CosineSDE(
... variance=jnp.asarray(2.0), frequency=jnp.asarray(3.0)
... )
>>> kernel = gaussx.ProductSDE(kernel1=matern, kernel2=cosine)
>>> kernel.state_dim
4
The product's kernel is the product of the kernels:
>>> lags = jnp.array([0.0, 0.4])
>>> got = gaussx.sde_autocovariance(kernel, lags)
>>> expected = gaussx.sde_autocovariance(
... matern, lags
... ) * gaussx.sde_autocovariance(cosine, lags)
>>> bool(jnp.allclose(got, expected, atol=1e-5))
True
A factor without a stationary covariance cannot be composed:
>>> trend = gaussx.IntegratedWienerSDE(diffusion=jnp.asarray(1.0))
>>> gaussx.ProductSDE(
... kernel1=trend, kernel2=cosine
... ).sde_params()
Traceback (most recent call last):
...
NotImplementedError: ProductSDE cannot report SDE parameters
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
state_dim: int
property
¶
State length D_x = D_x^(1) D_x^(2).
stationary: bool
property
¶
Stationary only if both factors are.
sde_params() -> SDEParams
¶
Kronecker-structured continuous-time parameters of the product.
F_c = F_c^(1) ⊗ I + I ⊗ F_c^(2), Σ_x,∞ = Σ_x,∞^(1) ⊗ Σ_x,∞^(2)
B_c = B_c^(1) ⊗ Σ_x,∞^(2) + Σ_x,∞^(1) ⊗ B_c^(2)
L_c = [L_c^(1) ⊗ I, I ⊗ L_c^(2)]
Q_c = blockdiag(Q_c^(1) ⊗ Σ_x,∞^(2), Σ_x,∞^(1) ⊗ Q_c^(2))
The drift is the Kronecker sum and the stationary covariance
the Kronecker product. Substituting those into the Lyapunov
equation F_c Σ_x,∞ + Σ_x,∞ F_cᵀ + B_c = 0 fixes the composite
diffusion covariance B_c above, which is not B_c^(1) ⊗ B_c^(2),
the value a naive L_c^(1) ⊗ L_c^(2), Q_c^(1) ⊗ Q_c^(2) pair would
imply. Reporting the latter used to hand out a tuple that failed
its own Lyapunov equation (gh-219); for a Matérn ⊗ Cosine product
it was identically zero, since CosineSDE has Q_c = 0.
The sum of two Kronecker products is still expressible in the
(L_c, Q_c) form above, by widening the noise dimension and carrying
each factor's stationary covariance in the spectral density, so
that L_c Q_c L_cᵀ telescopes to exactly B_c by the mixed-product
property. Writing it this way rather than through square roots
S Sᵀ = Σ_x,∞ keeps the result exact for singular or zero Σ_x,∞
(where a Cholesky would need jitter, and would then violate the
very Lyapunov equation this enforces) and keeps sde_params
reverse-mode differentiable.
Note
SDEParams types its fields as dense
jaxtyping.Float[Array, ...]. The Kronecker products below
are dense materialisations of size D_x × D_x with
D_x = D_x^(1) D_x^(2); for typical SSM kernels (Matérn-3/2,
periodic) this is ≤ 32, so the materialisation is bounded and
cheap. A future refactor could expose a parallel
sde_operators() method that returns gaussx.Kronecker
operators for downstream filters that can exploit the
structure (issue #153).
Returns:
| Type | Description |
|---|---|
SDEParams
|
The |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If either factor lacks a stationary covariance. The composite diffusion needs both, so the tuple cannot be built, and reporting the inconsistent Kronecker product instead is what gh-219 was about. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 | |
discretise(dt: Float[Array, '']) -> tuple[Float[Array, 'd d'], Float[Array, 'd d']]
¶
Discretise per factor, through the Kronecker exponential identity.
F_t = exp(F_c Δt) = exp(F_c^(1) Δt) ⊗ exp(F_c^(2) Δt)
= F_t^(1) ⊗ F_t^(2)
Σ_η,t = Σ_x,∞ − (F_t^(1) Σ_x,∞^(1) F_t^(1)ᵀ)
⊗ (F_t^(2) Σ_x,∞^(2) F_t^(2)ᵀ)
The two terms of the Kronecker sum F_c^(1) ⊗ I and I ⊗ F_c^(2)
commute, so the exponential factorises: two exponentials of size
D_x^(1) and D_x^(2) plus one Kronecker product, instead of one of
size D_x^(1) D_x^(2). By the mixed-product property the congruence
F_t Σ_x,∞ F_tᵀ factorises too, so gaussx.process_noise_covariance
evaluates it per factor on gaussx.Kronecker operands, in
O((D_x^(1))³ + (D_x^(2))³) instead of O((D_x^(1) D_x^(2))³). Only
the final Σ_η,t is materialised, to keep the consumer-facing
(A, Q) interface unchanged.
Algorithm
- Exponentiate each factor's drift, F_t^(i) = exp(F_c^(i) Δt).
- Form F_t = F_t^(1) ⊗ F_t^(2).
- Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ on Kronecker operands, then materialise and symmetrise it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dt
|
Float[Array, '']
|
Time step Δt > 0. |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, 'd d']
|
Tuple |
Float[Array, 'd d']
|
model-noise covariance Σ_η,t, as in |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If either factor lacks a stationary covariance. |
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 | |
QuasiPeriodicSDE
¶
Bases: ProductSDE
Quasi-periodic kernel: a Matérn factor times a periodic factor.
k(τ) = k_Matérn(τ) k_periodic(τ)
The state-space form is that of ProductSDE.
Attributes:
| Name | Type | Description |
|---|---|---|
kernel1 |
SDEKernel
|
Modulating factor k^(1), typically a |
kernel2 |
SDEKernel
|
Periodic factor k^(2), typically a |
Examples:
>>> import jax.numpy as jnp
>>> import gaussx
>>> kernel = gaussx.QuasiPeriodicSDE(
... kernel1=gaussx.MaternSDE(
... variance=jnp.asarray(1.0), lengthscale=jnp.asarray(2.0), order=0
... ),
... kernel2=gaussx.PeriodicSDE(
... variance=jnp.asarray(1.0),
... lengthscale=jnp.asarray(1.0),
... period=jnp.asarray(1.0),
... n_harmonics=3,
... ),
... )
>>> kernel.state_dim
8
>>> transition, noise = kernel.discretise(jnp.asarray(0.1))
>>> transition.shape, noise.shape
((8, 8), (8, 8))
Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
Linear-Gaussian state-space models¶
LinearGaussianSSMPrior is the general Gaussian state-space model, given directly by its transitions A_k, observation matrices H_k, process and observation noise covariances Q_k and R_k, an initial state N(m_0, P_0) and an optional known observation offset b_k, so that x_k = A_k x_{k-1} + eta_k and y_k = H_k x_k + b_k + eps_k for k = 1, …, T. Use it when the dynamics are known as matrices rather than as a GP kernel: a local-level model, a multi-output state, a discretised physical model whose matrices carry priors. It follows the gaussx.kalman_filter convention of predicting before every update, so y[0] is scored against A_1 x_0; set transition[0] = I and process_noise[0] = 0 to observe the initial state itself.
Observations are (T, M) (a flat (T,) series is accepted when M = 1), and every method takes a mask= either per step, (T,), or per entry, (T, M); a masked entry is marginalised out exactly and may hold NaN. log_marginal, smooth and condition give the prediction-error log marginal and the RTS-smoothed state moments, and lgssm_factor adds the log marginal to a NumPyro model:
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
def local_level(y, mask):
T = y.shape[0]
q = numpyro.sample("q", dist.LogNormal(-2.0, 1.0))
r = numpyro.sample("r", dist.LogNormal(-1.0, 1.0))
prior = pss.LinearGaussianSSMPrior(
transition=jnp.ones((T, 1, 1)), obs_model=jnp.eye(1),
process_noise=q * jnp.ones((T, 1, 1)), obs_noise=r * jnp.eye(1),
init_mean=jnp.zeros(1), init_cov=10.0 * jnp.eye(1),
)
pss.lgssm_factor("y", prior, y, mask=mask)
MarkovGPPrior is its kernel-built special case: as_lgssm(noise_var) returns the kernel's discretised transitions over the time grid (with a leading zero step, so A_1 = I and Q_1 = 0), H, R_k = noise_var + obs_noise_floor, m_0 = 0, P_0 = initial_covariance() and the offset b_k = mean_fn(t_k). MarkovGPPrior's filtering and smoothing run through this model, so the two agree bit for bit.
After condition(y, mask=mask), predict() returns each channel's posterior mean H_k m_{k|T} + b_k and variance diag(H_k P_{k|T} H_kᵀ) at every step, (T, M) each, and include_noise=True adds diag(R_k) for the band a new observation should fall in. The model is indexed by step, so to forecast or fill a gap, extend the matrices over the extra steps and mask them.
cond.sample(key, n_paths) draws whole state paths \(x_{1:T}\) from the posterior by backward sampling (gaussx.rts_sample), shaped (S, T, D), for any quantity of several steps that the marginals cannot give (a maximum, a run length, a sum); prior.sample(key, n) simulates (x, y) from the model itself.
LinearGaussianSSMPrior
¶
Bases: Module
Prior over a linear-Gaussian state-space model given by its matrices.
With \(T\) observation steps, a state of length \(D\) and observations of length \(M\), the model is
for \(k = 1, \dots, T\), and row \(k - 1\) of every time-stacked field
holds step \(k\). This is the convention of gaussx.kalman_filter, which
predicts before every update: the first observation y[0] is \(y_1\),
scored against \(A_1 x_0\), not against \(x_0\). To observe the initial
state itself, set transition[0] = I and process_noise[0] = 0,
which is what pyrox_ssm.MarkovGPPrior.as_lgssm does (its first step
has \(\Delta t = 0\)).
The marginal likelihood is the prediction-error decomposition
with \(m_k^-, P_k^-\) the predicted moments of \(x_k\) given \(y_{1:k-1}\), at \(O(T D^3)\) cost.
Every method that reads observations takes an optional mask, either
per step, shaped (T,) (a masked step runs the predict only), or per
entry, shaped (T, M) (the masked entries of \(y_k\) are marginalised
out exactly, so the log marginal is that of the observed entries).
Masked entries of y are replaced by zero before any arithmetic, so a
NaN placeholder there reaches neither the value nor a gradient.
The prior registers no NumPyro sites itself; lgssm_factor adds its log
marginal as a factor. Shapes are checked at construction (array shapes
are static, so the check also runs on traced matrices), and integer
arrays are promoted to float.
Attributes:
| Name | Type | Description |
|---|---|---|
transition |
Float[Array, 'T D D']
|
Transitions \(A_k\), shaped |
obs_model |
Float[Array, 'T M D'] | Float[Array, 'M D']
|
Observation matrices \(H_k\), shaped |
process_noise |
Float[Array, 'T D D']
|
Process-noise covariances \(Q_k\), shaped
|
obs_noise |
Float[Array, 'T M M'] | Float[Array, 'M M']
|
Observation-noise covariances \(R_k\), shaped
|
init_mean |
Float[Array, ' D']
|
Mean \(m_0\) of the initial state, shaped |
init_cov |
Float[Array, 'D D']
|
Covariance \(P_0\) of the initial state, shaped |
obs_offset |
Float[Array, 'T M'] | None
|
Optional known observation offset \(b_k\), shaped
|
parallel |
bool
|
Filter with
On an accelerator the parallel filter's depth is \(O(\log T)\) against \(O(T)\); the numbers above are CPU only. |
Examples:
A local-level model, \(x_k = x_{k-1} + \eta_k\) observed with noise:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> T, q, r = 5, 0.1, 0.5
>>> prior = pss.LinearGaussianSSMPrior(
... transition=jnp.ones((T, 1, 1)),
... obs_model=jnp.eye(1),
... process_noise=jnp.full((T, 1, 1), q),
... obs_noise=r * jnp.eye(1),
... init_mean=jnp.zeros(1),
... init_cov=10.0 * jnp.eye(1),
... )
>>> y = jnp.array([[0.1], [0.4], [jnp.nan], [0.3], [0.2]])
>>> mask = jnp.array([True, True, False, True, True])
>>> log_marg = prior.log_marginal(y, mask=mask)
>>> log_marg.shape
()
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 | |
n_steps: int
property
¶
Number of observation steps \(T\).
state_dim: int
property
¶
State dimension \(D\).
obs_dim: int
property
¶
Observation dimension \(M\).
filter(y: Float[Array, 'T M'] | Float[Array, ' T'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> FilterState
¶
Run the forward Kalman filter.
Each step predicts, then updates on the observed entries of \(y_k\),
and adds \(\log \mathcal{N}(y_k;\, H_k m_k^- + b_k,\, H_k P_k^- H_k^\top + R_k)\) over those entries to the log marginal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M'] | Float[Array, ' T']
|
Observations, shaped |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional boolean mask, |
None
|
Returns:
| Type | Description |
|---|---|
FilterState
|
The |
FilterState
|
|
FilterState
|
step \(k\), and the scalar |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((3, 1, 1)), jnp.eye(1), jnp.full((3, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> state = prior.filter(jnp.array([0.1, 0.3, 0.2]))
>>> state.filtered_means.shape, state.log_likelihood.shape
((3, 1), ())
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
log_marginal(y: Float[Array, 'T M'] | Float[Array, ' T'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> Float[Array, '']
¶
Marginal log-likelihood \(\log p(y_{\mathrm{obs}} \mid \theta)\).
restricted to the observed entries when a mask is given.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M'] | Float[Array, ' T']
|
Observations, shaped |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar log marginal of the observed entries. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.broadcast_to(jnp.eye(2), (4, 2, 2)), jnp.eye(2),
... jnp.broadcast_to(0.1 * jnp.eye(2), (4, 2, 2)),
... 0.5 * jnp.eye(2), jnp.zeros(2), jnp.eye(2),
... )
>>> y = jnp.array([[0.1, 0.2], [0.3, jnp.nan], [0.2, 0.1], [0.0, 0.4]])
>>> mask = ~jnp.isnan(y) # one output missing at step 2
>>> log_marg = prior.log_marginal(y, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
smooth(y: Float[Array, 'T M'] | Float[Array, ' T'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> tuple[Float[Array, 'T D'], Float[Array, 'T D D'], Float[Array, '']]
¶
Run the Kalman filter and the RTS smoother.
Returns the moments of \(p(x_k \mid y_{1:T})\) for \(k = 1, \dots, T\)
(row \(k - 1\)), via gaussx.rts_smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M'] | Float[Array, ' T']
|
Observations, shaped |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'T D']
|
|
Float[Array, 'T D D']
|
|
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((3, 1, 1)), jnp.eye(1), jnp.full((3, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> m, P, _ = prior.smooth(jnp.array([0.1, 0.3, 0.2]))
>>> m.shape, P.shape
((3, 1), (3, 1, 1))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
sample(key: PRNGKeyArray, n: int = 1) -> tuple[Float[Array, 'S T D'], Float[Array, 'S T M']]
¶
Draws of \((x_{1:T}, y_{1:T})\) from the prior, by running the model forward.
with \(\eta_k \sim \mathcal{N}(0, Q_k)\) and
\(\varepsilon_k \sim \mathcal{N}(0, R_k)\), row \(k - 1\) holding step
\(k\). The noise square roots are symmetric (gaussx.sqrt), so a
singular \(Q_k\), such as the zero first step of
pyrox_ssm.MarkovGPPrior.as_lgssm, is drawn exactly. Use it to
simulate data from the model, or to check a fit on data whose truth
is known.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key. |
required |
n
|
int
|
Number of independent draws \(S\). |
1
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'S T D'], Float[Array, 'S T M']]
|
|
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((5, 1, 1)), jnp.eye(1), jnp.full((5, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> states, y = prior.sample(jr.key(0), n=3)
>>> states.shape, y.shape
((3, 5, 1), (3, 5, 1))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 | |
condition(y: Float[Array, 'T M'] | Float[Array, ' T'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> ConditionedLinearGaussianSSM
¶
Condition on y with the filter and the RTS smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M'] | Float[Array, ' T']
|
Observations, shaped |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedLinearGaussianSSM
|
The |
ConditionedLinearGaussianSSM
|
with its masked entries set to zero. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((3, 1, 1)), jnp.eye(1), jnp.full((3, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> cond = prior.condition(jnp.array([0.1, 0.3, 0.2]))
>>> cond.smoothed_means.shape
(3, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
ConditionedLinearGaussianSSM
¶
Bases: Module
A LinearGaussianSSMPrior conditioned on observations.
Holds the smoothed moments of \(p(x_k \mid y_{1:T})\), row \(k - 1\) for
step \(k\), and the log marginal. predict gives each observation
channel's marginal mean and variance at every step.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
LinearGaussianSSMPrior
|
The originating |
y |
Float[Array, 'T M']
|
Observations, |
smoothed_means |
Float[Array, 'T D']
|
Smoothed state means, |
smoothed_covs |
Float[Array, 'T D D']
|
Smoothed state covariances, |
log_marginal |
Float[Array, '']
|
Scalar \(\log p(y_{\mathrm{obs}} \mid \theta)\). |
mask |
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
The |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((3, 1, 1)), jnp.eye(1), jnp.full((3, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> cond = prior.condition(jnp.array([0.1, 0.3, 0.2]))
>>> cond.smoothed_covs.shape, cond.log_marginal.shape
((3, 1, 1), ())
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 | |
sample(key: PRNGKeyArray, n_paths: int = 1) -> Float[Array, 'S T D']
¶
Joint draws of the state path from \(p(x_{1:T} \mid y_{\mathrm{obs}})\).
Backward sampling (gaussx.rts_sample) on the filter's moments: \(x_T\)
from its filtered distribution, then each \(x_k \mid x_{k+1}\) with the
smoother's gain. Each draw is a whole path, so a quantity of several
steps (a maximum over a window, a run length, a sum) gets its joint
uncertainty, which the marginals of smoothed_means and
smoothed_covs cannot give; the per-step moments of the draws
converge to them. The filter runs again on the stored observations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key. |
required |
n_paths
|
int
|
Number of joint draws \(S\). |
1
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'S T D']
|
The state paths, shaped |
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((4, 1, 1)), jnp.eye(1), jnp.full((4, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> y = jnp.array([0.1, 0.3, jnp.nan, 0.2])
>>> cond = prior.condition(y, mask=~jnp.isnan(y))
>>> cond.sample(jr.key(0), n_paths=16).shape
(16, 4, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
predict(*, include_noise: bool = False) -> tuple[Float[Array, 'T M'], Float[Array, 'T M']]
¶
Marginal mean and variance of each observation channel at every step.
With the smoothed moments \(m_{k \mid T}, P_{k \mid T}\) and the known
offset \(b_k\) (obs_offset, zero by default),
and include_noise=True adds \((R_k)_{jj}\), the variance of a new
observation, for the band a withheld one should fall in. The mean is
the same either way.
The model is indexed by step, so there are no new times to predict
at: to forecast or fill a gap, extend the prior's matrices over the
extra steps and mask them, since a masked step runs the predict only.
For a pyrox_ssm.MarkovGPPrior.as_lgssm model this equals
pyrox_ssm.ConditionedMarkovGP.predict at the training times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_noise
|
bool
|
Add the observation-noise variance \((R_k)_{jj}\).
Default |
False
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'T M']
|
|
Float[Array, 'T M']
|
step \(k\). |
Examples:
A local-level model with its third step missing:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.LinearGaussianSSMPrior(
... jnp.ones((4, 1, 1)), jnp.eye(1), jnp.full((4, 1, 1), 0.1),
... 0.5 * jnp.eye(1), jnp.zeros(1), jnp.eye(1),
... )
>>> y = jnp.array([0.1, 0.3, jnp.nan, 0.2])
>>> cond = prior.condition(y, mask=~jnp.isnan(y))
>>> mean, var = cond.predict()
>>> _, band = cond.predict(include_noise=True)
>>> mean.shape, var.shape
((4, 1), (4, 1))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
lgssm_factor(name: str, prior: LinearGaussianSSMPrior, y: Float[Array, 'T M'] | Float[Array, ' T'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> None
¶
Register a linear-Gaussian SSM's log marginal as a NumPyro factor.
Adds numpyro.factor(name, prior.log_marginal(y, mask=mask)), the
state path marginalised out by the Kalman filter,
Registers the one site name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
LinearGaussianSSMPrior
|
The |
required |
y
|
Float[Array, 'T M'] | Float[Array, ' T']
|
Observations, shaped |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Examples:
A local-level model with priors on its two noise variances:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> def model(y):
... T = y.shape[0]
... q = numpyro.sample("q", dist.LogNormal(-2.0, 1.0))
... r = numpyro.sample("r", dist.LogNormal(-1.0, 1.0))
... prior = pss.LinearGaussianSSMPrior(
... jnp.ones((T, 1, 1)), jnp.eye(1), q * jnp.ones((T, 1, 1)),
... r * jnp.eye(1), jnp.zeros(1), 10.0 * jnp.eye(1),
... )
... pss.lgssm_factor("y", prior, y)
>>> trace = numpyro.handlers.trace(numpyro.handlers.seed(model, 0)).get_trace(
... jnp.array([0.1, 0.4, 0.3])
... )
>>> sorted(trace)
['q', 'r', 'y']
Source code in packages/pyrox-ssm/src/pyrox_ssm/_lgssm.py
Nonlinear state-space models¶
nonlinear_ssm_factor scores a series under nonlinear dynamics x_k = f(x_{k-1}) + eta_k and observations y_k = h(x_k) + eps_k with gaussx.nonlinear_kalman_filter, adds its log likelihood to the NumPyro model and returns the gaussx.FilterState; the gaussx integrator picks the filter (TaylorIntegrator for the EKF, UnscentedIntegrator for the UKF and the default, CubatureIntegrator for the CKF, GaussHermiteIntegrator, MonteCarloIntegrator). The log likelihood is gaussx's moment-matched surrogate, exact only when f and h are affine, and the time convention and the mask= are those of LinearGaussianSSMPrior:
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
def log_emission(y): # x_k = a x_{k-1} + eta_k, y_k = exp(x_k) + eps_k
a = numpyro.sample("a", dist.Uniform(-1.0, 1.0))
pss.nonlinear_ssm_factor(
"y", lambda x: a * x, jnp.exp, 0.1 * jnp.eye(1), 0.05 * jnp.eye(1),
y, jnp.zeros(1), jnp.eye(1),
)
NonlinearGaussianSSMPrior holds the same model, (f, h, Q, R, m_0, P_0) and the integrator, as a prior, as LinearGaussianSSMPrior does for the linear case: filter, log_marginal (the value the factor registers), smooth, which runs gaussx.nonlinear_rts_smoother with the same integrator, and condition. The ConditionedNonlinearGaussianSSM it returns holds the smoothed states and gives predict(), each channel's mean and variance at every step, pushed through h by the integrator (include_noise=True adds diag(R_k)). The factor builds this prior, so the two cannot drift apart. With affine f and h every deterministic integrator reproduces LinearGaussianSSMPrior.
prior = pss.NonlinearGaussianSSMPrior(
lambda x: 0.8 * x, jnp.exp, 0.1 * jnp.eye(1), 0.05 * jnp.eye(1), jnp.zeros(1), jnp.eye(1)
)
posterior = prior.condition(y, mask=mask)
states, state_covs = posterior.smoothed_means, posterior.smoothed_covs # (T, D), (T, D, D)
mean, var = posterior.predict(include_noise=True) # (T, M) each
NonlinearGaussianSSMPrior
¶
Bases: Module
Prior over a nonlinear state-space model, filtered by moment matching.
With \(T\) observation steps, a state of length \(D\) and observations of length \(M\), the model is
for \(k = 1, \dots, T\), with row \(k - 1\) of y holding step \(k\): the
convention of gaussx.nonlinear_kalman_filter and of
pyrox_ssm.LinearGaussianSSMPrior, which predict before every update.
filter runs gaussx.nonlinear_kalman_filter, which pushes the Gaussian
belief through \(f\) and \(h\) by the integrator's moment transform, and
log_marginal is its prediction-error sum
with \(\hat{y}_k = \mathbb{E}[h(x_k)]\) and
\(S_k = \operatorname{Cov}[h(x_k)] + R_k\) under the predicted Gaussian of
\(x_k\). In gaussx's words this is "a moment-matched surrogate, not the
exact marginal likelihood"; it is exact when \(f\) and \(h\) are affine.
smooth runs gaussx.nonlinear_rts_smoother backwards with the same
integrator, whose gain uses the cross-covariance of \(x_k\) and
\(f(x_k)\); for affine \(f\) it is the Kalman RTS smoother. A Monte Carlo
integrator makes the filter and the smoother stochastic; the tests use
the deterministic rules.
The integrator picks the filter: gaussx.TaylorIntegrator (EKF),
gaussx.UnscentedIntegrator (UKF, the default),
gaussx.CubatureIntegrator (CKF),
gaussx.FifthOrderCubatureIntegrator, gaussx.GaussHermiteIntegrator
or gaussx.MonteCarloIntegrator.
Every method that reads observations takes an optional mask, per
step (T,) (a masked step runs the predict only) or per entry
(T, M) (masked entries are marginalised out of the update). Masked
entries of y are replaced by zero before any arithmetic, so a
NaN there reaches neither the value nor a gradient. The prior
registers no NumPyro sites; nonlinear_ssm_factor adds its log
likelihood as a factor.
Attributes:
| Name | Type | Description |
|---|---|---|
dynamics |
Callable[[Float[Array, ' D']], Float[Array, ' D']]
|
Deterministic dynamics \(f\), from a |
obs_fn |
Callable[[Float[Array, ' D']], Float[Array, ' M']]
|
Observation map \(h\), from a |
process_noise |
Float[Array, 'D D'] | Float[Array, 'T D D'] | AbstractLinearOperator
|
Process-noise covariance \(Q_k\): |
obs_noise |
Float[Array, 'M M'] | Float[Array, 'T M M'] | AbstractLinearOperator
|
Observation-noise covariance \(R_k\): |
init_mean |
Float[Array, ' D']
|
Mean \(m_0\) of the initial state, |
init_cov |
Float[Array, 'D D']
|
Covariance \(P_0\) of the initial state, |
integrator |
AbstractIntegrator | None
|
The gaussx moment-matching rule. |
joseph |
bool
|
Use the Joseph-form covariance update. Default |
solver |
AbstractSolverStrategy | None
|
Solver strategy for \(S_k\), passed through to gaussx.
|
Examples:
A log-emission AR(1) state, \(x_k = 0.8 x_{k-1} + \eta_k\) observed through \(y_k = \exp(x_k) + \varepsilon_k\), with the third step missing:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... lambda x: 0.8 * x, jnp.exp, 0.1 * jnp.eye(1), 0.05 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> y = jnp.array([[1.1], [0.9], [jnp.nan], [1.0]])
>>> mask = jnp.array([True, True, False, True])
>>> log_marg = prior.log_marginal(y, mask=mask)
>>> posterior = prior.condition(y, mask=mask)
>>> posterior.smoothed_means.shape
(4, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
filter(y: Float[Array, 'T M'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> FilterState
¶
Run the moment-matched forward filter.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
FilterState
|
The |
FilterState
|
and covariances |
FilterState
|
the scalar surrogate |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... jnp.sin, lambda x: x, 0.1 * jnp.eye(1), 0.2 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> state = prior.filter(jnp.array([[0.1], [0.3], [0.2]]))
>>> state.filtered_means.shape
(3, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
log_marginal(y: Float[Array, 'T M'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> Float[Array, '']
¶
The moment-matched surrogate of \(\log p(y_{\mathrm{obs}} \mid \theta)\).
over the observed entries. Exact when \(f\) and \(h\) are affine; a
surrogate otherwise, so maximising it or sampling under it targets
the surrogate. It is the value nonlinear_ssm_factor registers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar surrogate log marginal. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... lambda x: 0.8 * x, jnp.exp, 0.1 * jnp.eye(1), 0.05 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> log_marg = prior.log_marginal(jnp.array([[1.1], [0.9], [1.0]]))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
smooth(y: Float[Array, 'T M'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> tuple[Float[Array, 'T D'], Float[Array, 'T D D'], Float[Array, '']]
¶
Run the filter and the moment-matched RTS smoother.
Returns the moments of \(p(x_k \mid y_{1:T})\) for \(k = 1, \dots, T\)
(row \(k - 1\)), from gaussx.nonlinear_rts_smoother with the
filter's integrator. The smoother gain is
\(G_k = \operatorname{Cov}[x_k, f(x_k)] (P_{k+1}^-)^{-1}\); for affine
\(f(x) = A x\) it is the Kalman gain \(P_k A^\top (P_{k+1}^-)^{-1}\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'T D']
|
|
Float[Array, 'T D D']
|
|
Float[Array, '']
|
|
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... jnp.sin, lambda x: x, 0.1 * jnp.eye(1), 0.2 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> m, P, _ = prior.smooth(jnp.array([[0.1], [0.3], [0.2]]))
>>> m.shape, P.shape
((3, 1), (3, 1, 1))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
condition(y: Float[Array, 'T M'], *, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None) -> ConditionedNonlinearGaussianSSM
¶
Condition on y with the filter and the moment-matched smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, |
required |
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonlinearGaussianSSM
|
The |
ConditionedNonlinearGaussianSSM
|
masked entries set to zero. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... jnp.sin, lambda x: x, 0.1 * jnp.eye(1), 0.2 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> posterior = prior.condition(jnp.array([[0.1], [0.3], [0.2]]))
>>> mean, var = posterior.predict()
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
ConditionedNonlinearGaussianSSM
¶
Bases: Module
A NonlinearGaussianSSMPrior conditioned on observations.
Returned by NonlinearGaussianSSMPrior.condition. Holds the moments of
\(p(x_k \mid y_{1:T})\) from the moment-matched smoother, row \(k - 1\) for
step \(k\), and the surrogate log marginal; predict pushes them through
\(h\) for each observation channel.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
NonlinearGaussianSSMPrior
|
The originating |
y |
Float[Array, 'T M']
|
Observations, |
smoothed_means |
Float[Array, 'T D']
|
Smoothed state means, |
smoothed_covs |
Float[Array, 'T D D']
|
Smoothed state covariances, |
log_marginal |
Float[Array, '']
|
The scalar moment-matched surrogate of \(\log p(y_{\mathrm{obs}} \mid \theta)\). |
mask |
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
The |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
predict(*, include_noise: bool = False) -> tuple[Float[Array, 'T M'], Float[Array, 'T M']]
¶
Mean and variance of each observation channel at every step.
The smoothed Gaussian of \(x_k\) is pushed through \(h\) by the prior's
integrator, gaussx.moment_transform,
and include_noise=True adds \((R_k)_{jj}\), the variance of a new
observation. For affine \(h(x) = H x\) this is
pyrox_ssm.ConditionedLinearGaussianSSM.predict. Like the filter,
it is a moment-matched approximation when \(h\) is nonlinear. To
forecast or fill a gap, extend y with masked steps and condition
again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
include_noise
|
bool
|
Add the observation-noise variance \((R_k)_{jj}\).
Default |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'T M'], Float[Array, 'T M']]
|
|
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> prior = pss.NonlinearGaussianSSMPrior(
... lambda x: 0.8 * x, jnp.exp, 0.1 * jnp.eye(1), 0.05 * jnp.eye(1),
... jnp.zeros(1), jnp.eye(1),
... )
>>> posterior = prior.condition(jnp.array([[1.1], [0.9], [1.0]]))
>>> mean, band = posterior.predict(include_noise=True)
>>> mean.shape
(3, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
nonlinear_ssm_factor(name: str, dynamics: Callable[[Float[Array, ' D']], Float[Array, ' D']], obs_fn: Callable[[Float[Array, ' D']], Float[Array, ' M']], process_noise: Float[Array, 'D D'] | Float[Array, 'T D D'] | lx.AbstractLinearOperator, obs_noise: Float[Array, 'M M'] | Float[Array, 'T M M'] | lx.AbstractLinearOperator, y: Float[Array, 'T M'], init_mean: Float[Array, ' D'], init_cov: Float[Array, 'D D'], *, integrator: AbstractIntegrator | None = None, mask: Bool[Array, ' T'] | Bool[Array, 'T M'] | None = None, joseph: bool = True, solver: AbstractSolverStrategy | None = None) -> FilterState
¶
Register a nonlinear state-space model's log likelihood as a factor.
With \(T\) observation steps, a state of length \(D\) and observations of length \(M\), the model is
for \(k = 1, \dots, T\), with \(f\) the dynamics and \(h\) the
obs_fn, and row \(k - 1\) of y holds step \(k\). This is the
convention of gaussx.nonlinear_kalman_filter (and of
pyrox_ssm.LinearGaussianSSMPrior), which predicts before every
update: the first observation y[0] is \(y_1\), scored against
\(f(x_0) + \eta_1\), not against \(x_0\).
gaussx.nonlinear_kalman_filter pushes the Gaussian belief through \(f\)
and \(h\) by the integrator's moment transform. With
\(m_k^-, P_k^-\) the predicted moments of \(x_k\) given \(y_{1:k-1}\), the
update matches
and the factor is the prediction-error sum
In gaussx's words, this log_likelihood "is a moment-matched
surrogate, not the exact marginal likelihood: Σ_y,t is the matched
observation covariance rather than the true one. It is exact when f and
h are affine." Maximising it, or sampling under it, targets that
surrogate.
The integrator picks the filter:
| integrator | filter |
|---|---|
gaussx.TaylorIntegrator |
extended Kalman filter (EKF) |
gaussx.UnscentedIntegrator |
unscented Kalman filter (UKF), the default |
gaussx.CubatureIntegrator |
cubature Kalman filter (CKF) |
gaussx.FifthOrderCubatureIntegrator |
degree-5 cubature Kalman filter |
gaussx.GaussHermiteIntegrator |
Gauss-Hermite Kalman filter (GHKF) |
gaussx.MonteCarloIntegrator |
Monte Carlo Kalman filter |
Masked entries of y are replaced by zero before the filter runs, so
a NaN placeholder there reaches neither the value nor a gradient. A
per-step mask, shaped (T,), runs the predict only at a masked step;
a per-entry mask, shaped (T, M), marginalises the masked entries
out of the update, so either one scores exactly the observed entries.
Registers the one NumPyro site name, a factor, whose value is
NonlinearGaussianSSMPrior(dynamics, obs_fn, ...).log_marginal(y,
mask=mask); build that prior to smooth and predict after a fit.
Library code adds no jax.jit; jit the model or the loss at the top.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
dynamics
|
Callable[[Float[Array, ' D']], Float[Array, ' D']]
|
Deterministic dynamics \(f\), from a |
required |
obs_fn
|
Callable[[Float[Array, ' D']], Float[Array, ' M']]
|
Observation map \(h\), from a |
required |
process_noise
|
Float[Array, 'D D'] | Float[Array, 'T D D'] | AbstractLinearOperator
|
Process-noise covariance \(Q_k\): one |
required |
obs_noise
|
Float[Array, 'M M'] | Float[Array, 'T M M'] | AbstractLinearOperator
|
Observation-noise covariance \(R_k\), |
required |
y
|
Float[Array, 'T M']
|
Observations \(y_{1:T}\), shaped |
required |
init_mean
|
Float[Array, ' D']
|
Mean \(m_0\) of the initial state \(x_0\), shaped |
required |
init_cov
|
Float[Array, 'D D']
|
Covariance \(P_0\) of \(x_0\), shaped |
required |
integrator
|
AbstractIntegrator | None
|
The gaussx moment-matching rule. |
None
|
mask
|
Bool[Array, ' T'] | Bool[Array, 'T M'] | None
|
Optional boolean mask, |
None
|
joseph
|
bool
|
Use the Joseph-form covariance update, passed through to
|
True
|
solver
|
AbstractSolverStrategy | None
|
Solver strategy for \(S_k\), passed through to
|
None
|
Returns:
| Type | Description |
|---|---|
FilterState
|
The |
FilterState
|
and covariances |
FilterState
|
scalar |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
A log-emission AR(1) state, \(x_k = a x_{k-1} + \eta_k\) observed through \(y_k = \exp(x_k) + \varepsilon_k\), with a prior on \(a\):
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> def model(y):
... a = numpyro.sample("a", dist.Uniform(-1.0, 1.0))
... pss.nonlinear_ssm_factor(
... "y",
... lambda x: a * x,
... jnp.exp,
... 0.1 * jnp.eye(1),
... 0.05 * jnp.eye(1),
... y,
... jnp.zeros(1),
... jnp.eye(1),
... )
>>> y = jnp.array([[1.1], [0.9], [1.3], [1.0]])
>>> trace = numpyro.handlers.trace(numpyro.handlers.seed(model, 0)).get_trace(y)
>>> sorted(trace)
['a', 'y']
Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 | |
Markov GP — Kalman / RTS workflow¶
MarkovGPPrior consumes any SDEKernel over a sorted
1-D grid and gives O(N d^3) marginal likelihood (forward Kalman filter)
and posterior smoothing (backward RTS), where d is the SDE state
dimension. Use it for temporal GP regression / forecasting when the
training grid lives on a single time axis. Predictions at arbitrary
test times — including forecasting, backcasting, and within-window
interpolation — re-run the filter+smoother over the merged grid with the
test points masked out of the update step.
import jax.numpy as jnp
from pyrox_ssm import MaternSDE, MarkovGPPrior, markov_gp_factor
times = jnp.linspace(0.0, 5.0, 200)
y = jnp.sin(times) + 0.05 * jnp.cos(7.0 * times)
prior = MarkovGPPrior(
MaternSDE(variance=1.0, lengthscale=0.5, order=1), # Matern-3/2
times,
)
log_marg = prior.log_marginal(y, jnp.asarray(0.01)) # Kalman forward
cond = prior.condition(y, jnp.asarray(0.01)) # filter + RTS smoother
mean, var = cond.predict(jnp.linspace(-0.5, 6.0, 50)) # arbitrary test times
Inside a NumPyro model, swap gp_factor for markov_gp_factor:
import jax.numpy as jnp
import numpyro
from numpyro import distributions as dist
from pyrox_ssm import MarkovGPPrior, MaternSDE, markov_gp_factor
def temporal_model(times, y):
sigma2 = numpyro.sample("variance", dist.LogNormal(0.0, 1.0))
ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
sde = MaternSDE(variance=sigma2, lengthscale=ell, order=1)
prior = MarkovGPPrior(sde, times)
markov_gp_factor("obs", prior, y, jnp.array(0.01))
For non-Gaussian likelihoods on the Markov path, see the Markov non-Gaussian strategies below; for inducing-grid scalability, the sparse Markov GP.
MarkovGPPrior
¶
Bases: Module
Linear-time temporal GP prior over a sorted 1-D grid.
Wraps any pyrox_ssm.SDEKernel (e.g. pyrox_ssm.MaternSDE,
pyrox_ssm.SumSDE, pyrox_ssm.PeriodicSDE) to give Kalman
filtering for the marginal log-likelihood and RTS smoothing for the
posterior on the training grid. Supports an optional mean function and a
small observation-noise floor for numerical stability.
Attributes:
| Name | Type | Description |
|---|---|---|
sde_kernel |
SDEKernel
|
Any |
times |
Float[Array, ' N']
|
Sorted, strictly increasing observation times of shape
|
mean_fn |
Callable[[Float[Array, ' N']], Float[Array, ' N']] | None
|
Optional callable mapping |
obs_noise_floor |
float
|
Small extra diagonal added to the observation
variance |
init_cov |
Float[Array, 'd d'] | None
|
Optional |
parallel |
bool
|
Run every Kalman filter over this prior (
|
Every method that reads observations (filter, smooth,
log_marginal, condition, condition_nongauss) takes an optional
mask of shape (N,). A masked step runs the Kalman predict only,
so it adds nothing to the log marginal, and its observation is replaced
by zero before any arithmetic, so a NaN placeholder there is safe.
pyrox_ssm.pad_sites builds such masks for ragged per-site series.
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> times = jnp.linspace(0.0, 5.0, 50)
>>> sde = MaternSDE(variance=1.0, lengthscale=0.5, order=1)
>>> prior = MarkovGPPrior(sde, times)
>>> y = jnp.sin(times) + 0.05 * jnp.cos(3.0 * times)
>>> log_marg = prior.log_marginal(y, jnp.asarray(0.01))
>>> mask = jnp.arange(50) % 5 != 0 # every fifth step unobserved
>>> log_marg_masked = prior.log_marginal(y, jnp.asarray(0.01), mask=mask)
Notes
The solver-strategy plumbing used by pyrox_gp.GPPrior does
not apply here — Kalman filtering is its own linear-algebra path
and does not factor through gaussx.AbstractSolverStrategy.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 | |
state_dim: int
property
¶
SDE state dimension \(d\) for this kernel.
initial_covariance() -> Float[Array, 'd d']
¶
Covariance the Kalman recursions start from.
The init_cov given at construction if there is one, otherwise
whatever the kernel reports — \(P_\infty\) for a stationary kernel,
an explicit diffuse covariance for a non-stationary one. This is
the single seed every filtering surface here uses, so a kernel
with no \(P_\infty\) is only a problem for the paths that are
defined in terms of it (log_prob, the dense Gram).
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
mean(times: Float[Array, ' M']) -> Float[Array, ' M']
¶
Evaluate the mean function at times; zero by default.
as_lgssm(noise_var: Float[Array, '']) -> LinearGaussianSSMPrior
¶
This prior as a pyrox_ssm.LinearGaussianSSMPrior.
With \(\Delta t_1 = 0\) and \(\Delta t_k = t_k - t_{k-1}\), the kernel's discretisation gives the transitions and process noise,
where \(\epsilon\) is obs_noise_floor, \(\mu\) the mean function
and \(P_{\mathrm{init}}\) initial_covariance (\(P_\infty\) for a
stationary kernel). The zero first step makes \(A_1 = I\) and
\(Q_1 = 0\), so the first observation sees the initial state itself.
filter, smooth and log_marginal run through this model, so
the two give the same results bit for bit.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
noise_var
|
Float[Array, '']
|
Observation noise variance \(\sigma_n^2\). |
required |
Returns:
| Type | Description |
|---|---|
LinearGaussianSSMPrior
|
The |
LinearGaussianSSMPrior
|
\(T = N\) steps, state dimension \(d\) and one output. |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> lgssm = prior.as_lgssm(jnp.asarray(0.1))
>>> lgssm.transition.shape, lgssm.obs_model.shape
((4, 2, 2), (1, 2))
>>> y = jnp.array([0.1, 0.4, 0.3, 0.2])
>>> log_marg = lgssm.log_marginal(y) # == prior.log_marginal(y, 0.1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
filter(y: Float[Array, ' N'], noise_var: Float[Array, ''], *, mask: Bool[Array, ' N'] | None = None) -> tuple[Float[Array, 'N d'], Float[Array, 'N d d'], Float[Array, 'N d'], Float[Array, 'N d d'], Float[Array, '']]
¶
Run the forward Kalman filter on the training grid.
With \(o_k \in \{0, 1\}\) the mask, an observed step (\(o_k = 1\)) runs the usual update and a masked step (\(o_k = 0\)) runs the predict only,
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, ' N']
|
Observations of shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance \(\sigma_n^2\). |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'N d']
|
Tuple |
Float[Array, 'N d d']
|
each |
Float[Array, 'N d']
|
|
Float[Array, 'N d d']
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([0.1, jnp.nan, 0.3, 0.2])
>>> mask = jnp.array([True, False, True, True])
>>> *_, log_marg = prior.filter(y, jnp.asarray(0.1), mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
log_marginal(y: Float[Array, ' N'], noise_var: Float[Array, ''], *, mask: Bool[Array, ' N'] | None = None) -> Float[Array, '']
¶
Marginal log-likelihood log p(y | theta) via Kalman filtering.
A masked step contributes nothing,
so padding a series after its last observation and masking the padded steps leaves the result unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, ' N']
|
Observations of shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance \(\sigma_n^2\). |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar log marginal of the observed steps. |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([0.1, 0.4, 0.3, jnp.nan])
>>> mask = jnp.array([True, True, True, False])
>>> log_marg = prior.log_marginal(y, jnp.asarray(0.1), mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
smooth(y: Float[Array, ' N'], noise_var: Float[Array, ''], *, mask: Bool[Array, ' N'] | None = None) -> tuple[Float[Array, 'N d'], Float[Array, 'N d d'], Float[Array, '']]
¶
Run filter + RTS smoother on the training grid.
Masked steps run the predict only (see filter), so their smoothed
moments are interpolations from the observed neighbours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, ' N']
|
Observations of shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance \(\sigma_n^2\). |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'N d']
|
|
Float[Array, 'N d d']
|
shaped |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> mask = jnp.array([True, False, True, True])
>>> m, P, _ = prior.smooth(jnp.ones(4), jnp.asarray(0.1), mask=mask)
>>> m.shape, P.shape
((4, 2), (4, 2, 2))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
condition(y: Float[Array, ' N'], noise_var: Float[Array, ''], *, mask: Bool[Array, ' N'] | None = None) -> ConditionedMarkovGP
¶
Condition on Gaussian-likelihood observations via filter + smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, ' N']
|
Observations of shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance. |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedMarkovGP
|
The |
ConditionedMarkovGP
|
set to zero. |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> mask = jnp.array([True, False, True, True])
>>> cond = prior.condition(jnp.ones(4), jnp.asarray(0.1), mask=mask)
>>> mean, var = cond.predict(jnp.array([1.0, 5.0]))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
condition_nongauss(likelihood: Likelihood, y: Float[Array, ' N'], *, strategy: _NonGaussMarkovStrategy, mask: Bool[Array, ' N'] | None = None) -> ConditionedNonGaussMarkovGP
¶
Condition on a non-Gaussian likelihood via a site-based strategy.
Convenience that forwards to strategy.fit(self, likelihood, y).
Pick any of the Markov-aware site-based strategies in
pyrox_ssm._inference_nongauss_markov:
pyrox_ssm.LaplaceMarkovInference,
pyrox_ssm.GaussNewtonMarkovInference,
pyrox_ssm.PosteriorLinearizationMarkov, or
pyrox_ssm.ExpectationPropagationMarkov. Returns a
pyrox_ssm.ConditionedNonGaussMarkovGP with the same
predict API as the Gaussian-likelihood
ConditionedMarkovGP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
strategy
|
_NonGaussMarkovStrategy
|
The site-based strategy that fits the sites. |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussMarkovGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> from pyrox_ssm import LaplaceMarkovInference, MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([1.0, 0.0, jnp.nan, 1.0])
>>> cond = prior.condition_nongauss(
... BernoulliLikelihood(), y,
... strategy=LaplaceMarkovInference(),
... mask=jnp.array([True, True, False, True]),
... )
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
log_prob(f: Float[Array, ' N']) -> Float[Array, '']
¶
Log density of an exact-state path \(f(t_n) = H x_n\) under the prior.
Evaluates log N(f | mu(times), K_NN) where K_NN is the dense
Gram of the kernel encoded by sde_kernel on self.times.
Computes the dense covariance via H exp(F |t_i - t_j|) P_inf H^T
— one expm per pairwise lag, costing \(O(N^2 d^3)\) for the
Gram plus \(O(N^3)\) for the Cholesky solve — intended for
sanity checks and small-grid use rather than scalable inference.
For training, prefer log_marginal.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
ConditionedMarkovGP
¶
Bases: Module
Markov GP conditioned on Gaussian-likelihood observations.
Holds the smoothed posterior on the training grid plus the marginal
log-likelihood. Use predict for marginal posterior mean / variance
at arbitrary test times.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
MarkovGPPrior
|
The originating |
y |
Float[Array, ' N']
|
Observations of shape |
noise_var |
Float[Array, '']
|
Observation variance used for conditioning. |
smoothed_means |
Float[Array, 'N d']
|
|
smoothed_covs |
Float[Array, 'N d d']
|
|
log_marginal |
Float[Array, '']
|
Scalar \(\log p(y \mid \theta)\). |
mask |
Bool[Array, ' N'] | None
|
Optional |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 | |
predict(t_star: Float[Array, ' M'], *, include_noise: bool = False) -> tuple[Float[Array, ' M'], Float[Array, ' M']]
¶
Predictive marginals (mean, var) at arbitrary test times.
With include_noise=False (the default) var is the variance of
the latent signal, \(\sigma_*^2\). With include_noise=True it is the
variance of a new observation at each test time,
\(\sigma_*^2 + R\), where \(R\) = noise_var + obs_noise_floor is the
observation variance the posterior was conditioned on. Use it for the
band a withheld observation should fall in. The mean is the same
either way.
Implementation: re-run the filter+smoother over the merged grid
sort(times \\cup t_star) with the test points masked out of the
update step, then read off the smoothed marginals at the test
positions via H @ m and H @ P @ H^T. Cost is
\(O((N + M)\\,d^3)\). Handles training-grid lookups, forecasting,
backcasting, and within-window interpolation under one code path.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
sample(key: PRNGKeyArray, n_paths: int = 1, t_star: Float[Array, ' M'] | None = None) -> Float[Array, 'S M']
¶
Joint draws of the latent path \(f(t_*) \mid y\).
Backward sampling (gaussx.rts_sample) through the filter of
MarkovGPPrior.as_lgssm: the last state from its filtered
distribution, then each state given the next with the smoother's
gain, and \(f(t) = H x(t) + \mu(t)\) read off. Each draw is a whole
path, so a quantity of several times (a maximum over a window, the
length of an exceedance, a total over a season) gets its joint
uncertainty, which predict's marginals cannot give; the
per-time moments of the draws converge to predict's.
With t_star=None the draws are at the training times. Otherwise
the filter runs over the merged grid sort(times ∪ t_star) with
the test times unobserved, as predict does, and the draws are read
off at the test times, in the order given; a test time equal to a
training time sorts after it, so it sees that observation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
PRNGKeyArray
|
PRNG key. |
required |
n_paths
|
int
|
Number of joint draws \(S\). |
1
|
t_star
|
Float[Array, ' M'] | None
|
Optional test times |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'S M']
|
The paths, shaped |
Float[Array, 'S M']
|
mean function included. |
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(6.0))
>>> y = jnp.array([0.1, 0.4, jnp.nan, jnp.nan, 0.3, 0.2])
>>> cond = prior.condition(y, jnp.asarray(0.1), mask=~jnp.isnan(y))
>>> paths = cond.sample(jr.key(0), n_paths=32, t_star=jnp.linspace(1, 4, 7))
>>> paths.shape
(32, 7)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 | |
markov_gp_factor(name: str, prior: MarkovGPPrior, y: Float[Array, ' N'], noise_var: Float[Array, ''], *, mask: Bool[Array, ' N'] | None = None) -> None
¶
Register the collapsed Markov-GP marginal log-likelihood with NumPyro.
Computes log p(y | times, theta) via Kalman filtering and adds it as
numpyro.factor(name, ...). Use this inside a NumPyro model for
Gaussian-likelihood temporal GP regression — the latent function is
marginalized analytically. With a mask, only the observed steps score,
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
MarkovGPPrior
|
The |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
noise_var
|
Float[Array, '']
|
Observation noise variance. |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Examples:
One factor per site over padded ragged series:
>>> import jax
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> def model():
... with numpyro.plate("site", 2):
... ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
... def site(ell_s, t_s, y_s, m_s):
... prior = pss.MarkovGPPrior(pss.MaternSDE(1.0, ell_s, order=1), t_s)
... return prior.log_marginal(y_s, jnp.asarray(0.1), mask=m_s)
... numpyro.factor("y", jax.vmap(site)(ell, t, y, mask).sum())
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
markov_gp_sample(name: str, prior: MarkovGPPrior) -> Float[Array, ' N']
¶
Sample a latent function f at the prior's training times.
Registers a single numpyro.sample(name, MVN(mu, K)) site where K
is the dense Gram derived from the SDE autocovariance
H exp(F|tau|) P_inf H^T. This is the simple, dense path: building
K costs \(O(N^2 d^3)\) and every log-density evaluation an \(O(N^3)\)
Cholesky, so use it when N is a few hundred at most and the kernel
is stationary. For longer series, a non-stationary kernel, or NUTS over
a non-Gaussian likelihood, use markov_gp_innovations_sample, which
builds the same path from whitened innovations in \(O(N d^3)\).
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
Latent paths from whitened innovations¶
When the latent path has to be sampled, as under a Bernoulli or Poisson likelihood with NUTS or SVI, markov_gp_sample builds the dense N × N Gram and pays an O(N^3) Cholesky per evaluation. markov_gp_innovations_sample samples standard normal innovations eps of shape (N, d) as the one site f"{name}_eps" instead and records the path f, built by markov_gp_from_innovations with a scan over the kernel's discretisation, as the deterministic site name. That costs O(N d^3), works for non-stationary kernels such as IntegratedWienerSDE, and is the whitened, non-centred parameterisation NUTS prefers. Keep markov_gp_sample for short series of a stationary kernel. The sqrt= option chooses the square roots of the process noise: "cholesky" (the default, with a small jitter) or "eigh", which also handles a process noise that is only positive semi-definite, as at closely spaced times.
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
def bernoulli_model(times, y):
ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
prior = pss.MarkovGPPrior(pss.MaternSDE(1.0, ell, order=1), times)
f = pss.markov_gp_innovations_sample("f", prior) # (N,)
numpyro.sample("y", dist.Bernoulli(logits=f), obs=y)
markov_gp_from_innovations(prior: MarkovGPPrior, eps: Float[Array, '*batch N d'], *, sqrt: _SqrtMethod = 'cholesky', jitter: float = 1e-10) -> Float[Array, '*batch N']
¶
Latent path of a Markov GP from whitened innovations, in linear time.
With \(\Delta t_k = t_k - t_{k-1}\) and \((A_k, Q_k)\) the kernel's
discretisation over \(\Delta t_k\) (the time convention of
MarkovGPPrior.as_lgssm), the state is run forward from standard
normal innovations \(\varepsilon_k \sim \mathcal{N}(0, I_d)\) by a
jax.lax.scan,
where \(L_0 L_0^\top = P_0\) (MarkovGPPrior.initial_covariance, so
\(P_\infty\) for a stationary kernel) and \(L_{Q,k} L_{Q,k}^\top = Q_k\).
The map \(\varepsilon \mapsto f\) is linear, \(f = \mu + M \varepsilon\)
with \(M M^\top = K\) the prior covariance of the path, so for a
stationary kernel \(f\) has the law markov_gp_sample draws from. Time
is \(O(N d^3)\) and memory \(O(N d^2)\): no \(N \times N\) array is formed,
and a non-stationary kernel such as gaussx.IntegratedWienerSDE works
as well as a stationary one.
Use it as a non-centred parameterisation of the latent path: sample
eps and compute f deterministically, which is what NUTS prefers
and what markov_gp_innovations_sample registers. markov_gp_sample's
dense MultivariateNormal site stays the simpler choice for short
series (a few hundred points) of a stationary kernel.
The square roots are taken by sqrt. \(Q_k\) is only positive
semi-definite when \(\Delta t_k\) is small (it is computed as a
difference, and its round-off can be slightly indefinite) and, for
gaussx.IntegratedWienerSDE, close to singular whenever \(\Delta t_k\)
is small.
"cholesky"(the default):gaussx.choleskyof \(\Sigma + \beta I\) with \(\beta\) =jitter, so each covariance is inflated by \(\beta I\). Cheapest; fine in float64 for the default \(\beta = 10^{-10}\) unless the round-off in \(Q_k\) exceeds \(\beta\) (large variances, very short lengthscales), when the factor turnsNaN."eigh": the symmetric root \(Q \operatorname{diag}(\sqrt{\max(\gamma, 0)}) Q^\top\) fromgaussx.sqrt(a denseeighwith a Sylvester-equation derivative). It clips negative round-off, needs no jitter and is exact for a singular \(Q_k\), so it is the one that handles a \(Q_k\) that is only positive semi-definite, and the one to use in float32.jitteris ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
MarkovGPPrior
|
The |
required |
eps
|
Float[Array, '*batch N d']
|
Standard normal innovations of shape |
required |
sqrt
|
_SqrtMethod
|
How the covariance square roots are taken, |
'cholesky'
|
jitter
|
float
|
The diagonal \(\beta\) added before the Cholesky factor. |
1e-10
|
Returns:
| Type | Description |
|---|---|
Float[Array, '*batch N']
|
The path \(f(t_1), \dots, f(t_N)\), shape |
Float[Array, '*batch N']
|
included. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the trailing shape of |
Examples:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import pyrox_ssm as pss
>>> times = jnp.linspace(0.0, 10.0, 500)
>>> prior = pss.MarkovGPPrior(pss.MaternSDE(1.0, 0.5, order=1), times)
>>> eps = jr.normal(jr.key(0), (500, prior.state_dim))
>>> f = pss.markov_gp_from_innovations(prior, eps)
>>> f.shape
(500,)
>>> eps_batch = jr.normal(jr.key(1), (8, 500, prior.state_dim))
>>> paths = pss.markov_gp_from_innovations(prior, eps_batch)
>>> paths.shape
(8, 500)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 | |
markov_gp_innovations_sample(name: str, prior: MarkovGPPrior, *, sqrt: _SqrtMethod = 'cholesky', jitter: float = 1e-10) -> Float[Array, ' N']
¶
Sample a Markov-GP latent path through whitened innovations.
Registers the innovations as one sample site and the path, built from
them by markov_gp_from_innovations, as a deterministic one,
so the path costs \(O(N d^3)\) per model evaluation instead of the
\(O(N^3)\) Cholesky of markov_gp_sample, and NUTS sees a whitened,
non-centred parameterisation. Use it for long series, non-stationary
kernels, and non-Gaussian likelihoods sampled with NUTS or fitted with
SVI; keep markov_gp_sample for short series of a stationary kernel.
The sqrt and jitter options are those of
markov_gp_from_innovations; "eigh" handles a process noise \(Q_k\)
that is only positive semi-definite (closely spaced times,
gaussx.IntegratedWienerSDE).
It registers two sites, unscoped like markov_gp_sample's:
f"{name}_eps", the innovations:Normal(0, 1)of shape(N, d)with both dimensions in the event (.expand([N, d]).to_event(2));name, anumpyro.deterministicholding the path of shape(N,), sonumpyro.infer.Predictivereturns it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The deterministic site's name; the innovations site is
|
required |
prior
|
MarkovGPPrior
|
The |
required |
sqrt
|
_SqrtMethod
|
How the covariance square roots are taken, |
'cholesky'
|
jitter
|
float
|
The diagonal added before the Cholesky factor. |
1e-10
|
Returns:
| Type | Description |
|---|---|
Float[Array, ' N']
|
The path \(f(t_1), \dots, f(t_N)\), shape |
Float[Array, ' N']
|
|
Float[Array, ' N']
|
independent path per plate index. |
Examples:
A Bernoulli series with a latent Matérn-3/2 path:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import numpyro
>>> import numpyro.distributions as dist
>>> from numpyro.infer import MCMC, NUTS
>>> import pyrox_ssm as pss
>>> times = jnp.linspace(0.0, 10.0, 200)
>>> y = (jnp.sin(times) > 0).astype(jnp.int32)
>>> def model(times, y):
... ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
... sde = pss.MaternSDE(variance=1.0, lengthscale=ell, order=1)
... f = pss.markov_gp_innovations_sample("f", pss.MarkovGPPrior(sde, times))
... numpyro.sample("y", dist.Bernoulli(logits=f), obs=y)
>>> mcmc = MCMC(
... NUTS(model), num_warmup=100, num_samples=100, progress_bar=False
... )
>>> mcmc.run(jr.key(0), times, y)
>>> mcmc.get_samples()["f"].shape
(100, 200)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 | |
Ragged sites¶
Every method that reads observations (filter, smooth, log_marginal, condition, condition_nongauss, markov_gp_factor, each non-Gaussian strategy's fit, sparse_markov_elbo and sparse_markov_factor) takes an optional boolean mask= of the observations' shape. A masked step runs the Kalman predict only, so it adds nothing to the log marginal, and its observation is replaced before any arithmetic, so a NaN placeholder there reaches neither the value nor the gradient. mask=None is the unmasked result, bit for bit.
Sites observed on different days become one vmapped factor with pad_sites, which pads each series after its last observation (at its median spacing, so the padded times stay strictly increasing) and returns the mask. Padding after the last observation adds predict-only steps, so each site's log marginal is unchanged:
import jax
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
t, y, mask = pss.pad_sites(times_per_site, y_per_site) # (S, N) each
def site_log_marginal(ell_s, t_s, y_s, m_s):
sde = pss.MaternSDE(variance=1.0, lengthscale=ell_s, order=1)
return pss.MarkovGPPrior(sde, t_s).log_marginal(y_s, jnp.asarray(0.01), mask=m_s)
def pooled_model(t, y, mask):
mu = numpyro.sample("mu", dist.Normal(0.0, 1.0))
with numpyro.plate("site", t.shape[0]):
ell = numpyro.sample("lengthscale", dist.LogNormal(mu, 0.5)) # (S,)
numpyro.factor("y", jax.vmap(site_log_marginal)(ell, t, y, mask).sum())
markov_gp_sites_factor writes that factor in one call. It takes one kernel whose array leaves carry the leading site axis (a scalar leaf is shared by every site), the (S, N) arrays from pad_sites, and a shared or per-site noise variance:
def pooled_model(t, y, mask):
mu = numpyro.sample("mu", dist.Normal(0.0, 1.0))
with numpyro.plate("site", t.shape[0]):
ell = numpyro.sample("lengthscale", dist.LogNormal(mu, 0.5)) # (S,)
kernel = pss.MaternSDE(variance=1.0, lengthscale=ell, order=1)
pss.markov_gp_sites_factor("y", kernel, t, y, jnp.asarray(0.01), mask=mask)
The factor registers MarkovGPSitesPrior(kernel, t, mask=mask).log_marginal(y, noise_var). After a fit, build that prior with the fitted kernel to predict every site at once: condition(y, noise_var) runs each site's filter and smoother, and the ConditionedMarkovGPSites it returns gives predict(t_star), each site's mean and variance shaped (S, M), at the same (M,) times for every site or at an (S, M) row per site. A mean function follows the kernel's rule: a plain function is shared, and an eqx.Module mean whose array leaves carry the leading (S,) axis gives each site its own mean:
prior = pss.MarkovGPSitesPrior(kernel, t, mask=mask)
mean, var = prior.condition(y, jnp.asarray(0.01)).predict(t_star) # (S, M) each
Per-site hyperparameters drawn around a population value with an unknown spread give NUTS a funnel when the spread is small. noncentred_log_normal samples a standard normal f"{name}_z" per site under the plate and records exp(loc + scale * z) as the deterministic site name:
with numpyro.plate("site", t.shape[0]):
ell = pss.noncentred_log_normal("lengthscale", ell_loc, ell_scale) # (S,)
pad_sites(times: Sequence[Float[Array, ' N_s']], ys: Sequence[Float[Array, ' N_s']], *, masks: Sequence[Bool[Array, ' N_s']] | None = None, length: int | None = None) -> tuple[Float[Array, 'S N'], Float[Array, 'S N'], Bool[Array, 'S N']]
¶
Pad ragged site series to (S, N) with strictly increasing padded times.
Site \(s\) with \(N_s\) observations at times \(t_1 < \dots < t_{N_s}\) is extended to length \(N\) by stepping on from its last observation at its median spacing,
with \(\delta_s = 1\) for a site with one observation. The padded steps are masked, and a masked step runs the Kalman predict only,
so it adds nothing to the log marginal: padding after the last
observation changes no site's log marginal or smoothed moments at its
observed steps. The padded times stay strictly increasing, so the
monotonicity check and the kernel discretisation are unchanged. Padded
entries of y are zero.
Missing steps inside a record are masked the same way, so a record on a
regular grid with gaps can be passed as it is: a step is masked where
masks is False or, by default, where y is NaN. A masked
step runs the predict step only, as a padded one does, so the site's log
marginal equals that of the same site with those steps dropped. Masked
entries of y are zero, as padded ones are.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
times
|
Sequence[Float[Array, ' N_s']]
|
One strictly increasing |
required |
ys
|
Sequence[Float[Array, ' N_s']]
|
One |
required |
masks
|
Sequence[Bool[Array, ' N_s']] | None
|
Optional |
None
|
length
|
int | None
|
Padded length \(N\). Defaults to the longest site, \(\max_s N_s\). |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'S N']
|
Tuple |
Float[Array, 'S N']
|
the padded observations and a boolean mask that is |
Bool[Array, 'S N']
|
row's observed steps: its first \(N_s\) steps less any masked ones. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no site is given, if |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> times = [jnp.array([0.0, 1.0, 3.0]), jnp.array([0.5, 1.0])]
>>> ys = [jnp.array([0.2, 0.1, -0.3]), jnp.array([1.0, 0.8])]
>>> t, y, mask = pss.pad_sites(times, ys)
>>> t.tolist()
[[0.0, 1.0, 3.0], [0.5, 1.0, 1.5]]
>>> mask.tolist()
[[True, True, True], [True, True, False]]
>>> def site_log_marginal(t_s, y_s, m_s):
... prior = pss.MarkovGPPrior(pss.MaternSDE(1.0, 1.0, order=1), t_s)
... return prior.log_marginal(y_s, jnp.asarray(0.1), mask=m_s)
>>> jax.vmap(site_log_marginal)(t, y, mask).shape
(2,)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 | |
MarkovGPSitesPrior
¶
Bases: Module
A Markov GP prior over \(S\) padded sites that share one SDE kernel.
Site \(s\) is an independent Markov GP over its own row of times, with
kernel \(\theta_s\) and noise variance \(\sigma_s^2\), so the log marginal of
the sites is the sum of theirs,
each term pyrox_ssm.MarkovGPPrior.log_marginal over the site's masked
padded series. times and mask are the (S, N) arrays that
pyrox_ssm.pad_sites returns; padding after a site's last observation
adds predict-only steps, so it changes neither the site's log marginal
nor its predictions.
One kernel per site is one kernel whose array leaves carry a leading
(S,) axis, such as MaternSDE(variance, lengthscale, order=1) with
(S,) arrays; a 0-d leaf is shared by every site. The mean function
follows the same rule: a plain function, or a module whose array leaves
are 0-d, is shared, and a module (an eqx.Module) whose array leaves
carry a leading (S,) axis gives each site its own mean.
obs_noise_floor is shared by every site. The prior registers no
NumPyro sites; markov_gp_sites_factor adds its log marginal as one
factor.
Attributes:
| Name | Type | Description |
|---|---|---|
sde_kernel |
SDEKernel
|
An |
times |
Float[Array, 'S N']
|
|
mask |
Bool[Array, 'S N'] | None
|
Optional |
mean_fn |
Callable[[Float[Array, ' N']], Float[Array, ' N']] | None
|
Optional mean function |
obs_noise_floor |
float
|
Extra observation variance, as in
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> kernel = pss.MaternSDE(1.0, jnp.array([0.5, 2.0]), order=1)
>>> prior = pss.MarkovGPSitesPrior(kernel, t, mask=mask)
>>> log_marg = prior.log_marginal(y, jnp.asarray(0.1))
>>> cond = prior.condition(y, jnp.asarray(0.1))
>>> mean, var = cond.predict(jnp.array([1.5, 6.0]))
>>> mean.shape
(2, 2)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 | |
n_sites: int
property
¶
Number of sites \(S\).
log_marginal(y: Float[Array, 'S N'], noise_var: Float[Array, ''] | Float[Array, ' S']) -> Float[Array, '']
¶
Summed log marginal of the sites' observed steps.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'S N']
|
|
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, shared |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar log marginal. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> prior = pss.MarkovGPSitesPrior(pss.MaternSDE(1.0, 1.0), t, mask=mask)
>>> log_marg = prior.log_marginal(y, jnp.array([0.1, 0.2]))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
condition(y: Float[Array, 'S N'], noise_var: Float[Array, ''] | Float[Array, ' S']) -> ConditionedMarkovGPSites
¶
Condition every site on its observations, by its filter and smoother.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'S N']
|
|
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, shared |
required |
Returns:
| Type | Description |
|---|---|
ConditionedMarkovGPSites
|
The |
ConditionedMarkovGPSites
|
moments, with |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> prior = pss.MarkovGPSitesPrior(pss.MaternSDE(1.0, 1.0), t, mask=mask)
>>> cond = prior.condition(y, jnp.asarray(0.1))
>>> cond.smoothed_means.shape
(2, 5, 1)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
ConditionedMarkovGPSites
¶
Bases: Module
A MarkovGPSitesPrior conditioned on every site's observations.
Returned by MarkovGPSitesPrior.condition. Holds each site's smoothed
moments on its padded grid; predict gives every site's marginal mean and
variance at any times, as pyrox_ssm.ConditionedMarkovGP.predict does for
one site.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
MarkovGPSitesPrior
|
The originating |
y |
Float[Array, 'S N']
|
|
noise_var |
Float[Array, ''] | Float[Array, ' S']
|
The noise variance conditioned on, |
smoothed_means |
Float[Array, 'S N d']
|
|
smoothed_covs |
Float[Array, 'S N d d']
|
|
site_log_marginals |
Float[Array, ' S']
|
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
log_marginal: Float[Array, '']
property
¶
The summed log marginal, equal to MarkovGPSitesPrior.log_marginal.
predict(t_star: Float[Array, ' M'] | Float[Array, 'S M'], *, include_noise: bool = False) -> tuple[Float[Array, 'S M'], Float[Array, 'S M']]
¶
Every site's predictive marginals (mean, var) at t_star.
Site \(s\) is predicted as pyrox_ssm.ConditionedMarkovGP.predict
predicts one site: its filter and smoother rerun over the merged grid
of its padded times and the test times, with the test times
unobserved. With include_noise=True the variance is that of a new
observation, \(\sigma_*^2 + \sigma_s^2\) plus obs_noise_floor.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t_star
|
Float[Array, ' M'] | Float[Array, 'S M']
|
Test times, |
required |
include_noise
|
bool
|
Add the site's observation variance. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, 'S M'], Float[Array, 'S M']]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> prior = pss.MarkovGPSitesPrior(pss.MaternSDE(1.0, 1.0), t, mask=mask)
>>> cond = prior.condition(y, jnp.asarray(0.1))
>>> mean, var = cond.predict(jnp.linspace(0.0, 6.0, 7))
>>> mean.shape
(2, 7)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 | |
markov_gp_sites_factor(name: str, sde_kernel: SDEKernel, times: Float[Array, 'S N'], y: Float[Array, 'S N'], noise_var: Float[Array, ''] | Float[Array, ' S'], *, mask: Bool[Array, 'S N'] | None = None, mean_fn: Callable[[Float[Array, ' N']], Float[Array, ' N']] | None = None, obs_noise_floor: float = 0.0) -> None
¶
Register the summed Markov-GP log marginal of S sites as one factor.
The multi-site form of markov_gp_factor, for the (S, N) padded
times, observations and mask that pyrox_ssm.pad_sites returns. Site
\(s\) has its own kernel \(\theta_s\) and noise variance \(\sigma_s^2\), and the
sites are independent given them, so the factor is
each term the masked Kalman log marginal of MarkovGPPrior.log_marginal.
It replaces the hand-written jax.vmap over sites shown in
markov_gp_factor's example, and is one numpyro.factor site, so it
composes with NUTS and SVI as that pattern does. It registers
MarkovGPSitesPrior(sde_kernel, times, mask=mask, ...).log_marginal(y,
noise_var); build that prior to condition and predict after a fit.
One kernel per site is one kernel whose array leaves carry a leading
(S,) axis, such as MaternSDE(variance, lengthscale, order=1) with
(S,) arrays sampled under a numpyro.plate over sites. A 0-d leaf
(a Python float or a scalar array) is shared by every site.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
sde_kernel
|
SDEKernel
|
An |
required |
times
|
Float[Array, 'S N']
|
|
required |
y
|
Float[Array, 'S N']
|
|
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, shared |
required |
mask
|
Bool[Array, 'S N'] | None
|
Optional |
None
|
mean_fn
|
Callable[[Float[Array, ' N']], Float[Array, ' N']] | None
|
Optional mean function, as in |
None
|
obs_noise_floor
|
float
|
Extra observation variance, as in |
0.0
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> def model():
... with numpyro.plate("site", 2):
... ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
... kernel = pss.MaternSDE(1.0, ell, order=1)
... noise = jnp.asarray(0.1)
... pss.markov_gp_sites_factor("y", kernel, t, y, noise, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
noncentred_log_normal(name: str, loc: Float[Array, ' *batch'] | float, scale: Float[Array, ' *batch'] | float) -> Float[Array, ' *batch']
¶
A positive per-site parameter around a population value, non-centred.
Site \(n\)'s parameter \(\theta_n\) (a lengthscale, a variance) is log-normal around a population log-mean \(m\) with spread \(\tau\),
which has the distribution of the centred form
\(\log \theta_n \sim \mathcal{N}(m, \tau^2)\). The sampler sees \(z_n\), which
is independent of \(\tau\) a priori, instead of \(\log \theta_n\), whose
spread shrinks with \(\tau\). That removes the funnel NUTS meets when \(\tau\)
is small, the usual case for sites that differ little. NumPyro's
LocScaleReparam(centered=0) does the same rewrite on a centred
Normal site through a reparam handler; this helper writes it out and
names its sites predictably.
Call it inside the numpyro.plate over sites, so there is one \(z_n\) per
site; loc and scale broadcast against the plate.
Registers the sample site f"{name}_z" (standard normal) and the
deterministic site name (\(\theta_n\), so its posterior is in the
trace).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
Name of the deterministic site; the sample site is
|
required |
loc
|
Float[Array, ' *batch'] | float
|
Population log-mean \(m\). |
required |
scale
|
Float[Array, ' *batch'] | float
|
Population log-spread \(\tau > 0\). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, ' *batch']
|
\(\theta_n = \exp(m + \tau z_n)\), shaped by the enclosing plates. |
Examples:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> t, y, mask = pss.pad_sites(
... [jnp.arange(5.0), jnp.arange(3.0)], [jnp.ones(5), jnp.zeros(3)]
... )
>>> def model():
... loc = numpyro.sample("lengthscale_loc", dist.Normal(jnp.log(7.0), 1.0))
... scale = numpyro.sample("lengthscale_scale", dist.HalfNormal(0.5))
... with numpyro.plate("site", 2):
... ell = pss.noncentred_log_normal("lengthscale", loc, scale)
... kernel = pss.MaternSDE(1.0, ell, order=1)
... noise = jnp.asarray(0.1)
... pss.markov_gp_sites_factor("y", kernel, t, y, noise, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
A shared GP plus one GP per site¶
When the sites share a regional signal, y_s(t) = g(t) + h_s(t) + eps_s(t) with one shared GP g and an independent GP h_s per site is one linear-Gaussian SSM on the merged grid of all site times: SharedPlusSiteMarkovGPPrior.from_sites merges the ragged series (NaN and a (T, S) mask where a site was not observed), as_lgssm builds the block-diagonal transitions and the observation rows H[s] = (H_g, 0, …, H_h at block s, …, 0), log_marginal is the exact log marginal of the observed pairs, which shared_plus_site_factor adds to a NumPyro model, and decompose splits the smoothed means into E[g | y] and E[h_s | y]. The site kernel's hyperparameters are pooled (scalar leaves) or per site (leaves with a leading axis of length S), and each pass costs O(T D^3) with D = d_g + S d_h, so it suits a few dozen sites:
import jax.numpy as jnp
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
shared = pss.MaternSDE(variance=1.0, lengthscale=30.0, order=1)
site = pss.MaternSDE(variance=jnp.full(S, 0.3), lengthscale=5.0, order=1) # per-site variance
model, y_grid = pss.SharedPlusSiteMarkovGPPrior.from_sites(shared, site, times_per_site, y_per_site)
def regional_model(y_grid):
noise_var = numpyro.sample("noise_var", dist.LogNormal(-3.0, 1.0))
pss.shared_plus_site_factor("y", model, y_grid, noise_var)
g_mean, h_mean = model.decompose(y_grid, jnp.asarray(0.05)) # (T,), (T, S)
decompose(..., return_var=True) also returns the marginal variances V[g | y] and V[h_s | y] from the same smoother pass. The two parts are correlated a posteriori, so their variances do not add to that of g + h_s. A known per-site mean, such as a station climatology, goes in as mean_fn, a callable from the (T,) grid to (T, S) means. It is the observation offset of as_lgssm, so the model fits raw readings and its log marginal equals that of the anomalies y - mean. A ConstantSDE term in the site kernel instead integrates an unknown level out.
To predict at times no site observed, such as a gap or a forecast, condition once and call predict, which adds the test times to the grid as unobserved rows:
cond = model.condition(y_grid, jnp.asarray(0.05))
g_mean, h_mean, g_var, h_var = cond.predict(t_star) # (M,), (M, S), (M,), (M, S)
from_sites takes the union of the site times with jnp.unique, so it needs concrete times. Inside jax.jit or a NumPyro model under NUTS, build the grid and mask once outside and construct the model with SharedPlusSiteMarkovGPPrior(shared, site, times, mask) from the sampled kernels.
SharedPlusSiteMarkovGPPrior
¶
Bases: Module
A shared GP plus one independent GP per site, on a merged time grid.
Site \(s = 1, \dots, S\) is observed on its own days as
with \(g\), \(h_1, \dots, h_S\) independent and \(\mu_s\) an optional known
per-site mean (mean_fn, zero by default). Every kernel is an SDE kernel
with state \(x_g \in \mathbb{R}^{d_g}\) or \(x_{h,s} \in \mathbb{R}^{d_h}\),
and the joint state on the merged grid \(t_1 < \dots < t_T\) stacks them,
as_lgssm returns that model as a pyrox_ssm.LinearGaussianSSMPrior
with block-diagonal transitions, process noise and initial covariance,
observation rows \(H[s] = (H_g, 0, \dots, H_h \text{ at block } s,
\dots, 0)\) and \(R = \mathrm{diag}(\sigma_{n,1}^2, \dots,
\sigma_{n,S}^2)\). mask[k, s] says whether site \(s\) was observed at
\(t_k\); an unobserved entry is marginalised out exactly, so the log
marginal is that of the observed \((t, s)\) pairs under the dense
Gaussian with covariance \(K = K_g \otimes \mathbf{1}\mathbf{1}^\top +
\mathrm{blockdiag}_s(K_{h,s}) + \mathrm{diag}(\sigma_{n,s}^2)\).
The site kernel's array leaves are either scalars, shared by every site
(pooled hyperparameters), or carry a leading axis of length \(S\)
(per-site hyperparameters); the two may be mixed, for example a
per-site variance with a pooled lengthscale. \(S\) is mask.shape[1].
Each site's discretisation runs once, under jax.vmap over the
batched leaves, or once in total when every leaf is pooled.
Cost: each filter or smoother pass is \(O(T D^3)\), cubic in the number
of sites. Beyond a few dozen sites \(D^3\) dominates. Two cheaper routes
exist: gaussx's meanfield_kalman_filter and
meanfield_rts_smoother run independent filters on the diagonal
state blocks at \(O(T L d^3)\) for \(L\) blocks of size \(d\), dropping every
cross-block covariance; that projection is exact only when the blocks
do not couple, and here every site couples \(g\) to \(h_s\) through the
observation, so it is an approximation that ignores the posterior
correlation between the shared and the site parts. An ensemble Kalman
filter (filterax) keeps that correlation at the price of Monte Carlo
error in the covariances.
The per-site mean \(\mu_s(t)\) (a station climatology, an offset) enters
as_lgssm as the observation offset, so it shifts the observations and
leaves every covariance unchanged: the log marginal is that of the
anomalies \(y - \mu\), and gradients flow to whatever parameters
mean_fn closes over. That is a fixed shift, given its parameters; a
pyrox_ssm.ConstantSDE term in the site kernel instead integrates an
unknown level out.
To predict at times no site observed (a gap, a forecast), condition once
and call predict: model.condition(y, noise_var).predict(t_star)
adds the test times to the grid as unobserved rows. from_sites takes
the union of the site times with jnp.unique, so it needs concrete
times and runs outside jax.jit. A model rebuilt from sampled kernels
inside jax.jit or a NumPyro model under NUTS uses the constructor with
a grid and mask computed once outside, for example the times and
mask of one from_sites call made before sampling.
The model registers no NumPyro sites; wrap log_marginal in
numpyro.factor (or pass as_lgssm to pyrox_ssm.lgssm_factor).
Shapes are checked at construction, and concrete times must be
strictly increasing (a traced times is trusted, as in
pyrox_ssm.MarkovGPPrior).
Attributes:
| Name | Type | Description |
|---|---|---|
shared |
SDEKernel
|
The SDE kernel \(k_g\) of the shared GP. |
site |
SDEKernel
|
The SDE kernel \(k_h\) of the site GPs; each array leaf is a scalar (pooled) or has a leading axis of length \(S\) (per site). |
times |
Float[Array, ' T']
|
Merged, strictly increasing grid, shaped |
mask |
Bool[Array, 'T S']
|
Boolean |
mean_fn |
Callable[[Float[Array, ' T']], Float[Array, 'T S']] | None
|
Optional callable mapping times |
Examples:
Three sites on ragged days, a per-site variance and a pooled lengthscale:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> t_per_site = [jnp.array([0.0, 1.0, 3.0]), jnp.array([1.0, 2.0]),
... jnp.array([0.0, 2.0, 3.0])]
>>> y_per_site = [jnp.array([0.2, 0.1, -0.3]), jnp.array([0.4, 0.0]),
... jnp.array([0.1, -0.2, 0.3])]
>>> shared = pss.MaternSDE(variance=1.0, lengthscale=2.0, order=1)
>>> site = pss.MaternSDE(variance=jnp.array([0.3, 0.5, 0.2]),
... lengthscale=0.5, order=1)
>>> model, y_grid = pss.SharedPlusSiteMarkovGPPrior.from_sites(
... shared, site, t_per_site, y_per_site
... )
>>> y_grid.shape, model.state_dim
((4, 3), 8)
>>> log_marg = model.log_marginal(y_grid, jnp.asarray(0.01))
>>> g_mean, h_mean = model.decompose(y_grid, jnp.asarray(0.01))
>>> g_mean.shape, h_mean.shape
((4,), (4, 3))
Inside a NumPyro model, the log marginal is a factor:
>>> def numpyro_model(y_grid):
... noise_var = numpyro.sample("noise_var", dist.LogNormal(-3.0, 1.0))
... numpyro.factor("y", model.log_marginal(y_grid, noise_var))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 | |
n_sites: int
property
¶
Number of sites \(S\), mask.shape[1].
state_dim: int
property
¶
Joint state dimension \(D = d_g + S d_h\).
from_sites(shared: SDEKernel, site: SDEKernel, times_per_site: Sequence[Float[Array, ' N_s']], y_per_site: Sequence[Float[Array, ' N_s']], mean_fn: Callable[[Float[Array, ' T']], Float[Array, 'T S']] | None = None) -> tuple[SharedPlusSiteMarkovGPPrior, Float[Array, 'T S']]
classmethod
¶
Merge ragged site series onto one grid and build the model.
The grid is the sorted union of the site times,
\(\{t_1 < \dots < t_T\} = \bigcup_s \{t_{s,1}, \dots, t_{s,N_s}\}\);
site \(s\)'s observations land in column \(s\) at their own times, and
every other entry is NaN and masked. Where pyrox_ssm.pad_sites
pads each site on its own axis for a vmapped per-site factor, this
lays every site on the shared axis that the shared GP needs. The
union is taken with jnp.unique, so the times must be concrete
(call it outside jax.jit).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shared
|
SDEKernel
|
The SDE kernel \(k_g\) of the shared GP. |
required |
site
|
SDEKernel
|
The SDE kernel \(k_h\) of the site GPs (scalar leaves pooled, leaves with a leading axis of length \(S\) per site). |
required |
times_per_site
|
Sequence[Float[Array, ' N_s']]
|
One strictly increasing |
required |
y_per_site
|
Sequence[Float[Array, ' N_s']]
|
One |
required |
mean_fn
|
Callable[[Float[Array, ' T']], Float[Array, 'T S']] | None
|
Optional per-site mean, as in the class. |
None
|
Returns:
| Type | Description |
|---|---|
SharedPlusSiteMarkovGPPrior
|
|
Float[Array, 'T S']
|
its |
tuple[SharedPlusSiteMarkovGPPrior, Float[Array, 'T S']]
|
where a site was not observed. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If no site is given, if the two sequences differ in length, if a site is not a non-empty 1-D series matching its observations, or if a site's times are not strictly increasing. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=0)
>>> model, y_grid = pss.SharedPlusSiteMarkovGPPrior.from_sites(
... kernel, kernel,
... [jnp.array([0.0, 2.0]), jnp.array([1.0, 2.0])],
... [jnp.array([0.5, 0.1]), jnp.array([0.3, 0.2])],
... )
>>> model.times.tolist(), model.mask.tolist()
([0.0, 1.0, 2.0], [[True, False], [False, True], [True, True]])
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 | |
as_lgssm(noise_var: Float[Array, ''] | Float[Array, ' S']) -> LinearGaussianSSMPrior
¶
This model as a pyrox_ssm.LinearGaussianSSMPrior over \(D\) states.
With \(\Delta t_1 = 0\) and \(\Delta t_k = t_k - t_{k-1}\), as in
pyrox_ssm.MarkovGPPrior.as_lgssm,
each block from its kernel's discretisation over \(\Delta t_k\), so
\(A_1 = I\) and \(Q_1 = 0\) and the first observation sees the initial
state. \(m_0 = 0\), \(P_0\) is the block diagonal of each kernel's
initial_covariance() (\(P_\infty\) for a stationary kernel), the
time-invariant observation matrix is the (S, D) stack of rows
\(H[s] = (H_g, 0, \dots, H_h \text{ at block } s, \dots, 0)\) and
\(R = \mathrm{diag}(\sigma_{n,1}^2, \dots, \sigma_{n,S}^2)\). With a
mean_fn, its (T, S) values on the grid are the observation
offset \(b_k\).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, a scalar shared by every
site or one per site, shaped |
required |
Returns:
| Type | Description |
|---|---|
LinearGaussianSSMPrior
|
The |
LinearGaussianSSMPrior
|
dimension \(D = d_g + S d_h\) and \(S\) outputs; filter it with |
LinearGaussianSSMPrior
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=1)
>>> model = pss.SharedPlusSiteMarkovGPPrior(
... kernel, kernel, jnp.arange(5.0), jnp.ones((5, 3), dtype=bool)
... )
>>> lgssm = model.as_lgssm(jnp.array([0.1, 0.2, 0.1]))
>>> lgssm.transition.shape, lgssm.obs_model.shape
((5, 8, 8), (3, 8))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 | |
log_marginal(y: Float[Array, 'T S'], noise_var: Float[Array, ''] | Float[Array, ' S']) -> Float[Array, '']
¶
Marginal log-likelihood of the observed \((t, s)\) pairs.
with \(o_k\) the sites observed at \(t_k\) (mask[k]), equal to the
dense Gaussian over the observed pairs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T S']
|
Observations, shaped |
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, scalar or |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar log marginal. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=0)
>>> mask = jnp.array([[True, False], [True, True]])
>>> times = jnp.arange(2.0)
>>> model = pss.SharedPlusSiteMarkovGPPrior(kernel, kernel, times, mask)
>>> y = jnp.array([[0.3, jnp.nan], [0.1, -0.2]])
>>> log_marg = model.log_marginal(y, jnp.asarray(0.1))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
decompose(y: Float[Array, 'T S'], noise_var: Float[Array, ''] | Float[Array, ' S'], *, return_var: bool = False) -> tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]
¶
Posterior means, and optionally variances, of the shared and site GPs.
Runs the Kalman filter and RTS smoother on as_lgssm and reads the
blocks of the smoothed state mean \(\hat{x}_k = \mathbb{E}[x_k \mid y]\),
so the two sum to the posterior mean of site \(s\)'s signal,
\(\mathbb{E}[g(t_k) + h_s(t_k) \mid y] = H[s] \hat{x}_k\). With
return_var=True the marginal variances come from the same
smoothed state covariance \(\hat{P}_k\),
The two parts are correlated a posteriori (one observation informs
both), so their variances do not add to the variance of
\(g + h_s\), \(H[s] \hat{P}_k H[s]^\top\). The RTS smoother solves
against the predicted state covariance, so a kernel of exactly zero
variance (a singular block) gives NaN here; log_marginal is unaffected.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T S']
|
Observations, shaped |
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, scalar or |
required |
return_var
|
bool
|
Also return the marginal variances. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]
|
|
tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]
|
|
tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]
|
|
tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]
|
variances shaped like the means. |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=0)
>>> mask = jnp.array([[True, False], [True, True]])
>>> times = jnp.arange(2.0)
>>> model = pss.SharedPlusSiteMarkovGPPrior(kernel, kernel, times, mask)
>>> y = jnp.array([[0.3, jnp.nan], [0.1, -0.2]])
>>> g_mean, h_mean = model.decompose(y, jnp.asarray(0.1))
>>> g_mean.shape, h_mean.shape
((2,), (2, 2))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
condition(y: Float[Array, 'T S'], noise_var: Float[Array, ''] | Float[Array, ' S']) -> ConditionedSharedPlusSiteMarkovGP
¶
Condition on the observations, to predict \(g\) and \(h_s\) at any times.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T S']
|
Observations on the grid, |
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, scalar or |
required |
Returns:
| Type | Description |
|---|---|
ConditionedSharedPlusSiteMarkovGP
|
A |
ConditionedSharedPlusSiteMarkovGP
|
gives the posterior marginals of the shared and site signals. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=0)
>>> mask = jnp.array([[True, False], [True, True]])
>>> times = jnp.arange(2.0)
>>> model = pss.SharedPlusSiteMarkovGPPrior(kernel, kernel, times, mask)
>>> y = jnp.array([[0.3, jnp.nan], [0.1, -0.2]])
>>> cond = model.condition(y, jnp.asarray(0.1))
>>> g_mean, h_mean, g_var, h_var = cond.predict(jnp.array([0.5, 3.0]))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
ConditionedSharedPlusSiteMarkovGP
¶
Bases: Module
A SharedPlusSiteMarkovGPPrior conditioned on its observations.
Returned by SharedPlusSiteMarkovGPPrior.condition. predict gives the
posterior marginals of the shared signal \(g\) and of each site's signal
\(h_s\) at any times: observed days, gaps no site observed, and forecasts
or backcasts beyond the grid.
Attributes:
| Name | Type | Description |
|---|---|---|
model |
SharedPlusSiteMarkovGPPrior
|
The conditioned |
y |
Float[Array, 'T S']
|
Observations on the model's grid, |
noise_var |
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, scalar or |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 | |
predict(t_star: Float[Array, ' M']) -> tuple[Float[Array, ' M'], Float[Array, 'M S'], Float[Array, ' M'], Float[Array, 'M S']]
¶
Posterior marginals of \(g\) and every \(h_s\) at the test times.
The test times join the grid as rows with no observed site, the
sorted union \(t_{1:T} \cup t^*_{1:M}\), and one filter and smoother
pass over that grid gives SharedPlusSiteMarkovGPPrior.decompose's means
and variances at every row; the test rows are read off. An
unobserved row runs the Kalman predict only, so the log marginal and
the posterior at the observed rows are unchanged, and a test time
equal to a grid time sees that time's observations. Cost is
\(O((T + M) D^3)\). The test times need not be sorted or distinct, and
the method traces, so it runs under jax.jit given a model built
with the constructor.
With a stationary kernel a test time before the grid is a backcast
from the stationary prior. A non-stationary kernel, such as
pyrox_ssm.IntegratedWienerSDE, starts its prior covariance at the
first grid time, so a test time before it would move that start and
change the posterior at the observed times; predict raises
instead. Build the model on a grid that starts early enough.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
t_star
|
Float[Array, ' M']
|
Test times, |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, ' M']
|
|
Float[Array, 'M S']
|
signal's mean and variance, |
Float[Array, ' M']
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
EquinoxRuntimeError
|
If a kernel is non-stationary and a test
time is before the first grid time (checked at run time, so
also under |
Examples:
>>> import jax.numpy as jnp
>>> import pyrox_ssm as pss
>>> kernel = pss.MaternSDE(variance=1.0, lengthscale=1.0, order=0)
>>> mask = jnp.array([[True, False], [True, True]])
>>> times = jnp.arange(2.0)
>>> model = pss.SharedPlusSiteMarkovGPPrior(kernel, kernel, times, mask)
>>> y = jnp.array([[0.3, jnp.nan], [0.1, -0.2]])
>>> cond = model.condition(y, jnp.asarray(0.1))
>>> g_mean, h_mean, g_var, h_var = cond.predict(jnp.array([0.5, 3.0]))
>>> g_mean.shape, h_mean.shape
((2,), (2, 2))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 | |
shared_plus_site_factor(name: str, prior: SharedPlusSiteMarkovGPPrior, y: Float[Array, 'T S'], noise_var: Float[Array, ''] | Float[Array, ' S']) -> None
¶
Register the log marginal of a shared GP plus one GP per site.
Adds numpyro.factor(name, prior.log_marginal(y, noise_var)), the
shared path and every site path marginalised out by one Kalman filter
over the merged grid,
with \(o_k\) the sites observed at \(t_k\). The mask is the prior's own
(from SharedPlusSiteMarkovGPPrior.from_sites), so the factor takes
none, as SharedPlusSiteMarkovGPPrior.log_marginal takes none.
Registers the one site name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
SharedPlusSiteMarkovGPPrior
|
The |
required |
y
|
Float[Array, 'T S']
|
Observations, shaped |
required |
noise_var
|
Float[Array, ''] | Float[Array, ' S']
|
Observation noise variance, scalar or |
required |
Examples:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import pyrox_ssm as pss
>>> times = jnp.arange(3.0)
>>> mask = jnp.array([[True, False], [True, True], [False, True]])
>>> y = jnp.array([[0.3, jnp.nan], [0.1, -0.2], [jnp.nan, 0.4]])
>>> def model(y):
... ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
... shared = pss.MaternSDE(variance=1.0, lengthscale=ell, order=0)
... site = pss.MaternSDE(variance=0.5, lengthscale=1.0, order=0)
... prior = pss.SharedPlusSiteMarkovGPPrior(shared, site, times, mask)
... pss.shared_plus_site_factor("y", prior, y, jnp.asarray(0.1))
>>> trace = numpyro.handlers.trace(numpyro.handlers.seed(model, 0)).get_trace(y)
>>> sorted(trace)
['lengthscale', 'y']
Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
Normalizing Kalman Filter¶
NormalizingKalmanPrior wraps a pyrox_gauss.LGSSM (or pyrox_gauss.MaskedLGSSM)
base and an optional per-timestep observation warp into the same
model surface: exact collapsed marginal via log_marginal, NumPyro
registration via normalizing_kalman_factor, and observation-space
predictive moments via predict (RTS smoothing followed by a
Gauss-Hermite pushforward through the warp — the mean is E[G(z)],
not G(E[z])).
pyrox_ssm.flows needs the flows extra (pip install 'pyrox-ssm[flows]'),
which brings flowjax and, for a non-None warp, gauss_flows; the
unwarped model (warp=None) needs no gauss_flows at runtime. Because the warp acts on observations,
the log-det term is independent of the latent state, the Kalman
recursion stays exact, and none of the non-Gaussian Markov strategies
below are involved.
import jax.numpy as jnp
import numpyro
from numpyro import distributions as dist
from pyrox_gauss import LGSSM
from pyrox_ssm.flows import NormalizingKalmanPrior, normalizing_kalman_factor
def nkf_model(y, warp=None, mask=None):
T, M = y.shape
log_q = numpyro.sample("log_q", dist.Normal(0.0, 1.0).expand([M]).to_event(1))
log_r = numpyro.sample("log_r", dist.Normal(0.0, 1.0).expand([M]).to_event(1))
base = LGSSM(0.9 * jnp.eye(M), jnp.eye(M),
jnp.diag(jnp.exp(jnp.asarray(log_q))),
jnp.diag(jnp.exp(jnp.asarray(log_r))),
jnp.zeros(M), jnp.eye(M), n_steps=T)
prior = NormalizingKalmanPrior(base, warp=warp)
normalizing_kalman_factor("nkf", prior, y, mask)
After fitting, prior.condition(y, mask) filters once and returns the ConditionedNormalizingKalman, whose predict(n_ahead=..., order=...) gives the observation-space mean and variance on the training grid and n_ahead steps beyond it, pushed through the warp by Gauss-Hermite quadrature. Calling predict again, for a forecast after an in-sample fit, runs no second filter. NormalizingKalmanPrior.predict(y, mask, ...) is deprecated and returns the same numbers with a DeprecationWarning.
NormalizingKalmanPrior
¶
Bases: Module
Normalizing Kalman Filter prior over a multivariate time grid.
Wraps a pyrox_gauss.LGSSM (or pyrox_gauss.MaskedLGSSM) base and an
optional per-timestep observation warp into the pyrox_ssm model
surface, so the state-space parameters and the warp can carry NumPyro
priors and be fitted with any pyrox.inference driver
(pyrox.inference.EnsembleMAP, pyrox.inference.EnsembleVI, SVI,
MCMC).
Because the warp acts on observations rather than on the latent
state, the log-determinant term is independent of \(x_t\) and the
Kalman recursion stays exact — the marginal likelihood is
closed-form and no non-Gaussian inference strategy is required.
With warp=None this reduces exactly to the base LGSSM marginal
likelihood, with no flow dependencies at runtime.
The state-space parameters \((A, H, Q, R)\) are rotationally
non-identifiable in the same way a latent-factor mixing matrix is,
so ensembling over seeds (pyrox.inference.EnsembleMAP) is the
recommended fitting pattern rather than a convenience.
Attributes:
| Name | Type | Description |
|---|---|---|
base |
LGSSM
|
|
warp |
AbstractBijection | None
|
Optional bijection with event shape |
mean_fn |
Callable[[Float[Array, ' T']], Float[Array, 'T M']] | None
|
Optional callable |
Examples:
>>> import jax.numpy as jnp, jax.random as jr
>>> from pyrox_gauss import LGSSM
>>> from pyrox_ssm.flows import NormalizingKalmanPrior
>>> T, M = 12, 2
>>> base = LGSSM(0.9 * jnp.eye(M), jnp.eye(M), 0.1 * jnp.eye(M),
... 0.2 * jnp.eye(M), jnp.zeros(M), jnp.eye(M), n_steps=T)
>>> prior = NormalizingKalmanPrior(base) # unwarped: no flow deps
>>> y = base.sample(jr.key(0))
>>> prior.log_marginal(y).shape
()
>>> mean, var = prior.condition(y).predict(n_ahead=3)
>>> mean.shape
(15, 2)
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 | |
n_steps: int
property
¶
Sequence length T of the base.
n_channels: int
property
¶
Observation dimension M of the base.
log_marginal(y: Float[Array, 'T M'], mask: Bool[Array, 'T M'] | None = None) -> Float[Array, '']
¶
Exact log marginal likelihood, warp included.
Computes \(\log p(y) = \log p_{\mathrm{LGSSM}}(G^{-1}(y - m)) + \sum_t \log|\det \partial G^{-1}/\partial y_t|\) — a Kalman forward pass on the inverse-warped observations plus the summed log-determinant. The log-det does not depend on the latent path, so the result is exact, not a bound.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, shape |
required |
mask
|
Bool[Array, 'T M'] | None
|
Optional observation mask, shape |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar \(\log p(y_{\mathrm{obs}} \mid \theta)\). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
condition(y: Float[Array, 'T M'], mask: Bool[Array, 'T M'] | None = None) -> ConditionedNormalizingKalman
¶
Condition on y: inverse-warp it, filter once and smooth.
Each observation is mapped to the warped space,
\(z_t = G^{-1}(y_t - m(t))\), and the Kalman filter and RTS smoother
run once over \(z\). The result holds the smoothed moments and the
last filtered state, so ConditionedNormalizingKalman.predict can
be called several times (in-sample, then a forecast) without
filtering again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
y
|
Float[Array, 'T M']
|
Observations, shape |
required |
mask
|
Bool[Array, 'T M'] | None
|
Optional observation mask, shape |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNormalizingKalman
|
The |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
>>> import jax.numpy as jnp, jax.random as jr
>>> from pyrox_gauss import LGSSM
>>> from pyrox_ssm.flows import NormalizingKalmanPrior
>>> base = LGSSM(0.9 * jnp.eye(2), jnp.eye(2), 0.1 * jnp.eye(2),
... 0.2 * jnp.eye(2), jnp.zeros(2), jnp.eye(2), n_steps=12)
>>> y = base.sample(jr.key(0))
>>> cond = NormalizingKalmanPrior(base).condition(y)
>>> mean, var = cond.predict(n_ahead=3)
>>> mean.shape
(15, 2)
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 | |
predict(y: Float[Array, 'T M'], mask: Bool[Array, 'T M'] | None = None, *, n_ahead: int = 0, order: int = 32) -> tuple[Float[Array, 'Tp M'], Float[Array, 'Tp M']]
¶
Deprecated: use prior.condition(y, mask).predict(...).
Conditions on y and predicts in one call, filtering every time.
Returns exactly what
self.condition(y, mask).predict(n_ahead=n_ahead, order=order)
returns, with a DeprecationWarning.
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
ConditionedNormalizingKalman
¶
Bases: Module
A NormalizingKalmanPrior conditioned on observations.
Returned by NormalizingKalmanPrior.condition. Holds the RTS-smoothed
moments of the state in the warped space and the last filtered state,
so predict runs no filter: in-sample and forecast predictions come
from one filtering pass.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
NormalizingKalmanPrior
|
The originating |
y |
Float[Array, 'T M']
|
Observations, |
mask |
Bool[Array, 'T M'] | None
|
The effective |
smoothed_means |
Float[Array, 'T D']
|
Smoothed state means, |
smoothed_covs |
Float[Array, 'T D D']
|
Smoothed state covariances, |
last_filtered_mean |
Float[Array, ' D']
|
Filtered state mean at the last step, |
last_filtered_cov |
Float[Array, 'D D']
|
Filtered state covariance at the last step,
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
predict(*, n_ahead: int = 0, order: int = 32) -> tuple[Float[Array, 'Tp M'], Float[Array, 'Tp M']]
¶
Predictive moments in observation space.
Two stages. RTS smoothing gives Gaussian moments of the warped
observation \(z_t = H x_t + r_t \sim N(\mu_t, \sigma_t^2)\)
(per channel, noise included) on the training grid, extended
n_ahead steps by open-loop propagation through \((A, Q)\).
Those moments are then pushed through the warp by Gauss-Hermite
quadrature:
The returned mean is \(\mathbb{E}[G(z)]\), not \(G(\mathbb{E}[z])\) — the latter is the pushforward median for a monotone warp and is badly biased for a skewed one.
The quadrature is per-channel over the marginal warped-space
moments, so it is the right integral only when each output
channel depends on its own input channel alone. This method
therefore requires an elementwise warp and raises otherwise —
a channel-mixing warp's outputs depend on the full joint
Gaussian, cross-channel covariances included, and per-channel
moments would be silently wrong rather than merely imprecise.
NormalizingKalmanPrior.log_marginal carries no such
restriction: it stays exact for any unmasked warp.
Gauss-Hermite converges spectrally only for analytic
integrands. A piecewise rational-quadratic spline warp is not
analytic at its knots, so its quadrature error plateaus around
~3e-3 and can get worse with increasing order — the
default order=32 is the sweet spot for splines, and raising
the order is not a convergence diagnostic.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_ahead
|
int
|
Number of forecast steps appended after the training grid. |
0
|
order
|
int
|
Gauss-Hermite order for the warped pushforward, in
|
32
|
Returns:
| Type | Description |
|---|---|
Float[Array, 'Tp M']
|
Tuple |
Float[Array, 'Tp M']
|
each of shape |
tuple[Float[Array, 'Tp M'], Float[Array, 'Tp M']]
|
so |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the warp is not elementwise, or if |
Examples:
>>> import jax.numpy as jnp, jax.random as jr
>>> from pyrox_gauss import LGSSM
>>> from pyrox_ssm.flows import NormalizingKalmanPrior
>>> base = LGSSM(0.9 * jnp.eye(2), jnp.eye(2), 0.1 * jnp.eye(2),
... 0.2 * jnp.eye(2), jnp.zeros(2), jnp.eye(2), n_steps=12)
>>> cond = NormalizingKalmanPrior(base).condition(base.sample(jr.key(0)))
>>> in_sample, _ = cond.predict()
>>> forecast, _ = cond.predict(n_ahead=5) # no second filter pass
>>> in_sample.shape, forecast.shape
((12, 2), (17, 2))
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 | |
normalizing_kalman_factor(name: str, prior: NormalizingKalmanPrior, y: Float[Array, 'T M'], mask: Bool[Array, 'T M'] | None = None) -> None
¶
Register the NKF marginal log-likelihood with NumPyro.
Computes the exact collapsed marginal via NormalizingKalmanPrior.log_marginal
and adds it as numpyro.factor(name, ...). Mirrors
pyrox_ssm.markov_gp_factor — the latent state path is marginalised
analytically, so the model only carries sample sites for the
state-space (and warp) hyperparameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
NumPyro factor site name. |
required |
prior
|
NormalizingKalmanPrior
|
The |
required |
y
|
Float[Array, 'T M']
|
Observations, shape |
required |
mask
|
Bool[Array, 'T M'] | None
|
Optional observation mask, shape |
None
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
Ensemble Kalman log likelihood¶
ensemble_factor adds the ensemble Kalman log likelihood of a filterax assimilation run (filterax.differentiable_assimilate) to a NumPyro model, for models whose state is too large for a moment filter. The initial ensemble is data, drawn once outside the model, and only deterministic square-root filters are accepted, so the log density is deterministic and smooth in the parameters. It is biased, the bias shrinking as the ensemble grows, so report the ensemble size with any result. Fit it with SVI or MAP by default, with NUTS for a small set of parameters, and with filterax's ensemble Kalman inversion when the model cannot be differentiated.
pyrox_ssm.ensemble needs the ensemble extra (pip install 'pyrox-ssm[ensemble]'), which installs filterax.
ensemble_factor(name: str, filter_: flx.AbstractSequentialFilter, dynamics: flx.AbstractDynamics, obs_op: flx.AbstractObsOperator, init_ensemble: Float[Array, 'E D'], y: Float[Array, 'T M'], obs_times: Float[Array, ' T'], obs_noise: Float[Array, 'M M'] | lx.AbstractLinearOperator, *, inflator: flx.AbstractInflator | None = None, t0: float | Float[Array, ''] = 0.0, adjoint: Any | None = None, **analysis_extra: Any) -> flx.AssimilationResult
¶
Register the ensemble Kalman log likelihood as a NumPyro factor.
With an ensemble of \(E\) members, a state of length \(D\), observations of length \(M\) at \(T\) times, deterministic dynamics \(f_\theta\) and an observation operator \(h_\theta\), the filter forecasts every member from the previous analysis time to \(t_k\) and scores \(y_k\) under the Gaussian the forecast ensemble implies,
with \(U_k\) the predicted-observation anomalies scaled by
\(1 / \sqrt{E - 1}\) and \(\Sigma_\varepsilon\) the obs_noise. The
factor is the prediction-error sum
Row \(k - 1\) of y holds step \(k\), observed at obs_times[k - 1];
the first forecast runs from t0 to obs_times[0].
The log density is deterministic in \(\theta\). The initial ensemble
\(X_0\) is data, drawn once outside the model, and the filter is a
square-root filter, so every evaluation sees the same random numbers
(common random numbers) and the log density is a smooth function of
\(\theta\). Draw \(X_0\) once, before inference, and pass the same array to
every call. Filters and inflators that draw at each step
(filterax.filters.StochasticEnKF, filterax.filters.ETKF_Livings,
filterax.AdditiveInflator) raise.
The log likelihood is biased, not exact: the ensemble mean and
covariance are Monte Carlo estimates, and the bias shrinks as \(E\)
grows. For linear-Gaussian dynamics and observations it converges to
the Kalman filter's exact log marginal (pyrox_ssm.lgssm_factor).
Report \(E\) with any result.
Fitting: SVI or MAP is the default; NUTS suits a small set of
parameters, since every gradient is one assimilation run and its
backward pass; when \(f_\theta\) or \(h_\theta\) cannot be differentiated,
use filterax's ensemble Kalman inversion (filterax.EKI) instead of
this factor.
Registers the one NumPyro site name, a factor. Library code adds no
jax.jit; jit the model or the loss at the top.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
filter_
|
AbstractSequentialFilter
|
A deterministic square-root filter from
|
required |
dynamics
|
AbstractDynamics
|
Deterministic dynamics \(f_\theta\), called per member as
|
required |
obs_op
|
AbstractObsOperator
|
Observation operator \(h_\theta\), from a |
required |
init_ensemble
|
Float[Array, 'E D']
|
The initial ensemble \(X_0\), shaped |
required |
y
|
Float[Array, 'T M']
|
Observations \(y_{1:T}\), shaped |
required |
obs_times
|
Float[Array, ' T']
|
Observation times, shaped |
required |
obs_noise
|
Float[Array, 'M M'] | AbstractLinearOperator
|
Observation-noise covariance \(\Sigma_\varepsilon\), an
|
required |
inflator
|
AbstractInflator | None
|
Optional deterministic inflator
( |
None
|
t0
|
float | Float[Array, '']
|
The time of \(X_0\), where the first forecast starts. |
0.0
|
adjoint
|
Any | None
|
The gradient strategy from |
None
|
**analysis_extra
|
Any
|
Passed to |
{}
|
Returns:
| Type | Description |
|---|---|
AssimilationResult
|
The |
AssimilationResult
|
|
AssimilationResult
|
|
AssimilationResult
|
sum is the factor. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Examples:
A damped rotation of a 2-D state, observed in its first coordinate, with a prior on the damping:
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import numpyro
>>> import numpyro.distributions as dist
>>> import filterax as flx
>>> from pyrox_ssm.ensemble import ensemble_factor
>>> rotation = jnp.array([[0.8, -0.6], [0.6, 0.8]])
>>> X0 = jr.normal(jr.key(0), (64, 2)) # E = 64, drawn once
>>> def model(y, obs_times):
... a = numpyro.sample("a", dist.Uniform(0.5, 1.0))
... ensemble_factor(
... "y",
... flx.filters.ETKF(),
... lambda x, t0, t1: a * rotation @ x,
... lambda x: x[:1],
... X0,
... y,
... obs_times,
... 0.1 * jnp.eye(1),
... )
>>> y = jnp.array([[0.5], [0.2], [-0.1]])
>>> trace = numpyro.handlers.trace(numpyro.handlers.seed(model, 0)).get_trace(
... y, jnp.array([1.0, 2.0, 3.0])
... )
>>> sorted(trace)
['a', 'y']
Source code in packages/pyrox-ssm/src/pyrox_ssm/ensemble.py
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 | |
Non-Gaussian inference (Markov)¶
The Markov-aware counterparts of pyrox-gp's site-based strategies
(GP API): same
diagonal-site math, but the global posterior recomputation runs through
the Kalman filter / RTS smoother in O(N d^3) instead of a dense
O(N^3) solve. Each fit(prior, likelihood, y) returns a
ConditionedNonGaussMarkovGP with the same predict API as the
Gaussian-likelihood ConditionedMarkovGP. PosteriorLinearizationMarkov and
ExpectationPropagationMarkov take the same integrator as their dense twins;
expectation propagation accepts only a gaussx.GaussHermiteIntegrator.
Each strategy runs its site updates on argminax.solve.site_fixed_point, the site loop pyrox-gp's posterior linearisation and EP share, and reports the evidence as the Kalman marginal of its sites plus gaussx.site_evidence_correction, so a fit and its log_marginal_approx trace under jax.jit and differentiate with respect to the kernel hyperparameters (the adjoint field). LaplaceMarkovInference differentiates through the iterations that ran by default, and the other strategies use the implicit function theorem at the fixed point, markov_implicit_adjoint; the adjoint attribute of LaplaceMarkovInference sets out the trade-off. converged and n_iter are arrays, traced under jit; the gradient is that of a fixed point only when converged is true. markov_laplace_factor adds the approximate evidence to a NumPyro model, so NUTS or SVI can run over the hyperparameters with the latent path marginalised out; reject_unconverged=True makes the factor -inf where the fit did not converge.
import numpyro
import numpyro.distributions as dist
import pyrox_ssm as pss
def model(times, y, likelihood):
variance = numpyro.sample("variance", dist.LogNormal(0.0, 1.0))
lengthscale = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
prior = pss.MarkovGPPrior(pss.MaternSDE(variance, lengthscale, order=1), times)
pss.markov_laplace_factor(
"y", prior, likelihood, y,
strategy=pss.LaplaceMarkovInference(), reject_unconverged=True,
)
LaplaceMarkovInference
¶
Bases: Module
Laplace approximation for MarkovGPPrior.
Fixed-point Newton on the smoothed posterior: each iteration runs filter + smoother with the current sites to obtain the posterior mean \(\hat f\), then sets the site naturals from the per-point gradient \(g_n\) and curvature \(h_n\) of \(\log p(y \mid f)\) at \(\hat f\),
with the site precision \(\Lambda = -h\) clipped to precision_floor.
The step size \(\alpha\) is damping times a cap on how far one step may
move the posterior mean. With \(f^N\) the posterior mean
under the full Newton sites \(T(s)\) and \(\sigma_n\) the prior's marginal
standard deviation at \(t_n\),
with \(\alpha_d\) = damping and \(\delta\) = max_step.
A full Newton step on a Bernoulli likelihood at a large prior variance
overshoots and cycles without converging, however many iterations it is
given; the cap shortens those steps and keeps the full step wherever it
is short, so convergence near the mode stays quadratic. Any
\(\alpha > 0\) leaves the fixed point, and so the fit and its implicit
gradient, unchanged. The cap costs one more filter and smoother pass per
iteration (and, for a non-stationary kernel, one pass per fit for
\(\sigma_n\)); max_step=None turns it off and takes the full step.
The loop is argminax.solve.site_fixed_point, so a fit traces under
jax.jit and differentiates through adjoint (see the module notes).
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
Newton iterations. Default |
tol |
float
|
Convergence tolerance: the loop stops at the first iteration
where every site natural \(\lambda_n\), \(\Lambda_n\) changed by less
than |
damping |
float
|
Factor \(\alpha_d\) in (0, 1] on every Newton
step, on top of |
max_step |
float | None
|
The largest change one step may make to the posterior
mean, \(\delta\), in prior standard deviations \(\sigma_n\). Default
|
precision_floor |
float
|
Lower bound on the diagonal precision. Default
|
adjoint |
AbstractAdjoint
|
How gradients pass through the loop. Default
For small \(N\), |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | |
fit(prior: MarkovGPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, mask: Bool[Array, ' N'] | None = None) -> ConditionedNonGaussMarkovGP
¶
Fit the sites by Newton steps on the smoothed posterior mean.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
MarkovGPPrior
|
The |
required |
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussMarkovGP
|
The |
Examples:
>>> import jax
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> from pyrox_ssm import LaplaceMarkovInference
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([1.0, 0.0, jnp.nan, 1.0])
>>> mask = jnp.array([True, True, False, True])
>>> strategy = LaplaceMarkovInference()
>>> cond = strategy.fit(prior, BernoulliLikelihood(), y, mask=mask)
The fit traces, so the Laplace evidence jits and differentiates:
>>> def evidence(ell):
... p = MarkovGPPrior(MaternSDE(1.0, ell, order=1), jnp.arange(4.0))
... fit = strategy.fit(p, BernoulliLikelihood(), y, mask=mask)
... return fit.log_marginal_approx
>>> grad = jax.jit(jax.grad(evidence))(0.5)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 | |
GaussNewtonMarkovInference
¶
Bases: Module
Gauss-Newton (Markov) inference: Newton with a strict PSD floor.
Identical to LaplaceMarkovInference for log-concave
likelihoods (Bernoulli, Poisson). For non-log-concave likelihoods
(StudentT) the larger precision_floor keeps the Newton step
PSD-stable. Same fixed-point loop, damping and tolerance as
LaplaceMarkovInference; its default adjoint is the implicit one.
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
Newton iterations. Default |
tol |
float
|
Convergence tolerance on the site naturals, as in
|
damping |
float
|
Step-size in (0, 1]. Default |
precision_floor |
float
|
Strict positive floor. Default |
adjoint |
AbstractAdjoint
|
How gradients pass through the loop. Default
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
fit(prior: MarkovGPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, mask: Bool[Array, ' N'] | None = None) -> ConditionedNonGaussMarkovGP
¶
Fit the sites by Gauss-Newton steps, as LaplaceMarkovInference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
MarkovGPPrior
|
The |
required |
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussMarkovGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> from pyrox_ssm import GaussNewtonMarkovInference
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([1.0, 0.0, jnp.nan, 1.0])
>>> mask = jnp.array([True, True, False, True])
>>> strategy = GaussNewtonMarkovInference()
>>> cond = strategy.fit(prior, BernoulliLikelihood(), y, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
PosteriorLinearizationMarkov
¶
Bases: Module
Posterior linearization for MarkovGPPrior (Markov IPLF).
Iterates filter + smoother + cavity-averaged statistical
linearization. At each iteration, with current sites producing
smoothed marginals (m_n, V_n), form the cavity
q_{\\setminus n}(f) = N(m_{c,n}, V_{c,n}), evaluate the expected
per-point gradient and Hessian under the cavity (via the integrator),
and update the sites with damping. The loop is
argminax.solve.site_fixed_point, so a fit traces under jax.jit and
differentiates through adjoint.
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
Iterations. Default |
tol |
float
|
Convergence tolerance on the site naturals, as in
|
damping |
float
|
Step-size in (0, 1]. Default |
precision_floor |
float
|
Floor on the diagonal precision. Default |
deg |
int | None
|
Deprecated. |
integrator |
AbstractIntegrator
|
Rule for the cavity expectations, any
|
adjoint |
AbstractAdjoint
|
How gradients pass through the loop. Default
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 | |
fit(prior: MarkovGPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, mask: Bool[Array, ' N'] | None = None) -> ConditionedNonGaussMarkovGP
¶
Fit the sites by posterior linearization.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
MarkovGPPrior
|
The |
required |
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussMarkovGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> from pyrox_ssm import PosteriorLinearizationMarkov
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([1.0, 0.0, jnp.nan, 1.0])
>>> mask = jnp.array([True, True, False, True])
>>> strategy = PosteriorLinearizationMarkov()
>>> cond = strategy.fit(prior, BernoulliLikelihood(), y, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
ExpectationPropagationMarkov
¶
Bases: Module
Parallel Expectation Propagation for MarkovGPPrior.
Each iteration: run filter + smoother, form cavities at every site,
match tilted-distribution moments via Gauss-Hermite (with log-space
stabilisation), and update sites with damping. The loop is
argminax.solve.site_fixed_point, so a fit traces under jax.jit and
differentiates through adjoint.
Attributes:
| Name | Type | Description |
|---|---|---|
max_iter |
int
|
EP iterations. Default |
tol |
float
|
Convergence tolerance on the site naturals, as in
|
damping |
float
|
Damping in (0, 1]. Default |
precision_floor |
float
|
Floor on the diagonal precision. Default |
deg |
int | None
|
Deprecated. |
integrator |
AbstractIntegrator
|
Rule for the tilted moments. Default
|
adjoint |
AbstractAdjoint
|
How gradients pass through the loop. Default
|
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 | |
fit(prior: MarkovGPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, mask: Bool[Array, ' N'] | None = None) -> ConditionedNonGaussMarkovGP
¶
Fit the sites by parallel expectation propagation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
MarkovGPPrior
|
The |
required |
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
ConditionedNonGaussMarkovGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import BernoulliLikelihood
>>> from pyrox_ssm import MaternSDE, MarkovGPPrior
>>> from pyrox_ssm import ExpectationPropagationMarkov
>>> prior = MarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(4.0))
>>> y = jnp.array([1.0, 0.0, jnp.nan, 1.0])
>>> mask = jnp.array([True, True, False, True])
>>> strategy = ExpectationPropagationMarkov()
>>> cond = strategy.fit(prior, BernoulliLikelihood(), y, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
ConditionedNonGaussMarkovGP
¶
Bases: Module
Markov GP conditioned on a non-Gaussian likelihood via a site-based strategy.
Equivalent role to pyrox_ssm.ConditionedMarkovGP but the
posterior over training latents is a generic Gaussian
approximation produced by one of the strategies in this module
rather than the closed-form Gaussian-likelihood smoother. Predictions
at arbitrary test times use the standard site-as-pseudo-observation
trick on the merged grid sort(times | t_star) with the test
points masked.
Attributes:
| Name | Type | Description |
|---|---|---|
prior |
MarkovGPPrior
|
The originating |
y |
Float[Array, ' N']
|
Training targets (kept for round-trip / diagnostics). |
site_nat1 |
Float[Array, ' N']
|
Diagonal site naturals \(\lambda \in \mathbb{R}^N\). |
site_nat2 |
Float[Array, ' N']
|
Diagonal site precisions \(\Lambda \in \mathbb{R}^N\) (positive). |
q_mean |
Float[Array, ' N']
|
Posterior mean over training latents. |
q_var |
Float[Array, ' N']
|
Marginal posterior variance per training point. |
log_marginal_approx |
Float[Array, '']
|
Approximate log marginal likelihood \(\log p(y)\): the Kalman marginal of the fitted Gaussian sites with the pseudo-data fit swapped for the data fit at the posterior mean, the same Laplace-style correction for every strategy. |
n_iter |
Int[Array, '']
|
Iterations used by the strategy, a |
converged |
Bool[Array, '']
|
Whether the strategy's |
mask |
Bool[Array, ' N'] | None
|
Optional |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 | |
predict(t_star: Float[Array, ' M']) -> tuple[Float[Array, ' M'], Float[Array, ' M']]
¶
Predictive marginals (mean, var) at arbitrary test times.
Re-runs filter + smoother over the merged grid
sort(times \cup t_star) with per-step pseudo-observation
variances 1/Λ_n on the training points and the test points
masked out of the update step. Cost is \(O((N + M)\,d^3)\).
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
markov_laplace_factor(name: str, prior: MarkovGPPrior, likelihood: Likelihood, y: Float[Array, ' N'], *, strategy: LaplaceMarkovInference | GaussNewtonMarkovInference | PosteriorLinearizationMarkov | ExpectationPropagationMarkov, mask: Bool[Array, ' N'] | None = None, reject_unconverged: bool = False) -> None
¶
Register a non-Gaussian Markov GP's approximate evidence with NumPyro.
Fits the sites with strategy and adds its
log_marginal_approx as numpyro.factor(name, ...), the latent path
marginalised out. With LaplaceMarkovInference (or
GaussNewtonMarkovInference) that is the Laplace evidence
at the mode \(\hat f\) with \(W = \operatorname{diag}(\Lambda)\), computed by
the Kalman smoother in \(O(N d^3)\). Inside NUTS over \(\theta\) this is the
INLA recipe on a Markov prior. The fit traces and its gradient is implicit
at the fixed point (see LaplaceMarkovInference), so the factor works under
NUTS and SVI. With PosteriorLinearizationMarkov or
ExpectationPropagationMarkov the factor is that strategy's
log_marginal_approx.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
MarkovGPPrior
|
The |
required |
likelihood
|
Likelihood
|
Any scalar-latent |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
strategy
|
LaplaceMarkovInference | GaussNewtonMarkovInference | PosteriorLinearizationMarkov | ExpectationPropagationMarkov
|
The site-based strategy that fits the sites. |
required |
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
reject_unconverged
|
bool
|
If |
False
|
Examples:
>>> import jax.numpy as jnp
>>> import numpyro
>>> import numpyro.distributions as dist
>>> from pyrox_gp import BernoulliLikelihood
>>> import pyrox_ssm as pss
>>> def model(times, y):
... var = numpyro.sample("variance", dist.LogNormal(0.0, 1.0))
... ell = numpyro.sample("lengthscale", dist.LogNormal(0.0, 1.0))
... prior = pss.MarkovGPPrior(pss.MaternSDE(var, ell, order=1), times)
... pss.markov_laplace_factor(
... "y", prior, BernoulliLikelihood(), y,
... strategy=pss.LaplaceMarkovInference(),
... reject_unconverged=True,
... )
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 | |
markov_implicit_adjoint() -> optx.ImplicitAdjoint
¶
The implicit adjoint of the Markov strategies, safe to use inside NUTS.
The implicit function theorem at the fixed point \(s^\star\) (see the module
notes), solved matrix-free: \(I - \partial T_\alpha / \partial s\) is not
symmetric, so lineax.GMRES (rtol and atol 1e-10, restart
20, at most 50 steps), which needs only products with the operator. No
(2N, 2N) Jacobian is formed, and each product costs one Kalman smoother
pass. A solve that fails returns a value instead of raising: where the fit
is already non-finite the gradient is non-finite, and a solve that stops at
max_steps keeps its last iterate. A bare optimistix.ImplicitAdjoint
raises in both cases, which ends a NUTS chain. The mechanism is
argminax.adjoint.safe_implicit_adjoint; only the GMRES setting is
Markov-specific.
The default adjoint of GaussNewtonMarkovInference,
PosteriorLinearizationMarkov and ExpectationPropagationMarkov; pass it
to LaplaceMarkovInference for the trade-off its adjoint attribute
describes.
Returns:
| Type | Description |
|---|---|
ImplicitAdjoint
|
An |
Examples:
>>> import pyrox_ssm as pss
>>> strategy = pss.LaplaceMarkovInference(
... adjoint=pss.markov_implicit_adjoint()
... )
Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
Sparse Markov GP¶
Sparse variational GP over an SDE kernel and an inducing time grid: the variational family lives on the inducing times while predictions exploit the Markov structure between them.
Fit a guide over the inducing values with sparse_markov_factor or sparse_markov_elbo, then prior.condition(guide) returns the ConditionedSparseMarkovGP, whose predict(t_star) gives the SVGP predictive mean and variance at any times. The observations are already summarised in the guide, so condition takes the guide rather than y.
SparseMarkovGPPrior
¶
Bases: Module
Sparse variational GP prior over an SDE kernel and inducing time grid.
Equivalent role to pyrox_gp.SparseGPPrior but the
covariance is derived from the state-space autocovariance
\(k(\tau) = H \exp(F\tau) P_\infty H^\top\) of an
SDEKernel. Predictions and the SVGP ELBO go through the
same predictive_blocks contract as the dense
SparseGPPrior, so the existing variational guides
(pyrox_gp.FullRankGuide, pyrox_gp.MeanFieldGuide,
pyrox_gp.WhitenedGuide) and pyrox_gp.svgp_elbo
work as-is.
Attributes:
| Name | Type | Description |
|---|---|---|
sde_kernel |
SDEKernel
|
Any |
Z |
Float[Array, ' M']
|
Sorted, strictly increasing inducing times of shape |
mean_fn |
Callable[[Float[Array, ' N']], Float[Array, ' N']] | None
|
Optional callable |
solver |
AbstractSolverStrategy | None
|
Any |
jitter |
float
|
Diagonal regularisation added to |
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 | |
num_inducing: int
property
¶
Number of inducing time points \(M\).
mean(times: Float[Array, ' N']) -> Float[Array, ' N']
¶
Evaluate the mean function at times; zero by default.
inducing_operator() -> lx.AbstractLinearOperator
¶
Return K_{ZZ} + \text{jitter}\,I as a PSD lineax operator.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
cross_covariance(times: Float[Array, ' N']) -> Float[Array, 'N M']
¶
K_{XZ} — pairwise SDE autocov between training and inducing times.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
kernel_diag(times: Float[Array, ' N']) -> Float[Array, ' N']
¶
Prior diagonal \(\mathrm{diag}\,K(X, X)\).
Constant for stationary SDE kernels — equal to H P_inf H^T.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
predictive_blocks(times: Float[Array, ' N']) -> tuple[lx.AbstractLinearOperator, Float[Array, 'N M'], Float[Array, ' N']]
¶
Return (K_zz_op, K_xz, K_xx_diag) for the SVGP predictive math.
Mirrors SparseGPPrior.predictive_blocks. Delegates to the
three independent accessors:
inducing_operator—K_{ZZ} + \\text{jitter}\\,Iwrapped as a PSDlineaxoperator.cross_covariance— pairwise SDE autocovK_{XZ}.kernel_diag— prior marginal variance, constant for stationary SDE kernels.
Each accessor calls SDEKernel.sde_params independently;
these calls are cheap (parameter unpacking, not a kernel build)
so no shared-state caching is performed.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
log_prob(u: Float[Array, ' M']) -> Float[Array, '']
¶
Log-density under the inducing prior.
\(p(u) = \mathcal{N}(0,\, K_{ZZ} + \text{jitter}\,I)\).
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
sample(key: Array) -> Float[Array, ' M']
¶
Draw \(u \sim p(u)\) from the inducing prior.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
condition(guide: Guide) -> ConditionedSparseMarkovGP
¶
The sparse posterior for a fitted guide.
For a sparse prior the observations are already summarised in the
fitted guide \(q(u) = \mathcal{N}(m_q, S_q)\), so condition takes the
guide rather than y; the result is
whose predict(t_star) gives the SVGP predictive marginals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
guide
|
Guide
|
The fitted guide over the inducing values, any
|
required |
Returns:
| Type | Description |
|---|---|
ConditionedSparseMarkovGP
|
The |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox_gp import FullRankGuide
>>> from pyrox_ssm import MaternSDE, SparseMarkovGPPrior
>>> prior = SparseMarkovGPPrior(
... MaternSDE(1.0, 0.6, order=1), jnp.linspace(0.0, 5.0, 6)
... )
>>> guide = FullRankGuide.init(prior.num_inducing, scale=0.3)
>>> mean, var = prior.condition(guide).predict(jnp.array([0.5, 6.0]))
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
ConditionedSparseMarkovGP
¶
Bases: Module
Sparse Markov GP fitted to a guide.
Returned by SparseMarkovGPPrior.condition. Bundles the
SparseMarkovGPPrior and a fitted
pyrox_gp.Guide so that predict(t_star) can be called
against arbitrary test times. The math is the standard SVGP
predictive
Cost is \(O(M^3 + |t_*|\,M)\) per call.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
predict(t_star: Float[Array, ' M_star']) -> tuple[Float[Array, ' M_star'], Float[Array, ' M_star']]
¶
Predictive (mean, var) at arbitrary test times.
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
sparse_markov_elbo(prior: SparseMarkovGPPrior, guide: Guide, likelihood: Likelihood, times: Float[Array, ' N'], y: Float[Array, ' N'], *, integrator: AbstractIntegrator | None = None, mask: Bool[Array, ' N'] | None = None) -> Float[Array, '']
¶
Sparse variational ELBO for SparseMarkovGPPrior.
Mirrors pyrox_gp.svgp_elbo for the SDE-derived sparse
Markov prior. Builds the SVGP predictive blocks
\((K_{ZZ}, K_{XZ}, \mathrm{diag}\,K_{XX})\) from the prior, asks
the guide for the predictive marginals
\((\mu_n, \sigma_n^2) = q(f_n)\), and combines them with a closed-form
Gaussian or quadrature-based expected log-likelihood and the
inducing KL term:
With an observation mask \(o_n \in \{0, 1\}\) only the observed points score, \(\sum_n o_n\, \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)]\); the KL term is unchanged.
Unlike pyrox_gp.svgp_elbo, times stays as a 1-D vector
of shape (N,) — the SDE-pair autocov works on raw 1-D times and
has no need for a feature dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
prior
|
SparseMarkovGPPrior
|
|
required |
guide
|
Guide
|
Variational guide over inducing values. |
required |
likelihood
|
Likelihood
|
Observation model. |
required |
times
|
Float[Array, ' N']
|
Training times of shape |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
integrator
|
AbstractIntegrator | None
|
|
None
|
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
Scalar ELBO value (higher is better). |
Raises:
| Type | Description |
|---|---|
ValueError
|
If a non-conjugate likelihood is used without an
integrator, or if |
Examples:
>>> import jax.numpy as jnp
>>> from pyrox.likelihoods import GaussianLikelihood
>>> from pyrox_gp import FullRankGuide
>>> from pyrox_ssm import MaternSDE, SparseMarkovGPPrior, sparse_markov_elbo
>>> prior = SparseMarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(3.0))
>>> times = jnp.linspace(0.0, 2.0, 6)
>>> y = jnp.array([0.1, jnp.nan, 0.3, 0.2, 0.0, 0.4])
>>> mask = ~jnp.isnan(y)
>>> guide, lik = FullRankGuide.init(3), GaussianLikelihood(0.1)
>>> elbo = sparse_markov_elbo(prior, guide, lik, times, y, mask=mask)
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 | |
sparse_markov_factor(name: str, prior: SparseMarkovGPPrior, guide: Guide, likelihood: Likelihood, times: Float[Array, ' N'], y: Float[Array, ' N'], *, integrator: AbstractIntegrator | None = None, mask: Bool[Array, ' N'] | None = None) -> None
¶
Register sparse_markov_elbo as a NumPyro factor site.
With a mask, only the observed points score:
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The factor site name. |
required |
prior
|
SparseMarkovGPPrior
|
|
required |
guide
|
Guide
|
Variational guide over inducing values. |
required |
likelihood
|
Likelihood
|
Observation model. |
required |
times
|
Float[Array, ' N']
|
Training times of shape |
required |
y
|
Float[Array, ' N']
|
Observations of shape |
required |
integrator
|
AbstractIntegrator | None
|
|
None
|
mask
|
Bool[Array, ' N'] | None
|
Optional |
None
|
Examples:
>>> import jax.numpy as jnp
>>> from numpyro import handlers
>>> from pyrox.likelihoods import GaussianLikelihood
>>> from pyrox_gp import FullRankGuide
>>> from pyrox_ssm import MaternSDE, SparseMarkovGPPrior, sparse_markov_factor
>>> prior = SparseMarkovGPPrior(MaternSDE(1.0, 0.5, order=1), jnp.arange(3.0))
>>> times, y = jnp.linspace(0.0, 2.0, 6), jnp.ones(6)
>>> mask = jnp.array([True, True, False, True, True, True])
>>> with handlers.trace() as tr:
... sparse_markov_factor(
... "elbo", prior, FullRankGuide.init(3), GaussianLikelihood(0.1),
... times, y, mask=mask,
... )