Skip to content

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
class SDEKernel(eqx.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))
    """

    @property
    @abc.abstractmethod
    def state_dim(self) -> int:
        """State length D_x."""
        ...

    @property
    def stationary(self) -> bool:
        """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).
        """
        return True

    @abc.abstractmethod
    def sde_params(self) -> SDEParams:
        """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) of the SDE.

        Returns:
            The `SDEParams` of this kernel.
        """
        ...

    def initial_covariance(self) -> 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:
            Initial state covariance Σ_x,0.

        Raises:
            ValueError: If ``sde_params().P_inf`` is ``None``, so there
                is no stationary covariance to fall back on.
        """
        stationary_covariance = self.sde_params().P_inf
        if stationary_covariance is None:
            msg = (
                f"{type(self).__name__} has no initial covariance: it "
                f"reports P_inf=None, and the default initial covariance "
                f"is the stationary one. Override initial_covariance() "
                f"with an explicit choice (a diffuse prior, typically), "
                f"or give the kernel a P_inf."
            )
            raise ValueError(msg)
        return stationary_covariance

    def discretise(
        self,
        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:
            1. Without Σ_x,∞, form B_c = L_c Q_c L_cᵀ and return
               `gaussx.discretize_mfd` (F_c, B_c, Δt).
            2. Otherwise exponentiate the drift, F_t = exp(F_c Δt).
            3. Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ and symmetrise it.

        Args:
            dt: Time step Δt ≥ 0.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t.
        """
        params = self.sde_params()
        if params.P_inf is None:
            # L_c Q_c
            noise_effect_density = einsum(
                params.L, params.Q_c, "state noise, noise col -> state col"
            )
            # B_c = L_c Q_c L_cᵀ
            diffusion_covariance = einsum(
                noise_effect_density, params.L, "state col, other col -> state other"
            )
            return discretize_mfd(params.F, diffusion_covariance, dt)
        # F_t = exp(F_c Δt)
        transition = jsl.expm(params.F * dt)
        # Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ
        model_noise_covariance = process_noise_covariance(transition, params.P_inf)
        model_noise_covariance = symmetrize(model_noise_covariance)
        return transition, model_noise_covariance

    def discretise_sequence(
        self,
        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

        Args:
            dt: Time steps Δt_1:T.

        Returns:
            Tuple ``(A_seq, Q_seq)`` stacking F_t and Σ_η,t over time.
        """
        return jax.vmap(self.discretise)(dt)

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 SDEParams of this kernel.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
@abc.abstractmethod
def sde_params(self) -> SDEParams:
    """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) of the SDE.

    Returns:
        The `SDEParams` of this kernel.
    """
    ...

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 sde_params().P_inf is None, so there is no stationary covariance to fall back on.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
def initial_covariance(self) -> 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:
        Initial state covariance Σ_x,0.

    Raises:
        ValueError: If ``sde_params().P_inf`` is ``None``, so there
            is no stationary covariance to fall back on.
    """
    stationary_covariance = self.sde_params().P_inf
    if stationary_covariance is None:
        msg = (
            f"{type(self).__name__} has no initial covariance: it "
            f"reports P_inf=None, and the default initial covariance "
            f"is the stationary one. Override initial_covariance() "
            f"with an explicit choice (a diffuse prior, typically), "
            f"or give the kernel a P_inf."
        )
        raise ValueError(msg)
    return stationary_covariance

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
  1. Without Σ_x,∞, form B_c = L_c Q_c L_cᵀ and return gaussx.discretize_mfd (F_c, B_c, Δt).
  2. Otherwise exponentiate the drift, F_t = exp(F_c Δt).
  3. 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 (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
def discretise(
    self,
    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:
        1. Without Σ_x,∞, form B_c = L_c Q_c L_cᵀ and return
           `gaussx.discretize_mfd` (F_c, B_c, Δt).
        2. Otherwise exponentiate the drift, F_t = exp(F_c Δt).
        3. Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ and symmetrise it.

    Args:
        dt: Time step Δt ≥ 0.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t.
    """
    params = self.sde_params()
    if params.P_inf is None:
        # L_c Q_c
        noise_effect_density = einsum(
            params.L, params.Q_c, "state noise, noise col -> state col"
        )
        # B_c = L_c Q_c L_cᵀ
        diffusion_covariance = einsum(
            noise_effect_density, params.L, "state col, other col -> state other"
        )
        return discretize_mfd(params.F, diffusion_covariance, dt)
    # F_t = exp(F_c Δt)
    transition = jsl.expm(params.F * dt)
    # Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ
    model_noise_covariance = process_noise_covariance(transition, params.P_inf)
    model_noise_covariance = symmetrize(model_noise_covariance)
    return transition, model_noise_covariance

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 (A_seq, Q_seq) stacking F_t and Σ_η,t over time.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_sde_kernel.py
def discretise_sequence(
    self,
    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

    Args:
        dt: Time steps Δt_1:T.

    Returns:
        Tuple ``(A_seq, Q_seq)`` stacking F_t and Σ_η,t over time.
    """
    return jax.vmap(self.discretise)(dt)

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 None when the kernel has no closed form for it: a learned drift matrix, or a non-stationary kernel such as gaussx.IntegratedWienerSDE, which has no stationary covariance at all. SDEKernel.discretise then falls back to gaussx.discretize_mfd, which needs no Σ_x,∞, and the filter is started from SDEKernel.initial_covariance instead.

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
class SDEParams(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:
        F: Drift matrix F_c.
        L: Diffusion (noise-effect) matrix L_c.
        H: Measurement row H.
        Q_c: White-noise spectral density Q_c.
        P_inf: Stationary covariance Σ_x,∞, or ``None`` when the kernel
            has no closed form for it: a learned drift matrix, or a
            non-stationary kernel such as `gaussx.IntegratedWienerSDE`,
            which has no stationary covariance at all.
            `SDEKernel.discretise` then falls back to
            `gaussx.discretize_mfd`, which needs no Σ_x,∞, and the filter
            is started from `SDEKernel.initial_covariance` instead.

    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
    """

    F: Float[Array, "d d"]
    L: Float[Array, "d s"]
    H: Float[Array, "1 d"]
    Q_c: Float[Array, "s s"]
    P_inf: Float[Array, "d d"] | None = None

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
class MaternSDE(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:
        variance: Kernel variance σ_k².
        lengthscale: Lengthscale ℓ.
        order: 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()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        ValueError: Unsupported Matern order 3; must be 0, 1, or 2
    """

    variance: Float[Array, ""]
    lengthscale: Float[Array, ""]
    order: int = eqx.field(static=True)

    @property
    def state_dim(self) -> int:
        """State length D_x = p + 1."""
        return self.order + 1

    def sde_params(self) -> SDEParams:
        """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) for order p.

        Returns:
            The `SDEParams` of the Matérn-(p + ½) SDE.

        Raises:
            ValueError: If ``order`` is not 0, 1 or 2.
        """
        if self.order == 0:
            return self._matern12()
        elif self.order == 1:
            return self._matern32()
        elif self.order == 2:
            return self._matern52()
        else:
            msg = f"Unsupported Matern order {self.order}; must be 0, 1, or 2"
            raise ValueError(msg)

    def _matern12(self) -> SDEParams:
        """Matérn-1/2 (Ornstein-Uhlenbeck) SDE, λ = 1/ℓ.

            F_c = −λ,  L_c = 1,  H = 1,  Q_c = 2λσ_k²,  Σ_x,∞ = σ_k²

        Returns:
            The `SDEParams` of the one-state SDE.
        """
        # Constant blocks follow the hyperparameter dtype; an untyped
        # ``jnp.array`` of Python floats is float64 under x64 (gh-224).
        dtype = jnp.result_type(self.variance, self.lengthscale)
        # λ = 1/ℓ
        rate = 1.0 / self.lengthscale
        # F_c = −λ
        drift = jnp.array([[-rate]])
        # L_c = 1
        noise_effect = jnp.array([[1.0]], dtype=dtype)
        # H = 1
        obs_operator = jnp.array([[1.0]], dtype=dtype)
        # Q_c = 2λσ_k²
        spectral_density = jnp.array([[2.0 * rate * self.variance]])
        # Σ_x,∞ = σ_k²
        stationary_covariance = jnp.array([[self.variance]])
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def _matern32(self) -> SDEParams:
        """Matérn-3/2 SDE on x = [f, f^(1)], λ = √3/ℓ.

            F_c = [[0, 1], [−λ², −2λ]],  L_c = [0, 1]ᵀ,  H = [1, 0]
            Q_c = 4λ³σ_k²,  Σ_x,∞ = diag(σ_k², λ²σ_k²)

        Returns:
            The `SDEParams` of the two-state SDE.
        """
        dtype = jnp.result_type(self.variance, self.lengthscale)
        # λ = √3/ℓ
        rate = jnp.sqrt(3.0) / self.lengthscale
        # F_c = [[0, 1], [−λ², −2λ]]
        drift = jnp.array([[0.0, 1.0], [-(rate**2), -2.0 * rate]])
        # L_c = [0, 1]ᵀ
        noise_effect = jnp.array([[0.0], [1.0]], dtype=dtype)
        # H = [1, 0]
        obs_operator = jnp.array([[1.0, 0.0]], dtype=dtype)
        # q = 4λ³σ_k²
        density = 4.0 * rate**3 * self.variance
        # Q_c = q
        spectral_density = jnp.array([[density]])
        # Σ_x,∞ = diag(σ_k², λ²σ_k²)
        stationary_covariance = jnp.array(
            [[self.variance, 0.0], [0.0, rate**2 * self.variance]]
        )
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def _matern52(self) -> SDEParams:
        """Matérn-5/2 SDE on x = [f, f^(1), f^(2)], λ = √5/ℓ.

            F_c = [[0, 1, 0], [0, 0, 1], [−λ³, −3λ², −3λ]]
            L_c = [0, 0, 1]ᵀ,  H = [1, 0, 0],  Q_c = 16λ⁵σ_k²/3
            Σ_x,∞ = [[σ_k², 0, −v₁], [0, v₁, 0], [−v₁, 0, λ⁴σ_k²]]

        with v₁ = 5σ_k²/(3ℓ²) the variance of f^(1).

        Returns:
            The `SDEParams` of the three-state SDE.
        """
        dtype = jnp.result_type(self.variance, self.lengthscale)
        # λ = √5/ℓ
        rate = jnp.sqrt(5.0) / self.lengthscale
        # F_c = [[0, 1, 0], [0, 0, 1], [−λ³, −3λ², −3λ]]
        drift = jnp.array(
            [
                [0.0, 1.0, 0.0],
                [0.0, 0.0, 1.0],
                [-(rate**3), -3.0 * rate**2, -3.0 * rate],
            ]
        )
        # L_c = [0, 0, 1]ᵀ
        noise_effect = jnp.array([[0.0], [0.0], [1.0]], dtype=dtype)
        # H = [1, 0, 0]
        obs_operator = jnp.array([[1.0, 0.0, 0.0]], dtype=dtype)
        # v₁ = 5σ_k²/(3ℓ²), the variance of f^(1)
        derivative_variance = 5.0 / 3.0 * self.variance / self.lengthscale**2
        # q = 16λ⁵σ_k²/3
        density = 16.0 / 3.0 * rate**5 * self.variance
        # Q_c = q
        spectral_density = jnp.array([[density]])
        # Σ_x,∞ = [[σ_k², 0, −v₁], [0, v₁, 0], [−v₁, 0, λ⁴σ_k²]]
        stationary_covariance = jnp.array(
            [
                [self.variance, 0.0, -derivative_variance],
                [0.0, derivative_variance, 0.0],
                [-derivative_variance, 0.0, rate**4 * self.variance],
            ]
        )
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

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 SDEParams of the Matérn-(p + ½) SDE.

Raises:

Type Description
ValueError

If order is not 0, 1 or 2.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_matern.py
def sde_params(self) -> SDEParams:
    """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞) for order p.

    Returns:
        The `SDEParams` of the Matérn-(p + ½) SDE.

    Raises:
        ValueError: If ``order`` is not 0, 1 or 2.
    """
    if self.order == 0:
        return self._matern12()
    elif self.order == 1:
        return self._matern32()
    elif self.order == 2:
        return self._matern52()
    else:
        msg = f"Unsupported Matern order {self.order}; must be 0, 1, or 2"
        raise ValueError(msg)

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
class ConstantSDE(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:
        variance: 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)
    """

    variance: Float[Array, ""]

    @property
    def state_dim(self) -> int:
        """State length D_x = 1."""
        return 1

    def sde_params(self) -> SDEParams:
        """Continuous-time parameters: zero drift and diffusion, variance σ_k².

        Returns:
            `SDEParams` with ``F = 0``, ``L = 0``, ``H = 1``, ``Q_c = 0`` and
            the stationary covariance ``P_inf = σ_k²``.
        """
        # Constant blocks follow the hyperparameter dtype; untyped
        # ``jnp.zeros``/``jnp.array`` are float64 under x64 (gh-224).
        dtype = jnp.result_type(self.variance)
        # drift 0
        F = jnp.zeros((1, 1), dtype=dtype)
        # diffusion 0
        L = jnp.zeros((1, 1), dtype=dtype)
        # observation 1
        H = jnp.array([[1.0]], dtype=dtype)
        # spectral density 0
        Q_c = jnp.zeros((1, 1), dtype=dtype)
        # stationary covariance σ_k²
        P_inf = jnp.array([[self.variance]])
        return SDEParams(F=F, L=L, H=H, Q_c=Q_c, P_inf=P_inf)

    def discretise(
        self,
        dt: Float[Array, ""],
    ) -> tuple[Float[Array, "d d"], Float[Array, "d d"]]:
        """Closed-form discretisation: transition 1 and model error 0.

        Args:
            dt: Time step Δt; unused, since nothing changes over time.

        Returns:
            Tuple ``(A, Q)`` of the discrete transition and the model-error
            covariance Σ_η.
        """
        dtype = jnp.result_type(self.variance)
        # transition exp(0 · Δt) = 1
        A = jnp.eye(1, dtype=dtype)
        # Σ_η = 0
        Q = jnp.zeros((1, 1), dtype=dtype)
        return A, Q

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 with F = 0, L = 0, H = 1, Q_c = 0 and

SDEParams

the stationary covariance P_inf = σ_k².

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_constant.py
def sde_params(self) -> SDEParams:
    """Continuous-time parameters: zero drift and diffusion, variance σ_k².

    Returns:
        `SDEParams` with ``F = 0``, ``L = 0``, ``H = 1``, ``Q_c = 0`` and
        the stationary covariance ``P_inf = σ_k²``.
    """
    # Constant blocks follow the hyperparameter dtype; untyped
    # ``jnp.zeros``/``jnp.array`` are float64 under x64 (gh-224).
    dtype = jnp.result_type(self.variance)
    # drift 0
    F = jnp.zeros((1, 1), dtype=dtype)
    # diffusion 0
    L = jnp.zeros((1, 1), dtype=dtype)
    # observation 1
    H = jnp.array([[1.0]], dtype=dtype)
    # spectral density 0
    Q_c = jnp.zeros((1, 1), dtype=dtype)
    # stationary covariance σ_k²
    P_inf = jnp.array([[self.variance]])
    return SDEParams(F=F, L=L, H=H, Q_c=Q_c, P_inf=P_inf)

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 (A, Q) of the discrete transition and the model-error

Float[Array, 'd d']

covariance Σ_η.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_constant.py
def discretise(
    self,
    dt: Float[Array, ""],
) -> tuple[Float[Array, "d d"], Float[Array, "d d"]]:
    """Closed-form discretisation: transition 1 and model error 0.

    Args:
        dt: Time step Δt; unused, since nothing changes over time.

    Returns:
        Tuple ``(A, Q)`` of the discrete transition and the model-error
        covariance Σ_η.
    """
    dtype = jnp.result_type(self.variance)
    # transition exp(0 · Δt) = 1
    A = jnp.eye(1, dtype=dtype)
    # Σ_η = 0
    Q = jnp.zeros((1, 1), dtype=dtype)
    return A, Q

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
class CosineSDE(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:
        variance: Kernel variance σ_k².
        frequency: 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
    """

    variance: Float[Array, ""]
    frequency: Float[Array, ""]

    @property
    def state_dim(self) -> int:
        """State length D_x = 2."""
        return 2

    def sde_params(self) -> SDEParams:
        """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞).

        Returns:
            `SDEParams` with F_c = [[0, −ω₀], [ω₀, 0]], L_c = 0, H = [1, 0],
            Q_c = 0 and Σ_x,∞ = σ_k² I₂.
        """
        # Constant blocks follow the hyperparameter dtype; untyped
        # ``jnp.zeros``/``jnp.eye`` are float64 under x64 (gh-224).
        dtype = jnp.result_type(self.variance, self.frequency)
        angular_frequency = self.frequency
        # F_c = [[0, −ω₀], [ω₀, 0]]
        drift = jnp.array([[0.0, -angular_frequency], [angular_frequency, 0.0]])
        # L_c = 0
        noise_effect = jnp.zeros((2, 1), dtype=dtype)
        # H = [1, 0]
        obs_operator = jnp.array([[1.0, 0.0]], dtype=dtype)
        # Q_c = 0
        spectral_density = jnp.zeros((1, 1), dtype=dtype)
        # Σ_x,∞ = σ_k² I₂
        stationary_covariance = self.variance * jnp.eye(2, dtype=dtype)
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def discretise(
        self,
        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

        Args:
            dt: Time step Δt.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t = 0.
        """
        angular_frequency = self.frequency
        # cos ω₀Δt
        cos_step = jnp.cos(angular_frequency * dt)
        # sin ω₀Δt
        sin_step = jnp.sin(angular_frequency * dt)
        # F_t = [[cos ω₀Δt, −sin ω₀Δt], [sin ω₀Δt, cos ω₀Δt]]
        transition = jnp.array([[cos_step, -sin_step], [sin_step, cos_step]])
        # Σ_η,t = 0
        model_noise_covariance = jnp.zeros((2, 2), dtype=transition.dtype)
        return transition, model_noise_covariance

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 with F_c = [[0, −ω₀], [ω₀, 0]], L_c = 0, H = [1, 0],

SDEParams

Q_c = 0 and Σ_x,∞ = σ_k² I₂.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
def sde_params(self) -> SDEParams:
    """Continuous-time parameters (F_c, L_c, H, Q_c, Σ_x,∞).

    Returns:
        `SDEParams` with F_c = [[0, −ω₀], [ω₀, 0]], L_c = 0, H = [1, 0],
        Q_c = 0 and Σ_x,∞ = σ_k² I₂.
    """
    # Constant blocks follow the hyperparameter dtype; untyped
    # ``jnp.zeros``/``jnp.eye`` are float64 under x64 (gh-224).
    dtype = jnp.result_type(self.variance, self.frequency)
    angular_frequency = self.frequency
    # F_c = [[0, −ω₀], [ω₀, 0]]
    drift = jnp.array([[0.0, -angular_frequency], [angular_frequency, 0.0]])
    # L_c = 0
    noise_effect = jnp.zeros((2, 1), dtype=dtype)
    # H = [1, 0]
    obs_operator = jnp.array([[1.0, 0.0]], dtype=dtype)
    # Q_c = 0
    spectral_density = jnp.zeros((1, 1), dtype=dtype)
    # Σ_x,∞ = σ_k² I₂
    stationary_covariance = self.variance * jnp.eye(2, dtype=dtype)
    return SDEParams(
        F=drift,
        L=noise_effect,
        H=obs_operator,
        Q_c=spectral_density,
        P_inf=stationary_covariance,
    )

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 (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t = 0.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
def discretise(
    self,
    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

    Args:
        dt: Time step Δt.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t = 0.
    """
    angular_frequency = self.frequency
    # cos ω₀Δt
    cos_step = jnp.cos(angular_frequency * dt)
    # sin ω₀Δt
    sin_step = jnp.sin(angular_frequency * dt)
    # F_t = [[cos ω₀Δt, −sin ω₀Δt], [sin ω₀Δt, cos ω₀Δt]]
    transition = jnp.array([[cos_step, -sin_step], [sin_step, cos_step]])
    # Σ_η,t = 0
    model_noise_covariance = jnp.zeros((2, 2), dtype=transition.dtype)
    return transition, model_noise_covariance

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
class PeriodicSDE(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:
        variance: Kernel variance σ_k².
        lengthscale: Lengthscale ℓ.
        period: Period T_period.
        n_harmonics: 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.
    """

    variance: Float[Array, ""]
    lengthscale: Float[Array, ""]
    period: Float[Array, ""]
    n_harmonics: int = eqx.field(static=True, default=6)

    @property
    def state_dim(self) -> int:
        """State length D_x = 2(J + 1)."""
        return 2 * (self.n_harmonics + 1)

    def sde_params(self) -> 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:
            The `SDEParams` of the J + 1 rotation blocks.
        """
        dtype = jnp.result_type(self.variance, self.lengthscale, self.period)
        n_blocks = self.n_harmonics + 1
        state_size = 2 * n_blocks
        # ω₀ = 2π / T_period
        base_frequency = 2.0 * jnp.pi / self.period

        # ℓ⁻²
        inv_lengthscale_sq = 1.0 / self.lengthscale**2
        # Dropping j = 0 left every covariance short by q₀ (gh-289).
        # weights 1 for j = 0, 2 for j ≥ 1
        weights = jnp.ones(n_blocks, dtype=dtype).at[1:].set(2.0)
        # e^{−ℓ⁻²} I_j(ℓ⁻²)
        scaled_bessel = _scaled_bessel_i(self.n_harmonics, inv_lengthscale_sq)
        # q_j = weight_j σ_k² e^{−ℓ⁻²} I_j(ℓ⁻²)
        harmonic_variances = self.variance * weights * scaled_bessel

        drift = jnp.zeros((state_size, state_size), dtype=dtype)
        stationary_covariance = jnp.zeros((state_size, state_size), dtype=dtype)
        for harmonic in range(n_blocks):
            # j ω₀
            frequency = harmonic * base_frequency
            block_start = 2 * harmonic
            # F_c block j = [[0, −jω₀], [jω₀, 0]]
            drift = drift.at[block_start, block_start + 1].set(-frequency)
            drift = drift.at[block_start + 1, block_start].set(frequency)
            # Σ_x,∞ block j = q_j I₂
            stationary_covariance = stationary_covariance.at[
                block_start, block_start
            ].set(harmonic_variances[harmonic])
            stationary_covariance = stationary_covariance.at[
                block_start + 1, block_start + 1
            ].set(harmonic_variances[harmonic])

        # L_c = 0
        noise_effect = jnp.zeros((state_size, 1), dtype=dtype)
        obs_operator = jnp.zeros((1, state_size), dtype=dtype)
        for harmonic in range(n_blocks):
            # H = [1, 0, 1, 0, …]: f(t) sums the first state of every block
            obs_operator = obs_operator.at[0, 2 * harmonic].set(1.0)

        # Q_c = 0
        spectral_density = jnp.zeros((1, 1), dtype=dtype)
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def discretise(
        self,
        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

        Args:
            dt: Time step Δt.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t = 0.
        """
        n_blocks = self.n_harmonics + 1
        state_size = 2 * n_blocks
        # ω₀ = 2π / T_period
        base_frequency = 2.0 * jnp.pi / self.period

        transition = jnp.zeros(
            (state_size, state_size), dtype=jnp.result_type(base_frequency, dt)
        )
        for harmonic in range(n_blocks):
            # j ω₀
            frequency = harmonic * base_frequency
            # cos jω₀Δt
            cos_step = jnp.cos(frequency * dt)
            # sin jω₀Δt
            sin_step = jnp.sin(frequency * dt)
            block_start = 2 * harmonic
            # F_t block j = [[cos jω₀Δt, −sin jω₀Δt], [sin jω₀Δt, cos jω₀Δt]]
            transition = transition.at[block_start, block_start].set(cos_step)
            transition = transition.at[block_start, block_start + 1].set(-sin_step)
            transition = transition.at[block_start + 1, block_start].set(sin_step)
            transition = transition.at[block_start + 1, block_start + 1].set(cos_step)

        # Σ_η,t = 0
        model_noise_covariance = jnp.zeros(
            (state_size, state_size), dtype=transition.dtype
        )
        return transition, model_noise_covariance

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 SDEParams of the J + 1 rotation blocks.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
def sde_params(self) -> 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:
        The `SDEParams` of the J + 1 rotation blocks.
    """
    dtype = jnp.result_type(self.variance, self.lengthscale, self.period)
    n_blocks = self.n_harmonics + 1
    state_size = 2 * n_blocks
    # ω₀ = 2π / T_period
    base_frequency = 2.0 * jnp.pi / self.period

    # ℓ⁻²
    inv_lengthscale_sq = 1.0 / self.lengthscale**2
    # Dropping j = 0 left every covariance short by q₀ (gh-289).
    # weights 1 for j = 0, 2 for j ≥ 1
    weights = jnp.ones(n_blocks, dtype=dtype).at[1:].set(2.0)
    # e^{−ℓ⁻²} I_j(ℓ⁻²)
    scaled_bessel = _scaled_bessel_i(self.n_harmonics, inv_lengthscale_sq)
    # q_j = weight_j σ_k² e^{−ℓ⁻²} I_j(ℓ⁻²)
    harmonic_variances = self.variance * weights * scaled_bessel

    drift = jnp.zeros((state_size, state_size), dtype=dtype)
    stationary_covariance = jnp.zeros((state_size, state_size), dtype=dtype)
    for harmonic in range(n_blocks):
        # j ω₀
        frequency = harmonic * base_frequency
        block_start = 2 * harmonic
        # F_c block j = [[0, −jω₀], [jω₀, 0]]
        drift = drift.at[block_start, block_start + 1].set(-frequency)
        drift = drift.at[block_start + 1, block_start].set(frequency)
        # Σ_x,∞ block j = q_j I₂
        stationary_covariance = stationary_covariance.at[
            block_start, block_start
        ].set(harmonic_variances[harmonic])
        stationary_covariance = stationary_covariance.at[
            block_start + 1, block_start + 1
        ].set(harmonic_variances[harmonic])

    # L_c = 0
    noise_effect = jnp.zeros((state_size, 1), dtype=dtype)
    obs_operator = jnp.zeros((1, state_size), dtype=dtype)
    for harmonic in range(n_blocks):
        # H = [1, 0, 1, 0, …]: f(t) sums the first state of every block
        obs_operator = obs_operator.at[0, 2 * harmonic].set(1.0)

    # Q_c = 0
    spectral_density = jnp.zeros((1, 1), dtype=dtype)
    return SDEParams(
        F=drift,
        L=noise_effect,
        H=obs_operator,
        Q_c=spectral_density,
        P_inf=stationary_covariance,
    )

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 (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t = 0.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_periodic.py
def discretise(
    self,
    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

    Args:
        dt: Time step Δt.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t = 0.
    """
    n_blocks = self.n_harmonics + 1
    state_size = 2 * n_blocks
    # ω₀ = 2π / T_period
    base_frequency = 2.0 * jnp.pi / self.period

    transition = jnp.zeros(
        (state_size, state_size), dtype=jnp.result_type(base_frequency, dt)
    )
    for harmonic in range(n_blocks):
        # j ω₀
        frequency = harmonic * base_frequency
        # cos jω₀Δt
        cos_step = jnp.cos(frequency * dt)
        # sin jω₀Δt
        sin_step = jnp.sin(frequency * dt)
        block_start = 2 * harmonic
        # F_t block j = [[cos jω₀Δt, −sin jω₀Δt], [sin jω₀Δt, cos jω₀Δt]]
        transition = transition.at[block_start, block_start].set(cos_step)
        transition = transition.at[block_start, block_start + 1].set(-sin_step)
        transition = transition.at[block_start + 1, block_start].set(sin_step)
        transition = transition.at[block_start + 1, block_start + 1].set(cos_step)

    # Σ_η,t = 0
    model_noise_covariance = jnp.zeros(
        (state_size, state_size), dtype=transition.dtype
    )
    return transition, model_noise_covariance

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. 0 is a Brownian random walk; 1 (the default) is the local linear trend, which is also the cubic-spline-equivalent prior: f^(2) is white noise there, and the smoothed posterior mean is the cubic smoothing spline. Each further order raises the spline by two degrees, so 2 is the quintic-spline prior.

P_0 Float[Array, 'd d'] | None

Initial state covariance Σ_x,0. A modelling choice rather than something the kernel can derive; None (the default) means a diffuse κ I with κ = 1/√ε_mach for the dtype.

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
class IntegratedWienerSDE(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:
        diffusion: 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: Number of integrations p. ``0`` is a Brownian random walk;
            ``1`` (the default) is the local linear trend, which is also
            the cubic-spline-equivalent prior: f^(2) is white noise there,
            and the smoothed posterior mean is the cubic smoothing spline.
            Each further order raises the spline by two degrees, so ``2``
            is the quintic-spline prior.
        P_0: Initial state covariance Σ_x,0. A modelling choice rather
            than something the kernel can derive; ``None`` (the default)
            means a diffuse κ I with κ = 1/√ε_mach for the dtype.

    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
        ... )  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        ValueError: IntegratedWienerSDE order must be non-negative
    """

    diffusion: Float[Array, ""]
    order: int = eqx.field(static=True, default=1)
    P_0: Float[Array, "d d"] | None = None

    def __check_init__(self) -> None:
        """Reject a negative order at construction.

        The state length is D_x = p + 1, so a negative order gives an
        empty state and fails later, deep inside whichever method is
        called first, with an index error about an axis of size zero.

        Raises:
            ValueError: If ``order`` is negative.
        """
        if self.order < 0:
            msg = (
                f"IntegratedWienerSDE order must be non-negative "
                f"(the state is [f, ..., f^(order)], of dimension "
                f"order + 1), got {self.order}."
            )
            raise ValueError(msg)

    @property
    def state_dim(self) -> int:
        """State length D_x = p + 1."""
        return self.order + 1

    @property
    def stationary(self) -> bool:
        """``False``: the marginal variance grows without bound."""
        return False

    def sde_params(self) -> 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:
            `SDEParams` with ``P_inf=None``.
        """
        # Constant blocks follow the hyperparameter dtype; untyped
        # ``jnp.zeros``/``jnp.eye`` are float64 under x64 (gh-224).
        dtype = _inexact_dtype(self.diffusion)
        state_size = self.state_dim
        # F_c = [[0, I_p], [0, 0]], the upward shift
        drift = jnp.eye(state_size, k=1, dtype=dtype)
        # L_c = e_p
        noise_effect = (
            jnp.zeros((state_size, 1), dtype=dtype).at[state_size - 1, 0].set(1.0)
        )
        # H = e₀ᵀ
        obs_operator = jnp.zeros((1, state_size), dtype=dtype).at[0, 0].set(1.0)
        # Q_c
        spectral_density = jnp.full((1, 1), self.diffusion, dtype=dtype)
        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=None,
        )

    def initial_covariance(self) -> 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:
            Initial state covariance Σ_x,0.
        """
        dtype = _inexact_dtype(self.diffusion)
        if self.P_0 is None:
            # κ = 1/√ε_mach
            diffuse_variance = _default_diffuse_variance(dtype)
            # Σ_x,0 = κ I
            return diffuse_variance * jnp.eye(self.state_dim, dtype=dtype)
        return jnp.asarray(self.P_0, dtype=dtype)

    def discretise(
        self,
        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:
            1. Check Δt ≥ 0 with `equinox.error_if`.
            2. Form the 2p + 2 distinct powers Δt⁰, …, Δt^(2p+1) once.
            3. Build the static coefficient tables 1/(j−i)! and
               1/((p−i)! (p−j)! (2p+1−i−j)) on the host.
            4. 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.

        Args:
            dt: 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
                `equinox.error_if`, matching `gaussx.discretize_mfd`, so
                under ``jit`` the error fires at evaluation rather than
                trace time.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t.
        """
        dtype = _inexact_dtype(self.diffusion, dt)
        order = self.order
        state_size = self.state_dim

        # The closed form below is a polynomial in dt with no guard of
        # its own, unlike the ``expm`` routes; a negative step would run
        # it happily and hand back an indefinite Σ_η.
        dt = eqx.error_if(
            dt, dt < 0, "IntegratedWienerSDE.discretise requires dt >= 0."
        )

        # Powers are taken with *static* Python exponents so JAX lowers
        # them to ``integer_pow``, whose derivative is exact at zero. A
        # traced exponent would go through the generic ``y * x**(y-1)``
        # rule instead, and dt = 0 -- which the natural
        # ``diff(times, prepend=times[0])`` produces at the first step --
        # would differentiate to 0 * inf = NaN.
        def power(exponent: int) -> Float[Array, ""]:
            if exponent == 0:
                return jnp.ones_like(dt)
            # Δt^m
            return dt**exponent

        # Only 2p+2 distinct powers appear across both matrices, so they
        # are formed once and gathered by a static index table. That is
        # O(D_x) traced operations rather than one per entry: at order 40
        # the per-entry version took over five seconds to trace.
        # Δt⁰, …, Δt^(2p+1)
        powers = jnp.stack([power(m) for m in range(2 * order + 2)]).astype(dtype)

        # Host-side index grids i (rows) and j (columns).
        row, col = np.indices((state_size, state_size))
        upper = col >= row
        # Zeroed through the *coefficient* rather than by masking a
        # negative power, so no entry raises dt to a negative exponent.
        # j − i, clamped at 0 below the diagonal
        transition_power_index = np.maximum(col - row, 0)
        # 2p + 1 − i − j
        noise_power_index = 2 * order + 1 - row - col

        # ``1 / n`` keeps both operands Python ints, which are unbounded
        # and divide to a correctly rounded float. ``1.0 / n`` would
        # convert first and raise OverflowError from order 98 up, where
        # the denominator exceeds the float range even though its
        # reciprocal is perfectly representable (down to a subnormal,
        # and to zero beyond that).
        factorials = [math.factorial(n) for n in range(state_size)]
        # 1/(j−i)! for j ≥ i, else 0
        transition_coefficients = np.array(
            [
                [1 / factorials[c - r] if c >= r else 0.0 for c in range(state_size)]
                for r in range(state_size)
            ]
        )
        # 1/((p−i)! (p−j)! (2p+1−i−j))
        noise_coefficients = np.array(
            [
                [
                    1
                    / (
                        factorials[order - r]
                        * factorials[order - c]
                        * (2 * order + 1 - r - c)
                    )
                    for c in range(state_size)
                ]
                for r in range(state_size)
            ]
        )

        # [F_t]_ij = Δt^(j−i) / (j−i)!
        transition = (
            jnp.asarray(transition_coefficients * upper, dtype=dtype)
            * powers[transition_power_index]
        )
        # [Σ_η,t]_ij = Q_c Δt^(2p+1−i−j) / ((p−i)! (p−j)! (2p+1−i−j))
        model_noise_covariance = (
            self.diffusion
            * jnp.asarray(noise_coefficients, dtype=dtype)
            * powers[noise_power_index]
        )
        return transition.astype(dtype), model_noise_covariance.astype(dtype)

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

SDEParams with P_inf=None.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
def sde_params(self) -> 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:
        `SDEParams` with ``P_inf=None``.
    """
    # Constant blocks follow the hyperparameter dtype; untyped
    # ``jnp.zeros``/``jnp.eye`` are float64 under x64 (gh-224).
    dtype = _inexact_dtype(self.diffusion)
    state_size = self.state_dim
    # F_c = [[0, I_p], [0, 0]], the upward shift
    drift = jnp.eye(state_size, k=1, dtype=dtype)
    # L_c = e_p
    noise_effect = (
        jnp.zeros((state_size, 1), dtype=dtype).at[state_size - 1, 0].set(1.0)
    )
    # H = e₀ᵀ
    obs_operator = jnp.zeros((1, state_size), dtype=dtype).at[0, 0].set(1.0)
    # Q_c
    spectral_density = jnp.full((1, 1), self.diffusion, dtype=dtype)
    return SDEParams(
        F=drift,
        L=noise_effect,
        H=obs_operator,
        Q_c=spectral_density,
        P_inf=None,
    )

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
def initial_covariance(self) -> 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:
        Initial state covariance Σ_x,0.
    """
    dtype = _inexact_dtype(self.diffusion)
    if self.P_0 is None:
        # κ = 1/√ε_mach
        diffuse_variance = _default_diffuse_variance(dtype)
        # Σ_x,0 = κ I
        return diffuse_variance * jnp.eye(self.state_dim, dtype=dtype)
    return jnp.asarray(self.P_0, dtype=dtype)

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
  1. Check Δt ≥ 0 with equinox.error_if.
  2. Form the 2p + 2 distinct powers Δt⁰, …, Δt^(2p+1) once.
  3. Build the static coefficient tables 1/(j−i)! and 1/((p−i)! (p−j)! (2p+1−i−j)) on the host.
  4. 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 equinox.error_if, matching gaussx.discretize_mfd, so under jit the error fires at evaluation rather than trace time.

required

Returns:

Type Description
Float[Array, 'd d']

Tuple (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_wiener.py
def discretise(
    self,
    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:
        1. Check Δt ≥ 0 with `equinox.error_if`.
        2. Form the 2p + 2 distinct powers Δt⁰, …, Δt^(2p+1) once.
        3. Build the static coefficient tables 1/(j−i)! and
           1/((p−i)! (p−j)! (2p+1−i−j)) on the host.
        4. 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.

    Args:
        dt: 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
            `equinox.error_if`, matching `gaussx.discretize_mfd`, so
            under ``jit`` the error fires at evaluation rather than
            trace time.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t.
    """
    dtype = _inexact_dtype(self.diffusion, dt)
    order = self.order
    state_size = self.state_dim

    # The closed form below is a polynomial in dt with no guard of
    # its own, unlike the ``expm`` routes; a negative step would run
    # it happily and hand back an indefinite Σ_η.
    dt = eqx.error_if(
        dt, dt < 0, "IntegratedWienerSDE.discretise requires dt >= 0."
    )

    # Powers are taken with *static* Python exponents so JAX lowers
    # them to ``integer_pow``, whose derivative is exact at zero. A
    # traced exponent would go through the generic ``y * x**(y-1)``
    # rule instead, and dt = 0 -- which the natural
    # ``diff(times, prepend=times[0])`` produces at the first step --
    # would differentiate to 0 * inf = NaN.
    def power(exponent: int) -> Float[Array, ""]:
        if exponent == 0:
            return jnp.ones_like(dt)
        # Δt^m
        return dt**exponent

    # Only 2p+2 distinct powers appear across both matrices, so they
    # are formed once and gathered by a static index table. That is
    # O(D_x) traced operations rather than one per entry: at order 40
    # the per-entry version took over five seconds to trace.
    # Δt⁰, …, Δt^(2p+1)
    powers = jnp.stack([power(m) for m in range(2 * order + 2)]).astype(dtype)

    # Host-side index grids i (rows) and j (columns).
    row, col = np.indices((state_size, state_size))
    upper = col >= row
    # Zeroed through the *coefficient* rather than by masking a
    # negative power, so no entry raises dt to a negative exponent.
    # j − i, clamped at 0 below the diagonal
    transition_power_index = np.maximum(col - row, 0)
    # 2p + 1 − i − j
    noise_power_index = 2 * order + 1 - row - col

    # ``1 / n`` keeps both operands Python ints, which are unbounded
    # and divide to a correctly rounded float. ``1.0 / n`` would
    # convert first and raise OverflowError from order 98 up, where
    # the denominator exceeds the float range even though its
    # reciprocal is perfectly representable (down to a subnormal,
    # and to zero beyond that).
    factorials = [math.factorial(n) for n in range(state_size)]
    # 1/(j−i)! for j ≥ i, else 0
    transition_coefficients = np.array(
        [
            [1 / factorials[c - r] if c >= r else 0.0 for c in range(state_size)]
            for r in range(state_size)
        ]
    )
    # 1/((p−i)! (p−j)! (2p+1−i−j))
    noise_coefficients = np.array(
        [
            [
                1
                / (
                    factorials[order - r]
                    * factorials[order - c]
                    * (2 * order + 1 - r - c)
                )
                for c in range(state_size)
            ]
            for r in range(state_size)
        ]
    )

    # [F_t]_ij = Δt^(j−i) / (j−i)!
    transition = (
        jnp.asarray(transition_coefficients * upper, dtype=dtype)
        * powers[transition_power_index]
    )
    # [Σ_η,t]_ij = Q_c Δt^(2p+1−i−j) / ((p−i)! (p−j)! (2p+1−i−j))
    model_noise_covariance = (
        self.diffusion
        * jnp.asarray(noise_coefficients, dtype=dtype)
        * powers[noise_power_index]
    )
    return transition.astype(dtype), model_noise_covariance.astype(dtype)

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
class SumSDE(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:
        kernels: 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
    """

    kernels: tuple[SDEKernel, ...] = eqx.field()

    @property
    def state_dim(self) -> int:
        """State length D_x = ∑_i D_x^(i)."""
        return sum(k.state_dim for k in self.kernels)

    @property
    def stationary(self) -> bool:
        """Stationary only if every component is."""
        return all(k.stationary for k in self.kernels)

    def initial_covariance(self) -> 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:
            Initial state covariance Σ_x,0.
        """
        return jsl.block_diag(*[k.initial_covariance() for k in self.kernels])

    def sde_params(self) -> 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:
            The `SDEParams` of the sum.
        """
        component_params = [k.sde_params() for k in self.kernels]

        # F_c = blockdiag_i(F_c^(i))
        drift = jsl.block_diag(*[p.F for p in component_params])
        # A component with no closed-form stationary covariance leaves the
        # sum without one either; propagating ``None`` routes the composite
        # through ``discretize_mfd`` rather than fabricating a Σ_x,∞.
        component_stationary = [p.P_inf for p in component_params]
        # Σ_x,∞ = blockdiag_i(Σ_x,∞^(i))
        stationary_covariance = (
            None
            if any(block is None for block in component_stationary)
            else jsl.block_diag(*component_stationary)
        )

        # ``block_diag`` takes rectangular blocks and keeps their dtype; an
        # untyped ``jnp.zeros`` accumulator would be float64 under x64.
        # L_c = blockdiag_i(L_c^(i))
        noise_effect = jsl.block_diag(*[p.L for p in component_params])

        # Q_c = blockdiag_i(Q_c^(i))
        spectral_density = jsl.block_diag(*[p.Q_c for p in component_params])
        # H = [H^(1), …, H^(n)]
        obs_operator = jnp.concatenate([p.H for p in component_params], axis=1)

        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def discretise(
        self,
        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).

        Args:
            dt: Time step Δt.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t.
        """
        component_steps = [k.discretise(dt) for k in self.kernels]
        # F_t = blockdiag_i(F_t^(i))
        transition = jsl.block_diag(*(a for a, _ in component_steps))
        # Σ_η,t = blockdiag_i(Σ_η,t^(i))
        model_noise_covariance = jsl.block_diag(*(q for _, q in component_steps))
        return transition, model_noise_covariance

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
def initial_covariance(self) -> 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:
        Initial state covariance Σ_x,0.
    """
    return jsl.block_diag(*[k.initial_covariance() for k in self.kernels])

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 SDEParams of the sum.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
def sde_params(self) -> 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:
        The `SDEParams` of the sum.
    """
    component_params = [k.sde_params() for k in self.kernels]

    # F_c = blockdiag_i(F_c^(i))
    drift = jsl.block_diag(*[p.F for p in component_params])
    # A component with no closed-form stationary covariance leaves the
    # sum without one either; propagating ``None`` routes the composite
    # through ``discretize_mfd`` rather than fabricating a Σ_x,∞.
    component_stationary = [p.P_inf for p in component_params]
    # Σ_x,∞ = blockdiag_i(Σ_x,∞^(i))
    stationary_covariance = (
        None
        if any(block is None for block in component_stationary)
        else jsl.block_diag(*component_stationary)
    )

    # ``block_diag`` takes rectangular blocks and keeps their dtype; an
    # untyped ``jnp.zeros`` accumulator would be float64 under x64.
    # L_c = blockdiag_i(L_c^(i))
    noise_effect = jsl.block_diag(*[p.L for p in component_params])

    # Q_c = blockdiag_i(Q_c^(i))
    spectral_density = jsl.block_diag(*[p.Q_c for p in component_params])
    # H = [H^(1), …, H^(n)]
    obs_operator = jnp.concatenate([p.H for p in component_params], axis=1)

    return SDEParams(
        F=drift,
        L=noise_effect,
        H=obs_operator,
        Q_c=spectral_density,
        P_inf=stationary_covariance,
    )

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 (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
def discretise(
    self,
    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).

    Args:
        dt: Time step Δt.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t.
    """
    component_steps = [k.discretise(dt) for k in self.kernels]
    # F_t = blockdiag_i(F_t^(i))
    transition = jsl.block_diag(*(a for a, _ in component_steps))
    # Σ_η,t = blockdiag_i(Σ_η,t^(i))
    model_noise_covariance = jsl.block_diag(*(q for _, q in component_steps))
    return transition, model_noise_covariance

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
class ProductSDE(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:
        kernel1: First factor k^(1).
        kernel2: 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()  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        ...
        NotImplementedError: ProductSDE cannot report SDE parameters
    """

    kernel1: SDEKernel
    kernel2: SDEKernel

    @property
    def state_dim(self) -> int:
        """State length D_x = D_x^(1) D_x^(2)."""
        return self.kernel1.state_dim * self.kernel2.state_dim

    @property
    def stationary(self) -> bool:
        """Stationary only if both factors are."""
        return self.kernel1.stationary and self.kernel2.stationary

    def sde_params(self) -> 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:
            The `SDEParams` of the product.

        Raises:
            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.
        """
        params_1 = self.kernel1.sde_params()
        params_2 = self.kernel2.sde_params()

        state_size_1 = self.kernel1.state_dim
        state_size_2 = self.kernel2.state_dim

        if params_1.P_inf is None or params_2.P_inf is None:
            msg = (
                f"ProductSDE cannot report SDE parameters when a factor has "
                f"no stationary covariance: "
                f"{type(self.kernel1).__name__}.P_inf is "
                f"{'None' if params_1.P_inf is None else 'set'} and "
                f"{type(self.kernel2).__name__}.P_inf is "
                f"{'None' if params_2.P_inf is None else 'set'}. The composite "
                f"diffusion of a product kernel is B1 (x) P2 + P1 (x) B2, "
                f"which needs both. Use the factors' own parameters, or "
                f"give the factor a P_inf."
            )
            raise NotImplementedError(msg)

        # Identities carry the factor dtypes: an untyped ``jnp.eye`` is
        # float64 under x64 and would promote float32 kernels.
        identity_1 = jnp.eye(state_size_1, dtype=params_1.F.dtype)
        identity_2 = jnp.eye(state_size_2, dtype=params_2.F.dtype)

        # F_c = F_c^(1) ⊗ I + I ⊗ F_c^(2)
        drift = jnp.kron(params_1.F, identity_2) + jnp.kron(identity_1, params_2.F)
        # H = H^(1) ⊗ H^(2)
        obs_operator = jnp.kron(params_1.H, params_2.H)
        # Σ_x,∞ = Σ_x,∞^(1) ⊗ Σ_x,∞^(2)
        stationary_covariance = jnp.kron(params_1.P_inf, params_2.P_inf)

        # B_c = B_c^(1) ⊗ Σ_x,∞^(2) + Σ_x,∞^(1) ⊗ B_c^(2), kept in the
        # (L_c, Q_c) pair by putting each factor's Σ_x,∞ in the *spectral
        # density* rather than taking its square root:
        #
        #     B_c^(1) ⊗ Σ_x,∞^(2)
        #         = (L_c^(1) ⊗ I) (Q_c^(1) ⊗ Σ_x,∞^(2)) (L_c^(1) ⊗ I)ᵀ
        #     Σ_x,∞^(1) ⊗ B_c^(2)
        #         = (I ⊗ L_c^(2)) (Σ_x,∞^(1) ⊗ Q_c^(2)) (I ⊗ L_c^(2))ᵀ
        #
        # by the mixed-product property. Exact for any PSD Σ_x,∞, including
        # singular or zero ones, where a Cholesky would need jitter and stop
        # satisfying the Lyapunov equation this is here to enforce. The
        # noise dimension widens from D_b^(1) D_b^(2) to
        # D_b^(1) D_x^(2) + D_x^(1) D_b^(2).
        # L_c = [L_c^(1) ⊗ I, I ⊗ L_c^(2)]
        noise_effect = jnp.concatenate(
            [jnp.kron(params_1.L, identity_2), jnp.kron(identity_1, params_2.L)],
            axis=1,
        )
        # Q_c = blockdiag(Q_c^(1) ⊗ Σ_x,∞^(2), Σ_x,∞^(1) ⊗ Q_c^(2))
        spectral_density = jsl.block_diag(
            jnp.kron(params_1.Q_c, params_2.P_inf),
            jnp.kron(params_1.P_inf, params_2.Q_c),
        )

        return SDEParams(
            F=drift,
            L=noise_effect,
            H=obs_operator,
            Q_c=spectral_density,
            P_inf=stationary_covariance,
        )

    def discretise(
        self,
        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:
            1. Exponentiate each factor's drift, F_t^(i) = exp(F_c^(i) Δt).
            2. Form F_t = F_t^(1) ⊗ F_t^(2).
            3. Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ on Kronecker operands,
               then materialise and symmetrise it.

        Args:
            dt: Time step Δt > 0.

        Returns:
            Tuple ``(A, Q)`` holding the transition F_t and the
            model-noise covariance Σ_η,t, as in `SDEKernel.discretise`.

        Raises:
            NotImplementedError: If either factor lacks a stationary
                covariance.
        """
        params_1 = self.kernel1.sde_params()
        params_2 = self.kernel2.sde_params()
        # F_t^(1) = exp(F_c^(1) Δt)
        transition_1 = jsl.expm(params_1.F * dt)
        # F_t^(2) = exp(F_c^(2) Δt)
        transition_2 = jsl.expm(params_2.F * dt)
        # F_t = F_t^(1) ⊗ F_t^(2)
        transition = jnp.kron(transition_1, transition_2)

        # Use the per-factor stationary covariances directly; building
        # the full F_c via ``self.sde_params()`` would defeat the
        # whole point of this override. Keeping both operands as
        # ``Kronecker`` lets the shared helper contract each factor
        # separately instead of forming the full-size triple product.
        if params_1.P_inf is None or params_2.P_inf is None:
            # Deferring to the base MFD path here would be *wrong*, not
            # merely slower: the composite diffusion covariance
            #
            #     B_c = B_c^(1) ⊗ Σ_x,∞^(2) + Σ_x,∞^(1) ⊗ B_c^(2)
            #
            # needs both factor stationary covariances, exactly what is
            # missing, so MFD has nothing correct to consume. Checked
            # against the factors directly rather than via
            # ``self.sde_params()`` (which raises for the same reason)
            # so the message names the offending factor, and so the
            # happy path never builds the full-size drift it would
            # otherwise have to discard.
            msg = (
                f"ProductSDE cannot be discretised when a factor has no "
                f"stationary covariance: "
                f"{type(self.kernel1).__name__}.P_inf is "
                f"{'None' if params_1.P_inf is None else 'set'} and "
                f"{type(self.kernel2).__name__}.P_inf is "
                f"{'None' if params_2.P_inf is None else 'set'}. The composite "
                f"diffusion of a product kernel is B1 (x) P2 + P1 (x) B2, "
                f"which needs both. Discretise the factors separately, or "
                f"give the factor a P_inf."
            )
            raise NotImplementedError(msg)

        transition_op = Kronecker(
            lx.MatrixLinearOperator(transition_1),
            lx.MatrixLinearOperator(transition_2),
        )
        stationary_covariance_op = Kronecker(
            lx.MatrixLinearOperator(params_1.P_inf, lx.symmetric_tag),
            lx.MatrixLinearOperator(params_2.P_inf, lx.symmetric_tag),
        )
        # Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ, factor by factor
        model_noise_op = process_noise_covariance(
            transition_op, stationary_covariance_op
        )
        model_noise_covariance = symmetrize(model_noise_op.as_matrix())
        return transition, model_noise_covariance

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 SDEParams of the product.

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
def sde_params(self) -> 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:
        The `SDEParams` of the product.

    Raises:
        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.
    """
    params_1 = self.kernel1.sde_params()
    params_2 = self.kernel2.sde_params()

    state_size_1 = self.kernel1.state_dim
    state_size_2 = self.kernel2.state_dim

    if params_1.P_inf is None or params_2.P_inf is None:
        msg = (
            f"ProductSDE cannot report SDE parameters when a factor has "
            f"no stationary covariance: "
            f"{type(self.kernel1).__name__}.P_inf is "
            f"{'None' if params_1.P_inf is None else 'set'} and "
            f"{type(self.kernel2).__name__}.P_inf is "
            f"{'None' if params_2.P_inf is None else 'set'}. The composite "
            f"diffusion of a product kernel is B1 (x) P2 + P1 (x) B2, "
            f"which needs both. Use the factors' own parameters, or "
            f"give the factor a P_inf."
        )
        raise NotImplementedError(msg)

    # Identities carry the factor dtypes: an untyped ``jnp.eye`` is
    # float64 under x64 and would promote float32 kernels.
    identity_1 = jnp.eye(state_size_1, dtype=params_1.F.dtype)
    identity_2 = jnp.eye(state_size_2, dtype=params_2.F.dtype)

    # F_c = F_c^(1) ⊗ I + I ⊗ F_c^(2)
    drift = jnp.kron(params_1.F, identity_2) + jnp.kron(identity_1, params_2.F)
    # H = H^(1) ⊗ H^(2)
    obs_operator = jnp.kron(params_1.H, params_2.H)
    # Σ_x,∞ = Σ_x,∞^(1) ⊗ Σ_x,∞^(2)
    stationary_covariance = jnp.kron(params_1.P_inf, params_2.P_inf)

    # B_c = B_c^(1) ⊗ Σ_x,∞^(2) + Σ_x,∞^(1) ⊗ B_c^(2), kept in the
    # (L_c, Q_c) pair by putting each factor's Σ_x,∞ in the *spectral
    # density* rather than taking its square root:
    #
    #     B_c^(1) ⊗ Σ_x,∞^(2)
    #         = (L_c^(1) ⊗ I) (Q_c^(1) ⊗ Σ_x,∞^(2)) (L_c^(1) ⊗ I)ᵀ
    #     Σ_x,∞^(1) ⊗ B_c^(2)
    #         = (I ⊗ L_c^(2)) (Σ_x,∞^(1) ⊗ Q_c^(2)) (I ⊗ L_c^(2))ᵀ
    #
    # by the mixed-product property. Exact for any PSD Σ_x,∞, including
    # singular or zero ones, where a Cholesky would need jitter and stop
    # satisfying the Lyapunov equation this is here to enforce. The
    # noise dimension widens from D_b^(1) D_b^(2) to
    # D_b^(1) D_x^(2) + D_x^(1) D_b^(2).
    # L_c = [L_c^(1) ⊗ I, I ⊗ L_c^(2)]
    noise_effect = jnp.concatenate(
        [jnp.kron(params_1.L, identity_2), jnp.kron(identity_1, params_2.L)],
        axis=1,
    )
    # Q_c = blockdiag(Q_c^(1) ⊗ Σ_x,∞^(2), Σ_x,∞^(1) ⊗ Q_c^(2))
    spectral_density = jsl.block_diag(
        jnp.kron(params_1.Q_c, params_2.P_inf),
        jnp.kron(params_1.P_inf, params_2.Q_c),
    )

    return SDEParams(
        F=drift,
        L=noise_effect,
        H=obs_operator,
        Q_c=spectral_density,
        P_inf=stationary_covariance,
    )

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
  1. Exponentiate each factor's drift, F_t^(i) = exp(F_c^(i) Δt).
  2. Form F_t = F_t^(1) ⊗ F_t^(2).
  3. 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 (A, Q) holding the transition F_t and the

Float[Array, 'd d']

model-noise covariance Σ_η,t, as in SDEKernel.discretise.

Raises:

Type Description
NotImplementedError

If either factor lacks a stationary covariance.

Source code in .venv/lib/python3.12/site-packages/gaussx/_ssm/_composition.py
def discretise(
    self,
    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:
        1. Exponentiate each factor's drift, F_t^(i) = exp(F_c^(i) Δt).
        2. Form F_t = F_t^(1) ⊗ F_t^(2).
        3. Take Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ on Kronecker operands,
           then materialise and symmetrise it.

    Args:
        dt: Time step Δt > 0.

    Returns:
        Tuple ``(A, Q)`` holding the transition F_t and the
        model-noise covariance Σ_η,t, as in `SDEKernel.discretise`.

    Raises:
        NotImplementedError: If either factor lacks a stationary
            covariance.
    """
    params_1 = self.kernel1.sde_params()
    params_2 = self.kernel2.sde_params()
    # F_t^(1) = exp(F_c^(1) Δt)
    transition_1 = jsl.expm(params_1.F * dt)
    # F_t^(2) = exp(F_c^(2) Δt)
    transition_2 = jsl.expm(params_2.F * dt)
    # F_t = F_t^(1) ⊗ F_t^(2)
    transition = jnp.kron(transition_1, transition_2)

    # Use the per-factor stationary covariances directly; building
    # the full F_c via ``self.sde_params()`` would defeat the
    # whole point of this override. Keeping both operands as
    # ``Kronecker`` lets the shared helper contract each factor
    # separately instead of forming the full-size triple product.
    if params_1.P_inf is None or params_2.P_inf is None:
        # Deferring to the base MFD path here would be *wrong*, not
        # merely slower: the composite diffusion covariance
        #
        #     B_c = B_c^(1) ⊗ Σ_x,∞^(2) + Σ_x,∞^(1) ⊗ B_c^(2)
        #
        # needs both factor stationary covariances, exactly what is
        # missing, so MFD has nothing correct to consume. Checked
        # against the factors directly rather than via
        # ``self.sde_params()`` (which raises for the same reason)
        # so the message names the offending factor, and so the
        # happy path never builds the full-size drift it would
        # otherwise have to discard.
        msg = (
            f"ProductSDE cannot be discretised when a factor has no "
            f"stationary covariance: "
            f"{type(self.kernel1).__name__}.P_inf is "
            f"{'None' if params_1.P_inf is None else 'set'} and "
            f"{type(self.kernel2).__name__}.P_inf is "
            f"{'None' if params_2.P_inf is None else 'set'}. The composite "
            f"diffusion of a product kernel is B1 (x) P2 + P1 (x) B2, "
            f"which needs both. Discretise the factors separately, or "
            f"give the factor a P_inf."
        )
        raise NotImplementedError(msg)

    transition_op = Kronecker(
        lx.MatrixLinearOperator(transition_1),
        lx.MatrixLinearOperator(transition_2),
    )
    stationary_covariance_op = Kronecker(
        lx.MatrixLinearOperator(params_1.P_inf, lx.symmetric_tag),
        lx.MatrixLinearOperator(params_2.P_inf, lx.symmetric_tag),
    )
    # Σ_η,t = Σ_x,∞ − F_t Σ_x,∞ F_tᵀ, factor by factor
    model_noise_op = process_noise_covariance(
        transition_op, stationary_covariance_op
    )
    model_noise_covariance = symmetrize(model_noise_op.as_matrix())
    return transition, model_noise_covariance

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 MaternSDE.

kernel2 SDEKernel

Periodic factor k^(2), typically a PeriodicSDE.

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
class QuasiPeriodicSDE(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:
        kernel1: Modulating factor k^(1), typically a `MaternSDE`.
        kernel2: Periodic factor k^(2), typically a `PeriodicSDE`.

    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))
    """

    pass

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

\[ x_0 \sim \mathcal{N}(m_0, P_0), \qquad x_k = A_k x_{k-1} + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad y_k = H_k x_k + b_k + \varepsilon_k, \quad \varepsilon_k \sim \mathcal{N}(0, R_k), \]

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

\[ \log p(y \mid \theta) = \sum_{k=1}^{T} \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\, H_k P_k^- H_k^\top + R_k\right), \]

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 (T, D, D).

obs_model Float[Array, 'T M D'] | Float[Array, 'M D']

Observation matrices \(H_k\), shaped (T, M, D), or one (M, D) matrix for every step.

process_noise Float[Array, 'T D D']

Process-noise covariances \(Q_k\), shaped (T, D, D).

obs_noise Float[Array, 'T M M'] | Float[Array, 'M M']

Observation-noise covariances \(R_k\), shaped (T, M, M), or one (M, M) matrix for every step.

init_mean Float[Array, ' D']

Mean \(m_0\) of the initial state, shaped (D,).

init_cov Float[Array, 'D D']

Covariance \(P_0\) of the initial state, shaped (D, D).

obs_offset Float[Array, 'T M'] | None

Optional known observation offset \(b_k\), shaped (T, M); None is \(b_k = 0\). It is subtracted from y before filtering, so a GP with a mean function becomes an exact special case (pyrox_ssm.MarkovGPPrior.as_lgssm sets it to the mean at the observation times).

parallel bool

Filter with gaussx.parallel_kalman_filter, an associative scan, instead of the sequential gaussx.kalman_filter. Default False. Both give the same filtered moments, log marginal and gradients to round-off. The trade-off, measured on CPU for a scalar observation and a Matérn state of dimension 2 to 3 at 1,095 to 10,000 steps:

  • The value and gradient together (jax.value_and_grad, what NUTS and SVI call) are 1.2 to 1.8 times cheaper in parallel, because a reverse-mode pass through a sequential scan of small steps is slow.
  • The value alone is 1.5 to 2.2 times slower in parallel, so leave it off where only the value is needed (a fixed-parameter fit or predict).
  • The parallel filter runs in covariance form with dense solves in its combine step and does not take a solver; neither filter is a square-root filter.

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
class LinearGaussianSSMPrior(eqx.Module):
    r"""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

    $$
    x_0 \sim \mathcal{N}(m_0, P_0), \qquad
    x_k = A_k x_{k-1} + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad
    y_k = H_k x_k + b_k + \varepsilon_k, \quad
    \varepsilon_k \sim \mathcal{N}(0, R_k),
    $$

    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

    $$
    \log p(y \mid \theta) = \sum_{k=1}^{T}
      \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\,
      H_k P_k^- H_k^\top + R_k\right),
    $$

    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:
        transition: Transitions $A_k$, shaped ``(T, D, D)``.
        obs_model: Observation matrices $H_k$, shaped ``(T, M, D)``, or one
            ``(M, D)`` matrix for every step.
        process_noise: Process-noise covariances $Q_k$, shaped
            ``(T, D, D)``.
        obs_noise: Observation-noise covariances $R_k$, shaped
            ``(T, M, M)``, or one ``(M, M)`` matrix for every step.
        init_mean: Mean $m_0$ of the initial state, shaped ``(D,)``.
        init_cov: Covariance $P_0$ of the initial state, shaped ``(D, D)``.
        obs_offset: Optional known observation offset $b_k$, shaped
            ``(T, M)``; ``None`` is $b_k = 0$. It is subtracted from ``y``
            before filtering, so a GP with a mean function becomes an exact
            special case (`pyrox_ssm.MarkovGPPrior.as_lgssm` sets it to the
            mean at the observation times).
        parallel: Filter with `gaussx.parallel_kalman_filter`, an
            associative scan, instead of the sequential
            `gaussx.kalman_filter`. Default ``False``. Both give the same
            filtered moments, log marginal and gradients to round-off. The
            trade-off, measured on CPU for a scalar observation
            and a Matérn state of dimension 2 to 3 at 1,095 to 10,000 steps:

            - The value and gradient together (``jax.value_and_grad``, what
              NUTS and SVI call) are 1.2 to 1.8 times cheaper in parallel,
              because a reverse-mode pass through a sequential scan of small
              steps is slow.
            - The value alone is 1.5 to 2.2 times slower in parallel, so
              leave it off where only the value is needed (a fixed-parameter
              fit or predict).
            - The parallel filter runs in covariance form with dense solves
              in its combine step and does not take a ``solver``; neither
              filter is a square-root filter.

            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
        ()
    """

    transition: Float[Array, "T D D"]
    obs_model: Float[Array, "T M D"] | Float[Array, "M D"]
    process_noise: Float[Array, "T D D"]
    obs_noise: Float[Array, "T M M"] | Float[Array, "M M"]
    init_mean: Float[Array, " D"]
    init_cov: Float[Array, "D D"]
    obs_offset: Float[Array, "T M"] | None = None
    parallel: bool = eqx.field(static=True, default=False)

    def __init__(
        self,
        transition: Float[Array, "T D D"],
        obs_model: Float[Array, "T M D"] | Float[Array, "M D"],
        process_noise: Float[Array, "T D D"],
        obs_noise: Float[Array, "T M M"] | Float[Array, "M M"],
        init_mean: Float[Array, " D"],
        init_cov: Float[Array, "D D"],
        obs_offset: Float[Array, "T M"] | None = None,
        parallel: bool = False,
    ) -> None:
        transition = _as_float(transition)
        obs_model = _as_float(obs_model)
        process_noise = _as_float(process_noise)
        obs_noise = _as_float(obs_noise)
        init_mean = _as_float(init_mean)
        init_cov = _as_float(init_cov)
        if transition.ndim != 3 or transition.shape[1] != transition.shape[2]:
            raise ValueError(
                "transition must be a (T, D, D) stack of square matrices, got "
                f"shape {tuple(transition.shape)!r}"
            )
        T, D = transition.shape[0], transition.shape[1]
        if obs_model.ndim not in (2, 3) or obs_model.shape[-1] != D:
            raise ValueError(
                f"obs_model must have shape (T, M, D) or (M, D) with D = {D}, "
                f"got {tuple(obs_model.shape)!r}"
            )
        M = obs_model.shape[-2]
        _check_shape("obs_model", obs_model, ((T, M, D), (M, D)))
        _check_shape("process_noise", process_noise, ((T, D, D),))
        _check_shape("obs_noise", obs_noise, ((T, M, M), (M, M)))
        _check_shape("init_mean", init_mean, ((D,),))
        _check_shape("init_cov", init_cov, ((D, D),))
        if obs_offset is not None:
            obs_offset = _as_float(obs_offset)
            _check_shape("obs_offset", obs_offset, ((T, M),))
        self.transition = transition
        self.obs_model = obs_model
        self.process_noise = process_noise
        self.obs_noise = obs_noise
        self.init_mean = init_mean
        self.init_cov = init_cov
        self.obs_offset = obs_offset
        self.parallel = parallel

    @property
    def n_steps(self) -> int:
        """Number of observation steps $T$."""
        return self.transition.shape[0]

    @property
    def state_dim(self) -> int:
        """State dimension $D$."""
        return self.transition.shape[-1]

    @property
    def obs_dim(self) -> int:
        """Observation dimension $M$."""
        return self.obs_model.shape[-2]

    def _observations(
        self, y: Float[Array, "T M"] | Float[Array, " T"]
    ) -> Float[Array, "T M"]:
        """``y`` as a float ``(T, M)`` array; ``(T,)`` is accepted when M = 1."""
        y = _as_float(y)
        T, M = self.n_steps, self.obs_dim
        if y.ndim == 1 and M == 1:
            y = einx.id("t -> t 1", y)
        if tuple(y.shape) != (T, M):
            accepted = f"({T}, {M})" + (f" or ({T},)" if M == 1 else "")
            raise ValueError(
                f"y must have shape {accepted} for {T} steps and {M} outputs, "
                f"got {tuple(y.shape)!r}"
            )
        return y

    def _mask(
        self, mask: Bool[Array, " T"] | Bool[Array, "T M"] | None
    ) -> Bool[Array, " T"] | Bool[Array, "T M"] | None:
        """Validate ``mask`` as per step ``(T,)`` or per entry ``(T, M)``."""
        if mask is None:
            return None
        mask = jnp.asarray(mask).astype(bool)
        T, M = self.n_steps, self.obs_dim
        if tuple(mask.shape) not in ((T,), (T, M)):
            raise ValueError(
                f"mask has shape {tuple(mask.shape)!r}, but must be ({T},) to "
                f"mask whole steps or ({T}, {M}) to mask single entries"
            )
        return mask

    def _sanitise(
        self,
        y: Float[Array, "T M"],
        mask: Bool[Array, " T"] | Bool[Array, "T M"] | None,
    ) -> Float[Array, "T M"]:
        """Zero the masked entries of ``y``, so a ``NaN`` there is inert."""
        if mask is None:
            return y
        keep = mask if mask.ndim == 2 else einx.id("t -> t 1", mask)
        return jnp.where(keep, y, jnp.zeros((), dtype=y.dtype))

    def _residual(self, y: Float[Array, "T M"]) -> Float[Array, "T M"]:
        """``y - b``, the observations of the zero-offset model."""
        if self.obs_offset is None:
            return y
        return y - self.obs_offset

    def filter(
        self,
        y: Float[Array, "T M"] | Float[Array, " T"],
        *,
        mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
    ) -> FilterState:
        r"""Run the forward Kalman filter.

        Each step predicts, then updates on the observed entries of $y_k$,

        $$
        m_k^- = A_k m_{k-1}, \qquad P_k^- = A_k P_{k-1} A_k^\top + Q_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.

        Args:
            y: Observations, shaped ``(T, M)``; ``(T,)`` is accepted when
                $M = 1$. Masked entries may be ``NaN``.
            mask: Optional boolean mask, ``(T,)`` per step or ``(T, M)`` per
                entry, ``True`` where observed. ``None`` observes everything.

        Returns:
            The `gaussx.FilterState`: filtered and predicted means
            ``(T, D)`` and covariances ``(T, D, D)``, row $k - 1$ holding
            step $k$, and the scalar ``log_likelihood``.

        Raises:
            ValueError: If ``y`` or ``mask`` has the wrong shape.

        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), ())
        """
        mask = self._mask(mask)
        residual = self._residual(self._sanitise(self._observations(y), mask))
        kalman_filter = (
            gaussx.parallel_kalman_filter if self.parallel else gaussx.kalman_filter
        )
        return kalman_filter(
            transition=self.transition,
            obs_model=self.obs_model,
            process_noise=self.process_noise,
            obs_noise=self.obs_noise,
            observations=residual,
            init_mean=self.init_mean,
            init_cov=self.init_cov,
            mask=mask,
        )

    def log_marginal(
        self,
        y: Float[Array, "T M"] | Float[Array, " T"],
        *,
        mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
    ) -> Float[Array, ""]:
        r"""Marginal log-likelihood $\log p(y_{\mathrm{obs}} \mid \theta)$.

        $$
        \log p(y \mid \theta) = \sum_{k=1}^{T}
          \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\,
          H_k P_k^- H_k^\top + R_k\right),
        $$

        restricted to the observed entries when a mask is given.

        Args:
            y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
                masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            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)
        """
        return self.filter(y, mask=mask).log_likelihood

    def smooth(
        self,
        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, ""]]:
        r"""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`.

        Args:
            y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
                masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            ``(smoothed_means, smoothed_covs, log_marginal)``, shaped
            ``(T, D)``, ``(T, D, D)`` and ``()``.

        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))
        """
        state = self.filter(y, mask=mask)
        m_smooth, P_smooth = gaussx.rts_smoother(state, self.transition)
        return m_smooth, P_smooth, state.log_likelihood

    def sample(
        self, key: PRNGKeyArray, n: int = 1
    ) -> tuple[Float[Array, "S T D"], Float[Array, "S T M"]]:
        r"""Draws of $(x_{1:T}, y_{1:T})$ from the prior, by running the model forward.

        $$
        x_0 \sim \mathcal{N}(m_0, P_0), \qquad
        x_k = A_k x_{k-1} + \eta_k, \qquad
        y_k = H_k x_k + b_k + \varepsilon_k,
        $$

        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.

        Args:
            key: PRNG key.
            n: Number of independent draws $S$.

        Returns:
            ``(states, observations)``, shaped ``(S, T, D)`` and ``(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))
        """
        T, D, M = self.n_steps, self.state_dim, self.obs_dim
        dtype = self.init_mean.dtype
        init_root = _psd_root(self.init_cov)
        process_roots = jax.vmap(_psd_root)(self.process_noise)
        R = self.obs_noise
        obs_roots = jax.vmap(_psd_root)(R) if R.ndim == 3 else _psd_root(R)
        offset = (
            jnp.zeros((T, M), dtype=dtype)
            if self.obs_offset is None
            else self.obs_offset
        )

        def one(draw_key):
            init_key, state_key, obs_key = jr.split(draw_key, 3)
            # x_0 = m_0 + L_0 z_0
            x0 = self.init_mean + init_root @ jr.normal(init_key, (D,), dtype=dtype)
            state_noise = jr.normal(state_key, (T, D), dtype=dtype)

            def step(x_prev, inputs):
                transition, root, z = inputs
                # x_k = A_k x_{k-1} + L_{Q,k} z_k
                x = transition @ x_prev + root @ z
                return x, x

            _, states = jax.lax.scan(
                step, x0, (self.transition, process_roots, state_noise)
            )
            obs_noise = jr.normal(obs_key, (T, M), dtype=dtype)
            # H_k x_k and L_{R,k} e_k, with one H or R for every step or one per step
            if self.obs_model.ndim == 2:
                signal = einx.dot("m d, t d -> t m", self.obs_model, states)
            else:
                signal = einx.dot("t m d, t d -> t m", self.obs_model, states)
            if obs_roots.ndim == 2:
                noise = einx.dot("m n, t n -> t m", obs_roots, obs_noise)
            else:
                noise = einx.dot("t m n, t n -> t m", obs_roots, obs_noise)
            # y_k = H_k x_k + b_k + ε_k
            return states, signal + offset + noise

        return jax.vmap(one)(jr.split(key, n))

    def condition(
        self,
        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.

        Args:
            y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
                masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            The `ConditionedLinearGaussianSSM`, holding ``y`` as ``(T, M)``
            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)
        """
        mask = self._mask(mask)
        m_smooth, P_smooth, log_marg = self.smooth(y, mask=mask)
        return ConditionedLinearGaussianSSM(
            prior=self,
            y=self._sanitise(self._observations(y), mask),
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            log_marginal=log_marg,
            mask=mask,
        )

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\),

\[ m_k^- = A_k m_{k-1}, \qquad P_k^- = A_k P_{k-1} A_k^\top + Q_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 (T, M); (T,) is accepted when \(M = 1\). Masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional boolean mask, (T,) per step or (T, M) per entry, True where observed. None observes everything.

None

Returns:

Type Description
FilterState

The gaussx.FilterState: filtered and predicted means

FilterState

(T, D) and covariances (T, D, D), row \(k - 1\) holding

FilterState

step \(k\), and the scalar log_likelihood.

Raises:

Type Description
ValueError

If y or mask has the wrong shape.

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
def filter(
    self,
    y: Float[Array, "T M"] | Float[Array, " T"],
    *,
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
) -> FilterState:
    r"""Run the forward Kalman filter.

    Each step predicts, then updates on the observed entries of $y_k$,

    $$
    m_k^- = A_k m_{k-1}, \qquad P_k^- = A_k P_{k-1} A_k^\top + Q_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.

    Args:
        y: Observations, shaped ``(T, M)``; ``(T,)`` is accepted when
            $M = 1$. Masked entries may be ``NaN``.
        mask: Optional boolean mask, ``(T,)`` per step or ``(T, M)`` per
            entry, ``True`` where observed. ``None`` observes everything.

    Returns:
        The `gaussx.FilterState`: filtered and predicted means
        ``(T, D)`` and covariances ``(T, D, D)``, row $k - 1$ holding
        step $k$, and the scalar ``log_likelihood``.

    Raises:
        ValueError: If ``y`` or ``mask`` has the wrong shape.

    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), ())
    """
    mask = self._mask(mask)
    residual = self._residual(self._sanitise(self._observations(y), mask))
    kalman_filter = (
        gaussx.parallel_kalman_filter if self.parallel else gaussx.kalman_filter
    )
    return kalman_filter(
        transition=self.transition,
        obs_model=self.obs_model,
        process_noise=self.process_noise,
        obs_noise=self.obs_noise,
        observations=residual,
        init_mean=self.init_mean,
        init_cov=self.init_cov,
        mask=mask,
    )

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)\).

\[ \log p(y \mid \theta) = \sum_{k=1}^{T} \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\, H_k P_k^- H_k^\top + R_k\right), \]

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 (T, M) (or (T,) when \(M = 1\)); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

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
def log_marginal(
    self,
    y: Float[Array, "T M"] | Float[Array, " T"],
    *,
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
) -> Float[Array, ""]:
    r"""Marginal log-likelihood $\log p(y_{\mathrm{obs}} \mid \theta)$.

    $$
    \log p(y \mid \theta) = \sum_{k=1}^{T}
      \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\,
      H_k P_k^- H_k^\top + R_k\right),
    $$

    restricted to the observed entries when a mask is given.

    Args:
        y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
            masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        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)
    """
    return self.filter(y, mask=mask).log_likelihood

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 (T, M) (or (T,) when \(M = 1\)); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

None

Returns:

Type Description
Float[Array, 'T D']

(smoothed_means, smoothed_covs, log_marginal), shaped

Float[Array, 'T D D']

(T, D), (T, D, D) and ().

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
def smooth(
    self,
    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, ""]]:
    r"""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`.

    Args:
        y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
            masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        ``(smoothed_means, smoothed_covs, log_marginal)``, shaped
        ``(T, D)``, ``(T, D, D)`` and ``()``.

    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))
    """
    state = self.filter(y, mask=mask)
    m_smooth, P_smooth = gaussx.rts_smoother(state, self.transition)
    return m_smooth, P_smooth, state.log_likelihood

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.

\[ x_0 \sim \mathcal{N}(m_0, P_0), \qquad x_k = A_k x_{k-1} + \eta_k, \qquad y_k = H_k x_k + b_k + \varepsilon_k, \]

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']]

(states, observations), shaped (S, T, D) and (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
def sample(
    self, key: PRNGKeyArray, n: int = 1
) -> tuple[Float[Array, "S T D"], Float[Array, "S T M"]]:
    r"""Draws of $(x_{1:T}, y_{1:T})$ from the prior, by running the model forward.

    $$
    x_0 \sim \mathcal{N}(m_0, P_0), \qquad
    x_k = A_k x_{k-1} + \eta_k, \qquad
    y_k = H_k x_k + b_k + \varepsilon_k,
    $$

    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.

    Args:
        key: PRNG key.
        n: Number of independent draws $S$.

    Returns:
        ``(states, observations)``, shaped ``(S, T, D)`` and ``(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))
    """
    T, D, M = self.n_steps, self.state_dim, self.obs_dim
    dtype = self.init_mean.dtype
    init_root = _psd_root(self.init_cov)
    process_roots = jax.vmap(_psd_root)(self.process_noise)
    R = self.obs_noise
    obs_roots = jax.vmap(_psd_root)(R) if R.ndim == 3 else _psd_root(R)
    offset = (
        jnp.zeros((T, M), dtype=dtype)
        if self.obs_offset is None
        else self.obs_offset
    )

    def one(draw_key):
        init_key, state_key, obs_key = jr.split(draw_key, 3)
        # x_0 = m_0 + L_0 z_0
        x0 = self.init_mean + init_root @ jr.normal(init_key, (D,), dtype=dtype)
        state_noise = jr.normal(state_key, (T, D), dtype=dtype)

        def step(x_prev, inputs):
            transition, root, z = inputs
            # x_k = A_k x_{k-1} + L_{Q,k} z_k
            x = transition @ x_prev + root @ z
            return x, x

        _, states = jax.lax.scan(
            step, x0, (self.transition, process_roots, state_noise)
        )
        obs_noise = jr.normal(obs_key, (T, M), dtype=dtype)
        # H_k x_k and L_{R,k} e_k, with one H or R for every step or one per step
        if self.obs_model.ndim == 2:
            signal = einx.dot("m d, t d -> t m", self.obs_model, states)
        else:
            signal = einx.dot("t m d, t d -> t m", self.obs_model, states)
        if obs_roots.ndim == 2:
            noise = einx.dot("m n, t n -> t m", obs_roots, obs_noise)
        else:
            noise = einx.dot("t m n, t n -> t m", obs_roots, obs_noise)
        # y_k = H_k x_k + b_k + ε_k
        return states, signal + offset + noise

    return jax.vmap(one)(jr.split(key, n))

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 (T, M) (or (T,) when \(M = 1\)); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

None

Returns:

Type Description
ConditionedLinearGaussianSSM

The ConditionedLinearGaussianSSM, holding y as (T, M)

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
def condition(
    self,
    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.

    Args:
        y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
            masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        The `ConditionedLinearGaussianSSM`, holding ``y`` as ``(T, M)``
        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)
    """
    mask = self._mask(mask)
    m_smooth, P_smooth, log_marg = self.smooth(y, mask=mask)
    return ConditionedLinearGaussianSSM(
        prior=self,
        y=self._sanitise(self._observations(y), mask),
        smoothed_means=m_smooth,
        smoothed_covs=P_smooth,
        log_marginal=log_marg,
        mask=mask,
    )

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 LinearGaussianSSMPrior.

y Float[Array, 'T M']

Observations, (T, M), with masked entries set to zero.

smoothed_means Float[Array, 'T D']

Smoothed state means, (T, D).

smoothed_covs Float[Array, 'T D D']

Smoothed state covariances, (T, D, D).

log_marginal Float[Array, '']

Scalar \(\log p(y_{\mathrm{obs}} \mid \theta)\).

mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

The (T,) or (T, M) observation mask, or None when everything was observed.

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
class ConditionedLinearGaussianSSM(eqx.Module):
    r"""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:
        prior: The originating `LinearGaussianSSMPrior`.
        y: Observations, ``(T, M)``, with masked entries set to zero.
        smoothed_means: Smoothed state means, ``(T, D)``.
        smoothed_covs: Smoothed state covariances, ``(T, D, D)``.
        log_marginal: Scalar $\log p(y_{\mathrm{obs}} \mid \theta)$.
        mask: The ``(T,)`` or ``(T, M)`` observation mask, or ``None`` when
            everything was observed.

    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), ())
    """

    prior: LinearGaussianSSMPrior
    y: Float[Array, "T M"]
    smoothed_means: Float[Array, "T D"]
    smoothed_covs: Float[Array, "T D D"]
    log_marginal: Float[Array, ""]
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None

    def sample(self, key: PRNGKeyArray, n_paths: int = 1) -> Float[Array, "S T D"]:
        r"""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.

        Args:
            key: PRNG key.
            n_paths: Number of joint draws $S$.

        Returns:
            The state paths, shaped ``(S, T, D)``.

        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)
        """
        state = self.prior.filter(self.y, mask=self.mask)
        return gaussx.rts_sample(state, self.prior.transition, key, num_samples=n_paths)

    def predict(
        self, *, include_noise: bool = False
    ) -> tuple[Float[Array, "T M"], Float[Array, "T M"]]:
        r"""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),

        $$
        \mathbb{E}[y_k \mid y_{\mathrm{obs}}] = H_k m_{k \mid T} + b_k,
        \qquad
        \mathrm{Var}[(H_k x_k)_j \mid y_{\mathrm{obs}}]
          = (H_k P_{k \mid T} H_k^\top)_{jj},
        $$

        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.

        Args:
            include_noise: Add the observation-noise variance $(R_k)_{jj}$.
                Default ``False``.

        Returns:
            ``(mean, var)``, each shaped ``(T, M)``, row $k - 1$ holding
            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))
        """
        H = self.prior.obs_model
        # H_k m_k|T and diag(H_k P_k|T H_kᵀ), with one H or one per step.
        if H.ndim == 2:
            mean = einx.dot("m d, t d -> t m", H, self.smoothed_means)
            var = einx.dot("m d, t d e, m e -> t m", H, self.smoothed_covs, H)
        else:
            mean = einx.dot("t m d, t d -> t m", H, self.smoothed_means)
            var = einx.dot("t m d, t d e, t m e -> t m", H, self.smoothed_covs, H)
        if self.prior.obs_offset is not None:
            mean = mean + self.prior.obs_offset
        if include_noise:
            # diag(R_k), (M,) for one R or (T, M) for one per step; broadcasts.
            var = var + jnp.diagonal(self.prior.obs_noise, axis1=-2, axis2=-1)
        return mean, var

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 (S, T, D).

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
def sample(self, key: PRNGKeyArray, n_paths: int = 1) -> Float[Array, "S T D"]:
    r"""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.

    Args:
        key: PRNG key.
        n_paths: Number of joint draws $S$.

    Returns:
        The state paths, shaped ``(S, T, D)``.

    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)
    """
    state = self.prior.filter(self.y, mask=self.mask)
    return gaussx.rts_sample(state, self.prior.transition, key, num_samples=n_paths)

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),

\[ \mathbb{E}[y_k \mid y_{\mathrm{obs}}] = H_k m_{k \mid T} + b_k, \qquad \mathrm{Var}[(H_k x_k)_j \mid y_{\mathrm{obs}}] = (H_k P_{k \mid T} H_k^\top)_{jj}, \]

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.

False

Returns:

Type Description
Float[Array, 'T M']

(mean, var), each shaped (T, M), row \(k - 1\) holding

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
def predict(
    self, *, include_noise: bool = False
) -> tuple[Float[Array, "T M"], Float[Array, "T M"]]:
    r"""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),

    $$
    \mathbb{E}[y_k \mid y_{\mathrm{obs}}] = H_k m_{k \mid T} + b_k,
    \qquad
    \mathrm{Var}[(H_k x_k)_j \mid y_{\mathrm{obs}}]
      = (H_k P_{k \mid T} H_k^\top)_{jj},
    $$

    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.

    Args:
        include_noise: Add the observation-noise variance $(R_k)_{jj}$.
            Default ``False``.

    Returns:
        ``(mean, var)``, each shaped ``(T, M)``, row $k - 1$ holding
        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))
    """
    H = self.prior.obs_model
    # H_k m_k|T and diag(H_k P_k|T H_kᵀ), with one H or one per step.
    if H.ndim == 2:
        mean = einx.dot("m d, t d -> t m", H, self.smoothed_means)
        var = einx.dot("m d, t d e, m e -> t m", H, self.smoothed_covs, H)
    else:
        mean = einx.dot("t m d, t d -> t m", H, self.smoothed_means)
        var = einx.dot("t m d, t d e, t m e -> t m", H, self.smoothed_covs, H)
    if self.prior.obs_offset is not None:
        mean = mean + self.prior.obs_offset
    if include_noise:
        # diag(R_k), (M,) for one R or (T, M) for one per step; broadcasts.
        var = var + jnp.diagonal(self.prior.obs_noise, axis1=-2, axis2=-1)
    return mean, var

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,

\[ \log p(y \mid \theta) = \sum_{k=1}^{T} \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\, H_k P_k^- H_k^\top + R_k\right). \]

Registers the one site name.

Parameters:

Name Type Description Default
name str

The factor site name.

required
prior LinearGaussianSSMPrior

The LinearGaussianSSMPrior.

required
y Float[Array, 'T M'] | Float[Array, ' T']

Observations, shaped (T, M) (or (T,) when \(M = 1\)); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

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
def 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:
    r"""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,

    $$
    \log p(y \mid \theta) = \sum_{k=1}^{T}
      \log \mathcal{N}\!\left(y_k;\, H_k m_k^- + b_k,\,
      H_k P_k^- H_k^\top + R_k\right).
    $$

    Registers the one site ``name``.

    Args:
        name: The factor site name.
        prior: The `LinearGaussianSSMPrior`.
        y: Observations, shaped ``(T, M)`` (or ``(T,)`` when $M = 1$);
            masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where observed.

    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']
    """
    numpyro.factor(name, prior.log_marginal(y, mask=mask))

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

\[ x_0 \sim \mathcal{N}(m_0, P_0), \qquad x_k = f(x_{k-1}) + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad y_k = h(x_k) + \varepsilon_k, \quad \varepsilon_k \sim \mathcal{N}(0, R_k), \]

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

\[ \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T} \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k), \]

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 (D,) state to a (D,) state; a pytree (an eqx.Module or a closure), so its parameters get gradients.

obs_fn Callable[[Float[Array, ' D']], Float[Array, ' M']]

Observation map \(h\), from a (D,) state to an (M,) observation.

process_noise Float[Array, 'D D'] | Float[Array, 'T D D'] | AbstractLinearOperator

Process-noise covariance \(Q_k\): (D, D) for every step, a (T, D, D) stack, or a lineax operator.

obs_noise Float[Array, 'M M'] | Float[Array, 'T M M'] | AbstractLinearOperator

Observation-noise covariance \(R_k\): (M, M), (T, M, M) or a lineax operator.

init_mean Float[Array, ' D']

Mean \(m_0\) of the initial state, (D,).

init_cov Float[Array, 'D D']

Covariance \(P_0\) of the initial state, (D, D).

integrator AbstractIntegrator | None

The gaussx moment-matching rule. None is gaussx.UnscentedIntegrator(alpha=1.0), the default of gaussx.nonlinear_kalman_filter: derivative-free and exact for affine maps. gaussx.UnscentedIntegrator's own alpha=1e-3 loses about six digits to cancellation.

joseph bool

Use the Joseph-form covariance update. Default True.

solver AbstractSolverStrategy | None

Solver strategy for \(S_k\), passed through to gaussx. None factorises \(S_k\) once by Cholesky.

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
class NonlinearGaussianSSMPrior(eqx.Module):
    r"""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

    $$
    x_0 \sim \mathcal{N}(m_0, P_0), \qquad
    x_k = f(x_{k-1}) + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad
    y_k = h(x_k) + \varepsilon_k, \quad \varepsilon_k \sim \mathcal{N}(0, R_k),
    $$

    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

    $$
    \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T}
      \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k),
    $$

    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:
        dynamics: Deterministic dynamics $f$, from a ``(D,)`` state to a
            ``(D,)`` state; a pytree (an ``eqx.Module`` or a closure), so its
            parameters get gradients.
        obs_fn: Observation map $h$, from a ``(D,)`` state to an ``(M,)``
            observation.
        process_noise: Process-noise covariance $Q_k$: ``(D, D)`` for every
            step, a ``(T, D, D)`` stack, or a lineax operator.
        obs_noise: Observation-noise covariance $R_k$: ``(M, M)``,
            ``(T, M, M)`` or a lineax operator.
        init_mean: Mean $m_0$ of the initial state, ``(D,)``.
        init_cov: Covariance $P_0$ of the initial state, ``(D, D)``.
        integrator: The gaussx moment-matching rule. ``None`` is
            ``gaussx.UnscentedIntegrator(alpha=1.0)``, the default of
            `gaussx.nonlinear_kalman_filter`: derivative-free and exact for
            affine maps. `gaussx.UnscentedIntegrator`'s own ``alpha=1e-3``
            loses about six digits to cancellation.
        joseph: Use the Joseph-form covariance update. Default ``True``.
        solver: Solver strategy for $S_k$, passed through to gaussx.
            ``None`` factorises $S_k$ once by Cholesky.

    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)
    """

    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
    init_mean: Float[Array, " D"]
    init_cov: Float[Array, "D D"]
    integrator: AbstractIntegrator | None = None
    joseph: bool = eqx.field(static=True, default=True)
    solver: AbstractSolverStrategy | None = None

    def _integrator(self) -> AbstractIntegrator:
        return _default_integrator() if self.integrator is None else self.integrator

    def filter(
        self,
        y: Float[Array, "T M"],
        *,
        mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
    ) -> FilterState:
        """Run the moment-matched forward filter.

        Args:
            y: Observations, ``(T, M)``; masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            The `gaussx.FilterState`: filtered and predicted means ``(T, D)``
            and covariances ``(T, D, D)``, row $k - 1$ holding step $k$, and
            the scalar surrogate ``log_likelihood``.

        Raises:
            ValueError: If ``y`` is not ``(T, M)`` or ``mask`` is not ``(T,)``
                or ``(T, M)``.

        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)
        """
        y, mask = _check_observations(y, mask)
        return gaussx.nonlinear_kalman_filter(
            self.dynamics,
            self.obs_fn,
            self.process_noise,
            self.obs_noise,
            y,
            self.init_mean,
            self.init_cov,
            integrator=self._integrator(),
            mask=mask,
            joseph=self.joseph,
            solver=self.solver,
        )

    def log_marginal(
        self,
        y: Float[Array, "T M"],
        *,
        mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
    ) -> Float[Array, ""]:
        r"""The moment-matched surrogate of $\log p(y_{\mathrm{obs}} \mid \theta)$.

        $$
        \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T}
          \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k),
        $$

        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.

        Args:
            y: Observations, ``(T, M)``; masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            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]]))
        """
        return self.filter(y, mask=mask).log_likelihood

    def smooth(
        self,
        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, ""]]:
        r"""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}$.

        Args:
            y: Observations, ``(T, M)``; masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            ``(smoothed_means, smoothed_covs, log_marginal)``, shaped
            ``(T, D)``, ``(T, D, D)`` and ``()``, as
            `pyrox_ssm.LinearGaussianSSMPrior.smooth` returns.

        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))
        """
        state = self.filter(y, mask=mask)
        m_smooth, P_smooth = gaussx.nonlinear_rts_smoother(
            state, self.dynamics, integrator=self._integrator(), solver=self.solver
        )
        return m_smooth, P_smooth, state.log_likelihood

    def condition(
        self,
        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.

        Args:
            y: Observations, ``(T, M)``; masked entries may be ``NaN``.
            mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
                observed.

        Returns:
            The `ConditionedNonlinearGaussianSSM`, holding ``y`` with its
            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()
        """
        y_clean, mask = _check_observations(y, mask)
        m_smooth, P_smooth, log_marg = self.smooth(y_clean, mask=mask)
        return ConditionedNonlinearGaussianSSM(
            prior=self,
            y=y_clean,
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            log_marginal=log_marg,
            mask=mask,
        )

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, (T, M); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

None

Returns:

Type Description
FilterState

The gaussx.FilterState: filtered and predicted means (T, D)

FilterState

and covariances (T, D, D), row \(k - 1\) holding step \(k\), and

FilterState

the scalar surrogate log_likelihood.

Raises:

Type Description
ValueError

If y is not (T, M) or mask is not (T,) or (T, M).

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
def filter(
    self,
    y: Float[Array, "T M"],
    *,
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
) -> FilterState:
    """Run the moment-matched forward filter.

    Args:
        y: Observations, ``(T, M)``; masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        The `gaussx.FilterState`: filtered and predicted means ``(T, D)``
        and covariances ``(T, D, D)``, row $k - 1$ holding step $k$, and
        the scalar surrogate ``log_likelihood``.

    Raises:
        ValueError: If ``y`` is not ``(T, M)`` or ``mask`` is not ``(T,)``
            or ``(T, M)``.

    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)
    """
    y, mask = _check_observations(y, mask)
    return gaussx.nonlinear_kalman_filter(
        self.dynamics,
        self.obs_fn,
        self.process_noise,
        self.obs_noise,
        y,
        self.init_mean,
        self.init_cov,
        integrator=self._integrator(),
        mask=mask,
        joseph=self.joseph,
        solver=self.solver,
    )

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)\).

\[ \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T} \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k), \]

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, (T, M); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

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
def log_marginal(
    self,
    y: Float[Array, "T M"],
    *,
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None,
) -> Float[Array, ""]:
    r"""The moment-matched surrogate of $\log p(y_{\mathrm{obs}} \mid \theta)$.

    $$
    \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T}
      \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k),
    $$

    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.

    Args:
        y: Observations, ``(T, M)``; masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        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]]))
    """
    return self.filter(y, mask=mask).log_likelihood

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, (T, M); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

None

Returns:

Type Description
Float[Array, 'T D']

(smoothed_means, smoothed_covs, log_marginal), shaped

Float[Array, 'T D D']

(T, D), (T, D, D) and (), as

Float[Array, '']

pyrox_ssm.LinearGaussianSSMPrior.smooth returns.

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
def smooth(
    self,
    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, ""]]:
    r"""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}$.

    Args:
        y: Observations, ``(T, M)``; masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        ``(smoothed_means, smoothed_covs, log_marginal)``, shaped
        ``(T, D)``, ``(T, D, D)`` and ``()``, as
        `pyrox_ssm.LinearGaussianSSMPrior.smooth` returns.

    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))
    """
    state = self.filter(y, mask=mask)
    m_smooth, P_smooth = gaussx.nonlinear_rts_smoother(
        state, self.dynamics, integrator=self._integrator(), solver=self.solver
    )
    return m_smooth, P_smooth, state.log_likelihood

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, (T, M); masked entries may be NaN.

required
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional (T,) or (T, M) mask, True where observed.

None

Returns:

Type Description
ConditionedNonlinearGaussianSSM

The ConditionedNonlinearGaussianSSM, holding y with its

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
def condition(
    self,
    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.

    Args:
        y: Observations, ``(T, M)``; masked entries may be ``NaN``.
        mask: Optional ``(T,)`` or ``(T, M)`` mask, ``True`` where
            observed.

    Returns:
        The `ConditionedNonlinearGaussianSSM`, holding ``y`` with its
        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()
    """
    y_clean, mask = _check_observations(y, mask)
    m_smooth, P_smooth, log_marg = self.smooth(y_clean, mask=mask)
    return ConditionedNonlinearGaussianSSM(
        prior=self,
        y=y_clean,
        smoothed_means=m_smooth,
        smoothed_covs=P_smooth,
        log_marginal=log_marg,
        mask=mask,
    )

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 NonlinearGaussianSSMPrior.

y Float[Array, 'T M']

Observations, (T, M), with masked entries set to zero.

smoothed_means Float[Array, 'T D']

Smoothed state means, (T, D).

smoothed_covs Float[Array, 'T D D']

Smoothed state covariances, (T, D, D).

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 (T,) or (T, M) mask, or None when everything was observed.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_nonlinear.py
class ConditionedNonlinearGaussianSSM(eqx.Module):
    r"""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:
        prior: The originating `NonlinearGaussianSSMPrior`.
        y: Observations, ``(T, M)``, with masked entries set to zero.
        smoothed_means: Smoothed state means, ``(T, D)``.
        smoothed_covs: Smoothed state covariances, ``(T, D, D)``.
        log_marginal: The scalar moment-matched surrogate of
            $\log p(y_{\mathrm{obs}} \mid \theta)$.
        mask: The ``(T,)`` or ``(T, M)`` mask, or ``None`` when everything was
            observed.
    """

    prior: NonlinearGaussianSSMPrior
    y: Float[Array, "T M"]
    smoothed_means: Float[Array, "T D"]
    smoothed_covs: Float[Array, "T D D"]
    log_marginal: Float[Array, ""]
    mask: Bool[Array, " T"] | Bool[Array, "T M"] | None = None

    def predict(
        self, *, include_noise: bool = False
    ) -> tuple[Float[Array, "T M"], Float[Array, "T M"]]:
        r"""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`,

        $$
        \mathbb{E}[h(x_k) \mid y_{\mathrm{obs}}], \qquad
        \mathrm{Var}[h(x_k)_j \mid y_{\mathrm{obs}}], \qquad
        x_k \sim \mathcal{N}(m_{k \mid T}, P_{k \mid T}),
        $$

        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.

        Args:
            include_noise: Add the observation-noise variance $(R_k)_{jj}$.
                Default ``False``.

        Returns:
            ``(mean, var)``, each ``(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)
        """
        integrator = self.prior._integrator()

        def step(m, P):
            mean, cov, _ = gaussx.moment_transform(
                self.prior.obs_fn, m, P, integrator=integrator
            )
            return mean, jnp.diagonal(cov)

        mean, var = jax.vmap(step)(self.smoothed_means, self.smoothed_covs)
        if include_noise:
            R = self.prior.obs_noise
            if isinstance(R, lx.AbstractLinearOperator):
                R = R.as_matrix()
            # diag(R_k): (M,) for one R or (T, M) for one per step; broadcasts.
            var = var + jnp.diagonal(jnp.asarray(R), axis1=-2, axis2=-1)
        return mean, var

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,

\[ \mathbb{E}[h(x_k) \mid y_{\mathrm{obs}}], \qquad \mathrm{Var}[h(x_k)_j \mid y_{\mathrm{obs}}], \qquad x_k \sim \mathcal{N}(m_{k \mid T}, P_{k \mid T}), \]

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.

False

Returns:

Type Description
tuple[Float[Array, 'T M'], Float[Array, 'T M']]

(mean, var), each (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
def predict(
    self, *, include_noise: bool = False
) -> tuple[Float[Array, "T M"], Float[Array, "T M"]]:
    r"""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`,

    $$
    \mathbb{E}[h(x_k) \mid y_{\mathrm{obs}}], \qquad
    \mathrm{Var}[h(x_k)_j \mid y_{\mathrm{obs}}], \qquad
    x_k \sim \mathcal{N}(m_{k \mid T}, P_{k \mid T}),
    $$

    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.

    Args:
        include_noise: Add the observation-noise variance $(R_k)_{jj}$.
            Default ``False``.

    Returns:
        ``(mean, var)``, each ``(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)
    """
    integrator = self.prior._integrator()

    def step(m, P):
        mean, cov, _ = gaussx.moment_transform(
            self.prior.obs_fn, m, P, integrator=integrator
        )
        return mean, jnp.diagonal(cov)

    mean, var = jax.vmap(step)(self.smoothed_means, self.smoothed_covs)
    if include_noise:
        R = self.prior.obs_noise
        if isinstance(R, lx.AbstractLinearOperator):
            R = R.as_matrix()
        # diag(R_k): (M,) for one R or (T, M) for one per step; broadcasts.
        var = var + jnp.diagonal(jnp.asarray(R), axis1=-2, axis2=-1)
    return mean, var

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

\[ x_0 \sim \mathcal{N}(m_0, P_0), \qquad x_k = f(x_{k-1}) + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad y_k = h(x_k) + \varepsilon_k, \quad \varepsilon_k \sim \mathcal{N}(0, R_k), \]

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

\[ \hat{y}_k = \mathbb{E}[h(x_k)], \qquad S_k = \operatorname{Cov}[h(x_k)] + R_k, \qquad x_k \sim \mathcal{N}(m_k^-, P_k^-), \]

and the factor is the prediction-error sum

\[ \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T} \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k). \]

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 (D,) state to a (D,) state; the process noise is added separately.

required
obs_fn Callable[[Float[Array, ' D']], Float[Array, ' M']]

Observation map \(h\), from a (D,) state to an (M,) observation.

required
process_noise Float[Array, 'D D'] | Float[Array, 'T D D'] | AbstractLinearOperator

Process-noise covariance \(Q_k\): one (D, D) matrix for every step, a (T, D, D) stack, or a lineax operator.

required
obs_noise Float[Array, 'M M'] | Float[Array, 'T M M'] | AbstractLinearOperator

Observation-noise covariance \(R_k\), (M, M), (T, M, M) or a lineax operator.

required
y Float[Array, 'T M']

Observations \(y_{1:T}\), shaped (T, M); masked entries may be NaN.

required
init_mean Float[Array, ' D']

Mean \(m_0\) of the initial state \(x_0\), shaped (D,).

required
init_cov Float[Array, 'D D']

Covariance \(P_0\) of \(x_0\), shaped (D, D).

required
integrator AbstractIntegrator | None

The gaussx moment-matching rule. None (the default) is gaussx.UnscentedIntegrator(alpha=1.0), the default of gaussx.nonlinear_kalman_filter: derivative-free and exact for affine maps. gaussx.UnscentedIntegrator's own default alpha=1e-3 recovers the moments by cancellation and loses about six digits, which float32 cannot afford.

None
mask Bool[Array, ' T'] | Bool[Array, 'T M'] | None

Optional boolean mask, (T,) per step or (T, M) per entry, True where observed. None observes everything.

None
joseph bool

Use the Joseph-form covariance update, passed through to gaussx.nonlinear_kalman_filter. Defaults to True.

True
solver AbstractSolverStrategy | None

Solver strategy for \(S_k\), passed through to gaussx.nonlinear_kalman_filter. None factorises \(S_k\) once by Cholesky.

None

Returns:

Type Description
FilterState

The gaussx.FilterState: filtered and predicted means (T, D)

FilterState

and covariances (T, D, D), row \(k - 1\) holding step \(k\), and the

FilterState

scalar log_likelihood registered as the factor.

Raises:

Type Description
ValueError

If y is not (T, M) or mask is not (T,) or (T, M); gaussx raises for misshapen noise covariances.

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
def 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:
    r"""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

    $$
    x_0 \sim \mathcal{N}(m_0, P_0), \qquad
    x_k = f(x_{k-1}) + \eta_k, \quad \eta_k \sim \mathcal{N}(0, Q_k), \qquad
    y_k = h(x_k) + \varepsilon_k, \quad \varepsilon_k \sim \mathcal{N}(0, R_k),
    $$

    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

    $$
    \hat{y}_k = \mathbb{E}[h(x_k)], \qquad
    S_k = \operatorname{Cov}[h(x_k)] + R_k, \qquad
    x_k \sim \mathcal{N}(m_k^-, P_k^-),
    $$

    and the factor is the prediction-error sum

    $$
    \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T}
      \log \mathcal{N}(y_k;\, \hat{y}_k,\, S_k).
    $$

    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.

    Args:
        name: The factor site name.
        dynamics: Deterministic dynamics $f$, from a ``(D,)`` state to a
            ``(D,)`` state; the process noise is added separately.
        obs_fn: Observation map $h$, from a ``(D,)`` state to an ``(M,)``
            observation.
        process_noise: Process-noise covariance $Q_k$: one ``(D, D)``
            matrix for every step, a ``(T, D, D)`` stack, or a lineax
            operator.
        obs_noise: Observation-noise covariance $R_k$, ``(M, M)``,
            ``(T, M, M)`` or a lineax operator.
        y: Observations $y_{1:T}$, shaped ``(T, M)``; masked entries may be
            ``NaN``.
        init_mean: Mean $m_0$ of the initial state $x_0$, shaped ``(D,)``.
        init_cov: Covariance $P_0$ of $x_0$, shaped ``(D, D)``.
        integrator: The gaussx moment-matching rule. ``None`` (the default)
            is ``gaussx.UnscentedIntegrator(alpha=1.0)``, the default of
            `gaussx.nonlinear_kalman_filter`: derivative-free and exact for
            affine maps. `gaussx.UnscentedIntegrator`'s own default
            ``alpha=1e-3`` recovers the moments by cancellation and loses
            about six digits, which float32 cannot afford.
        mask: Optional boolean mask, ``(T,)`` per step or ``(T, M)`` per
            entry, ``True`` where observed. ``None`` observes everything.
        joseph: Use the Joseph-form covariance update, passed through to
            `gaussx.nonlinear_kalman_filter`. Defaults to ``True``.
        solver: Solver strategy for $S_k$, passed through to
            `gaussx.nonlinear_kalman_filter`. ``None`` factorises $S_k$ once
            by Cholesky.

    Returns:
        The `gaussx.FilterState`: filtered and predicted means ``(T, D)``
        and covariances ``(T, D, D)``, row $k - 1$ holding step $k$, and the
        scalar ``log_likelihood`` registered as the factor.

    Raises:
        ValueError: If ``y`` is not ``(T, M)`` or ``mask`` is not ``(T,)``
            or ``(T, M)``; gaussx raises for misshapen noise covariances.

    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']
    """
    prior = NonlinearGaussianSSMPrior(
        dynamics,
        obs_fn,
        process_noise,
        obs_noise,
        init_mean,
        init_cov,
        integrator=integrator,
        joseph=joseph,
        solver=solver,
    )
    state = prior.filter(y, mask=mask)
    numpyro.factor(name, state.log_likelihood)
    return state

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 SDEKernel. Provides (F, L, H, Q_c, P_inf) via sde_params() and the discrete transition sequence via discretise_sequence(dt).

times Float[Array, ' N']

Sorted, strictly increasing observation times of shape (N,). Concrete (non-traced) times arrays are validated for monotonicity at construction time; under jax.jit / SVI / MCMC the input is a tracer and the check is silently skipped — callers must guarantee monotonicity in that case.

mean_fn Callable[[Float[Array, ' N']], Float[Array, ' N']] | None

Optional callable mapping times -> (N,) mean values. Defaults to the zero mean. The mean is subtracted from observations before filtering and added back at predict time.

obs_noise_floor float

Small extra diagonal added to the observation variance R = noise_var + obs_noise_floor for stability when noise_var is near zero. Defaults to 0.0.

init_cov Float[Array, 'd d'] | None

Optional (d, d) covariance of the state at the first time point. None (the default) asks the kernel via initial_covariance(), which is \(P_\infty\) for a stationary kernel — so nothing changes for the kernels that have one — and an explicit diffuse covariance for a non-stationary one such as gaussx.IntegratedWienerSDE. Supply it to state what is known about the level (and its derivatives) before the first observation. Worth supplying for the site-based non-Gaussian strategies in particular: pyrox_ssm.PosteriorLinearizationMarkov and pyrox_ssm.ExpectationPropagationMarkov seed their cavities from the prior marginal variance, and a very diffuse prior can overflow their quadrature under an exponential-link likelihood — as a stationary kernel with an equally large variance does.

parallel bool

Run every Kalman filter over this prior (log_marginal, filter, smooth, condition, and each iteration of the non-Gaussian strategies) as gaussx.parallel_kalman_filter. Default False. The results agree with the sequential filter to round-off; the RTS smoother stays sequential. Measured on CPU (Matérn state of dimension 2 to 3):

  • With a Gaussian likelihood, turn it on where gradients dominate (NUTS, SVI): the value and gradient of log_marginal are 1.2 to 1.8 times cheaper at 1,095 to 10,000 steps, while the value alone is 1.5 to 2.2 times slower.
  • With the non-Gaussian strategies, leave it off: the Laplace evidence was slower in parallel both alone (1.4 to 1.6 times) and with its gradient (1.1 to 1.15 times) at 365 to 1,460 steps.

pyrox_ssm.LinearGaussianSSMPrior sets out the rest of the trade-off.

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
class MarkovGPPrior(eqx.Module):
    r"""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:
        sde_kernel: Any `SDEKernel`. Provides ``(F, L, H, Q_c, P_inf)``
            via ``sde_params()`` and the discrete transition sequence via
            ``discretise_sequence(dt)``.
        times: Sorted, strictly increasing observation times of shape
            ``(N,)``. Concrete (non-traced) ``times`` arrays are validated
            for monotonicity at construction time; under `jax.jit` /
            SVI / MCMC the input is a tracer and the check is silently
            skipped — callers must guarantee monotonicity in that case.
        mean_fn: Optional callable mapping ``times -> (N,)`` mean values.
            Defaults to the zero mean. The mean is subtracted from
            observations before filtering and added back at predict time.
        obs_noise_floor: Small extra diagonal added to the observation
            variance ``R = noise_var + obs_noise_floor`` for stability when
            ``noise_var`` is near zero. Defaults to ``0.0``.
        init_cov: Optional ``(d, d)`` covariance of the state at the first
            time point. ``None`` (the default) asks the kernel via
            ``initial_covariance()``, which is $P_\infty$ for a stationary
            kernel — so nothing changes for the kernels that have one — and
            an explicit diffuse covariance for a non-stationary one such as
            `gaussx.IntegratedWienerSDE`. Supply it to state what is known
            about the level (and its derivatives) before the first
            observation. Worth supplying for the site-based non-Gaussian
            strategies in particular: `pyrox_ssm.PosteriorLinearizationMarkov`
            and `pyrox_ssm.ExpectationPropagationMarkov` seed their cavities
            from the prior marginal variance, and a very diffuse prior can
            overflow their quadrature under an exponential-link likelihood
            — as a stationary kernel with an equally large variance does.
        parallel: Run every Kalman filter over this prior (`log_marginal`,
            `filter`, `smooth`, `condition`, and each iteration of the
            non-Gaussian strategies) as `gaussx.parallel_kalman_filter`.
            Default ``False``. The results agree with the sequential filter
            to round-off; the RTS smoother stays sequential. Measured on CPU
            (Matérn state of dimension 2 to 3):

            - With a Gaussian likelihood, turn it on where gradients
              dominate (NUTS, SVI): the value and gradient of
              `log_marginal` are 1.2 to 1.8 times cheaper at 1,095 to 10,000
              steps, while the value alone is 1.5 to 2.2 times slower.
            - With the non-Gaussian strategies, leave it off: the Laplace
              evidence was slower in parallel both alone (1.4 to 1.6 times)
              and with its gradient (1.1 to 1.15 times) at 365 to 1,460
              steps.

            `pyrox_ssm.LinearGaussianSSMPrior` sets out the rest of the
            trade-off.

    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``.
    """

    sde_kernel: SDEKernel
    times: Float[Array, " N"]
    mean_fn: Callable[[Float[Array, " N"]], Float[Array, " N"]] | None = None
    obs_noise_floor: float = eqx.field(static=True, default=0.0)
    init_cov: Float[Array, "d d"] | None = None
    parallel: bool = eqx.field(static=True, default=False)

    def __init__(
        self,
        sde_kernel: SDEKernel,
        times: Float[Array, " N"],
        mean_fn: Callable[[Float[Array, " N"]], Float[Array, " N"]] | None = None,
        obs_noise_floor: float = 0.0,
        init_cov: Float[Array, "d d"] | None = None,
        parallel: bool = False,
    ) -> None:
        if obs_noise_floor < 0:
            raise ValueError(
                f"obs_noise_floor must be non-negative, got {obs_noise_floor!r}"
            )
        times_arr = jnp.asarray(times, dtype=jnp.result_type(times, 0.0))
        if times_arr.ndim != 1:
            raise ValueError(f"times must be 1-D, got shape {tuple(times_arr.shape)!r}")
        # Eager monotonicity check for concrete (non-traced) inputs only.
        # Under ``jax.jit`` / SVI / similar transforms ``times`` may arrive as
        # a tracer; the ``bool`` conversion would raise, so we silence that
        # path and let downstream Kalman steps trust the contract.
        if times_arr.shape[0] >= 2:
            try:
                if not bool(jnp.all(jnp.diff(times_arr) > 0)):
                    raise ValueError("times must be strictly increasing")
            except jax.errors.TracerBoolConversionError:
                pass
        if init_cov is not None:
            # Promoted like ``times``: an integer covariance would seed the
            # scan with an int carry and fail inside it on a dtype mismatch.
            init_cov = jnp.asarray(init_cov, dtype=jnp.result_type(init_cov, 0.0))
            d = sde_kernel.state_dim
            if init_cov.shape != (d, d):
                raise ValueError(
                    f"init_cov must be ({d}, {d}) for a state dimension of "
                    f"{d}, got shape {tuple(init_cov.shape)!r}"
                )
        self.sde_kernel = sde_kernel
        self.times = times_arr
        self.mean_fn = mean_fn
        self.obs_noise_floor = float(obs_noise_floor)
        self.init_cov = init_cov
        self.parallel = parallel

    @property
    def state_dim(self) -> int:
        """SDE state dimension $d$ for this kernel."""
        return self.sde_kernel.state_dim

    def initial_covariance(self) -> Float[Array, "d d"]:
        r"""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).
        """
        if self.init_cov is not None:
            return self.init_cov
        return _kernel_initial_covariance(self.sde_kernel)

    def mean(self, times: Float[Array, " M"]) -> Float[Array, " M"]:
        """Evaluate the mean function at ``times``; zero by default."""
        if self.mean_fn is None:
            return jnp.zeros_like(times)
        return self.mean_fn(times)

    def _R(self, noise_var: Float[Array, ""]) -> Float[Array, ""]:
        return jnp.asarray(noise_var) + jnp.asarray(self.obs_noise_floor)

    def _observed(self, mask: Bool[Array, " N"] | None) -> Bool[Array, " N"] | None:
        """``mask`` checked against ``times``, or ``None`` when not given."""
        return None if mask is None else _observation_mask(mask, self.times)

    def as_lgssm(self, noise_var: Float[Array, ""]) -> LinearGaussianSSMPrior:
        r"""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,

        $$
        (A_k, Q_k) = \mathrm{discretise}(\Delta t_k), \qquad
        H_k = H, \qquad R_k = \sigma_n^2 + \epsilon, \qquad
        b_k = \mu(t_k), \qquad (m_0, P_0) = (0, P_{\mathrm{init}}),
        $$

        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.

        Args:
            noise_var: Observation noise variance $\sigma_n^2$.

        Returns:
            The `pyrox_ssm.LinearGaussianSSMPrior` over ``times``, with
            $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)
        """
        _F, _L, H, _Qc, _P_inf = self.sde_kernel.sde_params()
        init_cov = self.initial_covariance()
        A_seq, Q_seq = self.sde_kernel.discretise_sequence(_build_dt_full(self.times))
        R_seq = jnp.broadcast_to(self._R(noise_var), self.times.shape)
        return LinearGaussianSSMPrior(
            transition=A_seq,
            obs_model=H,
            process_noise=Q_seq,
            obs_noise=einx.id("n -> n 1 1", R_seq),
            init_mean=jnp.zeros(init_cov.shape[0], dtype=init_cov.dtype),
            init_cov=init_cov,
            obs_offset=einx.id("n -> n 1", self.mean(self.times)),
            parallel=self.parallel,
        )

    def filter(
        self,
        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, ""],
    ]:
        r"""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,

        $$
        \mu_k^+ = \mu_k^-, \qquad P_k^+ = P_k^-, \qquad
        \log p(y \mid \theta)
          = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R).
        $$

        Args:
            y: Observations of shape ``(N,)``. Masked entries are replaced
                by zero before the residual, so they may be ``NaN``.
            noise_var: Observation noise variance $\sigma_n^2$.
            mask: Optional ``(N,)`` boolean mask, ``True`` where a step is
                observed. ``None`` observes every step.

        Returns:
            Tuple ``(m_pred, P_pred, m_filt, P_filt, log_marginal)`` where
            each ``*_pred`` / ``*_filt`` is shaped ``(N, d)`` or
            ``(N, d, d)`` and ``log_marginal`` is the scalar log-likelihood
            ``log p(y | theta)`` of the observed steps.

        Raises:
            ValueError: If ``mask`` is not shaped like ``times``.

        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)
        """
        lgssm = self.as_lgssm(noise_var)
        return _filter_tuple(lgssm.filter(y, mask=self._observed(mask)))

    def log_marginal(
        self,
        y: Float[Array, " N"],
        noise_var: Float[Array, ""],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> Float[Array, ""]:
        r"""Marginal log-likelihood ``log p(y | theta)`` via Kalman filtering.

        A masked step contributes nothing,

        $$
        \log p(y \mid \theta)
          = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R),
        $$

        so padding a series after its last observation and masking the
        padded steps leaves the result unchanged.

        Args:
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            noise_var: Observation noise variance $\sigma_n^2$.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

        Returns:
            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)
        """
        lgssm = self.as_lgssm(noise_var)
        return lgssm.log_marginal(y, mask=self._observed(mask))

    def smooth(
        self,
        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, ""]]:
        r"""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.

        Args:
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            noise_var: Observation noise variance $\sigma_n^2$.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

        Returns:
            ``(m_smooth, P_smooth, log_marginal)`` over the training times,
            shaped ``(N, d)``, ``(N, d, d)`` and ``()``.

        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))
        """
        lgssm = self.as_lgssm(noise_var)
        return lgssm.smooth(y, mask=self._observed(mask))

    def condition(
        self,
        y: Float[Array, " N"],
        noise_var: Float[Array, ""],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> ConditionedMarkovGP:
        """Condition on Gaussian-likelihood observations via filter + smoother.

        Args:
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            noise_var: Observation noise variance.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. The
                conditioned GP keeps it, so `ConditionedMarkovGP.predict`
                treats the masked steps as unobserved too.

        Returns:
            The `ConditionedMarkovGP`, holding ``y`` with its masked entries
            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]))
        """
        m_smooth, P_smooth, log_marg = self.smooth(y, noise_var, mask=mask)
        return ConditionedMarkovGP(
            prior=self,
            y=_sanitise(y, mask),
            noise_var=jnp.asarray(noise_var),
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            log_marginal=log_marg,
            mask=None if mask is None else _observation_mask(mask, self.times),
        )

    def condition_nongauss(
        self,
        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`.

        Args:
            likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            strategy: The site-based strategy that fits the sites.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
                masked site has zero gradient and curvature, so its site
                precision is zero and the filter skips its update. Passed
                to ``strategy.fit`` only when given, so a strategy without
                a ``mask`` keyword still works unmasked.

        Returns:
            The `pyrox_ssm.ConditionedNonGaussMarkovGP` from the strategy.

        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]),
            ... )
        """
        if mask is None:
            return strategy.fit(self, likelihood, y)
        return strategy.fit(self, likelihood, y, mask=mask)

    def log_prob(self, f: Float[Array, " N"]) -> Float[Array, ""]:
        r"""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`.
        """
        K = _dense_sde_gram(self.sde_kernel, self.times)
        cov_op = lx.MatrixLinearOperator(K, lx.positive_semidefinite_tag)
        return gaussx.gaussian_log_prob(self.mean(self.times), cov_op, f)

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
def initial_covariance(self) -> Float[Array, "d d"]:
    r"""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).
    """
    if self.init_cov is not None:
        return self.init_cov
    return _kernel_initial_covariance(self.sde_kernel)

mean(times: Float[Array, ' M']) -> Float[Array, ' M']

Evaluate the mean function at times; zero by default.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
def mean(self, times: Float[Array, " M"]) -> Float[Array, " M"]:
    """Evaluate the mean function at ``times``; zero by default."""
    if self.mean_fn is None:
        return jnp.zeros_like(times)
    return self.mean_fn(times)

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,

\[ (A_k, Q_k) = \mathrm{discretise}(\Delta t_k), \qquad H_k = H, \qquad R_k = \sigma_n^2 + \epsilon, \qquad b_k = \mu(t_k), \qquad (m_0, P_0) = (0, P_{\mathrm{init}}), \]

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 pyrox_ssm.LinearGaussianSSMPrior over times, with

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
def as_lgssm(self, noise_var: Float[Array, ""]) -> LinearGaussianSSMPrior:
    r"""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,

    $$
    (A_k, Q_k) = \mathrm{discretise}(\Delta t_k), \qquad
    H_k = H, \qquad R_k = \sigma_n^2 + \epsilon, \qquad
    b_k = \mu(t_k), \qquad (m_0, P_0) = (0, P_{\mathrm{init}}),
    $$

    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.

    Args:
        noise_var: Observation noise variance $\sigma_n^2$.

    Returns:
        The `pyrox_ssm.LinearGaussianSSMPrior` over ``times``, with
        $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)
    """
    _F, _L, H, _Qc, _P_inf = self.sde_kernel.sde_params()
    init_cov = self.initial_covariance()
    A_seq, Q_seq = self.sde_kernel.discretise_sequence(_build_dt_full(self.times))
    R_seq = jnp.broadcast_to(self._R(noise_var), self.times.shape)
    return LinearGaussianSSMPrior(
        transition=A_seq,
        obs_model=H,
        process_noise=Q_seq,
        obs_noise=einx.id("n -> n 1 1", R_seq),
        init_mean=jnp.zeros(init_cov.shape[0], dtype=init_cov.dtype),
        init_cov=init_cov,
        obs_offset=einx.id("n -> n 1", self.mean(self.times)),
        parallel=self.parallel,
    )

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,

\[ \mu_k^+ = \mu_k^-, \qquad P_k^+ = P_k^-, \qquad \log p(y \mid \theta) = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R). \]

Parameters:

Name Type Description Default
y Float[Array, ' N']

Observations of shape (N,). Masked entries are replaced by zero before the residual, so they may be NaN.

required
noise_var Float[Array, '']

Observation noise variance \(\sigma_n^2\).

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where a step is observed. None observes every step.

None

Returns:

Type Description
Float[Array, 'N d']

Tuple (m_pred, P_pred, m_filt, P_filt, log_marginal) where

Float[Array, 'N d d']

each *_pred / *_filt is shaped (N, d) or

Float[Array, 'N d']

(N, d, d) and log_marginal is the scalar log-likelihood

Float[Array, 'N d d']

log p(y | theta) of the observed steps.

Raises:

Type Description
ValueError

If mask is not shaped like times.

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
def filter(
    self,
    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, ""],
]:
    r"""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,

    $$
    \mu_k^+ = \mu_k^-, \qquad P_k^+ = P_k^-, \qquad
    \log p(y \mid \theta)
      = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R).
    $$

    Args:
        y: Observations of shape ``(N,)``. Masked entries are replaced
            by zero before the residual, so they may be ``NaN``.
        noise_var: Observation noise variance $\sigma_n^2$.
        mask: Optional ``(N,)`` boolean mask, ``True`` where a step is
            observed. ``None`` observes every step.

    Returns:
        Tuple ``(m_pred, P_pred, m_filt, P_filt, log_marginal)`` where
        each ``*_pred`` / ``*_filt`` is shaped ``(N, d)`` or
        ``(N, d, d)`` and ``log_marginal`` is the scalar log-likelihood
        ``log p(y | theta)`` of the observed steps.

    Raises:
        ValueError: If ``mask`` is not shaped like ``times``.

    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)
    """
    lgssm = self.as_lgssm(noise_var)
    return _filter_tuple(lgssm.filter(y, mask=self._observed(mask)))

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,

\[ \log p(y \mid \theta) = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R), \]

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 (N,); masked entries may be NaN.

required
noise_var Float[Array, '']

Observation noise variance \(\sigma_n^2\).

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed.

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
def log_marginal(
    self,
    y: Float[Array, " N"],
    noise_var: Float[Array, ""],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> Float[Array, ""]:
    r"""Marginal log-likelihood ``log p(y | theta)`` via Kalman filtering.

    A masked step contributes nothing,

    $$
    \log p(y \mid \theta)
      = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R),
    $$

    so padding a series after its last observation and masking the
    padded steps leaves the result unchanged.

    Args:
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        noise_var: Observation noise variance $\sigma_n^2$.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

    Returns:
        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)
    """
    lgssm = self.as_lgssm(noise_var)
    return lgssm.log_marginal(y, mask=self._observed(mask))

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 (N,); masked entries may be NaN.

required
noise_var Float[Array, '']

Observation noise variance \(\sigma_n^2\).

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed.

None

Returns:

Type Description
Float[Array, 'N d']

(m_smooth, P_smooth, log_marginal) over the training times,

Float[Array, 'N d d']

shaped (N, d), (N, d, d) and ().

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
def smooth(
    self,
    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, ""]]:
    r"""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.

    Args:
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        noise_var: Observation noise variance $\sigma_n^2$.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

    Returns:
        ``(m_smooth, P_smooth, log_marginal)`` over the training times,
        shaped ``(N, d)``, ``(N, d, d)`` and ``()``.

    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))
    """
    lgssm = self.as_lgssm(noise_var)
    return lgssm.smooth(y, mask=self._observed(mask))

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 (N,); masked entries may be NaN.

required
noise_var Float[Array, '']

Observation noise variance.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. The conditioned GP keeps it, so ConditionedMarkovGP.predict treats the masked steps as unobserved too.

None

Returns:

Type Description
ConditionedMarkovGP

The ConditionedMarkovGP, holding y with its masked entries

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
def condition(
    self,
    y: Float[Array, " N"],
    noise_var: Float[Array, ""],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> ConditionedMarkovGP:
    """Condition on Gaussian-likelihood observations via filter + smoother.

    Args:
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        noise_var: Observation noise variance.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. The
            conditioned GP keeps it, so `ConditionedMarkovGP.predict`
            treats the masked steps as unobserved too.

    Returns:
        The `ConditionedMarkovGP`, holding ``y`` with its masked entries
        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]))
    """
    m_smooth, P_smooth, log_marg = self.smooth(y, noise_var, mask=mask)
    return ConditionedMarkovGP(
        prior=self,
        y=_sanitise(y, mask),
        noise_var=jnp.asarray(noise_var),
        smoothed_means=m_smooth,
        smoothed_covs=P_smooth,
        log_marginal=log_marg,
        mask=None if mask is None else _observation_mask(mask, self.times),
    )

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 pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
strategy _NonGaussMarkovStrategy

The site-based strategy that fits the sites.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. A masked site has zero gradient and curvature, so its site precision is zero and the filter skips its update. Passed to strategy.fit only when given, so a strategy without a mask keyword still works unmasked.

None

Returns:

Type Description
ConditionedNonGaussMarkovGP

The pyrox_ssm.ConditionedNonGaussMarkovGP from the strategy.

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
def condition_nongauss(
    self,
    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`.

    Args:
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        strategy: The site-based strategy that fits the sites.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
            masked site has zero gradient and curvature, so its site
            precision is zero and the filter skips its update. Passed
            to ``strategy.fit`` only when given, so a strategy without
            a ``mask`` keyword still works unmasked.

    Returns:
        The `pyrox_ssm.ConditionedNonGaussMarkovGP` from the strategy.

    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]),
        ... )
    """
    if mask is None:
        return strategy.fit(self, likelihood, y)
    return strategy.fit(self, likelihood, y, mask=mask)

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
def log_prob(self, f: Float[Array, " N"]) -> Float[Array, ""]:
    r"""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`.
    """
    K = _dense_sde_gram(self.sde_kernel, self.times)
    cov_op = lx.MatrixLinearOperator(K, lx.positive_semidefinite_tag)
    return gaussx.gaussian_log_prob(self.mean(self.times), cov_op, f)

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 MarkovGPPrior.

y Float[Array, ' N']

Observations of shape (N,).

noise_var Float[Array, '']

Observation variance used for conditioning.

smoothed_means Float[Array, 'N d']

(N, d) smoothed state means at training times.

smoothed_covs Float[Array, 'N d d']

(N, d, d) smoothed state covariances at training times.

log_marginal Float[Array, '']

Scalar \(\log p(y \mid \theta)\).

mask Bool[Array, ' N'] | None

Optional (N,) boolean observation mask from MarkovGPPrior.condition; predict leaves the masked steps out of the update. None means every step is observed.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_markov.py
class ConditionedMarkovGP(eqx.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:
        prior: The originating `MarkovGPPrior`.
        y: Observations of shape ``(N,)``.
        noise_var: Observation variance used for conditioning.
        smoothed_means: ``(N, d)`` smoothed state means at training times.
        smoothed_covs: ``(N, d, d)`` smoothed state covariances at training
            times.
        log_marginal: Scalar $\\log p(y \\mid \\theta)$.
        mask: Optional ``(N,)`` boolean observation mask from
            `MarkovGPPrior.condition`; `predict` leaves the masked steps
            out of the update. ``None`` means every step is observed.
    """

    prior: MarkovGPPrior
    y: Float[Array, " N"]
    noise_var: Float[Array, ""]
    smoothed_means: Float[Array, "N d"]
    smoothed_covs: Float[Array, "N d d"]
    log_marginal: Float[Array, ""]
    mask: Bool[Array, " N"] | None = None

    def predict(
        self,
        t_star: Float[Array, " M"],
        *,
        include_noise: bool = False,
    ) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
        r"""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.
        """
        F, _L, H, _Qc, _P_inf = self.prior.sde_kernel.sde_params()
        init_cov = self.prior.initial_covariance()
        times = self.prior.times
        t_star = jnp.asarray(t_star)

        N = times.shape[0]
        M = t_star.shape[0]
        merged = jnp.concatenate([times, t_star], axis=0)
        # Stable sort so the relative ordering of identical times is preserved
        # (training point sorts before a duplicate test point, so the test
        # point still sees the observation update earlier in the grid).
        order = jnp.argsort(merged, stable=True)
        merged_sorted = merged[order]

        observed = (
            jnp.ones(N, dtype=times.dtype)
            if self.mask is None
            else self.mask.astype(times.dtype)
        )
        is_obs = jnp.concatenate([observed, jnp.zeros(M, dtype=times.dtype)])[order]
        residual_full = jnp.concatenate(
            [self.y - self.prior.mean(times), jnp.zeros(M, dtype=self.y.dtype)]
        )[order]

        dt_full = _build_dt_full(merged_sorted)
        A_seq, Q_seq = self.prior.sde_kernel.discretise_sequence(dt_full)
        R_seq = jnp.broadcast_to(self.prior._R(self.noise_var), merged_sorted.shape)
        m_pred, P_pred, m_filt, P_filt, _ = _kalman_filter(
            F,
            H,
            init_cov,
            A_seq,
            Q_seq,
            residual_full,
            is_obs,
            R_seq,
            parallel=self.prior.parallel,
        )
        m_smooth, P_smooth = _rts_smoother(m_pred, P_pred, m_filt, P_filt, A_seq)

        # Inverse permutation: position in the sorted grid for each original
        # entry, then slice off the trailing M test entries.
        inv_order = jnp.argsort(order, stable=True)
        test_positions = inv_order[N:]
        m_test_state = m_smooth[test_positions]  # (M, d)
        P_test_state = P_smooth[test_positions]  # (M, d, d)
        means = (m_test_state @ H.T)[:, 0] + self.prior.mean(t_star)
        # var = H P H^T per test point — vmap over axis 0
        vars_ = jax.vmap(lambda P: (H @ P @ H.T)[0, 0])(P_test_state)
        if include_noise:
            vars_ = vars_ + self.prior._R(self.noise_var)
        return means, vars_

    def sample(
        self,
        key: PRNGKeyArray,
        n_paths: int = 1,
        t_star: Float[Array, " M"] | None = None,
    ) -> Float[Array, "S M"]:
        r"""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.

        Args:
            key: PRNG key.
            n_paths: Number of joint draws $S$.
            t_star: Optional test times ``(M,)``; ``None`` draws at the
                training times.

        Returns:
            The paths, shaped ``(S, M)`` (``(S, N)`` at the training times),
            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)
        """
        prior = self.prior
        _F, _L, H, _Qc, _P_inf = prior.sde_kernel.sde_params()
        times = prior.times
        if t_star is None:
            lgssm = prior.as_lgssm(self.noise_var)
            state = lgssm.filter(self.y, mask=self.mask)
            states = gaussx.rts_sample(state, lgssm.transition, key, n_paths)
            # f(t) = H x(t) + μ(t)
            return einx.dot("s n d, o d -> s n o", states, H)[..., 0] + prior.mean(
                times
            )

        t_star = jnp.asarray(t_star)
        n_train, n_test = times.shape[0], t_star.shape[0]
        merged = jnp.concatenate([times, t_star])
        # Stable sort: a test time equal to a training time sorts after it.
        order = jnp.argsort(merged, stable=True)
        observed = jnp.ones(n_train, dtype=bool) if self.mask is None else self.mask
        merged_mask = jnp.concatenate([observed, jnp.zeros(n_test, dtype=bool)])[order]
        merged_y = jnp.concatenate([self.y, jnp.zeros(n_test, dtype=self.y.dtype)])[
            order
        ]
        # tree_at skips __init__, whose strictly-increasing check a test time
        # equal to a training time would fail; a zero step is A = I, Q = 0.
        merged_prior = eqx.tree_at(lambda p: p.times, prior, merged[order])
        lgssm = merged_prior.as_lgssm(self.noise_var)
        state = lgssm.filter(merged_y, mask=merged_mask)
        states = gaussx.rts_sample(state, lgssm.transition, key, n_paths)
        test_rows = jnp.argsort(order, stable=True)[n_train:]
        # f(t_*) = H x(t_*) + μ(t_*)
        f_test = einx.dot("s m d, o d -> s m o", states[:, test_rows], H)[..., 0]
        return f_test + prior.mean(t_star)

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
def predict(
    self,
    t_star: Float[Array, " M"],
    *,
    include_noise: bool = False,
) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
    r"""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.
    """
    F, _L, H, _Qc, _P_inf = self.prior.sde_kernel.sde_params()
    init_cov = self.prior.initial_covariance()
    times = self.prior.times
    t_star = jnp.asarray(t_star)

    N = times.shape[0]
    M = t_star.shape[0]
    merged = jnp.concatenate([times, t_star], axis=0)
    # Stable sort so the relative ordering of identical times is preserved
    # (training point sorts before a duplicate test point, so the test
    # point still sees the observation update earlier in the grid).
    order = jnp.argsort(merged, stable=True)
    merged_sorted = merged[order]

    observed = (
        jnp.ones(N, dtype=times.dtype)
        if self.mask is None
        else self.mask.astype(times.dtype)
    )
    is_obs = jnp.concatenate([observed, jnp.zeros(M, dtype=times.dtype)])[order]
    residual_full = jnp.concatenate(
        [self.y - self.prior.mean(times), jnp.zeros(M, dtype=self.y.dtype)]
    )[order]

    dt_full = _build_dt_full(merged_sorted)
    A_seq, Q_seq = self.prior.sde_kernel.discretise_sequence(dt_full)
    R_seq = jnp.broadcast_to(self.prior._R(self.noise_var), merged_sorted.shape)
    m_pred, P_pred, m_filt, P_filt, _ = _kalman_filter(
        F,
        H,
        init_cov,
        A_seq,
        Q_seq,
        residual_full,
        is_obs,
        R_seq,
        parallel=self.prior.parallel,
    )
    m_smooth, P_smooth = _rts_smoother(m_pred, P_pred, m_filt, P_filt, A_seq)

    # Inverse permutation: position in the sorted grid for each original
    # entry, then slice off the trailing M test entries.
    inv_order = jnp.argsort(order, stable=True)
    test_positions = inv_order[N:]
    m_test_state = m_smooth[test_positions]  # (M, d)
    P_test_state = P_smooth[test_positions]  # (M, d, d)
    means = (m_test_state @ H.T)[:, 0] + self.prior.mean(t_star)
    # var = H P H^T per test point — vmap over axis 0
    vars_ = jax.vmap(lambda P: (H @ P @ H.T)[0, 0])(P_test_state)
    if include_noise:
        vars_ = vars_ + self.prior._R(self.noise_var)
    return means, vars_

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 (M,); None draws at the training times.

None

Returns:

Type Description
Float[Array, 'S M']

The paths, shaped (S, M) ((S, N) at the training times),

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
def sample(
    self,
    key: PRNGKeyArray,
    n_paths: int = 1,
    t_star: Float[Array, " M"] | None = None,
) -> Float[Array, "S M"]:
    r"""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.

    Args:
        key: PRNG key.
        n_paths: Number of joint draws $S$.
        t_star: Optional test times ``(M,)``; ``None`` draws at the
            training times.

    Returns:
        The paths, shaped ``(S, M)`` (``(S, N)`` at the training times),
        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)
    """
    prior = self.prior
    _F, _L, H, _Qc, _P_inf = prior.sde_kernel.sde_params()
    times = prior.times
    if t_star is None:
        lgssm = prior.as_lgssm(self.noise_var)
        state = lgssm.filter(self.y, mask=self.mask)
        states = gaussx.rts_sample(state, lgssm.transition, key, n_paths)
        # f(t) = H x(t) + μ(t)
        return einx.dot("s n d, o d -> s n o", states, H)[..., 0] + prior.mean(
            times
        )

    t_star = jnp.asarray(t_star)
    n_train, n_test = times.shape[0], t_star.shape[0]
    merged = jnp.concatenate([times, t_star])
    # Stable sort: a test time equal to a training time sorts after it.
    order = jnp.argsort(merged, stable=True)
    observed = jnp.ones(n_train, dtype=bool) if self.mask is None else self.mask
    merged_mask = jnp.concatenate([observed, jnp.zeros(n_test, dtype=bool)])[order]
    merged_y = jnp.concatenate([self.y, jnp.zeros(n_test, dtype=self.y.dtype)])[
        order
    ]
    # tree_at skips __init__, whose strictly-increasing check a test time
    # equal to a training time would fail; a zero step is A = I, Q = 0.
    merged_prior = eqx.tree_at(lambda p: p.times, prior, merged[order])
    lgssm = merged_prior.as_lgssm(self.noise_var)
    state = lgssm.filter(merged_y, mask=merged_mask)
    states = gaussx.rts_sample(state, lgssm.transition, key, n_paths)
    test_rows = jnp.argsort(order, stable=True)[n_train:]
    # f(t_*) = H x(t_*) + μ(t_*)
    f_test = einx.dot("s m d, o d -> s m o", states[:, test_rows], H)[..., 0]
    return f_test + prior.mean(t_star)

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,

\[ \log p(y \mid \theta) = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R). \]

Parameters:

Name Type Description Default
name str

The factor site name.

required
prior MarkovGPPrior

The MarkovGPPrior over the observation times.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
noise_var Float[Array, '']

Observation noise variance.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed.

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
def markov_gp_factor(
    name: str,
    prior: MarkovGPPrior,
    y: Float[Array, " N"],
    noise_var: Float[Array, ""],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> None:
    r"""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,

    $$
    \log p(y \mid \theta)
      = \sum_k o_k \log \mathcal{N}(y_k;\, H \mu_k^-,\, H P_k^- H^\top + R).
    $$

    Args:
        name: The factor site name.
        prior: The `MarkovGPPrior` over the observation times.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        noise_var: Observation noise variance.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

    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())
    """
    numpyro.factor(name, prior.log_marginal(y, noise_var, mask=mask))

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
def 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)$.
    """
    K = _dense_sde_gram(prior.sde_kernel, prior.times)
    mu = prior.mean(prior.times)
    return numpyro.sample(  # ty: ignore[invalid-return-type]
        name, dist.MultivariateNormal(mu, covariance_matrix=K)
    )

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,

\[ x_1 = L_0 \varepsilon_1, \qquad x_k = A_k x_{k-1} + L_{Q,k} \varepsilon_k \quad (k = 2, \dots, N), \qquad f(t_k) = H x_k + \mu(t_k), \]

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.cholesky of \(\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 turns NaN.
  • "eigh": the symmetric root \(Q \operatorname{diag}(\sqrt{\max(\gamma, 0)}) Q^\top\) from gaussx.sqrt (a dense eigh with 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. jitter is ignored.

Parameters:

Name Type Description Default
prior MarkovGPPrior

The MarkovGPPrior over the \(N\) sorted times.

required
eps Float[Array, '*batch N d']

Standard normal innovations of shape (*batch, N, d), one row per time, with \(d\) = prior.state_dim. Leading batch dimensions (a numpyro.plate, several paths) give one independent path each; the covariance roots are taken once and shared.

required
sqrt _SqrtMethod

How the covariance square roots are taken, "cholesky" or "eigh".

'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 (*batch, N), mean

Float[Array, '*batch N']

included.

Raises:

Type Description
ValueError

If the trailing shape of eps is not (N, d) or sqrt is unknown.

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
def markov_gp_from_innovations(
    prior: MarkovGPPrior,
    eps: Float[Array, "*batch N d"],
    *,
    sqrt: _SqrtMethod = "cholesky",
    jitter: float = 1e-10,
) -> Float[Array, "*batch N"]:
    r"""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`,

    $$
    x_1 = L_0 \varepsilon_1, \qquad
    x_k = A_k x_{k-1} + L_{Q,k} \varepsilon_k \quad (k = 2, \dots, N), \qquad
    f(t_k) = H x_k + \mu(t_k),
    $$

    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.cholesky` of
      $\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 turns
      ``NaN``.
    * ``"eigh"``: the symmetric root
      $Q \operatorname{diag}(\sqrt{\max(\gamma, 0)}) Q^\top$ from
      `gaussx.sqrt` (a dense ``eigh`` with 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.
      ``jitter`` is ignored.

    Args:
        prior: The `MarkovGPPrior` over the $N$ sorted times.
        eps: Standard normal innovations of shape ``(*batch, N, d)``, one
            row per time, with $d$ = ``prior.state_dim``. Leading batch
            dimensions (a ``numpyro.plate``, several paths) give one
            independent path each; the covariance roots are taken once and
            shared.
        sqrt: How the covariance square roots are taken, ``"cholesky"`` or
            ``"eigh"``.
        jitter: The diagonal $\beta$ added before the Cholesky factor.

    Returns:
        The path $f(t_1), \dots, f(t_N)$, shape ``(*batch, N)``, mean
        included.

    Raises:
        ValueError: If the trailing shape of ``eps`` is not ``(N, d)`` or
            ``sqrt`` is unknown.

    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)
    """
    if sqrt not in _SQRT_METHODS:
        raise ValueError(f"sqrt must be one of {_SQRT_METHODS!r}, got {sqrt!r}")
    n, d = prior.times.shape[0], prior.state_dim
    eps = jnp.asarray(eps)
    if eps.ndim < 2 or eps.shape[-2:] != (n, d):
        raise ValueError(
            f"eps must have shape (*batch, {n}, {d}), one row of {d} "
            f"innovations per time for a state dimension of {d}, got "
            f"{tuple(eps.shape)!r}"
        )
    batch_shape = eps.shape[:-2]
    _F, _L, H, _Qc, _P_inf = prior.sde_kernel.sde_params()
    # The leading zero step gives A_1 = I, so starting from x_0 = 0 and
    # replacing Q_1 = 0 by P_0 makes the first step draw x_1 = L_0 eps_1.
    A_seq, Q_seq = prior.sde_kernel.discretise_sequence(_build_dt_full(prior.times))
    cov_seq = Q_seq.at[0].set(prior.initial_covariance())
    L_seq = jax.vmap(lambda cov: _covariance_root(cov, sqrt=sqrt, jitter=jitter))(
        cov_seq
    )

    def step(
        x_prev: Float[Array, " d"],
        inputs: tuple[Float[Array, "d d"], Float[Array, "d d"], Float[Array, " d"]],
    ) -> tuple[Float[Array, " d"], Float[Array, " d"]]:
        A, L, e = inputs
        # xₖ = Aₖ xₖ₋₁ + L_{Q,k} εₖ
        x = einx.dot("i j, j -> i", A, x_prev) + einx.dot("i j, j -> i", L, e)
        return x, x

    x_init = jnp.zeros((d,), dtype=jnp.result_type(L_seq, eps))

    def path(e: Float[Array, "N d"]) -> Float[Array, " N"]:
        _, x_seq = jax.lax.scan(step, x_init, (A_seq, L_seq, e))
        # f(tₖ) = H xₖ
        return einx.dot("n d, o d -> n o", x_seq, H)[:, 0]

    # One scan per leading batch index, sharing A_seq and L_seq.
    f = jax.vmap(path)(eps.reshape((-1, n, d))).reshape((*batch_shape, n))
    # f(tₖ) += μ(tₖ)
    return f + prior.mean(prior.times)

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,

\[ \varepsilon \sim \mathcal{N}(0, I_{N d}), \qquad f = \mu + M \varepsilon, \qquad M M^\top = K, \]

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, a numpyro.deterministic holding the path of shape (N,), so numpyro.infer.Predictive returns it.

Parameters:

Name Type Description Default
name str

The deterministic site's name; the innovations site is f"{name}_eps".

required
prior MarkovGPPrior

The MarkovGPPrior over the \(N\) sorted times.

required
sqrt _SqrtMethod

How the covariance square roots are taken, "cholesky" or "eigh".

'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 (N,), or

Float[Array, ' N']

(*batch, N) under enclosing numpyro.plate contexts, one

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
def markov_gp_innovations_sample(
    name: str,
    prior: MarkovGPPrior,
    *,
    sqrt: _SqrtMethod = "cholesky",
    jitter: float = 1e-10,
) -> Float[Array, " N"]:
    r"""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,

    $$
    \varepsilon \sim \mathcal{N}(0, I_{N d}), \qquad
    f = \mu + M \varepsilon, \qquad M M^\top = K,
    $$

    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``, a ``numpyro.deterministic`` holding the path of shape
      ``(N,)``, so `numpyro.infer.Predictive` returns it.

    Args:
        name: The deterministic site's name; the innovations site is
            ``f"{name}_eps"``.
        prior: The `MarkovGPPrior` over the $N$ sorted times.
        sqrt: How the covariance square roots are taken, ``"cholesky"`` or
            ``"eigh"``.
        jitter: The diagonal added before the Cholesky factor.

    Returns:
        The path $f(t_1), \dots, f(t_N)$, shape ``(N,)``, or
        ``(*batch, N)`` under enclosing ``numpyro.plate`` contexts, one
        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)
    """
    n, d = prior.times.shape[0], prior.state_dim
    zero = jnp.zeros((), dtype=prior.times.dtype)
    eps = numpyro.sample(
        f"{name}_eps", dist.Normal(zero, 1.0).expand([n, d]).to_event(2)
    )
    # Enclosing plates prepend batch dimensions to eps; the path keeps them.
    f = markov_gp_from_innovations(prior, jnp.asarray(eps), sqrt=sqrt, jitter=jitter)
    return numpyro.deterministic(name, f)  # ty: ignore[invalid-return-type]

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,

\[ t_{N_s + j} = t_{N_s} + j\, \delta_s, \qquad \delta_s = \operatorname{median}(\operatorname{diff}(t_s)), \qquad j = 1, \dots, N - N_s, \]

with \(\delta_s = 1\) for a site with one observation. The padded steps are masked, and a masked step runs the Kalman predict only,

\[ \mu_k^+ = \mu_k^-, \qquad P_k^+ = P_k^-, \]

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 (N_s,) array of observation times per site.

required
ys Sequence[Float[Array, ' N_s']]

One (N_s,) array of observations per site, matching times. NaN marks a missing step when masks is not given.

required
masks Sequence[Bool[Array, ' N_s']] | None

Optional (N_s,) boolean array per site, True where the step is observed. Defaults to ~jnp.isnan(y) per site.

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 (t, y, mask), each of shape (S, N): the padded times,

Float[Array, 'S N']

the padded observations and a boolean mask that is True at each

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 times, ys and masks differ in length or shape, if a site is not a non-empty 1-D series, if a site's (concrete) times are not strictly increasing, or if length is shorter than the longest site.

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
def 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"]]:
    r"""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,

    $$
    t_{N_s + j} = t_{N_s} + j\, \delta_s, \qquad
    \delta_s = \operatorname{median}(\operatorname{diff}(t_s)), \qquad
    j = 1, \dots, N - N_s,
    $$

    with $\delta_s = 1$ for a site with one observation. The padded steps
    are masked, and a masked step runs the Kalman predict only,

    $$
    \mu_k^+ = \mu_k^-, \qquad P_k^+ = P_k^-,
    $$

    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.

    Args:
        times: One strictly increasing ``(N_s,)`` array of observation times
            per site.
        ys: One ``(N_s,)`` array of observations per site, matching
            ``times``. ``NaN`` marks a missing step when ``masks`` is not
            given.
        masks: Optional ``(N_s,)`` boolean array per site, ``True`` where the
            step is observed. Defaults to ``~jnp.isnan(y)`` per site.
        length: Padded length $N$. Defaults to the longest site,
            $\max_s N_s$.

    Returns:
        Tuple ``(t, y, mask)``, each of shape ``(S, N)``: the padded times,
        the padded observations and a boolean mask that is ``True`` at each
        row's observed steps: its first $N_s$ steps less any masked ones.

    Raises:
        ValueError: If no site is given, if ``times``, ``ys`` and ``masks``
            differ in length or shape, if a site is not a non-empty 1-D series, if a
            site's (concrete) times are not strictly increasing, or if
            ``length`` is shorter than the longest site.

    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,)
    """
    if len(times) != len(ys):
        raise ValueError(
            f"times has {len(times)} sites but ys has {len(ys)}; pass one "
            "series of each per site."
        )
    if len(times) == 0:
        raise ValueError("pad_sites needs at least one site.")
    if masks is not None and len(masks) != len(times):
        raise ValueError(
            f"masks has {len(masks)} sites but times has {len(times)}; pass "
            "one mask per site."
        )
    t_dtype = jnp.result_type(*times, 0.0)
    y_dtype = jnp.result_type(*ys)
    sites = []
    site_masks = [None] * len(times) if masks is None else list(masks)
    for s, (t_s, y_s, m_s) in enumerate(zip(times, ys, site_masks, strict=True)):
        t_s = jnp.asarray(t_s, dtype=t_dtype)
        y_s = jnp.asarray(y_s, dtype=y_dtype)
        if t_s.ndim != 1 or t_s.shape[0] == 0:
            raise ValueError(
                f"site {s}: times must be a non-empty 1-D series, got shape "
                f"{tuple(t_s.shape)!r}."
            )
        if y_s.shape != t_s.shape:
            raise ValueError(
                f"site {s}: ys has shape {tuple(y_s.shape)!r} but times has "
                f"{tuple(t_s.shape)!r}; each observation needs one time."
            )
        m_s = ~jnp.isnan(y_s) if m_s is None else jnp.asarray(m_s, dtype=bool)
        if m_s.shape != t_s.shape:
            raise ValueError(
                f"site {s}: masks has shape {tuple(m_s.shape)!r} but times has "
                f"{tuple(t_s.shape)!r}; pass one flag per observation."
            )
        if t_s.shape[0] >= 2:
            # Concrete times only; a tracer cannot be checked and is trusted,
            # as in MarkovGPPrior.
            try:
                if not bool(jnp.all(jnp.diff(t_s) > 0)):
                    raise ValueError(f"site {s}: times must be strictly increasing.")
            except jax.errors.TracerBoolConversionError:
                pass
        sites.append((t_s, jnp.where(m_s, y_s, 0), m_s))

    longest = max(t_s.shape[0] for t_s, _, _ in sites)
    n = longest if length is None else int(length)
    if n < longest:
        raise ValueError(
            f"length={n} is shorter than the longest site ({longest} "
            "observations); padding cannot drop observations."
        )

    t_rows, y_rows, mask_rows = [], [], []
    for t_s, y_s, m_s in sites:
        n_s = t_s.shape[0]
        # δₛ = median(diff(tₛ)), one time unit for a single observation
        step = jnp.median(jnp.diff(t_s)) if n_s >= 2 else jnp.ones((), dtype=t_dtype)
        # t_{Nₛ + j} = t_{Nₛ} + j δₛ,  j = 1, …, N − Nₛ
        padded_times = t_s[-1] + step * jnp.arange(1, n - n_s + 1, dtype=t_dtype)
        t_rows.append(jnp.concatenate([t_s, padded_times]))
        y_rows.append(jnp.concatenate([y_s, jnp.zeros(n - n_s, dtype=y_dtype)]))
        mask_rows.append(jnp.concatenate([m_s, jnp.zeros(n - n_s, dtype=bool)]))
    return jnp.stack(t_rows), jnp.stack(y_rows), jnp.stack(mask_rows)

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,

\[ \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2), \]

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 SDEKernel whose non-scalar array leaves have a leading site axis of length S.

times Float[Array, 'S N']

(S, N) padded times, strictly increasing along each row.

mask Bool[Array, 'S N'] | None

Optional (S, N) boolean mask, True where observed.

mean_fn Callable[[Float[Array, ' N']], Float[Array, ' N']] | None

Optional mean function times -> (N,), as in pyrox_ssm.MarkovGPPrior; shared, or one per site through array leaves with a leading (S,) axis.

obs_noise_floor float

Extra observation variance, as in pyrox_ssm.MarkovGPPrior.

Raises:

Type Description
ValueError

If times is not (S, N), mask is not shaped like it, or a non-scalar array leaf of the kernel or the mean function has a leading axis whose length is not S.

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
class MarkovGPSitesPrior(eqx.Module):
    r"""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,

    $$
    \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2),
    $$

    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:
        sde_kernel: An `SDEKernel` whose non-scalar array leaves have a
            leading site axis of length ``S``.
        times: ``(S, N)`` padded times, strictly increasing along each row.
        mask: Optional ``(S, N)`` boolean mask, ``True`` where observed.
        mean_fn: Optional mean function ``times -> (N,)``, as in
            `pyrox_ssm.MarkovGPPrior`; shared, or one per site through array
            leaves with a leading ``(S,)`` axis.
        obs_noise_floor: Extra observation variance, as in
            `pyrox_ssm.MarkovGPPrior`.

    Raises:
        ValueError: If ``times`` is not ``(S, N)``, ``mask`` is not shaped
            like it, or a non-scalar array leaf of the kernel or the mean
            function has a leading axis whose length is not ``S``.

    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)
    """

    sde_kernel: SDEKernel
    times: Float[Array, "S N"]
    mask: Bool[Array, "S N"] | None = None
    mean_fn: Callable[[Float[Array, " N"]], Float[Array, " N"]] | None = None
    obs_noise_floor: float = eqx.field(static=True, default=0.0)

    def __init__(
        self,
        sde_kernel: SDEKernel,
        times: Float[Array, "S N"],
        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:
        times = jnp.asarray(times, dtype=jnp.result_type(times, 0.0))
        if times.ndim != 2:
            raise ValueError(
                "times must be (S, N), one row per site, got shape "
                f"{tuple(times.shape)!r}."
            )
        if mask is not None:
            if jnp.shape(mask) != times.shape:
                raise ValueError(
                    f"mask has shape {tuple(jnp.shape(mask))!r} but times has "
                    f"{tuple(times.shape)!r}."
                )
            mask = jnp.asarray(mask).astype(bool)
        # Validate the site axis of the kernel's and the mean's leaves now.
        _site_axes(sde_kernel, times.shape[0])
        _site_axes(eqx.filter(mean_fn, eqx.is_array), times.shape[0])
        if obs_noise_floor < 0:
            raise ValueError(
                f"obs_noise_floor must be non-negative, got {obs_noise_floor!r}"
            )
        self.sde_kernel = sde_kernel
        self.times = times
        self.mask = mask
        self.mean_fn = mean_fn
        self.obs_noise_floor = float(obs_noise_floor)

    @property
    def n_sites(self) -> int:
        """Number of sites $S$."""
        return self.times.shape[0]

    def _mean_parts(self) -> tuple[Any, Any, Any]:
        """The mean's array leaves, their vmap axes, and the rest of it."""
        dynamic, static = eqx.partition(self.mean_fn, eqx.is_array)
        return dynamic, _site_axes(dynamic, self.n_sites), static

    def _site_prior(
        self, kernel_s: SDEKernel, t_s: Float[Array, " N"], mean_s: Any, static: Any
    ) -> MarkovGPPrior:
        mean_fn = None if self.mean_fn is None else eqx.combine(mean_s, static)
        return MarkovGPPrior(
            kernel_s, t_s, mean_fn=mean_fn, obs_noise_floor=self.obs_noise_floor
        )

    def _check_y(self, y: Float[Array, "S N"]) -> Float[Array, "S N"]:
        y = jnp.asarray(y)
        if y.shape != self.times.shape:
            raise ValueError(
                f"y has shape {tuple(y.shape)!r} but times has "
                f"{tuple(self.times.shape)!r}."
            )
        return y

    def _noise(
        self, noise_var: Float[Array, ""] | Float[Array, " S"]
    ) -> tuple[Float[Array, ""] | Float[Array, " S"], int | None]:
        """``noise_var`` as an array and its vmap axis, validated against S."""
        noise_var = jnp.asarray(noise_var)
        if noise_var.ndim not in (0, 1) or (
            noise_var.ndim == 1 and noise_var.shape[0] != self.n_sites
        ):
            raise ValueError(
                f"noise_var must be () or (S,)=({self.n_sites},), got shape "
                f"{tuple(noise_var.shape)!r}."
            )
        return noise_var, None if noise_var.ndim == 0 else 0

    def _site_log_marginals(
        self,
        y: Float[Array, "S N"],
        noise_var: Float[Array, ""] | Float[Array, " S"],
    ) -> Float[Array, " S"]:
        y = self._check_y(y)
        noise_var, noise_axis = self._noise(noise_var)
        mean_dynamic, mean_axes, mean_static = self._mean_parts()

        def site(kernel_s, mean_s, t_s, y_s, m_s, noise_s):
            prior_s = self._site_prior(kernel_s, t_s, mean_s, mean_static)
            return prior_s.log_marginal(y_s, noise_s, mask=m_s)

        in_axes = (
            _site_axes(self.sde_kernel, self.n_sites),
            mean_axes,
            0,
            0,
            None if self.mask is None else 0,
            noise_axis,
        )
        return jax.vmap(site, in_axes=in_axes)(
            self.sde_kernel, mean_dynamic, self.times, y, self.mask, noise_var
        )

    def log_marginal(
        self,
        y: Float[Array, "S N"],
        noise_var: Float[Array, ""] | Float[Array, " S"],
    ) -> Float[Array, ""]:
        r"""Summed log marginal of the sites' observed steps.

        $$
        \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2).
        $$

        Args:
            y: ``(S, N)`` observations; masked entries may be ``NaN``.
            noise_var: Observation noise variance, shared ``()`` or per site
                ``(S,)``.

        Returns:
            The scalar log marginal.

        Raises:
            ValueError: If ``y`` is not shaped like ``times``, or
                ``noise_var`` is neither ``()`` nor ``(S,)``.

        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]))
        """
        return jnp.sum(self._site_log_marginals(y, noise_var))

    def condition(
        self,
        y: Float[Array, "S N"],
        noise_var: Float[Array, ""] | Float[Array, " S"],
    ) -> ConditionedMarkovGPSites:
        """Condition every site on its observations, by its filter and smoother.

        Args:
            y: ``(S, N)`` observations; masked entries may be ``NaN``.
            noise_var: Observation noise variance, shared ``()`` or per site
                ``(S,)``.

        Returns:
            The `ConditionedMarkovGPSites`, holding each site's smoothed
            moments, with ``y``'s masked entries set to zero.

        Raises:
            ValueError: If ``y`` is not shaped like ``times``, or
                ``noise_var`` is neither ``()`` nor ``(S,)``.

        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)
        """
        y = self._check_y(y)
        noise_arr, noise_axis = self._noise(noise_var)
        mean_dynamic, mean_axes, mean_static = self._mean_parts()

        def site(kernel_s, mean_s, t_s, y_s, m_s, noise_s):
            prior_s = self._site_prior(kernel_s, t_s, mean_s, mean_static)
            cond = prior_s.condition(y_s, noise_s, mask=m_s)
            return cond.y, cond.smoothed_means, cond.smoothed_covs, cond.log_marginal

        in_axes = (
            _site_axes(self.sde_kernel, self.n_sites),
            mean_axes,
            0,
            0,
            None if self.mask is None else 0,
            noise_axis,
        )
        y_clean, m_smooth, P_smooth, site_lml = jax.vmap(site, in_axes=in_axes)(
            self.sde_kernel, mean_dynamic, self.times, y, self.mask, noise_arr
        )
        return ConditionedMarkovGPSites(
            prior=self,
            y=y_clean,
            noise_var=noise_arr,
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            site_log_marginals=site_lml,
        )

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.

\[ \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2). \]

Parameters:

Name Type Description Default
y Float[Array, 'S N']

(S, N) observations; masked entries may be NaN.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, shared () or per site (S,).

required

Returns:

Type Description
Float[Array, '']

The scalar log marginal.

Raises:

Type Description
ValueError

If y is not shaped like times, or noise_var is neither () nor (S,).

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
def log_marginal(
    self,
    y: Float[Array, "S N"],
    noise_var: Float[Array, ""] | Float[Array, " S"],
) -> Float[Array, ""]:
    r"""Summed log marginal of the sites' observed steps.

    $$
    \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2).
    $$

    Args:
        y: ``(S, N)`` observations; masked entries may be ``NaN``.
        noise_var: Observation noise variance, shared ``()`` or per site
            ``(S,)``.

    Returns:
        The scalar log marginal.

    Raises:
        ValueError: If ``y`` is not shaped like ``times``, or
            ``noise_var`` is neither ``()`` nor ``(S,)``.

    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]))
    """
    return jnp.sum(self._site_log_marginals(y, noise_var))

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']

(S, N) observations; masked entries may be NaN.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, shared () or per site (S,).

required

Returns:

Type Description
ConditionedMarkovGPSites

The ConditionedMarkovGPSites, holding each site's smoothed

ConditionedMarkovGPSites

moments, with y's masked entries set to zero.

Raises:

Type Description
ValueError

If y is not shaped like times, or noise_var is neither () nor (S,).

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
def condition(
    self,
    y: Float[Array, "S N"],
    noise_var: Float[Array, ""] | Float[Array, " S"],
) -> ConditionedMarkovGPSites:
    """Condition every site on its observations, by its filter and smoother.

    Args:
        y: ``(S, N)`` observations; masked entries may be ``NaN``.
        noise_var: Observation noise variance, shared ``()`` or per site
            ``(S,)``.

    Returns:
        The `ConditionedMarkovGPSites`, holding each site's smoothed
        moments, with ``y``'s masked entries set to zero.

    Raises:
        ValueError: If ``y`` is not shaped like ``times``, or
            ``noise_var`` is neither ``()`` nor ``(S,)``.

    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)
    """
    y = self._check_y(y)
    noise_arr, noise_axis = self._noise(noise_var)
    mean_dynamic, mean_axes, mean_static = self._mean_parts()

    def site(kernel_s, mean_s, t_s, y_s, m_s, noise_s):
        prior_s = self._site_prior(kernel_s, t_s, mean_s, mean_static)
        cond = prior_s.condition(y_s, noise_s, mask=m_s)
        return cond.y, cond.smoothed_means, cond.smoothed_covs, cond.log_marginal

    in_axes = (
        _site_axes(self.sde_kernel, self.n_sites),
        mean_axes,
        0,
        0,
        None if self.mask is None else 0,
        noise_axis,
    )
    y_clean, m_smooth, P_smooth, site_lml = jax.vmap(site, in_axes=in_axes)(
        self.sde_kernel, mean_dynamic, self.times, y, self.mask, noise_arr
    )
    return ConditionedMarkovGPSites(
        prior=self,
        y=y_clean,
        noise_var=noise_arr,
        smoothed_means=m_smooth,
        smoothed_covs=P_smooth,
        site_log_marginals=site_lml,
    )

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 MarkovGPSitesPrior.

y Float[Array, 'S N']

(S, N) observations, with masked entries set to zero.

noise_var Float[Array, ''] | Float[Array, ' S']

The noise variance conditioned on, () or (S,).

smoothed_means Float[Array, 'S N d']

(S, N, d) smoothed state means.

smoothed_covs Float[Array, 'S N d d']

(S, N, d, d) smoothed state covariances.

site_log_marginals Float[Array, ' S']

(S,) log marginal of each site.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_sites.py
class ConditionedMarkovGPSites(eqx.Module):
    r"""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:
        prior: The originating `MarkovGPSitesPrior`.
        y: ``(S, N)`` observations, with masked entries set to zero.
        noise_var: The noise variance conditioned on, ``()`` or ``(S,)``.
        smoothed_means: ``(S, N, d)`` smoothed state means.
        smoothed_covs: ``(S, N, d, d)`` smoothed state covariances.
        site_log_marginals: ``(S,)`` log marginal of each site.
    """

    prior: MarkovGPSitesPrior
    y: Float[Array, "S N"]
    noise_var: Float[Array, ""] | Float[Array, " S"]
    smoothed_means: Float[Array, "S N d"]
    smoothed_covs: Float[Array, "S N d d"]
    site_log_marginals: Float[Array, " S"]

    @property
    def log_marginal(self) -> Float[Array, ""]:
        """The summed log marginal, equal to `MarkovGPSitesPrior.log_marginal`."""
        return jnp.sum(self.site_log_marginals)

    def predict(
        self,
        t_star: Float[Array, " M"] | Float[Array, "S M"],
        *,
        include_noise: bool = False,
    ) -> tuple[Float[Array, "S M"], Float[Array, "S M"]]:
        r"""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``.

        Args:
            t_star: Test times, ``(M,)`` for the same times at every site or
                ``(S, M)`` for one row per site.
            include_noise: Add the site's observation variance.

        Returns:
            ``(mean, var)``, each ``(S, M)``.

        Raises:
            ValueError: If ``t_star`` is neither ``(M,)`` nor ``(S, M)``.

        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)
        """
        prior = self.prior
        t_star = jnp.asarray(t_star)
        if t_star.ndim == 1:
            t_axis = None
        elif t_star.ndim == 2 and t_star.shape[0] == prior.n_sites:
            t_axis = 0
        else:
            raise ValueError(
                f"t_star must be (M,) or (S, M)=({prior.n_sites}, M), got shape "
                f"{tuple(t_star.shape)!r}."
            )
        noise_axis = None if self.noise_var.ndim == 0 else 0
        mean_dynamic, mean_axes, mean_static = prior._mean_parts()

        def site(kernel_s, mean_s, t_s, y_s, m_s, noise_s, m_smooth, P_smooth, lml, ts):
            site_prior = prior._site_prior(kernel_s, t_s, mean_s, mean_static)
            cond = ConditionedMarkovGP(
                prior=site_prior,
                y=y_s,
                noise_var=noise_s,
                smoothed_means=m_smooth,
                smoothed_covs=P_smooth,
                log_marginal=lml,
                mask=None if m_s is None else _observation_mask(m_s, t_s),
            )
            return cond.predict(ts, include_noise=include_noise)

        in_axes = (
            _site_axes(prior.sde_kernel, prior.n_sites),
            mean_axes,
            0,
            0,
            None if prior.mask is None else 0,
            noise_axis,
            0,
            0,
            0,
            t_axis,
        )
        return jax.vmap(site, in_axes=in_axes)(
            prior.sde_kernel,
            mean_dynamic,
            prior.times,
            self.y,
            prior.mask,
            self.noise_var,
            self.smoothed_means,
            self.smoothed_covs,
            self.site_log_marginals,
            t_star,
        )

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, (M,) for the same times at every site or (S, M) for one row per site.

required
include_noise bool

Add the site's observation variance.

False

Returns:

Type Description
tuple[Float[Array, 'S M'], Float[Array, 'S M']]

(mean, var), each (S, M).

Raises:

Type Description
ValueError

If t_star is neither (M,) nor (S, M).

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
def predict(
    self,
    t_star: Float[Array, " M"] | Float[Array, "S M"],
    *,
    include_noise: bool = False,
) -> tuple[Float[Array, "S M"], Float[Array, "S M"]]:
    r"""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``.

    Args:
        t_star: Test times, ``(M,)`` for the same times at every site or
            ``(S, M)`` for one row per site.
        include_noise: Add the site's observation variance.

    Returns:
        ``(mean, var)``, each ``(S, M)``.

    Raises:
        ValueError: If ``t_star`` is neither ``(M,)`` nor ``(S, M)``.

    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)
    """
    prior = self.prior
    t_star = jnp.asarray(t_star)
    if t_star.ndim == 1:
        t_axis = None
    elif t_star.ndim == 2 and t_star.shape[0] == prior.n_sites:
        t_axis = 0
    else:
        raise ValueError(
            f"t_star must be (M,) or (S, M)=({prior.n_sites}, M), got shape "
            f"{tuple(t_star.shape)!r}."
        )
    noise_axis = None if self.noise_var.ndim == 0 else 0
    mean_dynamic, mean_axes, mean_static = prior._mean_parts()

    def site(kernel_s, mean_s, t_s, y_s, m_s, noise_s, m_smooth, P_smooth, lml, ts):
        site_prior = prior._site_prior(kernel_s, t_s, mean_s, mean_static)
        cond = ConditionedMarkovGP(
            prior=site_prior,
            y=y_s,
            noise_var=noise_s,
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            log_marginal=lml,
            mask=None if m_s is None else _observation_mask(m_s, t_s),
        )
        return cond.predict(ts, include_noise=include_noise)

    in_axes = (
        _site_axes(prior.sde_kernel, prior.n_sites),
        mean_axes,
        0,
        0,
        None if prior.mask is None else 0,
        noise_axis,
        0,
        0,
        0,
        t_axis,
    )
    return jax.vmap(site, in_axes=in_axes)(
        prior.sde_kernel,
        mean_dynamic,
        prior.times,
        self.y,
        prior.mask,
        self.noise_var,
        self.smoothed_means,
        self.smoothed_covs,
        self.site_log_marginals,
        t_star,
    )

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

\[ \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2), \]

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 SDEKernel whose non-scalar array leaves have a leading site axis of length S.

required
times Float[Array, 'S N']

(S, N) strictly increasing times per row.

required
y Float[Array, 'S N']

(S, N) observations; masked entries may be NaN.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, shared () or per site (S,).

required
mask Bool[Array, 'S N'] | None

Optional (S, N) boolean mask, True where observed.

None
mean_fn Callable[[Float[Array, ' N']], Float[Array, ' N']] | None

Optional mean function, as in MarkovGPPrior; shared, or one per site through array leaves with a leading (S,) axis (see MarkovGPSitesPrior).

None
obs_noise_floor float

Extra observation variance, as in MarkovGPPrior.

0.0

Raises:

Type Description
ValueError

If times, y or mask is not (S, N), or if a non-scalar array leaf of the kernel or the mean function, or noise_var, has a leading axis whose length is not S.

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
def 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:
    r"""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

    $$
    \log p(Y \mid \theta) = \sum_{s=1}^{S} \log p(y_s \mid \theta_s, \sigma_s^2),
    $$

    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.

    Args:
        name: The factor site name.
        sde_kernel: An `SDEKernel` whose non-scalar array leaves have a
            leading site axis of length ``S``.
        times: ``(S, N)`` strictly increasing times per row.
        y: ``(S, N)`` observations; masked entries may be ``NaN``.
        noise_var: Observation noise variance, shared ``()`` or per site
            ``(S,)``.
        mask: Optional ``(S, N)`` boolean mask, ``True`` where observed.
        mean_fn: Optional mean function, as in `MarkovGPPrior`; shared, or
            one per site through array leaves with a leading ``(S,)`` axis
            (see `MarkovGPSitesPrior`).
        obs_noise_floor: Extra observation variance, as in `MarkovGPPrior`.

    Raises:
        ValueError: If ``times``, ``y`` or ``mask`` is not ``(S, N)``, or if a
            non-scalar array leaf of the kernel or the mean function, or
            ``noise_var``, has a leading axis whose length is not ``S``.

    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)
    """
    prior = MarkovGPSitesPrior(
        sde_kernel, times, mask=mask, mean_fn=mean_fn, obs_noise_floor=obs_noise_floor
    )
    numpyro.factor(name, prior.log_marginal(y, noise_var))

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\),

\[ \log \theta_n = m + \tau z_n, \qquad z_n \sim \mathcal{N}(0, 1), \]

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 f"{name}_z".

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
def noncentred_log_normal(
    name: str,
    loc: Float[Array, " *batch"] | float,
    scale: Float[Array, " *batch"] | float,
) -> Float[Array, " *batch"]:
    r"""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$,

    $$
    \log \theta_n = m + \tau z_n, \qquad z_n \sim \mathcal{N}(0, 1),
    $$

    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).

    Args:
        name: Name of the deterministic site; the sample site is
            ``f"{name}_z"``.
        loc: Population log-mean $m$.
        scale: Population log-spread $\tau > 0$.

    Returns:
        $\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)
    """
    z = numpyro.sample(f"{name}_z", dist.Normal(0.0, 1.0))
    # log θ_n = m + τ z_n
    log_value = jnp.asarray(loc) + jnp.asarray(scale) * z
    return numpyro.deterministic(  # ty: ignore[invalid-return-type]
        name, jnp.exp(log_value)
    )

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

\[ y_s(t) = \mu_s(t) + g(t) + h_s(t) + \varepsilon_s(t), \qquad g \sim \mathcal{GP}(0, k_g), \quad h_s \sim \mathcal{GP}(0, k_{h,s}), \quad \varepsilon_s(t) \sim \mathcal{N}(0, \sigma_{n,s}^2), \]

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,

\[ x = (x_g, x_{h,1}, \dots, x_{h,S}) \in \mathbb{R}^{D}, \qquad D = d_g + S\, d_h . \]

as_lgssm returns that model as a pyrox_ssm.LinearGaussianSSMPrior with block-diagonal transitions, process noise and initial covariance,

\[ A_k = \mathrm{blockdiag}(A_k^{(g)}, A_k^{(h,1)}, \dots, A_k^{(h,S)}), \qquad Q_k \text{ likewise}, \qquad P_0 = \mathrm{blockdiag}(P_0^{(g)}, P_0^{(h,1)}, \dots, P_0^{(h,S)}), \]

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 (T,).

mask Bool[Array, 'T S']

Boolean (T, S) mask, True where site \(s\) was observed at times[k].

mean_fn Callable[[Float[Array, ' T']], Float[Array, 'T S']] | None

Optional callable mapping times (T,) to the per-site means \(\mu_s(t_k)\), (T, S). None (the default) is the zero mean.

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
class SharedPlusSiteMarkovGPPrior(eqx.Module):
    r"""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

    $$
    y_s(t) = \mu_s(t) + g(t) + h_s(t) + \varepsilon_s(t), \qquad
    g \sim \mathcal{GP}(0, k_g), \quad
    h_s \sim \mathcal{GP}(0, k_{h,s}), \quad
    \varepsilon_s(t) \sim \mathcal{N}(0, \sigma_{n,s}^2),
    $$

    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,

    $$
    x = (x_g, x_{h,1}, \dots, x_{h,S}) \in \mathbb{R}^{D}, \qquad
    D = d_g + S\, d_h .
    $$

    `as_lgssm` returns that model as a `pyrox_ssm.LinearGaussianSSMPrior`
    with block-diagonal transitions, process noise and initial covariance,

    $$
    A_k = \mathrm{blockdiag}(A_k^{(g)}, A_k^{(h,1)}, \dots, A_k^{(h,S)}),
    \qquad Q_k \text{ likewise}, \qquad
    P_0 = \mathrm{blockdiag}(P_0^{(g)}, P_0^{(h,1)}, \dots, P_0^{(h,S)}),
    $$

    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:
        shared: The SDE kernel $k_g$ of the shared GP.
        site: 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: Merged, strictly increasing grid, shaped ``(T,)``.
        mask: Boolean ``(T, S)`` mask, ``True`` where site $s$ was observed
            at ``times[k]``.
        mean_fn: Optional callable mapping times ``(T,)`` to the per-site
            means $\mu_s(t_k)$, ``(T, S)``. ``None`` (the default) is the
            zero mean.

    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))
    """

    shared: SDEKernel
    site: SDEKernel
    times: Float[Array, " T"]
    mask: Bool[Array, "T S"]
    mean_fn: Callable[[Float[Array, " T"]], Float[Array, "T S"]] | None = None

    def __init__(
        self,
        shared: SDEKernel,
        site: SDEKernel,
        times: Float[Array, " T"],
        mask: Bool[Array, "T S"],
        mean_fn: Callable[[Float[Array, " T"]], Float[Array, "T S"]] | None = None,
    ) -> None:
        times_arr = jnp.asarray(times, dtype=jnp.result_type(times, 0.0))
        if times_arr.ndim != 1:
            raise ValueError(f"times must be 1-D, got shape {tuple(times_arr.shape)!r}")
        if times_arr.shape[0] >= 2:
            # Concrete times only; a tracer cannot be checked and is trusted.
            try:
                if not bool(jnp.all(jnp.diff(times_arr) > 0)):
                    raise ValueError("times must be strictly increasing")
            except jax.errors.TracerBoolConversionError:
                pass
        mask_arr = jnp.asarray(mask).astype(bool)
        if mask_arr.ndim != 2 or mask_arr.shape[0] != times_arr.shape[0]:
            raise ValueError(
                f"mask must have shape (T, S) with T = {times_arr.shape[0]} "
                f"steps, got {tuple(mask_arr.shape)!r}"
            )
        if mask_arr.shape[1] == 0:
            raise ValueError("mask must cover at least one site (S >= 1)")
        _site_axes(site, mask_arr.shape[1])
        self.shared = shared
        self.site = site
        self.times = times_arr
        self.mask = mask_arr
        self.mean_fn = mean_fn

    @property
    def n_sites(self) -> int:
        """Number of sites $S$, ``mask.shape[1]``."""
        return self.mask.shape[1]

    @property
    def state_dim(self) -> int:
        """Joint state dimension $D = d_g + S d_h$."""
        return self.shared.state_dim + self.n_sites * self.site.state_dim

    @classmethod
    def from_sites(
        cls,
        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"]]:
        r"""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`).

        Args:
            shared: The SDE kernel $k_g$ of the shared GP.
            site: The SDE kernel $k_h$ of the site GPs (scalar leaves pooled,
                leaves with a leading axis of length $S$ per site).
            times_per_site: One strictly increasing ``(N_s,)`` array of
                observation times per site.
            y_per_site: One ``(N_s,)`` array of observations per site.
            mean_fn: Optional per-site mean, as in the class.

        Returns:
            ``(model, y_grid)``: the model over the merged ``(T,)`` grid with
            its ``(T, S)`` mask, and the ``(T, S)`` observations, ``NaN``
            where a site was not observed.

        Raises:
            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]])
        """
        if len(times_per_site) != len(y_per_site):
            raise ValueError(
                f"times_per_site has {len(times_per_site)} sites but y_per_site "
                f"has {len(y_per_site)}; pass one series of each per site."
            )
        if len(times_per_site) == 0:
            raise ValueError("from_sites needs at least one site.")
        t_dtype = jnp.result_type(*times_per_site, 0.0)
        y_dtype = jnp.result_type(*y_per_site, 0.0)
        sites = []
        for s, (t_s, y_s) in enumerate(zip(times_per_site, y_per_site, strict=True)):
            t_s = jnp.asarray(t_s, dtype=t_dtype)
            y_s = jnp.asarray(y_s, dtype=y_dtype)
            if t_s.ndim != 1 or t_s.shape[0] == 0:
                raise ValueError(
                    f"site {s}: times must be a non-empty 1-D series, got shape "
                    f"{tuple(t_s.shape)!r}."
                )
            if y_s.shape != t_s.shape:
                raise ValueError(
                    f"site {s}: y has shape {tuple(y_s.shape)!r} but times has "
                    f"{tuple(t_s.shape)!r}; each observation needs one time."
                )
            if t_s.shape[0] >= 2 and not bool(jnp.all(jnp.diff(t_s) > 0)):
                raise ValueError(f"site {s}: times must be strictly increasing.")
            sites.append((t_s, y_s))

        times = jnp.unique(jnp.concatenate([t_s for t_s, _ in sites]))
        n_steps, n_sites = times.shape[0], len(sites)
        y_grid = jnp.full((n_steps, n_sites), jnp.nan, dtype=y_dtype)
        mask = jnp.zeros((n_steps, n_sites), dtype=bool)
        for s, (t_s, y_s) in enumerate(sites):
            rows = jnp.searchsorted(times, t_s)
            y_grid = y_grid.at[rows, s].set(y_s)
            mask = mask.at[rows, s].set(True)
        return cls(shared, site, times, mask, mean_fn), y_grid

    def _noise_vector(
        self, noise_var: Float[Array, ""] | Float[Array, " S"]
    ) -> Float[Array, " S"]:
        """``noise_var`` as the ``(S,)`` per-site observation variances."""
        noise_var = jnp.asarray(noise_var)
        if noise_var.shape not in ((), (self.n_sites,)):
            raise ValueError(
                f"noise_var must be a scalar or have shape ({self.n_sites},), "
                f"one variance per site, got {tuple(noise_var.shape)!r}"
            )
        return jnp.broadcast_to(noise_var, (self.n_sites,))

    def as_lgssm(
        self, noise_var: Float[Array, ""] | Float[Array, " S"]
    ) -> LinearGaussianSSMPrior:
        r"""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`,

        $$
        A_k = \mathrm{blockdiag}(A_k^{(g)}, A_k^{(h,1)}, \dots,
        A_k^{(h,S)}), \qquad
        Q_k = \mathrm{blockdiag}(Q_k^{(g)}, Q_k^{(h,1)}, \dots,
        Q_k^{(h,S)}),
        $$

        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$.

        Args:
            noise_var: Observation noise variance, a scalar shared by every
                site or one per site, shaped ``(S,)``.

        Returns:
            The `pyrox_ssm.LinearGaussianSSMPrior` with $T$ steps, state
            dimension $D = d_g + S d_h$ and $S$ outputs; filter it with
            ``mask=self.mask``.

        Raises:
            ValueError: If ``noise_var`` is neither a scalar nor ``(S,)``, or
                if ``mean_fn`` does not return ``(T, S)``.

        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))
        """
        n_sites = self.n_sites
        dt = _build_dt_full(self.times)
        A_g, Q_g = self.shared.discretise_sequence(dt)
        P_g = _kernel_initial_covariance(self.shared)
        H_g = self.shared.sde_params().H

        def site_model(kernel: SDEKernel):
            A_h, Q_h = kernel.discretise_sequence(dt)
            return A_h, Q_h, _kernel_initial_covariance(kernel), kernel.sde_params().H

        A_h, Q_h, P_h, H_h = _per_site(site_model, self.site, n_sites)
        # (S, T, d, d) → (T, S, d, d): one block per site at every step
        A_h = einx.id("s t i j -> t s i j", A_h)
        Q_h = einx.id("s t i j -> t s i j", Q_h)
        dtype = jnp.result_type(A_g, A_h)

        noise = self._noise_vector(noise_var).astype(dtype)
        init_cov = _stack_block_diag(P_g.astype(dtype), P_h.astype(dtype))
        offset = None if self.mean_fn is None else self.mean_fn(self.times)
        return LinearGaussianSSMPrior(
            transition=_stack_block_diag(A_g.astype(dtype), A_h.astype(dtype)),
            obs_model=_shared_plus_site_rows(H_g[0], H_h[:, 0]).astype(dtype),
            process_noise=_stack_block_diag(Q_g.astype(dtype), Q_h.astype(dtype)),
            obs_noise=jnp.diag(noise),
            init_mean=jnp.zeros(init_cov.shape[0], dtype=dtype),
            init_cov=init_cov,
            obs_offset=offset,
        )

    def log_marginal(
        self,
        y: Float[Array, "T S"],
        noise_var: Float[Array, ""] | Float[Array, " S"],
    ) -> Float[Array, ""]:
        r"""Marginal log-likelihood of the observed $(t, s)$ pairs.

        $$
        \log p(y_{\mathrm{obs}} \mid \theta) = \sum_{k=1}^{T}
          \log \mathcal{N}\!\left(y_{k, o_k};\, H_{o_k} m_k^-,\,
          H_{o_k} P_k^- H_{o_k}^\top + R_{o_k o_k}\right),
        $$

        with $o_k$ the sites observed at $t_k$ (``mask[k]``), equal to the
        dense Gaussian over the observed pairs.

        Args:
            y: Observations, shaped ``(T, S)``; unobserved entries may be
                ``NaN`` and reach neither the value nor a gradient.
            noise_var: Observation noise variance, scalar or ``(S,)``.

        Returns:
            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))
        """
        return self.as_lgssm(noise_var).log_marginal(y, mask=self.mask)

    def decompose(
        self,
        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"],
        ]
    ):
        r"""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]$,

        $$
        \mathbb{E}[g(t_k) \mid y] = H_g \hat{x}_{g,k}, \qquad
        \mathbb{E}[h_s(t_k) \mid y] = H_h \hat{x}_{h,s,k},
        $$

        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$,

        $$
        \mathbb{V}[g(t_k) \mid y] = H_g \hat{P}_{gg,k} H_g^\top, \qquad
        \mathbb{V}[h_s(t_k) \mid y] = H_h \hat{P}_{h_s h_s,k} H_h^\top .
        $$

        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.

        Args:
            y: Observations, shaped ``(T, S)``; unobserved entries may be
                ``NaN``.
            noise_var: Observation noise variance, scalar or ``(S,)``.
            return_var: Also return the marginal variances.

        Returns:
            ``(g_mean, h_mean)``: $\mathbb{E}[g \mid y]$ on the grid,
            ``(T,)``, and $\mathbb{E}[h_s \mid y]$, ``(T, S)``. With
            ``return_var=True``, ``(g_mean, h_mean, g_var, h_var)``, the
            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))
        """
        lgssm = self.as_lgssm(noise_var)
        means, covs, _ = lgssm.smooth(y, mask=self.mask)
        d_g, d_h = self.shared.state_dim, self.site.state_dim
        n_steps, n_sites = means.shape[0], self.n_sites
        H = lgssm.obs_model
        # H[s] = (H_g, 0, …, H_h at block s, …, 0): read each block separately
        H_g = H[0, :d_g]
        g_mean = einx.dot("t i, i -> t", means[:, :d_g], H_g)
        site_means = means[:, d_g:].reshape(n_steps, n_sites, d_h)
        H_h = H[:, d_g:].reshape(n_sites, n_sites, d_h)
        H_h = jnp.diagonal(H_h, axis1=0, axis2=1).T  # (S, d_h), row s = H_h,s
        h_mean = einx.dot("t s i, s i -> t s", site_means, H_h)
        if not return_var:
            return g_mean, h_mean
        # V[g] = H_g P̂_gg H_gᵀ
        g_var = einx.dot("t i j, i, j -> t", covs[:, :d_g, :d_g], H_g, H_g)
        # the (d_h, d_h) diagonal block of each site: P̂_{h_s h_s}
        site_cov = covs[:, d_g:, d_g:].reshape(n_steps, n_sites, d_h, n_sites, d_h)
        site_cov = jnp.diagonal(site_cov, axis1=1, axis2=3)  # (T, d_h, d_h, S)
        # V[h_s] = H_h,s P̂_{h_s h_s} H_h,sᵀ
        h_var = einx.dot("t i j s, s i, s j -> t s", site_cov, H_h, H_h)
        return g_mean, h_mean, g_var, h_var

    def condition(
        self,
        y: Float[Array, "T S"],
        noise_var: Float[Array, ""] | Float[Array, " S"],
    ) -> ConditionedSharedPlusSiteMarkovGP:
        r"""Condition on the observations, to predict $g$ and $h_s$ at any times.

        Args:
            y: Observations on the grid, ``(T, S)``; unobserved entries may be
                ``NaN``.
            noise_var: Observation noise variance, scalar or ``(S,)``.

        Returns:
            A `ConditionedSharedPlusSiteMarkovGP`, whose ``predict(t_star)``
            gives the posterior marginals of the shared and site signals.

        Raises:
            ValueError: If ``y`` is not ``(T, S)`` or ``noise_var`` is neither
                a scalar nor ``(S,)``.

        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]))
        """
        y = jnp.asarray(y)
        if y.shape != self.mask.shape:
            raise ValueError(
                f"y must have the mask's shape {tuple(self.mask.shape)!r}, got "
                f"{tuple(y.shape)!r}"
            )
        noise_var = jnp.asarray(noise_var)
        self._noise_vector(noise_var)  # validates the shape
        return ConditionedSharedPlusSiteMarkovGP(self, y, noise_var)

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 (N_s,) array of observation times per site.

required
y_per_site Sequence[Float[Array, ' N_s']]

One (N_s,) array of observations per site.

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

(model, y_grid): the model over the merged (T,) grid with

Float[Array, 'T S']

its (T, S) mask, and the (T, S) observations, NaN

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
@classmethod
def from_sites(
    cls,
    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"]]:
    r"""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`).

    Args:
        shared: The SDE kernel $k_g$ of the shared GP.
        site: The SDE kernel $k_h$ of the site GPs (scalar leaves pooled,
            leaves with a leading axis of length $S$ per site).
        times_per_site: One strictly increasing ``(N_s,)`` array of
            observation times per site.
        y_per_site: One ``(N_s,)`` array of observations per site.
        mean_fn: Optional per-site mean, as in the class.

    Returns:
        ``(model, y_grid)``: the model over the merged ``(T,)`` grid with
        its ``(T, S)`` mask, and the ``(T, S)`` observations, ``NaN``
        where a site was not observed.

    Raises:
        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]])
    """
    if len(times_per_site) != len(y_per_site):
        raise ValueError(
            f"times_per_site has {len(times_per_site)} sites but y_per_site "
            f"has {len(y_per_site)}; pass one series of each per site."
        )
    if len(times_per_site) == 0:
        raise ValueError("from_sites needs at least one site.")
    t_dtype = jnp.result_type(*times_per_site, 0.0)
    y_dtype = jnp.result_type(*y_per_site, 0.0)
    sites = []
    for s, (t_s, y_s) in enumerate(zip(times_per_site, y_per_site, strict=True)):
        t_s = jnp.asarray(t_s, dtype=t_dtype)
        y_s = jnp.asarray(y_s, dtype=y_dtype)
        if t_s.ndim != 1 or t_s.shape[0] == 0:
            raise ValueError(
                f"site {s}: times must be a non-empty 1-D series, got shape "
                f"{tuple(t_s.shape)!r}."
            )
        if y_s.shape != t_s.shape:
            raise ValueError(
                f"site {s}: y has shape {tuple(y_s.shape)!r} but times has "
                f"{tuple(t_s.shape)!r}; each observation needs one time."
            )
        if t_s.shape[0] >= 2 and not bool(jnp.all(jnp.diff(t_s) > 0)):
            raise ValueError(f"site {s}: times must be strictly increasing.")
        sites.append((t_s, y_s))

    times = jnp.unique(jnp.concatenate([t_s for t_s, _ in sites]))
    n_steps, n_sites = times.shape[0], len(sites)
    y_grid = jnp.full((n_steps, n_sites), jnp.nan, dtype=y_dtype)
    mask = jnp.zeros((n_steps, n_sites), dtype=bool)
    for s, (t_s, y_s) in enumerate(sites):
        rows = jnp.searchsorted(times, t_s)
        y_grid = y_grid.at[rows, s].set(y_s)
        mask = mask.at[rows, s].set(True)
    return cls(shared, site, times, mask, mean_fn), y_grid

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,

\[ A_k = \mathrm{blockdiag}(A_k^{(g)}, A_k^{(h,1)}, \dots, A_k^{(h,S)}), \qquad Q_k = \mathrm{blockdiag}(Q_k^{(g)}, Q_k^{(h,1)}, \dots, Q_k^{(h,S)}), \]

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 (S,).

required

Returns:

Type Description
LinearGaussianSSMPrior

The pyrox_ssm.LinearGaussianSSMPrior with \(T\) steps, state

LinearGaussianSSMPrior

dimension \(D = d_g + S d_h\) and \(S\) outputs; filter it with

LinearGaussianSSMPrior

mask=self.mask.

Raises:

Type Description
ValueError

If noise_var is neither a scalar nor (S,), or if mean_fn does not return (T, S).

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
def as_lgssm(
    self, noise_var: Float[Array, ""] | Float[Array, " S"]
) -> LinearGaussianSSMPrior:
    r"""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`,

    $$
    A_k = \mathrm{blockdiag}(A_k^{(g)}, A_k^{(h,1)}, \dots,
    A_k^{(h,S)}), \qquad
    Q_k = \mathrm{blockdiag}(Q_k^{(g)}, Q_k^{(h,1)}, \dots,
    Q_k^{(h,S)}),
    $$

    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$.

    Args:
        noise_var: Observation noise variance, a scalar shared by every
            site or one per site, shaped ``(S,)``.

    Returns:
        The `pyrox_ssm.LinearGaussianSSMPrior` with $T$ steps, state
        dimension $D = d_g + S d_h$ and $S$ outputs; filter it with
        ``mask=self.mask``.

    Raises:
        ValueError: If ``noise_var`` is neither a scalar nor ``(S,)``, or
            if ``mean_fn`` does not return ``(T, S)``.

    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))
    """
    n_sites = self.n_sites
    dt = _build_dt_full(self.times)
    A_g, Q_g = self.shared.discretise_sequence(dt)
    P_g = _kernel_initial_covariance(self.shared)
    H_g = self.shared.sde_params().H

    def site_model(kernel: SDEKernel):
        A_h, Q_h = kernel.discretise_sequence(dt)
        return A_h, Q_h, _kernel_initial_covariance(kernel), kernel.sde_params().H

    A_h, Q_h, P_h, H_h = _per_site(site_model, self.site, n_sites)
    # (S, T, d, d) → (T, S, d, d): one block per site at every step
    A_h = einx.id("s t i j -> t s i j", A_h)
    Q_h = einx.id("s t i j -> t s i j", Q_h)
    dtype = jnp.result_type(A_g, A_h)

    noise = self._noise_vector(noise_var).astype(dtype)
    init_cov = _stack_block_diag(P_g.astype(dtype), P_h.astype(dtype))
    offset = None if self.mean_fn is None else self.mean_fn(self.times)
    return LinearGaussianSSMPrior(
        transition=_stack_block_diag(A_g.astype(dtype), A_h.astype(dtype)),
        obs_model=_shared_plus_site_rows(H_g[0], H_h[:, 0]).astype(dtype),
        process_noise=_stack_block_diag(Q_g.astype(dtype), Q_h.astype(dtype)),
        obs_noise=jnp.diag(noise),
        init_mean=jnp.zeros(init_cov.shape[0], dtype=dtype),
        init_cov=init_cov,
        obs_offset=offset,
    )

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.

\[ \log p(y_{\mathrm{obs}} \mid \theta) = \sum_{k=1}^{T} \log \mathcal{N}\!\left(y_{k, o_k};\, H_{o_k} m_k^-,\, H_{o_k} P_k^- H_{o_k}^\top + R_{o_k o_k}\right), \]

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 (T, S); unobserved entries may be NaN and reach neither the value nor a gradient.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, scalar or (S,).

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
def log_marginal(
    self,
    y: Float[Array, "T S"],
    noise_var: Float[Array, ""] | Float[Array, " S"],
) -> Float[Array, ""]:
    r"""Marginal log-likelihood of the observed $(t, s)$ pairs.

    $$
    \log p(y_{\mathrm{obs}} \mid \theta) = \sum_{k=1}^{T}
      \log \mathcal{N}\!\left(y_{k, o_k};\, H_{o_k} m_k^-,\,
      H_{o_k} P_k^- H_{o_k}^\top + R_{o_k o_k}\right),
    $$

    with $o_k$ the sites observed at $t_k$ (``mask[k]``), equal to the
    dense Gaussian over the observed pairs.

    Args:
        y: Observations, shaped ``(T, S)``; unobserved entries may be
            ``NaN`` and reach neither the value nor a gradient.
        noise_var: Observation noise variance, scalar or ``(S,)``.

    Returns:
        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))
    """
    return self.as_lgssm(noise_var).log_marginal(y, mask=self.mask)

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]\),

\[ \mathbb{E}[g(t_k) \mid y] = H_g \hat{x}_{g,k}, \qquad \mathbb{E}[h_s(t_k) \mid y] = H_h \hat{x}_{h,s,k}, \]

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\),

\[ \mathbb{V}[g(t_k) \mid y] = H_g \hat{P}_{gg,k} H_g^\top, \qquad \mathbb{V}[h_s(t_k) \mid y] = H_h \hat{P}_{h_s h_s,k} H_h^\top . \]

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 (T, S); unobserved entries may be NaN.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, scalar or (S,).

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']]

(g_mean, h_mean): \(\mathbb{E}[g \mid y]\) on the grid,

tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]

(T,), and \(\mathbb{E}[h_s \mid y]\), (T, S). With

tuple[Float[Array, ' T'], Float[Array, 'T S']] | tuple[Float[Array, ' T'], Float[Array, 'T S'], Float[Array, ' T'], Float[Array, 'T S']]

return_var=True, (g_mean, h_mean, g_var, h_var), the

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
def decompose(
    self,
    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"],
    ]
):
    r"""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]$,

    $$
    \mathbb{E}[g(t_k) \mid y] = H_g \hat{x}_{g,k}, \qquad
    \mathbb{E}[h_s(t_k) \mid y] = H_h \hat{x}_{h,s,k},
    $$

    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$,

    $$
    \mathbb{V}[g(t_k) \mid y] = H_g \hat{P}_{gg,k} H_g^\top, \qquad
    \mathbb{V}[h_s(t_k) \mid y] = H_h \hat{P}_{h_s h_s,k} H_h^\top .
    $$

    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.

    Args:
        y: Observations, shaped ``(T, S)``; unobserved entries may be
            ``NaN``.
        noise_var: Observation noise variance, scalar or ``(S,)``.
        return_var: Also return the marginal variances.

    Returns:
        ``(g_mean, h_mean)``: $\mathbb{E}[g \mid y]$ on the grid,
        ``(T,)``, and $\mathbb{E}[h_s \mid y]$, ``(T, S)``. With
        ``return_var=True``, ``(g_mean, h_mean, g_var, h_var)``, the
        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))
    """
    lgssm = self.as_lgssm(noise_var)
    means, covs, _ = lgssm.smooth(y, mask=self.mask)
    d_g, d_h = self.shared.state_dim, self.site.state_dim
    n_steps, n_sites = means.shape[0], self.n_sites
    H = lgssm.obs_model
    # H[s] = (H_g, 0, …, H_h at block s, …, 0): read each block separately
    H_g = H[0, :d_g]
    g_mean = einx.dot("t i, i -> t", means[:, :d_g], H_g)
    site_means = means[:, d_g:].reshape(n_steps, n_sites, d_h)
    H_h = H[:, d_g:].reshape(n_sites, n_sites, d_h)
    H_h = jnp.diagonal(H_h, axis1=0, axis2=1).T  # (S, d_h), row s = H_h,s
    h_mean = einx.dot("t s i, s i -> t s", site_means, H_h)
    if not return_var:
        return g_mean, h_mean
    # V[g] = H_g P̂_gg H_gᵀ
    g_var = einx.dot("t i j, i, j -> t", covs[:, :d_g, :d_g], H_g, H_g)
    # the (d_h, d_h) diagonal block of each site: P̂_{h_s h_s}
    site_cov = covs[:, d_g:, d_g:].reshape(n_steps, n_sites, d_h, n_sites, d_h)
    site_cov = jnp.diagonal(site_cov, axis1=1, axis2=3)  # (T, d_h, d_h, S)
    # V[h_s] = H_h,s P̂_{h_s h_s} H_h,sᵀ
    h_var = einx.dot("t i j s, s i, s j -> t s", site_cov, H_h, H_h)
    return g_mean, h_mean, g_var, h_var

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, (T, S); unobserved entries may be NaN.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, scalar or (S,).

required

Returns:

Type Description
ConditionedSharedPlusSiteMarkovGP

A ConditionedSharedPlusSiteMarkovGP, whose predict(t_star)

ConditionedSharedPlusSiteMarkovGP

gives the posterior marginals of the shared and site signals.

Raises:

Type Description
ValueError

If y is not (T, S) or noise_var is neither a scalar nor (S,).

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
def condition(
    self,
    y: Float[Array, "T S"],
    noise_var: Float[Array, ""] | Float[Array, " S"],
) -> ConditionedSharedPlusSiteMarkovGP:
    r"""Condition on the observations, to predict $g$ and $h_s$ at any times.

    Args:
        y: Observations on the grid, ``(T, S)``; unobserved entries may be
            ``NaN``.
        noise_var: Observation noise variance, scalar or ``(S,)``.

    Returns:
        A `ConditionedSharedPlusSiteMarkovGP`, whose ``predict(t_star)``
        gives the posterior marginals of the shared and site signals.

    Raises:
        ValueError: If ``y`` is not ``(T, S)`` or ``noise_var`` is neither
            a scalar nor ``(S,)``.

    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]))
    """
    y = jnp.asarray(y)
    if y.shape != self.mask.shape:
        raise ValueError(
            f"y must have the mask's shape {tuple(self.mask.shape)!r}, got "
            f"{tuple(y.shape)!r}"
        )
    noise_var = jnp.asarray(noise_var)
    self._noise_vector(noise_var)  # validates the shape
    return ConditionedSharedPlusSiteMarkovGP(self, y, noise_var)

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 SharedPlusSiteMarkovGPPrior.

y Float[Array, 'T S']

Observations on the model's grid, (T, S); unobserved entries may be NaN.

noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, scalar or (S,).

Source code in packages/pyrox-ssm/src/pyrox_ssm/_hierarchical.py
class ConditionedSharedPlusSiteMarkovGP(eqx.Module):
    r"""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:
        model: The conditioned `SharedPlusSiteMarkovGPPrior`.
        y: Observations on the model's grid, ``(T, S)``; unobserved entries
            may be ``NaN``.
        noise_var: Observation noise variance, scalar or ``(S,)``.
    """

    model: SharedPlusSiteMarkovGPPrior
    y: Float[Array, "T S"]
    noise_var: Float[Array, ""] | Float[Array, " S"]

    def predict(
        self, t_star: Float[Array, " M"]
    ) -> tuple[
        Float[Array, " M"], Float[Array, "M S"], Float[Array, " M"], Float[Array, "M S"]
    ]:
        r"""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.

        Args:
            t_star: Test times, ``(M,)``.

        Returns:
            ``(g_mean, h_mean, g_var, h_var)`` at ``t_star``: the shared
            signal's mean and variance, ``(M,)`` each, and each site's,
            ``(M, S)`` each.

        Raises:
            ValueError: If ``t_star`` is not 1-D.
            EquinoxRuntimeError: If a kernel is non-stationary and a test
                time is before the first grid time (checked at run time, so
                also under `jax.jit`).

        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))
        """
        model = self.model
        times = model.times
        t_star = jnp.asarray(t_star, dtype=times.dtype)
        if t_star.ndim != 1:
            raise ValueError(f"t_star must be 1-D, got shape {tuple(t_star.shape)!r}")
        if not (_is_stationary(model.shared) and _is_stationary(model.site)):
            t_star = eqx.error_if(
                t_star,
                jnp.any(t_star < times[0]),
                "predict cannot backcast before the first grid time with a "
                "non-stationary kernel: its prior covariance starts there. "
                "Build the model on a grid that starts earlier.",
            )
        n_steps, n_test, n_sites = times.shape[0], t_star.shape[0], model.n_sites
        # Stable sort: a test time equal to a grid time sorts after it, so it
        # sees that step's update.
        order = jnp.argsort(jnp.concatenate([times, t_star]), stable=True)
        merged_times = jnp.concatenate([times, t_star])[order]
        no_obs = jnp.zeros((n_test, n_sites), dtype=bool)
        merged_mask = jnp.concatenate([model.mask, no_obs])[order]
        merged_y = jnp.concatenate(
            [self.y, jnp.zeros((n_test, n_sites), dtype=self.y.dtype)]
        )[order]
        # tree_at skips __init__, whose strictly-increasing check a test time
        # equal to a grid time would fail; a zero step is A = I, Q = 0.
        merged = eqx.tree_at(
            lambda m: (m.times, m.mask), model, (merged_times, merged_mask)
        )
        g_mean, h_mean, g_var, h_var = merged.decompose(
            merged_y, self.noise_var, return_var=True
        )
        test_rows = jnp.argsort(order, stable=True)[n_steps:]
        return g_mean[test_rows], h_mean[test_rows], g_var[test_rows], h_var[test_rows]

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, (M,).

required

Returns:

Type Description
Float[Array, ' M']

(g_mean, h_mean, g_var, h_var) at t_star: the shared

Float[Array, 'M S']

signal's mean and variance, (M,) each, and each site's,

Float[Array, ' M']

(M, S) each.

Raises:

Type Description
ValueError

If t_star is not 1-D.

EquinoxRuntimeError

If a kernel is non-stationary and a test time is before the first grid time (checked at run time, so also under jax.jit).

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
def predict(
    self, t_star: Float[Array, " M"]
) -> tuple[
    Float[Array, " M"], Float[Array, "M S"], Float[Array, " M"], Float[Array, "M S"]
]:
    r"""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.

    Args:
        t_star: Test times, ``(M,)``.

    Returns:
        ``(g_mean, h_mean, g_var, h_var)`` at ``t_star``: the shared
        signal's mean and variance, ``(M,)`` each, and each site's,
        ``(M, S)`` each.

    Raises:
        ValueError: If ``t_star`` is not 1-D.
        EquinoxRuntimeError: If a kernel is non-stationary and a test
            time is before the first grid time (checked at run time, so
            also under `jax.jit`).

    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))
    """
    model = self.model
    times = model.times
    t_star = jnp.asarray(t_star, dtype=times.dtype)
    if t_star.ndim != 1:
        raise ValueError(f"t_star must be 1-D, got shape {tuple(t_star.shape)!r}")
    if not (_is_stationary(model.shared) and _is_stationary(model.site)):
        t_star = eqx.error_if(
            t_star,
            jnp.any(t_star < times[0]),
            "predict cannot backcast before the first grid time with a "
            "non-stationary kernel: its prior covariance starts there. "
            "Build the model on a grid that starts earlier.",
        )
    n_steps, n_test, n_sites = times.shape[0], t_star.shape[0], model.n_sites
    # Stable sort: a test time equal to a grid time sorts after it, so it
    # sees that step's update.
    order = jnp.argsort(jnp.concatenate([times, t_star]), stable=True)
    merged_times = jnp.concatenate([times, t_star])[order]
    no_obs = jnp.zeros((n_test, n_sites), dtype=bool)
    merged_mask = jnp.concatenate([model.mask, no_obs])[order]
    merged_y = jnp.concatenate(
        [self.y, jnp.zeros((n_test, n_sites), dtype=self.y.dtype)]
    )[order]
    # tree_at skips __init__, whose strictly-increasing check a test time
    # equal to a grid time would fail; a zero step is A = I, Q = 0.
    merged = eqx.tree_at(
        lambda m: (m.times, m.mask), model, (merged_times, merged_mask)
    )
    g_mean, h_mean, g_var, h_var = merged.decompose(
        merged_y, self.noise_var, return_var=True
    )
    test_rows = jnp.argsort(order, stable=True)[n_steps:]
    return g_mean[test_rows], h_mean[test_rows], g_var[test_rows], h_var[test_rows]

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,

\[ \log p(y_{\mathrm{obs}} \mid \theta) = \sum_{k=1}^{T} \log \mathcal{N}\!\left(y_{k, o_k};\, H_{o_k} m_k^-,\, H_{o_k} P_k^- H_{o_k}^\top + R_{o_k o_k}\right), \]

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 SharedPlusSiteMarkovGPPrior on the merged grid.

required
y Float[Array, 'T S']

Observations, shaped (T, S); unobserved entries may be NaN and reach neither the value nor a gradient.

required
noise_var Float[Array, ''] | Float[Array, ' S']

Observation noise variance, scalar or (S,).

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
def shared_plus_site_factor(
    name: str,
    prior: SharedPlusSiteMarkovGPPrior,
    y: Float[Array, "T S"],
    noise_var: Float[Array, ""] | Float[Array, " S"],
) -> None:
    r"""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,

    $$
    \log p(y_{\mathrm{obs}} \mid \theta) = \sum_{k=1}^{T}
      \log \mathcal{N}\!\left(y_{k, o_k};\, H_{o_k} m_k^-,\,
      H_{o_k} P_k^- H_{o_k}^\top + R_{o_k o_k}\right),
    $$

    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``.

    Args:
        name: The factor site name.
        prior: The `SharedPlusSiteMarkovGPPrior` on the merged grid.
        y: Observations, shaped ``(T, S)``; unobserved entries may be
            ``NaN`` and reach neither the value nor a gradient.
        noise_var: Observation noise variance, scalar or ``(S,)``.

    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']
    """
    numpyro.factor(name, prior.log_marginal(y, noise_var))

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

pyrox_gauss.LGSSM or pyrox_gauss.MaskedLGSSM with event shape (T, M). Available without the flows extra. A pyrox_gauss.MaskedLGSSM base contributes its obs_mask whenever no call-time mask is given.

warp AbstractBijection | None

Optional bijection with event shape (M,), applied independently at each step (requires the flows extra). None means the identity, in which case this is exactly the base LGSSM. Conditional warps (non-None cond_shape) are rejected. A channel-mixing warp is usable with log_marginal on an unmasked base, but nothing else: gauss_flows refuses it over a masked base (masking and a non-diagonal Jacobian do not commute), and ConditionedNormalizingKalman.predict refuses it because its per-channel quadrature would be wrong (see there). Put cross-channel structure in H and R instead.

mean_fn Callable[[Float[Array, ' T']], Float[Array, 'T M']] | None

Optional callable times -> (T, M) evaluated on the integer grid 0, ..., T-1 of the base. The mean acts in observation space — it is subtracted from y before the inverse warp and filtering, and added back at predict time — so the model is \(y_t = m(t) + G(H x_t + r_t)\) and conjugacy is untouched.

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
class NormalizingKalmanPrior(eqx.Module):
    r"""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:
        base: `pyrox_gauss.LGSSM` or `pyrox_gauss.MaskedLGSSM` with event shape
            ``(T, M)``. Available without the ``flows`` extra. A
            `pyrox_gauss.MaskedLGSSM` base contributes its ``obs_mask``
            whenever no call-time ``mask`` is given.
        warp: Optional bijection with event shape ``(M,)``, applied
            independently at each step (requires the ``flows`` extra).
            ``None`` means the identity, in which case this is exactly
            the base LGSSM. Conditional warps (non-``None``
            ``cond_shape``) are rejected. A channel-mixing warp is
            usable with `log_marginal` on an unmasked base, but nothing
            else: ``gauss_flows`` refuses it over a masked base (masking
            and a non-diagonal Jacobian do not commute), and
            `ConditionedNormalizingKalman.predict` refuses it because its
            per-channel quadrature would be wrong (see there). Put
            cross-channel structure in ``H`` and ``R`` instead.
        mean_fn: Optional callable ``times -> (T, M)`` evaluated on the
            integer grid ``0, ..., T-1`` of the base. The mean acts in
            **observation space** — it is subtracted from ``y`` before
            the inverse warp and filtering, and added back at predict
            time — so the model is $y_t = m(t) + G(H x_t + r_t)$ and
            conjugacy is untouched.

    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)
    """

    base: LGSSM
    warp: AbstractBijection | None = None
    mean_fn: Callable[[Float[Array, " T"]], Float[Array, "T M"]] | None = None

    def __init__(
        self,
        base: LGSSM,
        warp: AbstractBijection | None = None,
        mean_fn: Callable[[Float[Array, " T"]], Float[Array, "T M"]] | None = None,
    ) -> None:
        if warp is not None:
            _require_flows()
            if warp.cond_shape is not None:
                raise ValueError(
                    "Conditional warps are not supported: the collapsed "
                    "marginal assumes one fixed observation warp per channel. "
                    f"Got cond_shape={warp.cond_shape!r}."
                )
            n_channels = base.event_shape[1]
            if len(warp.shape) != 1 or warp.shape[0] != n_channels:
                raise ValueError(
                    f"warp must have event shape ({n_channels},) to match the "
                    f"base's channel count; got {warp.shape!r}. Lift scalar "
                    "bijections over the channel axis first, e.g. "
                    "Vmap(RationalQuadraticSpline(...), in_axes=None, "
                    f"axis_size={n_channels})."
                )
        self.base = base
        self.warp = warp
        self.mean_fn = mean_fn

    @property
    def n_steps(self) -> int:
        """Sequence length ``T`` of the base."""
        return self.base.event_shape[0]

    @property
    def n_channels(self) -> int:
        """Observation dimension ``M`` of the base."""
        return self.base.event_shape[1]

    def _mean_grid(self, n_steps: int, dtype: np.dtype) -> Float[Array, "T M"]:
        """Mean values on the integer grid ``0, ..., n_steps - 1``."""
        if self.mean_fn is None:
            return jnp.zeros((n_steps, self.n_channels), dtype=dtype)
        return jnp.asarray(self.mean_fn(jnp.arange(n_steps, dtype=dtype)))

    def _effective_mask(
        self, mask: Bool[Array, "T M"] | None
    ) -> Bool[Array, "T M"] | None:
        """Call-time mask if given, else a `MaskedLGSSM` base's own mask."""
        if mask is not None:
            return jnp.asarray(mask, dtype=bool)
        if isinstance(self.base, MaskedLGSSM):
            return self.base.obs_mask
        return None

    def _check_shapes(
        self,
        y: Float[Array, "T M"],
        mask: Bool[Array, "T M"] | None,
    ) -> None:
        """Reject ``y`` / ``mask`` that do not match the base event shape.

        ``y - mean_grid`` and the filter's own broadcasting would other-
        wise accept a ``(T, 1)`` series against an ``(T, M)`` base,
        silently replicating the one observed channel across all ``M``
        and returning a finite log-likelihood for data the caller never
        supplied. Shapes are static under ``jit``, so this costs nothing
        at trace time.
        """
        expected = (self.n_steps, self.n_channels)
        if y.shape != expected:
            raise ValueError(
                f"y has shape {y.shape}, but the base event shape is "
                f"{expected}. Observations must match the base exactly — "
                "a mismatched channel or time axis would broadcast rather "
                "than raise."
            )
        if mask is not None and mask.shape != expected:
            raise ValueError(
                f"mask has shape {mask.shape}, but the base event shape "
                f"is {expected}. The mask marks observed entries of y, so "
                "it must have the same shape."
            )

    def _require_elementwise_warp(self, flows: ModuleType) -> None:
        """Raise unless ``gauss_flows`` classifies the warp as elementwise.

        Asked through the public surface rather than a private helper:
        `gauss_flows.normalizing_kalman_filter` documents that it
        refuses a channel-mixing warp over a **conditional** (mask-
        consuming) base, because masking and a non-diagonal Jacobian do
        not commute. Building that form is construction-only and cheap,
        so it doubles as the classifier — and it stays correct if
        ``gauss_flows`` refines what counts as elementwise. Shapes were
        already validated in ``__init__``, so a ``ValueError`` out of
        this constructor is that rejection.
        """
        try:
            self._nkf(flows, masked=True)
        except ValueError as exc:
            raise ValueError(
                "predict requires an elementwise warp: it pushes the "
                "per-channel marginal moments through the warp with a "
                "scalar Gauss-Hermite rule, which is only the right "
                "integral when each output channel depends on its own "
                "input channel alone. This warp mixes channels (or "
                "cannot be shown not to), so those moments would be "
                "silently wrong — log_marginal is unaffected and stays "
                "exact. Put cross-channel structure in H and R instead."
            ) from exc

    def _nkf(self, flows: ModuleType, *, masked: bool):
        """Build the ``gauss_flows`` NKF density for the current warp.

        Unmasked: wrap the base directly. Masked: rebuild the base's
        parameters into a `pyrox_gauss.LGSSMFactory` so the mask arrives as
        a flowjax ``condition`` — that is what routes the log-det through
        ``gauss_flows``' masked change-of-variables (observed channels
        only) and triggers its rejection of channel-mixing warps.
        """
        if not masked:
            return flows.normalizing_kalman_filter(
                flows.NumpyroBase(dist=self.base), self.warp
            )
        factory = pyrox_gauss.LGSSMFactory(
            self.base.A,
            self.base.H,
            self.base.Q,
            self.base.R,
            self.base.m0,
            self.base.P0,
            self.n_steps,
        )
        conditional_base = flows.NumpyroBase(
            dist_factory=factory,
            event_shape=tuple(self.base.event_shape),
            cond_shape=tuple(self.base.event_shape),
        )
        return flows.normalizing_kalman_filter(conditional_base, self.warp)

    def log_marginal(
        self,
        y: Float[Array, "T M"],
        mask: Bool[Array, "T M"] | None = None,
    ) -> Float[Array, ""]:
        r"""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.

        Args:
            y: Observations, shape ``(T, M)``. Masked entries are never
                read and may be ``NaN``.
            mask: Optional observation mask, shape ``(T, M)``; ``True``
                marks an observed entry. Overrides a
                `pyrox_gauss.MaskedLGSSM` base's own mask when both are
                present. Unobserved channels are marginalised exactly;
                with a warp this requires an elementwise warp (see
                the class docstring).

        Returns:
            Scalar $\log p(y_{\mathrm{obs}} \mid \theta)$.

        Raises:
            ValueError: If ``y`` or ``mask`` does not match the base
                event shape.
        """
        y = jnp.asarray(y)
        mask_eff = self._effective_mask(mask)
        self._check_shapes(y, mask_eff)
        residual = y - self._mean_grid(y.shape[0], y.dtype)
        if self.warp is None:
            return gaussx.kalman_filter(
                self.base.A,
                self.base.H,
                self.base.Q,
                self.base.R,
                residual,
                self.base.m0,
                self.base.P0,
                mask=mask_eff,
            ).log_likelihood
        flows = _require_flows()
        nkf = self._nkf(flows, masked=mask_eff is not None)
        if mask_eff is None:
            return nkf.log_prob(residual)
        return nkf.log_prob(residual, condition=mask_eff)

    def condition(
        self,
        y: Float[Array, "T M"],
        mask: Bool[Array, "T M"] | None = None,
    ) -> ConditionedNormalizingKalman:
        r"""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.

        Args:
            y: Observations, shape ``(T, M)``. Masked entries are never
                read and may be ``NaN``.
            mask: Optional observation mask, shape ``(T, M)``; ``True``
                marks an observed entry. Overrides a
                `pyrox_gauss.MaskedLGSSM` base's own mask when both are
                present.

        Returns:
            The `ConditionedNormalizingKalman`.

        Raises:
            ValueError: If ``y`` or ``mask`` does not match the base event
                shape.

        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)
        """
        y = jnp.asarray(y)
        mask_eff = self._effective_mask(mask)
        self._check_shapes(y, mask_eff)
        residual = y - self._mean_grid(self.n_steps, y.dtype)

        if self.warp is None:
            z = residual
        else:
            _require_flows()
            if mask_eff is not None:
                # Unobserved slots hold junk (often NaN); substitute an
                # in-support reference before the inverse warp. The
                # filter never reads those entries afterwards.
                reference = self.warp.transform(
                    jnp.zeros(self.n_channels, dtype=y.dtype)
                )
                residual = jnp.where(mask_eff, residual, reference)
            z = jax.vmap(self.warp.inverse)(residual)  # (T, M)

        state = gaussx.kalman_filter(
            self.base.A,
            self.base.H,
            self.base.Q,
            self.base.R,
            z,
            self.base.m0,
            self.base.P0,
            mask=mask_eff,
        )
        m_smooth, P_smooth = gaussx.rts_smoother(state, self.base.A)
        return ConditionedNormalizingKalman(
            prior=self,
            y=y if mask_eff is None else jnp.where(mask_eff, y, jnp.zeros_like(y)),
            mask=mask_eff,
            smoothed_means=m_smooth,
            smoothed_covs=P_smooth,
            last_filtered_mean=state.filtered_means[-1],
            last_filtered_cov=state.filtered_covs[-1],
        )

    def predict(
        self,
        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`.
        """
        warnings.warn(
            "NormalizingKalmanPrior.predict(y, mask, ...) is deprecated; use "
            "prior.condition(y, mask).predict(n_ahead=..., order=...).",
            DeprecationWarning,
            stacklevel=2,
        )
        return self.condition(y, mask).predict(n_ahead=n_ahead, order=order)

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 (T, M). Masked entries are never read and may be NaN.

required
mask Bool[Array, 'T M'] | None

Optional observation mask, shape (T, M); True marks an observed entry. Overrides a pyrox_gauss.MaskedLGSSM base's own mask when both are present. Unobserved channels are marginalised exactly; with a warp this requires an elementwise warp (see the class docstring).

None

Returns:

Type Description
Float[Array, '']

Scalar \(\log p(y_{\mathrm{obs}} \mid \theta)\).

Raises:

Type Description
ValueError

If y or mask does not match the base event shape.

Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
def log_marginal(
    self,
    y: Float[Array, "T M"],
    mask: Bool[Array, "T M"] | None = None,
) -> Float[Array, ""]:
    r"""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.

    Args:
        y: Observations, shape ``(T, M)``. Masked entries are never
            read and may be ``NaN``.
        mask: Optional observation mask, shape ``(T, M)``; ``True``
            marks an observed entry. Overrides a
            `pyrox_gauss.MaskedLGSSM` base's own mask when both are
            present. Unobserved channels are marginalised exactly;
            with a warp this requires an elementwise warp (see
            the class docstring).

    Returns:
        Scalar $\log p(y_{\mathrm{obs}} \mid \theta)$.

    Raises:
        ValueError: If ``y`` or ``mask`` does not match the base
            event shape.
    """
    y = jnp.asarray(y)
    mask_eff = self._effective_mask(mask)
    self._check_shapes(y, mask_eff)
    residual = y - self._mean_grid(y.shape[0], y.dtype)
    if self.warp is None:
        return gaussx.kalman_filter(
            self.base.A,
            self.base.H,
            self.base.Q,
            self.base.R,
            residual,
            self.base.m0,
            self.base.P0,
            mask=mask_eff,
        ).log_likelihood
    flows = _require_flows()
    nkf = self._nkf(flows, masked=mask_eff is not None)
    if mask_eff is None:
        return nkf.log_prob(residual)
    return nkf.log_prob(residual, condition=mask_eff)

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 (T, M). Masked entries are never read and may be NaN.

required
mask Bool[Array, 'T M'] | None

Optional observation mask, shape (T, M); True marks an observed entry. Overrides a pyrox_gauss.MaskedLGSSM base's own mask when both are present.

None

Returns:

Type Description
ConditionedNormalizingKalman

The ConditionedNormalizingKalman.

Raises:

Type Description
ValueError

If y or mask does not match the base event shape.

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
def condition(
    self,
    y: Float[Array, "T M"],
    mask: Bool[Array, "T M"] | None = None,
) -> ConditionedNormalizingKalman:
    r"""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.

    Args:
        y: Observations, shape ``(T, M)``. Masked entries are never
            read and may be ``NaN``.
        mask: Optional observation mask, shape ``(T, M)``; ``True``
            marks an observed entry. Overrides a
            `pyrox_gauss.MaskedLGSSM` base's own mask when both are
            present.

    Returns:
        The `ConditionedNormalizingKalman`.

    Raises:
        ValueError: If ``y`` or ``mask`` does not match the base event
            shape.

    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)
    """
    y = jnp.asarray(y)
    mask_eff = self._effective_mask(mask)
    self._check_shapes(y, mask_eff)
    residual = y - self._mean_grid(self.n_steps, y.dtype)

    if self.warp is None:
        z = residual
    else:
        _require_flows()
        if mask_eff is not None:
            # Unobserved slots hold junk (often NaN); substitute an
            # in-support reference before the inverse warp. The
            # filter never reads those entries afterwards.
            reference = self.warp.transform(
                jnp.zeros(self.n_channels, dtype=y.dtype)
            )
            residual = jnp.where(mask_eff, residual, reference)
        z = jax.vmap(self.warp.inverse)(residual)  # (T, M)

    state = gaussx.kalman_filter(
        self.base.A,
        self.base.H,
        self.base.Q,
        self.base.R,
        z,
        self.base.m0,
        self.base.P0,
        mask=mask_eff,
    )
    m_smooth, P_smooth = gaussx.rts_smoother(state, self.base.A)
    return ConditionedNormalizingKalman(
        prior=self,
        y=y if mask_eff is None else jnp.where(mask_eff, y, jnp.zeros_like(y)),
        mask=mask_eff,
        smoothed_means=m_smooth,
        smoothed_covs=P_smooth,
        last_filtered_mean=state.filtered_means[-1],
        last_filtered_cov=state.filtered_covs[-1],
    )

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
def predict(
    self,
    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`.
    """
    warnings.warn(
        "NormalizingKalmanPrior.predict(y, mask, ...) is deprecated; use "
        "prior.condition(y, mask).predict(n_ahead=..., order=...).",
        DeprecationWarning,
        stacklevel=2,
    )
    return self.condition(y, mask).predict(n_ahead=n_ahead, order=order)

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 NormalizingKalmanPrior.

