Skip to content

Base Distributions

A normalizing flow needs a tractable base distribution \(p_Z\) to push forward through its bijections. The default is a standard normal (flowjax.distributions.Normal), but a richer or structured base can shorten the flow it has to learn. These distributions expose log_prob and sample and plug into any FlowJax Transformed or the package's SurVAEFlow container as the base_dist argument.

Euclidean bases

LowRankGaussian is \(\mathcal{N}(\gvect{\mu}, \mat{W} \mat{W}^\top + \gmat{\Psi})\) with a loading \(\mat{W} \in \mathbb{R}^{D \times K}\) and a noise covariance \(\gmat{\Psi} = \mathrm{diag}(\gvect{\psi})\): isotropic noise (\(\gvect{\psi} = \sigma^2 \vect{1}\), noise="isotropic") is probabilistic PCA, and a free diagonal (noise="diagonal") is factor analysis. Its covariance is a gaussx.LowRankUpdate, so gaussx evaluates the density by the Woodbury identity and the matrix-determinant lemma with the \(K \times K\) capacitance \(\mat{M} = \mat{I} + \mat{W}^\top \gmat{\Psi}^{-1} \mat{W}\),

\[ \gmat{\Sigma}^{-1} = \gmat{\Psi}^{-1} - \gmat{\Psi}^{-1} \mat{W} \mat{M}^{-1} \mat{W}^\top \gmat{\Psi}^{-1}, \text{ and } \log \det \gmat{\Sigma} = \sum_{i=1}^{D} \log \psi_i + \log \det \mat{M}, \]

at \(O(DK^2 + K^3)\) cost, without forming the \(D \times D\) covariance. It replaces GaussianPCA (GaussianPCA(key, event_shape, latent_dim, log_sigma_init=…) is now LowRankGaussian(key, event_shape, rank, log_noise_scale_init=…)). AbstractOperatorGaussian is its base: a subclass builds the covariance operator \(\gmat{\Sigma}\), and the base takes the log-density from gaussx.gaussian_log_prob and the draws from gaussx.sample_mvn, both dispatched on the structure of \(\gmat{\Sigma}\).

GaussianMixture is a 1-D mixture used as a marginal target. Its component scales or Cholesky factors (scale_tril) and its weights are paramax.Parameterize leaves of gauss_flows_maps.reparam (an exp-diagonal CholeskyFactor or Reparametrised("exp"), and a Simplex), and GaussianMixture.from_fitted starts one from fitted means, scales and weights. The conditional variants emit mean/scale from a context vector for amortised inference and class-conditional flows.

ConditionalDiagGaussian draws \(\vect{x} = \gvect{\beta}(\vect{c}) + \gvect{\gamma}(\vect{c}) \odot \gvect{\epsilon}\) with \(\gvect{\epsilon} \sim \mathcal{N}(\vect{0}, \mat{I})\), where \((\gvect{\gamma}, \gvect{\beta})\) come from the shared AffineModulation of the context. Its readout starts at zero, so the distribution is \(\mathcal{N}(\vect{0}, \mat{I})\) for every context at initialisation.

LowRankGaussian

Bases: AbstractOperatorGaussian

𝒩(μ, W Wᵀ + Ψ): probabilistic PCA (isotropic Ψ) or factor analysis (diagonal Ψ).

Σ = W Wᵀ + Ψ,   Ψ = diag(ψ),   ψ = exp(2 log s) + ε,   x = μ + W z + Ψ^½ η

with the loading W ∈ ℝ^(D×K), K ≤ D, the noise scale s (one scalar for noise="isotropic", so ψ = σ² 1 with σ = s; one per dimension for noise="diagonal"), the floor ε, and z ∈ ℝᴷ, η ∈ ℝᴰ standard normal. Σ is a gaussx.LowRankUpdate of a diagonal base, so gaussx.gaussian_log_prob evaluates it by the Woodbury identity and the matrix-determinant lemma with the K × K capacitance M = I + Wᵀ Ψ⁻¹ W,

Σ⁻¹ = Ψ⁻¹ − Ψ⁻¹ W M⁻¹ Wᵀ Ψ⁻¹,   log det Σ = ∑ᵢ log ψᵢ + log det M,

at O(DK² + K³) cost, and gaussx.sample_mvn draws it at O(DK).

Use as a flow base when the Gaussianized target has approximately low-rank correlation in D dimensions.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key used to initialise W.

required
event_shape tuple[int, ...]

Shape of a single sample (D,). 1-D only.

required
rank int

Rank K of the loading W (1 ≤ K ≤ D).

required
noise NoiseKind

"isotropic" (one noise scale, probabilistic PCA) or "diagonal" (one per dimension, factor analysis). Defaults to "isotropic".

'isotropic'
loc ArrayLike

Mean μ. A scalar is broadcast to shape (D,). Defaults to 0.0.

0.0
log_noise_scale_init float

Initial value of every log s. Defaults to 0.0 (unit noise variance).

0.0
W_init_scale float

Standard deviation of the Gaussian that initialises W. Defaults to 0.1.

0.1
eps float

Floor ε added to the noise variance ψ, so Ψ stays invertible when log s drifts very negative in training. Defaults to 1e-12.

1e-12

Raises:

Type Description
ValueError

If event_shape is not 1-D, rank is outside [1, D], noise is not one of the two kinds, or eps is negative.

Shape
  • log_prob: (D,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, D)
  • covariance_operator: → a D × D gaussx.LowRankUpdate
  • covariance: → (D, D)

Examples:

Probabilistic PCA, x ~ 𝒩(μ, W Wᵀ + σ² I):

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import LowRankGaussian
>>> pca_base = LowRankGaussian(jr.key(0), event_shape=(50,), rank=5)
>>> pca_base.sample(jr.key(1), (8,)).shape
(8, 50)

Factor analysis, x ~ 𝒩(μ, W Wᵀ + diag(ψ)):

>>> fa_base = LowRankGaussian(
...     jr.key(1), event_shape=(50,), rank=5, noise="diagonal"
... )
>>> fa_base.log_noise_scale.shape
(50,)
>>> fa_base.log_prob(jnp.zeros(50)).shape
()

As the base of a Gaussianization flow:

>>> from gauss_flows_models.flows import gaussianization_flow
>>> base = LowRankGaussian(jr.key(2), event_shape=(4,), rank=2)
>>> flow = gaussianization_flow(jr.key(3), n_dims=4, n_layers=2, base_dist=base)
>>> flow.sample(jr.key(4), (8,)).shape
(8, 4)
References

Tipping, M. E. and Bishop, C. M. (1999). Probabilistic principal component analysis. Journal of the Royal Statistical Society: Series B, 61(3), 611–622.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/low_rank.py
class LowRankGaussian(AbstractOperatorGaussian):
    """𝒩(μ, W Wᵀ + Ψ): probabilistic PCA (isotropic Ψ) or factor analysis (diagonal Ψ).

        Σ = W Wᵀ + Ψ,   Ψ = diag(ψ),   ψ = exp(2 log s) + ε,   x = μ + W z + Ψ^½ η

    with the loading W ∈ ℝ^(D×K), K ≤ D, the noise scale s (one scalar for
    ``noise="isotropic"``, so ψ = σ² 1 with σ = s; one per dimension for
    ``noise="diagonal"``), the floor ε, and z ∈ ℝᴷ, η ∈ ℝᴰ standard normal.
    Σ is a `gaussx.LowRankUpdate` of a diagonal base, so
    `gaussx.gaussian_log_prob` evaluates it by the Woodbury identity and the
    matrix-determinant lemma with the K × K capacitance M = I + Wᵀ Ψ⁻¹ W,

        Σ⁻¹ = Ψ⁻¹ − Ψ⁻¹ W M⁻¹ Wᵀ Ψ⁻¹,   log det Σ = ∑ᵢ log ψᵢ + log det M,

    at O(DK² + K³) cost, and `gaussx.sample_mvn` draws it at O(DK).

    Use as a flow base when the Gaussianized target has approximately
    low-rank correlation in ``D`` dimensions.

    Args:
        key: JAX random key used to initialise ``W``.
        event_shape: Shape of a single sample ``(D,)``. 1-D only.
        rank: Rank ``K`` of the loading ``W`` (``1 ≤ K ≤ D``).
        noise: ``"isotropic"`` (one noise scale, probabilistic PCA) or
            ``"diagonal"`` (one per dimension, factor analysis). Defaults to
            ``"isotropic"``.
        loc: Mean μ. A scalar is broadcast to shape ``(D,)``. Defaults to
            ``0.0``.
        log_noise_scale_init: Initial value of every log s. Defaults to
            ``0.0`` (unit noise variance).
        W_init_scale: Standard deviation of the Gaussian that initialises
            ``W``. Defaults to ``0.1``.
        eps: Floor ε added to the noise variance ψ, so Ψ stays invertible
            when log s drifts very negative in training. Defaults to
            ``1e-12``.

    Raises:
        ValueError: If ``event_shape`` is not 1-D, ``rank`` is outside
            ``[1, D]``, ``noise`` is not one of the two kinds, or ``eps`` is
            negative.

    Shape:
        - log_prob: ``(D,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, D)``
        - covariance_operator: → a D × D `gaussx.LowRankUpdate`
        - covariance: → ``(D, D)``

    Examples:
        Probabilistic PCA, x ~ 𝒩(μ, W Wᵀ + σ² I):

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import LowRankGaussian
        >>> pca_base = LowRankGaussian(jr.key(0), event_shape=(50,), rank=5)
        >>> pca_base.sample(jr.key(1), (8,)).shape
        (8, 50)

        Factor analysis, x ~ 𝒩(μ, W Wᵀ + diag(ψ)):

        >>> fa_base = LowRankGaussian(
        ...     jr.key(1), event_shape=(50,), rank=5, noise="diagonal"
        ... )
        >>> fa_base.log_noise_scale.shape
        (50,)
        >>> fa_base.log_prob(jnp.zeros(50)).shape
        ()

        As the base of a Gaussianization flow:

        >>> from gauss_flows_models.flows import gaussianization_flow
        >>> base = LowRankGaussian(jr.key(2), event_shape=(4,), rank=2)
        >>> flow = gaussianization_flow(jr.key(3), n_dims=4, n_layers=2, base_dist=base)
        >>> flow.sample(jr.key(4), (8,)).shape
        (8, 4)

    References:
        Tipping, M. E. and Bishop, C. M. (1999). Probabilistic principal
        component analysis. *Journal of the Royal Statistical Society:
        Series B*, 61(3), 611–622.
    """

    loc: Array
    W: Array
    log_noise_scale: Array
    shape: tuple[int, ...]
    noise: NoiseKind = eqx.field(static=True)
    eps: float = eqx.field(static=True)

    def __init__(
        self,
        key: PRNGKeyArray,
        event_shape: tuple[int, ...],
        rank: int,
        *,
        noise: NoiseKind = "isotropic",
        loc: ArrayLike = 0.0,
        log_noise_scale_init: float = 0.0,
        W_init_scale: float = 0.1,
        eps: float = 1e-12,
    ):
        if len(event_shape) != 1:
            raise ValueError(
                f"LowRankGaussian only supports 1D event shapes, got {event_shape}."
            )
        event_size = event_shape[0]
        if not 1 <= rank <= event_size:
            raise ValueError(f"rank must be in [1, {event_size}], got {rank}.")
        if noise not in ("isotropic", "diagonal"):
            raise ValueError(f"noise must be 'isotropic' or 'diagonal', got {noise!r}.")
        if eps < 0:
            raise ValueError(f"eps must be non-negative, got {eps}.")
        noise_size = 1 if noise == "isotropic" else event_size
        self.loc = jnp.broadcast_to(jnp.asarray(loc, dtype=float), event_shape)
        self.W = jr.normal(key, (event_size, rank)) * W_init_scale
        self.log_noise_scale = jnp.full((noise_size,), log_noise_scale_init)
        self.shape = event_shape
        self.noise = noise
        self.eps = eps

    def _noise_variance(self) -> Array:
        """The noise variances ψ, shape ``(D,)``, floored at ε."""
        # ψ = exp(2 log s) + ε, broadcast (P,) → (D,)
        variance = jnp.exp(2.0 * self.log_noise_scale) + self.eps
        return jnp.broadcast_to(variance, self.shape)

    def covariance_operator(self) -> gx.LowRankUpdate:
        """The covariance Σ = Ψ + W Wᵀ as a `gaussx.LowRankUpdate`.

        Returns:
            ``gaussx.low_rank_plus_diag(ψ, W, psd=True)``.
        """
        # Σ = diag(ψ) + W Wᵀ
        return gx.low_rank_plus_diag(self._noise_variance(), self.W, psd=True)

    def covariance(self) -> Array:
        """The dense covariance W Wᵀ + Ψ, for tests and small ``D``.

        Returns:
            The ``(D, D)`` matrix Σ.
        """
        return self.covariance_operator().as_matrix()

covariance_operator

covariance_operator() -> LowRankUpdate

The covariance Σ = Ψ + W Wᵀ as a gaussx.LowRankUpdate.

Returns:

Type Description
LowRankUpdate

gaussx.low_rank_plus_diag(ψ, W, psd=True).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/low_rank.py
def covariance_operator(self) -> gx.LowRankUpdate:
    """The covariance Σ = Ψ + W Wᵀ as a `gaussx.LowRankUpdate`.

    Returns:
        ``gaussx.low_rank_plus_diag(ψ, W, psd=True)``.
    """
    # Σ = diag(ψ) + W Wᵀ
    return gx.low_rank_plus_diag(self._noise_variance(), self.W, psd=True)

covariance

covariance() -> Array

The dense covariance W Wᵀ + Ψ, for tests and small D.

Returns:

Type Description
Array

The (D, D) matrix Σ.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/low_rank.py
def covariance(self) -> Array:
    """The dense covariance W Wᵀ + Ψ, for tests and small ``D``.

    Returns:
        The ``(D, D)`` matrix Σ.
    """
    return self.covariance_operator().as_matrix()

AbstractOperatorGaussian

Bases: AbstractDistribution

𝒩(μ, Σ) with Σ a lineax operator that the subclass builds.

log p(x) = −½ (D log 2π + log det Σ + (x − μ)ᵀ Σ⁻¹ (x − μ)),   x = μ + L z

with z ~ 𝒩(0, I) and L Lᵀ = Σ. The log-density is gaussx.gaussian_log_prob and the draw gaussx.sample_mvn, so the solve, the log-determinant and the factor L are chosen by the structure of Σ (a low-rank update, a Kronecker product, a block-tridiagonal band, …).

