Skip to content

Reparametrisations

A constrained parameter (a positive viscosity, a fraction, a covariance factor, mixture weights) is written as \(x = g(u)\), with \(u\) unconstrained and \(g\) a bijection onto the constrained set. A model stores \(u\) as its trainable leaf and only ever sees \(x\), so no gradient step on \(u\) can leave the set. gauss_flows_maps.reparam is the stack's one home for these maps, in the Core-layer package that geonnax, sesmax, pyrox and argminax can all import.

Every map is an AbstractReparametrisation with forward (\(u \mapsto x\)), inverse (\(x \mapsto u\)), log_det_jacobian (\(\log |\det J_g(u)|\)) and parameter, which turns an initial value \(x_0\) into a paramax.Parameterize leaf that paramax.unwrap gives back as \(x_0\):

import paramax
from gauss_flows_maps.reparam import Reparametrised

# ν = softplus(u), stored as u = softplus⁻¹(10⁻⁴)
viscosity = Reparametrised("softplus").parameter(1e-4)

# the model sees ν = 10⁻⁴; the optimiser steps u
nu = paramax.unwrap(viscosity)

parameter checks the value before it inverts it (finite, strictly positive for softplus with no lower bound, strictly inside a finite interval for sigmoid) and raises ValueError otherwise. Two leaves built from equal maps have equal pytree structures, so models built from them stack with jax.tree.map.

Elementwise maps

