Skip to content

Flows & RBIG

These are the Layer 1 assemblies — containers that stack transforms into a full flow, and one-call factories that build a ready-to-train (or already-fitted) Gaussianization flow. A Gaussianization flow alternates a marginal CDF step \(G\) with a rotation \(R\),

\[ z \;=\; (R_L \circ G_L)\circ\cdots\circ(R_1 \circ G_1)\,(x), \]

driving the data toward a standard normal one block at a time. After \(L\) blocks the flow is a density estimator (log_prob), a sampler (sample), and — because the latent is Gaussian — a plug-in estimator for the information-theoretic measures in Information Theory.

Containers

SurVAEFlow is the general container: it threads a key through a chain that may mix bijections, surjections, and stochastic transforms, and vmaps log_prob / sample over any leading sample_shape. For a bijection-only chain it matches flowjax.Transformed exactly.

SurVAEFlow

Bases: Module

Container that threads PRNG keys through a mixed bijection / surjection chain.

Composes any sequence of flowjax.bijections.AbstractBijection and AbstractSurjection transforms. Forward direction is base -> data (used by sample); inverse direction is data -> base (used by log_prob). Each transform receives its own independent split of the user-supplied key, regardless of whether it actually consumes it — this keeps the call shape uniform and JIT-friendly.

For a chain consisting solely of AbstractBijection instances, log_prob is identical (up to numerical noise) to that of the equivalent flowjax.distributions.Transformed(base, Chain(transforms)), so users can migrate without changing semantics.

Attributes:

Name Type Description
base_dist AbstractDistribution

A flowjax.distributions.AbstractDistribution whose event shape matches the start of the forward chain.

transforms tuple[AbstractBijection | AbstractSurjection, ...]

Tuple of bijections / surjections, applied left-to-right in the forward direction.

data_shape tuple[int, ...]

Event shape of the data (output of the forward chain / input to log_prob). Defaults to base_dist.shape for shape-preserving chains; must be supplied explicitly when the chain contains a surjection that changes dimensionality (e.g. Slice, Augment, SimpleMaxPoolSurjection2d).

Properties

lower_bound: True iff at least one surjection in the chain contributes a lower bound to log_prob (i.e. has its class-level lower_bound flag set).

Conditioning model

sample and log_prob accept a single optional condition kwarg that is broadcast to every layer in the chain and to the base distribution. A layer that opts in (cond_shape is not None) consumes the condition; a layer that does not (cond_shape is None) silently ignores it. So a single global context vector can drive any subset of {base, couplings, FiLM-wrapped layers} — including:

  • base only: pair a ConditionalDiagGaussian / ClassCondDiagGaussian (or pyrox_flows.NumpyroBase in factory mode) base with otherwise unconditional transforms.
  • transforms only: pair an unconditional base (flowjax.distributions.Normal, …) with one or more coupling layers built with cond_dim > 0 (or any transform wrapped in Conditioner).
  • both: a conditional base and condition-aware transforms; the same condition reaches both.

Inside a coupling layer there are two distinct conditioning streams: the data-dependent untransformed half of x (always present — the whole point of coupling) and the external condition (present only when cond_dim > 0). The two are concatenated inside the inner MLP; users do not slice or merge them manually.

Shape

Methods follow the single-event convention but accept a leading sample_shape that is vmapped over internally:

  • sample(key, sample_shape, condition) → sample_shape + data_shape
  • log_prob(x, key, condition): x of shape sample_shape + data_shape → sample_shape

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.distributions import Normal
>>> from gauss_flows_models.flows import SurVAEFlow
>>> from gauss_flows_maps.bijections import AffineCoupling
>>> base = Normal(jnp.zeros(4))
>>> flow = SurVAEFlow(base, [AffineCoupling(jr.key(0), shape=(4,))])
>>> x = flow.sample(jr.key(1), (5,))
>>> x.shape
(5, 4)
>>> flow.log_prob(x, jr.key(2)).shape
(5,)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/survae.py
class SurVAEFlow(eqx.Module):
    """Container that threads PRNG keys through a mixed bijection / surjection chain.

    Composes any sequence of `flowjax.bijections.AbstractBijection` and
    `AbstractSurjection` transforms. Forward direction is base -> data
    (used by ``sample``); inverse direction is data -> base (used by
    ``log_prob``). Each transform receives its own independent split of the
    user-supplied key, regardless of whether it actually consumes it — this
    keeps the call shape uniform and JIT-friendly.

    For a chain consisting solely of `AbstractBijection` instances,
    ``log_prob`` is identical (up to numerical noise) to that of the
    equivalent ``flowjax.distributions.Transformed(base, Chain(transforms))``,
    so users can migrate without changing semantics.

    Attributes:
        base_dist: A `flowjax.distributions.AbstractDistribution`
            whose event shape matches the start of the forward chain.
        transforms: Tuple of bijections / surjections, applied left-to-right
            in the forward direction.
        data_shape: Event shape of the data (output of the forward chain /
            input to ``log_prob``). Defaults to ``base_dist.shape`` for
            shape-preserving chains; **must** be supplied explicitly when
            the chain contains a surjection that changes dimensionality
            (e.g. `Slice`, `Augment`,
            `SimpleMaxPoolSurjection2d`).

    Properties:
        lower_bound: ``True`` iff at least one surjection in the chain
            contributes a lower bound to ``log_prob`` (i.e. has its
            class-level ``lower_bound`` flag set).

    Conditioning model:
        ``sample`` and ``log_prob`` accept a single optional ``condition``
        kwarg that is broadcast to **every** layer in the chain *and* to the
        base distribution. A layer that opts in (``cond_shape is not None``)
        consumes the condition; a layer that does not (``cond_shape is
        None``) silently ignores it. So a single global context vector can
        drive any subset of {base, couplings, FiLM-wrapped layers} —
        including:

        - **base only**: pair a `ConditionalDiagGaussian` /
          `ClassCondDiagGaussian` (or ``pyrox_flows.NumpyroBase`` in
          factory mode) base with otherwise unconditional transforms.
        - **transforms only**: pair an unconditional base
          (`flowjax.distributions.Normal`, …) with one or more
          coupling layers built with ``cond_dim > 0`` (or any transform
          wrapped in `Conditioner`).
        - **both**: a conditional base **and** condition-aware transforms;
          the same ``condition`` reaches both.

        Inside a coupling layer there are two distinct conditioning streams:
        the *data-dependent* untransformed half of ``x`` (always present —
        the whole point of coupling) and the *external* ``condition``
        (present only when ``cond_dim > 0``). The two are concatenated
        inside the inner MLP; users do not slice or merge them manually.

    Shape:
        Methods follow the single-event convention but accept a leading
        ``sample_shape`` that is vmapped over internally:

        - ``sample(key, sample_shape, condition)`` → ``sample_shape + data_shape``
        - ``log_prob(x, key, condition)``: ``x`` of shape
          ``sample_shape + data_shape`` → ``sample_shape``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from flowjax.distributions import Normal
        >>> from gauss_flows_models.flows import SurVAEFlow
        >>> from gauss_flows_maps.bijections import AffineCoupling
        >>> base = Normal(jnp.zeros(4))
        >>> flow = SurVAEFlow(base, [AffineCoupling(jr.key(0), shape=(4,))])
        >>> x = flow.sample(jr.key(1), (5,))
        >>> x.shape
        (5, 4)
        >>> flow.log_prob(x, jr.key(2)).shape
        (5,)
    """

    base_dist: AbstractDistribution
    transforms: tuple[AbstractBijection | AbstractSurjection, ...]
    data_shape: tuple[int, ...]

    def __init__(
        self,
        base_dist: AbstractDistribution,
        transforms: tuple[AbstractBijection | AbstractSurjection, ...]
        | list[AbstractBijection | AbstractSurjection],
        data_shape: tuple[int, ...] | None = None,
    ):
        self.base_dist = base_dist
        self.transforms = tuple(transforms)
        self.data_shape = data_shape if data_shape is not None else base_dist.shape

    @property
    def lower_bound(self) -> bool:
        return any(
            isinstance(t, AbstractSurjection) and t.lower_bound for t in self.transforms
        )

    def _split_keys(self, key: PRNGKeyArray) -> tuple[PRNGKeyArray, list[PRNGKeyArray]]:
        """Split ``key`` into one base-distribution key plus one per transform."""
        all_keys = jr.split(key, len(self.transforms) + 1)
        return all_keys[0], list(all_keys[1:])

    def _single_sample(self, key: PRNGKeyArray, cond: Array | None) -> Array:
        k_base, t_keys = self._split_keys(key)
        x = self.base_dist._sample(k_base, cond)
        for t, k_t in zip(self.transforms, t_keys, strict=True):
            x, _ = _to_data(t, x, k_t, cond)
        return x

    def _single_log_prob(
        self, x: Array, key: PRNGKeyArray, cond: Array | None
    ) -> Array:
        _k_base, t_keys = self._split_keys(key)
        z = x
        log_det = jnp.zeros(())
        for t, k_t in zip(reversed(self.transforms), reversed(t_keys), strict=True):
            z, ld = _to_base(t, z, k_t, cond)
            log_det = log_det + ld
        return self.base_dist._log_prob(z, cond) + log_det

    def sample(
        self,
        key: PRNGKeyArray,
        sample_shape: tuple[int, ...] = (),
        condition: ArrayLike | None = None,
    ) -> Array:
        """Sample by drawing from ``base_dist`` and pushing through to data.

        Each draw uses an independent key derived from ``key``; ``sample_shape``
        is realised via `jax.vmap` over a leading batch of keys, mirroring
        the FlowJax convention.
        """
        cond = None if condition is None else jnp.asarray(condition)

        if sample_shape == ():
            return self._single_sample(key, cond)
        n = 1
        for s in sample_shape:
            n *= s
        keys = jr.split(key, n)
        flat = jax.vmap(lambda k: self._single_sample(k, cond))(keys)
        return flat.reshape(sample_shape + flat.shape[1:])

    def log_prob(
        self,
        x: ArrayLike,
        key: PRNGKeyArray,
        condition: ArrayLike | None = None,
    ) -> Array:
        """Evaluate ``log p(x)`` (or its lower bound if any surjection is lower-bound).

        Accepts batched inputs of shape ``sample_shape + data_shape``; the
        leading ``sample_shape`` dimensions are vmapped over and each sample
        receives its own key derived from ``key``. For deterministic chains
        (bijections + non-stochastic surjections) the key is unused but still
        consumed by the dispatch.
        """
        cond = None if condition is None else jnp.asarray(condition)
        x = jnp.asarray(x)

        n_data = len(self.data_shape)
        # x: (*sample_shape, *data_shape) -> sample_shape: (*sample_shape,)
        if n_data > 0 and x.shape[-n_data:] != self.data_shape:
            raise ValueError(
                f"x trailing shape {x.shape[-n_data:]} does not match "
                f"data_shape {self.data_shape}."
            )
        sample_shape = x.shape if n_data == 0 else x.shape[:-n_data]

        if sample_shape == ():
            return self._single_log_prob(x, key, cond)

        n = 1
        for s in sample_shape:
            n *= s
        # flat: (n, *data_shape) for the vmap.
        flat = x.reshape((n, *self.data_shape))
        keys = jr.split(key, n)
        out = jax.vmap(lambda xi, ki: self._single_log_prob(xi, ki, cond))(flat, keys)
        return out.reshape(sample_shape)

sample

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

Sample by drawing from base_dist and pushing through to data.

Each draw uses an independent key derived from key; sample_shape is realised via jax.vmap over a leading batch of keys, mirroring the FlowJax convention.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/survae.py
def sample(
    self,
    key: PRNGKeyArray,
    sample_shape: tuple[int, ...] = (),
    condition: ArrayLike | None = None,
) -> Array:
    """Sample by drawing from ``base_dist`` and pushing through to data.

    Each draw uses an independent key derived from ``key``; ``sample_shape``
    is realised via `jax.vmap` over a leading batch of keys, mirroring
    the FlowJax convention.
    """
    cond = None if condition is None else jnp.asarray(condition)

    if sample_shape == ():
        return self._single_sample(key, cond)
    n = 1
    for s in sample_shape:
        n *= s
    keys = jr.split(key, n)
    flat = jax.vmap(lambda k: self._single_sample(k, cond))(keys)
    return flat.reshape(sample_shape + flat.shape[1:])

log_prob

log_prob(x: ArrayLike, key: PRNGKeyArray, condition: ArrayLike | None = None) -> Array

Evaluate log p(x) (or its lower bound if any surjection is lower-bound).

Accepts batched inputs of shape sample_shape + data_shape; the leading sample_shape dimensions are vmapped over and each sample receives its own key derived from key. For deterministic chains (bijections + non-stochastic surjections) the key is unused but still consumed by the dispatch.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/survae.py
def log_prob(
    self,
    x: ArrayLike,
    key: PRNGKeyArray,
    condition: ArrayLike | None = None,
) -> Array:
    """Evaluate ``log p(x)`` (or its lower bound if any surjection is lower-bound).

    Accepts batched inputs of shape ``sample_shape + data_shape``; the
    leading ``sample_shape`` dimensions are vmapped over and each sample
    receives its own key derived from ``key``. For deterministic chains
    (bijections + non-stochastic surjections) the key is unused but still
    consumed by the dispatch.
    """
    cond = None if condition is None else jnp.asarray(condition)
    x = jnp.asarray(x)

    n_data = len(self.data_shape)
    # x: (*sample_shape, *data_shape) -> sample_shape: (*sample_shape,)
    if n_data > 0 and x.shape[-n_data:] != self.data_shape:
        raise ValueError(
            f"x trailing shape {x.shape[-n_data:]} does not match "
            f"data_shape {self.data_shape}."
        )
    sample_shape = x.shape if n_data == 0 else x.shape[:-n_data]

    if sample_shape == ():
        return self._single_log_prob(x, key, cond)

    n = 1
    for s in sample_shape:
        n *= s
    # flat: (n, *data_shape) for the vmap.
    flat = x.reshape((n, *self.data_shape))
    keys = jr.split(key, n)
    out = jax.vmap(lambda xi, ki: self._single_log_prob(xi, ki, cond))(flat, keys)
    return out.reshape(sample_shape)

ClassCondFlow

Bases: Module

Class-conditional flow built on a ClassCondDiagGaussian base.

A thin convenience wrapper around SurVAEFlow that:

  • constructs a ClassCondDiagGaussian base with the given n_classes and event_shape;
  • exposes a label keyword in its public API (instead of the more generic condition) for ergonomics in the class-conditional case;
  • carries n_classes as static metadata for downstream tooling.

Only the base is class-conditioned. The transform chain must be unconditional — every transform's cond_shape must be None. This is because the class label is broadcast as a scalar int (a shape-() condition that the base requires for index lookup), which is incompatible with the (cond_dim,)-shaped condition that conditional couplings expect. If you want conditional transforms in addition to a class- conditional base, build a SurVAEFlow directly and pack a label-derived feature vector (e.g. one-hot) into a custom condition; this wrapper deliberately does not support that to keep the contract simple.

Parameters:

Name Type Description Default
key PRNGKeyArray

PRNG key used to initialise the base distribution.

required
n_classes int

Number of classes C (must be positive).

required
event_shape tuple[int, ...]

Single-event shape (D,).

required
transforms Sequence[AbstractBijection | AbstractSurjection]