y Float[Array, 'T M']

Observations, (T, M), with masked entries set to zero.

mask Bool[Array, 'T M'] | None

The effective (T, M) observation mask, or None when everything was observed.

smoothed_means Float[Array, 'T D']

Smoothed state means, (T, D).

smoothed_covs Float[Array, 'T D D']

Smoothed state covariances, (T, D, D).

last_filtered_mean Float[Array, ' D']

Filtered state mean at the last step, (D,), where a forecast starts.

last_filtered_cov Float[Array, 'D D']

Filtered state covariance at the last step, (D, D).

Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
class ConditionedNormalizingKalman(eqx.Module):
    r"""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:
        prior: The originating `NormalizingKalmanPrior`.
        y: Observations, ``(T, M)``, with masked entries set to zero.
        mask: The effective ``(T, M)`` observation mask, or ``None`` when
            everything was observed.
        smoothed_means: Smoothed state means, ``(T, D)``.
        smoothed_covs: Smoothed state covariances, ``(T, D, D)``.
        last_filtered_mean: Filtered state mean at the last step, ``(D,)``,
            where a forecast starts.
        last_filtered_cov: Filtered state covariance at the last step,
            ``(D, D)``.
    """

    prior: NormalizingKalmanPrior
    y: Float[Array, "T M"]
    mask: Bool[Array, "T M"] | None
    smoothed_means: Float[Array, "T D"]
    smoothed_covs: Float[Array, "T D D"]
    last_filtered_mean: Float[Array, " D"]
    last_filtered_cov: Float[Array, "D D"]

    def predict(
        self,
        *,
        n_ahead: int = 0,
        order: int = 32,
    ) -> tuple[Float[Array, "Tp M"], Float[Array, "Tp M"]]:
        r"""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:

        $$
        \mathbb{E}[y_t] = \int G(z)\, N(z; \mu_t, \sigma_t^2)\, dz,
        \qquad
        \mathrm{Var}[y_t] = \int (G(z) - \mathbb{E}[y_t])^2
          N(z; \mu_t, \sigma_t^2)\, dz .
        $$

        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.

        Args:
            n_ahead: Number of forecast steps appended after the
                training grid.
            order: Gauss-Hermite order for the warped pushforward, in
                ``[2, 256]``. Ignored when ``warp is None``.

        Returns:
            Tuple ``(mean, var)`` of observation-space marginal moments,
            each of shape ``(T + n_ahead, M)``. Variances are non-negative,
            so ``sqrt`` on them is always safe.

        Raises:
            ValueError: If the warp is not elementwise, or if ``order`` is
                outside ``[2, 256]`` with a warp.

        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))
        """
        prior = self.prior
        if prior.warp is not None:
            # The scalar per-channel quadrature below is only the right
            # integral for an elementwise warp, so predict requires one
            # even when log_marginal would not.
            prior._require_elementwise_warp(_require_flows())
        mean_grid = prior._mean_grid(prior.n_steps + n_ahead, self.y.dtype)
        m_smooth, P_smooth = self.smoothed_means, self.smoothed_covs

        if n_ahead > 0:
            A_dense = _dense(prior.base.A)
            Q_dense = _dense(prior.base.Q)

            def step(carry, _):
                m, P = carry
                m_next = A_dense @ m
                P_next = A_dense @ P @ A_dense.T + Q_dense
                return (m_next, P_next), (m_next, P_next)

            last = (self.last_filtered_mean, self.last_filtered_cov)
            _, (m_ahead, P_ahead) = jax.lax.scan(step, last, None, length=n_ahead)
            m_smooth = jnp.concatenate([m_smooth, m_ahead], axis=0)
            P_smooth = jnp.concatenate([P_smooth, P_ahead], axis=0)

        H_dense = _dense(prior.base.H)
        R_diag = jnp.diagonal(_dense(prior.base.R))
        # z-space marginals: mean H m_t, variance diag(H P_t H^T + R).
        mz = m_smooth @ H_dense.T  # (T', M)
        # einx.dot is typed as possibly returning a tuple (multi-output
        # patterns); narrow back to a single array for the typechecker.
        # Clamped at zero: the quadratic form is PSD in exact arithmetic,
        # but a rounding-negative entry would become NaN under the sqrt
        # taken for the quadrature nodes below.
        vz = jnp.maximum(
            jnp.asarray(einx.dot("m n, t n k, m k -> t m", H_dense, P_smooth, H_dense))
            + R_diag,
            0.0,
        )

        if prior.warp is None:
            return mz + mean_grid, vz

        first_moment, variance = _pushforward_moments(
            jax.vmap(prior.warp.transform), mz, vz, order=order
        )
        return first_moment + mean_grid, variance

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:

