Skip to content

Gauss API

pyrox_gauss holds the Gaussian NumPyro distributions whose covariance or precision is a gaussx operator. They moved here from gaussx with their names, constructors and numerics unchanged (#453), so moving to them is an import change. pyrox_gauss imports gaussx and NumPyro and never imports pyrox; the model packages build these distributions from the hyperparameters they sample.

Multivariate normals

AbstractMultivariateNormal

Bases: Distribution

Common surface of MultivariateNormal and MultivariateNormalPrecision.

x ~ 𝒩(μ, Σ),   Λ = Σ⁻¹

A subclass stores one native operator: the covariance Σ (MultivariateNormal) or the precision Λ (MultivariateNormalPrecision). The other one is the lazy gaussx.inv of it. Code written against this base works for either parameterisation:

  • covariance_operator / precision_operator: lineax operators, one native and one a lazy inverse.
  • covariance_matrix / precision_matrix / scale_tril: dense arrays with numpyro's names and batch broadcasting. They materialise D_x × D_x matrices, so they are for small problems and interop.
  • mean, log_prob, kl.

Requires the numpyro optional extra (pip install "gaussx[numpyro]").

Examples:

Both parameterisations expose the same accessors:

>>> import jax.numpy as jnp
>>> import lineax as lx
>>> from pyrox_gauss import (
...     AbstractMultivariateNormal,
...     MultivariateNormal,
...     MultivariateNormalPrecision,
... )
>>> covariance = lx.MatrixLinearOperator(
...     2.0 * jnp.eye(2), lx.positive_semidefinite_tag
... )
>>> precision = lx.MatrixLinearOperator(
...     0.5 * jnp.eye(2), lx.positive_semidefinite_tag
... )
>>> p = MultivariateNormal(jnp.zeros(2), covariance)
>>> q = MultivariateNormalPrecision(jnp.zeros(2), precision)
>>> isinstance(q, AbstractMultivariateNormal)
True
>>> bool(jnp.allclose(p.precision_matrix, q.precision_matrix))
True

Equal Gaussians have zero KL, whatever the parameterisation:

>>> bool(jnp.allclose(p.kl(q), 0.0, atol=1e-6))
True

Batched means broadcast the dense accessors:

>>> batched = MultivariateNormal(jnp.zeros((3, 2)), covariance)
>>> batched.covariance_matrix.shape, batched.log_prob(jnp.ones(2)).shape
((3, 2, 2), (3,))
Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
class AbstractMultivariateNormal(dist.Distribution):
    """Common surface of `MultivariateNormal` and `MultivariateNormalPrecision`.

        x ~ 𝒩(μ, Σ),   Λ = Σ⁻¹

    A subclass stores one native operator: the covariance Σ
    (`MultivariateNormal`) or the precision Λ (`MultivariateNormalPrecision`).
    The other one is the lazy `gaussx.inv` of it. Code written against this
    base works for either parameterisation:

    - ``covariance_operator`` / ``precision_operator``: lineax operators,
      one native and one a lazy inverse.
    - ``covariance_matrix`` / ``precision_matrix`` / ``scale_tril``: dense
      arrays with numpyro's names and batch broadcasting. They materialise
      D_x × D_x matrices, so they are for small problems and interop.
    - ``mean``, ``log_prob``, `kl`.

    Requires the ``numpyro`` optional extra
    (``pip install "gaussx[numpyro]"``).

    Examples:
        Both parameterisations expose the same accessors:

        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> from pyrox_gauss import (
        ...     AbstractMultivariateNormal,
        ...     MultivariateNormal,
        ...     MultivariateNormalPrecision,
        ... )
        >>> covariance = lx.MatrixLinearOperator(
        ...     2.0 * jnp.eye(2), lx.positive_semidefinite_tag
        ... )
        >>> precision = lx.MatrixLinearOperator(
        ...     0.5 * jnp.eye(2), lx.positive_semidefinite_tag
        ... )
        >>> p = MultivariateNormal(jnp.zeros(2), covariance)
        >>> q = MultivariateNormalPrecision(jnp.zeros(2), precision)
        >>> isinstance(q, AbstractMultivariateNormal)
        True
        >>> bool(jnp.allclose(p.precision_matrix, q.precision_matrix))
        True

        Equal Gaussians have zero KL, whatever the parameterisation:

        >>> bool(jnp.allclose(p.kl(q), 0.0, atol=1e-6))
        True

        Batched means broadcast the dense accessors:

        >>> batched = MultivariateNormal(jnp.zeros((3, 2)), covariance)
        >>> batched.covariance_matrix.shape, batched.log_prob(jnp.ones(2)).shape
        ((3, 2, 2), (3,))
    """

    arg_constraints = {"loc": dist.constraints.real_vector}  # noqa: RUF012
    support = dist.constraints.real_vector
    reparametrized_params = ["loc"]  # noqa: RUF012

    loc: Float[Array, "*batch N"]
    solver: AbstractSolverStrategy

    @property
    def covariance_operator(self) -> lx.AbstractLinearOperator:
        """The covariance Σ as a lineax operator."""
        raise NotImplementedError

    @property
    def precision_operator(self) -> lx.AbstractLinearOperator:
        """The precision Λ = Σ⁻¹ as a lineax operator."""
        raise NotImplementedError

    def _log_prob_single(self, residual: Float[Array, " N"]) -> Float[Array, ""]:
        """Log-density of one event from its residual r = x − μ.

        Args:
            residual: Residual r = x − μ of a single event.

        Returns:
            The scalar log 𝒩(x; μ, Σ).
        """
        raise NotImplementedError

    @validate_sample
    def log_prob(self, value: Float[Array, "*batch N"]) -> Float[Array, "*batch"]:
        """Log-density log 𝒩(x; μ, Σ), broadcast over the batch shape.

            log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + rᵀ Σ⁻¹ r),
            r = x − μ

        Algorithm:
            1. Form the residuals r = x − μ, broadcasting x against μ.
            2. Flatten the leading axes and evaluate one event at a time.
            3. Restore the leading shape.

        Args:
            value: Points x, with any leading shape that broadcasts against
                the batch shape.

        Returns:
            One log-density per broadcast batch element.
        """
        # r = x − μ
        residual = value - self.loc
        leading_shape = residual.shape[:-1]
        residual_flat = rearrange(residual, "... D -> (...) D")
        log_prob_flat = jax.vmap(self._log_prob_single)(residual_flat)
        return _reshape_batch(log_prob_flat, leading_shape)

    @lazy_property
    def mean(self) -> Float[Array, "*batch N"]:
        """The mean μ."""
        return self.loc

    def _broadcast_matrix(self, matrix: Float[Array, "N N"]) -> Array:
        """Broadcast a shared D_x × D_x matrix over the batch shape.

        Args:
            matrix: The shared matrix.

        Returns:
            The matrix repeated for every batch element.
        """
        return jnp.broadcast_to(matrix, self.batch_shape + self.event_shape * 2)

    @lazy_property
    def covariance_matrix(self) -> Float[Array, "*batch N N"]:
        """Dense Σ, broadcast over the batch shape."""
        return self._broadcast_matrix(self.covariance_operator.as_matrix())

    @lazy_property
    def precision_matrix(self) -> Float[Array, "*batch N N"]:
        """Dense Λ = Σ⁻¹, broadcast over the batch shape."""
        return self._broadcast_matrix(self.precision_operator.as_matrix())

    @lazy_property
    def scale_tril(self) -> Float[Array, "*batch N N"]:
        """Dense lower Cholesky factor L of Σ = L Lᵀ (numpyro's name)."""
        # L Lᵀ = Σ
        return jnp.linalg.cholesky(self.covariance_matrix)

    def kl(self, other: AbstractMultivariateNormal) -> Float[Array, "*batch"]:
        """KL(first ‖ second): KL[self ‖ other] in closed form.

            KL[p ‖ q] = ½ (tr(Σ_q⁻¹ Σ_p) + (μ_q − μ_p)ᵀ Σ_q⁻¹ (μ_q − μ_p) − D_x
                           + log det Σ_q − log det Σ_p)

        with p = self and q = other. Any mix of covariance and precision
        parameterisations works. A precision-parameterised ``other`` needs no
        solve for tr(Σ_q⁻¹ Σ_p) or the quadratic term, because the inverse of
        its lazy covariance is its precision. Batch shapes broadcast as in
        numpyro's ``kl_divergence``. Unlike
        ``numpyro.distributions.kl_divergence``, it uses the closed form
        whatever the solver strategies are.

        Args:
            other: The second Gaussian q, with the same event shape.

        Returns:
            The KL divergence, with the broadcast batch shape.
        """
        # lazy import, cycle: _numpyro_kl -> _mvn_base
        from pyrox_gauss._numpyro_kl import closed_form_kl

        return closed_form_kl(self, other)

covariance_operator: lx.AbstractLinearOperator property

The covariance Σ as a lineax operator.

precision_operator: lx.AbstractLinearOperator property

The precision Λ = Σ⁻¹ as a lineax operator.

log_prob(value: Float[Array, '*batch N']) -> Float[Array, '*batch']

Log-density log 𝒩(x; μ, Σ), broadcast over the batch shape.

log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + rᵀ Σ⁻¹ r),
r = x − μ
Algorithm
  1. Form the residuals r = x − μ, broadcasting x against μ.
  2. Flatten the leading axes and evaluate one event at a time.
  3. Restore the leading shape.

Parameters:

Name Type Description Default
value Float[Array, '*batch N']

Points x, with any leading shape that broadcasts against the batch shape.

required

Returns:

Type Description
Float[Array, '*batch']

One log-density per broadcast batch element.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
@validate_sample
def log_prob(self, value: Float[Array, "*batch N"]) -> Float[Array, "*batch"]:
    """Log-density log 𝒩(x; μ, Σ), broadcast over the batch shape.

        log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + rᵀ Σ⁻¹ r),
        r = x − μ

    Algorithm:
        1. Form the residuals r = x − μ, broadcasting x against μ.
        2. Flatten the leading axes and evaluate one event at a time.
        3. Restore the leading shape.

    Args:
        value: Points x, with any leading shape that broadcasts against
            the batch shape.

    Returns:
        One log-density per broadcast batch element.
    """
    # r = x − μ
    residual = value - self.loc
    leading_shape = residual.shape[:-1]
    residual_flat = rearrange(residual, "... D -> (...) D")
    log_prob_flat = jax.vmap(self._log_prob_single)(residual_flat)
    return _reshape_batch(log_prob_flat, leading_shape)

mean() -> Float[Array, '*batch N']

The mean μ.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
@lazy_property
def mean(self) -> Float[Array, "*batch N"]:
    """The mean μ."""
    return self.loc

covariance_matrix() -> Float[Array, '*batch N N']

Dense Σ, broadcast over the batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
@lazy_property
def covariance_matrix(self) -> Float[Array, "*batch N N"]:
    """Dense Σ, broadcast over the batch shape."""
    return self._broadcast_matrix(self.covariance_operator.as_matrix())

precision_matrix() -> Float[Array, '*batch N N']

Dense Λ = Σ⁻¹, broadcast over the batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
@lazy_property
def precision_matrix(self) -> Float[Array, "*batch N N"]:
    """Dense Λ = Σ⁻¹, broadcast over the batch shape."""
    return self._broadcast_matrix(self.precision_operator.as_matrix())

scale_tril() -> Float[Array, '*batch N N']

Dense lower Cholesky factor L of Σ = L Lᵀ (numpyro's name).

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
@lazy_property
def scale_tril(self) -> Float[Array, "*batch N N"]:
    """Dense lower Cholesky factor L of Σ = L Lᵀ (numpyro's name)."""
    # L Lᵀ = Σ
    return jnp.linalg.cholesky(self.covariance_matrix)

kl(other: AbstractMultivariateNormal) -> Float[Array, '*batch']

KL(first ‖ second): KL[self ‖ other] in closed form.

KL[p ‖ q] = ½ (tr(Σ_q⁻¹ Σ_p) + (μ_q − μ_p)ᵀ Σ_q⁻¹ (μ_q − μ_p) − D_x
               + log det Σ_q − log det Σ_p)

with p = self and q = other. Any mix of covariance and precision parameterisations works. A precision-parameterised other needs no solve for tr(Σ_q⁻¹ Σ_p) or the quadratic term, because the inverse of its lazy covariance is its precision. Batch shapes broadcast as in numpyro's kl_divergence. Unlike numpyro.distributions.kl_divergence, it uses the closed form whatever the solver strategies are.

Parameters:

Name Type Description Default
other AbstractMultivariateNormal

The second Gaussian q, with the same event shape.

required

Returns:

Type Description
Float[Array, '*batch']

The KL divergence, with the broadcast batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_base.py
def kl(self, other: AbstractMultivariateNormal) -> Float[Array, "*batch"]:
    """KL(first ‖ second): KL[self ‖ other] in closed form.

        KL[p ‖ q] = ½ (tr(Σ_q⁻¹ Σ_p) + (μ_q − μ_p)ᵀ Σ_q⁻¹ (μ_q − μ_p) − D_x
                       + log det Σ_q − log det Σ_p)

    with p = self and q = other. Any mix of covariance and precision
    parameterisations works. A precision-parameterised ``other`` needs no
    solve for tr(Σ_q⁻¹ Σ_p) or the quadratic term, because the inverse of
    its lazy covariance is its precision. Batch shapes broadcast as in
    numpyro's ``kl_divergence``. Unlike
    ``numpyro.distributions.kl_divergence``, it uses the closed form
    whatever the solver strategies are.

    Args:
        other: The second Gaussian q, with the same event shape.

    Returns:
        The KL divergence, with the broadcast batch shape.
    """
    # lazy import, cycle: _numpyro_kl -> _mvn_base
    from pyrox_gauss._numpyro_kl import closed_form_kl

    return closed_form_kl(self, other)

MultivariateNormal

Bases: AbstractMultivariateNormal

Multivariate normal 𝒩(μ, Σ) whose covariance Σ is a lineax operator.

x ~ 𝒩(μ, Σ)
log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + (x − μ)ᵀ Σ⁻¹ (x − μ))

Covariance-parameterised member of AbstractMultivariateNormal, which supplies the shared accessors (covariance_operator, precision_operator, covariance_matrix, scale_tril, kl, …). Unlike numpyro.distributions.MultivariateNormal, which needs dense arrays, it accepts any lineax.AbstractLinearOperator as Σ, so the log-density, sampling and entropy use gaussx structural dispatch for structured covariances (Kronecker, block-diagonal, low-rank, diagonal, …).

Requires the numpyro optional extra (pip install "gaussx[numpyro]").