Sequence of unconditional bijections / surjections, applied left-to-right in the base→data direction. Conditional transforms (cond_shape != None) are rejected at construction.

required
learn_mean bool

Forwarded to ClassCondDiagGaussian.

True
logscale_factor float

Forwarded to ClassCondDiagGaussian.

1.0
Shape
  • label: scalar int (cond_shape == ())
  • x / y: event_shape

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.flows import ClassCondFlow
>>> from gauss_flows_maps.bijections import AffineCoupling
>>> coupling = AffineCoupling(jr.key(0), shape=(4,))   # unconditional layer
>>> flow = ClassCondFlow(
...     jr.key(1), n_classes=3, event_shape=(4,),
...     transforms=[coupling],
... )
>>> label = jnp.int32(1)
>>> x = flow.sample(jr.key(2), label=label)
>>> log_p = flow.log_prob(x, jr.key(3), label=label)
>>> assert x.shape == (4,) and log_p.shape == ()
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/class_cond_flow.py
class ClassCondFlow(eqx.Module):
    """Class-conditional flow built on a `ClassCondDiagGaussian` base.

    A thin convenience wrapper around `SurVAEFlow` that:

    - constructs a `ClassCondDiagGaussian` base with the given
      ``n_classes`` and ``event_shape``;
    - exposes a ``label`` keyword in its public API (instead of the more
      generic ``condition``) for ergonomics in the class-conditional case;
    - carries ``n_classes`` as static metadata for downstream tooling.

    Only the **base** is class-conditioned. The transform chain must be
    unconditional — every transform's ``cond_shape`` must be ``None``. This
    is because the class label is broadcast as a scalar ``int`` (a shape-``()``
    condition that the base requires for index lookup), which is incompatible
    with the ``(cond_dim,)``-shaped condition that conditional couplings
    expect. If you want conditional transforms in addition to a class-
    conditional base, build a `SurVAEFlow` directly and pack a
    label-derived feature vector (e.g. one-hot) into a custom condition;
    this wrapper deliberately does not support that to keep the contract
    simple.

    Args:
        key: PRNG key used to initialise the base distribution.
        n_classes: Number of classes ``C`` (must be positive).
        event_shape: Single-event shape ``(D,)``.
        transforms: Sequence of unconditional bijections / surjections,
            applied left-to-right in the base→data direction. Conditional
            transforms (``cond_shape != None``) are rejected at construction.
        learn_mean: Forwarded to `ClassCondDiagGaussian`.
        logscale_factor: Forwarded to `ClassCondDiagGaussian`.

    Shape:
        - ``label``: scalar int (``cond_shape == ()``)
        - ``x`` / ``y``: ``event_shape``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.flows import ClassCondFlow
        >>> from gauss_flows_maps.bijections import AffineCoupling
        >>> coupling = AffineCoupling(jr.key(0), shape=(4,))   # unconditional layer
        >>> flow = ClassCondFlow(
        ...     jr.key(1), n_classes=3, event_shape=(4,),
        ...     transforms=[coupling],
        ... )
        >>> label = jnp.int32(1)
        >>> x = flow.sample(jr.key(2), label=label)
        >>> log_p = flow.log_prob(x, jr.key(3), label=label)
        >>> assert x.shape == (4,) and log_p.shape == ()
    """

    flow: SurVAEFlow
    n_classes: int = eqx.field(static=True)

    def __init__(
        self,
        key: PRNGKeyArray,
        *,
        n_classes: int,
        event_shape: tuple[int, ...],
        transforms: Sequence[AbstractBijection | AbstractSurjection],
        learn_mean: bool = True,
        logscale_factor: float = 1.0,
    ):
        # The class label is a scalar int; conditional transforms expect a
        # vector condition (cond_dim,). There is no single condition shape
        # that satisfies both base (()-shape) and a conditional transform,
        # so we reject the latter at construction with a clear message.
        for i, t in enumerate(transforms):
            t_cond = getattr(t, "cond_shape", None)
            if t_cond is not None:
                raise ValueError(
                    f"ClassCondFlow only conditions the base distribution; "
                    f"transforms[{i}] has cond_shape={t_cond!r}, but the "
                    "label is forwarded as a scalar int. Either drop "
                    "cond_dim from this transform, or build a SurVAEFlow "
                    "directly and pack a label-derived feature vector into "
                    "a custom condition."
                )
        base = ClassCondDiagGaussian(
            key,
            n_classes=n_classes,
            event_shape=event_shape,
            learn_mean=learn_mean,
            logscale_factor=logscale_factor,
        )
        self.flow = SurVAEFlow(base, transforms)
        self.n_classes = int(n_classes)

    def sample(
        self,
        key: PRNGKeyArray,
        sample_shape: tuple[int, ...] = (),
        *,
        label: ArrayLike,
    ) -> Array:
        """Sample by drawing from the class-conditional base and pushing through."""
        return self.flow.sample(
            key, sample_shape, condition=jnp.asarray(label, dtype=jnp.int32)
        )

    def log_prob(
        self,
        x: ArrayLike,
        key: PRNGKeyArray,
        *,
        label: ArrayLike,
    ) -> Array:
        """Evaluate ``log p(x | label)``."""
        return self.flow.log_prob(x, key, condition=jnp.asarray(label, dtype=jnp.int32))

sample

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

Sample by drawing from the class-conditional base and pushing through.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/class_cond_flow.py
def sample(
    self,
    key: PRNGKeyArray,
    sample_shape: tuple[int, ...] = (),
    *,
    label: ArrayLike,
) -> Array:
    """Sample by drawing from the class-conditional base and pushing through."""
    return self.flow.sample(
        key, sample_shape, condition=jnp.asarray(label, dtype=jnp.int32)
    )

log_prob

log_prob(x: ArrayLike, key: PRNGKeyArray, *, label: ArrayLike) -> Array

Evaluate log p(x | label).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/class_cond_flow.py
def log_prob(
    self,
    x: ArrayLike,
    key: PRNGKeyArray,
    *,
    label: ArrayLike,
) -> Array:
    """Evaluate ``log p(x | label)``."""
    return self.flow.log_prob(x, key, condition=jnp.asarray(label, dtype=jnp.int32))

Flow factories

gaussianization_flow builds the classic marginal-mixture + rotation stack; coupling_gaussianization_flow swaps the marginal step for spline coupling layers; iterative_rbig constructs the trainable iterative-RBIG flow. Each returns a FlowJax Transformed distribution.

gaussianization_flow

gaussianization_flow(key: PRNGKeyArray, *, n_dims: int, n_layers: int = 8, n_components: int = 8, rotation: str = 'householder', n_reflections: int | None = None, base_dist: AbstractDistribution | None = None) -> Transformed

Construct a Gaussianization flow.

Stacks n_layers alternating G∘R blocks, where each block is a marginal Gaussianization step G (a mixture-of-Gaussians CDF applied per dimension) followed by a rotation R (Householder, orthogonal, or LU-parametrised linear). Mixture means and Householder vectors are randomly initialised to break symmetry so gradient training has a signal to separate the components. The block stack is composed with a memory-efficient flowjax.bijections.Scan and wrapped in a base flowjax.distributions.Normal.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key.

required
n_dims int

Dimensionality of the data.

required
n_layers int

Number of flow layers. Defaults to 8.

8
n_components int

Number of mixture components for marginal Gaussianization. Defaults to 8.

8
rotation str

Type of rotation, one of "householder", "orthogonal", or "lu" (LU-parametrised linear + reverse permutation). Defaults to "householder".

'householder'
n_reflections int | None

Number of Householder reflections (only for "householder"). Defaults to n_dims.

None
base_dist AbstractDistribution | None

Optional base distribution override (must have event shape (n_dims,) and be unconditional). Defaults to a standard Normal.

None

Returns:

Type Description
Transformed

A flowjax Transformed distribution with log_prob and sample.

Raises:

Type Description
ValueError

If base_dist has the wrong event shape, is conditional, or rotation is not a recognised name.

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.flows import gaussianization_flow
>>> flow = gaussianization_flow(jr.key(0), n_dims=4, n_layers=4, n_components=8)
>>> flow.sample(jr.key(1), (8,)).shape
(8, 4)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/gaussianization.py
def gaussianization_flow(
    key: PRNGKeyArray,
    *,
    n_dims: int,
    n_layers: int = 8,
    n_components: int = 8,
    rotation: str = "householder",
    n_reflections: int | None = None,
    base_dist: AbstractDistribution | None = None,
) -> Transformed:
    """Construct a Gaussianization flow.

    Stacks ``n_layers`` alternating G∘R blocks, where each block is a
    marginal Gaussianization step G (a mixture-of-Gaussians CDF applied
    per dimension) followed by a rotation R (Householder, orthogonal, or
    LU-parametrised linear). Mixture means and Householder vectors are
    randomly initialised to break symmetry so gradient training has a
    signal to separate the components. The block stack is composed with a
    memory-efficient `flowjax.bijections.Scan` and wrapped in a
    base `flowjax.distributions.Normal`.

    Args:
        key: JAX random key.
        n_dims: Dimensionality of the data.
        n_layers: Number of flow layers. Defaults to 8.
        n_components: Number of mixture components for marginal Gaussianization.
            Defaults to 8.
        rotation: Type of rotation, one of ``"householder"``, ``"orthogonal"``,
            or ``"lu"`` (LU-parametrised linear + reverse permutation).
            Defaults to ``"householder"``.
        n_reflections: Number of Householder reflections (only for
            ``"householder"``). Defaults to ``n_dims``.
        base_dist: Optional base distribution override (must have event
            shape ``(n_dims,)`` and be unconditional). Defaults to a standard
            ``Normal``.

    Returns:
        A flowjax ``Transformed`` distribution with ``log_prob`` and ``sample``.

    Raises:
        ValueError: If ``base_dist`` has the wrong event shape, is
            conditional, or ``rotation`` is not a recognised name.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.flows import gaussianization_flow
        >>> flow = gaussianization_flow(jr.key(0), n_dims=4, n_layers=4, n_components=8)
        >>> flow.sample(jr.key(1), (8,)).shape
        (8, 4)
    """
    if n_reflections is None:
        n_reflections = n_dims

    shape = (n_dims,)
    if base_dist is None:
        base_dist = Normal(jnp.zeros(n_dims))
    else:
        if base_dist.shape != shape:
            raise ValueError(
                f"base_dist.shape {base_dist.shape} does not match (n_dims,) = {shape}."
            )
        if base_dist.cond_shape is not None:
            raise ValueError(
                "Conditional base distributions are not supported by "
                "gaussianization_flow (no condition is threaded through). "
                f"Got base_dist with cond_shape={base_dist.cond_shape}."
            )

    def make_layer(key):
        # Break symmetry at init: a plain MixtureGaussianCDF has means=0 and
        # a plain HouseholderRotation has deterministic params, so all
        # mixture components collapse to the same Gaussian and training
        # sees no gradient to push them apart. The Keras reference
        # (research_notebook/projects/gaussianization) uses Uniform(-3, 3)
        # means and RandomNormal Householder vectors for exactly this
        # reason.
        marginal_key, rot_key = jr.split(key)
        marginal = MixtureGaussianCDF(n_components=n_components, shape=shape)
        init_means = jr.uniform(
            marginal_key, marginal.means.shape, minval=-3.0, maxval=3.0
        )
        marginal = eqx.tree_at(lambda m: m.means, marginal, init_means)

        if rotation == "householder":
            rot = HouseholderRotation(n_reflections=n_reflections, shape=shape)
            init_params = jr.normal(rot_key, rot.params.shape)
            rot = eqx.tree_at(lambda r: r.params, rot, init_params)
        elif rotation == "orthogonal":
            rot = OrthogonalRotation(shape=shape)
        elif rotation == "lu":
            rot = LULinearPermute(shape=shape)
        else:
            raise ValueError(f"Unknown rotation type: {rotation!r}")
        return Chain([marginal, rot])

    keys = jr.split(key, n_layers)
    layers = eqx.filter_vmap(make_layer)(keys)
    bijection = Invert(Scan(layers))
    return Transformed(base_dist, bijection)

coupling_gaussianization_flow

coupling_gaussianization_flow(key: PRNGKeyArray, *, n_dims: int, n_layers: int = 8, n_bins: int = 8, nn_width: int = 64, nn_depth: int = 2, interval: float = 5.0, invert: bool = True) -> Transformed

Construct a coupling-based Gaussianization flow.

Stacks n_layers alternating C∘P blocks, where each block is a rational-quadratic-spline coupling layer C followed by a permutation P (a flowjax.bijections.Flip for n_dims == 2, a random flowjax.bijections.Permute otherwise; no permutation for n_dims == 1). Unlike gaussianization_flow, the coupling conditioner lets each layer represent non-linear, cross-coordinate transformations. The block stack is composed with flowjax.bijections.Scan and wrapped in a base flowjax.distributions.Normal.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key.

required
n_dims int

Dimensionality of the data.

required
n_layers int

Number of coupling layers. Defaults to 8.

8
n_bins int

Number of spline bins in each coupling layer. Defaults to 8.

8
nn_width int

Hidden layer width for coupling conditioner. Defaults to 64.

64
nn_depth int

Depth of the coupling conditioner MLP. Defaults to 2.

2
interval float

Interval for the rational quadratic spline. Defaults to 5.0.

5.0
invert bool

Whether to invert the bijection so log_prob runs in the fast direction. Defaults to True.

True

Returns:

Type Description
Transformed

A flowjax Transformed distribution with log_prob and sample.

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.flows import coupling_gaussianization_flow
>>> flow = coupling_gaussianization_flow(jr.key(0), n_dims=4, n_layers=2)
>>> flow.sample(jr.key(1), (8,)).shape
(8, 4)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/gaussianization.py
def coupling_gaussianization_flow(
    key: PRNGKeyArray,
    *,
    n_dims: int,
    n_layers: int = 8,
    n_bins: int = 8,
    nn_width: int = 64,
    nn_depth: int = 2,
    interval: float = 5.0,
    invert: bool = True,
) -> Transformed:
    """Construct a coupling-based Gaussianization flow.

    Stacks ``n_layers`` alternating C∘P blocks, where each block is a
    rational-quadratic-spline coupling layer C followed by a permutation P
    (a `flowjax.bijections.Flip` for ``n_dims == 2``, a random
    `flowjax.bijections.Permute` otherwise; no permutation for
    ``n_dims == 1``). Unlike `gaussianization_flow`, the coupling
    conditioner lets each layer represent non-linear, cross-coordinate
    transformations. The block stack is composed with
    `flowjax.bijections.Scan` and wrapped in a base
    `flowjax.distributions.Normal`.

    Args:
        key: JAX random key.
        n_dims: Dimensionality of the data.
        n_layers: Number of coupling layers. Defaults to 8.
        n_bins: Number of spline bins in each coupling layer. Defaults to 8.
        nn_width: Hidden layer width for coupling conditioner. Defaults to 64.
        nn_depth: Depth of the coupling conditioner MLP. Defaults to 2.
        interval: Interval for the rational quadratic spline. Defaults to 5.0.
        invert: Whether to invert the bijection so ``log_prob`` runs in the
            fast direction. Defaults to True.

    Returns:
        A flowjax ``Transformed`` distribution with ``log_prob`` and ``sample``.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.flows import coupling_gaussianization_flow
        >>> flow = coupling_gaussianization_flow(jr.key(0), n_dims=4, n_layers=2)
        >>> flow.sample(jr.key(1), (8,)).shape
        (8, 4)
    """
    shape = (n_dims,)
    base_dist = Normal(jnp.zeros(n_dims))

    def make_layer(key):
        bij_key, perm_key = jr.split(key)
        coupling = RQSplineCoupling(
            key=bij_key,
            shape=shape,
            n_bins=n_bins,
            interval=interval,
            nn_width=nn_width,
            nn_depth=nn_depth,
        )
        if n_dims == 1:
            return coupling
        elif n_dims == 2:
            return Chain([coupling, Flip(shape)]).merge_chains()  # ty: ignore[missing-argument]
        perm = Permute(jr.permutation(perm_key, jnp.arange(n_dims)))
        return Chain([coupling, perm]).merge_chains()

    keys = jr.split(key, n_layers)
    layers = eqx.filter_vmap(make_layer)(keys)
    bijection = Invert(Scan(layers)) if invert else Scan(layers)
    return Transformed(base_dist, bijection)