\[ \mathbb{E}[y_t] = \int G(z)\, N(z; \mu_t, \sigma_t^2)\, dz, \qquad \mathrm{Var}[y_t] = \int (G(z) - \mathbb{E}[y_t])^2 N(z; \mu_t, \sigma_t^2)\, dz . \]

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 [2, 256]. Ignored when warp is None.

32

Returns:

Type Description
Float[Array, 'Tp M']

Tuple (mean, var) of observation-space marginal moments,

Float[Array, 'Tp M']

each of shape (T + n_ahead, M). Variances are non-negative,

tuple[Float[Array, 'Tp M'], Float[Array, 'Tp M']]

so sqrt on them is always safe.

Raises:

Type Description
ValueError

If the warp is not elementwise, or if order is outside [2, 256] with a warp.

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
def predict(
    self,
    *,
    n_ahead: int = 0,
    order: int = 32,
) -> tuple[Float[Array, "Tp M"], Float[Array, "Tp M"]]:
    r"""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:

    $$
    \mathbb{E}[y_t] = \int G(z)\, N(z; \mu_t, \sigma_t^2)\, dz,
    \qquad
    \mathrm{Var}[y_t] = \int (G(z) - \mathbb{E}[y_t])^2
      N(z; \mu_t, \sigma_t^2)\, dz .
    $$

    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.

    Args:
        n_ahead: Number of forecast steps appended after the
            training grid.
        order: Gauss-Hermite order for the warped pushforward, in
            ``[2, 256]``. Ignored when ``warp is None``.

    Returns:
        Tuple ``(mean, var)`` of observation-space marginal moments,
        each of shape ``(T + n_ahead, M)``. Variances are non-negative,
        so ``sqrt`` on them is always safe.

    Raises:
        ValueError: If the warp is not elementwise, or if ``order`` is
            outside ``[2, 256]`` with a warp.

    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))
    """
    prior = self.prior
    if prior.warp is not None:
        # The scalar per-channel quadrature below is only the right
        # integral for an elementwise warp, so predict requires one
        # even when log_marginal would not.
        prior._require_elementwise_warp(_require_flows())
    mean_grid = prior._mean_grid(prior.n_steps + n_ahead, self.y.dtype)
    m_smooth, P_smooth = self.smoothed_means, self.smoothed_covs

    if n_ahead > 0:
        A_dense = _dense(prior.base.A)
        Q_dense = _dense(prior.base.Q)

        def step(carry, _):
            m, P = carry
            m_next = A_dense @ m
            P_next = A_dense @ P @ A_dense.T + Q_dense
            return (m_next, P_next), (m_next, P_next)

        last = (self.last_filtered_mean, self.last_filtered_cov)
        _, (m_ahead, P_ahead) = jax.lax.scan(step, last, None, length=n_ahead)
        m_smooth = jnp.concatenate([m_smooth, m_ahead], axis=0)
        P_smooth = jnp.concatenate([P_smooth, P_ahead], axis=0)

    H_dense = _dense(prior.base.H)
    R_diag = jnp.diagonal(_dense(prior.base.R))
    # z-space marginals: mean H m_t, variance diag(H P_t H^T + R).
    mz = m_smooth @ H_dense.T  # (T', M)
    # einx.dot is typed as possibly returning a tuple (multi-output
    # patterns); narrow back to a single array for the typechecker.
    # Clamped at zero: the quadratic form is PSD in exact arithmetic,
    # but a rounding-negative entry would become NaN under the sqrt
    # taken for the quadrature nodes below.
    vz = jnp.maximum(
        jnp.asarray(einx.dot("m n, t n k, m k -> t m", H_dense, P_smooth, H_dense))
        + R_diag,
        0.0,
    )

    if prior.warp is None:
        return mz + mean_grid, vz

    first_moment, variance = _pushforward_moments(
        jax.vmap(prior.warp.transform), mz, vz, order=order
    )
    return first_moment + mean_grid, variance

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 NormalizingKalmanPrior.