For an elementwise map the Jacobian is diagonal, so \(\log |\det J_g(u)| = \sum_i \log g'(u_i)\). With \(a\) the lower bound and \(b\) the upper bound:

Map \(g(u)\) \(\log g'(u)\) \(g^{-1}(x)\)
exp \(a + e^{u}\) \(u\) \(\log(x - a)\)
softplus \(a + \mathrm{softplus}(u)\) \(-\mathrm{softplus}(-u)\) \(y + \log(-\mathrm{expm1}(-y))\), with \(y = x - a\)
sigmoid \(a + (b - a)\sigma(u)\) \(\log(b - a) - \mathrm{softplus}(u) - \mathrm{softplus}(-u)\) \(\mathrm{logit}((x - a)/(b - a))\)

For a composition \(g_2 \circ g_1\), \(\log g'(u) = \log g_2'(g_1(u)) + \log g_1'(u)\) and the inverse is \(g_1^{-1} \circ g_2^{-1}\). Since \(1 + \tanh u = 2\sigma(2u)\), a 1 + tanh scale is sigmoid on \((0, 2)\), and Composed(outer=Reparametrised("exp"), inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0)) is the bounded log-scale \(\gamma = \exp(3\tanh(u/2))\).

AbstractReparametrisation

Bases: Module

A bijection x = g(u) from an unconstrained u ∈ ℝᵐ onto a constrained set.

x = g(u),   u = g⁻¹(x),   log |det J_g(u)| = log |det ∂x/∂u|

A model keeps the unconstrained u as its trainable leaf and sees the constrained x only through forward, so a gradient step on u can never leave the set. parameter builds that leaf from an initial value x₀: paramax.Parameterize(self.forward, self.inverse(x₀)), which paramax.unwrap turns back into x₀.

A subclass implements forward, inverse and log_det_jacobian, and states its set by overriding _validate, which parameter calls before it inverts the value. A subclass holds only static fields and other reparametrisations, so that two equal maps give parameter leaves with equal pytree structures (jax.tree.structure) and models built from them can be stacked with jax.tree.map.

Raises:

Type Description
ValueError

From parameter, when the value lies outside the set.

Examples:

>>> import jax.numpy as jnp
>>> import paramax
>>> from gauss_flows_maps.reparam import Reparametrised
>>> viscosity = Reparametrised("softplus").parameter(1e-4)
>>> bool(jnp.isclose(paramax.unwrap(viscosity), 1e-4))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_base.py
class AbstractReparametrisation(eqx.Module):
    """A bijection x = g(u) from an unconstrained u ∈ ℝᵐ onto a constrained set.

        x = g(u),   u = g⁻¹(x),   log |det J_g(u)| = log |det ∂x/∂u|

    A model keeps the unconstrained u as its trainable leaf and sees the
    constrained x only through `forward`, so a gradient step on u can never
    leave the set. `parameter` builds that leaf from an initial value x₀:
    ``paramax.Parameterize(self.forward, self.inverse(x₀))``, which
    ``paramax.unwrap`` turns back into x₀.

    A subclass implements `forward`, `inverse` and `log_det_jacobian`, and
    states its set by overriding `_validate`, which `parameter` calls before
    it inverts the value. A subclass holds only static fields and other
    reparametrisations, so that two equal maps give `parameter` leaves with
    equal pytree structures (``jax.tree.structure``) and models built from
    them can be stacked with ``jax.tree.map``.

    Raises:
        ValueError: From `parameter`, when the value lies outside the set.

    Examples:
        >>> import jax.numpy as jnp
        >>> import paramax
        >>> from gauss_flows_maps.reparam import Reparametrised
        >>> viscosity = Reparametrised("softplus").parameter(1e-4)
        >>> bool(jnp.isclose(paramax.unwrap(viscosity), 1e-4))
        True
    """

    @abc.abstractmethod
    def forward(self, u: Array) -> Array:
        """Map the unconstrained u to the constrained x = g(u)."""

    @abc.abstractmethod
    def inverse(self, x: Array) -> Array:
        """Map the constrained x back to u = g⁻¹(x)."""

    @abc.abstractmethod
    def log_det_jacobian(self, u: Array) -> Array:
        """Return log |det J_g(u)|, a scalar, for one u."""

    def _validate(self, x: Array) -> None:
        """Raise `ValueError` unless x is in the set; by default, unless finite."""
        # all() of the positive predicate, so that a NaN fails it
        if not bool(jnp.all(jnp.isfinite(x))):
            msg = f"value must be finite, got {x!r}"
            raise ValueError(msg)

    def parameter(self, value: ArrayLike) -> paramax.Parameterize:
        """Store a constrained value x₀ as its unconstrained pre-image u₀ = g⁻¹(x₀).

            leaf = Parameterize(g, u₀),   paramax.unwrap(leaf) = g(u₀) = x₀

        The value is checked eagerly, so call this when the model is built,
        not inside a transformed function. An integer value is cast to the
        default floating dtype.

        Args:
            value: The initial constrained value x₀, inside the set.

        Returns:
            A ``paramax.Parameterize`` whose function is this map's `forward`
            and whose argument is u₀; it unwraps to x₀.

        Raises:
            ValueError: When x₀ is not finite or lies outside the set (each
                subclass's `_validate` says which set).

        Shape:
            ``value``: the shape of x (the codomain of `forward`). The stored
            u₀ has the shape `inverse` returns for it.

        Examples:
            >>> import jax
            >>> import paramax
            >>> from gauss_flows_maps.reparam import Reparametrised
            >>> rate = Reparametrised("exp")
            >>> leaf = rate.parameter(2.0)
            >>> float(paramax.unwrap(leaf))
            2.0
            >>> other = rate.parameter(5.0)
            >>> jax.tree.structure(leaf) == jax.tree.structure(other)
            True
        """
        x = jnp.asarray(value)
        if not jnp.issubdtype(x.dtype, jnp.floating):
            x = x.astype(jnp.result_type(float))
        self._validate(x)
        # u₀ = g⁻¹(x₀)
        u = self.inverse(x)
        return paramax.Parameterize(self.forward, u)

forward abstractmethod

forward(u: Array) -> Array

Map the unconstrained u to the constrained x = g(u).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_base.py
@abc.abstractmethod
def forward(self, u: Array) -> Array:
    """Map the unconstrained u to the constrained x = g(u)."""

inverse abstractmethod

inverse(x: Array) -> Array

Map the constrained x back to u = g⁻¹(x).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_base.py
@abc.abstractmethod
def inverse(self, x: Array) -> Array:
    """Map the constrained x back to u = g⁻¹(x)."""

log_det_jacobian abstractmethod

log_det_jacobian(u: Array) -> Array

Return log |det J_g(u)|, a scalar, for one u.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_base.py
@abc.abstractmethod
def log_det_jacobian(self, u: Array) -> Array:
    """Return log |det J_g(u)|, a scalar, for one u."""

parameter

parameter(value: ArrayLike) -> Parameterize

Store a constrained value x₀ as its unconstrained pre-image u₀ = g⁻¹(x₀).

leaf = Parameterize(g, u₀),   paramax.unwrap(leaf) = g(u₀) = x₀

The value is checked eagerly, so call this when the model is built, not inside a transformed function. An integer value is cast to the default floating dtype.

Parameters:

Name Type Description Default
value ArrayLike

The initial constrained value x₀, inside the set.

required

Returns:

Type Description
Parameterize

A paramax.Parameterize whose function is this map's forward

Parameterize

and whose argument is u₀; it unwraps to x₀.

Raises:

Type Description
ValueError

When x₀ is not finite or lies outside the set (each subclass's _validate says which set).

Shape

value: the shape of x (the codomain of forward). The stored u₀ has the shape inverse returns for it.

Examples:

>>> import jax
>>> import paramax
>>> from gauss_flows_maps.reparam import Reparametrised
>>> rate = Reparametrised("exp")
>>> leaf = rate.parameter(2.0)
>>> float(paramax.unwrap(leaf))
2.0
>>> other = rate.parameter(5.0)
>>> jax.tree.structure(leaf) == jax.tree.structure(other)
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_base.py
def parameter(self, value: ArrayLike) -> paramax.Parameterize:
    """Store a constrained value x₀ as its unconstrained pre-image u₀ = g⁻¹(x₀).

        leaf = Parameterize(g, u₀),   paramax.unwrap(leaf) = g(u₀) = x₀

    The value is checked eagerly, so call this when the model is built,
    not inside a transformed function. An integer value is cast to the
    default floating dtype.

    Args:
        value: The initial constrained value x₀, inside the set.

    Returns:
        A ``paramax.Parameterize`` whose function is this map's `forward`
        and whose argument is u₀; it unwraps to x₀.

    Raises:
        ValueError: When x₀ is not finite or lies outside the set (each
            subclass's `_validate` says which set).

    Shape:
        ``value``: the shape of x (the codomain of `forward`). The stored
        u₀ has the shape `inverse` returns for it.

    Examples:
        >>> import jax
        >>> import paramax
        >>> from gauss_flows_maps.reparam import Reparametrised
        >>> rate = Reparametrised("exp")
        >>> leaf = rate.parameter(2.0)
        >>> float(paramax.unwrap(leaf))
        2.0
        >>> other = rate.parameter(5.0)
        >>> jax.tree.structure(leaf) == jax.tree.structure(other)
        True
    """
    x = jnp.asarray(value)
    if not jnp.issubdtype(x.dtype, jnp.floating):
        x = x.astype(jnp.result_type(float))
    self._validate(x)
    # u₀ = g⁻¹(x₀)
    u = self.inverse(x)
    return paramax.Parameterize(self.forward, u)

Reparametrised

Bases: AbstractReparametrisation

An elementwise map x = g(u) onto (a, ∞) or (a, b).

exp:       x = a + eᵘ
softplus:  x = a + log(1 + eᵘ)
sigmoid:   x = a + (b − a) σ(u),   σ(u) = 1/(1 + e⁻ᵘ)

a is lower (0 when None, for exp and softplus) and b is upper, which only sigmoid takes. Each coordinate is mapped on its own, so the Jacobian is diagonal and log |det J_g(u)| = Σᵢ log g′(uᵢ):

map        log g′(u)                             g⁻¹(x)
exp        u                                     log(x − a)
softplus   −softplus(−u)                         y + log(−expm1(−y)), y = x − a
sigmoid    log(b − a) − softplus(u) − softplus(−u)   logit((x − a)/(b − a))

1 + tanh u equals 2σ(2u), so a 1 + tanh scale is sigmoid on (0, 2) of 2u. Every form above is evaluated without overflow or cancellation, so log_value, log_derivative and log_det_jacobian stay finite far into either tail.

Attributes:

Name Type Description
transform Literal['exp', 'softplus', 'sigmoid']

"exp", "softplus" or "sigmoid".

lower float | None

The lower bound a; must be finite.

upper float | None

The upper bound b (sigmoid only); must be finite.

Raises:

Type Description
ValueError

For an unknown transform, a bound that is not finite, an upper bound with exp or softplus, or a sigmoid without lower < upper.

Shape

Every method maps an array of any shape elementwise and returns the same shape, except log_det_jacobian, which returns a scalar.

Examples:

A positive viscosity that starts at 10⁻⁴ and trains in u:

>>> import jax.numpy as jnp
>>> import paramax
>>> from gauss_flows_maps.reparam import Reparametrised
>>> viscosity = Reparametrised("softplus").parameter(1e-4)
>>> bool(jnp.isclose(paramax.unwrap(viscosity), 1e-4))
True

A bounded fraction, and the log of its Jacobian:

>>> fraction = Reparametrised("sigmoid", lower=0.0, upper=1.0)
>>> float(fraction.forward(jnp.zeros(())))
0.5
>>> log_det = fraction.log_det_jacobian(jnp.zeros(2))
>>> bool(jnp.isclose(log_det, 2 * jnp.log(0.25)))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
class Reparametrised(AbstractReparametrisation):
    """An elementwise map x = g(u) onto (a, ∞) or (a, b).

        exp:       x = a + eᵘ
        softplus:  x = a + log(1 + eᵘ)
        sigmoid:   x = a + (b − a) σ(u),   σ(u) = 1/(1 + e⁻ᵘ)

    a is ``lower`` (0 when None, for ``exp`` and ``softplus``) and b is
    ``upper``, which only ``sigmoid`` takes. Each coordinate is mapped on
    its own, so the Jacobian is diagonal and log |det J_g(u)| = Σᵢ log g′(uᵢ):

        map        log g′(u)                             g⁻¹(x)
        exp        u                                     log(x − a)
        softplus   −softplus(−u)                         y + log(−expm1(−y)), y = x − a
        sigmoid    log(b − a) − softplus(u) − softplus(−u)   logit((x − a)/(b − a))

    1 + tanh u equals 2σ(2u), so a ``1 + tanh`` scale is ``sigmoid`` on
    (0, 2) of 2u. Every form above is evaluated without overflow or
    cancellation, so `log_value`, `log_derivative` and `log_det_jacobian`
    stay finite far into either tail.

    Attributes:
        transform: ``"exp"``, ``"softplus"`` or ``"sigmoid"``.
        lower: The lower bound a; must be finite.
        upper: The upper bound b (``sigmoid`` only); must be finite.

    Raises:
        ValueError: For an unknown transform, a bound that is not finite, an
            ``upper`` bound with ``exp`` or ``softplus``, or a ``sigmoid``
            without ``lower < upper``.

    Shape:
        Every method maps an array of any shape elementwise and returns the
        same shape, except `log_det_jacobian`, which returns a scalar.

    Examples:
        A positive viscosity that starts at 10⁻⁴ and trains in u:

        >>> import jax.numpy as jnp
        >>> import paramax
        >>> from gauss_flows_maps.reparam import Reparametrised
        >>> viscosity = Reparametrised("softplus").parameter(1e-4)
        >>> bool(jnp.isclose(paramax.unwrap(viscosity), 1e-4))
        True

        A bounded fraction, and the log of its Jacobian:

        >>> fraction = Reparametrised("sigmoid", lower=0.0, upper=1.0)
        >>> float(fraction.forward(jnp.zeros(())))
        0.5
        >>> log_det = fraction.log_det_jacobian(jnp.zeros(2))
        >>> bool(jnp.isclose(log_det, 2 * jnp.log(0.25)))
        True
    """

    transform: Literal["exp", "softplus", "sigmoid"] = eqx.field(static=True)
    lower: float | None = eqx.field(static=True, default=None)
    upper: float | None = eqx.field(static=True, default=None)

    def __check_init__(self) -> None:
        if self.transform not in _TRANSFORMS:
            msg = f"'transform' must be one of {_TRANSFORMS}, got {self.transform!r}"
            raise ValueError(msg)
        for name, bound in (("lower", self.lower), ("upper", self.upper)):
            if bound is not None and not math.isfinite(bound):
                msg = (
                    f"'{name}' must be finite, got {bound!r}; a semi-infinite "
                    "interval is 'exp' or 'softplus' with a finite 'lower'"
                )
                raise ValueError(msg)
        if self.transform == "sigmoid":
            if self.lower is None or self.upper is None or not self.lower < self.upper:
                msg = (
                    "'lower' and 'upper' must both be given, with lower < upper, "
                    f"for 'sigmoid', got lower={self.lower!r}, upper={self.upper!r}"
                )
                raise ValueError(msg)
        elif self.upper is not None:
            msg = (
                f"'upper' must be None for {self.transform!r}, which bounds from "
                f"below only, got {self.upper!r}"
            )
            raise ValueError(msg)

    def _offset(self) -> float:
        return 0.0 if self.lower is None else self.lower

    def _width(self) -> float:
        assert self.upper is not None
        return self.upper - self._offset()

    def forward(self, u: Array) -> Array:
        """Map the unconstrained u to the bounded x = g(u)."""
        offset = self._offset()
        if self.transform == "exp":
            # exp(u)
            growth = jnp.exp(u)
            # x = a + exp(u)
            return offset + growth
        if self.transform == "softplus":
            # log(1 + exp(u))
            growth = jax.nn.softplus(u)
            # x = a + log(1 + exp(u))
            return offset + growth
        # b − a
        width = self._width()
        # σ(u)
        fraction = _sigmoid(u)
        # x = a + (b − a) σ(u)
        return offset + width * fraction

    def inverse(self, x: Array) -> Array:
        """Map the bounded x back to u = g⁻¹(x)."""
        offset = self._offset()
        # x − a
        shifted = x - offset
        if self.transform == "exp":
            # u = log(x − a)
            return jnp.log(shifted)
        if self.transform == "softplus":
            # 1 − exp(−(x − a)), by expm1 so it keeps its digits near the bound
            complement = -jnp.expm1(-shifted)
            # u = log(exp(x − a) − 1) = (x − a) + log(1 − exp(−(x − a))), stable
            # far from the bound
            return shifted + jnp.log(complement)
        # b − a
        width = self._width()
        # the fraction (x − a)/(b − a)
        fraction = shifted / width
        # log((x − a)/(b − a))
        log_fraction = jnp.log(fraction)
        # log(1 − (x − a)/(b − a))
        log_complement = jnp.log1p(-fraction)
        # u = logit((x − a)/(b − a))
        return log_fraction - log_complement

    def derivative(self, u: Array) -> Array:
        """Return g′(u), the diagonal of the Jacobian J_g = ∂x/∂u."""
        if self.transform == "exp":
            # g′(u) = exp(u)
            return jnp.exp(u)
        if self.transform == "softplus":
            # g′(u) = σ(u)
            return jax.nn.sigmoid(u)
        # b − a
        width = self._width()
        # σ(u) and 1 − σ(u) = σ(−u), without cancellation for large u
        probability = jax.nn.sigmoid(u)
        complement = jax.nn.sigmoid(-u)
        # g′(u) = (b − a) σ(u) σ(−u)
        return width * probability * complement

    def log_value(self, u: Array) -> Array:
        """Return log g(u), elementwise, for a map used as a scale.

            exp:       log(a + eᵘ) = logaddexp(log a, u)
            softplus:  log(a + softplus(u))
            sigmoid:   log(a (1 − σ(u)) + b σ(u))
                       = logaddexp(log a − softplus(u), log b − softplus(−u))

        With a = 0 these are u, log softplus(u) and log b − softplus(−u),
        each finite for every finite u. With a < 0, g(u) can be negative and
        log g(u) is then NaN.
        """
        offset = self._offset()
        if offset < 0.0:
            # log g(u), defined only where g(u) > 0
            return jnp.log(self.forward(u))
        if self.transform == "exp":
            if offset == 0.0:
                # log eᵘ = u
                return jnp.asarray(u)
            # log(a + eᵘ)
            return jnp.logaddexp(math.log(offset), u)
        if self.transform == "softplus":
            if offset == 0.0:
                # log softplus(u)
                return _log_softplus(u)
            # log(a + softplus(u)), with a + softplus(u) ≥ a > 0
            return jnp.log(offset + jax.nn.softplus(u))
        assert self.upper is not None
        # log σ(u) = −softplus(−u)
        log_fraction = -jax.nn.softplus(-u)
        if offset == 0.0:
            # log b σ(u)
            return math.log(self.upper) + log_fraction
        # log(1 − σ(u)) = −softplus(u)
        log_complement = -jax.nn.softplus(u)
        # log(a (1 − σ(u)) + b σ(u))
        return jnp.logaddexp(
            math.log(offset) + log_complement, math.log(self.upper) + log_fraction
        )

    def log_derivative(self, u: Array) -> Array:
        """Return log g′(u), elementwise.

        exp:       log g′(u) = u
        softplus:  log g′(u) = log σ(u) = −softplus(−u)
        sigmoid:   log g′(u) = log(b − a) − softplus(u) − softplus(−u)
        """
        if self.transform == "exp":
            # log eᵘ = u
            return jnp.asarray(u)
        if self.transform == "softplus":
            # log σ(u) = −softplus(−u)
            return -jax.nn.softplus(-u)
        # log σ(u) + log(1 − σ(u)) = −softplus(−u) − softplus(u)
        log_slope = -jax.nn.softplus(u) - jax.nn.softplus(-u)
        # log(b − a) + log σ(u)(1 − σ(u))
        return math.log(self._width()) + log_slope

    def log_det_jacobian(self, u: Array) -> Array:
        """Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar."""
        return jnp.sum(self.log_derivative(u))

    def _validate(self, x: Array) -> None:
        """Raise `ValueError` unless every entry of x is finite and in bounds."""
        offset = self._offset()
        if self.transform != "sigmoid":
            # all() of the positive predicate, so that a NaN fails it; +inf is
            # above the bound but has no finite pre-image
            if bool(jnp.all(jnp.isfinite(x) & (x > offset))):
                return
            if self.lower is None:
                msg = (
                    f"value must be strictly positive and finite for "
                    f"{self.transform!r}, got {x!r}"
                )
            else:
                msg = (
                    f"value must be finite and strictly above lower={self.lower!r} "
                    f"for {self.transform!r}, got {x!r}"
                )
            raise ValueError(msg)
        assert self.upper is not None
        # b − a in the dtype that will compute it: finite bounds can still
        # give a span that overflows, which unwraps to NaN
        span = jnp.asarray(self.upper, x.dtype) - jnp.asarray(offset, x.dtype)
        if not bool(jnp.isfinite(span)):
            msg = (
                f"the span upper - lower = {self.upper!r} - {offset!r} overflows "
                f"{x.dtype.name}; narrow the bounds or use a wider dtype for the value"
            )
            raise ValueError(msg)
        inside = jnp.isfinite(x) & (x > offset) & (x < self.upper)
        if not bool(jnp.all(inside)):
            msg = (
                f"value must lie strictly inside ({offset!r}, {self.upper!r}), "
                f"got {x!r}"
            )
            raise ValueError(msg)

forward

forward(u: Array) -> Array

Map the unconstrained u to the bounded x = g(u).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def forward(self, u: Array) -> Array:
    """Map the unconstrained u to the bounded x = g(u)."""
    offset = self._offset()
    if self.transform == "exp":
        # exp(u)
        growth = jnp.exp(u)
        # x = a + exp(u)
        return offset + growth
    if self.transform == "softplus":
        # log(1 + exp(u))
        growth = jax.nn.softplus(u)
        # x = a + log(1 + exp(u))
        return offset + growth
    # b − a
    width = self._width()
    # σ(u)
    fraction = _sigmoid(u)
    # x = a + (b − a) σ(u)
    return offset + width * fraction

inverse

inverse(x: Array) -> Array

Map the bounded x back to u = g⁻¹(x).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def inverse(self, x: Array) -> Array:
    """Map the bounded x back to u = g⁻¹(x)."""
    offset = self._offset()
    # x − a
    shifted = x - offset
    if self.transform == "exp":
        # u = log(x − a)
        return jnp.log(shifted)
    if self.transform == "softplus":
        # 1 − exp(−(x − a)), by expm1 so it keeps its digits near the bound
        complement = -jnp.expm1(-shifted)
        # u = log(exp(x − a) − 1) = (x − a) + log(1 − exp(−(x − a))), stable
        # far from the bound
        return shifted + jnp.log(complement)
    # b − a
    width = self._width()
    # the fraction (x − a)/(b − a)
    fraction = shifted / width
    # log((x − a)/(b − a))
    log_fraction = jnp.log(fraction)
    # log(1 − (x − a)/(b − a))
    log_complement = jnp.log1p(-fraction)
    # u = logit((x − a)/(b − a))
    return log_fraction - log_complement

derivative

derivative(u: Array) -> Array

Return g′(u), the diagonal of the Jacobian J_g = ∂x/∂u.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def derivative(self, u: Array) -> Array:
    """Return g′(u), the diagonal of the Jacobian J_g = ∂x/∂u."""
    if self.transform == "exp":
        # g′(u) = exp(u)
        return jnp.exp(u)
    if self.transform == "softplus":
        # g′(u) = σ(u)
        return jax.nn.sigmoid(u)
    # b − a
    width = self._width()
    # σ(u) and 1 − σ(u) = σ(−u), without cancellation for large u
    probability = jax.nn.sigmoid(u)
    complement = jax.nn.sigmoid(-u)
    # g′(u) = (b − a) σ(u) σ(−u)
    return width * probability * complement

log_value

log_value(u: Array) -> Array

Return log g(u), elementwise, for a map used as a scale.

exp:       log(a + eᵘ) = logaddexp(log a, u)
softplus:  log(a + softplus(u))
sigmoid:   log(a (1 − σ(u)) + b σ(u))
           = logaddexp(log a − softplus(u), log b − softplus(−u))

With a = 0 these are u, log softplus(u) and log b − softplus(−u), each finite for every finite u. With a < 0, g(u) can be negative and log g(u) is then NaN.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_value(self, u: Array) -> Array:
    """Return log g(u), elementwise, for a map used as a scale.

        exp:       log(a + eᵘ) = logaddexp(log a, u)
        softplus:  log(a + softplus(u))
        sigmoid:   log(a (1 − σ(u)) + b σ(u))
                   = logaddexp(log a − softplus(u), log b − softplus(−u))

    With a = 0 these are u, log softplus(u) and log b − softplus(−u),
    each finite for every finite u. With a < 0, g(u) can be negative and
    log g(u) is then NaN.
    """
    offset = self._offset()
    if offset < 0.0:
        # log g(u), defined only where g(u) > 0
        return jnp.log(self.forward(u))
    if self.transform == "exp":
        if offset == 0.0:
            # log eᵘ = u
            return jnp.asarray(u)
        # log(a + eᵘ)
        return jnp.logaddexp(math.log(offset), u)
    if self.transform == "softplus":
        if offset == 0.0:
            # log softplus(u)
            return _log_softplus(u)
        # log(a + softplus(u)), with a + softplus(u) ≥ a > 0
        return jnp.log(offset + jax.nn.softplus(u))
    assert self.upper is not None
    # log σ(u) = −softplus(−u)
    log_fraction = -jax.nn.softplus(-u)
    if offset == 0.0:
        # log b σ(u)
        return math.log(self.upper) + log_fraction
    # log(1 − σ(u)) = −softplus(u)
    log_complement = -jax.nn.softplus(u)
    # log(a (1 − σ(u)) + b σ(u))
    return jnp.logaddexp(
        math.log(offset) + log_complement, math.log(self.upper) + log_fraction
    )

log_derivative

log_derivative(u: Array) -> Array

Return log g′(u), elementwise.

exp: log g′(u) = u softplus: log g′(u) = log σ(u) = −softplus(−u) sigmoid: log g′(u) = log(b − a) − softplus(u) − softplus(−u)

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_derivative(self, u: Array) -> Array:
    """Return log g′(u), elementwise.

    exp:       log g′(u) = u
    softplus:  log g′(u) = log σ(u) = −softplus(−u)
    sigmoid:   log g′(u) = log(b − a) − softplus(u) − softplus(−u)
    """
    if self.transform == "exp":
        # log eᵘ = u
        return jnp.asarray(u)
    if self.transform == "softplus":
        # log σ(u) = −softplus(−u)
        return -jax.nn.softplus(-u)
    # log σ(u) + log(1 − σ(u)) = −softplus(−u) − softplus(u)
    log_slope = -jax.nn.softplus(u) - jax.nn.softplus(-u)
    # log(b − a) + log σ(u)(1 − σ(u))
    return math.log(self._width()) + log_slope

log_det_jacobian

log_det_jacobian(u: Array) -> Array

Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_det_jacobian(self, u: Array) -> Array:
    """Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar."""
    return jnp.sum(self.log_derivative(u))

Composed

Bases: AbstractReparametrisation

The composition x = g₂(g₁(u)) of two elementwise maps.

x = g₂(g₁(u)),   u = g₁⁻¹(g₂⁻¹(x)),
log g′(u) = log g₂′(g₁(u)) + log g₁′(u)

g₂ is outer and g₁ is inner; a value is in the set when it is in g₂'s and its g₂⁻¹ is in g₁'s. exp after sigmoid on (−3, 3) is a bounded log-scale, γ = exp(−3 + 6σ(u)) = exp(3 tanh(u/2)), which keeps a multiplicative scale inside (e⁻³, e³).

Attributes:

Name Type Description
outer Reparametrised

The map g₂ applied last.

inner Reparametrised

The map g₁ applied first.

Raises:

Type Description
ValueError

From parameter, when the value lies outside the set.

Shape

Every method maps an array of any shape elementwise and returns the same shape, except log_det_jacobian, which returns a scalar.

Examples:

>>> import jax.numpy as jnp
>>> from gauss_flows_maps.reparam import Composed, Reparametrised
>>> bounded_scale = Composed(
...     outer=Reparametrised("exp"),
...     inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
... )
>>> u = jnp.array([-2.0, 0.0, 2.0])
>>> bool(jnp.allclose(bounded_scale.forward(u), jnp.exp(3 * jnp.tanh(u / 2))))
True
>>> bool(jnp.allclose(bounded_scale.log_value(u), 3 * jnp.tanh(u / 2)))
True
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
class Composed(AbstractReparametrisation):
    """The composition x = g₂(g₁(u)) of two elementwise maps.

        x = g₂(g₁(u)),   u = g₁⁻¹(g₂⁻¹(x)),
        log g′(u) = log g₂′(g₁(u)) + log g₁′(u)

    g₂ is ``outer`` and g₁ is ``inner``; a value is in the set when it is in
    g₂'s and its g₂⁻¹ is in g₁'s. ``exp`` after ``sigmoid`` on (−3, 3) is a
    bounded log-scale, γ = exp(−3 + 6σ(u)) = exp(3 tanh(u/2)), which keeps
    a multiplicative scale inside (e⁻³, e³).

    Attributes:
        outer: The map g₂ applied last.
        inner: The map g₁ applied first.

    Raises:
        ValueError: From `parameter`, when the value lies outside the set.

    Shape:
        Every method maps an array of any shape elementwise and returns the
        same shape, except `log_det_jacobian`, which returns a scalar.

    Examples:
        >>> import jax.numpy as jnp
        >>> from gauss_flows_maps.reparam import Composed, Reparametrised
        >>> bounded_scale = Composed(
        ...     outer=Reparametrised("exp"),
        ...     inner=Reparametrised("sigmoid", lower=-3.0, upper=3.0),
        ... )
        >>> u = jnp.array([-2.0, 0.0, 2.0])
        >>> bool(jnp.allclose(bounded_scale.forward(u), jnp.exp(3 * jnp.tanh(u / 2))))
        True
        >>> bool(jnp.allclose(bounded_scale.log_value(u), 3 * jnp.tanh(u / 2)))
        True
    """

    outer: Reparametrised
    inner: Reparametrised

    def forward(self, u: Array) -> Array:
        """Map u to x = g₂(g₁(u))."""
        # v = g₁(u)
        middle = self.inner.forward(u)
        # x = g₂(v)
        return self.outer.forward(middle)

    def inverse(self, x: Array) -> Array:
        """Map x back to u = g₁⁻¹(g₂⁻¹(x))."""
        # v = g₂⁻¹(x)
        middle = self.outer.inverse(x)
        # u = g₁⁻¹(v)
        return self.inner.inverse(middle)

    def derivative(self, u: Array) -> Array:
        """Return g′(u) = g₂′(g₁(u)) g₁′(u), elementwise."""
        # v = g₁(u)
        middle = self.inner.forward(u)
        # g₂′(v) g₁′(u)
        return self.outer.derivative(middle) * self.inner.derivative(u)

    def log_value(self, u: Array) -> Array:
        """Return log g(u) = log g₂(g₁(u)), elementwise."""
        # v = g₁(u)
        middle = self.inner.forward(u)
        # log g₂(v)
        return self.outer.log_value(middle)

    def log_derivative(self, u: Array) -> Array:
        """Return log g′(u) = log g₂′(g₁(u)) + log g₁′(u), elementwise."""
        # v = g₁(u)
        middle = self.inner.forward(u)
        # log g₂′(v) + log g₁′(u)
        return self.outer.log_derivative(middle) + self.inner.log_derivative(u)

    def log_det_jacobian(self, u: Array) -> Array:
        """Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar."""
        return jnp.sum(self.log_derivative(u))

    def _validate(self, x: Array) -> None:
        """Raise `ValueError` unless x is in g₂'s set and g₂⁻¹(x) in g₁'s."""
        self.outer._validate(x)
        self.inner._validate(self.outer.inverse(x))

forward

forward(u: Array) -> Array

Map u to x = g₂(g₁(u)).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def forward(self, u: Array) -> Array:
    """Map u to x = g₂(g₁(u))."""
    # v = g₁(u)
    middle = self.inner.forward(u)
    # x = g₂(v)
    return self.outer.forward(middle)

inverse

inverse(x: Array) -> Array

Map x back to u = g₁⁻¹(g₂⁻¹(x)).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def inverse(self, x: Array) -> Array:
    """Map x back to u = g₁⁻¹(g₂⁻¹(x))."""
    # v = g₂⁻¹(x)
    middle = self.outer.inverse(x)
    # u = g₁⁻¹(v)
    return self.inner.inverse(middle)

derivative

derivative(u: Array) -> Array

Return g′(u) = g₂′(g₁(u)) g₁′(u), elementwise.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def derivative(self, u: Array) -> Array:
    """Return g′(u) = g₂′(g₁(u)) g₁′(u), elementwise."""
    # v = g₁(u)
    middle = self.inner.forward(u)
    # g₂′(v) g₁′(u)
    return self.outer.derivative(middle) * self.inner.derivative(u)

log_value

log_value(u: Array) -> Array

Return log g(u) = log g₂(g₁(u)), elementwise.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_value(self, u: Array) -> Array:
    """Return log g(u) = log g₂(g₁(u)), elementwise."""
    # v = g₁(u)
    middle = self.inner.forward(u)
    # log g₂(v)
    return self.outer.log_value(middle)

log_derivative

log_derivative(u: Array) -> Array

Return log g′(u) = log g₂′(g₁(u)) + log g₁′(u), elementwise.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_derivative(self, u: Array) -> Array:
    """Return log g′(u) = log g₂′(g₁(u)) + log g₁′(u), elementwise."""
    # v = g₁(u)
    middle = self.inner.forward(u)
    # log g₂′(v) + log g₁′(u)
    return self.outer.log_derivative(middle) + self.inner.log_derivative(u)

log_det_jacobian

log_det_jacobian(u: Array) -> Array

Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_elementwise.py
def log_det_jacobian(self, u: Array) -> Array:
    """Return log |det J_g(u)| = Σᵢ log g′(uᵢ), a scalar."""
    return jnp.sum(self.log_derivative(u))

Structured maps

CholeskyFactor fills the lower triangle of \(L\) from \(u \in \mathbb{R}^{D(D+1)/2}\) and puts the diagonal through a positive map \(h\), so \(\log |\det J(u)| = \sum_i \log h'(u_{ii})\). Simplex maps \(u \in \mathbb{R}^{K-1}\) to \(w = \mathrm{softmax}([u, 0])\); on the first \(K - 1\) weights its Jacobian is \(\mathrm{diag}(w) - w w^\top\), whose determinant is \(\prod_{k=1}^{K} w_k\).

CholeskyFactor

Bases: AbstractReparametrisation

A lower-triangular L with a positive diagonal, from u ∈ ℝ^(D(D+1)/2).

Lᵢⱼ = h(uᵢᵢ) for i = j,   Lᵢⱼ = uᵢⱼ for i > j,   Lᵢⱼ = 0 for i < j

u lists the lower triangle row by row (the order of numpy.tril_indices(D)) and h is diagonal, softplus by default. The map from u to L's free entries has a diagonal Jacobian, so

log |det J(u)| = Σᵢ log h′(uᵢᵢ)

and L Lᵀ is a covariance matrix with a unique factor.

Attributes:

Name Type Description
dim int

D, the size of L.

diagonal Reparametrised

The map h onto a positive diagonal; its lower must be None or at least 0.

Raises:

Type Description
ValueError

When dim is below 1 or diagonal can reach zero or below; from parameter, when the value is not a finite (D, D) lower-triangular matrix with a diagonal in h's set.

Shape

forward: (D(D+1)/2,) → (D, D). inverse: (D, D) → (D(D+1)/2,). log_det_jacobian: (D(D+1)/2,) → ().

Examples:

>>> import jax.numpy as jnp
>>> import paramax
>>> from gauss_flows_maps.reparam import CholeskyFactor
>>> chol = CholeskyFactor(dim=4).parameter(jnp.eye(4))
>>> paramax.unwrap(chol).shape
(4, 4)
>>> bool(jnp.allclose(paramax.unwrap(chol), jnp.eye(4)))
True

Any u gives a valid factor:

>>> factor = CholeskyFactor(dim=2).forward(jnp.array([-5.0, 0.3, 2.0]))
>>> bool(jnp.all(jnp.diag(factor) > 0.0)), float(factor[0, 1])
(True, 0.0)
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
class CholeskyFactor(AbstractReparametrisation):
    """A lower-triangular L with a positive diagonal, from u ∈ ℝ^(D(D+1)/2).

        Lᵢⱼ = h(uᵢᵢ) for i = j,   Lᵢⱼ = uᵢⱼ for i > j,   Lᵢⱼ = 0 for i < j

    u lists the lower triangle row by row (the order of
    ``numpy.tril_indices(D)``) and h is ``diagonal``, softplus by default.
    The map from u to L's free entries has a diagonal Jacobian, so

        log |det J(u)| = Σᵢ log h′(uᵢᵢ)

    and L Lᵀ is a covariance matrix with a unique factor.

    Attributes:
        dim: D, the size of L.
        diagonal: The map h onto a positive diagonal; its ``lower`` must be
            None or at least 0.

    Raises:
        ValueError: When ``dim`` is below 1 or ``diagonal`` can reach zero or
            below; from `parameter`, when the value is not a finite (D, D)
            lower-triangular matrix with a diagonal in h's set.

    Shape:
        `forward`: (D(D+1)/2,) → (D, D). `inverse`: (D, D) → (D(D+1)/2,).
        `log_det_jacobian`: (D(D+1)/2,) → ().

    Examples:
        >>> import jax.numpy as jnp
        >>> import paramax
        >>> from gauss_flows_maps.reparam import CholeskyFactor
        >>> chol = CholeskyFactor(dim=4).parameter(jnp.eye(4))
        >>> paramax.unwrap(chol).shape
        (4, 4)
        >>> bool(jnp.allclose(paramax.unwrap(chol), jnp.eye(4)))
        True

        Any u gives a valid factor:

        >>> factor = CholeskyFactor(dim=2).forward(jnp.array([-5.0, 0.3, 2.0]))
        >>> bool(jnp.all(jnp.diag(factor) > 0.0)), float(factor[0, 1])
        (True, 0.0)
    """

    dim: int = eqx.field(static=True)
    diagonal: Reparametrised = Reparametrised("softplus")

    def __check_init__(self) -> None:
        if self.dim < 1:
            msg = f"'dim' must be at least 1, got {self.dim!r}"
            raise ValueError(msg)
        lower = self.diagonal.lower
        if lower is not None and lower < 0.0:
            msg = (
                "'diagonal' must map onto positive values (its lower bound None "
                f"or at least 0), got lower={lower!r}"
            )
            raise ValueError(msg)

    def _indices(self) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
        # rows and columns of the lower triangle, row by row, and the
        # positions in u of the diagonal entries
        rows, cols = np.tril_indices(self.dim)
        on_diagonal = np.flatnonzero(rows == cols)
        return rows, cols, on_diagonal

    def forward(self, u: Array) -> Array:
        """Map u to the lower-triangular L with diagonal h(uᵢᵢ)."""
        rows, cols, on_diagonal = self._indices()
        # h(uᵢᵢ) on the diagonal, uᵢⱼ below it
        diagonal = self.diagonal.forward(u[on_diagonal])
        entries = u.at[on_diagonal].set(diagonal)
        # u: (D(D+1)/2,) -> L: (D, D)
        factor = jnp.zeros((self.dim, self.dim), dtype=entries.dtype)
        return factor.at[rows, cols].set(entries)

    def inverse(self, x: Array) -> Array:
        """Map L back to u, with h⁻¹ on the diagonal; the upper triangle is ignored."""
        rows, cols, on_diagonal = self._indices()
        # L: (D, D) -> its lower triangle: (D(D+1)/2,)
        entries = x[rows, cols]
        # uᵢᵢ = h⁻¹(Lᵢᵢ)
        diagonal = self.diagonal.inverse(entries[on_diagonal])
        return entries.at[on_diagonal].set(diagonal)

    def log_det_jacobian(self, u: Array) -> Array:
        """Return log |det J(u)| = Σᵢ log h′(uᵢᵢ), a scalar."""
        _, _, on_diagonal = self._indices()
        return self.diagonal.log_det_jacobian(u[on_diagonal])

    def _validate(self, x: Array) -> None:
        """Raise `ValueError` unless x is a finite lower-triangular (D, D) factor."""
        if x.shape != (self.dim, self.dim):
            msg = f"value must have shape {(self.dim, self.dim)}, got {x.shape}"
            raise ValueError(msg)
        if not bool(jnp.all(jnp.isfinite(x))):
            msg = f"value must be finite, got {x!r}"
            raise ValueError(msg)
        # the strict upper triangle must be exactly zero, or unwrapping would
        # not give the value back
        if not bool(jnp.all(jnp.triu(x, k=1) == 0.0)):
            msg = f"value must be lower-triangular, got {x!r}"
            raise ValueError(msg)
        self.diagonal._validate(jnp.diagonal(x))

forward

forward(u: Array) -> Array

Map u to the lower-triangular L with diagonal h(uᵢᵢ).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def forward(self, u: Array) -> Array:
    """Map u to the lower-triangular L with diagonal h(uᵢᵢ)."""
    rows, cols, on_diagonal = self._indices()
    # h(uᵢᵢ) on the diagonal, uᵢⱼ below it
    diagonal = self.diagonal.forward(u[on_diagonal])
    entries = u.at[on_diagonal].set(diagonal)
    # u: (D(D+1)/2,) -> L: (D, D)
    factor = jnp.zeros((self.dim, self.dim), dtype=entries.dtype)
    return factor.at[rows, cols].set(entries)

inverse

inverse(x: Array) -> Array

Map L back to u, with h⁻¹ on the diagonal; the upper triangle is ignored.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def inverse(self, x: Array) -> Array:
    """Map L back to u, with h⁻¹ on the diagonal; the upper triangle is ignored."""
    rows, cols, on_diagonal = self._indices()
    # L: (D, D) -> its lower triangle: (D(D+1)/2,)
    entries = x[rows, cols]
    # uᵢᵢ = h⁻¹(Lᵢᵢ)
    diagonal = self.diagonal.inverse(entries[on_diagonal])
    return entries.at[on_diagonal].set(diagonal)

log_det_jacobian

log_det_jacobian(u: Array) -> Array

Return log |det J(u)| = Σᵢ log h′(uᵢᵢ), a scalar.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def log_det_jacobian(self, u: Array) -> Array:
    """Return log |det J(u)| = Σᵢ log h′(uᵢᵢ), a scalar."""
    _, _, on_diagonal = self._indices()
    return self.diagonal.log_det_jacobian(u[on_diagonal])

Simplex

Bases: AbstractReparametrisation

Weights on the open simplex, w = softmax([u, 0]) from u ∈ ℝ^(K−1).

wₖ = eᵘᵏ / (1 + Σⱼ eᵘʲ) for k < K,   w_K = 1 / (1 + Σⱼ eᵘʲ)
uₖ = log wₖ − log w_K

The additive logistic map (Aitchison, 1986) is a bijection from ℝ^(K−1) onto the open simplex. On the first K − 1 weights its Jacobian is diag(w) − w wᵀ, whose determinant is Πₖ₌₁ᴷ wₖ, so

log |det J(u)| = Σₖ₌₁ᴷ log wₖ

Attributes:

Name Type Description
size int

K, the number of weights; at least 2.

Raises:

Type Description
ValueError

When size is below 2; from parameter, when the value is not a (K,) vector of finite positive weights summing to 1 (within √ε of its dtype).

Shape

forward: (K − 1,) → (K,). inverse: (K,) → (K − 1,). log_det_jacobian: (K − 1,) → ().

Examples:

>>> import jax.numpy as jnp
>>> import paramax
>>> from gauss_flows_maps.reparam import Simplex
>>> weights = Simplex(size=3).parameter(jnp.full(3, 1 / 3))
>>> bool(jnp.allclose(paramax.unwrap(weights), 1 / 3))
True
>>> float(Simplex(size=3).forward(jnp.array([2.0, -1.0])).sum())
1.0
References

Aitchison, J. (1986). The Statistical Analysis of Compositional Data. Chapman and Hall.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
class Simplex(AbstractReparametrisation):
    """Weights on the open simplex, w = softmax([u, 0]) from u ∈ ℝ^(K−1).

        wₖ = eᵘᵏ / (1 + Σⱼ eᵘʲ) for k < K,   w_K = 1 / (1 + Σⱼ eᵘʲ)
        uₖ = log wₖ − log w_K

    The additive logistic map (Aitchison, 1986) is a bijection from ℝ^(K−1)
    onto the open simplex. On the first K − 1 weights its Jacobian is
    diag(w) − w wᵀ, whose determinant is Πₖ₌₁ᴷ wₖ, so

        log |det J(u)| = Σₖ₌₁ᴷ log wₖ

    Attributes:
        size: K, the number of weights; at least 2.

    Raises:
        ValueError: When ``size`` is below 2; from `parameter`, when the value
            is not a (K,) vector of finite positive weights summing to 1
            (within √ε of its dtype).

    Shape:
        `forward`: (K − 1,) → (K,). `inverse`: (K,) → (K − 1,).
        `log_det_jacobian`: (K − 1,) → ().

    Examples:
        >>> import jax.numpy as jnp
        >>> import paramax
        >>> from gauss_flows_maps.reparam import Simplex
        >>> weights = Simplex(size=3).parameter(jnp.full(3, 1 / 3))
        >>> bool(jnp.allclose(paramax.unwrap(weights), 1 / 3))
        True
        >>> float(Simplex(size=3).forward(jnp.array([2.0, -1.0])).sum())
        1.0

    References:
        Aitchison, J. (1986). *The Statistical Analysis of Compositional
        Data*. Chapman and Hall.
    """

    size: int = eqx.field(static=True)

    def __check_init__(self) -> None:
        if self.size < 2:
            msg = f"'size' must be at least 2, got {self.size!r}"
            raise ValueError(msg)

    def _logits(self, u: Array) -> Array:
        # [u, 0]: (K − 1,) -> (K,)
        reference = jnp.zeros((1,), dtype=u.dtype)
        return jnp.concatenate([u, reference])

    def forward(self, u: Array) -> Array:
        """Map u to the weights w = softmax([u, 0])."""
        return jax.nn.softmax(self._logits(u))

    def inverse(self, x: Array) -> Array:
        """Map the weights back to uₖ = log wₖ − log w_K."""
        log_weights = jnp.log(x)
        # uₖ = log wₖ − log w_K, for k < K
        return log_weights[:-1] - log_weights[-1]

    def log_det_jacobian(self, u: Array) -> Array:
        """Return log |det J(u)| = Σₖ log wₖ, a scalar."""
        # log wₖ = log softmax([u, 0])ₖ
        log_weights = jax.nn.log_softmax(self._logits(u))
        return jnp.sum(log_weights)

    def _validate(self, x: Array) -> None:
        """Raise `ValueError` unless x holds K finite positive weights summing to 1."""
        if x.shape != (self.size,):
            msg = f"value must have shape {(self.size,)}, got {x.shape}"
            raise ValueError(msg)
        if not bool(jnp.all(jnp.isfinite(x) & (x > 0.0))):
            msg = f"value must hold finite, strictly positive weights, got {x!r}"
            raise ValueError(msg)
        # √ε of the dtype: room for the rounding of weights normalised by
        # the caller, far below a real mistake
        tolerance = float(np.sqrt(jnp.finfo(x.dtype).eps))
        if not abs(float(jnp.sum(x)) - 1.0) <= tolerance:
            total = float(jnp.sum(x))
            msg = f"value must sum to 1 (within {tolerance:.1e}), got {total!r}"
            raise ValueError(msg)

forward

forward(u: Array) -> Array

Map u to the weights w = softmax([u, 0]).

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def forward(self, u: Array) -> Array:
    """Map u to the weights w = softmax([u, 0])."""
    return jax.nn.softmax(self._logits(u))

inverse

inverse(x: Array) -> Array

Map the weights back to uₖ = log wₖ − log w_K.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def inverse(self, x: Array) -> Array:
    """Map the weights back to uₖ = log wₖ − log w_K."""
    log_weights = jnp.log(x)
    # uₖ = log wₖ − log w_K, for k < K
    return log_weights[:-1] - log_weights[-1]

log_det_jacobian

log_det_jacobian(u: Array) -> Array

Return log |det J(u)| = Σₖ log wₖ, a scalar.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/reparam/_structured.py
def log_det_jacobian(self, u: Array) -> Array:
    """Return log |det J(u)| = Σₖ log wₖ, a scalar."""
    # log wₖ = log softmax([u, 0])ₖ
    log_weights = jax.nn.log_softmax(self._logits(u))
    return jnp.sum(log_weights)