Parameters:

Name Type Description Default
loc Float[Array, '*batch N']

Mean μ; leading axes are the batch shape.

required
cov_operator AbstractLinearOperator

Covariance Σ, shared by every batch element.

required
solver AbstractSolverStrategy | None

Solver strategy for the solves and log-determinants of Σ. Defaults to AutoSolver().

None
validate_args bool | None

Whether to validate input arguments.

None

Examples:

A standard normal in three dimensions:

>>> import jax
>>> import jax.numpy as jnp
>>> import lineax as lx
>>> from pyrox_gauss import MultivariateNormal
>>> covariance = lx.MatrixLinearOperator(
...     jnp.eye(3), lx.positive_semidefinite_tag
... )
>>> d = MultivariateNormal(jnp.zeros(3), covariance)
>>> round(float(d.log_prob(jnp.ones(3))), 4)
-4.2568

Draws carry the sample shape in front of the event shape:

>>> d.sample(jax.random.key(0), (4,)).shape
(4, 3)

A structured covariance gives the same entropy as its dense matrix:

>>> diagonal = MultivariateNormal(
...     jnp.zeros(3), lx.DiagonalLinearOperator(jnp.ones(3))
... )
>>> bool(jnp.allclose(diagonal.entropy(), d.entropy()))
True
Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn.py
class MultivariateNormal(AbstractMultivariateNormal):
    """Multivariate normal 𝒩(μ, Σ) whose covariance Σ is a lineax operator.

        x ~ 𝒩(μ, Σ)
        log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + (x − μ)ᵀ Σ⁻¹ (x − μ))

    Covariance-parameterised member of `AbstractMultivariateNormal`, which
    supplies the shared accessors (``covariance_operator``,
    ``precision_operator``, ``covariance_matrix``, ``scale_tril``, `kl`, …).
    Unlike ``numpyro.distributions.MultivariateNormal``, which needs dense
    arrays, it accepts any ``lineax.AbstractLinearOperator`` as Σ, so the
    log-density, sampling and entropy use gaussx structural dispatch for
    structured covariances (Kronecker, block-diagonal, low-rank, diagonal,
    …).

    Requires the ``numpyro`` optional extra
    (``pip install "gaussx[numpyro]"``).

    Args:
        loc: Mean μ; leading axes are the batch shape.
        cov_operator: Covariance Σ, shared by every batch element.
        solver: Solver strategy for the solves and log-determinants of Σ.
            Defaults to ``AutoSolver()``.
        validate_args: Whether to validate input arguments.

    Examples:
        A standard normal in three dimensions:

        >>> import jax
        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> from pyrox_gauss import MultivariateNormal
        >>> covariance = lx.MatrixLinearOperator(
        ...     jnp.eye(3), lx.positive_semidefinite_tag
        ... )
        >>> d = MultivariateNormal(jnp.zeros(3), covariance)
        >>> round(float(d.log_prob(jnp.ones(3))), 4)
        -4.2568

        Draws carry the sample shape in front of the event shape:

        >>> d.sample(jax.random.key(0), (4,)).shape
        (4, 3)

        A structured covariance gives the same entropy as its dense matrix:

        >>> diagonal = MultivariateNormal(
        ...     jnp.zeros(3), lx.DiagonalLinearOperator(jnp.ones(3))
        ... )
        >>> bool(jnp.allclose(diagonal.entropy(), d.entropy()))
        True
    """

    pytree_data_fields = ("loc", "cov_operator", "solver")

    def __init__(
        self,
        loc: Float[Array, "*batch N"],
        cov_operator: lx.AbstractLinearOperator,
        solver: AbstractSolverStrategy | None = None,
        *,
        validate_args: bool | None = None,
    ) -> None:
        if solver is None:
            solver = AutoSolver()
        self.loc = loc
        self.cov_operator = cov_operator
        self.solver = solver
        event_shape = loc.shape[-1:]
        batch_shape = loc.shape[:-1]
        super().__init__(
            batch_shape=batch_shape,
            event_shape=event_shape,
            validate_args=validate_args,
        )

    @property
    def covariance_operator(self) -> lx.AbstractLinearOperator:
        """The covariance Σ (native; the same object as ``cov_operator``)."""
        return self.cov_operator

    @property
    def precision_operator(self) -> lx.AbstractLinearOperator:
        """The precision Λ = Σ⁻¹: the lazy `gaussx.inv` of ``cov_operator``."""
        return _inv(self.cov_operator)

    def _log_prob_single(self, residual: Float[Array, " N"]) -> Float[Array, ""]:
        """Log-density of one event from its residual r = x − μ.

            log 𝒩(x; μ, Σ) = −½ (D_x log 2π + log det Σ + rᵀ Σ⁻¹ r)

        Args:
            residual: Residual r = x − μ of a single event.

        Returns:
            The scalar log 𝒩(x; μ, Σ).
        """
        # log 𝒩(r; 0, Σ), the same residual as log 𝒩(x; μ, Σ)
        return gaussian_log_prob(
            jnp.zeros_like(residual), self.cov_operator, residual, solver=self.solver
        )

    def sample(
        self,
        key: jax.Array | None,
        sample_shape: tuple[int, ...] = (),
    ) -> Float[Array, "*batch N"]:
        """Draw x = μ + Σ^½ z with z ~ 𝒩(0, I), through `gaussx.sample_mvn`.

            x = μ + Σ^½ z,   z ~ 𝒩(0, I)

        `gaussx.sample_mvn` dispatches on the structure of Σ (Kronecker,
        low-rank, scalar multiples, …) and takes a symmetric square root at
        the dense fallback, so a semi-definite Σ gives exact finite draws
        instead of a NaN Cholesky.

        Args:
            key: PRNG key.
            sample_shape: Leading shape of the draws.

        Returns:
            Draws of shape ``sample_shape + batch_shape + event_shape``.

        Raises:
            ValueError: If ``key`` is ``None``.
        """
        if key is None:
            raise ValueError(
                "PRNG key must be provided to sample from MultivariateNormal."
            )
        num_samples = math.prod(sample_shape)
        # μ, one per batch element
        mean = jnp.broadcast_to(self.loc, self.batch_shape + self.event_shape)
        if num_samples == 0:
            # sample_mvn needs at least one draw. Trace one abstractly, so an
            # empty sample still gets its shape checks and its dtype.
            one = jax.eval_shape(
                lambda: sample_mvn(mean, self.cov_operator, key=key, num_samples=1)
            )
            return jnp.zeros(sample_shape + one.shape[1:], dtype=one.dtype)
        # x = μ + Σ^½ z, stacked along one leading axis
        draws = sample_mvn(mean, self.cov_operator, key=key, num_samples=num_samples)
        return _unflatten_sample_axis(draws, sample_shape)

    @lazy_property
    def variance(self) -> Float[Array, "*batch N"]:
        """Marginal variances diag(Σ), broadcast over the batch shape."""
        # diag(Σ)
        marginal_variance = _diag(self.cov_operator)
        return jnp.broadcast_to(marginal_variance, self.batch_shape + self.event_shape)

    def entropy(self) -> Float[Array, "*batch"]:
        """Entropy ℍ[𝒩(μ, Σ)], one entry per batch element.

            ℍ[𝒩(μ, Σ)] = ½ (D_x (1 + log 2π) + log det Σ)

        Returns:
            The entropy, broadcast over the batch shape.
        """
        # ℍ[𝒩(μ, Σ)] = ½ (D_x (1 + log 2π) + log det Σ)
        entropy = gaussian_entropy(self.cov_operator, solver=self.solver)
        # The entropy does not depend on μ, but numpyro's contract is one
        # entry per batch element (Independent.entropy sums over them).
        return jnp.broadcast_to(entropy, self.batch_shape)

covariance_operator: lx.AbstractLinearOperator property

The covariance Σ (native; the same object as cov_operator).

precision_operator: lx.AbstractLinearOperator property

The precision Λ = Σ⁻¹: the lazy gaussx.inv of cov_operator.

sample(key: jax.Array | None, sample_shape: tuple[int, ...] = ()) -> Float[Array, '*batch N']

Draw x = μ + Σ^½ z with z ~ 𝒩(0, I), through gaussx.sample_mvn.

x = μ + Σ^½ z,   z ~ 𝒩(0, I)

gaussx.sample_mvn dispatches on the structure of Σ (Kronecker, low-rank, scalar multiples, …) and takes a symmetric square root at the dense fallback, so a semi-definite Σ gives exact finite draws instead of a NaN Cholesky.

Parameters:

Name Type Description Default
key Array | None

PRNG key.

required
sample_shape tuple[int, ...]

Leading shape of the draws.

()

Returns:

Type Description
Float[Array, '*batch N']

Draws of shape sample_shape + batch_shape + event_shape.

Raises:

Type Description
ValueError

If key is None.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn.py
def sample(
    self,
    key: jax.Array | None,
    sample_shape: tuple[int, ...] = (),
) -> Float[Array, "*batch N"]:
    """Draw x = μ + Σ^½ z with z ~ 𝒩(0, I), through `gaussx.sample_mvn`.

        x = μ + Σ^½ z,   z ~ 𝒩(0, I)

    `gaussx.sample_mvn` dispatches on the structure of Σ (Kronecker,
    low-rank, scalar multiples, …) and takes a symmetric square root at
    the dense fallback, so a semi-definite Σ gives exact finite draws
    instead of a NaN Cholesky.

    Args:
        key: PRNG key.
        sample_shape: Leading shape of the draws.

    Returns:
        Draws of shape ``sample_shape + batch_shape + event_shape``.

    Raises:
        ValueError: If ``key`` is ``None``.
    """
    if key is None:
        raise ValueError(
            "PRNG key must be provided to sample from MultivariateNormal."
        )
    num_samples = math.prod(sample_shape)
    # μ, one per batch element
    mean = jnp.broadcast_to(self.loc, self.batch_shape + self.event_shape)
    if num_samples == 0:
        # sample_mvn needs at least one draw. Trace one abstractly, so an
        # empty sample still gets its shape checks and its dtype.
        one = jax.eval_shape(
            lambda: sample_mvn(mean, self.cov_operator, key=key, num_samples=1)
        )
        return jnp.zeros(sample_shape + one.shape[1:], dtype=one.dtype)
    # x = μ + Σ^½ z, stacked along one leading axis
    draws = sample_mvn(mean, self.cov_operator, key=key, num_samples=num_samples)
    return _unflatten_sample_axis(draws, sample_shape)

variance() -> Float[Array, '*batch N']

Marginal variances diag(Σ), broadcast over the batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn.py
@lazy_property
def variance(self) -> Float[Array, "*batch N"]:
    """Marginal variances diag(Σ), broadcast over the batch shape."""
    # diag(Σ)
    marginal_variance = _diag(self.cov_operator)
    return jnp.broadcast_to(marginal_variance, self.batch_shape + self.event_shape)

entropy() -> Float[Array, '*batch']

Entropy ℍ[𝒩(μ, Σ)], one entry per batch element.

ℍ[𝒩(μ, Σ)] = ½ (D_x (1 + log 2π) + log det Σ)

Returns:

Type Description
Float[Array, '*batch']

The entropy, broadcast over the batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn.py
def entropy(self) -> Float[Array, "*batch"]:
    """Entropy ℍ[𝒩(μ, Σ)], one entry per batch element.

        ℍ[𝒩(μ, Σ)] = ½ (D_x (1 + log 2π) + log det Σ)

    Returns:
        The entropy, broadcast over the batch shape.
    """
    # ℍ[𝒩(μ, Σ)] = ½ (D_x (1 + log 2π) + log det Σ)
    entropy = gaussian_entropy(self.cov_operator, solver=self.solver)
    # The entropy does not depend on μ, but numpyro's contract is one
    # entry per batch element (Independent.entropy sums over them).
    return jnp.broadcast_to(entropy, self.batch_shape)

MultivariateNormalPrecision

Bases: AbstractMultivariateNormal

Multivariate normal 𝒩(μ, Λ⁻¹) whose precision Λ = Σ⁻¹ is a lineax operator.

x ~ 𝒩(μ, Λ⁻¹)
log 𝒩(x; μ, Λ⁻¹) = −½ (D_x log 2π − log det Λ + (x − μ)ᵀ Λ (x − μ))

The natural parameterisation for many inference algorithms (message passing, variational inference in natural coordinates): the log-density needs a matrix-vector product with Λ and no solve. Precision-parameterised member of AbstractMultivariateNormal, which supplies the shared accessors (covariance_operator, precision_operator, covariance_matrix, scale_tril, kl, …).

Requires the numpyro optional extra (pip install "gaussx[numpyro]").

Parameters:

Name Type Description Default
loc Float[Array, '*batch N']

Mean μ; leading axes are the batch shape.

required
prec_operator AbstractLinearOperator

Precision Λ = Σ⁻¹, shared by every batch element.

required
solver AbstractSolverStrategy | None

Solver strategy for the log-determinant of Λ. Defaults to AutoSolver().

None
validate_args bool | None

Whether to validate input arguments.

None

Examples:

A precision of 2 I in three dimensions:

>>> import jax
>>> import jax.numpy as jnp
>>> import lineax as lx
>>> from pyrox_gauss import MultivariateNormalPrecision
>>> precision = lx.MatrixLinearOperator(
...     2.0 * jnp.eye(3), lx.positive_semidefinite_tag
... )
>>> d = MultivariateNormalPrecision(jnp.zeros(3), precision)
>>> round(float(d.log_prob(jnp.ones(3))), 4)
-4.7171

The marginal variances are diag(Λ⁻¹):

>>> bool(jnp.allclose(d.variance, 0.5 * jnp.ones(3)))
True

Draws carry the sample shape in front of the event shape:

>>> d.sample(jax.random.key(0), (4,)).shape
(4, 3)
Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_prec.py
class MultivariateNormalPrecision(AbstractMultivariateNormal):
    """Multivariate normal 𝒩(μ, Λ⁻¹) whose precision Λ = Σ⁻¹ is a lineax operator.

        x ~ 𝒩(μ, Λ⁻¹)
        log 𝒩(x; μ, Λ⁻¹) = −½ (D_x log 2π − log det Λ + (x − μ)ᵀ Λ (x − μ))

    The natural parameterisation for many inference algorithms (message
    passing, variational inference in natural coordinates): the log-density
    needs a matrix-vector product with Λ and no solve. Precision-parameterised
    member of `AbstractMultivariateNormal`, which supplies the shared
    accessors (``covariance_operator``, ``precision_operator``,
    ``covariance_matrix``, ``scale_tril``, `kl`, …).

    Requires the ``numpyro`` optional extra
    (``pip install "gaussx[numpyro]"``).

    Args:
        loc: Mean μ; leading axes are the batch shape.
        prec_operator: Precision Λ = Σ⁻¹, shared by every batch element.
        solver: Solver strategy for the log-determinant of Λ. Defaults to
            ``AutoSolver()``.
        validate_args: Whether to validate input arguments.

    Examples:
        A precision of 2 I in three dimensions:

        >>> import jax
        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> from pyrox_gauss import MultivariateNormalPrecision
        >>> precision = lx.MatrixLinearOperator(
        ...     2.0 * jnp.eye(3), lx.positive_semidefinite_tag
        ... )
        >>> d = MultivariateNormalPrecision(jnp.zeros(3), precision)
        >>> round(float(d.log_prob(jnp.ones(3))), 4)
        -4.7171

        The marginal variances are diag(Λ⁻¹):

        >>> bool(jnp.allclose(d.variance, 0.5 * jnp.ones(3)))
        True

        Draws carry the sample shape in front of the event shape:

        >>> d.sample(jax.random.key(0), (4,)).shape
        (4, 3)
    """

    pytree_data_fields = ("loc", "prec_operator", "solver")

    def __init__(
        self,
        loc: Float[Array, "*batch N"],
        prec_operator: lx.AbstractLinearOperator,
        solver: AbstractSolverStrategy | None = None,
        *,
        validate_args: bool | None = None,
    ) -> None:
        if solver is None:
            solver = AutoSolver()
        self.loc = loc
        self.prec_operator = prec_operator
        self.solver = solver
        event_shape = loc.shape[-1:]
        batch_shape = loc.shape[:-1]
        super().__init__(
            batch_shape=batch_shape,
            event_shape=event_shape,
            validate_args=validate_args,
        )

    @property
    def covariance_operator(self) -> lx.AbstractLinearOperator:
        """The covariance Σ = Λ⁻¹: the lazy `gaussx.inv` of ``prec_operator``."""
        return _inv(self.prec_operator)

    @property
    def precision_operator(self) -> lx.AbstractLinearOperator:
        """The precision Λ (native; the same object as ``prec_operator``)."""
        return self.prec_operator

    def _log_prob_single(self, residual: Float[Array, " N"]) -> Float[Array, ""]:
        """Log-density of one event from its residual r = x − μ.

            log 𝒩(x; μ, Λ⁻¹) = −½ (D_x log 2π − log det Λ + rᵀ Λ r)

        Args:
            residual: Residual r = x − μ of a single event.

        Returns:
            The scalar log 𝒩(x; μ, Λ⁻¹).
        """
        # Λ r
        precision_residual = self.prec_operator.mv(residual)
        # rᵀ Λ r, a full reduction of one event's vector
        mahalanobis = jnp.sum(residual * precision_residual)
        # log det Λ
        logdet = self.solver.logdet(self.prec_operator)
        event_size = self.loc.shape[-1]
        # log 𝒩(x; μ, Λ⁻¹) = −½ (D_x log 2π − log det Λ + rᵀ Λ r)
        return -0.5 * (event_size * _LOG_2PI - logdet + mahalanobis)

    def sample(
        self,
        key: jax.Array | None,
        sample_shape: tuple[int, ...] = (),
    ) -> Float[Array, "*batch N"]:
        """Draw x = μ + L_Λ⁻ᵀ z with z ~ 𝒩(0, I), by a triangular solve.

            x = μ + L_Λ⁻ᵀ z,   z ~ 𝒩(0, I),   Λ = L_Λ L_Λᵀ

        Algorithm:
            1. Draw z ~ 𝒩(0, I) in the parameters' dtype.
            2. Strip tags and scalar multiples, Λ = c Λ₀, so a structured Λ₀
               keeps its structured Cholesky factor L_Λ₀.
            3. Solve L_Λ₀ᵀ x₀ = z and rescale, x − μ = c^(−½) x₀.
            4. For a dense Λ whose Cholesky fails (non-finite draws), use
               the symmetric inverse square root x − μ = Λ^(−½) z instead.
            5. Add the mean μ.

        Args:
            key: PRNG key.
            sample_shape: Leading shape of the draws.

        Returns:
            Draws of shape ``sample_shape + batch_shape + event_shape``.

        Raises:
            ValueError: If ``key`` is ``None``.
        """
        if key is None:
            raise ValueError(
                "PRNG key must be provided to sample from MultivariateNormalPrecision."
            )
        shape = sample_shape + self.batch_shape + self.event_shape
        # Draw in the parameters' dtype: default-float noise meets a float32
        # factor in the solve below, which lineax rejects under x64.
        dtype = jnp.result_type(self.loc, self.prec_operator.in_structure().dtype)
        # z ~ 𝒩(0, I)
        noise = jax.random.normal(key, shape=shape, dtype=dtype)  # type: ignore[arg-type]
        noise_flat = rearrange(noise, "... D -> (...) D")

        # Look through tags and scalar multiples so a structured precision
        # (e.g. 2 * Kronecker) keeps its structured Cholesky factor.
        # Λ = c Λ₀, s = c^(−½)
        precision, scale = _unwrap_scaled(self.prec_operator)
        # L_Λ₀ L_Λ₀ᵀ = Λ₀
        factor = _cholesky(precision)

        def _solve_one(standard_normal):
            if isinstance(factor, SparseCholeskyFactor):
                # A SparseOperator's factor is of P Λ₀ Pᵀ: x₀ = Pᵀ L⁻ᵀ z.
                return factor.solve_lower_transpose(standard_normal)
            # x₀ = L_Λ₀⁻ᵀ z
            return _solve(factor.T, standard_normal)

        # L_Λ₀⁻ᵀ z, one row per draw
        unscaled_flat = jax.vmap(_solve_one)(noise_flat)
        # x − μ = s L_Λ₀⁻ᵀ z
        draws_flat = scale * unscaled_flat
        if isinstance(precision, lx.MatrixLinearOperator):
            # A dense Cholesky that fails numerically (an ill-conditioned or
            # only semi-definite precision) gives non-finite draws; take the
            # dense symmetric inverse square root then. Dense precisions only:
            # lax.cond stages both branches under jit, and a dense branch
            # would put D_x × D_x buffers into every structured or sparse
            # sample.
            structured = draws_flat
            draws_flat = jax.lax.cond(
                jnp.all(jnp.isfinite(structured)),
                lambda: structured,
                lambda: _dense_precision_draws(self.prec_operator, noise_flat),
            )
        centred = _reshape_samples(draws_flat, shape[:-1])
        # x = μ + (x − μ)
        return self.loc + centred

    @lazy_property
    def variance(self) -> Float[Array, "*batch N"]:
        """Marginal variances diag(Λ⁻¹), broadcast over the batch shape.

        The exact structured paths of `gaussx.diag_inv` (e.g. the O(N d³)
        selected inverse of a `gaussx.BlockTriDiag`) apply; only an operator
        with none of them densifies (gh-360).

        Returns:
            The variances diag(Λ⁻¹), one per event entry and batch element.
        """
        # diag(Λ⁻¹), structured
        variance = _diag_inv_structured(
            self.prec_operator, pinv=False, num_probes=30, key=None, solver=None
        )
        if variance is None:
            # diag(Λ⁻¹) of the lazy inverse
            variance = _diag(_inv(self.prec_operator))
        return jnp.broadcast_to(variance, self.batch_shape + self.event_shape)

    def entropy(self) -> Float[Array, "*batch"]:
        """Entropy ℍ[𝒩(μ, Λ⁻¹)], one entry per batch element.

            ℍ[𝒩(μ, Λ⁻¹)] = ½ (D_x (1 + log 2π) − log det Λ)

        Returns:
            The entropy, broadcast over the batch shape.
        """
        event_size = self.loc.shape[-1]
        # log det Λ
        logdet = self.solver.logdet(self.prec_operator)
        # ℍ[𝒩(μ, Λ⁻¹)] = ½ (D_x (1 + log 2π) − log det Λ)
        entropy = 0.5 * (event_size * (1.0 + _LOG_2PI) - logdet)
        # One entry per batch element, as numpyro's contract requires.
        return jnp.broadcast_to(entropy, self.batch_shape)

covariance_operator: lx.AbstractLinearOperator property

The covariance Σ = Λ⁻¹: the lazy gaussx.inv of prec_operator.

precision_operator: lx.AbstractLinearOperator property

The precision Λ (native; the same object as prec_operator).

sample(key: jax.Array | None, sample_shape: tuple[int, ...] = ()) -> Float[Array, '*batch N']

Draw x = μ + L_Λ⁻ᵀ z with z ~ 𝒩(0, I), by a triangular solve.

x = μ + L_Λ⁻ᵀ z,   z ~ 𝒩(0, I),   Λ = L_Λ L_Λᵀ
Algorithm
  1. Draw z ~ 𝒩(0, I) in the parameters' dtype.
  2. Strip tags and scalar multiples, Λ = c Λ₀, so a structured Λ₀ keeps its structured Cholesky factor L_Λ₀.
  3. Solve L_Λ₀ᵀ x₀ = z and rescale, x − μ = c^(−½) x₀.
  4. For a dense Λ whose Cholesky fails (non-finite draws), use the symmetric inverse square root x − μ = Λ^(−½) z instead.
  5. Add the mean μ.

Parameters:

Name Type Description Default
key Array | None

PRNG key.

required
sample_shape tuple[int, ...]

Leading shape of the draws.

()

Returns:

Type Description
Float[Array, '*batch N']

Draws of shape sample_shape + batch_shape + event_shape.

Raises:

Type Description
ValueError

If key is None.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_prec.py
def sample(
    self,
    key: jax.Array | None,
    sample_shape: tuple[int, ...] = (),
) -> Float[Array, "*batch N"]:
    """Draw x = μ + L_Λ⁻ᵀ z with z ~ 𝒩(0, I), by a triangular solve.

        x = μ + L_Λ⁻ᵀ z,   z ~ 𝒩(0, I),   Λ = L_Λ L_Λᵀ

    Algorithm:
        1. Draw z ~ 𝒩(0, I) in the parameters' dtype.
        2. Strip tags and scalar multiples, Λ = c Λ₀, so a structured Λ₀
           keeps its structured Cholesky factor L_Λ₀.
        3. Solve L_Λ₀ᵀ x₀ = z and rescale, x − μ = c^(−½) x₀.
        4. For a dense Λ whose Cholesky fails (non-finite draws), use
           the symmetric inverse square root x − μ = Λ^(−½) z instead.
        5. Add the mean μ.

    Args:
        key: PRNG key.
        sample_shape: Leading shape of the draws.

    Returns:
        Draws of shape ``sample_shape + batch_shape + event_shape``.

    Raises:
        ValueError: If ``key`` is ``None``.
    """
    if key is None:
        raise ValueError(
            "PRNG key must be provided to sample from MultivariateNormalPrecision."
        )
    shape = sample_shape + self.batch_shape + self.event_shape
    # Draw in the parameters' dtype: default-float noise meets a float32
    # factor in the solve below, which lineax rejects under x64.
    dtype = jnp.result_type(self.loc, self.prec_operator.in_structure().dtype)
    # z ~ 𝒩(0, I)
    noise = jax.random.normal(key, shape=shape, dtype=dtype)  # type: ignore[arg-type]
    noise_flat = rearrange(noise, "... D -> (...) D")

    # Look through tags and scalar multiples so a structured precision
    # (e.g. 2 * Kronecker) keeps its structured Cholesky factor.
    # Λ = c Λ₀, s = c^(−½)
    precision, scale = _unwrap_scaled(self.prec_operator)
    # L_Λ₀ L_Λ₀ᵀ = Λ₀
    factor = _cholesky(precision)

    def _solve_one(standard_normal):
        if isinstance(factor, SparseCholeskyFactor):
            # A SparseOperator's factor is of P Λ₀ Pᵀ: x₀ = Pᵀ L⁻ᵀ z.
            return factor.solve_lower_transpose(standard_normal)
        # x₀ = L_Λ₀⁻ᵀ z
        return _solve(factor.T, standard_normal)

    # L_Λ₀⁻ᵀ z, one row per draw
    unscaled_flat = jax.vmap(_solve_one)(noise_flat)
    # x − μ = s L_Λ₀⁻ᵀ z
    draws_flat = scale * unscaled_flat
    if isinstance(precision, lx.MatrixLinearOperator):
        # A dense Cholesky that fails numerically (an ill-conditioned or
        # only semi-definite precision) gives non-finite draws; take the
        # dense symmetric inverse square root then. Dense precisions only:
        # lax.cond stages both branches under jit, and a dense branch
        # would put D_x × D_x buffers into every structured or sparse
        # sample.
        structured = draws_flat
        draws_flat = jax.lax.cond(
            jnp.all(jnp.isfinite(structured)),
            lambda: structured,
            lambda: _dense_precision_draws(self.prec_operator, noise_flat),
        )
    centred = _reshape_samples(draws_flat, shape[:-1])
    # x = μ + (x − μ)
    return self.loc + centred

variance() -> Float[Array, '*batch N']

Marginal variances diag(Λ⁻¹), broadcast over the batch shape.

The exact structured paths of gaussx.diag_inv (e.g. the O(N d³) selected inverse of a gaussx.BlockTriDiag) apply; only an operator with none of them densifies (gh-360).

Returns:

Type Description
Float[Array, '*batch N']

The variances diag(Λ⁻¹), one per event entry and batch element.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_prec.py
@lazy_property
def variance(self) -> Float[Array, "*batch N"]:
    """Marginal variances diag(Λ⁻¹), broadcast over the batch shape.

    The exact structured paths of `gaussx.diag_inv` (e.g. the O(N d³)
    selected inverse of a `gaussx.BlockTriDiag`) apply; only an operator
    with none of them densifies (gh-360).

    Returns:
        The variances diag(Λ⁻¹), one per event entry and batch element.
    """
    # diag(Λ⁻¹), structured
    variance = _diag_inv_structured(
        self.prec_operator, pinv=False, num_probes=30, key=None, solver=None
    )
    if variance is None:
        # diag(Λ⁻¹) of the lazy inverse
        variance = _diag(_inv(self.prec_operator))
    return jnp.broadcast_to(variance, self.batch_shape + self.event_shape)

entropy() -> Float[Array, '*batch']

Entropy ℍ[𝒩(μ, Λ⁻¹)], one entry per batch element.

ℍ[𝒩(μ, Λ⁻¹)] = ½ (D_x (1 + log 2π) − log det Λ)

Returns:

Type Description
Float[Array, '*batch']