iterative_rbig

iterative_rbig(key: PRNGKeyArray, *, n_dims: int, n_layers: int = 100, n_components: int = 8, rotation: str = 'householder', n_reflections: int | None = None) -> Transformed

Construct an iterative RBIG (Rotation-Based Iterative Gaussianization) flow.

Implements the classic RBIG algorithm as a normalizing flow: each of n_layers iterations alternates a marginal Gaussianization step G with a rotation R (the G∘R block). This is a thin wrapper around gauss_flows.gaussianization_flow with a large default n_layers reflecting the many shallow iterations RBIG typically uses; all arguments are forwarded unchanged.

Parameters:

Name Type Description Default
key PRNGKeyArray

JAX random key.

required
n_dims int

Dimensionality of the data.

required
n_layers int

Number of RBIG iterations. Defaults to 100.

100
n_components int

Number of mixture components for marginal Gaussianization. Defaults to 8.

8
rotation str

Type of rotation, either "householder" or "orthogonal". Defaults to "householder".

'householder'
n_reflections int | None

Number of Householder reflections. Defaults to n_dims.

None

Returns:

Type Description
Transformed

A flowjax Transformed distribution with log_prob and sample.

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.flows import iterative_rbig
>>> flow = iterative_rbig(jr.key(0), n_dims=4, n_layers=3, n_components=4)
>>> flow.sample(jr.key(1), (5,)).shape
(5, 4)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/rbig.py
def iterative_rbig(
    key: PRNGKeyArray,
    *,
    n_dims: int,
    n_layers: int = 100,
    n_components: int = 8,
    rotation: str = "householder",
    n_reflections: int | None = None,
) -> Transformed:
    """Construct an iterative RBIG (Rotation-Based Iterative Gaussianization) flow.

    Implements the classic RBIG algorithm as a normalizing flow: each of
    ``n_layers`` iterations alternates a marginal Gaussianization step G
    with a rotation R (the G∘R block). This is a thin wrapper around
    `gauss_flows.gaussianization_flow` with a large default
    ``n_layers`` reflecting the many shallow iterations RBIG typically
    uses; all arguments are forwarded unchanged.

    Args:
        key: JAX random key.
        n_dims: Dimensionality of the data.
        n_layers: Number of RBIG iterations. Defaults to 100.
        n_components: Number of mixture components for marginal Gaussianization.
            Defaults to 8.
        rotation: Type of rotation, either ``"householder"`` or
            ``"orthogonal"``. Defaults to ``"householder"``.
        n_reflections: Number of Householder reflections. Defaults to ``n_dims``.

    Returns:
        A flowjax ``Transformed`` distribution with ``log_prob`` and ``sample``.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.flows import iterative_rbig
        >>> flow = iterative_rbig(jr.key(0), n_dims=4, n_layers=3, n_components=4)
        >>> flow.sample(jr.key(1), (5,)).shape
        (5, 4)
    """
    return gaussianization_flow(
        key,
        n_dims=n_dims,
        n_layers=n_layers,
        n_components=n_components,
        rotation=rotation,
        n_reflections=n_reflections,
    )

RBIG warm-start

Rotation-Based Iterative Gaussianization fits each block in closed form from data — per-dimension Gaussian-mixture CDFs followed by a random/PCA rotation — giving a strong warm start with no gradient training. The result is an ordinary flow that can be used as-is or fine-tuned with fit_gaussianization_flow.

fit_rbig

fit_rbig(x: ArrayLike, *, n_layers: int = 10, n_components: int = 8, random_state: int = 0) -> Transformed

Fit an iterative-Gaussianization (RBIG) flow to data in closed form.

Greedily walks n_layers blocks of [FixedRotation (PCA), MixtureGaussianCDF (GMM per-dim)], fitting each block directly from the current data state — a per-dimension Gaussian-mixture EM fit in JAX, no gradient training — and propagating the data forward before the next block. The result is a warm start: a flowjax.distributions.Transformed whose log_prob is already a reasonable density estimator and can be refined further by the usual NLL minimisation (see gauss_flows.fit_gaussianization_flow).

Parameters:

Name Type Description Default
x ArrayLike

Training data of shape (n, d).

required
n_layers int

Number of (rotation, marginal) blocks. Defaults to 10.

10
n_components int

Mixture components K per marginal layer. Defaults to 8.

8
random_state int

Base seed for the k-means++ draws of the per-dim GMM EM fits. Each fit uses random_state + block_idx * 1000 + dim_idx. Defaults to 0.

0

Returns:

Type Description
Transformed

A flowjax Transformed distribution over ℝ^d whose bijection

Transformed

Gaussianises x, with log_prob and sample.

Raises:

Type Description
ValueError

If x is not 2-D.

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.inference import fit_rbig
>>> x = jr.normal(jr.key(0), (500, 2))
>>> flow = fit_rbig(x, n_layers=4, n_components=4)
>>> flow.sample(jr.key(1), (8,)).shape
(8, 2)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/init/rbig.py
def fit_rbig(
    x: ArrayLike,
    *,
    n_layers: int = 10,
    n_components: int = 8,
    random_state: int = 0,
) -> Transformed:
    """Fit an iterative-Gaussianization (RBIG) flow to data in closed form.

    Greedily walks ``n_layers`` blocks of ``[FixedRotation (PCA),
    MixtureGaussianCDF (GMM per-dim)]``, fitting each block directly from
    the current data state — a per-dimension Gaussian-mixture EM fit in
    JAX, no gradient training — and propagating the data forward
    before the next block. The result is a warm start: a
    `flowjax.distributions.Transformed` whose ``log_prob`` is
    already a reasonable density estimator and can be refined further by
    the usual NLL minimisation (see
    `gauss_flows.fit_gaussianization_flow`).

    Args:
        x: Training data of shape ``(n, d)``.
        n_layers: Number of ``(rotation, marginal)`` blocks. Defaults to 10.
        n_components: Mixture components ``K`` per marginal layer. Defaults
            to 8.
        random_state: Base seed for the k-means++ draws of the per-dim GMM
            EM fits. Each fit uses
            ``random_state + block_idx * 1000 + dim_idx``. Defaults to 0.

    Returns:
        A flowjax ``Transformed`` distribution over ℝ^d whose bijection
        Gaussianises ``x``, with ``log_prob`` and ``sample``.

    Raises:
        ValueError: If ``x`` is not 2-D.

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.inference import fit_rbig
        >>> x = jr.normal(jr.key(0), (500, 2))
        >>> flow = fit_rbig(x, n_layers=4, n_components=4)
        >>> flow.sample(jr.key(1), (8,)).shape
        (8, 2)
    """
    x_np = np.asarray(x, dtype=np.float32)
    if x_np.ndim != 2:
        raise ValueError(f"x must be 2-D (n, d); got shape {x_np.shape}")
    n_dims = x_np.shape[-1]

    bijections = []
    y = x_np
    for block_idx in range(int(n_layers)):
        rot = FixedRotation.from_data(y)
        bijections.append(rot)
        y = _push_forward(rot, y)

        marg = _fit_marginal(y, n_components, block_idx, random_state)
        bijections.append(marg)
        y = _push_forward(marg, y)

    base_dist = Normal(jnp.zeros(n_dims))
    bijection = Invert(Chain(bijections))
    return Transformed(base_dist, bijection)

fit_rbig_coupling

fit_rbig_coupling(x: ArrayLike, key: PRNGKeyArray, *, n_layers: int = 6, n_components: int = 8, nn_width: int = 64, nn_depth: int = 2, log_scale_bound: float = 5.0, random_state: int = 0) -> Transformed

Warm-start an RBIG-style coupling flow in closed form.

Each block is [FixedRotation (PCA), MixtureGaussianCDFCoupling]. The coupling's conditioner is initialised in closed form — no gradient training — with a zero kernel and a bias set from per-b-dim Gaussian-mixture EM fits (via _init_coupling_from_fits), so the layer starts as a constant-in-x_a mixture-CDF transform on the x_b half — numerically equivalent to a diagonal marginal fit on the x_b dims. Gradient training (see gauss_flows.fit_gaussianization_flow) can then break the constancy and let the conditioner modulate on x_a.

Parameters:

Name Type Description Default
x ArrayLike

Training data of shape (n, d) with even d ≥ 2.

required
key PRNGKeyArray

JAX random key for the conditioner MLPs' hidden-layer init.

required
n_layers int

Number of (rotation, coupling) blocks. Defaults to 6.

6
n_components int

Mixture components per transformed dim. Defaults to 8.

8
nn_width int

Hidden layer width of each conditioner MLP. Defaults to 64.

64
nn_depth int

Depth of each conditioner MLP. Defaults to 2.

2
log_scale_bound float

Tanh bound on per-dim log-scales. Must match the value used at gradient-training time. Defaults to 5.0.

5.0
random_state int

Base seed for per-dim GMM EM fits. Defaults to 0.

0

Returns:

Type Description
Transformed

A flowjax Transformed distribution with log_prob and sample.

Raises:

Type Description
ValueError

If x is not 2-D, or d is less than 2 or odd (the half-swap coupling pair requires an even number of dims).

Examples:

>>> import jax.random as jr
>>> from gauss_flows_models.inference import fit_rbig_coupling
>>> x = jr.normal(jr.key(0), (500, 2))
>>> flow = fit_rbig_coupling(x, jr.key(1), n_layers=2, n_components=4)
>>> flow.sample(jr.key(2), (8,)).shape
(8, 2)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/init/rbig.py
def fit_rbig_coupling(
    x: ArrayLike,
    key: PRNGKeyArray,
    *,
    n_layers: int = 6,
    n_components: int = 8,
    nn_width: int = 64,
    nn_depth: int = 2,
    log_scale_bound: float = 5.0,
    random_state: int = 0,
) -> Transformed:
    """Warm-start an RBIG-style coupling flow in closed form.

    Each block is ``[FixedRotation (PCA), MixtureGaussianCDFCoupling]``.
    The coupling's conditioner is initialised in closed form — no gradient
    training — with a zero kernel and a bias set from per-b-dim Gaussian-mixture
    EM fits (via `_init_coupling_from_fits`), so
    the layer starts as a constant-in-``x_a`` mixture-CDF transform on the
    ``x_b`` half — numerically equivalent to a diagonal marginal fit on
    the ``x_b`` dims. Gradient training (see
    `gauss_flows.fit_gaussianization_flow`) can then break the
    constancy and let the conditioner modulate on ``x_a``.

    Args:
        x: Training data of shape ``(n, d)`` with even ``d ≥ 2``.
        key: JAX random key for the conditioner MLPs' hidden-layer init.
        n_layers: Number of ``(rotation, coupling)`` blocks. Defaults to 6.
        n_components: Mixture components per transformed dim. Defaults to 8.
        nn_width: Hidden layer width of each conditioner MLP. Defaults to 64.
        nn_depth: Depth of each conditioner MLP. Defaults to 2.
        log_scale_bound: Tanh bound on per-dim log-scales. Must match the
            value used at gradient-training time. Defaults to 5.0.
        random_state: Base seed for per-dim GMM EM fits. Defaults to 0.

    Returns:
        A flowjax ``Transformed`` distribution with ``log_prob`` and ``sample``.

    Raises:
        ValueError: If ``x`` is not 2-D, or ``d`` is less than 2 or odd
            (the half-swap coupling pair requires an even number of dims).

    Examples:
        >>> import jax.random as jr
        >>> from gauss_flows_models.inference import fit_rbig_coupling
        >>> x = jr.normal(jr.key(0), (500, 2))
        >>> flow = fit_rbig_coupling(x, jr.key(1), n_layers=2, n_components=4)
        >>> flow.sample(jr.key(2), (8,)).shape
        (8, 2)
    """
    import jax.random as jr

    x_np = np.asarray(x, dtype=np.float32)
    if x_np.ndim != 2:
        raise ValueError(f"x must be 2-D (n, d); got shape {x_np.shape}")
    n_dims = x_np.shape[-1]
    if n_dims < 2:
        raise ValueError("fit_rbig_coupling needs n_dims >= 2 for a non-trivial split.")
    if n_dims % 2 != 0:
        # With odd n_dims the two coupling passes do not cover complementary
        # halves: `MixtureGaussianCDFCoupling` always uses
        # `untransformed_dim = n_dims // 2 = floor(n_dims/2)`, so each pass
        # transforms `ceil(n_dims/2)` coordinates. After the intervening Flip,
        # one dim ends up in *both* b-halves and gets transformed twice per
        # block, breaking the zero-kernel ≡ diagonal-RBIG equivalence.
        raise ValueError(
            f"fit_rbig_coupling requires even n_dims for the half-swap pair to "
            f"cover each dim exactly once; got n_dims={n_dims}. Pad the data "
            f"(e.g. via Augment) or use fit_rbig for odd dimensions."
        )

    keys = jr.split(key, int(n_layers))
    bijections = []
    y = x_np
    d_a = n_dims // 2
    for block_idx in range(int(n_layers)):
        rot = FixedRotation.from_data(y)
        bijections.append(rot)
        y = _push_forward(rot, y)

        # Two couplings with opposing halves (the flowjax equivalent of
        # the Keras `[coupling(mask=m), coupling(mask=~m)]` pair). Between
        # them a `Flip` swaps the halves so the second coupling sees the
        # original untransformed half as its b-half. A trailing `Flip`
        # restores dim order so the next block's PCA fit sees the
        # expected orientation.
        #
        # `current_perm[i]` = the original-dim (pre-any-flip) index that
        # currently sits at position `i`. At block start this is
        # `[0, 1, ..., d-1]`; each Flip reverses it. We use it to seed
        # each coupling's per-b-dim GMM fit by its *original* dim index,
        # so the paired couplings reproduce the same per-dim seeding a
        # diagonal-marginal block would use (mirroring the research-
        # notebook mask-based code, where `_dim_seed` takes the original
        # dim index).
        current_perm = np.arange(n_dims)
        coup_keys = jr.split(keys[block_idx], 2)
        for side_idx in range(2):
            seed_dims = current_perm[d_a:]
            bij = MixtureGaussianCDFCoupling(
                coup_keys[side_idx],
                shape=(n_dims,),
                n_components=n_components,
                nn_width=nn_width,
                nn_depth=nn_depth,
                log_scale_bound=log_scale_bound,
            )
            bij, y = _init_coupling_from_fits(
                bij, y, block_idx, random_state, seed_dim_idx=seed_dims
            )
            bijections.append(bij)

            flip = Flip(shape=(n_dims,))  # ty: ignore[missing-argument]
            bijections.append(flip)
            y = _push_forward(flip, y)
            current_perm = current_perm[::-1].copy()

    base_dist = Normal(jnp.zeros(n_dims))
    bijection = Invert(Chain(bijections))
    return Transformed(base_dist, bijection)