The base holds the mean loc (μ, shape (D,)); a subclass declares shape ((D,)) and implements covariance_operator. The base is unconditional (cond_shape is None).

Shape
  • log_prob: (D,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, D)

Examples:

A subclass needs only the mean, the event shape and Σ:

>>> import jax.numpy as jnp
>>> import lineax as lx
>>> from gauss_flows_models.distributions import AbstractOperatorGaussian
>>> class DiagonalGaussian(AbstractOperatorGaussian):
...     variance: jnp.ndarray
...     shape: tuple[int, ...]
...     def covariance_operator(self):
...         return lx.DiagonalLinearOperator(self.variance)
>>> dist = DiagonalGaussian(jnp.zeros(3), jnp.ones(3), (3,))
>>> round(float(dist.log_prob(jnp.zeros(3))), 4)
-2.7568
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/operator_gaussian.py
class AbstractOperatorGaussian(AbstractDistribution):
    """𝒩(μ, Σ) with Σ a lineax operator that the subclass builds.

        log p(x) = −½ (D log 2π + log det Σ + (x − μ)ᵀ Σ⁻¹ (x − μ)),   x = μ + L z

    with z ~ 𝒩(0, I) and L Lᵀ = Σ. The log-density is
    `gaussx.gaussian_log_prob` and the draw `gaussx.sample_mvn`, so the solve,
    the log-determinant and the factor L are chosen by the structure of Σ
    (a low-rank update, a Kronecker product, a block-tridiagonal band, …).

    The base holds the mean ``loc`` (μ, shape ``(D,)``); a subclass declares
    ``shape`` (``(D,)``) and implements `covariance_operator`. The base is
    unconditional (``cond_shape`` is ``None``).

    Shape:
        - log_prob: ``(D,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, D)``

    Examples:
        A subclass needs only the mean, the event shape and Σ:

        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> from gauss_flows_models.distributions import AbstractOperatorGaussian
        >>> class DiagonalGaussian(AbstractOperatorGaussian):
        ...     variance: jnp.ndarray
        ...     shape: tuple[int, ...]
        ...     def covariance_operator(self):
        ...         return lx.DiagonalLinearOperator(self.variance)
        >>> dist = DiagonalGaussian(jnp.zeros(3), jnp.ones(3), (3,))
        >>> round(float(dist.log_prob(jnp.zeros(3))), 4)
        -2.7568
    """

    loc: Array
    cond_shape: ClassVar[None] = None

    @abc.abstractmethod
    def covariance_operator(self) -> lx.AbstractLinearOperator:
        """The covariance Σ as a D × D lineax operator.

        Returns:
            The operator Σ; its structure decides gaussx's solve,
            log-determinant and sampling factor.
        """

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        # log N(x; μ, Σ), solve and log det Σ by the structure of Σ
        return gx.gaussian_log_prob(self.loc, self.covariance_operator(), x)

    def sample(
        self,
        key: PRNGKeyArray,
        sample_shape: tuple[int, ...] = (),
        condition: ArrayLike | None = None,
    ) -> Array:
        """Draw ``sample_shape`` events in one `gaussx.sample_mvn` call.

        FlowJax's `sample` maps `_sample` over one key per event with
        ``jax.vmap``; one call with ``num_samples`` instead lets gaussx factor Σ
        once and keeps its structure-or-fallback choices unbatched, so a
        fallback it guards with ``lax.cond`` is not evaluated for every draw.

        Args:
            key: JAX random key.
            sample_shape: Leading shape of the draws. Defaults to ``()``.
            condition: Unused; the distribution is unconditional.

        Returns:
            Draws of shape ``(*sample_shape, D)``.
        """
        self = paramax.unwrap(self)
        num_samples = math.prod(sample_shape)
        # (max(S, 1), D), with S = ∏ sample_shape
        draws = gx.sample_mvn(
            self.loc,
            self.covariance_operator(),
            key=key,
            num_samples=max(num_samples, 1),
        )
        # (S, D) → (*sample_shape, D)
        return draws[:num_samples].reshape(*sample_shape, *self.shape)

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        # x = μ + L z with L Lᵀ = Σ chosen by structure; (1, D) → (D,)
        draws = gx.sample_mvn(self.loc, self.covariance_operator(), key=key)
        return draws[0]

covariance_operator abstractmethod

covariance_operator() -> AbstractLinearOperator

The covariance Σ as a D × D lineax operator.

Returns:

Type Description
AbstractLinearOperator

The operator Σ; its structure decides gaussx's solve,

AbstractLinearOperator

log-determinant and sampling factor.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/operator_gaussian.py
@abc.abstractmethod
def covariance_operator(self) -> lx.AbstractLinearOperator:
    """The covariance Σ as a D × D lineax operator.

    Returns:
        The operator Σ; its structure decides gaussx's solve,
        log-determinant and sampling factor.
    """

sample

sample(key: PRNGKeyArray, sample_shape: tuple[int, ...] = (), condition: ArrayLike | None = None) -> Array

Draw sample_shape events in one gaussx.sample_mvn call.

FlowJax's sample maps _sample over one key per event with jax.vmap; one call with num_samples instead lets gaussx factor Σ once and keeps its structure-or-fallback choices unbatched, so a fallback it guards with lax.cond is not evaluated for every draw.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key.

required
sample_shape tuple[int, ...]

Leading shape of the draws. Defaults to ().

()
condition ArrayLike | None

Unused; the distribution is unconditional.

None

Returns:

Type Description
Array

Draws of shape (*sample_shape, D).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/operator_gaussian.py
def sample(
    self,
    key: PRNGKeyArray,
    sample_shape: tuple[int, ...] = (),
    condition: ArrayLike | None = None,
) -> Array:
    """Draw ``sample_shape`` events in one `gaussx.sample_mvn` call.

    FlowJax's `sample` maps `_sample` over one key per event with
    ``jax.vmap``; one call with ``num_samples`` instead lets gaussx factor Σ
    once and keeps its structure-or-fallback choices unbatched, so a
    fallback it guards with ``lax.cond`` is not evaluated for every draw.

    Args:
        key: JAX random key.
        sample_shape: Leading shape of the draws. Defaults to ``()``.
        condition: Unused; the distribution is unconditional.

    Returns:
        Draws of shape ``(*sample_shape, D)``.
    """
    self = paramax.unwrap(self)
    num_samples = math.prod(sample_shape)
    # (max(S, 1), D), with S = ∏ sample_shape
    draws = gx.sample_mvn(
        self.loc,
        self.covariance_operator(),
        key=key,
        num_samples=max(num_samples, 1),
    )
    # (S, D) → (*sample_shape, D)
    return draws[:num_samples].reshape(*sample_shape, *self.shape)

GaussianMixture

Bases: AbstractDistribution

Trainable multivariate Gaussian-mixture base distribution.

Parameterises a K-component mixture of D-dimensional Gaussians with trainable component means, scales, and weights. The density is p(x) = ∑ₖ wₖ · N(x; locₖ, Σₖ) with mixing weights w on the open simplex. Two covariance parameterisations are supported: a diagonal one (one scale per component per dim) and a full-covariance one (a per-component lower-triangular Cholesky factor Σₖ = Lₖ Lₖᵀ).

Both are stored as paramax.Parameterize leaves of the maps in gauss_flows_maps.reparam, and paramax.unwrap turns each into its constrained value:

  • weights: a Simplex leaf, w = softmax([u, 0]) with u of shape (K − 1,), so the weights have exactly K − 1 degrees of freedom. With K = 1 there is nothing to train and weights is the constant [1].
  • scale_tril, full covariance: a CholeskyFactor leaf with an exp diagonal, (K, D, D) unwrapped from (K, D(D + 1)/2) raw values.
  • scale_tril, diagonal: a Reparametrised("exp") leaf, the (K, D) scales unwrapped from their (K, D) logarithms.

Use as a flow base when the Gaussianized target is multi-modal or fat-tailed — the natural companion to MixtureGaussianCDF, the per-dimension marginal transform.

To start from fitted means, covariances and weights, use from_fitted, which stores each through the map's parameter (so it is checked and inverted): for diagonal=False, pass the Cholesky factors of the fitted covariances (jnp.linalg.cholesky), and for diagonal=True the fitted standard deviations.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key used to initialise the component means.

required
n_components int

Number of mixture components K.

required
event_shape tuple[int, ...]

Shape of a single sample (D,). 1-D only.

required
diagonal bool

If True (default), diagonal covariance. If False, full covariance via a per-component lower-triangular Cholesky factor. Defaults to True.

True
loc_init_scale float

Std of the Gaussian used to initialise component means. Defaults to 1.0.

1.0
log_scale_init float

Logarithm of the initial scale (resp. of the initial Cholesky diagonal for diagonal=False). Defaults to 0.0 (unit scale at init).

0.0
Note

The event shape is stored as self.shape per the flowjax distribution contract; mixing weights are uniform at init.

Shape
  • log_prob: (D,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, D)

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import GaussianMixture
>>> dist = GaussianMixture(jr.key(0), n_components=3, event_shape=(2,))
>>> dist.sample(jr.key(1), (8,)).shape
(8, 2)
>>> dist.log_prob(jnp.zeros(2)).shape
()
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/mixture.py
class GaussianMixture(AbstractDistribution):
    """Trainable multivariate Gaussian-mixture base distribution.

    Parameterises a ``K``-component mixture of ``D``-dimensional Gaussians
    with trainable component means, scales, and weights. The density is
    ``p(x) = ∑ₖ wₖ · N(x; locₖ, Σₖ)`` with mixing weights ``w`` on the open
    simplex. Two covariance parameterisations are supported: a diagonal one
    (one scale per component per dim) and a full-covariance one (a
    per-component lower-triangular Cholesky factor ``Σₖ = Lₖ Lₖᵀ``).

    Both are stored as `paramax.Parameterize` leaves of the maps in
    `gauss_flows_maps.reparam`, and ``paramax.unwrap`` turns each into its
    constrained value:

    - ``weights``: a `Simplex` leaf, ``w = softmax([u, 0])`` with ``u`` of
      shape ``(K − 1,)``, so the weights have exactly ``K − 1`` degrees of
      freedom. With ``K = 1`` there is nothing to train and ``weights`` is the
      constant ``[1]``.
    - ``scale_tril``, full covariance: a `CholeskyFactor` leaf with an ``exp``
      diagonal, ``(K, D, D)`` unwrapped from ``(K, D(D + 1)/2)`` raw values.
    - ``scale_tril``, diagonal: a ``Reparametrised("exp")`` leaf, the ``(K, D)``
      scales unwrapped from their ``(K, D)`` logarithms.

    Use as a flow base when the Gaussianized target is multi-modal or
    fat-tailed — the natural companion to `MixtureGaussianCDF`,
    the per-dimension marginal transform.

    To start from fitted means, covariances and weights, use `from_fitted`,
    which stores each through the map's ``parameter`` (so it is checked and
    inverted): for ``diagonal=False``, pass the Cholesky factors of the fitted
    covariances (``jnp.linalg.cholesky``), and for ``diagonal=True`` the
    fitted standard deviations.

    Args:
        key: JAX random key used to initialise the component means.
        n_components: Number of mixture components ``K``.
        event_shape: Shape of a single sample ``(D,)``. 1-D only.
        diagonal: If ``True`` (default), diagonal covariance. If ``False``,
            full covariance via a per-component lower-triangular Cholesky
            factor. Defaults to ``True``.
        loc_init_scale: Std of the Gaussian used to initialise component
            means. Defaults to ``1.0``.
        log_scale_init: Logarithm of the initial scale (resp. of the initial
            Cholesky diagonal for ``diagonal=False``). Defaults to ``0.0``
            (unit scale at init).

    Note:
        The event shape is stored as ``self.shape`` per the flowjax
        distribution contract; mixing weights are uniform at init.

    Shape:
        - log_prob: ``(D,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, D)``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import GaussianMixture
        >>> dist = GaussianMixture(jr.key(0), n_components=3, event_shape=(2,))
        >>> dist.sample(jr.key(1), (8,)).shape
        (8, 2)
        >>> dist.log_prob(jnp.zeros(2)).shape
        ()
    """

    n_components: int = eqx.field(static=True)
    diagonal: bool = eqx.field(static=True)
    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    loc: Array
    # paramax.Parameterize leaves (see Reparametrised.parameter) that unwrap to
    # the component scales or Cholesky factors and to the weights; annotated
    # Array as flowjax does for its own leaves
    scale_tril: Array
    weights: Array

    def __init__(
        self,
        key: PRNGKeyArray,
        n_components: int,
        event_shape: tuple[int, ...],
        *,
        diagonal: bool = True,
        loc_init_scale: float = 1.0,
        log_scale_init: float = 0.0,
    ):
        if n_components <= 0:
            raise ValueError(f"n_components must be positive, got {n_components}.")
        if len(event_shape) != 1:
            raise ValueError("GaussianMixture only supports 1D event shapes.")
        d = event_shape[0]
        k = n_components
        self.n_components = k
        self.diagonal = diagonal
        self.shape = event_shape
        self.loc = jr.normal(key, (k, d)) * loc_init_scale
        # scale = exp(log_scale_init): the diagonal of every factor, or all scales
        scale = jnp.exp(jnp.asarray(log_scale_init))
        if diagonal:
            # (K, D) scales
            initial = jnp.full((k, d), scale)
        else:
            # (K, D, D) factors scale · I
            initial = jnp.broadcast_to(scale * jnp.eye(d), (k, d, d))
        self.scale_tril = _scale_leaf(initial, diagonal=diagonal)
        self.weights = _weights_leaf(jnp.full((k,), 1.0 / k))

    @classmethod
    def from_fitted(
        cls,
        loc: ArrayLike,
        scale_tril: ArrayLike,
        weights: ArrayLike,
        *,
        diagonal: bool = True,
    ) -> GaussianMixture:
        """Build a mixture that starts at fitted means, scales and weights.

        Args:
            loc: Component means, ``(K, D)``.
            scale_tril: For ``diagonal=True``, the component standard
                deviations ``(K, D)``, strictly positive. For
                ``diagonal=False``, the lower-triangular Cholesky factors
                ``(K, D, D)`` of the covariances, with a positive diagonal.
            weights: Mixing weights ``(K,)``, positive and summing to 1.
            diagonal: Whether the covariances are diagonal.

        Returns:
            A `GaussianMixture` whose unwrapped ``scale_tril`` and ``weights``
            are the given values.

        Raises:
            ValueError: When a value lies outside its set (the maps check it).

        Examples:
            >>> import jax.numpy as jnp
            >>> from gauss_flows_models.distributions import GaussianMixture
            >>> covariances = jnp.stack([jnp.eye(2), 2.0 * jnp.eye(2)])
            >>> dist = GaussianMixture.from_fitted(
            ...     jnp.zeros((2, 2)),
            ...     jnp.linalg.cholesky(covariances),
            ...     jnp.array([0.3, 0.7]),
            ...     diagonal=False,
            ... )
            >>> dist.log_prob(jnp.zeros(2)).shape
            ()
        """
        loc = jnp.asarray(loc)
        k, d = loc.shape
        dist = cls(jr.key(0), k, (d,), diagonal=diagonal)
        scale_leaf = _scale_leaf(jnp.asarray(scale_tril), diagonal=diagonal)
        weights_leaf = _weights_leaf(jnp.asarray(weights))
        return eqx.tree_at(
            lambda m: (m.loc, m.scale_tril, m.weights),
            dist,
            (loc, scale_leaf, weights_leaf),
        )

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        # wₖ, unwrapped by flowjax's log_prob
        log_weights = jnp.log(self.weights)
        if self.diagonal:
            scales = self.scale_tril
            # jstats.norm.logpdf broadcasts (D,) vs (K, D) -> (K, D); sum last axis.
            log_pdfs = jnp.sum(
                jstats.norm.logpdf(x[None, :], self.loc, scales), axis=-1
            )
        else:
            L = self.scale_tril

            def _component_logpdf(loc_k: Array, L_k: Array) -> Array:
                # Σₖ = Lₖ Lₖᵀ, tagged PSD so gaussx factors it once
                covariance = lx.MatrixLinearOperator(
                    L_k @ L_k.T, lx.positive_semidefinite_tag
                )
                # log N(x; μₖ, Σₖ)
                return gx.gaussian_log_prob(loc_k, covariance, x)

            # (K, D), (K, D, D) → (K,)
            log_pdfs = jax.vmap(_component_logpdf)(self.loc, L)
        return logsumexp(log_weights + log_pdfs)

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        k_comp, k_normal = jr.split(key)
        component = jr.choice(k_comp, self.n_components, p=self.weights)
        z = jr.normal(k_normal, self.shape)
        if self.diagonal:
            return self.loc[component] + self.scale_tril[component] * z
        return self.loc[component] + self.scale_tril[component] @ z