The entropy, broadcast over the batch shape.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_mvn_prec.py
def entropy(self) -> Float[Array, "*batch"]:
    """Entropy ℍ[𝒩(μ, Λ⁻¹)], one entry per batch element.

        ℍ[𝒩(μ, Λ⁻¹)] = ½ (D_x (1 + log 2π) − log det Λ)

    Returns:
        The entropy, broadcast over the batch shape.
    """
    event_size = self.loc.shape[-1]
    # log det Λ
    logdet = self.solver.logdet(self.prec_operator)
    # ℍ[𝒩(μ, Λ⁻¹)] = ½ (D_x (1 + log 2π) − log det Λ)
    entropy = 0.5 * (event_size * (1.0 + _LOG_2PI) - logdet)
    # One entry per batch element, as numpyro's contract requires.
    return jnp.broadcast_to(entropy, self.batch_shape)

State-space models

LGSSM is a density over the observations with the states marginalised by the Kalman filter; MarkovGaussian is the density over the states themselves.

LGSSM

Bases: Distribution

Linear-Gaussian state-space model as a density over observations (T, M).

x_t = F x_t−1 + η_t,   η_t ~ 𝒩(0, Σ_η)
y_t = H x_t + ε_t,     ε_t ~ 𝒩(0, Σ_ε)

with x₀ ~ 𝒩(μ_x,0, Σ_x,0), a state x_t of length D_x, an observation y_t of length D_y and t = 1, …, T. log_prob is the Kalman marginal likelihood log p(y_1:T), delegated to gaussx.kalman_filter; sample is ancestral forward simulation. event_shape is (T, M), so log_prob returns a scalar and no .to_event() wrapping is needed.

Requires the numpyro optional extra (pip install "gaussx[numpyro]").

A, H, Q and R each accept a dense array or a lineax.AbstractLinearOperator, exactly matching gaussx.kalman_filter's contract. Structured Σ_η and Σ_ε keep their structure through the Cholesky in sample, H through the sandwich in variance, and F and H apply via structural matvec rather than a dense matmul. μ_x,0 and Σ_x,0 are dense, as they are for gaussx.kalman_filter.

Parameters:

Name Type Description Default
A _Transition

Transition F, the same for every step.

required
H _Emission

Observation operator H.

required
Q _StateCov

Model-noise covariance Σ_η.

required
R _ObsCov

Observation-noise covariance Σ_ε.

required
m0 Float[Array, ' N']

Prior mean μ_x,0 of the initial state x₀.

required
P0 Float[Array, 'N N']

Prior covariance Σ_x,0 of x₀.

required
n_steps int

Number of steps T.

required
validate_args bool | None

Whether to validate input arguments.

None

Examples:

Ten steps of a two-dimensional state, observed in full:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gaussx import LGSSM
>>> model = 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=10,
... )
>>> y = model.sample(jr.key(0))
>>> y.shape, model.log_prob(y).shape
((10, 2), ())

The marginal moments have the event shape:

>>> model.mean.shape, model.variance.shape
((10, 2), (10, 2))

A diagonal operator Σ_η gives the same density as its dense matrix:

>>> import lineax as lx
>>> structured = LGSSM(
...     0.9 * jnp.eye(2),
...     jnp.eye(2),
...     lx.DiagonalLinearOperator(0.1 * jnp.ones(2)),
...     0.2 * jnp.eye(2),
...     jnp.zeros(2),
...     jnp.eye(2),
...     n_steps=10,
... )
>>> bool(jnp.allclose(structured.log_prob(y), model.log_prob(y)))
True
Notes

To use as a normalizing-flow base, wrap with pyrox_flows.NumpyroBase; no bespoke adapter is required.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
class LGSSM(dist.Distribution):
    """Linear-Gaussian state-space model as a density over observations ``(T, M)``.

        x_t = F x_t−1 + η_t,   η_t ~ 𝒩(0, Σ_η)
        y_t = H x_t + ε_t,     ε_t ~ 𝒩(0, Σ_ε)

    with x₀ ~ 𝒩(μ_x,0, Σ_x,0), a state x_t of length D_x, an observation
    y_t of length D_y and t = 1, …, T. ``log_prob`` is the Kalman marginal
    likelihood log p(y_1:T), delegated to `gaussx.kalman_filter`; ``sample``
    is ancestral forward simulation. ``event_shape`` is ``(T, M)``, so
    ``log_prob`` returns a scalar and no ``.to_event()`` wrapping is needed.

    Requires the ``numpyro`` optional extra
    (``pip install "gaussx[numpyro]"``).

    ``A``, ``H``, ``Q`` and ``R`` each accept a dense array *or* a
    `lineax.AbstractLinearOperator`, exactly matching
    `gaussx.kalman_filter`'s contract. Structured Σ_η and Σ_ε keep their
    structure through the Cholesky in ``sample``, H through the sandwich in
    ``variance``, and F and H apply via structural matvec rather than a
    dense matmul. μ_x,0 and Σ_x,0 are dense, as they are for
    `gaussx.kalman_filter`.

    Args:
        A: Transition F, the same for every step.
        H: Observation operator H.
        Q: Model-noise covariance Σ_η.
        R: Observation-noise covariance Σ_ε.
        m0: Prior mean μ_x,0 of the initial state x₀.
        P0: Prior covariance Σ_x,0 of x₀.
        n_steps: Number of steps T.
        validate_args: Whether to validate input arguments.

    Examples:
        Ten steps of a two-dimensional state, observed in full:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gaussx import LGSSM
        >>> model = 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=10,
        ... )
        >>> y = model.sample(jr.key(0))
        >>> y.shape, model.log_prob(y).shape
        ((10, 2), ())

        The marginal moments have the event shape:

        >>> model.mean.shape, model.variance.shape
        ((10, 2), (10, 2))

        A diagonal operator Σ_η gives the same density as its dense matrix:

        >>> import lineax as lx
        >>> structured = LGSSM(
        ...     0.9 * jnp.eye(2),
        ...     jnp.eye(2),
        ...     lx.DiagonalLinearOperator(0.1 * jnp.ones(2)),
        ...     0.2 * jnp.eye(2),
        ...     jnp.zeros(2),
        ...     jnp.eye(2),
        ...     n_steps=10,
        ... )
        >>> bool(jnp.allclose(structured.log_prob(y), model.log_prob(y)))
        True

    Notes:
        To use as a normalizing-flow base, wrap with
        ``pyrox_flows.NumpyroBase``; no bespoke adapter is required.
    """

    arg_constraints = {}  # noqa: RUF012
    support = dist.constraints.real_matrix
    reparametrized_params = ["A", "H", "Q", "R", "m0", "P0"]  # noqa: RUF012
    pytree_data_fields = ("A", "H", "Q", "R", "m0", "P0")

    def __init__(
        self,
        A: _Transition,
        H: _Emission,
        Q: _StateCov,
        R: _ObsCov,
        m0: Float[Array, " N"],
        P0: Float[Array, "N N"],
        n_steps: int,
        *,
        validate_args: bool | None = None,
    ) -> None:
        self.A = A
        self.H = H
        self.Q = Q
        self.R = R
        self.m0 = m0
        self.P0 = P0
        super().__init__(
            batch_shape=(),
            event_shape=(n_steps, _out_size(H)),
            validate_args=validate_args,
        )

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

    @property
    def _obs_mask(self) -> Bool[Array, "T M"] | None:
        """Observation mask handed to `gaussx.kalman_filter`."""
        return None

    def _log_prob_single(self, value: Float[Array, "T M"]) -> Float[Array, ""]:
        """Kalman marginal log-likelihood log p(y_1:T) of one series.

        Args:
            value: Observations y_1:T, one row per step.

        Returns:
            The scalar log p(y_1:T).
        """
        filter_state = kalman_filter(
            self.A,
            self.H,
            self.Q,
            self.R,
            value,
            self.m0,
            self.P0,
            mask=self._obs_mask,
        )
        return filter_state.log_likelihood

    @validate_sample
    def log_prob(self, value: Float[Array, "*batch T M"]) -> Float[Array, "*batch"]:
        """Kalman marginal log-likelihood log p(y_1:T) of each series.

        Args:
            value: Observations y_1:T, with leading batch axes.

        Returns:
            One log-likelihood per series.
        """
        leading_shape = value.shape[:-2]
        value_flat = rearrange(value, "... step obs -> (...) step obs")
        log_prob_flat = jax.vmap(self._log_prob_single)(value_flat)
        return _reshape_batch(log_prob_flat, leading_shape)

    def _sample_single(self, key: jax.Array) -> Float[Array, "T M"]:
        """One ancestral forward simulation of the series y_1:T.

            x₀ = μ_x,0 + L_x,0 z₀
            x_t = F x_t−1 + L_η z_η,t
            y_t = H x_t + L_ε z_ε,t

        Cholesky factors go through the structural `gaussx.cholesky`
        primitive, so a Kronecker, block-diagonal or diagonal covariance is
        never materialised.

        Args:
            key: PRNG key.

        Returns:
            The observations y_1:T, one row per step.
        """
        state_size = self.m0.shape[0]
        obs_size = self.event_shape[1]
        prior_key, model_noise_key, obs_noise_key = jax.random.split(key, 3)
        # L_x,0 L_x,0ᵀ = Σ_x,0
        prior_factor = _cholesky(_psd(self.P0))
        # L_η L_ηᵀ = Σ_η
        model_noise_factor = _cholesky(_psd(self.Q))
        # L_ε L_εᵀ = Σ_ε
        obs_noise_factor = _cholesky(_psd(self.R))

        # Each noise term is drawn in its factor's dtype, not JAX's default
        # float, so a float32 model stays float32 under x64.
        # z₀ ~ 𝒩(0, I)
        prior_noise = jax.random.normal(
            prior_key, (state_size,), dtype=prior_factor.in_structure().dtype
        )
        # L_x,0 z₀
        prior_deviation = prior_factor.mv(prior_noise)
        # x₀ = μ_x,0 + L_x,0 z₀
        initial_state = self.m0 + prior_deviation
        # z_η,t ~ 𝒩(0, I), one per step
        model_noise_draws = jax.random.normal(
            model_noise_key,
            (self.n_steps, state_size),
            dtype=model_noise_factor.in_structure().dtype,
        )
        # z_ε,t ~ 𝒩(0, I), one per step
        obs_noise_draws = jax.random.normal(
            obs_noise_key,
            (self.n_steps, obs_size),
            dtype=obs_noise_factor.in_structure().dtype,
        )

        def step(state, noise):
            model_noise, obs_noise = noise
            # F x_t−1
            propagated = _matvec(self.A, state)
            # L_η z_η,t
            model_deviation = model_noise_factor.mv(model_noise)
            # x_t = F x_t−1 + L_η z_η,t
            state_next = propagated + model_deviation
            # H x_t
            predicted_obs = _matvec(self.H, state_next)
            # L_ε z_ε,t
            obs_deviation = obs_noise_factor.mv(obs_noise)
            # y_t = H x_t + L_ε z_ε,t
            obs = predicted_obs + obs_deviation
            return state_next, obs

        _, observations = jax.lax.scan(
            step, initial_state, (model_noise_draws, obs_noise_draws)
        )
        return observations

    def sample(
        self,
        key: jax.Array | None,
        sample_shape: tuple[int, ...] = (),
    ) -> Float[Array, "*sample T M"]:
        """Ancestral draws of the observation series y_1:T.

        Args:
            key: PRNG key.
            sample_shape: Leading shape of the draws.

        Returns:
            Draws of shape ``sample_shape + (T, M)``.

        Raises:
            ValueError: If ``key`` is ``None``.
        """
        if key is None:
            raise ValueError("PRNG key must be provided to sample from LGSSM.")
        num_draws = math.prod(sample_shape) if sample_shape else 1
        keys = jax.random.split(key, num_draws)
        samples_flat = jax.vmap(self._sample_single)(keys)
        return _reshape_series(samples_flat, sample_shape)

    @lazy_property
    def mean(self) -> Float[Array, "T M"]:
        """Marginal mean μ_y,t = H Fᵗ μ_x,0 of each observation."""

        def step(state_mean, _):
            # μ_x,t = F μ_x,t−1
            state_mean_next = _matvec(self.A, state_mean)
            # μ_y,t = H μ_x,t
            obs_mean = _matvec(self.H, state_mean_next)
            return state_mean_next, obs_mean

        _, obs_means = jax.lax.scan(step, self.m0, None, length=self.n_steps)
        return obs_means

    @lazy_property
    def variance(self) -> Float[Array, "T M"]:
        """Marginal variances diag(Σ_y,t) of each observation.

            diag(Σ_y,t) = diag(H Σ_x,t Hᵀ) + diag(Σ_ε)

        The state recursion Σ_x,t = F Σ_x,t−1 Fᵀ + Σ_η runs on a dense Σ_x,t,
        the evolving quantity, so no input structure survives it. The
        observation step avoids forming H Σ_x,t Hᵀ: operators go through
        `gaussx.sandwich` and `gaussx.diag`, arrays contract straight to
        the diagonal.
        """
        transition = _materialise(self.A)
        model_noise_covariance = _materialise(self.Q)
        # diag(Σ_ε)
        obs_noise_variance = _diag(_as_operator(self.R))
        obs_operator = self.H if isinstance(self.H, lx.AbstractLinearOperator) else None

        def step(state_covariance, _):
            # F Σ_x,t−1
            transition_covariance = einsum(
                transition, state_covariance, "next prev, prev col -> next col"
            )
            # F Σ_x,t−1 Fᵀ
            propagated = einsum(
                transition_covariance, transition, "next col, other col -> next other"
            )
            # Σ_x,t = F Σ_x,t−1 Fᵀ + Σ_η
            state_covariance_next = propagated + model_noise_covariance
            if obs_operator is not None:
                # H Σ_x,t Hᵀ, structure-preserving
                obs_projection = sandwich(obs_operator, _psd(state_covariance_next))
                # diag(H Σ_x,t Hᵀ)
                projected_variance = _diag(obs_projection)
            else:
                # diag(H Σ_x,t Hᵀ), one three-operand contraction
                projected_variance = einsum(
                    self.H,
                    state_covariance_next,
                    self.H,
                    "obs state, state col, obs col -> obs",
                )
            # diag(Σ_y,t) = diag(H Σ_x,t Hᵀ) + diag(Σ_ε)
            obs_variance = projected_variance + obs_noise_variance
            return state_covariance_next, obs_variance

        _, obs_variances = jax.lax.scan(step, self.P0, None, length=self.n_steps)
        return obs_variances

n_steps: int property

Number of steps T.

log_prob(value: Float[Array, '*batch T M']) -> Float[Array, '*batch']