State-space flows

Three constructions that put a normalizing flow and a state-space model together. All take their state-space pieces from gaussx, which is a declared dependency of gauss-flows-models (pinned by git tag, since gaussx is not on PyPI).

normalizing_kalman_filter itself never imports gaussx — it duck-types on the base distribution's cond_shape — so it works with any (T, M)-shaped base. ConjugateTransformFilter and TransformFilter import gaussx at module level.

Normalizing Kalman Filter

normalizing_kalman_filter composes a linear-Gaussian state-space base with a per-timestep observation warp (de Bézenac et al., 2020). The base supplies the density over the latent series and the warp maps each timestep into observation space, so the Markov structure survives and the Kalman recursion still applies in latent space.

The base is typically a LinearGaussianSSM, whose log_prob is the Kalman filter's marginal likelihood; build it with masked=True for partially observed series, or with LinearGaussianSSM.from_sde for a Gaussian-process prior over irregular observation times. The example below uses it.

Two things it exists to get right. First, the construction needs two nested Vmaps — one over channels, one over time — and skipping the channel one raises a shape error that mentions neither Vmap nor the axis at fault. The constructor supplies the time axis and validates the channel axis with an error that names the fix.

Second, and more consequential: the default recommendation deviates from the source paper. The paper uses a coupling flow specifically to model cross-series dependence. With a masked base — partially-observed series — that is unsound. Marginalising the unobserved channels commutes with the warp only when the warp's Jacobian is diagonal; a coupling bijection's is triangular, so a missing entry in the conditioning half corrupts the transform of channels that were observed. Measured on a 2-layer coupling flow with M = 6 and ~40% missing, the error on the observed channels alone had median 0.49 against a signal scale of 0.43 — the corruption is the size of the signal, and it looks like underfitting rather than a bug. An elementwise warp gives exactly 0.0.

So the recommendation is an elementwise warp with the cross-channel structure in the state-space model's H and R, where the Kalman recursion handles it exactly. A mask-conditioned warp is permitted; an unconditional channel-mixing warp over a masked base is refused at construction. An unmasked base places no restriction on the warp.

Two details that follow from this and are easy to get wrong:

  • The log-det is restricted to the observed channels. Change of variables applies to the coordinates being modelled, so with a masked base the Jacobian term is summed under the mask. A plain Transformed sums it over all T × M entries, adding terms for values that were never measured — the density then stops being a marginal likelihood, off by a data-dependent offset. The constructor wraps elementwise warps to handle this automatically, subtracting the unobserved channels' contributions from the warp's own log-determinant rather than rebuilding the total from autodiff — so a bijection that reports a log-det differing from its map's derivative (HistogramCDF(method="monotonic") is the in-repo example) keeps its declared value, and an all-observed mask reproduces the ordinary density exactly. In the mask-conditioned case (2) none of this applies: a channel-mixing Jacobian does not decompose per channel, so there log_prob is a training objective, not a marginal likelihood.
  • A warp is classified structurally, never by measurement. Sampling the Jacobian cannot establish diagonality, in two independent ways. OrthogonalRotation starts with zero Cayley parameters, so it is the identity when you build it and would pass any probe — then becomes a dense rotation the moment an optimiser touches it. And a parameter-free bijection need not have a constant Jacobian either: a fixed shear that engages only past a threshold looks diagonal at every probe point drawn from the bulk and mixes channels in the tail. So classification comes from the type. Recognised are flowjax's elementwise family and everything in gauss_flows' own transforms.bijections.elementwise subpackage — MixtureGaussianCDF, MixtureLogisticCDF, RQSplineMarginal, HistogramCDF, InverseGaussCDF, Elementwise. A scalar bijection lifted with Vmap(..., axis_size=M) is admitted whatever it contains, since 1x1 Jacobian blocks are diagonal by construction. For a warp outside all of that, pass assume_elementwise_warp=True to assert the property yourself; a probe still refuses assertions it can immediately disprove, but passing it proves nothing.
  • Mind the warp's direction. warp maps the Gaussian base to observations. The Gaussianising CDFs go the other way — MixtureGaussianCDF maps data to Gaussian — so they belong inside an Invert: Invert(MixtureGaussianCDF(n_components=8, shape=(M,))). Passing one directly builds a model of the pushforward through the Gaussianiser rather than of the observations. fit_rbig already follows this convention, returning Transformed(base, Invert(Chain(...))). RQSplineMarginal and a lifted RationalQuadraticSpline are direction-neutral.
  • HistogramCDF needs a probit step. It maps data to a uniform variable, not a Gaussian one, so Invert(HistogramCDF(...)) expects [0, 1] inputs while the base supplies all of ℝ; values outside clamp to the fitted bin edges and the density stops being normalised. Compose it with the step MixtureGaussianCDF already includes: Invert(Chain([HistogramCDF(...), InverseGaussCDF(shape=(M,))])).

normalizing_kalman_filter

normalizing_kalman_filter(base: AbstractDistribution, warp: AbstractBijection, *, n_steps: int | None = None, assume_elementwise_warp: bool = False) -> Transformed

Compose a state-space base with a per-timestep observation warp.

Builds the Normalizing Kalman Filter of de Bézenac et al. (2020) by lifting warp over the time axis, so the base's Markov structure is preserved and the Kalman recursion still applies in latent space. See the module docstring for the two-nested-flowjax.bijections.Vmap construction and the reason a masked base restricts which warps are allowed.

Parameters:

Name Type Description Default
base AbstractDistribution

Any distribution with event shape (T, M) — typically a linear-Gaussian state-space distribution, gauss_flows_models.distributions.LinearGaussianSSM, built with masked=True for the masked case. A non-None cond_shape is taken to mean the base consumes an observation mask.

required
warp AbstractBijection

Bijection with event shape (M,), mapping base values to observations. It is applied independently at each of the T timesteps.

required
n_steps int | None

Time-axis size T. Defaults to base.shape[0].

None
assume_elementwise_warp bool

Assert that warp is elementwise when its type is not recognised as such. Only consulted for a masked base. gauss_flows cannot verify the property — see _mixes_channels for why sampling the Jacobian cannot establish it — so this is a claim you are making, and getting it wrong silently corrupts the observed channels and invalidates the marginal likelihood. A cheap numerical probe still runs and refuses an assertion it can immediately disprove, but passing it is not evidence of correctness.

False

Returns:

Type Description
Transformed

A flowjax.distributions.Transformed over (T, M) observations.

Raises:

Type Description
ValueError

If base is not (T, M)-shaped, if warp is not (M,)-shaped or does not match the base's channel count, if n_steps disagrees with base.shape[0], or if base consumes a condition while warp mixes channels without consuming that condition itself. The last case silently corrupts the observed channels; the message names the three coherent alternatives.

Shape
  • Base event: (T, M)
  • Warp event: (M,) (single timestep, single event)
  • Returned distribution event: (T, M)
  • log_prob of a (T, M) observation: scalar ()
  • sample(key, (S,)): (S, T, M)

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.bijections import Affine, Chain, RationalQuadraticSpline, Vmap
>>> from gauss_flows_models.distributions import LinearGaussianSSM
>>> from gauss_flows_models.filters import normalizing_kalman_filter
>>> M, T = 4, 8
>>> # 1. Channel axis: lift the scalar spline to an M-vector, THEN chain.
>>> warp = Chain([
...     Vmap(RationalQuadraticSpline(knots=6, interval=4),
...          in_axes=None, axis_size=M),
...     Affine(loc=jnp.zeros(M), scale=jnp.ones(M)),
... ])
>>> # A state-space base over (T, M): s_t = A s_{t−1} + q_t, y_t = H s_t + v_t.
>>> base = LinearGaussianSSM(
...     transition=0.9 * jnp.eye(M), obs_model=jnp.eye(M),
...     process_noise=0.1 * jnp.eye(M), obs_noise=0.1 * jnp.eye(M),
...     init_mean=jnp.zeros(M), init_cov=jnp.eye(M), n_steps=T,
... )
>>> nkf = normalizing_kalman_filter(base, warp)   # 2. Time axis, for you.
>>> y = nkf.sample(jr.key(0))
>>> nkf.shape, nkf.log_prob(y).shape
((8, 4), ())

With missing data, build the base with masked=True and pass the observation mask as the condition:

>>> masked_base = LinearGaussianSSM(
...     transition=0.9 * jnp.eye(M), obs_model=jnp.eye(M),
...     process_noise=0.1 * jnp.eye(M), obs_noise=0.1 * jnp.eye(M),
...     init_mean=jnp.zeros(M), init_cov=jnp.eye(M), n_steps=T,
...     masked=True,
... )
>>> masked_nkf = normalizing_kalman_filter(masked_base, warp)
>>> mask = jr.bernoulli(jr.key(1), 0.7, (T, M))
>>> masked_nkf.log_prob(y, condition=mask).shape
()
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/kalman.py
def normalizing_kalman_filter(
    base: AbstractDistribution,
    warp: AbstractBijection,
    *,
    n_steps: int | None = None,
    assume_elementwise_warp: bool = False,
) -> Transformed:
    r"""Compose a state-space base with a per-timestep observation warp.

    Builds the Normalizing Kalman Filter of de Bézenac et al. (2020) by lifting
    ``warp`` over the time axis, so the base's Markov structure is preserved and
    the Kalman recursion still applies in latent space. See the module docstring
    for the two-nested-`flowjax.bijections.Vmap` construction and the reason a
    masked base restricts which warps are allowed.

    Args:
        base: Any distribution with event shape ``(T, M)`` — typically a
            linear-Gaussian state-space distribution,
            `gauss_flows_models.distributions.LinearGaussianSSM`, built with
            ``masked=True`` for the masked case. A non-``None``
            ``cond_shape`` is taken to mean the base consumes an observation
            mask.
        warp: Bijection with event shape ``(M,)``, mapping base values to
            observations. It is applied independently at each of the ``T``
            timesteps.
        n_steps: Time-axis size ``T``. Defaults to ``base.shape[0]``.
        assume_elementwise_warp: Assert that ``warp`` is elementwise when its
            type is not recognised as such. Only consulted for a masked base.
            gauss_flows cannot verify the property — see `_mixes_channels` for
            why sampling the Jacobian cannot establish it — so this is a claim
            you are making, and getting it wrong silently corrupts the observed
            channels and invalidates the marginal likelihood. A cheap numerical
            probe still runs and refuses an assertion it can immediately
            disprove, but passing it is not evidence of correctness.

    Returns:
        A `flowjax.distributions.Transformed` over ``(T, M)`` observations.

    Raises:
        ValueError: If ``base`` is not ``(T, M)``-shaped, if ``warp`` is not
            ``(M,)``-shaped or does not match the base's channel count, if
            ``n_steps`` disagrees with ``base.shape[0]``, or if ``base``
            consumes a condition while ``warp`` mixes channels without
            consuming that condition itself. The last case silently corrupts
            the observed channels; the message names the three coherent
            alternatives.

    Shape:
        - Base event: ``(T, M)``
        - Warp event: ``(M,)`` (single timestep, single event)
        - Returned distribution event: ``(T, M)``
        - ``log_prob`` of a ``(T, M)`` observation: scalar ``()``
        - ``sample(key, (S,))``: ``(S, T, M)``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from flowjax.bijections import Affine, Chain, RationalQuadraticSpline, Vmap
        >>> from gauss_flows_models.distributions import LinearGaussianSSM
        >>> from gauss_flows_models.filters import normalizing_kalman_filter
        >>> M, T = 4, 8
        >>> # 1. Channel axis: lift the scalar spline to an M-vector, THEN chain.
        >>> warp = Chain([
        ...     Vmap(RationalQuadraticSpline(knots=6, interval=4),
        ...          in_axes=None, axis_size=M),
        ...     Affine(loc=jnp.zeros(M), scale=jnp.ones(M)),
        ... ])
        >>> # A state-space base over (T, M): s_t = A s_{t−1} + q_t, y_t = H s_t + v_t.
        >>> base = LinearGaussianSSM(
        ...     transition=0.9 * jnp.eye(M), obs_model=jnp.eye(M),
        ...     process_noise=0.1 * jnp.eye(M), obs_noise=0.1 * jnp.eye(M),
        ...     init_mean=jnp.zeros(M), init_cov=jnp.eye(M), n_steps=T,
        ... )
        >>> nkf = normalizing_kalman_filter(base, warp)   # 2. Time axis, for you.
        >>> y = nkf.sample(jr.key(0))
        >>> nkf.shape, nkf.log_prob(y).shape
        ((8, 4), ())

        With missing data, build the base with ``masked=True`` and pass the
        observation mask as the condition:

        >>> masked_base = LinearGaussianSSM(
        ...     transition=0.9 * jnp.eye(M), obs_model=jnp.eye(M),
        ...     process_noise=0.1 * jnp.eye(M), obs_noise=0.1 * jnp.eye(M),
        ...     init_mean=jnp.zeros(M), init_cov=jnp.eye(M), n_steps=T,
        ...     masked=True,
        ... )
        >>> masked_nkf = normalizing_kalman_filter(masked_base, warp)
        >>> mask = jr.bernoulli(jr.key(1), 0.7, (T, M))
        >>> masked_nkf.log_prob(y, condition=mask).shape
        ()
    """
    if len(base.shape) != 2:
        raise ValueError(
            "base must have event shape (T, M) — a time axis and a channel "
            f"axis; got {base.shape}."
        )
    if len(warp.shape) != 1:
        raise ValueError(
            "warp must have event shape (M,), i.e. a single timestep. Scalar "
            "bijections need lifting over the channel axis first, e.g. "
            "Vmap(RationalQuadraticSpline(...), in_axes=None, axis_size=M); "
            f"got warp.shape={warp.shape}."
        )

    n_base_steps, n_channels = base.shape
    if warp.shape[0] != n_channels:
        raise ValueError(
            f"warp event shape {warp.shape} does not match the base's channel "
            f"count M={n_channels} (base event shape {base.shape})."
        )
    if n_steps is not None and n_steps != n_base_steps:
        raise ValueError(
            f"n_steps={n_steps} disagrees with the base's time axis T={n_base_steps}."
        )

    # Case 3: a masked base with an unconditional channel-mixing warp. The warp
    # is unconditional exactly when cond_shape is None; a conditioned warp is
    # case 2 and permitted, so it is never classified.
    masked = base.cond_shape is not None
    elementwise = warp.cond_shape is None and not _mixes_channels(warp)
    if masked and warp.cond_shape is None and not elementwise:
        if not assume_elementwise_warp:
            raise ValueError(_MASKED_COUPLING_MESSAGE)
        # Trust the caller, but reject an assertion the probe already refutes.
        if _probe_mixes_channels(warp):
            raise ValueError(
                "assume_elementwise_warp=True, but a numerical probe found "
                "off-diagonal Jacobian mass in this warp, so the assertion is "
                "false as written. (The probe is only a sanity check — it can "
                "miss channel mixing that appears at other inputs or other "
                "parameter values, so passing it would not have proved the "
                "warp elementwise.)"
            )
        elementwise = True

    if warp.cond_shape is not None:
        # Case 2 only. The warp's condition is one timestep's worth; the base's
        # is the whole series. Check that here, where the time axis can be
        # named, rather than letting flowjax report a bare cond_shape mismatch.
        if base.cond_shape is None:
            raise ValueError(
                f"warp consumes a condition of shape {warp.cond_shape} but base "
                "does not consume one at all. A conditional warp needs a base "
                "that takes the same per-timestep condition (the observation "
                "mask), e.g. LinearGaussianSSM(..., masked=True)."
            )
        if tuple(base.cond_shape) != (n_base_steps, *warp.cond_shape):
            raise ValueError(
                f"base.cond_shape={base.cond_shape} does not match the warp's "
                f"per-timestep condition {warp.cond_shape} lifted over the time "
                f"axis, which would be {(n_base_steps, *warp.cond_shape)}."
            )

    # Case 1 with a masked base: the change of variables must count only the
    # observed channels, or `Transformed` adds Jacobian terms for entries the
    # base marginalised away and the result stops being a marginal likelihood.
    # The wrapper consumes the same per-timestep mask the base does.
    per_step = _MaskedLogDet(warp) if masked and elementwise else warp

    # Time axis: apply the same (M,)-shaped warp at each of the T steps. A
    # conditional warp additionally needs its condition mapped over that axis,
    # so the lifted warp's cond_shape becomes (T, M) and matches the
    # per-timestep mask the base consumes. Without in_axes_condition the lifted
    # warp keeps cond_shape (M,) and `Transformed` rejects the pair.
    lifted = Vmap(
        per_step,
        in_axes=None,
        axis_size=n_steps or n_base_steps,
        in_axes_condition=None if per_step.cond_shape is None else 0,
    )
    return Transformed(base, lifted)