required
y Float[Array, 'T M']

Observations, shape (T, M).

required
mask Bool[Array, 'T M'] | None

Optional observation mask, shape (T, M).

None
Source code in packages/pyrox-ssm/src/pyrox_ssm/flows/_markov_flow.py
def 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.

    Args:
        name: NumPyro factor site name.
        prior: The `NormalizingKalmanPrior`.
        y: Observations, shape ``(T, M)``.
        mask: Optional observation mask, shape ``(T, M)``.
    """
    numpyro.factor(name, prior.log_marginal(y, mask))

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,

\[ \bar{r}_k = y_k - \frac{1}{E} \sum_{e=1}^{E} h_\theta(x_{k,e}^-), \qquad \hat{\Sigma}_{y,k} = U_k U_k^\top + \Sigma_\varepsilon, \]

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

\[ \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T} \log \mathcal{N}(\bar{r}_k;\, 0,\, \hat{\Sigma}_{y,k}). \]

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 filterax.filters: ETKF, EnSRF, ESTKF, EnSRF_Serial or LETKF.

required
dynamics AbstractDynamics

Deterministic dynamics \(f_\theta\), called per member as dynamics(x, t_prev, t_next) on a (D,) state: a filterax.AbstractDynamics, or a plain callable, which filterax also accepts.

required
obs_op AbstractObsOperator

Observation operator \(h_\theta\), from a (D,) state to an (M,) observation: a filterax.AbstractObsOperator or a plain callable.

required
init_ensemble Float[Array, 'E D']

The initial ensemble \(X_0\), shaped (E, D), drawn once outside the model.

required
y Float[Array, 'T M']

Observations \(y_{1:T}\), shaped (T, M).

required
obs_times Float[Array, ' T']

Observation times, shaped (T,).

required
obs_noise Float[Array, 'M M'] | AbstractLinearOperator

Observation-noise covariance \(\Sigma_\varepsilon\), an (M, M) matrix (wrapped as a positive semi-definite lineax operator) or a lineax operator.

required
inflator AbstractInflator | None

Optional deterministic inflator (filterax.MultiplicativeInflator, RTPS or RTPP).

None
t0 float | Float[Array, '']

The time of \(X_0\), where the first forecast starts.

0.0
adjoint Any | None

The gradient strategy from filterax.differentiable. None (the default) is RecursiveCheckpointAdjoint(): exact gradients that recompute the forecasts in the backward pass, trading compute for memory; DirectAdjoint() keeps the full tape.

None
**analysis_extra Any

Passed to filter_.analysis; LETKF takes state_coords and obs_coords here.

{}

Returns:

Type Description
AssimilationResult

The filterax.AssimilationResult: the final particles

AssimilationResult

(E, D), the forecast_history and analysis_history

AssimilationResult

(T, E, D), and the per-step log_likelihoods (T,) whose

AssimilationResult

sum is the factor.

Raises:

Type Description
ValueError

If filter_ or inflator draws random numbers at each step; filterax raises when y and obs_times have different lengths.

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
def 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:
    r"""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,

    $$
    \bar{r}_k = y_k - \frac{1}{E} \sum_{e=1}^{E} h_\theta(x_{k,e}^-), \qquad
    \hat{\Sigma}_{y,k} = U_k U_k^\top + \Sigma_\varepsilon,
    $$

    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

    $$
    \log p(y_{1:T} \mid \theta) \approx \sum_{k=1}^{T}
      \log \mathcal{N}(\bar{r}_k;\, 0,\, \hat{\Sigma}_{y,k}).
    $$

    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.

    Args:
        name: The factor site name.
        filter_: A deterministic square-root filter from
            ``filterax.filters``: ``ETKF``, ``EnSRF``, ``ESTKF``,
            ``EnSRF_Serial`` or ``LETKF``.
        dynamics: Deterministic dynamics $f_\theta$, called per member as
            ``dynamics(x, t_prev, t_next)`` on a ``(D,)`` state: a
            ``filterax.AbstractDynamics``, or a plain callable, which filterax
            also accepts.
        obs_op: Observation operator $h_\theta$, from a ``(D,)`` state to an
            ``(M,)`` observation: a ``filterax.AbstractObsOperator`` or a plain
            callable.
        init_ensemble: The initial ensemble $X_0$, shaped ``(E, D)``, drawn
            once outside the model.
        y: Observations $y_{1:T}$, shaped ``(T, M)``.
        obs_times: Observation times, shaped ``(T,)``.
        obs_noise: Observation-noise covariance $\Sigma_\varepsilon$, an
            ``(M, M)`` matrix (wrapped as a positive semi-definite lineax
            operator) or a lineax operator.
        inflator: Optional deterministic inflator
            (``filterax.MultiplicativeInflator``, ``RTPS`` or ``RTPP``).
        t0: The time of $X_0$, where the first forecast starts.
        adjoint: The gradient strategy from ``filterax.differentiable``.
            ``None`` (the default) is ``RecursiveCheckpointAdjoint()``: exact
            gradients that recompute the forecasts in the backward pass,
            trading compute for memory; ``DirectAdjoint()`` keeps the full
            tape.
        **analysis_extra: Passed to ``filter_.analysis``; ``LETKF`` takes
            ``state_coords`` and ``obs_coords`` here.

    Returns:
        The ``filterax.AssimilationResult``: the final ``particles``
        ``(E, D)``, the ``forecast_history`` and ``analysis_history``
        ``(T, E, D)``, and the per-step ``log_likelihoods`` ``(T,)`` whose
        sum is the factor.

    Raises:
        ValueError: If ``filter_`` or ``inflator`` draws random numbers at
            each step; filterax raises when ``y`` and ``obs_times`` have
            different lengths.

    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']
    """
    if not isinstance(obs_noise, lx.AbstractLinearOperator):
        obs_noise = lx.MatrixLinearOperator(
            jnp.asarray(obs_noise), lx.positive_semidefinite_tag
        )
    if adjoint is None:
        adjoint = flx.differentiable.RecursiveCheckpointAdjoint()
    try:
        result = flx.differentiable_assimilate(
            filter_,
            dynamics,
            obs_op,
            init_ensemble,
            y,
            obs_times,
            obs_noise,
            inflator=inflator,
            t0=t0,
            adjoint=adjoint,
            **analysis_extra,
        )
    except ValueError as exc:
        stochastic = next(
            (c for c in (filter_, inflator) if isinstance(c, _STOCHASTIC)), None
        )
        if stochastic is None:
            raise
        raise ValueError(
            f"ensemble_factor needs a deterministic square-root filter and "
            f"inflator, but {type(stochastic).__name__} draws random numbers at "
            "each analysis step. The log density is deterministic and smooth "
            "in the parameters only when the initial ensemble is data and the "
            "filter is a square-root filter, so that every evaluation sees the "
            "same draws (common random numbers). Use ETKF, EnSRF, ESTKF, "
            "EnSRF_Serial or LETKF from filterax.filters, and "
            "MultiplicativeInflator, RTPS or RTPP."
        ) from exc
    # differentiable_assimilate always fills log_likelihoods (one per step)
    log_likelihoods = result.log_likelihoods
    assert log_likelihoods is not None
    numpyro.factor(name, log_likelihoods.sum())
    return result

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\),

\[ T(s) = (g - h \odot \hat f,\; -h), \qquad s \leftarrow (1 - \alpha)\, s + \alpha\, T(s), \]

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\),

\[ \alpha = \alpha_d \min(1,\, \delta / \max_n |f^N_n - \hat f_n| / \sigma_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 50; a capped fit usually converges in under 20.

tol float

Convergence tolerance: the loop stops at the first iteration where every site natural \(\lambda_n\), \(\Lambda_n\) changed by less than 0.1 * tol * (1 + |new value|), which leaves the posterior marginals within about tol of the fixed point. Default 1e-6.

damping float

Factor \(\alpha_d\) in (0, 1] on every Newton step, on top of max_step. Default 1.0. With the cap on it is rarely needed, and it slows every iteration, not only the long steps.

max_step float | None

The largest change one step may make to the posterior mean, \(\delta\), in prior standard deviations \(\sigma_n\). Default 1.0. None takes the full Newton step.

precision_floor float

Lower bound on the diagonal precision. Default 1e-6.

adjoint AbstractAdjoint

How gradients pass through the loop. Default optimistix.RecursiveCheckpointAdjoint(), reverse-mode through the iterations that ran. The alternative is markov_implicit_adjoint, the implicit function theorem at the fixed point. Both match central differences equally well on a converged fit (relative error 5e-9 to 1.4e-8 on a 365-day Bernoulli record). They differ as follows:

  • Cost. With the step cap a fit typically converges in about 7 iterations, and then the checkpoint gradient is about 1.8 times cheaper (116 against 207 ms at N = 365, 422 against 783 ms at N = 1460, on CPU). Its cost grows with the iterations run, so a fit that needs many (a small damping, max_step=None, or a fit that runs to max_iter) can make the implicit adjoint the cheaper one. The implicit gradient costs about four reverse Kalman passes however many iterations ran.
  • Memory. The checkpoints hold up to max_iter copies of the (N,) site naturals; the implicit adjoint holds a few.
  • What it is the gradient of. The checkpoint gradient is that of the last iterate, so it matches the fixed point's only as closely as the loop converged, and it depends on damping and max_step. The implicit gradient is the fixed point's whatever the path to it.
  • Forward mode. The checkpoint adjoint supports reverse mode only: jax.jacfwd (or NumPyro's forward_mode_differentiation=True) raises, where the implicit adjoint supports both. jax.grad and jax.hessian work with either.
  • Failures. Neither raises inside NUTS: a non-finite fit gives a non-finite gradient.

For small \(N\), optimistix.ImplicitAdjoint() solves the dense (2N, 2N) Jacobian by LU.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
class LaplaceMarkovInference(eqx.Module):
    r"""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$,

    $$
    T(s) = (g - h \odot \hat f,\; -h), \qquad
    s \leftarrow (1 - \alpha)\, s + \alpha\, T(s),
    $$

    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$,

    $$
    \alpha = \alpha_d \min(1,\, \delta / \max_n |f^N_n - \hat f_n| / \sigma_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:
        max_iter: Newton iterations. Default ``50``; a capped fit usually
            converges in under 20.
        tol: Convergence tolerance: the loop stops at the first iteration
            where every site natural $\lambda_n$, $\Lambda_n$ changed by less
            than ``0.1 * tol * (1 + |new value|)``, which leaves the posterior
            marginals within about ``tol`` of the fixed point. Default
            ``1e-6``.
        damping: Factor $\alpha_d$ in (0, 1] on every Newton
            step, on top of ``max_step``. Default ``1.0``. With the cap on it
            is rarely needed, and it slows every iteration, not only the
            long steps.
        max_step: The largest change one step may make to the posterior
            mean, $\delta$, in prior standard deviations $\sigma_n$. Default
            ``1.0``. ``None`` takes the full Newton step.
        precision_floor: Lower bound on the diagonal precision. Default
            ``1e-6``.
        adjoint: How gradients pass through the loop. Default
            ``optimistix.RecursiveCheckpointAdjoint()``, reverse-mode through
            the iterations that ran. The alternative is
            `markov_implicit_adjoint`, the implicit function theorem at the
            fixed point. Both match central differences equally well on a
            converged fit (relative error 5e-9 to 1.4e-8 on a 365-day
            Bernoulli record). They differ as follows:

            - Cost. With the step cap a fit typically converges in about 7
              iterations, and then the checkpoint gradient is about 1.8 times
              cheaper (116 against 207 ms at N = 365, 422 against 783 ms at
              N = 1460, on CPU). Its cost grows with the iterations run, so a
              fit that needs many (a small ``damping``, ``max_step=None``, or
              a fit that runs to ``max_iter``) can make the implicit adjoint
              the cheaper one. The implicit gradient costs about four
              reverse Kalman passes however many iterations ran.
            - Memory. The checkpoints hold up to ``max_iter`` copies of the
              ``(N,)`` site naturals; the implicit adjoint holds a few.
            - What it is the gradient of. The checkpoint gradient is that of
              the last iterate, so it matches the fixed point's only as
              closely as the loop converged, and it depends on ``damping``
              and ``max_step``. The implicit gradient is the fixed point's
              whatever the path to it.
            - Forward mode. The checkpoint adjoint supports reverse mode only:
              ``jax.jacfwd`` (or NumPyro's
              ``forward_mode_differentiation=True``) raises, where the
              implicit adjoint supports both. ``jax.grad`` and
              ``jax.hessian`` work with either.
            - Failures. Neither raises inside NUTS: a non-finite fit gives a
              non-finite gradient.

            For small $N$, ``optimistix.ImplicitAdjoint()`` solves the dense
            ``(2N, 2N)`` Jacobian by LU.
    """

    max_iter: int = eqx.field(static=True, default=50)
    tol: float = eqx.field(static=True, default=1e-6)
    damping: float = eqx.field(static=True, default=1.0)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    adjoint: optx.AbstractAdjoint = optx.RecursiveCheckpointAdjoint()
    # last, so the earlier fields keep their positions
    max_step: float | None = eqx.field(static=True, default=1.0)

    def _newton_sites(
        self,
        f: Float[Array, " N"],
        site_lik: CallableLikelihood,
        observed: Bool[Array, " N"],
    ) -> _Sites:
        r"""The undamped Newton sites $T(s)$ at the posterior mean ``f``."""
        g, h = site_lik.site_derivatives(f)
        nat1, Lam = newton_update(f, g, h, precision_floor=self.precision_floor)
        return _mask_sites(nat1, Lam, observed, self.precision_floor)

    def _step_cap(
        self,
        prior: MarkovGPPrior,
        prior_sd: Float[Array, " N"] | None,
        f: Float[Array, " N"],
        new_nat1: Float[Array, " N"],
        new_nat2: Float[Array, " N"],
        observed: Bool[Array, " N"],
    ) -> Float[Array, ""] | float:
        r"""The step cap $\min(1, \delta / \max_n |f^N_n - \hat f_n| / \sigma_n)$.

        A step size only, so it is ``stop_gradient``-ed: at the fixed point the
        step is zero whatever its size, and the gradient does not depend on it.
        """
        if self.max_step is None or prior_sd is None:
            return 1.0
        f_newton, _, _ = _markov_smoothed_posterior(prior, new_nat1, new_nat2, observed)
        # A time with σ_n = 0 has a known latent, which no step moves (0 / 0
        # otherwise); it is left out of the cap.
        known = prior_sd <= 0.0
        safe_sd = jnp.where(known, jnp.ones((), dtype=prior_sd.dtype), prior_sd)
        jump = jnp.max(jnp.where(known, 0.0, jnp.abs(f_newton - f) / safe_sd))
        tiny = jnp.finfo(jump.dtype).tiny
        cap = jnp.minimum(1.0, self.max_step / jnp.maximum(jump, tiny))
        return jax.lax.stop_gradient(cap)

    def _step(self, sites: _Sites, args: PyTree) -> _Sites:
        r"""One damped, capped Newton step on the sites, $T_\alpha(s)$."""
        prior, site_lik, observed, prior_sd = args
        nat1, nat2 = sites
        f, _, _ = _markov_smoothed_posterior(prior, nat1, nat2, observed)
        new_nat1, new_nat2 = self._newton_sites(f, site_lik, observed)
        cap = self._step_cap(prior, prior_sd, f, new_nat1, new_nat2, observed)
        lr = self.damping * cap
        nat1, nat2 = damped_natural_update(nat1, nat2, new_nat1, new_nat2, lr=lr)
        assert isinstance(nat2, jax.Array)  # pyrox sites are diagonal arrays
        return _mask_sites(nat1, nat2, observed, self.precision_floor)

    def fit(
        self,
        prior: MarkovGPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> ConditionedNonGaussMarkovGP:
        r"""Fit the sites by Newton steps on the smoothed posterior mean.

        Args:
            prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
            likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
                masked site contributes $g_n = h_n = 0$, so its naturals are
                $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

        Returns:
            The `ConditionedNonGaussMarkovGP` with the fitted sites.

        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)
        """
        # Always the masked likelihood, so that mask=None and an all-True mask
        # compile the same loop and agree bit for bit.
        observed = _observation_mask(mask, prior.times)
        site_lik = as_gaussx_likelihood(likelihood, y, mask=observed)

        N = prior.times.shape[0]
        prior_mean = prior.mean(prior.times)
        nat1 = jnp.asarray(prior_mean) * self.precision_floor
        nat2 = jnp.full((N,), self.precision_floor, dtype=prior_mean.dtype)
        sites = _mask_sites(nat1, nat2, observed, self.precision_floor)
        # σ_n, once per fit: the step cap's scale
        prior_sd = (
            None if self.max_step is None else jnp.sqrt(_prior_marginal_variance(prior))
        )

        fit = argminax.solve.site_fixed_point(
            self._step,
            sites,
            (prior, site_lik, observed, prior_sd),
            tol=_loop_tolerance(self.tol),
            max_iter=self.max_iter,
            adjoint=self.adjoint,
        )
        (nat1, nat2), n_iter, converged = fit.sites, fit.n_iter, fit.converged

        # Final site naturals: the undamped Newton sites at the last mean.
        f, _, _ = _markov_smoothed_posterior(prior, nat1, nat2, observed)
        nat1, nat2 = self._newton_sites(f, site_lik, observed)
        q_mean, q_var, log_marg = _markov_smoothed_posterior(
            prior, nat1, nat2, observed
        )
        log_marg_corrected = log_marg + site_evidence_correction(
            site_lik.log_prob(q_mean), q_mean, nat1, nat2, mask=observed
        )

        return ConditionedNonGaussMarkovGP(
            prior=prior,
            y=y,
            site_nat1=nat1,
            site_nat2=nat2,
            q_mean=q_mean,
            q_var=q_var,
            log_marginal_approx=log_marg_corrected,
            n_iter=n_iter,
            converged=converged,
            mask=None if mask is None else observed,
        )

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 pyrox_ssm.MarkovGPPrior over the observation times.

required
likelihood Likelihood

Any scalar-latent pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. A masked site contributes \(g_n = h_n = 0\), so its naturals are \((\lambda_n, \Lambda_n) = (0, 0)\) and the filter skips it.

None

Returns:

Type Description
ConditionedNonGaussMarkovGP

The ConditionedNonGaussMarkovGP with the fitted sites.

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
def fit(
    self,
    prior: MarkovGPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> ConditionedNonGaussMarkovGP:
    r"""Fit the sites by Newton steps on the smoothed posterior mean.

    Args:
        prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
            masked site contributes $g_n = h_n = 0$, so its naturals are
            $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

    Returns:
        The `ConditionedNonGaussMarkovGP` with the fitted sites.

    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)
    """
    # Always the masked likelihood, so that mask=None and an all-True mask
    # compile the same loop and agree bit for bit.
    observed = _observation_mask(mask, prior.times)
    site_lik = as_gaussx_likelihood(likelihood, y, mask=observed)

    N = prior.times.shape[0]
    prior_mean = prior.mean(prior.times)
    nat1 = jnp.asarray(prior_mean) * self.precision_floor
    nat2 = jnp.full((N,), self.precision_floor, dtype=prior_mean.dtype)
    sites = _mask_sites(nat1, nat2, observed, self.precision_floor)
    # σ_n, once per fit: the step cap's scale
    prior_sd = (
        None if self.max_step is None else jnp.sqrt(_prior_marginal_variance(prior))
    )

    fit = argminax.solve.site_fixed_point(
        self._step,
        sites,
        (prior, site_lik, observed, prior_sd),
        tol=_loop_tolerance(self.tol),
        max_iter=self.max_iter,
        adjoint=self.adjoint,
    )
    (nat1, nat2), n_iter, converged = fit.sites, fit.n_iter, fit.converged

    # Final site naturals: the undamped Newton sites at the last mean.
    f, _, _ = _markov_smoothed_posterior(prior, nat1, nat2, observed)
    nat1, nat2 = self._newton_sites(f, site_lik, observed)
    q_mean, q_var, log_marg = _markov_smoothed_posterior(
        prior, nat1, nat2, observed
    )
    log_marg_corrected = log_marg + site_evidence_correction(
        site_lik.log_prob(q_mean), q_mean, nat1, nat2, mask=observed
    )

    return ConditionedNonGaussMarkovGP(
        prior=prior,
        y=y,
        site_nat1=nat1,
        site_nat2=nat2,
        q_mean=q_mean,
        q_var=q_var,
        log_marginal_approx=log_marg_corrected,
        n_iter=n_iter,
        converged=converged,
        mask=None if mask is None else observed,
    )

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 20.

tol float

Convergence tolerance on the site naturals, as in LaplaceMarkovInference. Default 1e-6.

damping float

Step-size in (0, 1]. Default 1.0.

precision_floor float

Strict positive floor. Default 1e-3.

adjoint AbstractAdjoint

How gradients pass through the loop. Default markov_implicit_adjoint; LaplaceMarkovInference sets out the trade-off against optimistix.RecursiveCheckpointAdjoint().

Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
class GaussNewtonMarkovInference(eqx.Module):
    r"""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:
        max_iter: Newton iterations. Default ``20``.
        tol: Convergence tolerance on the site naturals, as in
            `LaplaceMarkovInference`. Default ``1e-6``.
        damping: Step-size in (0, 1]. Default ``1.0``.
        precision_floor: Strict positive floor. Default ``1e-3``.
        adjoint: How gradients pass through the loop. Default
            `markov_implicit_adjoint`; `LaplaceMarkovInference` sets out
            the trade-off against ``optimistix.RecursiveCheckpointAdjoint()``.
    """

    max_iter: int = eqx.field(static=True, default=20)
    tol: float = eqx.field(static=True, default=1e-6)
    damping: float = eqx.field(static=True, default=1.0)
    precision_floor: float = eqx.field(static=True, default=1e-3)
    adjoint: optx.AbstractAdjoint = _IMPLICIT_ADJOINT

    def fit(
        self,
        prior: MarkovGPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> ConditionedNonGaussMarkovGP:
        r"""Fit the sites by Gauss-Newton steps, as `LaplaceMarkovInference`.

        Args:
            prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
            likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
                masked site contributes $g_n = h_n = 0$, so its naturals are
                $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

        Returns:
            The `ConditionedNonGaussMarkovGP` with the fitted sites.

        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)
        """
        inner = LaplaceMarkovInference(
            max_iter=self.max_iter,
            tol=self.tol,
            damping=self.damping,
            precision_floor=self.precision_floor,
            adjoint=self.adjoint,
        )
        return inner.fit(prior, likelihood, y, mask=mask)

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 pyrox_ssm.MarkovGPPrior over the observation times.

required
likelihood Likelihood

Any scalar-latent pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. A masked site contributes \(g_n = h_n = 0\), so its naturals are \((\lambda_n, \Lambda_n) = (0, 0)\) and the filter skips it.

None

Returns:

Type Description
ConditionedNonGaussMarkovGP

The ConditionedNonGaussMarkovGP with the fitted sites.

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
def fit(
    self,
    prior: MarkovGPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> ConditionedNonGaussMarkovGP:
    r"""Fit the sites by Gauss-Newton steps, as `LaplaceMarkovInference`.

    Args:
        prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
            masked site contributes $g_n = h_n = 0$, so its naturals are
            $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

    Returns:
        The `ConditionedNonGaussMarkovGP` with the fitted sites.

    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)
    """
    inner = LaplaceMarkovInference(
        max_iter=self.max_iter,
        tol=self.tol,
        damping=self.damping,
        precision_floor=self.precision_floor,
        adjoint=self.adjoint,
    )
    return inner.fit(prior, likelihood, y, mask=mask)

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 30.

tol float

Convergence tolerance on the site naturals, as in LaplaceMarkovInference: every \(\lambda_n\) and \(\Lambda_n\) changed by less than 0.1 * tol * (1 + |new value|). Default 1e-6.

damping float

Step-size in (0, 1]. Default 0.5.

precision_floor float

Floor on the diagonal precision. Default 1e-6.

deg int | None

Deprecated. deg=k warns and means integrator=gaussx.GaussHermiteIntegrator(order=k); passing both raises ValueError. Reads as None once resolved.

integrator AbstractIntegrator

Rule for the cavity expectations, any gaussx.AbstractIntegrator. Default gaussx.GaussHermiteIntegrator(order=20).

adjoint AbstractAdjoint

How gradients pass through the loop. Default markov_implicit_adjoint; LaplaceMarkovInference sets out the trade-off against optimistix.RecursiveCheckpointAdjoint().

Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
class PosteriorLinearizationMarkov(eqx.Module):
    r"""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:
        max_iter: Iterations. Default ``30``.
        tol: Convergence tolerance on the site naturals, as in
            `LaplaceMarkovInference`: every $\lambda_n$ and $\Lambda_n$ changed
            by less than ``0.1 * tol * (1 + |new value|)``. Default ``1e-6``.
        damping: Step-size in (0, 1]. Default ``0.5``.
        precision_floor: Floor on the diagonal precision. Default ``1e-6``.
        deg: Deprecated. ``deg=k`` warns and means
            ``integrator=gaussx.GaussHermiteIntegrator(order=k)``; passing
            both raises ``ValueError``. Reads as ``None`` once resolved.
        integrator: Rule for the cavity expectations, any
            `gaussx.AbstractIntegrator`. Default
            ``gaussx.GaussHermiteIntegrator(order=20)``.
        adjoint: How gradients pass through the loop. Default
            `markov_implicit_adjoint`; `LaplaceMarkovInference` sets out
            the trade-off against ``optimistix.RecursiveCheckpointAdjoint()``.
    """

    max_iter: int = eqx.field(static=True, default=30)
    tol: float = eqx.field(static=True, default=1e-6)
    damping: float = eqx.field(static=True, default=0.5)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    deg: int | None = eqx.field(static=True, default=None)
    # Last, so positional arguments keep their meaning. None until
    # __post_init__, which tells "not passed" from a passed rule so that deg and
    # integrator together can raise.
    integrator: AbstractIntegrator = eqx.field(default=None)
    adjoint: optx.AbstractAdjoint = _IMPLICIT_ADJOINT

    def __post_init__(self) -> None:
        self.integrator = _resolve_integrator(self.integrator, self.deg)
        self.deg = None

    def _update(
        self,
        sites: _Sites,
        q_mean: Float[Array, " N"],
        q_var: Float[Array, " N"],
        site_lik: CallableLikelihood,
        observed: Bool[Array, " N"],
    ) -> _Sites:
        """The damped PL sites from the marginals ``(q_mean, q_var)``."""
        nat1, nat2 = sites
        cav_mean, cav_var = cavity_distribution(
            q_mean, q_var, nat1, nat2, precision_floor=self.precision_floor
        )
        assert isinstance(cav_var, jax.Array)  # diagonal path in, diagonal out

        # ḡₙ = 𝔼_{cav}[∂f log p(yₙ | f)], h̄ₙ = 𝔼_{cav}[∂²f log p(yₙ | f)]
        g_avg, h_avg = _cavity_site_derivatives(
            site_lik, cav_mean, cav_var, self.integrator
        )

        new_nat1, new_prec = newton_update(
            cav_mean, g_avg, h_avg, precision_floor=self.precision_floor
        )
        nat1, nat2 = damped_natural_update(
            nat1, nat2, new_nat1, new_prec, lr=self.damping
        )
        assert isinstance(nat2, jax.Array)  # pyrox sites are diagonal arrays
        return _mask_sites(nat1, nat2, observed, self.precision_floor)

    def _step(self, sites: _Sites, args: PyTree) -> _Sites:
        r"""One damped PL sweep, $T_\alpha(s)$, from the smoothed marginals."""
        prior, site_lik, observed = args
        q_mean, q_var, _ = _markov_smoothed_posterior(prior, *sites, observed)
        return self._update(sites, q_mean, q_var, site_lik, observed)

    def fit(
        self,
        prior: MarkovGPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> ConditionedNonGaussMarkovGP:
        r"""Fit the sites by posterior linearization.

        Args:
            prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
            likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
                masked site contributes $g_n = h_n = 0$, so its naturals are
                $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

        Returns:
            The `ConditionedNonGaussMarkovGP` with the fitted sites.

        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)
        """
        return _fit_cavity_sites(self, prior, likelihood, y, mask)

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 pyrox_ssm.MarkovGPPrior over the observation times.

required
likelihood Likelihood

Any scalar-latent pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. A masked site contributes \(g_n = h_n = 0\), so its naturals are \((\lambda_n, \Lambda_n) = (0, 0)\) and the filter skips it.

None

Returns:

Type Description
ConditionedNonGaussMarkovGP

The ConditionedNonGaussMarkovGP with the fitted sites.

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
def fit(
    self,
    prior: MarkovGPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> ConditionedNonGaussMarkovGP:
    r"""Fit the sites by posterior linearization.

    Args:
        prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
            masked site contributes $g_n = h_n = 0$, so its naturals are
            $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

    Returns:
        The `ConditionedNonGaussMarkovGP` with the fitted sites.

    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)
    """
    return _fit_cavity_sites(self, prior, likelihood, y, mask)

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 40.

tol float

Convergence tolerance on the site naturals, as in LaplaceMarkovInference: every \(\lambda_n\) and \(\Lambda_n\) changed by less than 0.1 * tol * (1 + |new value|). Default 1e-5.

damping float

Damping in (0, 1]. Default 0.5.

precision_floor float

Floor on the diagonal precision. Default 1e-6.

deg int | None

Deprecated. deg=k warns and means integrator=gaussx.GaussHermiteIntegrator(order=k); passing both raises ValueError. Reads as None once resolved.

integrator AbstractIntegrator

Rule for the tilted moments. Default gaussx.GaussHermiteIntegrator(order=20). EP reads only its order, for gaussx.ep_tilted_moments, so any other rule raises TypeError.

adjoint AbstractAdjoint

How gradients pass through the loop. Default markov_implicit_adjoint; LaplaceMarkovInference sets out the trade-off against optimistix.RecursiveCheckpointAdjoint().

Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
class ExpectationPropagationMarkov(eqx.Module):
    r"""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:
        max_iter: EP iterations. Default ``40``.
        tol: Convergence tolerance on the site naturals, as in
            `LaplaceMarkovInference`: every $\lambda_n$ and $\Lambda_n$ changed
            by less than ``0.1 * tol * (1 + |new value|)``. Default ``1e-5``.
        damping: Damping in (0, 1]. Default ``0.5``.
        precision_floor: Floor on the diagonal precision. Default ``1e-6``.
        deg: Deprecated. ``deg=k`` warns and means
            ``integrator=gaussx.GaussHermiteIntegrator(order=k)``; passing
            both raises ``ValueError``. Reads as ``None`` once resolved.
        integrator: Rule for the tilted moments. Default
            ``gaussx.GaussHermiteIntegrator(order=20)``. EP reads only its
            ``order``, for `gaussx.ep_tilted_moments`, so any other rule
            raises ``TypeError``.
        adjoint: How gradients pass through the loop. Default
            `markov_implicit_adjoint`; `LaplaceMarkovInference` sets out
            the trade-off against ``optimistix.RecursiveCheckpointAdjoint()``.
    """

    max_iter: int = eqx.field(static=True, default=40)
    tol: float = eqx.field(static=True, default=1e-5)
    damping: float = eqx.field(static=True, default=0.5)
    precision_floor: float = eqx.field(static=True, default=1e-6)
    deg: int | None = eqx.field(static=True, default=None)
    # Last and None until __post_init__; see PosteriorLinearizationMarkov.
    integrator: AbstractIntegrator = eqx.field(default=None)
    adjoint: optx.AbstractAdjoint = _IMPLICIT_ADJOINT

    def __post_init__(self) -> None:
        self.integrator = _resolve_integrator(self.integrator, self.deg)
        self.deg = None

    def __check_init__(self) -> None:
        _require_gauss_hermite(self.integrator)

    def _update(
        self,
        sites: _Sites,
        q_mean: Float[Array, " N"],
        q_var: Float[Array, " N"],
        site_lik: CallableLikelihood,
        observed: Bool[Array, " N"],
    ) -> _Sites:
        """The damped EP sites from the marginals ``(q_mean, q_var)``."""
        nat1, nat2 = sites
        cav_mean, cav_var = cavity_distribution(
            q_mean, q_var, nat1, nat2, precision_floor=self.precision_floor
        )
        assert isinstance(cav_var, jax.Array)  # diagonal path in, diagonal out

        # ``gaussx.ep_tilted_moments`` requires ``log_lik_fn(f)`` with the
        # per-site target baked in; close over the site data ``d_n`` via vmap
        # to recover the (N,) shape contract.
        order = _require_gauss_hermite(self.integrator).order

        def _per_site_tilted(
            m_n: Float[Array, ""],
            v_n: Float[Array, ""],
            d_n: Float[Array, ""],
        ) -> tuple[Float[Array, ""], Float[Array, ""]]:
            return ep_tilted_moments(
                lambda f: site_lik.log_density(f, d_n), m_n, v_n, order=order
            )

        tilted_mean, tilted_var = jax.vmap(_per_site_tilted)(
            cav_mean, cav_var, site_lik.data
        )

        new_prec = jnp.reciprocal(tilted_var) - jnp.reciprocal(cav_var)
        new_prec = jnp.maximum(new_prec, self.precision_floor)
        new_nat1 = tilted_mean / tilted_var - cav_mean / cav_var
        nat1, nat2 = damped_natural_update(
            nat1, nat2, new_nat1, new_prec, lr=self.damping
        )
        assert isinstance(nat2, jax.Array)  # pyrox sites are diagonal arrays
        # A masked site's log density is zero, so its tilted moments are
        # its cavity's and the site it would get is (0, 0) up to rounding;
        # _mask_sites makes that exact.
        return _mask_sites(nat1, nat2, observed, self.precision_floor)

    def _step(self, sites: _Sites, args: PyTree) -> _Sites:
        r"""One damped EP sweep, $T_\alpha(s)$, from the smoothed marginals."""
        prior, site_lik, observed = args
        q_mean, q_var, _ = _markov_smoothed_posterior(prior, *sites, observed)
        return self._update(sites, q_mean, q_var, site_lik, observed)

    def fit(
        self,
        prior: MarkovGPPrior,
        likelihood: Likelihood,
        y: Float[Array, " N"],
        *,
        mask: Bool[Array, " N"] | None = None,
    ) -> ConditionedNonGaussMarkovGP:
        r"""Fit the sites by parallel expectation propagation.

        Args:
            prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
            likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
            y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
            mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
                masked site contributes $g_n = h_n = 0$, so its naturals are
                $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

        Returns:
            The `ConditionedNonGaussMarkovGP` with the fitted sites.

        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)
        """
        return _fit_cavity_sites(self, prior, likelihood, y, mask)

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 pyrox_ssm.MarkovGPPrior over the observation times.

required
likelihood Likelihood

Any scalar-latent pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed. A masked site contributes \(g_n = h_n = 0\), so its naturals are \((\lambda_n, \Lambda_n) = (0, 0)\) and the filter skips it.

None

Returns:

Type Description
ConditionedNonGaussMarkovGP

The ConditionedNonGaussMarkovGP with the fitted sites.

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
def fit(
    self,
    prior: MarkovGPPrior,
    likelihood: Likelihood,
    y: Float[Array, " N"],
    *,
    mask: Bool[Array, " N"] | None = None,
) -> ConditionedNonGaussMarkovGP:
    r"""Fit the sites by parallel expectation propagation.

    Args:
        prior: The `pyrox_ssm.MarkovGPPrior` over the observation times.
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed. A
            masked site contributes $g_n = h_n = 0$, so its naturals are
            $(\lambda_n, \Lambda_n) = (0, 0)$ and the filter skips it.

    Returns:
        The `ConditionedNonGaussMarkovGP` with the fitted sites.

    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)
    """
    return _fit_cavity_sites(self, prior, likelihood, y, mask)

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 MarkovGPPrior.

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 () integer array (a traced value under jax.jit).

converged Bool[Array, '']

Whether the strategy's tol was met within max_iter iterations, a () boolean array (a traced value under jax.jit). Gradients of a fit that did not converge are not those of a fixed point.

mask Bool[Array, ' N'] | None

Optional (N,) boolean observation mask the strategy was fitted with; masked sites hold zero naturals and predict leaves them out of the update. None means every site is observed.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_inference_nongauss_markov.py
class ConditionedNonGaussMarkovGP(eqx.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:
        prior: The originating `MarkovGPPrior`.
        y: Training targets (kept for round-trip / diagnostics).
        site_nat1: Diagonal site naturals $\\lambda \\in \\mathbb{R}^N$.
        site_nat2: Diagonal site precisions $\\Lambda \\in \\mathbb{R}^N$
            (positive).
        q_mean: Posterior mean over training latents.
        q_var: Marginal posterior variance per training point.
        log_marginal_approx: 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: Iterations used by the strategy, a ``()`` integer array (a
            traced value under `jax.jit`).
        converged: Whether the strategy's ``tol`` was met within ``max_iter``
            iterations, a ``()`` boolean array (a traced value under
            `jax.jit`). Gradients of a fit that did not converge are not those
            of a fixed point.
        mask: Optional ``(N,)`` boolean observation mask the strategy was
            fitted with; masked sites hold zero naturals and `predict`
            leaves them out of the update. ``None`` means every site is
            observed.
    """

    prior: MarkovGPPrior
    y: Float[Array, " N"]
    site_nat1: Float[Array, " N"]
    site_nat2: Float[Array, " N"]
    q_mean: Float[Array, " N"]
    q_var: Float[Array, " N"]
    log_marginal_approx: Float[Array, ""]
    n_iter: Int[Array, ""]
    converged: Bool[Array, ""]
    mask: Bool[Array, " N"] | None = None

    def predict(
        self,
        t_star: Float[Array, " M"],
    ) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
        r"""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)$.
        """
        F, _L, H, _Qc, _P_inf = self.prior.sde_kernel.sde_params()
        init_cov = self.prior.initial_covariance()
        times = self.prior.times
        t_star = jnp.asarray(t_star)

        N = times.shape[0]
        M = t_star.shape[0]
        merged = jnp.concatenate([times, t_star], axis=0)
        order = jnp.argsort(merged, stable=True)
        merged_sorted = merged[order]

        observed = _observation_mask(self.mask, times)
        is_obs = jnp.concatenate(
            [observed.astype(times.dtype), jnp.zeros(M, dtype=times.dtype)]
        )[order]
        # A masked training site holds Λ = 0; a unit placeholder keeps
        # λ / Λ and 1 / Λ finite, and the filter skips that step anyway.
        site_prec = jnp.where(
            observed, self.site_nat2, jnp.ones((), dtype=self.site_nat2.dtype)
        )
        pseudo_targets = self.site_nat1 / site_prec
        residual_full = jnp.concatenate(
            [
                pseudo_targets - self.prior.mean(times),
                jnp.zeros(M, dtype=self.y.dtype),
            ]
        )[order]
        # ``R_seq`` for masked steps is irrelevant (the update is
        # skipped) but must be finite to avoid NaN propagation through
        # the filter; use 1.0 as a safe placeholder.
        R_train = jnp.reciprocal(site_prec)
        R_full = jnp.concatenate([R_train, jnp.ones(M, dtype=self.y.dtype)])[order]

        dt_full = _build_dt_full(merged_sorted)
        A_seq, Q_seq = self.prior.sde_kernel.discretise_sequence(dt_full)
        m_pred, P_pred, m_filt, P_filt, _ = _kalman_filter(
            F,
            H,
            init_cov,
            A_seq,
            Q_seq,
            residual_full,
            is_obs,
            R_full,
            parallel=self.prior.parallel,
        )
        m_smooth, P_smooth = _rts_smoother(m_pred, P_pred, m_filt, P_filt, A_seq)

        inv_order = jnp.argsort(order, stable=True)
        test_positions = inv_order[N:]
        m_test_state = m_smooth[test_positions]
        P_test_state = P_smooth[test_positions]
        means = (m_test_state @ H.T)[:, 0] + self.prior.mean(t_star)
        vars_ = jax.vmap(lambda P: (H @ P @ H.T)[0, 0])(P_test_state)
        return means, jnp.maximum(vars_, 0.0)

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
def predict(
    self,
    t_star: Float[Array, " M"],
) -> tuple[Float[Array, " M"], Float[Array, " M"]]:
    r"""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)$.
    """
    F, _L, H, _Qc, _P_inf = self.prior.sde_kernel.sde_params()
    init_cov = self.prior.initial_covariance()
    times = self.prior.times
    t_star = jnp.asarray(t_star)

    N = times.shape[0]
    M = t_star.shape[0]
    merged = jnp.concatenate([times, t_star], axis=0)
    order = jnp.argsort(merged, stable=True)
    merged_sorted = merged[order]

    observed = _observation_mask(self.mask, times)
    is_obs = jnp.concatenate(
        [observed.astype(times.dtype), jnp.zeros(M, dtype=times.dtype)]
    )[order]
    # A masked training site holds Λ = 0; a unit placeholder keeps
    # λ / Λ and 1 / Λ finite, and the filter skips that step anyway.
    site_prec = jnp.where(
        observed, self.site_nat2, jnp.ones((), dtype=self.site_nat2.dtype)
    )
    pseudo_targets = self.site_nat1 / site_prec
    residual_full = jnp.concatenate(
        [
            pseudo_targets - self.prior.mean(times),
            jnp.zeros(M, dtype=self.y.dtype),
        ]
    )[order]
    # ``R_seq`` for masked steps is irrelevant (the update is
    # skipped) but must be finite to avoid NaN propagation through
    # the filter; use 1.0 as a safe placeholder.
    R_train = jnp.reciprocal(site_prec)
    R_full = jnp.concatenate([R_train, jnp.ones(M, dtype=self.y.dtype)])[order]

    dt_full = _build_dt_full(merged_sorted)
    A_seq, Q_seq = self.prior.sde_kernel.discretise_sequence(dt_full)
    m_pred, P_pred, m_filt, P_filt, _ = _kalman_filter(
        F,
        H,
        init_cov,
        A_seq,
        Q_seq,
        residual_full,
        is_obs,
        R_full,
        parallel=self.prior.parallel,
    )
    m_smooth, P_smooth = _rts_smoother(m_pred, P_pred, m_filt, P_filt, A_seq)

    inv_order = jnp.argsort(order, stable=True)
    test_positions = inv_order[N:]
    m_test_state = m_smooth[test_positions]
    P_test_state = P_smooth[test_positions]
    means = (m_test_state @ H.T)[:, 0] + self.prior.mean(t_star)
    vars_ = jax.vmap(lambda P: (H @ P @ H.T)[0, 0])(P_test_state)
    return means, jnp.maximum(vars_, 0.0)

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