Kalman marginal log-likelihood log p(y_1:T) of each series.

Parameters:

Name Type Description Default
value Float[Array, '*batch T M']

Observations y_1:T, with leading batch axes.

required

Returns:

Type Description
Float[Array, '*batch']

One log-likelihood per series.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
@validate_sample
def log_prob(self, value: Float[Array, "*batch T M"]) -> Float[Array, "*batch"]:
    """Kalman marginal log-likelihood log p(y_1:T) of each series.

    Args:
        value: Observations y_1:T, with leading batch axes.

    Returns:
        One log-likelihood per series.
    """
    leading_shape = value.shape[:-2]
    value_flat = rearrange(value, "... step obs -> (...) step obs")
    log_prob_flat = jax.vmap(self._log_prob_single)(value_flat)
    return _reshape_batch(log_prob_flat, leading_shape)

sample(key: jax.Array | None, sample_shape: tuple[int, ...] = ()) -> Float[Array, '*sample T M']

Ancestral draws of the observation series y_1:T.

Parameters:

Name Type Description Default
key Array | None

PRNG key.

required
sample_shape tuple[int, ...]

Leading shape of the draws.

()

Returns:

Type Description
Float[Array, '*sample T M']

Draws of shape sample_shape + (T, M).

Raises:

Type Description
ValueError

If key is None.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
def sample(
    self,
    key: jax.Array | None,
    sample_shape: tuple[int, ...] = (),
) -> Float[Array, "*sample T M"]:
    """Ancestral draws of the observation series y_1:T.

    Args:
        key: PRNG key.
        sample_shape: Leading shape of the draws.

    Returns:
        Draws of shape ``sample_shape + (T, M)``.

    Raises:
        ValueError: If ``key`` is ``None``.
    """
    if key is None:
        raise ValueError("PRNG key must be provided to sample from LGSSM.")
    num_draws = math.prod(sample_shape) if sample_shape else 1
    keys = jax.random.split(key, num_draws)
    samples_flat = jax.vmap(self._sample_single)(keys)
    return _reshape_series(samples_flat, sample_shape)

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

Marginal mean μ_y,t = H Fᵗ μ_x,0 of each observation.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
@lazy_property
def mean(self) -> Float[Array, "T M"]:
    """Marginal mean μ_y,t = H Fᵗ μ_x,0 of each observation."""

    def step(state_mean, _):
        # μ_x,t = F μ_x,t−1
        state_mean_next = _matvec(self.A, state_mean)
        # μ_y,t = H μ_x,t
        obs_mean = _matvec(self.H, state_mean_next)
        return state_mean_next, obs_mean

    _, obs_means = jax.lax.scan(step, self.m0, None, length=self.n_steps)
    return obs_means

variance() -> Float[Array, 'T M']

Marginal variances diag(Σ_y,t) of each observation.

diag(Σ_y,t) = diag(H Σ_x,t Hᵀ) + diag(Σ_ε)

The state recursion Σ_x,t = F Σ_x,t−1 Fᵀ + Σ_η runs on a dense Σ_x,t, the evolving quantity, so no input structure survives it. The observation step avoids forming H Σ_x,t Hᵀ: operators go through gaussx.sandwich and gaussx.diag, arrays contract straight to the diagonal.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
@lazy_property
def variance(self) -> Float[Array, "T M"]:
    """Marginal variances diag(Σ_y,t) of each observation.

        diag(Σ_y,t) = diag(H Σ_x,t Hᵀ) + diag(Σ_ε)

    The state recursion Σ_x,t = F Σ_x,t−1 Fᵀ + Σ_η runs on a dense Σ_x,t,
    the evolving quantity, so no input structure survives it. The
    observation step avoids forming H Σ_x,t Hᵀ: operators go through
    `gaussx.sandwich` and `gaussx.diag`, arrays contract straight to
    the diagonal.
    """
    transition = _materialise(self.A)
    model_noise_covariance = _materialise(self.Q)
    # diag(Σ_ε)
    obs_noise_variance = _diag(_as_operator(self.R))
    obs_operator = self.H if isinstance(self.H, lx.AbstractLinearOperator) else None

    def step(state_covariance, _):
        # F Σ_x,t−1
        transition_covariance = einsum(
            transition, state_covariance, "next prev, prev col -> next col"
        )
        # F Σ_x,t−1 Fᵀ
        propagated = einsum(
            transition_covariance, transition, "next col, other col -> next other"
        )
        # Σ_x,t = F Σ_x,t−1 Fᵀ + Σ_η
        state_covariance_next = propagated + model_noise_covariance
        if obs_operator is not None:
            # H Σ_x,t Hᵀ, structure-preserving
            obs_projection = sandwich(obs_operator, _psd(state_covariance_next))
            # diag(H Σ_x,t Hᵀ)
            projected_variance = _diag(obs_projection)
        else:
            # diag(H Σ_x,t Hᵀ), one three-operand contraction
            projected_variance = einsum(
                self.H,
                state_covariance_next,
                self.H,
                "obs state, state col, obs col -> obs",
            )
        # diag(Σ_y,t) = diag(H Σ_x,t Hᵀ) + diag(Σ_ε)
        obs_variance = projected_variance + obs_noise_variance
        return state_covariance_next, obs_variance

    _, obs_variances = jax.lax.scan(step, self.P0, None, length=self.n_steps)
    return obs_variances

MaskedLGSSM

Bases: LGSSM

LGSSM whose log_prob marginalises unobserved channels exactly.

log p(y_obs) = log ∫ p(y_obs, y_miss) dy_miss

Takes a (T, M) boolean mask at construction. log_prob returns the exact marginal log p(y_obs), not a bound: the conditional p(y_miss ∣ y_obs) is closed-form Gaussian, so dropping entries costs nothing in exactness. Masked entries of value are never read and may be NaN.

sample is inherited unchanged and simulates the complete (T, M) series: the mask governs which entries the density scores, not which are generated.

Parameters:

Name Type Description Default
A _Transition

Transition F, the same for every step.

required
H _Emission

Observation operator H.

required
Q _StateCov

Model-noise covariance Σ_η.

required
R _ObsCov

Observation-noise covariance Σ_ε.

required
m0 Float[Array, ' N']

Prior mean μ_x,0 of the initial state x₀.

required
P0 Float[Array, 'N N']

Prior covariance Σ_x,0 of x₀.

required
n_steps int

Number of steps T.

required
obs_mask Bool[Array, 'T M']

Observation mask, one row per step. True marks an observed channel. An all-False row leaves the state at its predicted value and contributes nothing. Named obs_mask so it does not shadow numpyro's inherited Distribution.mask() method.

required
validate_args bool | None

Whether to validate input arguments.

None

Raises:

Type Description
ValueError

If obs_mask does not have shape (n_steps, M).

Examples:

Score a partially observed series:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gaussx import LGSSM, MaskedLGSSM
>>> params = (
...     0.9 * jnp.eye(2),
...     jnp.eye(2),
...     0.1 * jnp.eye(2),
...     0.2 * jnp.eye(2),
...     jnp.zeros(2),
...     jnp.eye(2),
... )
>>> mask = jr.bernoulli(jr.key(0), 0.7, (10, 2))
>>> masked = MaskedLGSSM(*params, n_steps=10, obs_mask=mask)
>>> masked.log_prob(masked.sample(jr.key(1))).shape
()

An all-True mask gives the LGSSM density:

>>> y = masked.sample(jr.key(2))
>>> full = MaskedLGSSM(*params, n_steps=10, obs_mask=jnp.ones((10, 2)))
>>> plain = LGSSM(*params, n_steps=10)
>>> bool(jnp.allclose(full.log_prob(y), plain.log_prob(y)))
True
Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
class MaskedLGSSM(LGSSM):
    """`LGSSM` whose ``log_prob`` marginalises unobserved channels exactly.

        log p(y_obs) = log ∫ p(y_obs, y_miss) dy_miss

    Takes a ``(T, M)`` boolean mask at construction. ``log_prob`` returns
    the exact marginal log p(y_obs), not a bound: the conditional
    p(y_miss ∣ y_obs) is closed-form Gaussian, so dropping entries costs
    nothing in exactness. Masked entries of ``value`` are never read and
    may be ``NaN``.

    ``sample`` is inherited unchanged and simulates the **complete**
    ``(T, M)`` series: the mask governs which entries the density scores,
    not which are generated.

    Args:
        A: Transition F, the same for every step.
        H: Observation operator H.
        Q: Model-noise covariance Σ_η.
        R: Observation-noise covariance Σ_ε.
        m0: Prior mean μ_x,0 of the initial state x₀.
        P0: Prior covariance Σ_x,0 of x₀.
        n_steps: Number of steps T.
        obs_mask: Observation mask, one row per step. ``True`` marks an
            observed channel. An all-``False`` row leaves the state at
            its predicted value and contributes nothing. Named
            ``obs_mask`` so it does not shadow numpyro's inherited
            ``Distribution.mask()`` method.
        validate_args: Whether to validate input arguments.

    Raises:
        ValueError: If ``obs_mask`` does not have shape ``(n_steps, M)``.

    Examples:
        Score a partially observed series:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gaussx import LGSSM, MaskedLGSSM
        >>> params = (
        ...     0.9 * jnp.eye(2),
        ...     jnp.eye(2),
        ...     0.1 * jnp.eye(2),
        ...     0.2 * jnp.eye(2),
        ...     jnp.zeros(2),
        ...     jnp.eye(2),
        ... )
        >>> mask = jr.bernoulli(jr.key(0), 0.7, (10, 2))
        >>> masked = MaskedLGSSM(*params, n_steps=10, obs_mask=mask)
        >>> masked.log_prob(masked.sample(jr.key(1))).shape
        ()

        An all-``True`` mask gives the `LGSSM` density:

        >>> y = masked.sample(jr.key(2))
        >>> full = MaskedLGSSM(*params, n_steps=10, obs_mask=jnp.ones((10, 2)))
        >>> plain = LGSSM(*params, n_steps=10)
        >>> bool(jnp.allclose(full.log_prob(y), plain.log_prob(y)))
        True
    """

    pytree_data_fields = ("A", "H", "Q", "R", "m0", "P0", "obs_mask")

    # Named ``obs_mask`` rather than ``mask``: ``numpyro.distributions.
    # Distribution.mask`` is an inherited *method* returning a
    # ``MaskedDistribution`` (it backs ``numpyro.sample(..., obs_mask=)``),
    # and shadowing it with an array would silently break that API on
    # this subclass alone.
    obs_mask: Bool[Array, "T M"]

    def __init__(
        self,
        A: _Transition,
        H: _Emission,
        Q: _StateCov,
        R: _ObsCov,
        m0: Float[Array, " N"],
        P0: Float[Array, "N N"],
        n_steps: int,
        obs_mask: Bool[Array, "T M"],
        *,
        validate_args: bool | None = None,
    ) -> None:
        obs_mask = jnp.asarray(obs_mask, dtype=bool)
        expected = (n_steps, _out_size(H))
        if obs_mask.shape != expected:
            raise ValueError(
                f"obs_mask must have shape {expected}; got shape {obs_mask.shape}."
            )
        self.obs_mask = obs_mask
        super().__init__(A, H, Q, R, m0, P0, n_steps, validate_args=validate_args)

    @property
    def _obs_mask(self) -> Bool[Array, "T M"]:
        """Observation mask handed to `gaussx.kalman_filter`."""
        return self.obs_mask

    def _validate_sample(self, value: ArrayLike) -> ArrayLike:
        # Masked entries are never read and may be NaN, so check the support
        # on the observed entries only. numpyro >= 0.22 validates by default,
        # and a NaN anywhere would otherwise turn log_prob into -inf.
        return super()._validate_sample(jnp.where(self.obs_mask, value, 0.0))

LGSSMFactory

Bases: Module

Callable obs_mask -> MaskedLGSSM, for conditional use.

obs_mask ↦ MaskedLGSSM(F, H, Σ_η, Σ_ε, μ_x,0, Σ_x,0, T, obs_mask)

An equinox.Module rather than a closure so the state-space parameters stay visible to equinox.filter_grad when passed as pyrox_flows.NumpyroBase(dist_factory=...).

Attributes:

Name Type Description
A _Transition

Transition F, the same for every step.

H _Emission

Observation operator H.

Q _StateCov

Model-noise covariance Σ_η.

R _ObsCov

Observation-noise covariance Σ_ε.

m0 Float[Array, ' N']

Prior mean μ_x,0 of the initial state x₀.

P0 Float[Array, 'N N']

Prior covariance Σ_x,0 of x₀.

n_steps int

Number of steps T.

Examples:

Build a masked model for one mask:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gaussx import LGSSMFactory
>>> factory = LGSSMFactory(
...     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=10,
... )
>>> model = factory(jr.bernoulli(jr.key(0), 0.7, (10, 2)))
>>> model.event_shape
(10, 2)

The model carries the factory's parameters:

>>> bool(jnp.allclose(model.A, factory.A))
True
Source code in packages/pyrox-gauss/src/pyrox_gauss/_lgssm.py
class LGSSMFactory(eqx.Module):
    """Callable ``obs_mask -> MaskedLGSSM``, for conditional use.

        obs_mask ↦ MaskedLGSSM(F, H, Σ_η, Σ_ε, μ_x,0, Σ_x,0, T, obs_mask)

    An `equinox.Module` rather than a closure so the state-space
    parameters stay visible to `equinox.filter_grad` when passed as
    ``pyrox_flows.NumpyroBase(dist_factory=...)``.

    Attributes:
        A: Transition F, the same for every step.
        H: Observation operator H.
        Q: Model-noise covariance Σ_η.
        R: Observation-noise covariance Σ_ε.
        m0: Prior mean μ_x,0 of the initial state x₀.
        P0: Prior covariance Σ_x,0 of x₀.
        n_steps: Number of steps T.

    Examples:
        Build a masked model for one mask:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gaussx import LGSSMFactory
        >>> factory = LGSSMFactory(
        ...     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=10,
        ... )
        >>> model = factory(jr.bernoulli(jr.key(0), 0.7, (10, 2)))
        >>> model.event_shape
        (10, 2)

        The model carries the factory's parameters:

        >>> bool(jnp.allclose(model.A, factory.A))
        True
    """

    A: _Transition
    H: _Emission
    Q: _StateCov
    R: _ObsCov
    m0: Float[Array, " N"]
    P0: Float[Array, "N N"]
    n_steps: int = eqx.field(static=True)

    def __call__(self, obs_mask: Bool[Array, "T M"]) -> MaskedLGSSM:
        """Build the `MaskedLGSSM` for a given observation mask.

        Args:
            obs_mask: Observation mask, one row per step; ``True`` marks an
                observed channel.

        Returns:
            A `MaskedLGSSM` carrying this factory's parameters.
        """
        return MaskedLGSSM(
            self.A,
            self.H,
            self.Q,
            self.R,
            self.m0,
            self.P0,
            self.n_steps,
            obs_mask,
        )