Ensemble Conjugate Transform Filter

ConjugateTransformFilter performs the ensemble Kalman analysis in a Gaussianised latent space (Chipilski, 2025): warp the ensemble, update, warp back. The framing worth keeping is that the EnKF's Gaussian assumption is a statement about coordinates, not about the algorithm. Applied to a non-Gaussian prior the physical-space update is biased, and the bias does not shrink with ensemble size — no number of extra members will fix it. Conjugating the update with a bijection removes it.

Worth stating the exactness conditions precisely, because they are easy to over-claim. The conjugated update is exact Bayes only in the population limit, and only when the observation model is affine with additive Gaussian noise in the same latent coordinates that Gaussianise the prior. A merely "Gaussian likelihood" is not enough — y = ζ² + ε has Gaussian noise and a non-Gaussian posterior no Kalman update reproduces. With a finite ensemble the gain is empirical and the perturbations are Monte Carlo, so the result is an estimate regardless. Outside those conditions there is no guaranteed ordering against the physical-space update: it usually helps, and helps a lot when the prior really is a warped Gaussian, but a badly matched warp can make the latent joint less Gaussian and do worse. gauss_flows cannot check the condition for you.

On the reference paper's lognormal / logit-normal problem, whose exact posterior mean is [0.548062, 0.353937] (error in the posterior mean, averaged over 4 draws):

ensemble size J conjugated update physical-space update
2,000 0.0030 0.0239
20,000 0.0011 0.0257
200,000 0.0004 0.0260

One column converges; the other plateaus.

rbig_conjugate_filter fits the warp with RBIG, which suits the method unusually well: a closed-form Gaussianising map straight from the prior ensemble, no training loop — exactly the Γ the method needs, and exactly what the reference implementation hand-specifies per experiment.

ConjugateTransformFilter

Bases: Module

Ensemble Kalman analysis performed in a Gaussianised latent space.

Implements the Ensemble Conjugate Transform Filter of Chipilski (2025). Given a bijection \(\Gamma\) that maps a Gaussian latent space onto the physical state space, analysis warps the ensemble into latent coordinates, applies gaussx.enkf_analysis there, and warps the result back. See the module docstring for the accuracy argument.

Exactness caveat. The update is exact Bayes only in the population limit, and only when the prior really is the pushforward of a Gaussian under warp and the observation model is affine with additive Gaussian noise in those same latent coordinates. With a finite ensemble the gain is empirical and the perturbations are Monte Carlo, so even then the result is an estimate. "Gaussian likelihood" is not sufficient on its own: a model like \(y = \zeta^2 + \varepsilon\) has Gaussian noise but a non-Gaussian posterior this update does not reproduce.

When the assumption does not hold, this is an approximation with no guaranteed ordering against the physical-space update. A poorly matched warp can make the latent joint less Gaussian and give a worse answer than doing nothing — "Gaussianise first" is not monotone. It typically helps, and helps a great deal when the prior is genuinely a warped Gaussian (see the module docstring), but a degraded result is an expected possibility rather than a sign of a bug in the implementation or of too few members. gauss_flows cannot check the condition for you — nothing in the ensemble reveals it — so treat exactness as conditional on a modelling assumption you have made, not as a guarantee the library enforces.

A practical note on warp: analysis calls warp.inverse under jax.vmap once per ensemble member, so a warp whose inverse is itself iterative (flowjax.bijections.NumericalInverse, root-finding splines) makes the analysis step expensive in proportion to the ensemble size. Closed-form warps — RBIG's, or an explicit exp / logistic pair — are what this method is designed around.

Attributes:

Name Type Description
warp AbstractBijection

Bijection mapping latent (Gaussian) values to physical state values, with event shape (N,).

obs_warp AbstractBijection | None

Optional separate bijection for observation space, event shape (M,). Defaults to None, meaning warp is reused — correct when state and observations live in the same space.

Shape
  • analysis particles: (J, N) in, (J, N) out
  • analysis obs_particles: (J, M)
  • analysis observation: (M,)

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> import lineax as lx
>>> from flowjax.bijections import Exp
>>> from gauss_flows_models.filters import ConjugateTransformFilter
>>> # A strictly-positive state: the prior is lognormal in physical
>>> # space, Gaussian under log.
>>> filt = ConjugateTransformFilter(warp=Exp(shape=(2,)))
>>> prior = jnp.exp(jr.normal(jr.key(0), (256, 2)))       # (J, N)
>>> noise = lx.DiagonalLinearOperator(0.1 * jnp.ones(2))
>>> posterior = filt.analysis(
...     prior, prior, jnp.array([1.0, 2.0]), noise, key=jr.key(1)
... )
>>> posterior.shape
(256, 2)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/conjugate_filter.py
class ConjugateTransformFilter(eqx.Module):
    r"""Ensemble Kalman analysis performed in a Gaussianised latent space.

    Implements the Ensemble Conjugate Transform Filter of Chipilski (2025).
    Given a bijection $\Gamma$ that maps a Gaussian latent space onto the
    physical state space, `analysis` warps the ensemble into latent
    coordinates, applies `gaussx.enkf_analysis` there, and warps the result
    back. See the module docstring for the accuracy argument.

    **Exactness caveat.** The update is exact Bayes only in the population
    limit, and only when the prior really is the pushforward of a Gaussian under
    ``warp`` *and* the observation model is affine with additive Gaussian noise
    in those same latent coordinates. With a finite ensemble the gain is
    empirical and the perturbations are Monte Carlo, so even then the result is
    an estimate. "Gaussian likelihood" is not sufficient on its own: a model
    like $y = \zeta^2 + \varepsilon$ has Gaussian noise but a non-Gaussian
    posterior this update does not reproduce.

    When the assumption does not hold, this is an approximation with **no
    guaranteed ordering** against the physical-space update. A poorly matched
    warp can make the latent joint *less* Gaussian and give a worse answer than
    doing nothing — "Gaussianise first" is not monotone. It typically helps, and
    helps a great deal when the prior is genuinely a warped Gaussian (see the
    module docstring), but a degraded result is an expected possibility rather
    than a sign of a bug in the implementation or of too few members.
    gauss_flows cannot check the condition for you — nothing in the ensemble
    reveals it — so treat exactness as conditional on a modelling assumption you
    have made, not as a guarantee the library enforces.

    A practical note on ``warp``: `analysis` calls ``warp.inverse`` under
    `jax.vmap` once per ensemble member, so a warp whose inverse is itself
    iterative (`flowjax.bijections.NumericalInverse`, root-finding splines)
    makes the analysis step expensive in proportion to the ensemble size.
    Closed-form warps — RBIG's, or an explicit ``exp`` / ``logistic`` pair —
    are what this method is designed around.

    Attributes:
        warp: Bijection mapping latent (Gaussian) values to physical state
            values, with event shape ``(N,)``.
        obs_warp: Optional separate bijection for observation space, event
            shape ``(M,)``. Defaults to ``None``, meaning ``warp`` is reused —
            correct when state and observations live in the same space.

    Shape:
        - ``analysis`` particles: ``(J, N)`` in, ``(J, N)`` out
        - ``analysis`` obs_particles: ``(J, M)``
        - ``analysis`` observation: ``(M,)``

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> import lineax as lx
        >>> from flowjax.bijections import Exp
        >>> from gauss_flows_models.filters import ConjugateTransformFilter
        >>> # A strictly-positive state: the prior is lognormal in physical
        >>> # space, Gaussian under log.
        >>> filt = ConjugateTransformFilter(warp=Exp(shape=(2,)))
        >>> prior = jnp.exp(jr.normal(jr.key(0), (256, 2)))       # (J, N)
        >>> noise = lx.DiagonalLinearOperator(0.1 * jnp.ones(2))
        >>> posterior = filt.analysis(
        ...     prior, prior, jnp.array([1.0, 2.0]), noise, key=jr.key(1)
        ... )
        >>> posterior.shape
        (256, 2)
    """

    warp: AbstractBijection
    obs_warp: AbstractBijection | None = None

    def analysis(
        self,
        particles: Array,
        obs_particles: Array,
        observation: Array,
        obs_noise: Any,
        *,
        key: PRNGKeyArray | None = None,
        perturbed_obs: Array | None = None,
        localization: Array | None = None,
    ) -> Array:
        r"""Analysis step. Returns the posterior ensemble in physical space.

        Everything is supplied in **physical** coordinates and returned in
        physical coordinates; the latent detour is internal. ``obs_noise`` is
        the observation error covariance **in latent observation coordinates**,
        because that is where the Gaussian likelihood is assumed to live.

        Args:
            particles: Prior ensemble in physical state space, shape ``(J, N)``.
            obs_particles: Prior ensemble in physical observation space, i.e.
                the image of ``particles`` under the observation operator,
                shape ``(J, M)``.
            observation: The observation in physical space, shape ``(M,)``.
            obs_noise: Observation error covariance operator in *latent*
                observation coordinates, a ``lineax`` operator of shape
                ``(M, M)``.
            key: PRNG key, forwarded to `gaussx.enkf_analysis` to draw the
                observation perturbations in latent space. Mutually exclusive
                with ``perturbed_obs``.
            perturbed_obs: Pre-built perturbed observation ensemble in
                **physical** space, shape ``(J, M)``. Warped into latent
                coordinates before use. Pass this to compare against a
                physical-space filter on one shared noise realisation.
                Mutually exclusive with ``key``.
            localization: Optional state-observation taper, shape ``(N, M)``,
                forwarded to `gaussx.enkf_analysis`. It applies in latent
                coordinates, where the analysis happens.

        Returns:
            Posterior ensemble in physical state space, shape ``(J, N)``.

        Raises:
            ValueError: If the observation-space warp's event shape does not
                match ``obs_particles``, or if neither or both of ``key`` /
                ``perturbed_obs`` are given (the latter raised by
                `gaussx.enkf_analysis`).
        """
        obs_warp = self.warp if self.obs_warp is None else self.obs_warp

        if obs_warp.shape != obs_particles.shape[1:]:
            detail = (
                "obs_warp"
                if self.obs_warp is not None
                else "warp, which is reused for the observation space because "
                "obs_warp is None"
            )
            raise ValueError(
                f"{detail} has event shape {obs_warp.shape}, but obs_particles "
                f"has M={obs_particles.shape[1]} channels. When the observation "
                "space differs from the state space, pass a matching obs_warp "
                "— the Gaussianising map for the observed quantity, not for "
                "the whole state."
            )

        return _warped_enkf_analysis(
            self.warp,
            obs_warp,
            particles,
            obs_particles,
            observation,
            obs_noise,
            key=key,
            perturbed_obs=perturbed_obs,
            localization=localization,
        )

analysis

analysis(particles: Array, obs_particles: Array, observation: Array, obs_noise: Any, *, key: PRNGKeyArray | None = None, perturbed_obs: Array | None = None, localization: Array | None = None) -> Array

Analysis step. Returns the posterior ensemble in physical space.

Everything is supplied in physical coordinates and returned in physical coordinates; the latent detour is internal. obs_noise is the observation error covariance in latent observation coordinates, because that is where the Gaussian likelihood is assumed to live.

Parameters:

Name Type Description Default
particles Array

Prior ensemble in physical state space, shape (J, N).

required
obs_particles Array

Prior ensemble in physical observation space, i.e. the image of particles under the observation operator, shape (J, M).

required
observation Array

The observation in physical space, shape (M,).

required
obs_noise Any

Observation error covariance operator in latent observation coordinates, a lineax operator of shape (M, M).

required
key PRNGKeyArray | None

PRNG key, forwarded to gaussx.enkf_analysis to draw the observation perturbations in latent space. Mutually exclusive with perturbed_obs.

None
perturbed_obs Array | None

Pre-built perturbed observation ensemble in physical space, shape (J, M). Warped into latent coordinates before use. Pass this to compare against a physical-space filter on one shared noise realisation. Mutually exclusive with key.

None
localization Array | None

Optional state-observation taper, shape (N, M), forwarded to gaussx.enkf_analysis. It applies in latent coordinates, where the analysis happens.

None

Returns:

Type Description
Array

Posterior ensemble in physical state space, shape (J, N).

Raises:

Type Description
ValueError

If the observation-space warp's event shape does not match obs_particles, or if neither or both of key / perturbed_obs are given (the latter raised by gaussx.enkf_analysis).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/conjugate_filter.py
def analysis(
    self,
    particles: Array,
    obs_particles: Array,
    observation: Array,
    obs_noise: Any,
    *,
    key: PRNGKeyArray | None = None,
    perturbed_obs: Array | None = None,
    localization: Array | None = None,
) -> Array:
    r"""Analysis step. Returns the posterior ensemble in physical space.

    Everything is supplied in **physical** coordinates and returned in
    physical coordinates; the latent detour is internal. ``obs_noise`` is
    the observation error covariance **in latent observation coordinates**,
    because that is where the Gaussian likelihood is assumed to live.

    Args:
        particles: Prior ensemble in physical state space, shape ``(J, N)``.
        obs_particles: Prior ensemble in physical observation space, i.e.
            the image of ``particles`` under the observation operator,
            shape ``(J, M)``.
        observation: The observation in physical space, shape ``(M,)``.
        obs_noise: Observation error covariance operator in *latent*
            observation coordinates, a ``lineax`` operator of shape
            ``(M, M)``.
        key: PRNG key, forwarded to `gaussx.enkf_analysis` to draw the
            observation perturbations in latent space. Mutually exclusive
            with ``perturbed_obs``.
        perturbed_obs: Pre-built perturbed observation ensemble in
            **physical** space, shape ``(J, M)``. Warped into latent
            coordinates before use. Pass this to compare against a
            physical-space filter on one shared noise realisation.
            Mutually exclusive with ``key``.
        localization: Optional state-observation taper, shape ``(N, M)``,
            forwarded to `gaussx.enkf_analysis`. It applies in latent
            coordinates, where the analysis happens.

    Returns:
        Posterior ensemble in physical state space, shape ``(J, N)``.

    Raises:
        ValueError: If the observation-space warp's event shape does not
            match ``obs_particles``, or if neither or both of ``key`` /
            ``perturbed_obs`` are given (the latter raised by
            `gaussx.enkf_analysis`).
    """
    obs_warp = self.warp if self.obs_warp is None else self.obs_warp

    if obs_warp.shape != obs_particles.shape[1:]:
        detail = (
            "obs_warp"
            if self.obs_warp is not None
            else "warp, which is reused for the observation space because "
            "obs_warp is None"
        )
        raise ValueError(
            f"{detail} has event shape {obs_warp.shape}, but obs_particles "
            f"has M={obs_particles.shape[1]} channels. When the observation "
            "space differs from the state space, pass a matching obs_warp "
            "— the Gaussianising map for the observed quantity, not for "
            "the whole state."
        )

    return _warped_enkf_analysis(
        self.warp,
        obs_warp,
        particles,
        obs_particles,
        observation,
        obs_noise,
        key=key,
        perturbed_obs=perturbed_obs,
        localization=localization,
    )