from_fitted classmethod

from_fitted(loc: ArrayLike, scale_tril: ArrayLike, weights: ArrayLike, *, diagonal: bool = True) -> GaussianMixture

Build a mixture that starts at fitted means, scales and weights.

Parameters:

Name Type Description Default
loc ArrayLike

Component means, (K, D).

required
scale_tril ArrayLike

For diagonal=True, the component standard deviations (K, D), strictly positive. For diagonal=False, the lower-triangular Cholesky factors (K, D, D) of the covariances, with a positive diagonal.

required
weights ArrayLike

Mixing weights (K,), positive and summing to 1.

required
diagonal bool

Whether the covariances are diagonal.

True

Returns:

Type Description
GaussianMixture

A GaussianMixture whose unwrapped scale_tril and weights

GaussianMixture

are the given values.

Raises:

Type Description
ValueError

When a value lies outside its set (the maps check it).

Examples:

>>> import jax.numpy as jnp
>>> from gauss_flows_models.distributions import GaussianMixture
>>> covariances = jnp.stack([jnp.eye(2), 2.0 * jnp.eye(2)])
>>> dist = GaussianMixture.from_fitted(
...     jnp.zeros((2, 2)),
...     jnp.linalg.cholesky(covariances),
...     jnp.array([0.3, 0.7]),
...     diagonal=False,
... )
>>> dist.log_prob(jnp.zeros(2)).shape
()
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/mixture.py
@classmethod
def from_fitted(
    cls,
    loc: ArrayLike,
    scale_tril: ArrayLike,
    weights: ArrayLike,
    *,
    diagonal: bool = True,
) -> GaussianMixture:
    """Build a mixture that starts at fitted means, scales and weights.

    Args:
        loc: Component means, ``(K, D)``.
        scale_tril: For ``diagonal=True``, the component standard
            deviations ``(K, D)``, strictly positive. For
            ``diagonal=False``, the lower-triangular Cholesky factors
            ``(K, D, D)`` of the covariances, with a positive diagonal.
        weights: Mixing weights ``(K,)``, positive and summing to 1.
        diagonal: Whether the covariances are diagonal.

    Returns:
        A `GaussianMixture` whose unwrapped ``scale_tril`` and ``weights``
        are the given values.

    Raises:
        ValueError: When a value lies outside its set (the maps check it).

    Examples:
        >>> import jax.numpy as jnp
        >>> from gauss_flows_models.distributions import GaussianMixture
        >>> covariances = jnp.stack([jnp.eye(2), 2.0 * jnp.eye(2)])
        >>> dist = GaussianMixture.from_fitted(
        ...     jnp.zeros((2, 2)),
        ...     jnp.linalg.cholesky(covariances),
        ...     jnp.array([0.3, 0.7]),
        ...     diagonal=False,
        ... )
        >>> dist.log_prob(jnp.zeros(2)).shape
        ()
    """
    loc = jnp.asarray(loc)
    k, d = loc.shape
    dist = cls(jr.key(0), k, (d,), diagonal=diagonal)
    scale_leaf = _scale_leaf(jnp.asarray(scale_tril), diagonal=diagonal)
    weights_leaf = _weights_leaf(jnp.asarray(weights))
    return eqx.tree_at(
        lambda m: (m.loc, m.scale_tril, m.weights),
        dist,
        (loc, scale_leaf, weights_leaf),
    )

ConditionalDiagGaussian

Bases: AbstractDistribution

Diagonal Gaussian whose location and scale are an affine modulation of noise.

A draw is standard normal noise modulated by the context c,

x = β(c) + γ(c) ⊙ ε,   ε ~ 𝒩(0, I),

so by change of variables

log p(x | c) = Σᵢ [log 𝒩((xᵢ − βᵢ(c)) / γᵢ(c); 0, 1) − log γᵢ(c)],

where (γ, log γ, β) = modulation.modulation(c) come from the shared gauss_flows_maps.conditioning.AffineModulation. Its readout starts at zero weight and bias (0, r₀), so γ = 1 and β = 0 for every c and the distribution starts as 𝒩(0, I).

Parameters:

Name Type Description Default
key PRNGKeyArray

PRNG key for the modulation's init; unused with a pre-built modulation.

required
event_shape tuple[int, ...]

Single-event shape (D,). 1-D only.

required
cond_dim int

Context size K.

required
nn_width int

Width of the modulation's trunk.

64
nn_depth int

Number of trunk layers; 0 reads γ and β linearly from c.

2
activation Callable[[Array], Array]

Activation after each trunk layer.

tanh
readout_scale float

Factor on the readout's default weight; the default 0 makes the distribution exactly 𝒩(0, I) at init for every c.

0.0
scale_map _FlowScaleMap

The positive scale map σ of AffineModulation, a map of gauss_flows_maps.reparam or one of "exp" (default, γ = eʳ), "softplus" and "one_plus_tanh".

'exp'
modulation AffineModulation | None

A pre-built AffineModulation from K inputs to D features; it replaces the arguments from nn_width to scale_map.

None

Raises:

Type Description
ValueError

If event_shape is not 1-D with a positive size, if cond_dim is not positive, if scale_map is "identity", or if modulation has the wrong sizes.

Shape

sample: condition (K,) to x (D,). log_prob: x (D,) and condition (K,) to a scalar.

Examples:

At init the log-density is the standard normal's for every context:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.distributions import StandardNormal
>>> from gauss_flows_models.distributions import ConditionalDiagGaussian
>>> base = ConditionalDiagGaussian(jr.key(0), event_shape=(3,), cond_dim=2)
>>> cond = jnp.array([0.5, -0.5])
>>> x = base.sample(jr.key(1), condition=cond)
>>> x.shape
(3,)
>>> bool(jnp.allclose(base.log_prob(x, cond), StandardNormal((3,)).log_prob(x)))
True

A batch of contexts, with a bounded scale and a linear readout:

>>> base = ConditionalDiagGaussian(
...     jr.key(0), event_shape=(3,), cond_dim=2, nn_depth=0,
...     scale_map="one_plus_tanh",
... )
>>> base.log_prob(jnp.zeros((5, 3)), condition=jnp.ones((5, 2))).shape
(5,)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/conditional_diag_gaussian.py
class ConditionalDiagGaussian(AbstractDistribution):
    """Diagonal Gaussian whose location and scale are an affine modulation of noise.

    A draw is standard normal noise modulated by the context `c`,

        x = β(c) + γ(c) ⊙ ε,   ε ~ 𝒩(0, I),

    so by change of variables

        log p(x | c) = Σᵢ [log 𝒩((xᵢ − βᵢ(c)) / γᵢ(c); 0, 1) − log γᵢ(c)],

    where `(γ, log γ, β) = modulation.modulation(c)` come from the shared
    `gauss_flows_maps.conditioning.AffineModulation`. Its readout starts at zero
    weight and bias `(0, r₀)`, so `γ = 1` and `β = 0` for every `c` and the
    distribution starts as `𝒩(0, I)`.

    Args:
        key: PRNG key for the modulation's init; unused with a pre-built
            `modulation`.
        event_shape: Single-event shape `(D,)`. 1-D only.
        cond_dim: Context size `K`.
        nn_width: Width of the modulation's trunk.
        nn_depth: Number of trunk layers; `0` reads `γ` and `β` linearly from `c`.
        activation: Activation after each trunk layer.
        readout_scale: Factor on the readout's default weight; the default `0`
            makes the distribution exactly `𝒩(0, I)` at init for every `c`.
        scale_map: The positive scale map `σ` of `AffineModulation`, a map of
            `gauss_flows_maps.reparam` or one of `"exp"` (default, `γ = eʳ`),
            `"softplus"` and `"one_plus_tanh"`.
        modulation: A pre-built `AffineModulation` from `K` inputs to `D`
            features; it replaces the arguments from `nn_width` to `scale_map`.

    Raises:
        ValueError: If `event_shape` is not 1-D with a positive size, if
            `cond_dim` is not positive, if `scale_map` is `"identity"`, or if
            `modulation` has the wrong sizes.

    Shape:
        `sample`: `condition` `(K,)` to `x` `(D,)`.
        `log_prob`: `x` `(D,)` and `condition` `(K,)` to a scalar.

    Examples:
        At init the log-density is the standard normal's for every context:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from flowjax.distributions import StandardNormal
        >>> from gauss_flows_models.distributions import ConditionalDiagGaussian
        >>> base = ConditionalDiagGaussian(jr.key(0), event_shape=(3,), cond_dim=2)
        >>> cond = jnp.array([0.5, -0.5])
        >>> x = base.sample(jr.key(1), condition=cond)
        >>> x.shape
        (3,)
        >>> bool(jnp.allclose(base.log_prob(x, cond), StandardNormal((3,)).log_prob(x)))
        True

        A batch of contexts, with a bounded scale and a linear readout:

        >>> base = ConditionalDiagGaussian(
        ...     jr.key(0), event_shape=(3,), cond_dim=2, nn_depth=0,
        ...     scale_map="one_plus_tanh",
        ... )
        >>> base.log_prob(jnp.zeros((5, 3)), condition=jnp.ones((5, 2))).shape
        (5,)
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...]
    modulation: AffineModulation

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        event_shape: tuple[int, ...],
        cond_dim: int,
        nn_width: int = 64,
        nn_depth: int = 2,
        activation: Callable[[Array], Array] = jnn.tanh,
        readout_scale: float = 0.0,
        scale_map: _FlowScaleMap = "exp",
        modulation: AffineModulation | None = None,
    ):
        if len(event_shape) != 1:
            raise ValueError(
                "ConditionalDiagGaussian only supports 1D event shapes; "
                f"got {event_shape}."
            )
        if event_shape[0] < 1:
            raise ValueError(
                f"event_shape must have a positive dimension; got {event_shape}."
            )
        if cond_dim < 1:
            raise ValueError(f"cond_dim must be a positive int; got {cond_dim}.")

        self.shape = event_shape
        self.cond_shape = (cond_dim,)
        self.modulation = _flow_modulation(
            key,
            num_features=event_shape[0],
            cond_dim=cond_dim,
            nn_width=nn_width,
            nn_depth=nn_depth,
            activation=activation,
            readout_scale=readout_scale,
            scale_map=scale_map,
            modulation=modulation,
        )

    def _sample(self, key: PRNGKeyArray, condition: Array) -> Array:
        gamma, _log_gamma, beta = self.modulation.modulation(condition)
        noise = jr.normal(key, self.shape, dtype=beta.dtype)
        # x = β + gamma ⊙ ε
        return beta + gamma * noise

    def _log_prob(self, x: Array, condition: Array) -> Array:
        gamma, log_gamma, beta = self.modulation.modulation(condition)
        # ε = (x - β) / gamma
        noise = (x - beta) / gamma
        # log p = Σ [-½ (ε² + log 2π) - log gamma]
        return jnp.sum(-0.5 * (noise * noise + _LOG_2PI) - log_gamma)

ClassCondDiagGaussian

Bases: AbstractDistribution

Class-conditional diagonal Gaussian with learned per-class parameters.

Stores a (n_classes, *event_shape) lookup table for the means (when learn_mean=True) and another for the raw log-scales. The effective log-scale is log_scale_raw[idx] * logscale_factor; the multiplicative factor matches the Glow stabilisation trick (Kingma & Dhariwal 2018) where small stored values keep the effective scales well-conditioned at init.

The condition is a scalar integer class label (cond_shape = ()). Out-of-range indices follow JAX gather semantics — the caller is responsible for passing in-range labels.

Parameters:

Name Type Description Default
key PRNGKeyArray

PRNG key. Currently unused (parameters are deterministically initialised); accepted to match the constructor convention used by other learnable bases in this package.

required
n_classes int

Number of classes C (must be positive).

required
event_shape tuple[int, ...]

Single-event shape (any rank).

required
learn_mean bool

If False, the per-class mean is frozen at zero. (Glow uses False in some configurations.)

True
logscale_factor float

Multiplicative factor applied to log_scale_raw before exponentiation. Default 1.0 (no-op). Use 3.0 to recover the canonical Glow base.

1.0
Shape
  • Condition: () (scalar int)
  • Sample / log_prob input: event_shape
  • log_prob output: scalar ()
Glow recipe

ClassCondDiagGaussian(key, n_classes=10, event_shape=(D,), learn_mean=False, logscale_factor=3.0)

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import ClassCondDiagGaussian
>>> base = ClassCondDiagGaussian(jr.key(0), n_classes=4, event_shape=(3,))
>>> label = jnp.int32(2)
>>> x = base.sample(jr.key(1), condition=label)
>>> log_p = base.log_prob(x, condition=label)
>>> assert x.shape == (3,) and log_p.shape == ()
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/class_cond_diag_gaussian.py
class ClassCondDiagGaussian(AbstractDistribution):
    """Class-conditional diagonal Gaussian with learned per-class parameters.

    Stores a ``(n_classes, *event_shape)`` lookup table for the means
    (when ``learn_mean=True``) and another for the raw log-scales. The
    effective log-scale is ``log_scale_raw[idx] * logscale_factor``; the
    multiplicative factor matches the Glow stabilisation trick (Kingma &
    Dhariwal 2018) where small stored values keep the effective scales
    well-conditioned at init.

    The condition is a **scalar** integer class label (``cond_shape = ()``).
    Out-of-range indices follow JAX gather semantics — the caller is
    responsible for passing in-range labels.

    Args:
        key: PRNG key. Currently unused (parameters are deterministically
            initialised); accepted to match the constructor convention used
            by other learnable bases in this package.
        n_classes: Number of classes ``C`` (must be positive).
        event_shape: Single-event shape (any rank).
        learn_mean: If ``False``, the per-class mean is frozen at zero.
            (Glow uses ``False`` in some configurations.)
        logscale_factor: Multiplicative factor applied to ``log_scale_raw``
            before exponentiation. Default ``1.0`` (no-op). Use ``3.0`` to
            recover the canonical Glow base.

    Shape:
        - Condition: ``()`` (scalar int)
        - Sample / log_prob input: ``event_shape``
        - log_prob output: scalar ``()``

    Glow recipe:
        ``ClassCondDiagGaussian(key, n_classes=10, event_shape=(D,),
        learn_mean=False, logscale_factor=3.0)``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import ClassCondDiagGaussian
        >>> base = ClassCondDiagGaussian(jr.key(0), n_classes=4, event_shape=(3,))
        >>> label = jnp.int32(2)
        >>> x = base.sample(jr.key(1), condition=label)
        >>> log_p = base.log_prob(x, condition=label)
        >>> assert x.shape == (3,) and log_p.shape == ()
    """

    shape: tuple[int, ...]
    cond_shape: tuple[int, ...] = eqx.field(static=True)
    n_classes: int = eqx.field(static=True)
    learn_mean: bool = eqx.field(static=True)
    logscale_factor: float = eqx.field(static=True)
    loc: Array
    log_scale_raw: Array

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        n_classes: int,
        event_shape: tuple[int, ...],
        learn_mean: bool = True,
        logscale_factor: float = 1.0,
    ):
        del key  # parameters are deterministically initialised
        if n_classes < 1:
            raise ValueError(f"n_classes must be positive; got {n_classes}.")
        if any(d < 1 for d in event_shape):
            raise ValueError(
                f"event_shape entries must be positive; got {event_shape}."
            )
        if logscale_factor <= 0.0:
            raise ValueError(
                f"logscale_factor must be positive; got {logscale_factor}."
            )

        self.shape = tuple(event_shape)
        self.cond_shape = ()
        self.n_classes = int(n_classes)
        self.learn_mean = bool(learn_mean)
        self.logscale_factor = float(logscale_factor)
        self.loc = jnp.zeros((self.n_classes, *self.shape))
        self.log_scale_raw = jnp.zeros((self.n_classes, *self.shape))

    def _resolve_params(self, condition: ArrayLike) -> tuple[Array, Array]:
        idx = jnp.asarray(condition, dtype=jnp.int32)
        # flowjax's AbstractDistribution decorator does not currently enforce
        # ``condition.shape == ()`` for scalar cond_shapes, so a non-scalar
        # condition here would silently gather multiple rows and produce a
        # batched (loc, log_scale) — breaking the single-event contract.
        if idx.shape != ():
            raise ValueError(
                "ClassCondDiagGaussian expects a scalar integer class label "
                f"(condition.shape == ()); got shape {idx.shape}. For batched "
                "labels wrap the call in jax.vmap."
            )
        log_scale = self.log_scale_raw[idx] * self.logscale_factor
        if self.learn_mean:
            loc = self.loc[idx]
        else:
            loc = jnp.zeros(self.shape, dtype=log_scale.dtype)
        return loc, log_scale

    def _sample(self, key: PRNGKeyArray, condition: ArrayLike) -> Array:
        loc, log_scale = self._resolve_params(condition)
        z = jr.normal(key, self.shape, dtype=loc.dtype)
        return loc + jnp.exp(log_scale) * z

    def _log_prob(self, x: Array, condition: ArrayLike) -> Array:
        loc, log_scale = self._resolve_params(condition)
        z = (x - loc) * jnp.exp(-log_scale)
        return -0.5 * jnp.sum(z * z + 2.0 * log_scale + _LOG_2PI)

State-space bases

LinearGaussianSSM is the distribution of a whole series \(y_{1:T}\) under a linear-Gaussian state-space model, \(s_t = A_t s_{t-1} + q_t\) and \(y_t = H_t s_t + v_t\) with \(q_t \sim \mathcal{N}(0, Q_t)\) and \(v_t \sim \mathcal{N}(0, R_t)\). Its event shape is \((T, M)\) and its log_prob is the marginal likelihood \(\log p(y_{1:T})\) computed by gaussx.kalman_filter, in \(O(T N^3)\) for a state of size \(N\). Each matrix is shared by all steps or stacked over time. With masked=True it takes a boolean \((T, M)\) observation mask as its condition and scores only the observed entries, which is the masked base normalizing_kalman_filter expects. LinearGaussianSSM.from_sde builds the Gaussian process of a gaussx SDEKernel (such as gaussx.MaternSDE) at irregular times, so its density equals \(\mathcal{N}(y; 0, K + \sigma_v^2 I)\) with \(K\) the kernel matrix at those times.

LinearGaussianSSM

Bases: AbstractDistribution

p(y_1:T) of a linear-Gaussian state-space model; event shape (T, M).

s_t = A_t s_{t−1} + q_t,   q_t ~ 𝒩(0, Q_t)
y_t = H_t s_t + v_t,       v_t ~ 𝒩(0, R_t)

with s_0 ~ 𝒩(m₀, P₀), a state s_t ∈ ℝᴺ, an observation y_t ∈ ℝᴹ and t = 1, …, T. The density is log p(y_1:T), the log_likelihood of gaussx.kalman_filter. The filter predicts before each update, so row 0 of an event is y₁, scored against A₁ s₀ rather than against s₀.

Each of A_t, H_t, Q_t and R_t is either one matrix shared by every step or a stack over the T steps (a time-varying model). The matrices are plain array leaves, so they train; keeping Q_t, R_t and P₀ positive semi-definite is the caller's job (for instance through gauss_flows_maps.reparam.CholeskyFactor).

With masked=True the distribution consumes a boolean observation mask of shape (T, M) as its condition, and log_prob is the exact marginal log p(y_obs) over the entries where the mask is true; masked entries are never read, so they may hold NaN. A non-None cond_shape is how gauss_flows_models.filters.normalizing_kalman_filter recognises a masked base. Sampling ignores the mask and draws every entry, which is the model's imputation of the unobserved ones.

Parameters:

Name Type Description Default
transition ArrayLike

Dynamics A_t, (N, N) or (T, N, N).

required
obs_model ArrayLike

Observation operator H_t, (M, N) or (T, M, N).

required
process_noise ArrayLike

Process-noise covariance Q_t, (N, N) or (T, N, N).

required
obs_noise ArrayLike

Observation-noise covariance R_t, (M, M) or (T, M, M).

required
init_mean ArrayLike

Prior mean m₀ of s₀, (N,).

required
init_cov ArrayLike

Prior covariance P₀ of s₀, (N, N).

required
n_steps int

Number of steps T.

required
masked bool

Whether the distribution consumes an observation mask of shape (T, M) as its condition. Defaults to False.

False

Raises:

Type Description
ValueError

If n_steps is not positive, or if a matrix has the wrong rank, a leading time axis other than n_steps, or sizes that disagree with N (from init_mean) or M (from obs_model).

Shape
  • log_prob: (T, M) → scalar, with condition (T, M) when masked
  • sample(key, sample_shape): (*sample_shape, T, M)

Examples:

A damped random walk in four channels, observed with noise:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import LinearGaussianSSM
>>> ssm = LinearGaussianSSM(
...     transition=0.9 * jnp.eye(4), obs_model=jnp.eye(4),
...     process_noise=0.1 * jnp.eye(4), obs_noise=0.1 * jnp.eye(4),
...     init_mean=jnp.zeros(4), init_cov=jnp.eye(4), n_steps=8,
... )
>>> y = ssm.sample(jr.key(0), (3,))
>>> y.shape, ssm.log_prob(y).shape
((3, 8, 4), (3,))

The masked form marginalises the entries where the mask is false:

>>> masked = LinearGaussianSSM(
...     transition=0.9 * jnp.eye(4), obs_model=jnp.eye(4),
...     process_noise=0.1 * jnp.eye(4), obs_noise=0.1 * jnp.eye(4),
...     init_mean=jnp.zeros(4), init_cov=jnp.eye(4), n_steps=8,
...     masked=True,
... )
>>> mask = jr.bernoulli(jr.key(1), 0.7, (8, 4))
>>> masked.cond_shape, masked.log_prob(y[0], condition=mask).shape
((8, 4), ())
References

Särkkä, S. and Svensson, L. (2023). Bayesian Filtering and Smoothing, 2nd edition. Cambridge University Press.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/linear_gaussian_ssm.py
class LinearGaussianSSM(AbstractDistribution):
    """p(y_1:T) of a linear-Gaussian state-space model; event shape (T, M).

        s_t = A_t s_{t−1} + q_t,   q_t ~ 𝒩(0, Q_t)
        y_t = H_t s_t + v_t,       v_t ~ 𝒩(0, R_t)

    with s_0 ~ 𝒩(m₀, P₀), a state s_t ∈ ℝᴺ, an observation y_t ∈ ℝᴹ and
    t = 1, …, T. The density is log p(y_1:T), the ``log_likelihood`` of
    `gaussx.kalman_filter`. The filter predicts before each update, so row 0
    of an event is y₁, scored against A₁ s₀ rather than against s₀.

    Each of A_t, H_t, Q_t and R_t is either one matrix shared by every step or
    a stack over the T steps (a time-varying model). The matrices are plain
    array leaves, so they train; keeping Q_t, R_t and P₀ positive
    semi-definite is the caller's job (for instance through
    `gauss_flows_maps.reparam.CholeskyFactor`).

    With ``masked=True`` the distribution consumes a boolean observation mask
    of shape (T, M) as its ``condition``, and ``log_prob`` is the exact
    marginal log p(y_obs) over the entries where the mask is true; masked
    entries are never read, so they may hold ``NaN``. A non-``None``
    ``cond_shape`` is how `gauss_flows_models.filters.normalizing_kalman_filter`
    recognises a masked base. Sampling ignores the mask and draws every entry,
    which is the model's imputation of the unobserved ones.

    Args:
        transition: Dynamics A_t, (N, N) or (T, N, N).
        obs_model: Observation operator H_t, (M, N) or (T, M, N).
        process_noise: Process-noise covariance Q_t, (N, N) or (T, N, N).
        obs_noise: Observation-noise covariance R_t, (M, M) or (T, M, M).
        init_mean: Prior mean m₀ of s₀, (N,).
        init_cov: Prior covariance P₀ of s₀, (N, N).
        n_steps: Number of steps T.
        masked: Whether the distribution consumes an observation mask of shape
            (T, M) as its condition. Defaults to ``False``.

    Raises:
        ValueError: If ``n_steps`` is not positive, or if a matrix has the
            wrong rank, a leading time axis other than ``n_steps``, or sizes
            that disagree with N (from ``init_mean``) or M (from
            ``obs_model``).

    Shape:
        - ``log_prob``: (T, M) → scalar, with condition (T, M) when masked
        - ``sample(key, sample_shape)``: (*sample_shape, T, M)

    Examples:
        A damped random walk in four channels, observed with noise:

        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import LinearGaussianSSM
        >>> ssm = LinearGaussianSSM(
        ...     transition=0.9 * jnp.eye(4), obs_model=jnp.eye(4),
        ...     process_noise=0.1 * jnp.eye(4), obs_noise=0.1 * jnp.eye(4),
        ...     init_mean=jnp.zeros(4), init_cov=jnp.eye(4), n_steps=8,
        ... )
        >>> y = ssm.sample(jr.key(0), (3,))
        >>> y.shape, ssm.log_prob(y).shape
        ((3, 8, 4), (3,))

        The masked form marginalises the entries where the mask is false:

        >>> masked = LinearGaussianSSM(
        ...     transition=0.9 * jnp.eye(4), obs_model=jnp.eye(4),
        ...     process_noise=0.1 * jnp.eye(4), obs_noise=0.1 * jnp.eye(4),
        ...     init_mean=jnp.zeros(4), init_cov=jnp.eye(4), n_steps=8,
        ...     masked=True,
        ... )
        >>> mask = jr.bernoulli(jr.key(1), 0.7, (8, 4))
        >>> masked.cond_shape, masked.log_prob(y[0], condition=mask).shape
        ((8, 4), ())

    References:
        Särkkä, S. and Svensson, L. (2023). Bayesian Filtering and Smoothing,
        2nd edition. Cambridge University Press.
    """

    transition: Array
    obs_model: Array
    process_noise: Array
    obs_noise: Array
    init_mean: Array
    init_cov: Array
    shape: tuple[int, int] = eqx.field(static=True)
    cond_shape: tuple[int, int] | None = eqx.field(static=True)

    def __init__(
        self,
        transition: ArrayLike,
        obs_model: ArrayLike,
        process_noise: ArrayLike,
        obs_noise: ArrayLike,
        init_mean: ArrayLike,
        init_cov: ArrayLike,
        *,
        n_steps: int,
        masked: bool = False,
    ):
        if n_steps < 1:
            raise ValueError(f"n_steps must be positive; got {n_steps}.")
        init_mean = jnp.asarray(init_mean)
        obs_model = jnp.asarray(obs_model)
        if init_mean.ndim != 1:
            raise ValueError(f"init_mean must have shape (N,); got {init_mean.shape}.")
        if obs_model.ndim not in (2, 3):
            raise ValueError(
                f"obs_model must have shape (M, N) or (T, M, N); got {obs_model.shape}."
            )
        state_size = init_mean.shape[0]
        obs_size = obs_model.shape[-2]

        # Each matrix: its name, its value and the trailing (rows, cols) it needs.
        expected = {
            "transition": (transition, (state_size, state_size)),
            "obs_model": (obs_model, (obs_size, state_size)),
            "process_noise": (process_noise, (state_size, state_size)),
            "obs_noise": (obs_noise, (obs_size, obs_size)),
        }
        matrices = {}
        for name, (value, trailing) in expected.items():
            array = jnp.asarray(value)
            allowed = (trailing, (n_steps, *trailing))
            if array.shape not in allowed:
                raise ValueError(
                    f"{name} must have shape {trailing} (time-invariant) or "
                    f"{(n_steps, *trailing)} (time-varying, n_steps={n_steps}); "
                    f"got {array.shape}."
                )
            matrices[name] = array
        init_cov = jnp.asarray(init_cov)
        if init_cov.shape != (state_size, state_size):
            raise ValueError(
                f"init_cov must have shape {(state_size, state_size)}; got "
                f"{init_cov.shape}."
            )

        self.transition = matrices["transition"]
        self.obs_model = matrices["obs_model"]
        self.process_noise = matrices["process_noise"]
        self.obs_noise = matrices["obs_noise"]
        self.init_mean = init_mean
        self.init_cov = init_cov
        self.shape = (n_steps, obs_size)
        self.cond_shape = (n_steps, obs_size) if masked else None

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        # FlowJax hands the condition over as floats; the filter wants booleans.
        mask = None if condition is None else condition.astype(bool)
        # log p(y_1:T) = ∑_t log 𝒩(y_t; H_t m_t|t−1, H_t P_t|t−1 H_tᵀ + R_t)
        state = gx.kalman_filter(
            self.transition,
            self.obs_model,
            self.process_noise,
            self.obs_noise,
            x,
            self.init_mean,
            self.init_cov,
            mask=mask,
        )
        return state.log_likelihood

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        n_steps = self.shape[0]

        def _over_time(matrix: Array) -> Array:
            # (rows, cols) or (T, rows, cols) -> (T, rows, cols)
            return jnp.broadcast_to(matrix, (n_steps, *matrix.shape[-2:]))

        # Roots before broadcasting: a time-invariant Q or R is factored once.
        transitions = _over_time(self.transition)
        obs_models = _over_time(self.obs_model)
        process_roots = _over_time(_psd_sqrt(self.process_noise))
        obs_roots = _over_time(_psd_sqrt(self.obs_noise))

        init_key, step_key = jr.split(key)
        # s₀ = m₀ + P₀^½ ε,  ε ~ 𝒩(0, I)
        init_noise = jr.normal(init_key, self.init_mean.shape, self.init_mean.dtype)
        init_state = self.init_mean + _psd_sqrt(self.init_cov) @ init_noise
        step_keys = jr.split(step_key, n_steps)

        def step(previous_state, inputs):
            transition, obs_model, process_root, obs_root, step_key = inputs
            state_key, obs_key = jr.split(step_key)
            state_noise = jr.normal(state_key, previous_state.shape, init_state.dtype)
            # s_t = A_t s_{t−1} + Q_t^½ ε_t
            state = transition @ previous_state + process_root @ state_noise
            obs_noise = jr.normal(obs_key, (obs_model.shape[0],), init_state.dtype)
            # y_t = H_t s_t + R_t^½ ν_t
            observation = obs_model @ state + obs_root @ obs_noise
            return state, observation

        inputs = (transitions, obs_models, process_roots, obs_roots, step_keys)
        _, observations = jax.lax.scan(step, init_state, inputs)  # (T, M)
        return observations

    @classmethod
    def from_sde(
        cls,
        kernel: gx.SDEKernel,
        times: ArrayLike,
        obs_noise: ArrayLike,
        *,
        masked: bool = False,
    ) -> LinearGaussianSSM:
        """A Gaussian process at ``times`` from a gaussx SDE kernel; event (T, 1).

            y = f(t_1:T) + v,   f ~ 𝒢𝒫(0, k),   v ~ 𝒩(0, σ_v² I)

        The kernel's continuous-time SDE is discretised over the gaps
        Δ_t = t_t − t_{t−1} by ``kernel.discretise_sequence``, giving (A_t,
        Q_t) for t = 2, …, T. The first observation sees the stationary prior
        directly, so A₁ = I and Q₁ = 0 (the convention `gaussx.kalman_filter`
        gives for observing the prior at the first step), with m₀ = 0,
        P₀ = Σ_∞ from ``kernel.initial_covariance()``, H from
        ``kernel.sde_params().H`` and R = σ_v² I. The result is the Gaussian
        process whose covariance at ``times`` is the kernel matrix, evaluated
        in O(T N³) for a state of size N rather than O(T³).

        Args:
            kernel: A stationary gaussx `SDEKernel`, such as
                ``gaussx.MaternSDE(variance=1.0, lengthscale=5.0, order=1)``.
            times: Observation times t_1:T, sorted increasing, (T,).
            obs_noise: Observation-noise variance σ_v², a scalar.
            masked: Whether the result consumes an observation mask of shape
                (T, 1) as its condition. Defaults to ``False``.

        Returns:
            A `LinearGaussianSSM` with event shape (T, 1).

        Raises:
            ValueError: If ``times`` is not one-dimensional and non-empty, or
                if ``obs_noise`` is not a scalar.

        Shape:
            - ``times``: (T,)
            - Returned event: (T, 1)

        Examples:
            A Matérn-3/2 process at eight irregular times, observed with
            noise variance 0.01:

            >>> import gaussx as gx
            >>> import jax.numpy as jnp
            >>> import jax.random as jr
            >>> from gauss_flows_models.distributions import LinearGaussianSSM
            >>> times = jnp.sort(jr.uniform(jr.key(2), (8,)) * 30.0)
            >>> kernel = gx.MaternSDE(variance=1.0, lengthscale=5.0, order=1)
            >>> gp = LinearGaussianSSM.from_sde(kernel, times, obs_noise=0.01)
            >>> gp.shape, gp.log_prob(gp.sample(jr.key(3))).shape
            ((8, 1), ())

        References:
            Särkkä, S. and Solin, A. (2019). Applied Stochastic Differential
            Equations. Cambridge University Press.
        """
        times = jnp.asarray(times)
        if times.ndim != 1 or times.shape[0] < 1:
            raise ValueError(
                f"times must have shape (T,) with T ≥ 1; got {times.shape}."
            )
        obs_noise = jnp.asarray(obs_noise)
        if obs_noise.ndim != 0:
            raise ValueError(
                f"obs_noise must be a scalar variance; got shape {obs_noise.shape}."
            )

        # Δ_t = t_t − t_{t−1} for t = 2, …, T
        gaps = jnp.diff(times)  # (T − 1,)
        later_transitions, later_noises = kernel.discretise_sequence(gaps)
        stationary_cov = kernel.initial_covariance()  # (N, N)
        state_size = stationary_cov.shape[0]
        dtype = stationary_cov.dtype
        # A₁ = I and Q₁ = 0: the first observation sees s₀ ~ 𝒩(0, Σ_∞) itself.
        first_transition = jnp.eye(state_size, dtype=dtype)[None]  # (1, N, N)
        first_noise = jnp.zeros((1, state_size, state_size), dtype=dtype)
        transitions = jnp.concatenate([first_transition, later_transitions])
        process_noises = jnp.concatenate([first_noise, later_noises])  # (T, N, N)

        obs_operator = kernel.sde_params().H  # (1, N)
        # R = σ_v² I
        obs_covariance = obs_noise.astype(dtype) * jnp.eye(1, dtype=dtype)
        return cls(
            transitions,
            obs_operator,
            process_noises,
            obs_covariance,
            jnp.zeros(state_size, dtype=dtype),
            stationary_cov,
            n_steps=times.shape[0],
            masked=masked,
        )

from_sde classmethod

from_sde(kernel: SDEKernel, times: ArrayLike, obs_noise: ArrayLike, *, masked: bool = False) -> LinearGaussianSSM

A Gaussian process at times from a gaussx SDE kernel; event (T, 1).

y = f(t_1:T) + v,   f ~ 𝒢𝒫(0, k),   v ~ 𝒩(0, σ_v² I)

The kernel's continuous-time SDE is discretised over the gaps Δ_t = t_t − t_{t−1} by kernel.discretise_sequence, giving (A_t, Q_t) for t = 2, …, T. The first observation sees the stationary prior directly, so A₁ = I and Q₁ = 0 (the convention gaussx.kalman_filter gives for observing the prior at the first step), with m₀ = 0, P₀ = Σ_∞ from kernel.initial_covariance(), H from kernel.sde_params().H and R = σ_v² I. The result is the Gaussian process whose covariance at times is the kernel matrix, evaluated in O(T N³) for a state of size N rather than O(T³).

Parameters:

Name Type Description Default
kernel SDEKernel

A stationary gaussx SDEKernel, such as gaussx.MaternSDE(variance=1.0, lengthscale=5.0, order=1).

required
times ArrayLike

Observation times t_1:T, sorted increasing, (T,).

required
obs_noise ArrayLike

Observation-noise variance σ_v², a scalar.

required
masked bool

Whether the result consumes an observation mask of shape (T, 1) as its condition. Defaults to False.

False

Returns:

Type Description
LinearGaussianSSM

A LinearGaussianSSM with event shape (T, 1).

Raises:

Type Description
ValueError

If times is not one-dimensional and non-empty, or if obs_noise is not a scalar.

Shape
  • times: (T,)
  • Returned event: (T, 1)

Examples:

A Matérn-3/2 process at eight irregular times, observed with noise variance 0.01:

>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import LinearGaussianSSM
>>> times = jnp.sort(jr.uniform(jr.key(2), (8,)) * 30.0)
>>> kernel = gx.MaternSDE(variance=1.0, lengthscale=5.0, order=1)
>>> gp = LinearGaussianSSM.from_sde(kernel, times, obs_noise=0.01)
>>> gp.shape, gp.log_prob(gp.sample(jr.key(3))).shape
((8, 1), ())
References

Särkkä, S. and Solin, A. (2019). Applied Stochastic Differential Equations. Cambridge University Press.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/linear_gaussian_ssm.py
@classmethod
def from_sde(
    cls,
    kernel: gx.SDEKernel,
    times: ArrayLike,
    obs_noise: ArrayLike,
    *,
    masked: bool = False,
) -> LinearGaussianSSM:
    """A Gaussian process at ``times`` from a gaussx SDE kernel; event (T, 1).

        y = f(t_1:T) + v,   f ~ 𝒢𝒫(0, k),   v ~ 𝒩(0, σ_v² I)

    The kernel's continuous-time SDE is discretised over the gaps
    Δ_t = t_t − t_{t−1} by ``kernel.discretise_sequence``, giving (A_t,
    Q_t) for t = 2, …, T. The first observation sees the stationary prior
    directly, so A₁ = I and Q₁ = 0 (the convention `gaussx.kalman_filter`
    gives for observing the prior at the first step), with m₀ = 0,
    P₀ = Σ_∞ from ``kernel.initial_covariance()``, H from
    ``kernel.sde_params().H`` and R = σ_v² I. The result is the Gaussian
    process whose covariance at ``times`` is the kernel matrix, evaluated
    in O(T N³) for a state of size N rather than O(T³).

    Args:
        kernel: A stationary gaussx `SDEKernel`, such as
            ``gaussx.MaternSDE(variance=1.0, lengthscale=5.0, order=1)``.
        times: Observation times t_1:T, sorted increasing, (T,).
        obs_noise: Observation-noise variance σ_v², a scalar.
        masked: Whether the result consumes an observation mask of shape
            (T, 1) as its condition. Defaults to ``False``.

    Returns:
        A `LinearGaussianSSM` with event shape (T, 1).

    Raises:
        ValueError: If ``times`` is not one-dimensional and non-empty, or
            if ``obs_noise`` is not a scalar.

    Shape:
        - ``times``: (T,)
        - Returned event: (T, 1)

    Examples:
        A Matérn-3/2 process at eight irregular times, observed with
        noise variance 0.01:

        >>> import gaussx as gx
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import LinearGaussianSSM
        >>> times = jnp.sort(jr.uniform(jr.key(2), (8,)) * 30.0)
        >>> kernel = gx.MaternSDE(variance=1.0, lengthscale=5.0, order=1)
        >>> gp = LinearGaussianSSM.from_sde(kernel, times, obs_noise=0.01)
        >>> gp.shape, gp.log_prob(gp.sample(jr.key(3))).shape
        ((8, 1), ())

    References:
        Särkkä, S. and Solin, A. (2019). Applied Stochastic Differential
        Equations. Cambridge University Press.
    """
    times = jnp.asarray(times)
    if times.ndim != 1 or times.shape[0] < 1:
        raise ValueError(
            f"times must have shape (T,) with T ≥ 1; got {times.shape}."
        )
    obs_noise = jnp.asarray(obs_noise)
    if obs_noise.ndim != 0:
        raise ValueError(
            f"obs_noise must be a scalar variance; got shape {obs_noise.shape}."
        )

    # Δ_t = t_t − t_{t−1} for t = 2, …, T
    gaps = jnp.diff(times)  # (T − 1,)
    later_transitions, later_noises = kernel.discretise_sequence(gaps)
    stationary_cov = kernel.initial_covariance()  # (N, N)
    state_size = stationary_cov.shape[0]
    dtype = stationary_cov.dtype
    # A₁ = I and Q₁ = 0: the first observation sees s₀ ~ 𝒩(0, Σ_∞) itself.
    first_transition = jnp.eye(state_size, dtype=dtype)[None]  # (1, N, N)
    first_noise = jnp.zeros((1, state_size, state_size), dtype=dtype)
    transitions = jnp.concatenate([first_transition, later_transitions])
    process_noises = jnp.concatenate([first_noise, later_noises])  # (T, N, N)

    obs_operator = kernel.sde_params().H  # (1, N)
    # R = σ_v² I
    obs_covariance = obs_noise.astype(dtype) * jnp.eye(1, dtype=dtype)
    return cls(
        transitions,
        obs_operator,
        process_noises,
        obs_covariance,
        jnp.zeros(state_size, dtype=dtype),
        stationary_cov,
        n_steps=times.shape[0],
        masked=masked,
    )

Gaussian Markov random fields

GMRFBase wraps one of gaussx's Gaussian Markov random fields (GaussianMRF, IntrinsicGMRF, BYM2GMRF or ConstrainedGMRF), \(x \sim \mathcal{N}(\mu, \Lambda^{-1})\) with a sparse or structured precision \(\Lambda\), so that a flow over a gridded field starts from a Matérn or AR(1) field and its bijections only learn what the Gaussian field cannot express. log_prob and sample are the field's, so they use whatever structure the precision has; the field's array leaves (\(\mu\) and the arrays inside \(\Lambda\), such as \(\kappa\) and \(\tau\)) are trainable like any other flow parameter. An intrinsic field is improper and is a valid base only on its constrained subspace, so GMRFBase raises ValueError for an IntrinsicGMRF or BYM2GMRF with constraint="none". GaussianFieldLike is the Protocol that says what the wrapper uses: an event_shape, log_prob and sample.

A Matérn field on a regular grid solves \((\kappa^2 - \Delta)^{\alpha/2}\, \tau\, x = \mathcal{W}\) (Lindgren, Rue and Lindström, 2011), and gaussx's spde_precision_grid builds its precision; an AR(1) chain comes from ar1_precision. Here the field is a Matérn field on a 64 × 64 grid (\(\alpha = 2\), \(\kappa = 0.2\) per cell, \(\tau = 1\)), the base of a flow over the flattened grid:

import gaussx as gx
import jax.numpy as jnp
import jax.random as jr
from flowjax.bijections import Affine
from flowjax.distributions import Transformed
from gauss_flows_models.distributions import GMRFBase

# Λ: Matérn SPDE precision on the grid, as an operator on the 4096 cells
precision = gx.spde_precision_grid((64, 64), kappa=0.2, tau=1.0, alpha=2)

# x ~ 𝒩(0, Λ⁻¹), the base of a flow over the grid; event shape (4096,)
base = GMRFBase(gx.GaussianMRF(jnp.zeros(64 * 64), precision))

# a flow whose bijections learn what the Gaussian field cannot express
flow = Transformed(base, Affine(jnp.zeros(64 * 64), jnp.ones(64 * 64)))
samples = flow.sample(jr.key(0), (4,))  # (4, 4096)
log_prob = flow.log_prob(samples)  # (4,)

GMRFBase

Bases: AbstractDistribution

A flow base over a gaussx Gaussian Markov random field.

The base is the field x ~ 𝒩(μ, Λ⁻¹) with a sparse or structured precision Λ,

log p(x) = ½ log det Λ − ½ (x − μ)ᵀ Λ (x − μ) − ½ N log 2π,

and both log_prob and sample are the wrapped field's, so they use whatever structure its precision has (a sparse or dense factorisation, per-factor eigenvalues for a Kronecker-structured Λ such as gaussx.spde_precision_grid, or matrix-free perturbation-optimisation). The field's array leaves (μ, and the arrays inside its precision such as κ and τ) are trainable like any other flow parameter. An intrinsic field is improper, so it is a valid base only on its constrained subspace: IntrinsicGMRF (and BYM2GMRF, its subclass) with constraint="none" is refused.

Parameters:

Name Type Description Default
field GaussianFieldLike

A gaussx GaussianMRF, IntrinsicGMRF, BYM2GMRF or ConstrainedGMRF, or any object with an event_shape, log_prob and sample (see GaussianFieldLike).

required

Raises:

Type Description
ValueError

If field is an IntrinsicGMRF or BYM2GMRF with constraint="none", which has no proper density.

ValueError

If field.event_shape is not one-dimensional.

Shape
  • log_prob: (N,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, N)

Examples:

A Matérn field on a 16 × 16 grid (α = 2, κ = 0.2 per cell, τ = 1) as the base of a flow over the flattened grid:

>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import GMRFBase
>>> precision = gx.spde_precision_grid((16, 16), kappa=0.2, tau=1.0, alpha=2)
>>> base = GMRFBase(gx.GaussianMRF(jnp.zeros(16 * 16), precision))
>>> base.sample(jr.key(0), (3,)).shape
(3, 256)
>>> base.log_prob(jnp.zeros(256)).shape
()

Inside a flow, through FlowJax's Transformed:

>>> from flowjax.bijections import Affine
>>> from flowjax.distributions import Transformed
>>> flow = Transformed(base, Affine(jnp.zeros(256), 2.0 * jnp.ones(256)))
>>> flow.log_prob(jnp.zeros(256)).shape
()
References

Lindgren, Rue and Lindström 2011, An explicit link between Gaussian fields and Gaussian Markov random fields: the stochastic partial differential equation approach, JRSS B 73(4), 423–498.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/gmrf.py
class GMRFBase(AbstractDistribution):
    """A flow base over a gaussx Gaussian Markov random field.

    The base is the field x ~ 𝒩(μ, Λ⁻¹) with a sparse or structured precision Λ,

        log p(x) = ½ log det Λ − ½ (x − μ)ᵀ Λ (x − μ) − ½ N log 2π,

    and both `log_prob` and `sample` are the wrapped field's, so they use
    whatever structure its precision has (a sparse or dense factorisation,
    per-factor eigenvalues for a Kronecker-structured Λ such as
    `gaussx.spde_precision_grid`, or matrix-free perturbation-optimisation).
    The field's array leaves (μ, and the arrays inside its precision such as κ
    and τ) are trainable like any other flow parameter. An intrinsic field is
    improper, so it is a valid base only on its constrained subspace:
    `IntrinsicGMRF` (and `BYM2GMRF`, its subclass) with ``constraint="none"``
    is refused.

    Args:
        field: A gaussx `GaussianMRF`, `IntrinsicGMRF`, `BYM2GMRF` or
            `ConstrainedGMRF`, or any object with an ``event_shape``,
            ``log_prob`` and ``sample`` (see `GaussianFieldLike`).

    Raises:
        ValueError: If ``field`` is an `IntrinsicGMRF` or `BYM2GMRF` with
            ``constraint="none"``, which has no proper density.
        ValueError: If ``field.event_shape`` is not one-dimensional.

    Shape:
        - log_prob: ``(N,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, N)``

    Examples:
        A Matérn field on a 16 × 16 grid (α = 2, κ = 0.2 per cell, τ = 1) as the
        base of a flow over the flattened grid:

        >>> import gaussx as gx
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import GMRFBase
        >>> precision = gx.spde_precision_grid((16, 16), kappa=0.2, tau=1.0, alpha=2)
        >>> base = GMRFBase(gx.GaussianMRF(jnp.zeros(16 * 16), precision))
        >>> base.sample(jr.key(0), (3,)).shape
        (3, 256)
        >>> base.log_prob(jnp.zeros(256)).shape
        ()

        Inside a flow, through FlowJax's `Transformed`:

        >>> from flowjax.bijections import Affine
        >>> from flowjax.distributions import Transformed
        >>> flow = Transformed(base, Affine(jnp.zeros(256), 2.0 * jnp.ones(256)))
        >>> flow.log_prob(jnp.zeros(256)).shape
        ()

    References:
        Lindgren, Rue and Lindström 2011, *An explicit link between Gaussian
        fields and Gaussian Markov random fields: the stochastic partial
        differential equation approach*, JRSS B 73(4), 423–498.
    """

    field: GaussianFieldLike
    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None

    def __init__(self, field: GaussianFieldLike):
        if isinstance(field, gx.IntrinsicGMRF) and field.constraint == "none":
            raise ValueError(
                f"{type(field).__name__} with constraint='none' is improper and has "
                "no density to use as a base: pass constraint='soft' or 'hard', "
                "which restrict the field to a proper subspace."
            )
        event_shape = tuple(field.event_shape)
        if len(event_shape) != 1:
            raise ValueError(
                f"field.event_shape must be one-dimensional (N,), got {event_shape}."
            )
        self.field = field
        self.shape = event_shape

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        return self.field.log_prob(x)

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        return self.field.sample(key)

GaussianFieldLike

Bases: Protocol

What GMRFBase uses of a Gaussian field.

The three members are an event shape, log_prob and sample.

gaussx's GaussianMRF, IntrinsicGMRF, BYM2GMRF and ConstrainedGMRF all fit; they share no base class, so the wrapper types them structurally.

Shape
  • event_shape: (N,)
  • log_prob: (*sample, N) → (*sample,)
  • sample: (key, sample_shape) → (*sample_shape, N)

Examples:

>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> from gauss_flows_models.distributions import GaussianFieldLike
>>> precision = gx.spde_precision_grid((4, 4), kappa=0.5, tau=1.0, alpha=2)
>>> field = gx.GaussianMRF(jnp.zeros(16), precision)
>>> isinstance(field, GaussianFieldLike)
True
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/gmrf.py
@runtime_checkable
class GaussianFieldLike(Protocol):
    """What `GMRFBase` uses of a Gaussian field.

    The three members are an event shape, `log_prob` and `sample`.

    gaussx's `GaussianMRF`, `IntrinsicGMRF`, `BYM2GMRF` and `ConstrainedGMRF`
    all fit; they share no base class, so the wrapper types them structurally.

    Shape:
        - event_shape: ``(N,)``
        - log_prob: ``(*sample, N)`` → ``(*sample,)``
        - sample: ``(key, sample_shape)`` → ``(*sample_shape, N)``

    Examples:
        >>> import gaussx as gx
        >>> import jax.numpy as jnp
        >>> from gauss_flows_models.distributions import GaussianFieldLike
        >>> precision = gx.spde_precision_grid((4, 4), kappa=0.5, tau=1.0, alpha=2)
        >>> field = gx.GaussianMRF(jnp.zeros(16), precision)
        >>> isinstance(field, GaussianFieldLike)
        True
    """

    @property
    def event_shape(self) -> tuple[int]:
        """The event shape ``(N,)``."""
        ...

    def log_prob(self, value: Array) -> Array:
        """The log-density of each point."""
        ...

    def sample(self, key: PRNGKeyArray, sample_shape: tuple[int, ...] = ()) -> Array:
        """Draws of shape ``sample_shape + (N,)``."""
        ...

event_shape property

event_shape: tuple[int]

The event shape (N,).

log_prob

log_prob(value: Array) -> Array

The log-density of each point.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/gmrf.py
def log_prob(self, value: Array) -> Array:
    """The log-density of each point."""
    ...

sample

sample(key: PRNGKeyArray, sample_shape: tuple[int, ...] = ()) -> Array

Draws of shape sample_shape + (N,).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/gmrf.py
def sample(self, key: PRNGKeyArray, sample_shape: tuple[int, ...] = ()) -> Array:
    """Draws of shape ``sample_shape + (N,)``."""
    ...

Structured Gaussian bases

StructuredGaussian is \(\mathcal{N}(\gvect{\mu}, \gmat{\Sigma})\) for any lineax or gaussx covariance operator, so a flow over a gridded field or a long series can start from a base that already carries its correlation, and the bijections only learn what a Gaussian cannot express. Like LowRankGaussian, it is an AbstractOperatorGaussian: gaussx.sample_mvn draws \(\vect{x} = \gvect{\mu} + \mat{L} \vect{z}\) with \(\mat{L} \mat{L}^\top = \gmat{\Sigma}\) chosen by structure, and gaussx.gaussian_log_prob chooses the solve and the log-determinant by structure. The operator's array leaves (a Toeplitz column, Kronecker factors, …) are trainable; keeping \(\gmat{\Sigma}\) positive definite while they train is the caller's choice of parameterisation.

Covariance Typical base Exact draw Log-density
gaussx.Toeplitz stationary series on a regular grid \(O(D \log D)\), by FFT dense, \(O(D^3)\)
gaussx.Kronecker separable space × time per-factor eigendecompositions structured
gaussx.KroneckerSum separable 2-D field per-factor eigendecompositions structured
gaussx.BlockTriDiag Markov chain \(O(B d^3)\); dense inside a flow \(O(B d^3)\)
gaussx.LowRankUpdate LowRankGaussian base's cost + \(O(DK)\) \(O(DK^2)\)

The "dense" entries are gaussx v0.8.4's: it has no structured solve or log-determinant for a Toeplitz operator, and its block-tridiagonal draw falls back to the dense square root of \(\gmat{\Sigma}\) in a way that jax.vmap evaluates for every draw, which is how a FlowJax Transformed samples its base. The class docstring has the details.

StructuredGaussian

Bases: AbstractOperatorGaussian

𝒩(μ, Σ) for a structured covariance operator whose array leaves are trainable.

x = μ + L z,   z ~ 𝒩(0, I),   L Lᵀ = Σ,   log p(x) = log 𝒩(x; μ, Σ)

gaussx.sample_mvn chooses the factor L and gaussx.gaussian_log_prob the solve and the log-determinant, both by the structure of Σ (gaussx v0.8.4; measured at D = 4096 by the tests):

Covariance Σ Exact draw Log-density
gaussx.Toeplitz O(D log D), by FFT dense, O(D³)
gaussx.Kronecker per-factor eigendecompositions structured
gaussx.KroneckerSum per-factor eigendecompositions structured
gaussx.BlockTriDiag O(B d³); dense inside a flow (below) O(B d³)
gaussx.LowRankUpdate base's cost + O(DK) O(DK²)

Two structures still form a D × D array:

  • Toeplitz log-density. gaussx has no structured solve or log-determinant for a Toeplitz operator, so log_prob forms Σ and factors it (O(D²) memory, O(D³) time). Its draws are structured, but the traced program also holds the dense square root that gaussx falls back to when the circulant embedding is not positive.
  • Block-tridiagonal draws. gaussx guards the banded-Cholesky draw with a fallback to the dense square root of Σ, chosen by whether the draws are finite. sample draws all events in one gaussx.sample_mvn call, where the choice is one lax.cond and the dense branch only sits in the compiled program. Inside a flow, though, FlowJax's Transformed maps _sample over one key per event with jax.vmap, which turns the choice into a select that computes the dense root (O(D³)) for every draw: at D = 256, a hundred draws took about 40 s that way and 10⁵ draws through sample about 3 s. The log-density is structured.

Keeping Σ positive definite while its leaves are trained is the caller's choice of parameterisation (a Toeplitz column from a positive spectrum, Kronecker factors from Cholesky factors, …): neither this class nor gaussx checks it.

Parameters:

Name Type Description Default
loc ArrayLike

Mean μ, shape (D,).

required
covariance AbstractLinearOperator

Covariance Σ, a square D × D lineax operator.

required

Raises:

Type Description
ValueError

If loc is not 1-D, or covariance is not square with size D.

Shape
  • log_prob: (D,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, D)
  • covariance_operator: → the D × D operator Σ

Examples:

A stationary daily series, Σ = toeplitz(t) with t_k = 0.8^k:

>>> import gaussx as gx
>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import StructuredGaussian
>>> lags = jnp.arange(365.0)
>>> series_base = StructuredGaussian(
...     loc=jnp.zeros(365), covariance=gx.Toeplitz(0.8**lags)
... )
>>> series_base.sample(jr.key(0), (4,)).shape
(4, 365)

A separable 2-D field, Σ = A₁ ⊗ A₂ on a 16 × 32 grid:

>>> import lineax as lx
>>> psd = lx.positive_semidefinite_tag
>>> rows = lx.MatrixLinearOperator(jnp.eye(16) + 0.5, psd)
>>> columns = lx.MatrixLinearOperator(jnp.eye(32) + 0.1, psd)
>>> field_base = StructuredGaussian(
...     loc=jnp.zeros(512), covariance=gx.Kronecker(rows, columns)
... )
>>> field_base.log_prob(jnp.zeros(512)).shape
()

As the base of a FlowJax flow:

>>> from flowjax.bijections import Affine
>>> from flowjax.distributions import Transformed
>>> flow = Transformed(field_base, Affine(loc=1.0, scale=2.0 * jnp.ones(512)))
>>> flow.sample(jr.key(1), (2,)).shape
(2, 512)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/structured.py
class StructuredGaussian(AbstractOperatorGaussian):
    """𝒩(μ, Σ) for a structured covariance operator whose array leaves are trainable.

        x = μ + L z,   z ~ 𝒩(0, I),   L Lᵀ = Σ,   log p(x) = log 𝒩(x; μ, Σ)

    `gaussx.sample_mvn` chooses the factor L and `gaussx.gaussian_log_prob`
    the solve and the log-determinant, both by the structure of Σ (gaussx
    v0.8.4; measured at D = 4096 by the tests):

    | Covariance Σ | Exact draw | Log-density |
    |---|---|---|
    | `gaussx.Toeplitz` | O(D log D), by FFT | dense, O(D³) |
    | `gaussx.Kronecker` | per-factor eigendecompositions | structured |
    | `gaussx.KroneckerSum` | per-factor eigendecompositions | structured |
    | `gaussx.BlockTriDiag` | O(B d³); dense inside a flow (below) | O(B d³) |
    | `gaussx.LowRankUpdate` | base's cost + O(DK) | O(DK²) |

    Two structures still form a D × D array:

    - **Toeplitz log-density.** gaussx has no structured solve or
      log-determinant for a Toeplitz operator, so `log_prob` forms Σ and
      factors it (O(D²) memory, O(D³) time). Its draws are structured, but
      the traced program also holds the dense square root that gaussx falls
      back to when the circulant embedding is not positive.
    - **Block-tridiagonal draws.** gaussx guards the banded-Cholesky draw with
      a fallback to the dense square root of Σ, chosen by whether the draws
      are finite. `sample` draws all events in one `gaussx.sample_mvn` call,
      where the choice is one ``lax.cond`` and the dense branch only sits in
      the compiled program. Inside a flow, though, FlowJax's `Transformed`
      maps `_sample` over one key per event with ``jax.vmap``, which turns the
      choice into a select that computes the dense root (O(D³)) for every
      draw: at D = 256, a hundred draws took about 40 s that way and 10⁵
      draws through `sample` about 3 s. The log-density is structured.

    Keeping Σ positive definite while its leaves are trained is the caller's
    choice of parameterisation (a Toeplitz column from a positive spectrum,
    Kronecker factors from Cholesky factors, …): neither this class nor gaussx
    checks it.

    Args:
        loc: Mean μ, shape ``(D,)``.
        covariance: Covariance Σ, a square D × D lineax operator.

    Raises:
        ValueError: If ``loc`` is not 1-D, or ``covariance`` is not square
            with size ``D``.

    Shape:
        - log_prob: ``(D,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, D)``
        - covariance_operator: → the D × D operator Σ

    Examples:
        A stationary daily series, Σ = toeplitz(t) with t_k = 0.8^k:

        >>> import gaussx as gx
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import StructuredGaussian
        >>> lags = jnp.arange(365.0)
        >>> series_base = StructuredGaussian(
        ...     loc=jnp.zeros(365), covariance=gx.Toeplitz(0.8**lags)
        ... )
        >>> series_base.sample(jr.key(0), (4,)).shape
        (4, 365)

        A separable 2-D field, Σ = A₁ ⊗ A₂ on a 16 × 32 grid:

        >>> import lineax as lx
        >>> psd = lx.positive_semidefinite_tag
        >>> rows = lx.MatrixLinearOperator(jnp.eye(16) + 0.5, psd)
        >>> columns = lx.MatrixLinearOperator(jnp.eye(32) + 0.1, psd)
        >>> field_base = StructuredGaussian(
        ...     loc=jnp.zeros(512), covariance=gx.Kronecker(rows, columns)
        ... )
        >>> field_base.log_prob(jnp.zeros(512)).shape
        ()

        As the base of a FlowJax flow:

        >>> from flowjax.bijections import Affine
        >>> from flowjax.distributions import Transformed
        >>> flow = Transformed(field_base, Affine(loc=1.0, scale=2.0 * jnp.ones(512)))
        >>> flow.sample(jr.key(1), (2,)).shape
        (2, 512)
    """

    covariance: lx.AbstractLinearOperator
    shape: tuple[int, ...]

    def __init__(self, loc: ArrayLike, covariance: lx.AbstractLinearOperator):
        loc = jnp.asarray(loc, dtype=float)
        if loc.ndim != 1:
            raise ValueError(f"loc must be 1-D, got shape {loc.shape}.")
        event_size = loc.shape[0]
        if covariance.in_size() != covariance.out_size():
            raise ValueError(
                "covariance must be square, got "
                f"{covariance.out_size()} x {covariance.in_size()}."
            )
        if covariance.in_size() != event_size:
            raise ValueError(
                f"covariance must be {event_size} x {event_size} to match loc, "
                f"got size {covariance.in_size()}."
            )
        self.loc = loc
        self.covariance = covariance
        self.shape = (event_size,)

    def covariance_operator(self) -> lx.AbstractLinearOperator:
        """The covariance Σ, as given.

        Returns:
            The operator ``covariance``.
        """
        return self.covariance

covariance_operator

covariance_operator() -> AbstractLinearOperator

The covariance Σ, as given.

Returns:

Type Description
AbstractLinearOperator

The operator covariance.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/structured.py
def covariance_operator(self) -> lx.AbstractLinearOperator:
    """The covariance Σ, as given.

    Returns:
        The operator ``covariance``.
    """
    return self.covariance

Manifold (sphere) distributions

Distributions on the unit sphere \(\mathbb{S}^{d}\subset\mathbb{R}^{d+1}\) for directional data and global flows. The von Mises–Fisher density \(p(x)\propto\exp(\kappa\,\mu^\top x)\) concentrates around a mean direction \(\mu\) with concentration \(\kappa\); UniformOnSphere is its \(\kappa\to 0\) limit. The exp/log maps and tangent basis below move between the manifold and its tangent plane for building flows in local coordinates.

VonMisesFisher

Bases: AbstractDistribution

Von Mises–Fisher distribution on the unit sphere Sᵈ ⊂ ℝ^{d+1}.

Density p(x) ∝ exp(κ · μᵀx) on the sphere: the spherical analogue of an isotropic Gaussian, peaked at the mean direction μ with concentration κ (κ = 0 recovers UniformOnSphere). The normaliser involves a modified Bessel function I_ν(κ), evaluated here via a hybrid power-series / asymptotic expansion. Sampling uses Wood's (1994) rejection scheme. Useful as a flow base for concentrated directional data.

Invalid inputs (zero-vector mean or negative concentration) are propagated as NaN through log_prob / sample rather than being rejected at construction, so the constructor stays jit / vmap-safe (e.g. inside a mixture of VMFs).

Parameters:

Name Type Description Default
mean ArrayLike

Mean direction μ in ℝ^{d+1}. Normalised internally; integer inputs are promoted to a floating dtype. Sets the event dimension d = mean.shape[0] − 1.

required
concentration ArrayLike

Non-negative scalar concentration κ.

required
Shape
  • log_prob: (d+1,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, d+1)

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.distributions import VonMisesFisher
>>> dist = VonMisesFisher(jnp.array([0.0, 0.0, 1.0]), 3.0)
>>> dist.sample(jr.key(0), (2,)).shape
(2, 3)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/sphere.py
class VonMisesFisher(AbstractDistribution):
    """Von Mises–Fisher distribution on the unit sphere ``Sᵈ ⊂ ℝ^{d+1}``.

    Density ``p(x) ∝ exp(κ · μᵀx)`` on the sphere: the spherical analogue of
    an isotropic Gaussian, peaked at the mean direction ``μ`` with
    concentration ``κ`` (``κ = 0`` recovers `UniformOnSphere`). The
    normaliser involves a modified Bessel function ``I_ν(κ)``, evaluated
    here via a hybrid power-series / asymptotic expansion. Sampling uses
    Wood's (1994) rejection scheme. Useful as a flow base for concentrated
    directional data.

    Invalid inputs (zero-vector ``mean`` or negative ``concentration``) are
    propagated as ``NaN`` through ``log_prob`` / ``sample`` rather than being
    rejected at construction, so the constructor stays ``jit`` / ``vmap``-safe
    (e.g. inside a mixture of VMFs).

    Args:
        mean: Mean direction ``μ`` in ``ℝ^{d+1}``. Normalised internally;
            integer inputs are promoted to a floating dtype. Sets the event
            dimension ``d = mean.shape[0] − 1``.
        concentration: Non-negative scalar concentration ``κ``.

    Shape:
        - log_prob: ``(d+1,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, d+1)``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import VonMisesFisher
        >>> dist = VonMisesFisher(jnp.array([0.0, 0.0, 1.0]), 3.0)
        >>> dist.sample(jr.key(0), (2,)).shape
        (2, 3)
    """

    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None
    mean: Array
    concentration: Array

    def __init__(self, mean: ArrayLike, concentration: ArrayLike):
        mean_array = jnp.asarray(mean)
        if mean_array.ndim != 1:
            raise ValueError("mean must have shape (d+1,).")
        if mean_array.shape[0] < 2:
            raise ValueError("mean must live in at least two ambient dimensions.")

        # Promote integer inputs to a floating dtype so downstream `jnp.finfo`
        # calls and rejection-sampling arithmetic work regardless of how the
        # user typed `mean`.
        float_dtype = jnp.result_type(mean_array.dtype, float)
        mean_array = mean_array.astype(float_dtype)
        concentration_array = jnp.asarray(concentration, dtype=float_dtype)
        if concentration_array.shape != ():
            raise ValueError("concentration must be a scalar.")

        # NaN-propagate invalid inputs so errors surface downstream instead of
        # silently producing finite-but-wrong numbers. We can't raise here
        # without breaking vmap-over-κ patterns.
        norm = jnp.linalg.norm(mean_array)
        safe_norm = jnp.where(norm > 0, norm, jnp.asarray(1.0, dtype=float_dtype))
        normalized_mean = jnp.where(
            norm > 0,
            mean_array / safe_norm,
            jnp.full_like(mean_array, jnp.nan),
        )
        concentration_array = jnp.where(
            concentration_array >= 0,
            concentration_array,
            jnp.asarray(jnp.nan, dtype=float_dtype),
        )

        self.shape = mean_array.shape
        self.mean = normalized_mean
        self.concentration = concentration_array

    @property
    def d(self) -> int:
        return self.shape[0] - 1

    def _log_normalizer(self) -> Array:
        nu = 0.5 * (self.d - 1)
        concentration = self.concentration
        concentration_safe = jnp.maximum(
            concentration,
            jnp.finfo(concentration.dtype).tiny,
        )
        uniform_log_density = -_log_surface_area_sphere(self.d)
        vmf_log_density = (
            nu * jnp.log(concentration_safe)
            - 0.5 * (self.d + 1) * _LOG_2PI
            - _log_bessel_iv(nu, concentration_safe)
        )
        # `κ > 0` is false for both κ == 0 and κ == NaN. Adding `0 · κ` below
        # taints the uniform branch with NaN when κ is NaN so invalid inputs
        # don't silently return the uniform density.
        log_density = jnp.where(concentration > 0, vmf_log_density, uniform_log_density)
        return log_density + 0.0 * concentration

    def _sample_w(self, key: PRNGKeyArray) -> Array:
        p = self.shape[0]
        m = p - 1.0
        concentration = self.concentration
        # Wood's acceptance test hangs the while-loop for any non-finite or
        # non-positive κ (NaN, ±inf, 0, negatives), so we run the sampler
        # with a safe placeholder κ and taint the output afterwards to
        # propagate the invalid input. Beyond a dtype-dependent bound,
        # ``b ≈ m / (4κ)`` rounds below the floating eps and ``x0`` snaps to
        # ``1.0``; then ``c = κ + m log1p(-1) = -inf`` and the acceptance
        # test ``κ w + m log1p(-x0 w) - c`` evaluates to NaN, so the loop
        # never accepts. Clamp finite κ to the safe range; the sampler then
        # returns ``w ≈ 1`` (i.e. ``sample ≈ mean``), which is the correct
        # asymptotic limit as ``κ → ∞``.
        eps = jnp.finfo(concentration.dtype).eps
        kappa_safe_max = jnp.asarray(0.25 / eps, dtype=concentration.dtype)
        is_finite_positive = (concentration > 0) & jnp.isfinite(concentration)
        safe_concentration = jnp.where(
            is_finite_positive,
            jnp.minimum(concentration, kappa_safe_max),
            jnp.asarray(1.0, dtype=concentration.dtype),
        )
        # Algebraically equivalent to
        #   ``(-2κ + sqrt(4κ² + m²)) / m``
        # but avoids catastrophic cancellation for large κ.
        denom = 2.0 * safe_concentration + jnp.sqrt(
            4.0 * safe_concentration * safe_concentration + m * m
        )
        b = m / denom
        x0 = (1.0 - b) / (1.0 + b)
        c = safe_concentration * x0 + m * jnp.log1p(-(x0 * x0))
        alpha = 0.5 * m

        def cond_fn(state):
            _, _, accepted = state
            return ~accepted

        def body_fn(state):
            loop_key, accepted_w, _ = state
            loop_key, key_beta, key_uniform = jr.split(loop_key, 3)
            z = jr.beta(key_beta, alpha, alpha)
            w = (1.0 - (1.0 + b) * z) / (1.0 - (1.0 - b) * z)
            u = jr.uniform(key_uniform, minval=jnp.finfo(concentration.dtype).tiny)
            accept = safe_concentration * w + m * jnp.log1p(-x0 * w) - c >= jnp.log(u)
            return loop_key, jnp.where(accept, w, accepted_w), accept

        _, w, _ = jax.lax.while_loop(
            cond_fn,
            body_fn,
            (key, jnp.asarray(0.0, dtype=concentration.dtype), jnp.asarray(False)),
        )
        # Non-finite/non-positive κ went through the placeholder branch;
        # NaN the output so callers see the invalid input downstream. Finite
        # κ above the safe clamp just gets its sampler-clamped value (a
        # near-delta) and is considered valid.
        return jnp.where(is_finite_positive, w, jnp.asarray(jnp.nan, dtype=w.dtype))

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        del condition

        def sample_uniform(sample_key: PRNGKeyArray) -> Array:
            return _normalize_to_sphere(jr.normal(sample_key, self.shape))

        def sample_vmf(sample_key: PRNGKeyArray) -> Array:
            key_w, key_v = jr.split(sample_key)
            w = self._sample_w(key_w)
            v = _normalize_to_sphere(jr.normal(key_v, (self.d,)))
            basis = tangent_basis(self.mean)
            tangent_part = basis @ v
            scale = jnp.sqrt(jnp.maximum(1.0 - w * w, 0.0))
            sample = w * self.mean + scale * tangent_part
            return _normalize_to_sphere(sample)

        return jax.lax.cond(self.concentration == 0, sample_uniform, sample_vmf, key)

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        del condition
        x = jnp.asarray(x)
        on_sphere = jnp.isclose(jnp.linalg.norm(x), 1.0, atol=_ON_SPHERE_ATOL)
        log_density = self._log_normalizer() + self.concentration * jnp.dot(
            self.mean, x
        )
        return jnp.where(on_sphere, log_density, -jnp.inf)

UniformOnSphere

Bases: AbstractDistribution

Uniform distribution on the unit sphere Sᵈ ⊂ ℝ^{d+1}.

Constant density 1 / A_d over the sphere, where A_d is the surface area of Sᵈ; log_prob returns −∞ for off-sphere points. Samples are drawn by normalising an isotropic Gaussian, so they satisfy ‖x‖₂ = 1 up to numerical precision. Useful as a flow base for directional / rotation-invariant data.

Parameters:

Name Type Description Default
d int

Intrinsic sphere dimension. Samples live in ℝ^{d+1}.

required
Shape
  • log_prob: (d+1,) → scalar (batch via vmap / leading axes)
  • sample: (key, sample_shape) → (*sample_shape, d+1)

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.distributions import UniformOnSphere
>>> dist = UniformOnSphere(d=2)
>>> dist.sample(jr.key(0), (4,)).shape
(4, 3)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/distributions/sphere.py
class UniformOnSphere(AbstractDistribution):
    """Uniform distribution on the unit sphere ``Sᵈ ⊂ ℝ^{d+1}``.

    Constant density ``1 / A_d`` over the sphere, where ``A_d`` is the
    surface area of ``Sᵈ``; ``log_prob`` returns ``−∞`` for off-sphere
    points. Samples are drawn by normalising an isotropic Gaussian, so
    they satisfy ``‖x‖₂ = 1`` up to numerical precision. Useful as a flow
    base for directional / rotation-invariant data.

    Args:
        d: Intrinsic sphere dimension. Samples live in ``ℝ^{d+1}``.

    Shape:
        - log_prob: ``(d+1,)`` → scalar    (batch via vmap / leading axes)
        - sample:   ``(key, sample_shape)`` → ``(*sample_shape, d+1)``

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.distributions import UniformOnSphere
        >>> dist = UniformOnSphere(d=2)
        >>> dist.sample(jr.key(0), (4,)).shape
        (4, 3)
    """

    d: int = eqx.field(static=True)
    shape: tuple[int, ...]
    cond_shape: ClassVar[None] = None

    def __init__(self, d: int):
        if d < 1:
            raise ValueError(f"d must be positive, got {d}.")
        self.d = d
        self.shape = (d + 1,)

    def _sample(self, key: PRNGKeyArray, condition: Array | None = None) -> Array:
        del condition
        raw = jr.normal(key, self.shape)
        return _normalize_to_sphere(raw)

    def _log_prob(self, x: Array, condition: Array | None = None) -> Array:
        del condition
        x = jnp.asarray(x)
        on_sphere = jnp.isclose(jnp.linalg.norm(x), 1.0, atol=_ON_SPHERE_ATOL)
        log_density = -_log_surface_area_sphere(self.d)
        return jnp.where(on_sphere, log_density, -jnp.inf)

expmap_sphere

expmap_sphere(x: Array, v: Array) -> Array

Map a tangent vector at x to the sphere via the exponential map.

expmap(x, v) = x·cos(‖v‖) + v·sin(‖v‖) / ‖v‖ with the sin(r) / r factor evaluated via sinc for stability at r → 0. The component of v along x is removed first, so v need not be exactly tangent.

Parameters:

Name Type Description Default
x Array

Base point in ℝ^{d+1} (normalised internally), shape (d+1,).

required
v Array

Tangent vector at x, shape (d+1,).

required

Returns:

Type Description
Array

The point expmap(x, v) on the sphere, shape (d+1,).

Shape

x and v are single events of shape (d+1,). Returns a single point on the sphere with shape (d+1,).

Examples:

>>> import jax.numpy as jnp
>>> from gauss_flows_maps.sphere import expmap_sphere
>>> x = jnp.array([0.0, 0.0, 1.0])
>>> v = jnp.array([0.1, 0.0, 0.0])
>>> expmap_sphere(x, v).shape
(3,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/_sphere_utils.py
def expmap_sphere(
    x: Array,
    v: Array,
) -> Array:
    """Map a tangent vector at ``x`` to the sphere via the exponential map.

    ``expmap(x, v) = x·cos(‖v‖) + v·sin(‖v‖) / ‖v‖`` with the ``sin(r) / r``
    factor evaluated via ``sinc`` for stability at ``r → 0``. The component
    of ``v`` along ``x`` is removed first, so ``v`` need not be exactly
    tangent.

    Args:
        x: Base point in ``ℝ^{d+1}`` (normalised internally), shape ``(d+1,)``.
        v: Tangent vector at ``x``, shape ``(d+1,)``.

    Returns:
        The point ``expmap(x, v)`` on the sphere, shape ``(d+1,)``.

    Shape:
        ``x`` and ``v`` are single events of shape ``(d+1,)``.
        Returns a single point on the sphere with shape ``(d+1,)``.

    Examples:
        >>> import jax.numpy as jnp
        >>> from gauss_flows_maps.sphere import expmap_sphere
        >>> x = jnp.array([0.0, 0.0, 1.0])
        >>> v = jnp.array([0.1, 0.0, 0.0])
        >>> expmap_sphere(x, v).shape
        (3,)
    """

    x_unit = _safe_normalize(x)
    v_tangent = v - x_unit * jnp.dot(x_unit, v)
    radius = jnp.linalg.norm(v_tangent)
    scale = jnp.sinc(radius / jnp.pi)
    y = jnp.cos(radius) * x_unit + scale * v_tangent
    return _safe_normalize(y)

logmap_sphere

logmap_sphere(x: Array, y: Array) -> Array

Return the tangent vector at x whose exp-map reaches y.

Inverse of expmap_sphere: expmap(x, logmap(x, y)) ≈ y. The log map is not uniquely defined when y is antipodal to x; this implementation returns π · e for a deterministic tangent direction e obtained from tangent_basis, which at least satisfies ‖logmap‖ == π (the geodesic distance to the antipode) and is continuous under perturbations of x.

Parameters:

Name Type Description Default
x Array

Base point on the sphere in ℝ^{d+1} (normalised internally), shape (d+1,).

required
y Array

Target point on the sphere, shape (d+1,).

required

Returns:

Type Description
Array

The tangent vector in Tₓ Sᵈ reaching y, shape (d+1,).

Shape

x and y are single points on the sphere with shape (d+1,). Returns a tangent vector in Tₓ Sᵈ with shape (d+1,).

Examples:

>>> import jax.numpy as jnp
>>> from gauss_flows_maps.sphere import expmap_sphere, logmap_sphere
>>> x = jnp.array([0.0, 0.0, 1.0])
>>> v = jnp.array([0.1, 0.0, 0.0])
>>> y = expmap_sphere(x, v)
>>> logmap_sphere(x, y).shape
(3,)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/_sphere_utils.py
def logmap_sphere(
    x: Array,
    y: Array,
) -> Array:
    """Return the tangent vector at ``x`` whose exp-map reaches ``y``.

    Inverse of `expmap_sphere`: ``expmap(x, logmap(x, y)) ≈ y``. The
    log map is not uniquely defined when ``y`` is antipodal to ``x``; this
    implementation returns ``π · e`` for a deterministic tangent direction
    ``e`` obtained from `tangent_basis`, which at least satisfies
    ``‖logmap‖ == π`` (the geodesic distance to the antipode) and is
    continuous under perturbations of ``x``.

    Args:
        x: Base point on the sphere in ``ℝ^{d+1}`` (normalised internally),
            shape ``(d+1,)``.
        y: Target point on the sphere, shape ``(d+1,)``.

    Returns:
        The tangent vector in ``Tₓ Sᵈ`` reaching ``y``, shape ``(d+1,)``.

    Shape:
        ``x`` and ``y`` are single points on the sphere with shape ``(d+1,)``.
        Returns a tangent vector in ``Tₓ Sᵈ`` with shape ``(d+1,)``.

    Examples:
        >>> import jax.numpy as jnp
        >>> from gauss_flows_maps.sphere import expmap_sphere, logmap_sphere
        >>> x = jnp.array([0.0, 0.0, 1.0])
        >>> v = jnp.array([0.1, 0.0, 0.0])
        >>> y = expmap_sphere(x, v)
        >>> logmap_sphere(x, y).shape
        (3,)
    """

    x_unit = _safe_normalize(x)
    y_unit = _safe_normalize(y)
    cosine = jnp.clip(jnp.dot(x_unit, y_unit), -1.0, 1.0)
    tangent = y_unit - cosine * x_unit
    tangent_sq = jnp.sum(tangent * tangent)
    # Double-where on ``tangent_sq`` so ``jnp.sqrt`` and the division have
    # finite gradients even at ``y == x`` (where ``tangent == 0``). The
    # ``arctan2`` form avoids the ``arccos`` boundary singularity at
    # ``cosine == ±1`` (whose derivative is ``-∞``) which would otherwise leak
    # NaN via ``0 · ∞`` in the inactive branch of the ``where``.
    eps_sq = jnp.asarray(
        jnp.finfo(tangent.dtype).eps ** 2,
        dtype=tangent.dtype,
    )
    is_nonzero = tangent_sq > eps_sq
    safe_tangent_sq = jnp.where(is_nonzero, tangent_sq, 1.0)
    safe_norm = jnp.sqrt(safe_tangent_sq)
    angle = jnp.arctan2(safe_norm, cosine)
    scale = jnp.where(is_nonzero, angle / safe_norm, 1.0)
    generic = scale * tangent

    # Antipodal fallback fires only at the true singularity ``y == -x``
    # (tangent exactly zero with ``cosine < 0``). Near-antipodal points with
    # ``cosine`` close to but not exactly ``-1`` still have a well-defined
    # shortest-geodesic tangent that the generic branch computes correctly;
    # triggering the fallback on those would snap them to an arbitrary
    # π-length direction and break ``expmap(x, logmap(x, y)) ≈ y``.
    is_antipodal = (~is_nonzero) & (cosine < 0.0)
    antipodal_direction = jnp.pi * tangent_basis(x_unit)[:, 0]
    return jnp.where(is_antipodal, antipodal_direction, generic)

tangent_basis

tangent_basis(x: Array) -> Array

Return an orthonormal basis of the tangent space Tₓ Sᵈ.

Uses a Householder reflection that maps x to ±e₁ and then takes columns 2..d+1 of that orthogonal matrix.

Parameters:

Name Type Description Default
x Array

A point in ℝ^{d+1} (normalised internally to the sphere), shape (d+1,).

required

Returns:

Type Description
Array

Tangent basis E of shape (d+1, d) with Eᵀ E = I and

Array

xᵀ E = 0.

Shape

Input: (d+1,). Output: (d+1, d) with Eᵀ E = I and xᵀ E = 0.

Examples:

>>> import jax.numpy as jnp
>>> from gauss_flows_maps.sphere import tangent_basis
>>> x = jnp.array([0.0, 0.0, 1.0])
>>> tangent_basis(x).shape
(3, 2)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/transforms/_sphere_utils.py
def tangent_basis(x: Array) -> Array:
    """Return an orthonormal basis of the tangent space ``Tₓ Sᵈ``.

    Uses a Householder reflection that maps ``x`` to ``±e₁`` and then takes
    columns ``2..d+1`` of that orthogonal matrix.

    Args:
        x: A point in ``ℝ^{d+1}`` (normalised internally to the sphere),
            shape ``(d+1,)``.

    Returns:
        Tangent basis ``E`` of shape ``(d+1, d)`` with ``Eᵀ E = I`` and
        ``xᵀ E = 0``.

    Shape:
        Input: ``(d+1,)``.
        Output: ``(d+1, d)`` with ``Eᵀ E = I`` and ``xᵀ E = 0``.

    Examples:
        >>> import jax.numpy as jnp
        >>> from gauss_flows_maps.sphere import tangent_basis
        >>> x = jnp.array([0.0, 0.0, 1.0])
        >>> tangent_basis(x).shape
        (3, 2)
    """

    x_unit = _safe_normalize(x)
    d_plus_1 = x_unit.shape[0]
    e1 = jnp.eye(d_plus_1, dtype=x_unit.dtype)[:, 0]
    sign = jnp.where(x_unit[0] >= 0, 1.0, -1.0).astype(x_unit.dtype)
    v = x_unit + sign * e1
    v_norm2 = jnp.maximum(jnp.dot(v, v), jnp.finfo(x_unit.dtype).tiny)
    householder = (
        jnp.eye(d_plus_1, dtype=x_unit.dtype) - 2.0 * jnp.outer(v, v) / v_norm2
    )
    return householder[:, 1:]