\[ \log p(y \mid \theta) \approx \log p(y \mid \hat f) + \log p(\hat f \mid \theta) - \tfrac{1}{2} \log \det (I + W K_\theta), \]

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 MarkovGPPrior over the observation times.

required
likelihood Likelihood

Any scalar-latent pyrox.likelihoods.Likelihood.

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
strategy LaplaceMarkovInference | GaussNewtonMarkovInference | PosteriorLinearizationMarkov | ExpectationPropagationMarkov

The site-based strategy that fits the sites.

required
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed.

None
reject_unconverged bool

If True, the factor is \(-\infty\) when the fit did not meet the strategy's tol within max_iter iterations, so NUTS rejects that \(\theta\) rather than move on an evidence (and an implicit gradient) taken away from the fixed point. Default False: the factor is the evidence at the last iterate.

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
def 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:
    r"""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

    $$
    \log p(y \mid \theta) \approx \log p(y \mid \hat f)
      + \log p(\hat f \mid \theta)
      - \tfrac{1}{2} \log \det (I + W K_\theta),
    $$

    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``.

    Args:
        name: The factor site name.
        prior: The `MarkovGPPrior` over the observation times.
        likelihood: Any scalar-latent `pyrox.likelihoods.Likelihood`.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        strategy: The site-based strategy that fits the sites.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed.
        reject_unconverged: If ``True``, the factor is $-\infty$ when the fit
            did not meet the strategy's ``tol`` within ``max_iter`` iterations,
            so NUTS rejects that $\theta$ rather than move on an evidence (and
            an implicit gradient) taken away from the fixed point. Default
            ``False``: the factor is the evidence at the last iterate.

    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,
        ...     )
    """
    cond = prior.condition_nongauss(likelihood, y, strategy=strategy, mask=mask)
    value = cond.log_marginal_approx
    if reject_unconverged:
        value = jnp.where(cond.converged, value, -jnp.inf)
    numpyro.factor(name, value)

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 optimistix.ImplicitAdjoint for a strategy's adjoint.

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
def markov_implicit_adjoint() -> optx.ImplicitAdjoint:
    r"""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:
        An ``optimistix.ImplicitAdjoint`` for a strategy's ``adjoint``.

    Examples:
        >>> import pyrox_ssm as pss
        >>> strategy = pss.LaplaceMarkovInference(
        ...     adjoint=pss.markov_implicit_adjoint()
        ... )
    """
    return argminax.adjoint.safe_implicit_adjoint(
        lx.GMRES(rtol=1e-10, atol=1e-10, restart=20, max_steps=50)
    )

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 SDEKernel (Matern, Periodic, Cosine, Sum/Product compositions, ...).