MarkovGaussian

Bases: Distribution

Gauss-Markov chain over the states x_0:T−1 as a density over (T, d).

x₀ ~ 𝒩(μ_x,0, Σ_x,0)
x_t+1 = F_t x_t + c_t + η_t+1,   η_t+1 ~ 𝒩(0, Σ_η,t+1)

for t = 0, …, T − 2 and states x_t ∈ ℝ^{D_x}. This generative state-space form is the canonical parameterisation; the joint covariance Σ_x of x_0:T−1 has a block-tridiagonal inverse Λ_x. event_shape is (T, d), so log_prob of a trajectory is a scalar and the distribution can be used directly as a NumPyro site: a prior over a latent path, or a structured variational guide. Every view is derived from the state-space parameters on demand:

View Cost Route
marginals, mean, variance O(T D_x³) forward moment propagation
sample, log_prob O(T D_x³) chain factorisation, no joint Cholesky
precision, to_precision_form O(T D_x³) udl_from_ssm_params
from_precision_form O(T D_x³) udl_decomposition
covariance_matrix O(T² D_x³) banded solves against I; small T

Where LGSSM is a density over the observations of a chain with the states marginalised out, this is the density over the states themselves. Requires the numpyro optional extra (pip install "gaussx[numpyro]").

Parameters:

Name Type Description Default
A Float[Array, 'Tm1 d d']

Transition matrices F_t, with A[t] mapping x_t to x_t+1.

required
Q Float[Array, 'Tm1 d d']

Model-noise covariances Σ_η,t+1, with Q[t] driving the step from x_t to x_t+1.

required
mu0 Float[Array, ' d']

Prior mean μ_x,0 of the initial state x₀.

required
P0 Float[Array, 'd d']

Prior covariance Σ_x,0 of x₀.

required
b Float[Array, 'Tm1 d'] | None

Optional transition offsets c_t, with b[t] added in the step from x_t to x_t+1. Defaults to zero.

None
validate_args bool | None

Whether to validate input arguments.

None

Raises:

Type Description
ValueError

If A is not a stack of square matrices, or Q, mu0, P0 or b does not match its shape.

Examples:

A ten-step chain in two dimensions:

>>> import jax
>>> import jax.numpy as jnp
>>> import gaussx
>>> import pyrox_gauss
>>> T, d = 10, 2
>>> A = jnp.broadcast_to(0.9 * jnp.eye(d), (T - 1, d, d))
>>> Q = jnp.broadcast_to(0.1 * jnp.eye(d), (T - 1, d, d))
>>> chain = pyrox_gauss.MarkovGaussian(A, Q, jnp.zeros(d), jnp.eye(d))
>>> xs = chain.sample(jax.random.key(0), (4,))
>>> xs.shape, chain.log_prob(xs).shape
((4, 10, 2), (4,))

The precision form round-trips to the same chain:

>>> mean, precision = chain.to_precision_form()
>>> mean.shape, precision.as_matrix().shape
((20,), (20, 20))
>>> rebuilt = pyrox_gauss.MarkovGaussian.from_precision_form(mean, precision)
>>> bool(jnp.allclose(rebuilt.A, A, atol=1e-4))
True

A single state has no transitions:

>>> single = pyrox_gauss.MarkovGaussian(A[:0], Q[:0], jnp.zeros(d), jnp.eye(d))
>>> single.event_shape, single.cross_covariances().shape
((1, 2), (0, 2, 2))
Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
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
class MarkovGaussian(dist.Distribution):
    """Gauss-Markov chain over the states x_0:T−1 as a density over ``(T, d)``.

        x₀ ~ 𝒩(μ_x,0, Σ_x,0)
        x_t+1 = F_t x_t + c_t + η_t+1,   η_t+1 ~ 𝒩(0, Σ_η,t+1)

    for t = 0, …, T − 2 and states x_t ∈ ℝ^{D_x}. This generative
    state-space form is the canonical parameterisation; the joint
    covariance Σ_x of x_0:T−1 has a block-tridiagonal inverse Λ_x.
    ``event_shape`` is ``(T, d)``, so ``log_prob`` of a trajectory is a
    scalar and the distribution can be used directly as a NumPyro site: a
    prior over a latent path, or a structured variational guide. Every view
    is derived from the state-space parameters on demand:

    | View | Cost | Route |
    |---|---|---|
    | `marginals`, `mean`, `variance` | O(T D_x³) | forward moment propagation |
    | `sample`, `log_prob` | O(T D_x³) | chain factorisation, no joint Cholesky |
    | `precision`, `to_precision_form` | O(T D_x³) | `udl_from_ssm_params` |
    | `from_precision_form` | O(T D_x³) | `udl_decomposition` |
    | `covariance_matrix` | O(T² D_x³) | banded solves against I; small T |

    Where `LGSSM` is a density over the *observations* of a chain with
    the states marginalised out, this is the density over the *states*
    themselves. Requires the ``numpyro`` optional extra
    (``pip install "gaussx[numpyro]"``).

    Args:
        A: Transition matrices F_t, with ``A[t]`` mapping x_t to x_t+1.
        Q: Model-noise covariances Σ_η,t+1, with ``Q[t]`` driving the step
            from x_t to x_t+1.
        mu0: Prior mean μ_x,0 of the initial state x₀.
        P0: Prior covariance Σ_x,0 of x₀.
        b: Optional transition offsets c_t, with ``b[t]`` added in the step
            from x_t to x_t+1. Defaults to zero.
        validate_args: Whether to validate input arguments.

    Raises:
        ValueError: If ``A`` is not a stack of square matrices, or ``Q``,
            ``mu0``, ``P0`` or ``b`` does not match its shape.

    Examples:
        A ten-step chain in two dimensions:

        >>> import jax
        >>> import jax.numpy as jnp
        >>> import gaussx
        >>> import pyrox_gauss
        >>> T, d = 10, 2
        >>> A = jnp.broadcast_to(0.9 * jnp.eye(d), (T - 1, d, d))
        >>> Q = jnp.broadcast_to(0.1 * jnp.eye(d), (T - 1, d, d))
        >>> chain = pyrox_gauss.MarkovGaussian(A, Q, jnp.zeros(d), jnp.eye(d))
        >>> xs = chain.sample(jax.random.key(0), (4,))
        >>> xs.shape, chain.log_prob(xs).shape
        ((4, 10, 2), (4,))

        The precision form round-trips to the same chain:

        >>> mean, precision = chain.to_precision_form()
        >>> mean.shape, precision.as_matrix().shape
        ((20,), (20, 20))
        >>> rebuilt = pyrox_gauss.MarkovGaussian.from_precision_form(mean, precision)
        >>> bool(jnp.allclose(rebuilt.A, A, atol=1e-4))
        True

        A single state has no transitions:

        >>> single = pyrox_gauss.MarkovGaussian(A[:0], Q[:0], jnp.zeros(d), jnp.eye(d))
        >>> single.event_shape, single.cross_covariances().shape
        ((1, 2), (0, 2, 2))
    """

    arg_constraints = {}  # noqa: RUF012
    support = dist.constraints.real_matrix
    reparametrized_params = ["A", "b", "Q", "mu0", "P0"]  # noqa: RUF012
    pytree_data_fields = ("A", "b", "Q", "mu0", "P0")

    def __init__(
        self,
        A: Float[Array, "Tm1 d d"],
        Q: Float[Array, "Tm1 d d"],
        mu0: Float[Array, " d"],
        P0: Float[Array, "d d"],
        *,
        b: Float[Array, "Tm1 d"] | None = None,
        validate_args: bool | None = None,
    ) -> None:
        if A.ndim != 3 or A.shape[1] != A.shape[2]:
            raise ValueError(f"A must have shape (T-1, d, d), got {A.shape}.")
        Tm1, d, _ = A.shape
        if Q.shape != (Tm1, d, d):
            raise ValueError(f"Q must have shape {(Tm1, d, d)}, got {Q.shape}.")
        if mu0.shape != (d,):
            raise ValueError(f"mu0 must have shape {(d,)}, got {mu0.shape}.")
        if P0.shape != (d, d):
            raise ValueError(f"P0 must have shape {(d, d)}, got {P0.shape}.")
        if b is None:
            b = jnp.zeros((Tm1, d), dtype=A.dtype)
        elif b.shape != (Tm1, d):
            raise ValueError(f"b must have shape {(Tm1, d)}, got {b.shape}.")
        self.A = A
        self.b = b
        self.Q = Q
        self.mu0 = mu0
        self.P0 = P0
        super().__init__(
            batch_shape=(),
            event_shape=(Tm1 + 1, d),
            validate_args=validate_args,
        )

    @property
    def horizon(self) -> int:
        """Number of states T in the chain."""
        return self.event_shape[0]

    @property
    def state_dim(self) -> int:
        """State size D_x."""
        return self.event_shape[1]

    # ------------------------------------------------------------------
    # Moment views
    # ------------------------------------------------------------------

    def marginals(self) -> tuple[Float[Array, "T d"], Float[Array, "T d d"]]:
        """Marginal means μ_x,t and covariances Σ_x,t of every state.

            μ_x,t+1 = F_t μ_x,t + c_t
            Σ_x,t+1 = F_t Σ_x,t F_tᵀ + Σ_η,t+1

        Algorithm:
            1. Start from the prior moments μ_x,0 and Σ_x,0.
            2. Push the moments through each transition with a scan.
            3. Prepend the prior moments to the propagated ones.

        Returns:
            Tuple ``(means, covs)`` holding μ_x,t and Σ_x,t for
            t = 0, …, T − 1.
        """

        def _step(carry, inputs):
            mean, covariance = carry
            transition, offset, model_noise_covariance = inputs
            # F_t μ_x,t
            propagated_mean = transition @ mean
            # μ_x,t+1 = F_t μ_x,t + c_t
            mean_next = propagated_mean + offset
            # F_t Σ_x,t F_tᵀ, one three-operand contraction
            propagated_covariance = einsum(
                transition,
                covariance,
                transition,
                "next prev, prev col, other col -> next other",
            )
            # Σ_x,t+1 = F_t Σ_x,t F_tᵀ + Σ_η,t+1
            covariance_next = propagated_covariance + model_noise_covariance
            return (mean_next, covariance_next), (mean_next, covariance_next)

        _, (means_rest, covs_rest) = jax.lax.scan(
            _step, (self.mu0, self.P0), (self.A, self.b, self.Q)
        )
        # μ_x,0 as the first row
        prior_mean_row = rearrange(self.mu0, "state -> 1 state")
        # Σ_x,0 as the first slab
        prior_covariance_slab = rearrange(self.P0, "row col -> 1 row col")
        # μ_x,0:T−1, prior first
        means = jnp.concatenate([prior_mean_row, means_rest])
        # Σ_x,0:T−1, prior first
        covs = jnp.concatenate([prior_covariance_slab, covs_rest])
        return means, covs

    @lazy_property
    def mean(self) -> Float[Array, "T d"]:
        """Marginal means μ_x,t, one row per state."""
        return self.marginals()[0]

    @lazy_property
    def variance(self) -> Float[Array, "T d"]:
        """Marginal variances diag(Σ_x,t), one row per state."""
        _, covs = self.marginals()
        # diag(Σ_x,t)
        return rearrange(covs, "step state state -> step state")

    def cross_covariances(self) -> Float[Array, "Tm1 d d"]:
        """Lag-one cross-covariances Σ_x,t+1,t = Cov[x_t+1, x_t] = F_t Σ_x,t.

        Returns:
            One D_x × D_x block per transition, t = 0, …, T − 2.
        """
        _, covs = self.marginals()
        return self._cross(covs)

    def _cross(self, covs: Float[Array, "T d d"]) -> Float[Array, "Tm1 d d"]:
        """Lag-one cross-covariances Σ_x,t+1,t = F_t Σ_x,t from the marginals.

        Args:
            covs: Marginal covariances Σ_x,t, one per state.

        Returns:
            One block Σ_x,t+1,t per transition.
        """
        if self.A.shape[0] == 0:
            # One step, no transitions: einx cannot contract the empty
            # transition axis (gh-348).
            return self.A
        # Σ_x,t+1,t = F_t Σ_x,t
        return einsum(
            self.A, covs[:-1], "step next prev, step prev col -> step next col"
        )

    def pairwise_marginals(
        self,
    ) -> tuple[Float[Array, "Tm1 two_d"], Float[Array, "Tm1 two_d two_d"]]:
        """Joint Gaussian p(x_t, x_t+1) of each pair of consecutive states.

            p(x_t, x_t+1) = 𝒩([μ_x,t; μ_x,t+1], [[Σ_x,t, Σ_x,t+1,tᵀ],
                                                [Σ_x,t+1,t, Σ_x,t+1]])

        Returns:
            Tuple ``(joint_means, joint_covs)`` with one pair per
            transition, each of length 2 D_x, in the layout of
            `gaussx.pairwise_marginals`.
        """
        means, covs = self.marginals()
        if self.A.shape[0] == 0:
            # One state, no pairs.
            # 2 D_x
            joint_size = 2 * self.state_dim
            return (
                jnp.zeros((0, joint_size), means.dtype),
                jnp.zeros((0, joint_size, joint_size), covs.dtype),
            )
        return pairwise_marginals(means, covs, self._cross(covs))

    @lazy_property
    def covariance_matrix(self) -> Float[Array, "Td Td"]:
        """Dense joint covariance Σ_x = Λ_x⁻¹ of the flattened trajectory.

        Built column by column through `UDLDecomposition.solve`, so it
        costs O(T² D_x³) and is meant for small T (reference checks, dense
        downstream consumers).
        """
        # T D_x
        joint_size = self.horizon * self.state_dim
        identity = jnp.eye(joint_size, dtype=self.A.dtype)
        # Λ_x = U D Uᵀ
        udl = self.udl()
        # Σ_x = Λ_x⁻¹ I, one column at a time
        return jax.vmap(udl.solve, in_axes=1, out_axes=1)(identity)

    # ------------------------------------------------------------------
    # Precision views
    # ------------------------------------------------------------------

    def udl(self) -> UDLDecomposition:
        """The chain's precision, already factorised as Λ_x = U D Uᵀ.

        Returns:
            The `UDLDecomposition` with U_tᵀ = −F_t, D_t = Σ_η,t⁻¹ for
            t ≥ 1 and D_0 = Σ_x,0⁻¹.
        """
        return udl_from_ssm_params(self.A, self.Q, self.P0)

    @property
    def precision(self) -> BlockTriDiag:
        """Joint precision Λ_x = Σ_x⁻¹ as a `BlockTriDiag`.

        Raw Λ_x, not the −½ Λ_x natural-parameter convention of
        `ssm_to_naturals`.
        """
        return self.udl().as_block_tridiag()

    def to_precision_form(self) -> tuple[Float[Array, " Td"], BlockTriDiag]:
        """The chain as its flattened mean and joint precision ``(μ_x, Λ_x)``.

        This is the layout `spingp_posterior` consumes and returns: pass
        ``mean`` as its ``prior_mean`` (it assumes a zero-mean prior
        otherwise) and hand its output to `from_precision_form`. The
        information vector Λ_x μ_x, if needed, is ``precision.mv(mean)``.

        Returns:
            Tuple ``(mean, precision)``: the marginal means μ_x,t
            flattened state by state, and the joint precision Λ_x.
        """
        # μ_x = [μ_x,0; …; μ_x,T−1]
        mean = rearrange(self.mean, "step state -> (step state)")
        return mean, self.precision

    @classmethod
    def from_precision_form(
        cls,
        mean: Float[Array, " Td"] | Float[Array, "T d"],
        precision: BlockTriDiag,
    ) -> MarkovGaussian:
        """Recover the generative chain from its mean and precision.

            F_t = −U_tᵀ,   Σ_η,t+1 = D_t+1⁻¹,   c_t = μ_x,t+1 − F_t μ_x,t

        Round-trips `to_precision_form` exactly (to floating point).

        Algorithm:
            1. Factorise Λ_x = U D Uᵀ with one `udl_decomposition` pass.
            2. Read off F_t, Σ_η,t+1 and Σ_x,0 = D_0⁻¹ with
               `udl_to_ssm_params`.
            3. Recover the offsets c_t from the mean chain.

        Args:
            mean: Marginal means μ_x,t, flattened state by state or one row
                per state.
            precision: Symmetric positive-definite joint precision Λ_x.

        Returns:
            The equivalent `MarkovGaussian`.
        """
        num_blocks, block_size = precision._num_blocks, precision._block_size
        if mean.ndim == 2:
            means = mean
        else:
            # μ_x,t, one row per state
            means = rearrange(
                mean,
                "(step state) -> step state",
                step=num_blocks,
                state=block_size,
            )
        # Λ_x = U D Uᵀ
        udl = udl_decomposition(precision)
        # F_t = −U_tᵀ and the stacked covariances [Σ_x,0; Σ_η,1:T−1]
        transitions, covariances, _ = udl_to_ssm_params(udl)
        if num_blocks == 1:
            # One state, no transitions: einx cannot contract the empty axis.
            offsets = means[1:]
        else:
            # F_t μ_x,t
            propagated_means = einsum(
                transitions,
                means[:-1],
                "step next prev, step prev -> step next",
            )
            # c_t = μ_x,t+1 − F_t μ_x,t
            offsets = means[1:] - propagated_means
        return cls(transitions, covariances[1:], means[0], covariances[0], b=offsets)

    # ------------------------------------------------------------------
    # Density and sampling
    # ------------------------------------------------------------------

    def _chol_factors(self) -> tuple[Float[Array, "d d"], Float[Array, "Tm1 d d"]]:
        """Lower Cholesky factors L_x,0 of Σ_x,0 and L_η,t+1 of each Σ_η,t+1.

        Returns:
            Tuple ``(prior_factor, model_noise_factors)``.
        """
        # L_x,0 L_x,0ᵀ = Σ_x,0
        prior_factor = jnp.linalg.cholesky(self.P0)
        # L_η,t+1 L_η,t+1ᵀ = Σ_η,t+1
        model_noise_factors = jnp.linalg.cholesky(self.Q)
        return prior_factor, model_noise_factors

    def _log_prob_single(self, xs: Float[Array, "T d"]) -> Float[Array, ""]:
        """Log-density of one trajectory by the chain factorisation, O(T D_x³).

            log p(x_0:T−1) = log 𝒩(x₀; μ_x,0, Σ_x,0)
                + ∑_t log 𝒩(x_t+1; F_t x_t + c_t, Σ_η,t+1)

        Args:
            xs: Trajectory x_0:T−1, one row per state.

        Returns:
            The scalar log p(x_0:T−1).
        """
        prior_factor, model_noise_factors = self._chol_factors()
        # x₀ − μ_x,0
        prior_residual = xs[0] - self.mu0
        # log 𝒩(x₀; μ_x,0, Σ_x,0)
        prior_log_prob = _chol_log_prob(prior_factor, prior_residual)
        if self.A.shape[0] == 0:
            return prior_log_prob
        # F_t x_t
        propagated = einsum(self.A, xs[:-1], "step next prev, step prev -> step next")
        # x_t+1 − F_t x_t
        innovations = xs[1:] - propagated
        # r_t+1 = x_t+1 − F_t x_t − c_t
        residuals = innovations - self.b
        # log 𝒩(x_t+1; F_t x_t + c_t, Σ_η,t+1), one per transition
        transition_log_probs = jax.vmap(_chol_log_prob)(model_noise_factors, residuals)
        # ∑_t log 𝒩(x_t+1; F_t x_t + c_t, Σ_η,t+1), a full reduction
        transition_log_prob = jnp.sum(transition_log_probs)
        # log p(x_0:T−1)
        return prior_log_prob + transition_log_prob

    @validate_sample
    def log_prob(self, value: Float[Array, "*batch T d"]) -> Float[Array, "*batch"]:
        """Log-density log p(x_0:T−1) of each trajectory in ``value``.

        Args:
            value: Trajectories x_0:T−1, with leading batch axes.

        Returns:
            One log-density per trajectory.
        """
        leading_shape = value.shape[:-2]
        value_flat = rearrange(value, "... step state -> (...) step state")
        log_prob_flat = jax.vmap(self._log_prob_single)(value_flat)
        return _reshape_batch(log_prob_flat, leading_shape)

    def _sample_single(self, key: jax.Array) -> Float[Array, "T d"]:
        """One ancestral draw of the trajectory x_0:T−1, O(T D_x³).

            x₀ = μ_x,0 + L_x,0 z₀
            x_t+1 = F_t x_t + c_t + L_η,t+1 z_t+1

        Args:
            key: PRNG key.

        Returns:
            The trajectory x_0:T−1, one row per state.
        """
        prior_factor, model_noise_factors = self._chol_factors()
        num_states, state_size = self.horizon, self.state_dim
        prior_key, transition_key = jax.random.split(key)
        # Draw in the parameters' dtype, not JAX's default float.
        dtype = jnp.result_type(self.mu0, self.P0, self.Q)
        # z₀ ~ 𝒩(0, I)
        prior_noise = jax.random.normal(prior_key, (state_size,), dtype=dtype)
        # L_x,0 z₀
        prior_deviation = prior_factor @ prior_noise
        # x₀ = μ_x,0 + L_x,0 z₀
        initial_state = self.mu0 + prior_deviation
        # z_t+1 ~ 𝒩(0, I), one per transition
        transition_noise = jax.random.normal(
            transition_key, (num_states - 1, state_size), dtype=dtype
        )

        def _step(state, inputs):
            transition, offset, model_noise_factor, noise = inputs
            # F_t x_t
            propagated = transition @ state
            # F_t x_t + c_t
            mean_next = propagated + offset
            # L_η,t+1 z_t+1
            model_noise = model_noise_factor @ noise
            # x_t+1 = F_t x_t + c_t + L_η,t+1 z_t+1
            state_next = mean_next + model_noise
            return state_next, state_next

        _, states_rest = jax.lax.scan(
            _step,
            initial_state,
            (self.A, self.b, model_noise_factors, transition_noise),
        )
        # jnp, not einx: a draw with D_x = 0 works today, and einx rejects
        # a zero-length axis.
        # x₀ as the first row
        initial_state_row = initial_state[None]
        # x_0:T−1, x₀ first
        return jnp.concatenate([initial_state_row, states_rest])

    def sample(
        self,
        key: jax.Array | None,
        sample_shape: tuple[int, ...] = (),
    ) -> Float[Array, "*sample T d"]:
        """Ancestral draws of the trajectory x_0:T−1.

        Args:
            key: PRNG key.
            sample_shape: Leading shape of the draws.

        Returns:
            Draws of shape ``sample_shape + (T, d)``.

        Raises:
            ValueError: If ``key`` is ``None``.
        """
        if key is None:
            raise ValueError("PRNG key must be provided to sample from MarkovGaussian.")
        num_draws = math.prod(sample_shape) if sample_shape else 1
        keys = jax.random.split(key, num_draws)
        samples_flat = jax.vmap(self._sample_single)(keys)
        return _reshape_series(samples_flat, sample_shape)