rbig_conjugate_filter

rbig_conjugate_filter(particles: Array, *, n_layers: int = 10, n_components: int = 8, random_state: int = 0) -> ConjugateTransformFilter

Fit a Gaussianising warp to a prior ensemble with RBIG.

Convenience constructor. RBIG gives a closed-form \(\Gamma\) from the ensemble with no gradient-based training, which is what the conjugate transform needs and what the reference implementation specifies by hand for each experiment. The fitted warp is used for both the state and the observation space.

Unlike a hand-specified warp, an RBIG warp is fitted, so the resulting filter is an approximation even when the prior really is a pushforward of a Gaussian — expect a bias reduction rather than the exact update.

Parameters:

Name Type Description Default
particles Array

Prior ensemble in physical state space, shape (J, N). Used only to fit the warp.

required
n_layers int

Number of RBIG (rotation, marginal) blocks. Defaults to 10.

10
n_components int

Mixture components per marginal layer. Defaults to 8.

8
random_state int

Base seed for the per-dimension GMM fits. RBIG's fit is deterministic given this seed, so no PRNG key is taken.

0

Returns:

Type Description
ConjugateTransformFilter

A ConjugateTransformFilter whose warp Gaussianises particles.

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from gauss_flows_models.filters import rbig_conjugate_filter
>>> prior = jnp.exp(jr.normal(jr.key(0), (512, 2)))       # lognormal
>>> filt = rbig_conjugate_filter(prior, n_layers=4, n_components=4)
>>> filt.warp.shape
(2,)
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/conjugate_filter.py
def rbig_conjugate_filter(
    particles: Array,
    *,
    n_layers: int = 10,
    n_components: int = 8,
    random_state: int = 0,
) -> ConjugateTransformFilter:
    r"""Fit a Gaussianising warp to a prior ensemble with RBIG.

    Convenience constructor. RBIG gives a closed-form $\Gamma$ from the
    ensemble with no gradient-based training, which is what the conjugate
    transform needs and what the reference implementation specifies by hand
    for each experiment. The fitted warp is used for both the state and the
    observation space.

    Unlike a hand-specified warp, an RBIG warp is *fitted*, so the resulting
    filter is an approximation even when the prior really is a pushforward of a
    Gaussian — expect a bias reduction rather than the exact update.

    Args:
        particles: Prior ensemble in physical state space, shape ``(J, N)``.
            Used only to fit the warp.
        n_layers: Number of RBIG ``(rotation, marginal)`` blocks. Defaults
            to 10.
        n_components: Mixture components per marginal layer. Defaults to 8.
        random_state: Base seed for the per-dimension GMM fits. RBIG's fit is
            deterministic given this seed, so no PRNG key is taken.

    Returns:
        A `ConjugateTransformFilter` whose ``warp`` Gaussianises ``particles``.

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from gauss_flows_models.filters import rbig_conjugate_filter
        >>> prior = jnp.exp(jr.normal(jr.key(0), (512, 2)))       # lognormal
        >>> filt = rbig_conjugate_filter(prior, n_layers=4, n_components=4)
        >>> filt.warp.shape
        (2,)
    """
    flow = fit_rbig(
        particles,
        n_layers=n_layers,
        n_components=n_components,
        random_state=random_state,
    )
    return ConjugateTransformFilter(warp=flow.bijection)

Transform Filter

TransformFilter runs any Gaussian filter in warped coordinates. It composes bijections into the dynamics and observation operators,

\[ \tilde f = \Gamma_x^{-1} \circ f \circ \Gamma_x, \qquad \tilde h = \Gamma_y^{-1} \circ h \circ \Gamma_x, \]

and delegates to gaussx.nonlinear_kalman_filter (the integrator passed through selects EKF / UKF / CKF / GHKF / Monte Carlo) or, for the ensemble case, to gaussx.enkf_analysis. Warping only the observation preserves conjugacy and is the territory of the two constructions above; warping the state breaks conjugacy and makes the predict step non-Gaussian, which is why the moment-based path needs an integrator even for linear physical dynamics.

What this buys — and what it does not. Measured on a strictly positive 2-D state with saturating growth and multiplicative noise (T = 40), against a physical-space filter with noise matched at the operating point:

  • Support: 0/80 latent 95% credible intervals cross zero, against 54/80 (EKF) and 57/80 (UKF) in physical coordinates; the ensemble analysis produces 0/8,000 negative members against 743/8,000.
  • Calibration: NLPD improves from 1.35 to 0.24.
  • Point accuracy: no win. RMSE on the posterior mean is a wash (within a few percent, either direction, depending on the problem and precision).

A user who adopts this expecting RMSE wins will be disappointed, and will be right to be — the feature buys calibration and support, not point accuracy.

Two traps the API is shaped around: predictive() returns the quadrature mean, because pushing the latent mean through the warp yields the pushforward median (comparing that against a physical-space mean silently mixes estimands and once flipped this feature's own benchmark conclusions); and predictive_interval() offers transformed quantiles only, because a symmetric moment interval in physical space is exactly what reintroduces impossible values.

TransformFilter

Bases: Module

Run a Gaussian filter in warped coordinates.

Composes warp_state and warp_obs into the dynamics and observation operators and delegates to gaussx:

\[ \tilde f = \Gamma_x^{-1} \circ f \circ \Gamma_x, \qquad \tilde h = \Gamma_y^{-1} \circ h \circ \Gamma_x . \]

filter runs gaussx.nonlinear_kalman_filter on the composed maps (the integrator passed through selects EKF / UKF / CKF / GHKF / Monte Carlo); analysis runs gaussx.enkf_analysis for the ensemble case. Latent moments are pushed back to physical space with predictive (quadrature mean and covariance) and predictive_interval (transformed quantiles).

What this buys, measured — and what it does not. Filtering a positive state in log coordinates removes impossible posterior mass (zero credible intervals crossing zero, zero negative ensemble members) and improves predictive density, but point RMSE can worsen relative to the physical-space filter. Calibration and support, not point accuracy.

A practical note on warps: every filter step calls the warps' forward and inverse maps, so a warp_state whose inverse is itself iterative (flowjax.bijections.NumericalInverse, root-finding splines) puts a root-find inside the innermost filter loop — a performance cliff. Closed-form warps (Exp, Affine chains, RBIG's) are what this wrapper is designed around.

Attributes:

Name Type Description
warp_state AbstractBijection | None

Bijection, latent → physical state, event shape (N,). None for an observation-only warp, which preserves conjugacy and reduces to the conjugate case.

warp_obs AbstractBijection | None

Bijection, latent → physical observation, event shape (M,). None for a state-only warp.

noise_frame Literal['latent', 'physical']

Where the noise covariances are Gaussian — "latent" (default) or "physical". With "latent" the noise is Gaussian in warped coordinates, so physical noise is multiplicative or otherwise support-respecting for free; this is the recommended default and costs nothing. "physical" re-expresses Gaussian physical noise in latent coordinates with one extra linearisation per step, and is approximate even for linear dynamics.

Shape
  • filter observations: (T, M) physical; init moments (N,) / (N, N) latent; returned moments latent.
  • analysis particles: (J, N) in, (J, N) out, physical.
  • predictive / predictive_interval: (N,) / (N, N) latent in, physical out; a leading time axis is vmapped.

Examples:

>>> import jax.numpy as jnp
>>> import jax.random as jr
>>> from flowjax.bijections import Exp
>>> from gauss_flows_models.filters import TransformFilter
>>> # A strictly positive 2-D state filtered in log coordinates.
>>> filt = TransformFilter(warp_state=Exp(shape=(2,)))
>>> growth = lambda x: x * jnp.exp(0.3 * (1.0 - x / 3.0))
>>> observations = jnp.exp(jr.normal(jr.key(0), (40, 2)))  # (T, M)
>>> state = filt.filter(
...     growth,                     # physical dynamics, (N,) -> (N,)
...     lambda x: x,                # physical observation operator
...     0.05 * jnp.eye(2),          # Q, latent frame
...     0.10 * jnp.eye(2),          # R, latent frame
...     observations,
...     jnp.zeros(2),               # latent init mean
...     jnp.eye(2),                 # latent init cov
... )
>>> mean, cov = filt.predictive(
...     state.filtered_means, state.filtered_covs
... )  # physical-space moments, (T, 2) / (T, 2, 2)
>>> lo, hi = filt.predictive_interval(
...     state.filtered_means, state.filtered_covs
... )  # strictly positive by construction
Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/transform_filter.py
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
class TransformFilter(eqx.Module):
    r"""Run a Gaussian filter in warped coordinates.

    Composes ``warp_state`` and ``warp_obs`` into the dynamics and
    observation operators and delegates to gaussx:

    $$
    \tilde f = \Gamma_x^{-1} \circ f \circ \Gamma_x, \qquad
    \tilde h = \Gamma_y^{-1} \circ h \circ \Gamma_x .
    $$

    `filter` runs `gaussx.nonlinear_kalman_filter` on the composed maps (the
    integrator passed through selects EKF / UKF / CKF / GHKF / Monte Carlo);
    `analysis` runs `gaussx.enkf_analysis` for the ensemble case. Latent
    moments are pushed back to physical space with `predictive` (quadrature
    mean and covariance) and `predictive_interval` (transformed quantiles).

    **What this buys, measured — and what it does not.** Filtering a
    positive state in log coordinates removes impossible posterior mass
    (zero credible intervals crossing zero, zero negative ensemble members)
    and improves predictive density, but point RMSE can *worsen* relative to
    the physical-space filter. Calibration and support, not point accuracy.

    A practical note on warps: every filter step calls the warps' forward
    and inverse maps, so a ``warp_state`` whose inverse is itself iterative
    (`flowjax.bijections.NumericalInverse`, root-finding splines) puts a
    root-find inside the innermost filter loop — a performance cliff.
    Closed-form warps (``Exp``, ``Affine`` chains, RBIG's) are what this
    wrapper is designed around.

    Attributes:
        warp_state: Bijection, latent → physical state, event shape ``(N,)``.
            ``None`` for an observation-only warp, which preserves conjugacy
            and reduces to the conjugate case.
        warp_obs: Bijection, latent → physical observation, event shape
            ``(M,)``. ``None`` for a state-only warp.
        noise_frame: Where the noise covariances are Gaussian — ``"latent"``
            (default) or ``"physical"``. With ``"latent"`` the noise is
            Gaussian in warped coordinates, so physical noise is
            multiplicative or otherwise support-respecting for free; this is
            the recommended default and costs nothing. ``"physical"``
            re-expresses Gaussian physical noise in latent coordinates with
            one extra linearisation per step, and is approximate even for
            linear dynamics.

    Shape:
        - ``filter`` observations: ``(T, M)`` physical; init moments
          ``(N,)`` / ``(N, N)`` **latent**; returned moments latent.
        - ``analysis`` particles: ``(J, N)`` in, ``(J, N)`` out, physical.
        - ``predictive`` / ``predictive_interval``: ``(N,)`` / ``(N, N)``
          latent in, physical out; a leading time axis is vmapped.

    Examples:
        >>> import jax.numpy as jnp
        >>> import jax.random as jr
        >>> from flowjax.bijections import Exp
        >>> from gauss_flows_models.filters import TransformFilter
        >>> # A strictly positive 2-D state filtered in log coordinates.
        >>> filt = TransformFilter(warp_state=Exp(shape=(2,)))
        >>> growth = lambda x: x * jnp.exp(0.3 * (1.0 - x / 3.0))
        >>> observations = jnp.exp(jr.normal(jr.key(0), (40, 2)))  # (T, M)
        >>> state = filt.filter(
        ...     growth,                     # physical dynamics, (N,) -> (N,)
        ...     lambda x: x,                # physical observation operator
        ...     0.05 * jnp.eye(2),          # Q, latent frame
        ...     0.10 * jnp.eye(2),          # R, latent frame
        ...     observations,
        ...     jnp.zeros(2),               # latent init mean
        ...     jnp.eye(2),                 # latent init cov
        ... )
        >>> mean, cov = filt.predictive(
        ...     state.filtered_means, state.filtered_covs
        ... )  # physical-space moments, (T, 2) / (T, 2, 2)
        >>> lo, hi = filt.predictive_interval(
        ...     state.filtered_means, state.filtered_covs
        ... )  # strictly positive by construction
    """

    warp_state: AbstractBijection | None = None
    warp_obs: AbstractBijection | None = None
    noise_frame: Literal["latent", "physical"] = "latent"

    def __check_init__(self):
        if self.noise_frame not in ("latent", "physical"):
            raise ValueError(
                f"noise_frame must be 'latent' or 'physical'; got {self.noise_frame!r}."
            )

    def _check_channel_mask(self, mask: Array | None, n_obs: int) -> None:
        """Refuse a per-channel mask when the observation warp mixes channels.

        ``warp_obs.inverse`` runs on the raw observation vector *before* the
        filter's mask machinery sees it, so with a channel-mixing warp the
        placeholder garbage in masked channels contaminates the observed
        ones. An elementwise warp keeps each channel's garbage in its own
        channel, where the mask then removes it.
        """
        if mask is None or mask.ndim != 2:
            return
        if self.warp_obs is not None and _mixes_channels(self.warp_obs):
            raise ValueError(
                "A per-channel observation mask cannot be combined with a "
                "warp_obs that mixes channels: the warp runs on the raw "
                "observation vector before masking, so placeholder values in "
                "masked channels would contaminate the observed ones. Use an "
                "elementwise warp_obs, or a per-step (T,) mask."
            )
        del n_obs

    def filter(
        self,
        dynamics: Any,
        obs_fn: Any,
        process_noise: Any,
        obs_noise: Any,
        observations: Array,
        init_mean: Array,
        init_cov: Array,
        *,
        integrator: Any | None = None,
        mask: Array | None = None,
        joseph: bool = True,
        solver: Any | None = None,
    ) -> Any:
        r"""Filter in latent coordinates. Moments returned are latent.

        ``dynamics``, ``obs_fn``, and ``observations`` are all supplied in
        **physical** coordinates; the composition and the warping of the
        data are internal. The initial moments are **latent** — they
        describe a Gaussian, and latent space is where the Gaussian lives.
        Push the returned moments to physical space with `predictive` /
        `predictive_interval`.

        Args:
            dynamics: Physical state transition ``(N,) -> (N,)``.
            obs_fn: Physical observation operator ``(N,) -> (M,)``.
            process_noise: Process covariance, ``(N, N)`` or ``(T, N, N)``
                or a lineax operator — Gaussian in the frame selected by
                ``noise_frame``.
            obs_noise: Observation covariance, ``(M, M)`` or ``(T, M, M)``
                or a lineax operator, in the ``noise_frame`` frame.
            observations: Physical observations, shape ``(T, M)``.
            init_mean: Latent initial mean, shape ``(N,)``.
            init_cov: Latent initial covariance, shape ``(N, N)``.
            integrator: gaussx integrator; the choice of integrator is the
                choice of filter. Defaults to gaussx's default (unscented).
            mask: Optional ``(T,)`` step mask or ``(T, M)`` channel mask,
                forwarded to the inner filter. A ``(T, M)`` mask requires an
                elementwise ``warp_obs`` (see Raises).
            joseph: Use the Joseph-form covariance update. Default ``True``.
            solver: gaussx solver strategy for the innovation solve.

        Returns:
            ``gaussx.FilterState`` with **latent** filtered and predicted
            moments and the latent-space log-likelihood.

        Raises:
            ValueError: If a ``(T, M)`` channel mask is combined with a
                channel-mixing ``warp_obs``, or a noise shape is wrong.
        """
        observations = jnp.asarray(observations)
        self._check_channel_mask(mask, observations.shape[-1])

        fwd_state = _identity if self.warp_state is None else self.warp_state.transform
        inv_state = _identity if self.warp_state is None else self.warp_state.inverse
        inv_obs = _identity if self.warp_obs is None else self.warp_obs.inverse

        def latent_dynamics(z: Array) -> Array:
            # z: (N,) latent -> physical -> stepped physical -> latent
            return inv_state(dynamics(fwd_state(z)))

        def latent_obs_fn(z: Array) -> Array:
            # z: (N,) latent state -> (M,) latent observation
            return inv_obs(obs_fn(fwd_state(z)))

        latent_observations = jax.vmap(inv_obs)(observations)  # (T, M)

        if self.noise_frame == "latent":
            return gaussx.nonlinear_kalman_filter(
                latent_dynamics,
                latent_obs_fn,
                process_noise,
                obs_noise,
                latent_observations,
                init_mean,
                init_cov,
                integrator=integrator,
                mask=mask,
                joseph=joseph,
                solver=solver,
            )

        return self._filter_physical_noise(
            latent_dynamics,
            latent_obs_fn,
            dynamics,
            obs_fn,
            process_noise,
            obs_noise,
            latent_observations,
            init_mean,
            init_cov,
            integrator=integrator,
            mask=mask,
            joseph=joseph,
            solver=solver,
        )

    def _filter_physical_noise(
        self,
        latent_dynamics: Any,
        latent_obs_fn: Any,
        dynamics: Any,
        obs_fn: Any,
        process_noise: Any,
        obs_noise: Any,
        latent_observations: Array,
        init_mean: Array,
        init_cov: Array,
        *,
        integrator: Any | None,
        mask: Array | None,
        joseph: bool,
        solver: Any | None,
    ) -> Any:
        r"""The ``noise_frame="physical"`` loop: one linearisation per step.

        The model is $x' = f(x) + w$, $y = h(x) + v$ with $w, v$ Gaussian in
        **physical** coordinates. In latent coordinates the noise enters
        through $\Gamma^{-1}$, so it is re-expressed by linearising at the
        predicted physical mean:

        $$
        \tilde Q_t = J_x Q_t J_x^\top, \quad
        J_x = \partial \Gamma_x^{-1}(\hat x_t), \qquad
        \tilde R_t = J_y R_t J_y^\top, \quad
        J_y = \partial \Gamma_y^{-1}(\hat y_t),
        $$

        with $\hat x_t = \Gamma_x(m^-_t)$ and $\hat y_t = h(\hat x_t)$. This
        is a first-order approximation even when the dynamics are linear.
        For an identity warp both Jacobians are exactly the identity, so the
        loop reduces bit-for-bit to the ``"latent"`` path.
        """
        n_steps, n_obs = latent_observations.shape
        n_state = init_mean.shape[0]
        q_seq = _broadcast_noise(process_noise, n_steps, n_state, "process_noise")
        r_seq = _broadcast_noise(obs_noise, n_steps, n_obs, "obs_noise")
        channel_mask = mask is not None and mask.ndim == 2
        if mask is None:
            mask_seq = jnp.ones((n_steps, 1), dtype=bool)
        else:
            mask_seq = jnp.asarray(mask)
            if mask_seq.ndim == 1:
                # (T,) step gate -> (T, 1) so the scan slice stays indexable.
                mask_seq = mask_seq[:, None]

        fwd_state = _identity if self.warp_state is None else self.warp_state.transform
        inv_state = _identity if self.warp_state is None else self.warp_state.inverse
        inv_obs = _identity if self.warp_obs is None else self.warp_obs.inverse
        no_noise = jnp.zeros((n_state, n_state), dtype=init_cov.dtype)

        def step(carry, inputs):
            mean, cov, ll = carry
            q_t, r_t, y_t, mask_t = inputs

            mean_pred, cov_dyn = gaussx.nonlinear_kalman_predict(
                latent_dynamics, mean, cov, no_noise, integrator=integrator
            )
            # Linearise the warps at the predicted physical mean.
            x_hat = fwd_state(mean_pred)  # (N,) physical predicted state
            jac_state = jax.jacobian(inv_state)(x_hat)  # (N, N)
            cov_pred = cov_dyn + _symmetrize(jac_state @ q_t @ jac_state.T)

            y_hat = obs_fn(x_hat)  # (M,) physical predicted observation
            jac_obs = jax.jacobian(inv_obs)(y_hat)  # (M, M)
            r_lat = _symmetrize(jac_obs @ r_t @ jac_obs.T)

            def _update(_):
                return gaussx.nonlinear_kalman_update(
                    latent_obs_fn,
                    mean_pred,
                    cov_pred,
                    y_t,
                    r_lat,
                    integrator=integrator,
                    mask=mask_t if channel_mask else None,
                    joseph=joseph,
                    solver=solver,
                )

            def _skip(_):
                # Gated-off step: keep the prediction, contribute no
                # likelihood — same convention as the inner filter.
                return mean_pred, cov_pred, jnp.zeros((), dtype=cov_pred.dtype)

            if channel_mask:
                mean_new, cov_new, ll_inc = _update(None)
            else:
                mean_new, cov_new, ll_inc = jax.lax.cond(
                    mask_t[0], _update, _skip, operand=None
                )

            carry_new = (mean_new, cov_new, ll + ll_inc)
            return carry_new, (mean_new, cov_new, mean_pred, cov_pred)

        init_carry = (init_mean, init_cov, jnp.zeros((), dtype=init_cov.dtype))
        final_carry, (f_means, f_covs, p_means, p_covs) = jax.lax.scan(
            step, init_carry, (q_seq, r_seq, latent_observations, mask_seq)
        )
        return gaussx.FilterState(
            filtered_means=f_means,
            filtered_covs=f_covs,
            predicted_means=p_means,
            predicted_covs=p_covs,
            log_likelihood=final_carry[2],
        )

    def analysis(
        self,
        particles: Array,
        obs_particles: Array,
        observation: Array,
        obs_noise: Any,
        *,
        key: PRNGKeyArray | None = None,
        perturbed_obs: Array | None = None,
        localization: Array | None = None,
    ) -> Array:
        r"""Ensemble Kalman analysis in latent coordinates.

        The ensemble leg: warp the prior ensemble into latent coordinates,
        run `gaussx.enkf_analysis` there, warp the posterior ensemble back.
        Everything is supplied and returned in **physical** coordinates.

        ``obs_noise`` follows ``noise_frame``: with ``"latent"`` (default)
        it is the observation covariance in latent observation coordinates;
        with ``"physical"`` it is Gaussian in physical coordinates and is
        re-expressed by linearising $\Gamma_y^{-1}$ at the observation.

        Args:
            particles: Prior ensemble in physical state space, ``(J, N)``.
            obs_particles: Image of the ensemble under the observation
                operator, physical, ``(J, M)``.
            observation: The observation, physical, ``(M,)``.
            obs_noise: Observation error covariance, ``(M, M)`` array or
                lineax operator, in the ``noise_frame`` frame.
            key: PRNG key for the observation perturbations, drawn in latent
                space. Mutually exclusive with ``perturbed_obs``.
            perturbed_obs: Pre-built perturbed observations in **physical**
                space, ``(J, M)``; warped into latent coordinates before
                use. Mutually exclusive with ``key``.
            localization: Optional state-observation taper, ``(N, M)``,
                applied in latent coordinates.

        Returns:
            Posterior ensemble in physical state space, ``(J, N)``.

        Raises:
            ValueError: If a warp's event shape does not match its ensemble.
        """
        particles = jnp.asarray(particles)
        obs_particles = jnp.asarray(obs_particles)
        if self.warp_state is not None and self.warp_state.shape != particles.shape[1:]:
            raise ValueError(
                f"warp_state has event shape {self.warp_state.shape}, but "
                f"particles has N={particles.shape[1]} channels."
            )
        if self.warp_obs is not None and self.warp_obs.shape != obs_particles.shape[1:]:
            raise ValueError(
                f"warp_obs has event shape {self.warp_obs.shape}, but "
                f"obs_particles has M={obs_particles.shape[1]} channels."
            )

        if self.noise_frame == "physical":
            inv_obs = _identity if self.warp_obs is None else self.warp_obs.inverse
            jac_obs = jax.jacobian(inv_obs)(jnp.asarray(observation))  # (M, M)
            dense = (
                obs_noise.as_matrix()
                if hasattr(obs_noise, "as_matrix")
                else jnp.asarray(obs_noise)
            )
            obs_noise = lx.MatrixLinearOperator(
                _symmetrize(jac_obs @ dense @ jac_obs.T),
                lx.positive_semidefinite_tag,
            )

        return _warped_enkf_analysis(
            self.warp_state,
            self.warp_obs,
            particles,
            obs_particles,
            observation,
            obs_noise,
            key=key,
            perturbed_obs=perturbed_obs,
            localization=localization,
        )

    def predictive(
        self, mean: Array, cov: Array, *, order: int = 32
    ) -> tuple[Array, Array]:
        r"""Push latent moments to physical space by Gauss-Hermite quadrature.

        Returns $(\mathbb{E}[x], \mathrm{Cov}[x])$ for
        $x = \Gamma_x(z)$, $z \sim \mathcal{N}(m, P)$ — **not**
        $\Gamma_x(m)$, which is the pushforward *median*: for a non-affine
        warp the two differ, and comparing $\Gamma_x(m)$ against a
        physical-space mean silently mixes estimands.

        The quadrature grid is a tensor product, ``order ** N`` points, so
        this is practical for small state dimension (``N <= ~5``). Lower
        ``order`` before reaching for it in higher dimension.

        Args:
            mean: Latent mean, shape ``(N,)`` or ``(T, N)``.
            cov: Latent covariance, shape ``(N, N)`` or ``(T, N, N)``.
            order: Gauss-Hermite points per dimension. Default ``32``.

        Returns:
            Tuple ``(physical_mean, physical_cov)`` with the input's leading
            shape. With ``warp_state=None`` the inputs are returned as-is.
        """
        if self.warp_state is None:
            return mean, cov
        integrator = gaussx.GaussHermiteIntegrator(order=order)
        transform = self.warp_state.transform

        def push(m: Array, p: Array) -> tuple[Array, Array]:
            # m: (N,), p: (N, N) latent -> physical mean / cov
            phys_mean, phys_cov, _ = gaussx.moment_transform(
                transform, m, p, integrator=integrator
            )
            return phys_mean, phys_cov

        if jnp.asarray(mean).ndim == 2:
            return jax.vmap(push)(mean, cov)
        return push(mean, cov)

    def predictive_interval(
        self, mean: Array, cov: Array, *, level: float = 0.95
    ) -> tuple[Array, Array]:
        r"""Per-dimension credible interval via transformed quantiles.

        Computes $\Gamma_x(m \pm z_\alpha s)$ with $s$ the latent marginal
        standard deviations — the latent Gaussian quantiles pushed through
        the warp. Monotone maps preserve quantiles, so the result is an
        exact equal-tailed interval in physical space and it respects the
        support by construction. Deliberately offers **no** symmetric
        moment-based option: $\hat\mu \pm z_\alpha \hat\sigma$ in physical
        space is what reintroduces impossible values.

        Requires an elementwise ``warp_state`` (quantiles do not commute
        with channel mixing). A decreasing warp flips the endpoints; they
        are returned sorted.

        Args:
            mean: Latent mean, shape ``(N,)`` or ``(T, N)``.
            cov: Latent covariance, shape ``(N, N)`` or ``(T, N, N)``.
            level: Two-sided coverage level in ``(0, 1)``. Default ``0.95``.

        Returns:
            Tuple ``(lower, upper)``, each with ``mean``'s shape, physical.

        Raises:
            ValueError: If ``warp_state`` mixes channels, or ``level`` is
                outside ``(0, 1)``.
        """
        if not 0.0 < level < 1.0:
            raise ValueError(f"level must be in (0, 1); got {level}.")
        if self.warp_state is not None and _mixes_channels(self.warp_state):
            raise ValueError(
                "predictive_interval needs an elementwise warp_state: "
                "per-dimension quantiles do not commute with a warp that "
                "mixes channels. Use predictive() for moments, or sample."
            )
        mean = jnp.asarray(mean)
        cov = jnp.asarray(cov)
        z_alpha = jnp.sqrt(2.0) * jax.scipy.special.erfinv(level)
        # scale: marginal std devs, matching mean's shape
        scale = jnp.sqrt(jnp.diagonal(cov, axis1=-2, axis2=-1))
        lo_latent = mean - z_alpha * scale
        hi_latent = mean + z_alpha * scale

        transform = _identity if self.warp_state is None else self.warp_state.transform
        if mean.ndim == 2:
            transform = jax.vmap(transform)
        endpoint_a = transform(lo_latent)
        endpoint_b = transform(hi_latent)
        return jnp.minimum(endpoint_a, endpoint_b), jnp.maximum(endpoint_a, endpoint_b)

filter

filter(dynamics: Any, obs_fn: Any, process_noise: Any, obs_noise: Any, observations: Array, init_mean: Array, init_cov: Array, *, integrator: Any | None = None, mask: Array | None = None, joseph: bool = True, solver: Any | None = None) -> Any

Filter in latent coordinates. Moments returned are latent.

dynamics, obs_fn, and observations are all supplied in physical coordinates; the composition and the warping of the data are internal. The initial moments are latent — they describe a Gaussian, and latent space is where the Gaussian lives. Push the returned moments to physical space with predictive / predictive_interval.

Parameters:

Name Type Description Default
dynamics Any

Physical state transition (N,) -> (N,).

required
obs_fn Any

Physical observation operator (N,) -> (M,).

required
process_noise Any

Process covariance, (N, N) or (T, N, N) or a lineax operator — Gaussian in the frame selected by noise_frame.

required
obs_noise Any