Z Float[Array, ' M']

Sorted, strictly increasing inducing times of shape (M,).

mean_fn Callable[[Float[Array, ' N']], Float[Array, ' N']] | None

Optional callable times -> (N,) global mean. Convenience accessor; not folded into the inducing prior.

solver AbstractSolverStrategy | None

Any gaussx.AbstractSolverStrategy. Defaults to gaussx.DenseSolver().

jitter float

Diagonal regularisation added to K_{ZZ} for numerical stability.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
class SparseMarkovGPPrior(eqx.Module):
    r"""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:
        sde_kernel: Any `SDEKernel` (Matern, Periodic, Cosine,
            Sum/Product compositions, ...).
        Z: Sorted, strictly increasing inducing times of shape ``(M,)``.
        mean_fn: Optional callable ``times -> (N,)`` global mean.
            Convenience accessor; not folded into the inducing prior.
        solver: Any ``gaussx.AbstractSolverStrategy``. Defaults to
            ``gaussx.DenseSolver()``.
        jitter: Diagonal regularisation added to ``K_{ZZ}`` for numerical
            stability.
    """

    sde_kernel: SDEKernel
    Z: Float[Array, " M"]
    mean_fn: Callable[[Float[Array, " N"]], Float[Array, " N"]] | None = None
    solver: AbstractSolverStrategy | None = None
    jitter: float = eqx.field(static=True, default=1e-6)

    def __init__(
        self,
        sde_kernel: SDEKernel,
        Z: Float[Array, " M"],
        mean_fn: Callable[[Float[Array, " N"]], Float[Array, " N"]] | None = None,
        solver: AbstractSolverStrategy | None = None,
        jitter: float = 1e-6,
    ) -> None:
        Z_arr = jnp.asarray(Z, dtype=jnp.result_type(Z, 0.0))
        if Z_arr.ndim != 1:
            raise ValueError(f"Z must be 1-D, got shape {tuple(Z_arr.shape)!r}")
        if Z_arr.shape[0] >= 2:
            try:
                if not bool(jnp.all(jnp.diff(Z_arr) > 0)):
                    raise ValueError("Z must be strictly increasing")
            except jax.errors.TracerBoolConversionError:
                pass
        self.sde_kernel = sde_kernel
        self.Z = Z_arr
        self.mean_fn = mean_fn
        self.solver = solver
        self.jitter = float(jitter)

    @property
    def num_inducing(self) -> int:
        """Number of inducing time points $M$."""
        return self.Z.shape[0]

    def mean(self, times: Float[Array, " N"]) -> Float[Array, " N"]:
        """Evaluate the mean function at ``times``; zero by default."""
        if self.mean_fn is None:
            return jnp.zeros_like(times)
        return self.mean_fn(times)

    def _stationary_variance(self) -> Float[Array, ""]:
        r"""Stationary marginal variance ``H P_inf H^T`` (= kernel variance)."""
        _F, _L, H, _Qc, P_inf = self.sde_kernel.sde_params()
        P_inf = _require_stationary(self.sde_kernel, P_inf)
        return (H @ P_inf @ H.T)[0, 0]

    def inducing_operator(self) -> lx.AbstractLinearOperator:
        r"""Return ``K_{ZZ} + \text{jitter}\,I`` as a PSD ``lineax`` operator."""
        # Pairwise |Zᵢ - Zⱼ| lags between inducing times → (M, M).
        diffs = jnp.abs(einx.subtract("i, j -> i j", self.Z, self.Z))
        K_zz = sde_autocovariance(self.sde_kernel, diffs)
        K_zz = symmetrize(K_zz)
        K_zz = K_zz.at[jnp.diag_indices_from(K_zz)].add(self.jitter)
        return _psd_operator(K_zz)

    def cross_covariance(self, times: Float[Array, " N"]) -> Float[Array, "N M"]:
        """``K_{XZ}`` — pairwise SDE autocov between training and inducing times."""
        t = jnp.asarray(times)
        # Pairwise |tₙ - Zₘ| lags between training and inducing times → (N, M).
        diffs = jnp.abs(einx.subtract("n, m -> n m", t, self.Z))
        return sde_autocovariance(self.sde_kernel, diffs)

    def kernel_diag(self, times: Float[Array, " N"]) -> Float[Array, " N"]:
        r"""Prior diagonal $\mathrm{diag}\,K(X, X)$.

        Constant for stationary SDE kernels — equal to ``H P_inf H^T``.
        """
        var0 = self._stationary_variance()
        return jnp.broadcast_to(var0, jnp.asarray(times).shape).astype(self.Z.dtype)

    def predictive_blocks(
        self, times: Float[Array, " N"]
    ) -> tuple[
        lx.AbstractLinearOperator,
        Float[Array, "N M"],
        Float[Array, " N"],
    ]:
        r"""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}\\,I``
          wrapped as a PSD `lineax` operator.
        * `cross_covariance` — pairwise SDE autocov ``K_{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.
        """
        K_zz_op = self.inducing_operator()
        K_xz = self.cross_covariance(times)
        K_xx_diag = self.kernel_diag(times)
        return K_zz_op, K_xz, K_xx_diag

    def _resolved_solver(self) -> AbstractSolverStrategy:
        return DenseSolver() if self.solver is None else self.solver

    def log_prob(self, u: Float[Array, " M"]) -> Float[Array, ""]:
        r"""Log-density under the inducing prior.

        $p(u) = \mathcal{N}(0,\, K_{ZZ} + \text{jitter}\,I)$.
        """
        m = jnp.zeros(self.num_inducing, dtype=u.dtype)
        return gaussian_log_prob(
            m, self.inducing_operator(), u, solver=self._resolved_solver()
        )

    def sample(self, key: Array) -> Float[Array, " M"]:
        r"""Draw $u \sim p(u)$ from the inducing prior."""
        op = self.inducing_operator()
        loc = jnp.zeros(self.num_inducing, dtype=op.out_structure().dtype)
        mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
        return mvn.sample(key)

    def condition(self, guide: Guide) -> ConditionedSparseMarkovGP:
        r"""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

        $$
        q(f) = \int p(f \mid u)\, q(u)\, du,
        $$

        whose ``predict(t_star)`` gives the SVGP predictive marginals.

        Args:
            guide: The fitted guide over the inducing values, any
                `pyrox.likelihoods.Guide` with ``predict(K_xz, K_zz_op,
                K_xx_diag)`` (pyrox-gp's `FullRankGuide`, `WhitenedGuide`,
                …).

        Returns:
            The `ConditionedSparseMarkovGP` holding this prior and the guide.

        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]))
        """
        return ConditionedSparseMarkovGP(prior=self, guide=guide)

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.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
def mean(self, times: Float[Array, " N"]) -> Float[Array, " N"]:
    """Evaluate the mean function at ``times``; zero by default."""
    if self.mean_fn is None:
        return jnp.zeros_like(times)
    return self.mean_fn(times)

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
def inducing_operator(self) -> lx.AbstractLinearOperator:
    r"""Return ``K_{ZZ} + \text{jitter}\,I`` as a PSD ``lineax`` operator."""
    # Pairwise |Zᵢ - Zⱼ| lags between inducing times → (M, M).
    diffs = jnp.abs(einx.subtract("i, j -> i j", self.Z, self.Z))
    K_zz = sde_autocovariance(self.sde_kernel, diffs)
    K_zz = symmetrize(K_zz)
    K_zz = K_zz.at[jnp.diag_indices_from(K_zz)].add(self.jitter)
    return _psd_operator(K_zz)

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
def cross_covariance(self, times: Float[Array, " N"]) -> Float[Array, "N M"]:
    """``K_{XZ}`` — pairwise SDE autocov between training and inducing times."""
    t = jnp.asarray(times)
    # Pairwise |tₙ - Zₘ| lags between training and inducing times → (N, M).
    diffs = jnp.abs(einx.subtract("n, m -> n m", t, self.Z))
    return sde_autocovariance(self.sde_kernel, diffs)

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
def kernel_diag(self, times: Float[Array, " N"]) -> Float[Array, " N"]:
    r"""Prior diagonal $\mathrm{diag}\,K(X, X)$.

    Constant for stationary SDE kernels — equal to ``H P_inf H^T``.
    """
    var0 = self._stationary_variance()
    return jnp.broadcast_to(var0, jnp.asarray(times).shape).astype(self.Z.dtype)

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}\\,I wrapped as a PSD lineax operator.
  • cross_covariance — pairwise SDE autocov K_{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
def predictive_blocks(
    self, times: Float[Array, " N"]
) -> tuple[
    lx.AbstractLinearOperator,
    Float[Array, "N M"],
    Float[Array, " N"],
]:
    r"""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}\\,I``
      wrapped as a PSD `lineax` operator.
    * `cross_covariance` — pairwise SDE autocov ``K_{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.
    """
    K_zz_op = self.inducing_operator()
    K_xz = self.cross_covariance(times)
    K_xx_diag = self.kernel_diag(times)
    return K_zz_op, K_xz, K_xx_diag

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
def log_prob(self, u: Float[Array, " M"]) -> Float[Array, ""]:
    r"""Log-density under the inducing prior.

    $p(u) = \mathcal{N}(0,\, K_{ZZ} + \text{jitter}\,I)$.
    """
    m = jnp.zeros(self.num_inducing, dtype=u.dtype)
    return gaussian_log_prob(
        m, self.inducing_operator(), u, solver=self._resolved_solver()
    )

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
def sample(self, key: Array) -> Float[Array, " M"]:
    r"""Draw $u \sim p(u)$ from the inducing prior."""
    op = self.inducing_operator()
    loc = jnp.zeros(self.num_inducing, dtype=op.out_structure().dtype)
    mvn = MultivariateNormal(loc, op, solver=self._resolved_solver())
    return mvn.sample(key)

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

\[ q(f) = \int p(f \mid u)\, q(u)\, du, \]

whose predict(t_star) gives the SVGP predictive marginals.

Parameters:

Name Type Description Default
guide Guide

The fitted guide over the inducing values, any pyrox.likelihoods.Guide with predict(K_xz, K_zz_op, K_xx_diag) (pyrox-gp's FullRankGuide, WhitenedGuide, …).

required

Returns:

Type Description
ConditionedSparseMarkovGP

The ConditionedSparseMarkovGP holding this prior and the guide.

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
def condition(self, guide: Guide) -> ConditionedSparseMarkovGP:
    r"""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

    $$
    q(f) = \int p(f \mid u)\, q(u)\, du,
    $$

    whose ``predict(t_star)`` gives the SVGP predictive marginals.

    Args:
        guide: The fitted guide over the inducing values, any
            `pyrox.likelihoods.Guide` with ``predict(K_xz, K_zz_op,
            K_xx_diag)`` (pyrox-gp's `FullRankGuide`, `WhitenedGuide`,
            …).

    Returns:
        The `ConditionedSparseMarkovGP` holding this prior and the guide.

    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]))
    """
    return ConditionedSparseMarkovGP(prior=self, guide=guide)

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

\[ \mu_*(t) = K_{*Z} K_{ZZ}^{-1} m_q + \mu(t),\qquad \sigma_*^2(t) = k(t, t) - K_{*Z} K_{ZZ}^{-1} K_{Z*} + K_{*Z} K_{ZZ}^{-1} S_q K_{ZZ}^{-1} K_{Z*}. \]

Cost is \(O(M^3 + |t_*|\,M)\) per call.

Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
class ConditionedSparseMarkovGP(eqx.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

    $$
    \\mu_*(t) = K_{*Z} K_{ZZ}^{-1} m_q + \\mu(t),\\qquad
    \\sigma_*^2(t) = k(t, t) - K_{*Z} K_{ZZ}^{-1} K_{Z*}
                    + K_{*Z} K_{ZZ}^{-1} S_q K_{ZZ}^{-1} K_{Z*}.
    $$

    Cost is $O(M^3 + |t_*|\\,M)$ per call.
    """

    prior: SparseMarkovGPPrior
    guide: Guide

    def predict(
        self, t_star: Float[Array, " M_star"]
    ) -> tuple[Float[Array, " M_star"], Float[Array, " M_star"]]:
        """Predictive ``(mean, var)`` at arbitrary test times."""
        K_zz_op, K_xz, K_xx_diag = self.prior.predictive_blocks(t_star)
        mean, var = self.guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
        return mean + self.prior.mean(t_star), var

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
def predict(
    self, t_star: Float[Array, " M_star"]
) -> tuple[Float[Array, " M_star"], Float[Array, " M_star"]]:
    """Predictive ``(mean, var)`` at arbitrary test times."""
    K_zz_op, K_xz, K_xx_diag = self.prior.predictive_blocks(t_star)
    mean, var = self.guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
    return mean + self.prior.mean(t_star), var

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:

\[ \mathcal{L} = \sum_n \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)] - \mathrm{KL}[q(u) \\| p(u)]. \]

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

SparseMarkovGPPrior over an SDE kernel and inducing time grid.

required
guide Guide

Variational guide over inducing values.

required
likelihood Likelihood

Observation model.

required
times Float[Array, ' N']

Training times of shape (N,).

required
y Float[Array, ' N']

Observations of shape (N,).

required
integrator AbstractIntegrator | None

gaussx integrator for non-conjugate likelihoods. None is fine for pyrox.likelihoods.GaussianLikelihood.

None
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where a point is observed. Masked entries of y may be NaN; they are replaced before any arithmetic.

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 mask is not shaped like y.

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
def 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, ""]:
    r"""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:

    $$
    \mathcal{L} = \sum_n \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)]
                - \mathrm{KL}[q(u) \\| p(u)].
    $$

    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.

    Args:
        prior: `SparseMarkovGPPrior` over an SDE kernel and
            inducing time grid.
        guide: Variational guide over inducing values.
        likelihood: Observation model.
        times: Training times of shape ``(N,)``.
        y: Observations of shape ``(N,)``.
        integrator: ``gaussx`` integrator for non-conjugate
            likelihoods. ``None`` is fine for
            `pyrox.likelihoods.GaussianLikelihood`.
        mask: Optional ``(N,)`` boolean mask, ``True`` where a point is
            observed. Masked entries of ``y`` may be ``NaN``; they are
            replaced before any arithmetic.

    Returns:
        Scalar ELBO value (higher is better).

    Raises:
        ValueError: If a non-conjugate likelihood is used without an
            integrator, or if ``mask`` is not shaped like ``y``.

    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)
    """
    from gaussx import variational_elbo_gaussian

    times_arr = jnp.asarray(times)
    K_zz_op, K_xz, K_xx_diag = prior.predictive_blocks(times_arr)
    f_loc, f_var = guide.predict(K_xz, K_zz_op, K_xx_diag)  # ty: ignore[unresolved-attribute]
    f_loc = f_loc + prior.mean(times_arr)
    kl = guide.kl_divergence(K_zz_op)  # ty: ignore[unresolved-attribute]

    if isinstance(likelihood, GaussianLikelihood):
        if mask is None:
            return variational_elbo_gaussian(
                y,
                f_loc,
                f_var,
                likelihood.noise_var,  # ty: ignore[invalid-argument-type]
                kl,
            )
        observed = _observation_mask(mask, jnp.asarray(y))
        y_obs = jnp.where(observed, y, jnp.zeros((), dtype=f_loc.dtype))
        no_kl = jnp.zeros((), dtype=f_loc.dtype)

        def point_ell(y_n, m_n, v_n):
            # 𝔼_q[log 𝒩(yₙ; fₙ, σ²)] for one point: the ELBO of a single site
            return variational_elbo_gaussian(
                y_n[None],
                m_n[None],
                v_n[None],
                likelihood.noise_var,  # ty: ignore[invalid-argument-type]
                no_kl,
            )

        # ∑ₙ oₙ 𝔼_q[log 𝒩(yₙ; fₙ, σ²)]
        ell_points = jax.vmap(point_ell)(y_obs, f_loc, f_var)
        return jnp.sum(jnp.where(observed, ell_points, 0.0)) - kl

    if integrator is None:
        raise ValueError(
            "Non-conjugate likelihoods require an integrator "
            "(e.g. gaussx.GaussHermiteIntegrator). "
            "Pass integrator=GaussHermiteIntegrator(order=20)."
        )
    # q(fₙ) = 𝒩(mₙ, vₙ) at each time, independent across sites for the ELL
    state = GaussianState(f_loc, lx.DiagonalLinearOperator(f_var))
    # ∑ₙ oₙ 𝔼_q[log p(yₙ ∣ fₙ)]
    if mask is not None:
        _observation_mask(mask, jnp.asarray(y))  # shape check
    site_lik = as_gaussx_likelihood(likelihood, y, mask=mask)
    ell = expected_log_likelihood(site_lik, state, integrator)
    return ell - kl

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:

\[ \mathcal{L} = \sum_n o_n\, \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)] - \mathrm{KL}[q(u) \| p(u)]. \]

Parameters:

Name Type Description Default
name str

The factor site name.

required
prior SparseMarkovGPPrior

SparseMarkovGPPrior over an SDE kernel and inducing grid.

required
guide Guide

Variational guide over inducing values.

required
likelihood Likelihood

Observation model.

required
times Float[Array, ' N']

Training times of shape (N,).

required
y Float[Array, ' N']

Observations of shape (N,); masked entries may be NaN.

required
integrator AbstractIntegrator | None

gaussx integrator for non-conjugate likelihoods.

None
mask Bool[Array, ' N'] | None

Optional (N,) boolean mask, True where observed.

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,
...     )
Source code in packages/pyrox-ssm/src/pyrox_ssm/_sparse_markov.py
def 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:
    r"""Register `sparse_markov_elbo` as a NumPyro factor site.

    With a mask, only the observed points score:

    $$
    \mathcal{L} = \sum_n o_n\, \mathbb{E}_{q(f_n)}[\log p(y_n \mid f_n)]
                - \mathrm{KL}[q(u) \| p(u)].
    $$

    Args:
        name: The factor site name.
        prior: `SparseMarkovGPPrior` over an SDE kernel and inducing grid.
        guide: Variational guide over inducing values.
        likelihood: Observation model.
        times: Training times of shape ``(N,)``.
        y: Observations of shape ``(N,)``; masked entries may be ``NaN``.
        integrator: ``gaussx`` integrator for non-conjugate likelihoods.
        mask: Optional ``(N,)`` boolean mask, ``True`` where observed.

    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,
        ...     )
    """
    numpyro.factor(
        name,
        sparse_markov_elbo(
            prior, guide, likelihood, times, y, integrator=integrator, mask=mask
        ),
    )