horizon: int property

Number of states T in the chain.

state_dim: int property

State size D_x.

precision: BlockTriDiag property

Joint precision Λ_x = Σ_x⁻¹ as a BlockTriDiag.

Raw Λ_x, not the −½ Λ_x natural-parameter convention of ssm_to_naturals.

marginals() -> tuple[Float[Array, 'T d'], Float[Array, 'T d d']]

Marginal means μ_x,t and covariances Σ_x,t of every state.

μ_x,t+1 = F_t μ_x,t + c_t
Σ_x,t+1 = F_t Σ_x,t F_tᵀ + Σ_η,t+1
Algorithm
  1. Start from the prior moments μ_x,0 and Σ_x,0.
  2. Push the moments through each transition with a scan.
  3. Prepend the prior moments to the propagated ones.

Returns:

Type Description
Float[Array, 'T d']

Tuple (means, covs) holding μ_x,t and Σ_x,t for

Float[Array, 'T d d']

t = 0, …, T − 1.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def marginals(self) -> tuple[Float[Array, "T d"], Float[Array, "T d d"]]:
    """Marginal means μ_x,t and covariances Σ_x,t of every state.

        μ_x,t+1 = F_t μ_x,t + c_t
        Σ_x,t+1 = F_t Σ_x,t F_tᵀ + Σ_η,t+1

    Algorithm:
        1. Start from the prior moments μ_x,0 and Σ_x,0.
        2. Push the moments through each transition with a scan.
        3. Prepend the prior moments to the propagated ones.

    Returns:
        Tuple ``(means, covs)`` holding μ_x,t and Σ_x,t for
        t = 0, …, T − 1.
    """

    def _step(carry, inputs):
        mean, covariance = carry
        transition, offset, model_noise_covariance = inputs
        # F_t μ_x,t
        propagated_mean = transition @ mean
        # μ_x,t+1 = F_t μ_x,t + c_t
        mean_next = propagated_mean + offset
        # F_t Σ_x,t F_tᵀ, one three-operand contraction
        propagated_covariance = einsum(
            transition,
            covariance,
            transition,
            "next prev, prev col, other col -> next other",
        )
        # Σ_x,t+1 = F_t Σ_x,t F_tᵀ + Σ_η,t+1
        covariance_next = propagated_covariance + model_noise_covariance
        return (mean_next, covariance_next), (mean_next, covariance_next)

    _, (means_rest, covs_rest) = jax.lax.scan(
        _step, (self.mu0, self.P0), (self.A, self.b, self.Q)
    )
    # μ_x,0 as the first row
    prior_mean_row = rearrange(self.mu0, "state -> 1 state")
    # Σ_x,0 as the first slab
    prior_covariance_slab = rearrange(self.P0, "row col -> 1 row col")
    # μ_x,0:T−1, prior first
    means = jnp.concatenate([prior_mean_row, means_rest])
    # Σ_x,0:T−1, prior first
    covs = jnp.concatenate([prior_covariance_slab, covs_rest])
    return means, covs

mean() -> Float[Array, 'T d']

Marginal means μ_x,t, one row per state.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
@lazy_property
def mean(self) -> Float[Array, "T d"]:
    """Marginal means μ_x,t, one row per state."""
    return self.marginals()[0]

variance() -> Float[Array, 'T d']

Marginal variances diag(Σ_x,t), one row per state.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
@lazy_property
def variance(self) -> Float[Array, "T d"]:
    """Marginal variances diag(Σ_x,t), one row per state."""
    _, covs = self.marginals()
    # diag(Σ_x,t)
    return rearrange(covs, "step state state -> step state")

cross_covariances() -> Float[Array, 'Tm1 d d']

Lag-one cross-covariances Σ_x,t+1,t = Cov[x_t+1, x_t] = F_t Σ_x,t.

Returns:

Type Description
Float[Array, 'Tm1 d d']

One D_x × D_x block per transition, t = 0, …, T − 2.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def cross_covariances(self) -> Float[Array, "Tm1 d d"]:
    """Lag-one cross-covariances Σ_x,t+1,t = Cov[x_t+1, x_t] = F_t Σ_x,t.

    Returns:
        One D_x × D_x block per transition, t = 0, …, T − 2.
    """
    _, covs = self.marginals()
    return self._cross(covs)

pairwise_marginals() -> tuple[Float[Array, 'Tm1 two_d'], Float[Array, 'Tm1 two_d two_d']]

Joint Gaussian p(x_t, x_t+1) of each pair of consecutive states.

p(x_t, x_t+1) = 𝒩([μ_x,t; μ_x,t+1], [[Σ_x,t, Σ_x,t+1,tᵀ],
                                    [Σ_x,t+1,t, Σ_x,t+1]])

Returns:

Type Description
Float[Array, 'Tm1 two_d']

Tuple (joint_means, joint_covs) with one pair per

Float[Array, 'Tm1 two_d two_d']

transition, each of length 2 D_x, in the layout of

tuple[Float[Array, 'Tm1 two_d'], Float[Array, 'Tm1 two_d two_d']]

gaussx.pairwise_marginals.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def pairwise_marginals(
    self,
) -> tuple[Float[Array, "Tm1 two_d"], Float[Array, "Tm1 two_d two_d"]]:
    """Joint Gaussian p(x_t, x_t+1) of each pair of consecutive states.

        p(x_t, x_t+1) = 𝒩([μ_x,t; μ_x,t+1], [[Σ_x,t, Σ_x,t+1,tᵀ],
                                            [Σ_x,t+1,t, Σ_x,t+1]])

    Returns:
        Tuple ``(joint_means, joint_covs)`` with one pair per
        transition, each of length 2 D_x, in the layout of
        `gaussx.pairwise_marginals`.
    """
    means, covs = self.marginals()
    if self.A.shape[0] == 0:
        # One state, no pairs.
        # 2 D_x
        joint_size = 2 * self.state_dim
        return (
            jnp.zeros((0, joint_size), means.dtype),
            jnp.zeros((0, joint_size, joint_size), covs.dtype),
        )
    return pairwise_marginals(means, covs, self._cross(covs))