Observation covariance, (M, M) or (T, M, M) or a lineax operator, in the noise_frame frame.

required
observations Array

Physical observations, shape (T, M).

required
init_mean Array

Latent initial mean, shape (N,).

required
init_cov Array

Latent initial covariance, shape (N, N).

required
integrator Any | None

gaussx integrator; the choice of integrator is the choice of filter. Defaults to gaussx's default (unscented).

None
mask Array | None

Optional (T,) step mask or (T, M) channel mask, forwarded to the inner filter. A (T, M) mask requires an elementwise warp_obs (see Raises).

None
joseph bool

Use the Joseph-form covariance update. Default True.

True
solver Any | None

gaussx solver strategy for the innovation solve.

None

Returns:

Type Description
Any

gaussx.FilterState with latent filtered and predicted

Any

moments and the latent-space log-likelihood.

Raises:

Type Description
ValueError

If a (T, M) channel mask is combined with a channel-mixing warp_obs, or a noise shape is wrong.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/transform_filter.py
def filter(
    self,
    dynamics: Any,
    obs_fn: Any,
    process_noise: Any,
    obs_noise: Any,
    observations: Array,
    init_mean: Array,
    init_cov: Array,
    *,
    integrator: Any | None = None,
    mask: Array | None = None,
    joseph: bool = True,
    solver: Any | None = None,
) -> Any:
    r"""Filter in latent coordinates. Moments returned are latent.

    ``dynamics``, ``obs_fn``, and ``observations`` are all supplied in
    **physical** coordinates; the composition and the warping of the
    data are internal. The initial moments are **latent** — they
    describe a Gaussian, and latent space is where the Gaussian lives.
    Push the returned moments to physical space with `predictive` /
    `predictive_interval`.

    Args:
        dynamics: Physical state transition ``(N,) -> (N,)``.
        obs_fn: Physical observation operator ``(N,) -> (M,)``.
        process_noise: Process covariance, ``(N, N)`` or ``(T, N, N)``
            or a lineax operator — Gaussian in the frame selected by
            ``noise_frame``.
        obs_noise: Observation covariance, ``(M, M)`` or ``(T, M, M)``
            or a lineax operator, in the ``noise_frame`` frame.
        observations: Physical observations, shape ``(T, M)``.
        init_mean: Latent initial mean, shape ``(N,)``.
        init_cov: Latent initial covariance, shape ``(N, N)``.
        integrator: gaussx integrator; the choice of integrator is the
            choice of filter. Defaults to gaussx's default (unscented).
        mask: Optional ``(T,)`` step mask or ``(T, M)`` channel mask,
            forwarded to the inner filter. A ``(T, M)`` mask requires an
            elementwise ``warp_obs`` (see Raises).
        joseph: Use the Joseph-form covariance update. Default ``True``.
        solver: gaussx solver strategy for the innovation solve.

    Returns:
        ``gaussx.FilterState`` with **latent** filtered and predicted
        moments and the latent-space log-likelihood.

    Raises:
        ValueError: If a ``(T, M)`` channel mask is combined with a
            channel-mixing ``warp_obs``, or a noise shape is wrong.
    """
    observations = jnp.asarray(observations)
    self._check_channel_mask(mask, observations.shape[-1])

    fwd_state = _identity if self.warp_state is None else self.warp_state.transform
    inv_state = _identity if self.warp_state is None else self.warp_state.inverse
    inv_obs = _identity if self.warp_obs is None else self.warp_obs.inverse

    def latent_dynamics(z: Array) -> Array:
        # z: (N,) latent -> physical -> stepped physical -> latent
        return inv_state(dynamics(fwd_state(z)))

    def latent_obs_fn(z: Array) -> Array:
        # z: (N,) latent state -> (M,) latent observation
        return inv_obs(obs_fn(fwd_state(z)))

    latent_observations = jax.vmap(inv_obs)(observations)  # (T, M)

    if self.noise_frame == "latent":
        return gaussx.nonlinear_kalman_filter(
            latent_dynamics,
            latent_obs_fn,
            process_noise,
            obs_noise,
            latent_observations,
            init_mean,
            init_cov,
            integrator=integrator,
            mask=mask,
            joseph=joseph,
            solver=solver,
        )

    return self._filter_physical_noise(
        latent_dynamics,
        latent_obs_fn,
        dynamics,
        obs_fn,
        process_noise,
        obs_noise,
        latent_observations,
        init_mean,
        init_cov,
        integrator=integrator,
        mask=mask,
        joseph=joseph,
        solver=solver,
    )

analysis

analysis(particles: Array, obs_particles: Array, observation: Array, obs_noise: Any, *, key: PRNGKeyArray | None = None, perturbed_obs: Array | None = None, localization: Array | None = None) -> Array

Ensemble Kalman analysis in latent coordinates.

The ensemble leg: warp the prior ensemble into latent coordinates, run gaussx.enkf_analysis there, warp the posterior ensemble back. Everything is supplied and returned in physical coordinates.

obs_noise follows noise_frame: with "latent" (default) it is the observation covariance in latent observation coordinates; with "physical" it is Gaussian in physical coordinates and is re-expressed by linearising \(\Gamma_y^{-1}\) at the observation.

Parameters:

Name Type Description Default
particles Array

Prior ensemble in physical state space, (J, N).

required
obs_particles Array

Image of the ensemble under the observation operator, physical, (J, M).

required
observation Array

The observation, physical, (M,).

required
obs_noise Any

Observation error covariance, (M, M) array or lineax operator, in the noise_frame frame.

required
key PRNGKeyArray | None

PRNG key for the observation perturbations, drawn in latent space. Mutually exclusive with perturbed_obs.

None
perturbed_obs Array | None

Pre-built perturbed observations in physical space, (J, M); warped into latent coordinates before use. Mutually exclusive with key.

None
localization Array | None

Optional state-observation taper, (N, M), applied in latent coordinates.

None

Returns:

Type Description
Array

Posterior ensemble in physical state space, (J, N).

Raises:

Type Description
ValueError

If a warp's event shape does not match its ensemble.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/transform_filter.py
def analysis(
    self,
    particles: Array,
    obs_particles: Array,
    observation: Array,
    obs_noise: Any,
    *,
    key: PRNGKeyArray | None = None,
    perturbed_obs: Array | None = None,
    localization: Array | None = None,
) -> Array:
    r"""Ensemble Kalman analysis in latent coordinates.

    The ensemble leg: warp the prior ensemble into latent coordinates,
    run `gaussx.enkf_analysis` there, warp the posterior ensemble back.
    Everything is supplied and returned in **physical** coordinates.

    ``obs_noise`` follows ``noise_frame``: with ``"latent"`` (default)
    it is the observation covariance in latent observation coordinates;
    with ``"physical"`` it is Gaussian in physical coordinates and is
    re-expressed by linearising $\Gamma_y^{-1}$ at the observation.

    Args:
        particles: Prior ensemble in physical state space, ``(J, N)``.
        obs_particles: Image of the ensemble under the observation
            operator, physical, ``(J, M)``.
        observation: The observation, physical, ``(M,)``.
        obs_noise: Observation error covariance, ``(M, M)`` array or
            lineax operator, in the ``noise_frame`` frame.
        key: PRNG key for the observation perturbations, drawn in latent
            space. Mutually exclusive with ``perturbed_obs``.
        perturbed_obs: Pre-built perturbed observations in **physical**
            space, ``(J, M)``; warped into latent coordinates before
            use. Mutually exclusive with ``key``.
        localization: Optional state-observation taper, ``(N, M)``,
            applied in latent coordinates.

    Returns:
        Posterior ensemble in physical state space, ``(J, N)``.

    Raises:
        ValueError: If a warp's event shape does not match its ensemble.
    """
    particles = jnp.asarray(particles)
    obs_particles = jnp.asarray(obs_particles)
    if self.warp_state is not None and self.warp_state.shape != particles.shape[1:]:
        raise ValueError(
            f"warp_state has event shape {self.warp_state.shape}, but "
            f"particles has N={particles.shape[1]} channels."
        )
    if self.warp_obs is not None and self.warp_obs.shape != obs_particles.shape[1:]:
        raise ValueError(
            f"warp_obs has event shape {self.warp_obs.shape}, but "
            f"obs_particles has M={obs_particles.shape[1]} channels."
        )

    if self.noise_frame == "physical":
        inv_obs = _identity if self.warp_obs is None else self.warp_obs.inverse
        jac_obs = jax.jacobian(inv_obs)(jnp.asarray(observation))  # (M, M)
        dense = (
            obs_noise.as_matrix()
            if hasattr(obs_noise, "as_matrix")
            else jnp.asarray(obs_noise)
        )
        obs_noise = lx.MatrixLinearOperator(
            _symmetrize(jac_obs @ dense @ jac_obs.T),
            lx.positive_semidefinite_tag,
        )

    return _warped_enkf_analysis(
        self.warp_state,
        self.warp_obs,
        particles,
        obs_particles,
        observation,
        obs_noise,
        key=key,
        perturbed_obs=perturbed_obs,
        localization=localization,
    )

predictive

predictive(mean: Array, cov: Array, *, order: int = 32) -> tuple[Array, Array]

Push latent moments to physical space by Gauss-Hermite quadrature.

Returns \((\mathbb{E}[x], \mathrm{Cov}[x])\) for \(x = \Gamma_x(z)\), \(z \sim \mathcal{N}(m, P)\) — not \(\Gamma_x(m)\), which is the pushforward median: for a non-affine warp the two differ, and comparing \(\Gamma_x(m)\) against a physical-space mean silently mixes estimands.

The quadrature grid is a tensor product, order ** N points, so this is practical for small state dimension (N <= ~5). Lower order before reaching for it in higher dimension.

Parameters:

Name Type Description Default
mean Array

Latent mean, shape (N,) or (T, N).

required
cov Array

Latent covariance, shape (N, N) or (T, N, N).

required
order int

Gauss-Hermite points per dimension. Default 32.

32

Returns:

Type Description
Array

Tuple (physical_mean, physical_cov) with the input's leading

Array

shape. With warp_state=None the inputs are returned as-is.

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/transform_filter.py
def predictive(
    self, mean: Array, cov: Array, *, order: int = 32
) -> tuple[Array, Array]:
    r"""Push latent moments to physical space by Gauss-Hermite quadrature.

    Returns $(\mathbb{E}[x], \mathrm{Cov}[x])$ for
    $x = \Gamma_x(z)$, $z \sim \mathcal{N}(m, P)$ — **not**
    $\Gamma_x(m)$, which is the pushforward *median*: for a non-affine
    warp the two differ, and comparing $\Gamma_x(m)$ against a
    physical-space mean silently mixes estimands.

    The quadrature grid is a tensor product, ``order ** N`` points, so
    this is practical for small state dimension (``N <= ~5``). Lower
    ``order`` before reaching for it in higher dimension.

    Args:
        mean: Latent mean, shape ``(N,)`` or ``(T, N)``.
        cov: Latent covariance, shape ``(N, N)`` or ``(T, N, N)``.
        order: Gauss-Hermite points per dimension. Default ``32``.

    Returns:
        Tuple ``(physical_mean, physical_cov)`` with the input's leading
        shape. With ``warp_state=None`` the inputs are returned as-is.
    """
    if self.warp_state is None:
        return mean, cov
    integrator = gaussx.GaussHermiteIntegrator(order=order)
    transform = self.warp_state.transform

    def push(m: Array, p: Array) -> tuple[Array, Array]:
        # m: (N,), p: (N, N) latent -> physical mean / cov
        phys_mean, phys_cov, _ = gaussx.moment_transform(
            transform, m, p, integrator=integrator
        )
        return phys_mean, phys_cov

    if jnp.asarray(mean).ndim == 2:
        return jax.vmap(push)(mean, cov)
    return push(mean, cov)

predictive_interval

predictive_interval(mean: Array, cov: Array, *, level: float = 0.95) -> tuple[Array, Array]

Per-dimension credible interval via transformed quantiles.

Computes \(\Gamma_x(m \pm z_\alpha s)\) with \(s\) the latent marginal standard deviations — the latent Gaussian quantiles pushed through the warp. Monotone maps preserve quantiles, so the result is an exact equal-tailed interval in physical space and it respects the support by construction. Deliberately offers no symmetric moment-based option: \(\hat\mu \pm z_\alpha \hat\sigma\) in physical space is what reintroduces impossible values.

Requires an elementwise warp_state (quantiles do not commute with channel mixing). A decreasing warp flips the endpoints; they are returned sorted.

Parameters:

Name Type Description Default
mean Array

Latent mean, shape (N,) or (T, N).

required
cov Array

Latent covariance, shape (N, N) or (T, N, N).

required
level float

Two-sided coverage level in (0, 1). Default 0.95.

0.95

Returns:

Type Description
tuple[Array, Array]

Tuple (lower, upper), each with mean's shape, physical.

Raises:

Type Description
ValueError

If warp_state mixes channels, or level is outside (0, 1).

Source code in packages/gauss-flows-models/src/gauss_flows_models/_src/flows/transform_filter.py
def predictive_interval(
    self, mean: Array, cov: Array, *, level: float = 0.95
) -> tuple[Array, Array]:
    r"""Per-dimension credible interval via transformed quantiles.

    Computes $\Gamma_x(m \pm z_\alpha s)$ with $s$ the latent marginal
    standard deviations — the latent Gaussian quantiles pushed through
    the warp. Monotone maps preserve quantiles, so the result is an
    exact equal-tailed interval in physical space and it respects the
    support by construction. Deliberately offers **no** symmetric
    moment-based option: $\hat\mu \pm z_\alpha \hat\sigma$ in physical
    space is what reintroduces impossible values.

    Requires an elementwise ``warp_state`` (quantiles do not commute
    with channel mixing). A decreasing warp flips the endpoints; they
    are returned sorted.

    Args:
        mean: Latent mean, shape ``(N,)`` or ``(T, N)``.
        cov: Latent covariance, shape ``(N, N)`` or ``(T, N, N)``.
        level: Two-sided coverage level in ``(0, 1)``. Default ``0.95``.

    Returns:
        Tuple ``(lower, upper)``, each with ``mean``'s shape, physical.

    Raises:
        ValueError: If ``warp_state`` mixes channels, or ``level`` is
            outside ``(0, 1)``.
    """
    if not 0.0 < level < 1.0:
        raise ValueError(f"level must be in (0, 1); got {level}.")
    if self.warp_state is not None and _mixes_channels(self.warp_state):
        raise ValueError(
            "predictive_interval needs an elementwise warp_state: "
            "per-dimension quantiles do not commute with a warp that "
            "mixes channels. Use predictive() for moments, or sample."
        )
    mean = jnp.asarray(mean)
    cov = jnp.asarray(cov)
    z_alpha = jnp.sqrt(2.0) * jax.scipy.special.erfinv(level)
    # scale: marginal std devs, matching mean's shape
    scale = jnp.sqrt(jnp.diagonal(cov, axis1=-2, axis2=-1))
    lo_latent = mean - z_alpha * scale
    hi_latent = mean + z_alpha * scale

    transform = _identity if self.warp_state is None else self.warp_state.transform
    if mean.ndim == 2:
        transform = jax.vmap(transform)
    endpoint_a = transform(lo_latent)
    endpoint_b = transform(hi_latent)
    return jnp.minimum(endpoint_a, endpoint_b), jnp.maximum(endpoint_a, endpoint_b)