covariance_matrix() -> Float[Array, 'Td Td']

Dense joint covariance Σ_x = Λ_x⁻¹ of the flattened trajectory.

Built column by column through UDLDecomposition.solve, so it costs O(T² D_x³) and is meant for small T (reference checks, dense downstream consumers).

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
@lazy_property
def covariance_matrix(self) -> Float[Array, "Td Td"]:
    """Dense joint covariance Σ_x = Λ_x⁻¹ of the flattened trajectory.

    Built column by column through `UDLDecomposition.solve`, so it
    costs O(T² D_x³) and is meant for small T (reference checks, dense
    downstream consumers).
    """
    # T D_x
    joint_size = self.horizon * self.state_dim
    identity = jnp.eye(joint_size, dtype=self.A.dtype)
    # Λ_x = U D Uᵀ
    udl = self.udl()
    # Σ_x = Λ_x⁻¹ I, one column at a time
    return jax.vmap(udl.solve, in_axes=1, out_axes=1)(identity)

udl() -> UDLDecomposition

The chain's precision, already factorised as Λ_x = U D Uᵀ.

Returns:

Type Description
UDLDecomposition

The UDLDecomposition with U_tᵀ = −F_t, D_t = Σ_η,t⁻¹ for

UDLDecomposition

t ≥ 1 and D_0 = Σ_x,0⁻¹.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def udl(self) -> UDLDecomposition:
    """The chain's precision, already factorised as Λ_x = U D Uᵀ.

    Returns:
        The `UDLDecomposition` with U_tᵀ = −F_t, D_t = Σ_η,t⁻¹ for
        t ≥ 1 and D_0 = Σ_x,0⁻¹.
    """
    return udl_from_ssm_params(self.A, self.Q, self.P0)

to_precision_form() -> tuple[Float[Array, ' Td'], BlockTriDiag]

The chain as its flattened mean and joint precision (μ_x, Λ_x).

This is the layout spingp_posterior consumes and returns: pass mean as its prior_mean (it assumes a zero-mean prior otherwise) and hand its output to from_precision_form. The information vector Λ_x μ_x, if needed, is precision.mv(mean).

Returns:

Type Description
Float[Array, ' Td']

Tuple (mean, precision): the marginal means μ_x,t

BlockTriDiag

flattened state by state, and the joint precision Λ_x.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def to_precision_form(self) -> tuple[Float[Array, " Td"], BlockTriDiag]:
    """The chain as its flattened mean and joint precision ``(μ_x, Λ_x)``.

    This is the layout `spingp_posterior` consumes and returns: pass
    ``mean`` as its ``prior_mean`` (it assumes a zero-mean prior
    otherwise) and hand its output to `from_precision_form`. The
    information vector Λ_x μ_x, if needed, is ``precision.mv(mean)``.

    Returns:
        Tuple ``(mean, precision)``: the marginal means μ_x,t
        flattened state by state, and the joint precision Λ_x.
    """
    # μ_x = [μ_x,0; …; μ_x,T−1]
    mean = rearrange(self.mean, "step state -> (step state)")
    return mean, self.precision

from_precision_form(mean: Float[Array, ' Td'] | Float[Array, 'T d'], precision: BlockTriDiag) -> MarkovGaussian classmethod

Recover the generative chain from its mean and precision.

F_t = −U_tᵀ,   Σ_η,t+1 = D_t+1⁻¹,   c_t = μ_x,t+1 − F_t μ_x,t

Round-trips to_precision_form exactly (to floating point).

Algorithm
  1. Factorise Λ_x = U D Uᵀ with one udl_decomposition pass.
  2. Read off F_t, Σ_η,t+1 and Σ_x,0 = D_0⁻¹ with udl_to_ssm_params.
  3. Recover the offsets c_t from the mean chain.

Parameters:

Name Type Description Default
mean Float[Array, ' Td'] | Float[Array, 'T d']

Marginal means μ_x,t, flattened state by state or one row per state.

required
precision BlockTriDiag

Symmetric positive-definite joint precision Λ_x.

required

Returns:

Type Description
MarkovGaussian

The equivalent MarkovGaussian.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
@classmethod
def from_precision_form(
    cls,
    mean: Float[Array, " Td"] | Float[Array, "T d"],
    precision: BlockTriDiag,
) -> MarkovGaussian:
    """Recover the generative chain from its mean and precision.

        F_t = −U_tᵀ,   Σ_η,t+1 = D_t+1⁻¹,   c_t = μ_x,t+1 − F_t μ_x,t

    Round-trips `to_precision_form` exactly (to floating point).

    Algorithm:
        1. Factorise Λ_x = U D Uᵀ with one `udl_decomposition` pass.
        2. Read off F_t, Σ_η,t+1 and Σ_x,0 = D_0⁻¹ with
           `udl_to_ssm_params`.
        3. Recover the offsets c_t from the mean chain.

    Args:
        mean: Marginal means μ_x,t, flattened state by state or one row
            per state.
        precision: Symmetric positive-definite joint precision Λ_x.

    Returns:
        The equivalent `MarkovGaussian`.
    """
    num_blocks, block_size = precision._num_blocks, precision._block_size
    if mean.ndim == 2:
        means = mean
    else:
        # μ_x,t, one row per state
        means = rearrange(
            mean,
            "(step state) -> step state",
            step=num_blocks,
            state=block_size,
        )
    # Λ_x = U D Uᵀ
    udl = udl_decomposition(precision)
    # F_t = −U_tᵀ and the stacked covariances [Σ_x,0; Σ_η,1:T−1]
    transitions, covariances, _ = udl_to_ssm_params(udl)
    if num_blocks == 1:
        # One state, no transitions: einx cannot contract the empty axis.
        offsets = means[1:]
    else:
        # F_t μ_x,t
        propagated_means = einsum(
            transitions,
            means[:-1],
            "step next prev, step prev -> step next",
        )
        # c_t = μ_x,t+1 − F_t μ_x,t
        offsets = means[1:] - propagated_means
    return cls(transitions, covariances[1:], means[0], covariances[0], b=offsets)

log_prob(value: Float[Array, '*batch T d']) -> Float[Array, '*batch']

Log-density log p(x_0:T−1) of each trajectory in value.

Parameters:

Name Type Description Default
value Float[Array, '*batch T d']

Trajectories x_0:T−1, with leading batch axes.

required

Returns:

Type Description
Float[Array, '*batch']

One log-density per trajectory.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
@validate_sample
def log_prob(self, value: Float[Array, "*batch T d"]) -> Float[Array, "*batch"]:
    """Log-density log p(x_0:T−1) of each trajectory in ``value``.

    Args:
        value: Trajectories x_0:T−1, with leading batch axes.

    Returns:
        One log-density per trajectory.
    """
    leading_shape = value.shape[:-2]
    value_flat = rearrange(value, "... step state -> (...) step state")
    log_prob_flat = jax.vmap(self._log_prob_single)(value_flat)
    return _reshape_batch(log_prob_flat, leading_shape)

sample(key: jax.Array | None, sample_shape: tuple[int, ...] = ()) -> Float[Array, '*sample T d']

Ancestral draws of the trajectory x_0:T−1.

Parameters:

Name Type Description Default
key Array | None

PRNG key.

required
sample_shape tuple[int, ...]

Leading shape of the draws.

()

Returns:

Type Description
Float[Array, '*sample T d']

Draws of shape sample_shape + (T, d).

Raises:

Type Description
ValueError

If key is None.

Source code in packages/pyrox-gauss/src/pyrox_gauss/_markov_gaussian.py
def sample(
    self,
    key: jax.Array | None,
    sample_shape: tuple[int, ...] = (),
) -> Float[Array, "*sample T d"]:
    """Ancestral draws of the trajectory x_0:T−1.

    Args:
        key: PRNG key.
        sample_shape: Leading shape of the draws.

    Returns:
        Draws of shape ``sample_shape + (T, d)``.

    Raises:
        ValueError: If ``key`` is ``None``.
    """
    if key is None:
        raise ValueError("PRNG key must be provided to sample from MarkovGaussian.")
    num_draws = math.prod(sample_shape) if sample_shape else 1
    keys = jax.random.split(key, num_draws)
    samples_flat = jax.vmap(self._sample_single)(keys)
    return _reshape_series(samples_flat, sample_shape)

GMRFs

The GMRF fields (gaussx.GaussianMRF, IntrinsicGMRF, ConstrainedGMRF, BYM2GMRF) stay in gaussx, because gaussx's Laplace and VB code and argminax use them as linear-algebra objects. GMRFDistribution hands one to numpyro.sample.

GMRFDistribution

Bases: Distribution

A GMRF field as a NumPyro distribution, for numpyro.sample.

x ~ field,   log p(x) = field.log_prob(x)

The field keeps every structural dispatch (sparse Cholesky, factored eigenbasis, perturbation-optimisation, kriging); this class only gives it NumPyro's support, event shape and seeding. Draws are differentiable in the field's parameters, so the distribution is reparameterised.

Requires the numpyro optional extra.

Parameters:

Name Type Description Default
field GaussianMRF | ConstrainedGMRF | IntrinsicGMRF | BYM2GMRF

The field, a GaussianMRF, ConstrainedGMRF, IntrinsicGMRF or BYM2GMRF.

required
validate_args bool | None

Whether to validate input arguments.

None

Examples:

A proper field on four iid nodes, sampled inside a NumPyro model:

>>> import jax.numpy as jnp
>>> import lineax as lx
>>> import numpyro
>>> import gaussx as gx
>>> import pyrox_gauss as pg
>>> precision = lx.MatrixLinearOperator(
...     2.0 * jnp.eye(4), lx.positive_semidefinite_tag
... )
>>> field = gx.GaussianMRF(jnp.zeros(4), precision)
>>> def model():
...     return numpyro.sample("x", pg.GMRFDistribution(field))
>>> numpyro.handlers.seed(model, 0)().shape
(4,)
Source code in packages/pyrox-gauss/src/pyrox_gauss/_gmrf.py
class GMRFDistribution(dist.Distribution):
    """A GMRF field as a NumPyro distribution, for ``numpyro.sample``.

        x ~ field,   log p(x) = field.log_prob(x)

    The field keeps every structural dispatch (sparse Cholesky, factored
    eigenbasis, perturbation-optimisation, kriging); this class only gives
    it NumPyro's support, event shape and seeding. Draws are differentiable
    in the field's parameters, so the distribution is reparameterised.

    Requires the ``numpyro`` optional extra.

    Args:
        field: The field, a `GaussianMRF`, `ConstrainedGMRF`, `IntrinsicGMRF`
            or `BYM2GMRF`.
        validate_args: Whether to validate input arguments.

    Examples:
        A proper field on four iid nodes, sampled inside a NumPyro model:

        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> import numpyro
        >>> import gaussx as gx
        >>> import pyrox_gauss as pg
        >>> precision = lx.MatrixLinearOperator(
        ...     2.0 * jnp.eye(4), lx.positive_semidefinite_tag
        ... )
        >>> field = gx.GaussianMRF(jnp.zeros(4), precision)
        >>> def model():
        ...     return numpyro.sample("x", pg.GMRFDistribution(field))
        >>> numpyro.handlers.seed(model, 0)().shape
        (4,)
    """

    arg_constraints = {}  # noqa: RUF012
    support = dist.constraints.real_vector
    pytree_data_fields = ("field",)

    def __init__(
        self,
        field: GaussianMRF | ConstrainedGMRF | IntrinsicGMRF | BYM2GMRF,
        *,
        validate_args: bool | None = None,
    ) -> None:
        self.field = field
        super().__init__(
            batch_shape=(), event_shape=field.event_shape, validate_args=validate_args
        )

    @validate_sample
    def log_prob(self, value: Float[Array, "*sample N"]) -> Float[Array, "*sample"]:
        """The field's log-density.

        Args:
            value: Points x, shape ``(..., N)``.

        Returns:
            Log-densities, shape ``(...)``.
        """
        return self.field.log_prob(value)

    def sample(
        self,
        key: jax.Array | None,
        sample_shape: tuple[int, ...] = (),
    ) -> Float[Array, "*sample N"]:
        """The field's draws.

        Args:
            key: PRNG key. ``None`` means ``jax.random.PRNGKey(0)``.
            sample_shape: Leading sample shape.

        Returns:
            Draws, shape ``sample_shape + (N,)``.
        """
        return self.field.sample(key, sample_shape)

    @property
    def mean(self) -> Float[Array, " N"]:
        """The field's mean."""
        return self.field.mean

    @property
    def variance(self) -> Float[Array, " N"]:
        """The field's marginal variances."""
        return self.field.variance

mean: Float[Array, ' N'] property

The field's mean.

variance: Float[Array, ' N'] property

The field's marginal variances.

log_prob(value: Float[Array, '*sample N']) -> Float[Array, '*sample']

The field's log-density.

Parameters:

Name Type Description Default
value Float[Array, '*sample N']

Points x, shape (..., N).

required

Returns:

Type Description
Float[Array, '*sample']

Log-densities, shape (...).

Source code in packages/pyrox-gauss/src/pyrox_gauss/_gmrf.py
@validate_sample
def log_prob(self, value: Float[Array, "*sample N"]) -> Float[Array, "*sample"]:
    """The field's log-density.

    Args:
        value: Points x, shape ``(..., N)``.

    Returns:
        Log-densities, shape ``(...)``.
    """
    return self.field.log_prob(value)

sample(key: jax.Array | None, sample_shape: tuple[int, ...] = ()) -> Float[Array, '*sample N']

The field's draws.

Parameters:

Name Type Description Default
key Array | None

PRNG key. None means jax.random.PRNGKey(0).

required
sample_shape tuple[int, ...]

Leading sample shape.

()

Returns:

Type Description
Float[Array, '*sample N']

Draws, shape sample_shape + (N,).

Source code in packages/pyrox-gauss/src/pyrox_gauss/_gmrf.py
def sample(
    self,
    key: jax.Array | None,
    sample_shape: tuple[int, ...] = (),
) -> Float[Array, "*sample N"]:
    """The field's draws.

    Args:
        key: PRNG key. ``None`` means ``jax.random.PRNGKey(0)``.
        sample_shape: Leading sample shape.

    Returns:
        Draws, shape ``sample_shape + (N,)``.
    """
    return self.field.sample(key, sample_shape)