Skip to content

Monotone inverses

gauss_flows_maps.monotone inverts an elementwise increasing function \(f\) that has no closed-form inverse. For a target \(\tau\) and a bracket \([x_{\mathrm{lo}}, x_{\mathrm{hi}}]\) with \(f(x_{\mathrm{lo}}) \le \tau \le f(x_{\mathrm{hi}})\), the function \(x \mapsto f(x) - \tau\) changes sign once on the bracket, so a bracketing root finder needs neither a derivative nor a starting guess. A mixture CDF, the monotone transformer of a normalizing flow and an ensemble CDF are the usual cases.

monotone_inverse returns \(x_\tau = f^{-1}(\tau)\), entry by entry, and is safe under jax.jit and jax.vmap. Its gradients come from the implicit function theorem through optimistix.ImplicitAdjoint: with \(f' = \partial f / \partial x\) (the density \(p\) when \(f\) is a CDF),

\[ \frac{\partial x_\tau}{\partial \theta} = -\frac{\partial_\theta f(x_\tau; \theta)}{f'(x_\tau; \theta)}, \qquad \frac{\partial x_\tau}{\partial \tau} = \frac{1}{f'(x_\tau; \theta)}. \]

By default it uses Chandrupatla, an optimistix.AbstractRootFinder that takes an inverse-quadratic-interpolation step when the interpolant is monotone on the bracket and bisects otherwise, so it keeps the guarantee of bisection and converges superlinearly near a smooth root. Any optimistix root finder that takes options=dict(lower=..., upper=...) can replace it.

Worked example: quantiles of a Gaussian mixture

The two-component mixture \(F(y) = \frac{1}{2} \Phi(y + 1) + \frac{1}{2} \Phi((y - 2) / 0.5)\) has no closed-form quantile function. Its 5 %, 50 % and 95 % quantiles, bracketed in \([-10, 10]\):

import jax.numpy as jnp
import jax.scipy.stats as jss
from gauss_flows_maps.monotone import monotone_inverse


def mixture_cdf(y):
    return 0.5 * jss.norm.cdf(y + 1.0) + 0.5 * jss.norm.cdf((y - 2.0) / 0.5)


levels = jnp.array([0.05, 0.5, 0.95])
quantiles = monotone_inverse(mixture_cdf, levels, -10.0, 10.0, rtol=1e-6)
print([round(float(v), 4) for v in quantiles])
# [-2.2816, 1.0, 2.6412]

The median is exactly 1, where \(\Phi(2)\) and \(\Phi(-2)\) sum to one. A level outside \([F(y_{\mathrm{lo}}), F(y_{\mathrm{hi}})]\) returns the nearer endpoint, or raises with throw=True.

Reference

monotone_inverse

monotone_inverse(fn: Callable[[Float[Array, ...]], Float[Array, ...]], target: Float[ArrayLike, ...], lower: Float[ArrayLike, ...], upper: Float[ArrayLike, ...], *, solver: AbstractRootFinder | None = None, rtol: float = 0.0001, atol: float = 1e-06, max_steps: int = 64, throw: bool = False) -> Float[Array, ...]

Invert an elementwise increasing function by bracketed root finding.

f⁻¹(τ) = x   such that   f(x) − τ = 0,   x ∈ [x_lo, x_hi]

f is increasing, so f(x) − τ changes sign once on any bracket with f(x_lo) ≤ τ ≤ f(x_hi), and a bracketing method needs neither derivatives nor a good initial guess. The first use is a quantile: the CDF of a mixture or an ensemble, F_mix(y) = (1/E) ∑_e F_e(y), has no closed-form inverse even when every F_e does, and its quantile F_mix⁻¹(τ) is the root of F_mix(y) − τ. The monotone transformer of a normalizing flow is another.

Gradients go through optimistix.ImplicitAdjoint. For a root x_τ of f(x; θ) − τ, with derivative f′ = ∂f/∂x (the density p when f is a CDF),

∂x_τ/∂θ = −∂_θ f(x_τ; θ) / f′(x_τ; θ),   ∂x_τ/∂τ = 1 / f′(x_τ; θ)

evaluated with one Jacobian-vector product (the Jacobian is tagged diagonal). Parameters θ closed over by fn are differentiated too. The brackets are not.

Algorithm
  1. Promote τ and the bracket to one floating dtype and broadcast them to the output shape.
  2. With throw, check f(x_lo) − τ ≤ 0 ≤ f(x_hi) − τ and a finite bracket for every entry.
  3. Find the root of x ↦ f(x) − τ with the solver (Chandrupatla by default) from the bracket midpoint, through optimistix.root_find with the implicit adjoint and a diagonal Jacobian tag.

Parameters:

Name Type Description Default
fn Callable[[Float[Array, ...]], Float[Array, ...]]

Elementwise increasing function f, mapping an array to an array of the same shape. It must be strictly increasing where it crosses τ: on a flat segment at level τ the solver returns some point of the segment, not the generalized inverse inf{x : f(x) ≥ τ}. Gaussian-mixture CDFs always qualify.

required
target Float[ArrayLike, ...]

Target values τ, e.g. quantile levels in [0, 1] when fn is a CDF.

required
lower Float[ArrayLike, ...]

Finite lower bracket x_lo, with f(x_lo) ≤ τ.

required
upper Float[ArrayLike, ...]

Finite upper bracket x_hi, with f(x_hi) ≥ τ. Infinite brackets are rejected; for a Gaussian mixture, means ± 40 standard deviations bracket every level.

required
solver AbstractRootFinder | None

An optimistix root finder that takes options=dict(lower=..., upper=...). Defaults to Chandrupatla(rtol=rtol, atol=atol). optimistix.Bisection also fits, for scalar problems only.

None
rtol float

Relative tolerance on the root (default solver only).

0.0001
atol float

Absolute tolerance on the root (default solver only).

1e-06
max_steps int

Maximum number of solver iterations.

64
throw bool

If True, raise when a target is not bracketed (f(x_lo) ≤ τ ≤ f(x_hi) fails, including a NaN endpoint value, an infinite endpoint or a reversed bracket) or the solver does not converge. If False, an unbracketed target returns the bracket endpoint whose value is closer to τ (its gradient is then meaningless), and a non-converged one the best estimate so far.

False

Returns:

Type Description
Float[Array, ...]

The roots f⁻¹(τ), with the broadcast shape of target, lower

Float[Array, ...]

and upper.

Raises:

Type Description
EquinoxRuntimeError

With throw=True, when a target is not bracketed by finite endpoints or the solver does not converge.

Shape

target, lower and upper broadcast together (NumPy rules) to the output shape, and fn is called on arrays of that shape. It must act elementwise: entry i of its output may depend only on entry i of its input, e.g. a scalar CDF, or a per-point mixture CDF with a trailing level axis. With Q targets of shape (Q,) and a batch of brackets, give the brackets a trailing axis, (*batch, 1), to get (*batch, Q).

References

Chandrupatla, T. R. (1997). A new hybrid quadratic/bisection algorithm for finding the zero of a nonlinear function without using derivatives. Advances in Engineering Software 28(3), 145-149.

Examples:

The median and 97.5% quantile of a two-member Gaussian mixture:

>>> import jax.numpy as jnp
>>> from jax.scipy.stats import norm
>>> from gauss_flows_maps.monotone import monotone_inverse
>>> cdf = lambda y: 0.5 * (norm.cdf(y + 1.0) + norm.cdf(y - 1.0))
>>> y = monotone_inverse(cdf, jnp.array([0.5, 0.975]), -10.0, 10.0)
>>> [round(float(v), 3) for v in y]
[0.0, 2.646]

A batch of brackets with a trailing axis gives one row per bracket:

>>> lower = jnp.full((3, 1), -10.0)
>>> monotone_inverse(cdf, jnp.array([0.1, 0.9]), lower, 10.0).shape
(3, 2)

An unbracketed target returns the endpoint closer to τ:

>>> float(monotone_inverse(cdf, 0.999, -10.0, 1.0))
1.0
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/inverse.py
def monotone_inverse(
    fn: Callable[[Float[Array, ...]], Float[Array, ...]],
    target: Float[ArrayLike, ...],
    lower: Float[ArrayLike, ...],
    upper: Float[ArrayLike, ...],
    *,
    solver: optx.AbstractRootFinder | None = None,
    rtol: float = 1e-4,
    atol: float = 1e-6,
    max_steps: int = 64,
    throw: bool = False,
) -> Float[Array, ...]:
    """Invert an elementwise increasing function by bracketed root finding.

        f⁻¹(τ) = x   such that   f(x) − τ = 0,   x ∈ [x_lo, x_hi]

    f is increasing, so f(x) − τ changes sign once on any bracket with
    f(x_lo) ≤ τ ≤ f(x_hi), and a bracketing method needs neither derivatives
    nor a good initial guess. The first use is a quantile: the CDF of a
    mixture or an ensemble, F_mix(y) = (1/E) ∑_e F_e(y), has no closed-form
    inverse even when every F_e does, and its quantile F_mix⁻¹(τ) is the
    root of F_mix(y) − τ. The monotone transformer of a normalizing flow is
    another.

    **Gradients** go through `optimistix.ImplicitAdjoint`. For a root x_τ
    of f(x; θ) − τ, with derivative f′ = ∂f/∂x (the density p when f is a
    CDF),

        ∂x_τ/∂θ = −∂_θ f(x_τ; θ) / f′(x_τ; θ),   ∂x_τ/∂τ = 1 / f′(x_τ; θ)

    evaluated with one Jacobian-vector product (the Jacobian is tagged
    diagonal). Parameters θ closed over by ``fn`` are differentiated too.
    The brackets are not.

    Algorithm:
        1. Promote τ and the bracket to one floating dtype and broadcast
           them to the output shape.
        2. With ``throw``, check f(x_lo) − τ ≤ 0 ≤ f(x_hi) − τ and a finite
           bracket for every entry.
        3. Find the root of x ↦ f(x) − τ with the solver (`Chandrupatla` by
           default) from the bracket midpoint, through
           `optimistix.root_find` with the implicit adjoint and a diagonal
           Jacobian tag.

    Args:
        fn: Elementwise increasing function f, mapping an array to an array
            of the same shape. It must be strictly increasing where it
            crosses τ: on a flat segment at level τ the solver returns some
            point of the segment, not the generalized inverse
            inf{x : f(x) ≥ τ}. Gaussian-mixture CDFs always qualify.
        target: Target values τ, e.g. quantile levels in [0, 1] when ``fn``
            is a CDF.
        lower: Finite lower bracket x_lo, with f(x_lo) ≤ τ.
        upper: Finite upper bracket x_hi, with f(x_hi) ≥ τ. Infinite
            brackets are rejected; for a Gaussian mixture, means ± 40
            standard deviations bracket every level.
        solver: An optimistix root finder that takes
            ``options=dict(lower=..., upper=...)``. Defaults to
            ``Chandrupatla(rtol=rtol, atol=atol)``. `optimistix.Bisection`
            also fits, for scalar problems only.
        rtol: Relative tolerance on the root (default solver only).
        atol: Absolute tolerance on the root (default solver only).
        max_steps: Maximum number of solver iterations.
        throw: If ``True``, raise when a target is not bracketed
            (f(x_lo) ≤ τ ≤ f(x_hi) fails, including a NaN endpoint value, an
            infinite endpoint or a reversed bracket) or the solver does not
            converge. If ``False``, an unbracketed target returns the
            bracket endpoint whose value is closer to τ (its gradient is
            then meaningless), and a non-converged one the best estimate so
            far.

    Returns:
        The roots f⁻¹(τ), with the broadcast shape of ``target``, ``lower``
        and ``upper``.

    Raises:
        equinox.EquinoxRuntimeError: With ``throw=True``, when a target is
            not bracketed by finite endpoints or the solver does not
            converge.

    Shape:
        ``target``, ``lower`` and ``upper`` broadcast together (NumPy rules)
        to the output shape, and ``fn`` is called on arrays of that shape.
        It must act **elementwise**: entry ``i`` of its output may depend
        only on entry ``i`` of its input, e.g. a scalar CDF, or a per-point
        mixture CDF with a trailing level axis. With ``Q`` targets of shape
        ``(Q,)`` and a batch of brackets, give the brackets a trailing axis,
        ``(*batch, 1)``, to get ``(*batch, Q)``.

    References:
        Chandrupatla, T. R. (1997). A new hybrid quadratic/bisection
        algorithm for finding the zero of a nonlinear function without
        using derivatives. *Advances in Engineering Software* 28(3),
        145-149.

    Examples:
        The median and 97.5% quantile of a two-member Gaussian mixture:

        >>> import jax.numpy as jnp
        >>> from jax.scipy.stats import norm
        >>> from gauss_flows_maps.monotone import monotone_inverse
        >>> cdf = lambda y: 0.5 * (norm.cdf(y + 1.0) + norm.cdf(y - 1.0))
        >>> y = monotone_inverse(cdf, jnp.array([0.5, 0.975]), -10.0, 10.0)
        >>> [round(float(v), 3) for v in y]
        [0.0, 2.646]

        A batch of brackets with a trailing axis gives one row per bracket:

        >>> lower = jnp.full((3, 1), -10.0)
        >>> monotone_inverse(cdf, jnp.array([0.1, 0.9]), lower, 10.0).shape
        (3, 2)

        An unbracketed target returns the endpoint closer to τ:

        >>> float(monotone_inverse(cdf, 0.999, -10.0, 1.0))
        1.0
    """
    target = jnp.asarray(target)
    dtype = jnp.result_type(target, lower, upper, float)
    target = target.astype(dtype)
    shape = jnp.broadcast_shapes(target.shape, jnp.shape(lower), jnp.shape(upper))
    lower = jnp.broadcast_to(jnp.asarray(lower, dtype), shape)
    upper = jnp.broadcast_to(jnp.asarray(upper, dtype), shape)
    if solver is None:
        solver = Chandrupatla(rtol=rtol, atol=atol)

    def residual_fn(
        x: Float[Array, ...], level: Float[Array, ...]
    ) -> Float[Array, ...]:
        # f(x) - τ
        return fn(x) - level

    if throw:
        # f(x_lo) - τ
        lower_residual = residual_fn(lower, target)
        # f(x_hi) - τ
        upper_residual = residual_fn(upper, target)
        # Directed checks: they also reject NaN endpoint values and a
        # reversed bracket, which a sign-product test would let through.
        # f(x_lo) - τ ≤ 0 ≤ f(x_hi) - τ, with x_lo and x_hi finite
        bracketed = (
            (lower_residual <= 0)
            & (upper_residual >= 0)
            & jnp.isfinite(lower)
            & jnp.isfinite(upper)
        )
        lower = eqx.error_if(
            lower,
            ~jnp.all(bracketed),
            "monotone_inverse: some targets are not bracketed by finite "
            "endpoints, i.e. fn(lower) <= target <= fn(upper) fails or a "
            "bracket is infinite.",
        )
    # (x_lo + x_hi) / 2, halved first: no overflow for wide finite brackets
    midpoint = 0.5 * lower + 0.5 * upper
    solution = optx.root_find(
        residual_fn,
        solver,
        midpoint,
        args=jnp.broadcast_to(target, shape),
        options=dict(lower=lower, upper=upper),
        max_steps=max_steps,
        adjoint=optx.ImplicitAdjoint(),
        throw=throw,
        tags=frozenset({lx.diagonal_tag}),
    )
    return solution.value

Chandrupatla

Bases: AbstractRootFinder

Chandrupatla's hybrid inverse-quadratic / bisection root finder.

x_t = (1 − t) a + t b
t_IQI = f_a/(f_b − f_a) · f_c/(f_b − f_c)
        + (c − a)/(b − a) · f_a/(f_c − f_a) · f_b/(f_c − f_b)

A bracketing method for f(x) = 0 that keeps the robustness of bisection and the superlinear convergence of inverse quadratic interpolation (Chandrupatla, 1997). The bracket [a, b] with f_a f_b ≤ 0 and the previous point c are updated each step with the new point x_t. The next t is the inverse quadratic interpolant t_IQI through (a, b, c), accepted only when ξ = (a − b)/(c − b) and Φ = (f_a − f_b)/(f_c − f_b) satisfy Φ² < ξ and (1 − Φ)² < 1 − ξ, i.e. when the interpolant is monotone on the bracket; otherwise t = ½ (bisection). t is clipped to [t_lim, 1 − t_lim] with t_lim = ½ tol / |b − c| and tol = rtol |x_m| + atol, where x_m is whichever of a, b has the smaller |f|. The solve stops when t_lim > ½, i.e. |b − c| < tol, which bounds the bracket |b − a| ≤ |b − c| and so puts x_m within tol of the root; or when f(x_m) = 0; or when the bracket has shrunk to adjacent floats and x_t can no longer move. It returns x_m. (Scherer's formulation stops at 2 tol; halving keeps the requested tolerance.)

The solver is elementwise: y may be an array, fn must act on each entry independently (as a CDF evaluated pointwise does), and every entry carries its own bracket and stops on its own. The loop ends when all entries have converged. Pass tags=frozenset( {lineax.diagonal_tag}) to optimistix.root_find so the implicit adjoint uses the diagonal Jacobian.

Requires options=dict(lower=..., upper=...) (broadcastable to y), as optimistix.Bisection does. The bracket and every iterate keep y's dtype; only the function values take fn's. An entry whose bracket has no sign change (or a NaN endpoint value) is not iterated: it returns the endpoint with the smaller |f|, so the caller decides whether that is an error. With has_aux=True the auxiliary output is that of fn at the returned root (one extra evaluation).

Algorithm

Per entry, following Scherer (2010), §6.1:

  1. Start from b = lower, a = c = upper and t = ½; an entry whose bracket has no sign change, or is infinite, is done at once.
  2. Evaluate f at x_t = (1 − t) a + t b. If f(x_t) has the sign of f_a, set c ← a; otherwise set c ← b and b ← a. Then a ← x_t.
  3. Take x_m, whichever of a, b has the smaller |f|, and t_lim = (rtol |x_m| + atol) / (2 |b − c|). Stop if f(x_m) = 0, t_lim > ½, or x_t equalled a or b before the update.
  4. Take t = t_IQI if Φ² < ξ and (1 − Φ)² < 1 − ξ, else t = ½, and clip it to [t_lim, 1 − t_lim]. Repeat from step 2.

Attributes:

Name Type Description
rtol float

Relative tolerance on the root.

atol float

Absolute tolerance on the root.

References

Chandrupatla, T. R. (1997). A new hybrid quadratic/bisection algorithm for finding the zero of a nonlinear function without using derivatives. Advances in Engineering Software 28(3), 145-149.

Scherer, P. O. J. (2010). Computational Physics: Simulation of Classical and Quantum Systems. Springer, §6.1.

Examples:

The cube root of 2 on the bracket [0, 2]:

>>> import jax.numpy as jnp
>>> import optimistix as optx
>>> from gauss_flows_maps.monotone import Chandrupatla
>>> sol = optx.root_find(
...     lambda x, _: x**3 - 2.0,
...     Chandrupatla(rtol=1e-10, atol=1e-12),
...     jnp.array(1.0),
...     options=dict(lower=0.0, upper=2.0),
... )
>>> round(float(sol.value), 6)
1.259921

Every entry carries its own bracket and target:

>>> sol = optx.root_find(
...     lambda x, target: x**2 - target,
...     Chandrupatla(rtol=1e-6, atol=1e-8),
...     jnp.ones(2),
...     args=jnp.array([4.0, 9.0]),
...     options=dict(lower=0.0, upper=jnp.array([5.0, 10.0])),
... )
>>> [round(float(v), 4) for v in sol.value]
[2.0, 3.0]
Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/chandrupatla.py
class Chandrupatla(optx.AbstractRootFinder):
    """Chandrupatla's hybrid inverse-quadratic / bisection root finder.

        x_t = (1 − t) a + t b
        t_IQI = f_a/(f_b − f_a) · f_c/(f_b − f_c)
                + (c − a)/(b − a) · f_a/(f_c − f_a) · f_b/(f_c − f_b)

    A bracketing method for f(x) = 0 that keeps the robustness of bisection
    and the superlinear convergence of inverse quadratic interpolation
    (Chandrupatla, 1997). The bracket [a, b] with f_a f_b ≤ 0 and the
    previous point c are updated each step with the new point x_t. The next
    t is the inverse quadratic interpolant t_IQI through (a, b, c), accepted
    only when ξ = (a − b)/(c − b) and Φ = (f_a − f_b)/(f_c − f_b) satisfy
    Φ² < ξ and (1 − Φ)² < 1 − ξ, i.e. when the interpolant is monotone on
    the bracket; otherwise t = ½ (bisection). t is clipped to
    [t_lim, 1 − t_lim] with t_lim = ½ tol / |b − c| and
    tol = rtol |x_m| + atol, where x_m is whichever of a, b has the smaller
    |f|. The solve stops when t_lim > ½, i.e. |b − c| < tol, which bounds
    the bracket |b − a| ≤ |b − c| and so puts x_m within tol of the root; or
    when f(x_m) = 0; or when the bracket has shrunk to adjacent floats and
    x_t can no longer move. It returns x_m. (Scherer's formulation stops at
    2 tol; halving keeps the requested tolerance.)

    The solver is **elementwise**: ``y`` may be an array, ``fn`` must act
    on each entry independently (as a CDF evaluated pointwise does), and
    every entry carries its own bracket and stops on its own. The loop
    ends when all entries have converged. Pass ``tags=frozenset(
    {lineax.diagonal_tag})`` to `optimistix.root_find` so the implicit
    adjoint uses the diagonal Jacobian.

    Requires ``options=dict(lower=..., upper=...)`` (broadcastable to
    ``y``), as `optimistix.Bisection` does. The bracket and every iterate
    keep ``y``'s dtype; only the function values take ``fn``'s. An entry
    whose bracket has no sign change (or a NaN endpoint value) is not
    iterated: it returns the endpoint with the smaller |f|, so the caller
    decides whether that is an error. With ``has_aux=True`` the auxiliary
    output is that of ``fn`` at the returned root (one extra evaluation).

    Algorithm:
        Per entry, following Scherer (2010), §6.1:

        1. Start from b = lower, a = c = upper and t = ½; an entry whose
           bracket has no sign change, or is infinite, is done at once.
        2. Evaluate f at x_t = (1 − t) a + t b. If f(x_t) has the sign of
           f_a, set c ← a; otherwise set c ← b and b ← a. Then a ← x_t.
        3. Take x_m, whichever of a, b has the smaller |f|, and
           t_lim = (rtol |x_m| + atol) / (2 |b − c|). Stop if f(x_m) = 0,
           t_lim > ½, or x_t equalled a or b before the update.
        4. Take t = t_IQI if Φ² < ξ and (1 − Φ)² < 1 − ξ, else t = ½, and
           clip it to [t_lim, 1 − t_lim]. Repeat from step 2.

    Attributes:
        rtol: Relative tolerance on the root.
        atol: Absolute tolerance on the root.

    References:
        Chandrupatla, T. R. (1997). A new hybrid quadratic/bisection
        algorithm for finding the zero of a nonlinear function without
        using derivatives. *Advances in Engineering Software* 28(3),
        145-149.

        Scherer, P. O. J. (2010). *Computational Physics: Simulation of
        Classical and Quantum Systems*. Springer, §6.1.

    Examples:
        The cube root of 2 on the bracket [0, 2]:

        >>> import jax.numpy as jnp
        >>> import optimistix as optx
        >>> from gauss_flows_maps.monotone import Chandrupatla
        >>> sol = optx.root_find(
        ...     lambda x, _: x**3 - 2.0,
        ...     Chandrupatla(rtol=1e-10, atol=1e-12),
        ...     jnp.array(1.0),
        ...     options=dict(lower=0.0, upper=2.0),
        ... )
        >>> round(float(sol.value), 6)
        1.259921

        Every entry carries its own bracket and target:

        >>> sol = optx.root_find(
        ...     lambda x, target: x**2 - target,
        ...     Chandrupatla(rtol=1e-6, atol=1e-8),
        ...     jnp.ones(2),
        ...     args=jnp.array([4.0, 9.0]),
        ...     options=dict(lower=0.0, upper=jnp.array([5.0, 10.0])),
        ... )
        >>> [round(float(v), 4) for v in sol.value]
        [2.0, 3.0]
    """

    rtol: float
    atol: float
    norm: Callable[[PyTree], Scalar] = optx.max_norm

    def init(
        self,
        fn: Callable[[Array, Any], tuple[Array, Any]],
        y: Array,
        args: PyTree,
        options: dict[str, Any],
        f_struct: Any,
        aux_struct: Any,
        tags: frozenset[object],
    ) -> _ChandrupatlaState:
        """Set up the bracket b = lower, a = c = upper and t = ½.

        The arguments are those of ``optimistix.AbstractRootFinder.init``.

        Raises:
            ValueError: If ``fn``'s output is not one array of ``y``'s shape.
        """
        del aux_struct, tags
        if not isinstance(
            f_struct, jax.ShapeDtypeStruct
        ) or f_struct.shape != jnp.shape(y):
            raise ValueError(
                "Chandrupatla needs an elementwise function: the output must be "
                "a single array with the same shape as y."
            )
        shape, dtype = f_struct.shape, jnp.result_type(y)
        lower = jnp.broadcast_to(jnp.asarray(options["lower"], dtype), shape)
        upper = jnp.broadcast_to(jnp.asarray(options["upper"], dtype), shape)
        f_lower, _ = fn(lower, args)
        f_upper, _ = fn(upper, args)
        # Scherer's initialisation: b = lower, a = c = upper.
        a, b, c = upper, lower, upper
        fa, fb, fc = f_upper, f_lower, f_upper
        # NaN-aware: a finite residual always beats a NaN one.
        # |f_a| < |f_b|, or f_b is NaN
        a_better = (jnp.abs(fa) < jnp.abs(fb)) | jnp.isnan(fb)
        # x_m = argmin over a, b of |f|
        x_best = jnp.where(a_better, a, b)
        # f(x_m)
        f_best = jnp.where(a_better, fa, fb)
        # An infinite endpoint makes the convex-combination step NaN, so it
        # counts as unbracketed (finite brackets only).
        # f_a f_b ≤ 0, with a and b finite
        bracketed = (
            (jnp.sign(fa) * jnp.sign(fb) <= 0) & jnp.isfinite(a) & jnp.isfinite(b)
        )
        # tol = rtol |x_m| + atol
        tol = self.rtol * jnp.abs(x_best) + self.atol
        # done if unbracketed, f(x_m) = 0 or |b - a| < tol
        done = (~bracketed) | (f_best == 0) | (jnp.abs(b - a) < tol)
        return _ChandrupatlaState(
            a=a,
            b=b,
            c=c,
            fa=fa,
            fb=fb,
            fc=fc,
            t=jnp.full(shape, 0.5, dtype),
            x_best=x_best,
            done=done,
        )

    def step(
        self,
        fn: Callable[[Array, Any], tuple[Array, Any]],
        y: Array,
        args: PyTree,
        options: dict[str, Any],
        state: _ChandrupatlaState,
        tags: frozenset[object],
    ) -> tuple[Array, _ChandrupatlaState, Any]:
        """One Chandrupatla step on every entry that has not converged.

            x_t = (1 − t) a + t b

        The arguments are those of ``optimistix.AbstractRootFinder.step``;
        it returns the best point x_m, the new state and ``fn``'s aux at
        x_t.
        """
        del y, options, tags
        previous = state
        # The convex combination cannot overflow for finite a, b, unlike
        # a + t (b - a) on a bracket wider than the largest float.
        # x_t = (1 - t) a + t b
        x_t = (1 - previous.t) * previous.a + previous.t * previous.b
        # x_t ∈ {a, b}: the bracket is down to adjacent floats
        stalled = (x_t == previous.a) | (x_t == previous.b)
        f_t, aux = fn(x_t, args)

        # --- update the bracket ---
        # sign f(x_t) = sign f_a
        same_sign = jnp.sign(f_t) == jnp.sign(previous.fa)
        # c ← a if the signs agree, else c ← b
        c = jnp.where(same_sign, previous.a, previous.b)
        fc = jnp.where(same_sign, previous.fa, previous.fb)
        # b ← a if the signs differ
        b = jnp.where(same_sign, previous.b, previous.a)
        fb = jnp.where(same_sign, previous.fb, previous.fa)
        # a ← x_t
        a, fa = x_t, f_t

        # --- convergence ---
        # |f_a| < |f_b|, or f_b is NaN
        a_better = (jnp.abs(fa) < jnp.abs(fb)) | jnp.isnan(fb)
        # x_m = argmin over a, b of |f|
        x_best = jnp.where(a_better, a, b)
        # f(x_m)
        f_best = jnp.where(a_better, fa, fb)
        # tol = rtol |x_m| + atol
        tol = self.rtol * jnp.abs(x_best) + self.atol
        # t_lim = ½ tol / |b - c|
        t_lim = 0.5 * tol / jnp.abs(b - c)
        converged = (f_best == 0) | (t_lim > 0.5) | stalled

        # --- next fraction t ---
        # The divisions below may produce inf/nan on degenerate entries;
        # those entries either fail the IQI test (nan comparisons are
        # False) and bisect, or have already converged.
        # ξ = (a - b)/(c - b)
        xi = (a - b) / (c - b)
        # Φ = (f_a - f_b)/(f_c - f_b)
        phi = (fa - fb) / (fc - fb)
        # Φ² < ξ and (1 - Φ)² < 1 - ξ
        use_iqi = (phi**2 < xi) & ((1 - phi) ** 2 < 1 - xi)
        # f_a/(f_b - f_a) · f_c/(f_b - f_c)
        iqi_first = fa / (fb - fa) * fc / (fb - fc)
        # (c - a)/(b - a) · f_a/(f_c - f_a) · f_b/(f_c - f_b)
        iqi_second = (c - a) / (b - a) * fa / (fc - fa) * fb / (fc - fb)
        # t_IQI
        t_iqi = iqi_first + iqi_second
        # t = t_IQI if accepted, else ½
        t = jnp.where(use_iqi, t_iqi, 0.5)
        # t ← clip(t, t_lim, 1 - t_lim)
        t = jnp.clip(t, t_lim, 1 - t_lim)

        updated = _ChandrupatlaState(
            a=a,
            b=b,
            c=c,
            fa=fa,
            fb=fb,
            fc=fc,
            t=t,
            x_best=x_best,
            done=converged,
        )
        # Freeze entries that had already converged.
        updated = jax.tree.map(
            lambda old, new: jnp.where(previous.done, old, new), previous, updated
        )
        return updated.x_best, updated, aux

    def terminate(
        self,
        fn: Callable[[Array, Any], tuple[Array, Any]],
        y: Array,
        args: PyTree,
        options: dict[str, Any],
        state: _ChandrupatlaState,
        tags: frozenset[object],
    ) -> tuple[Bool[Array, ""], optx.RESULTS]:  # noqa: F722
        """Stop once every entry has converged.

        The arguments are those of ``optimistix.AbstractRootFinder.terminate``.
        """
        del fn, y, args, options, tags
        return jnp.all(state.done), optx.RESULTS.successful

    def postprocess(
        self,
        fn: Callable[[Array, Any], tuple[Array, Any]],
        y: Array,
        aux: Any,
        args: PyTree,
        options: dict[str, Any],
        state: _ChandrupatlaState,
        tags: frozenset[object],
        result: optx.RESULTS,
    ) -> tuple[Array, Any, dict[str, Any]]:
        """Return x_m with ``fn``'s aux evaluated there.

        The arguments are those of
        ``optimistix.AbstractRootFinder.postprocess``.
        """
        del y, aux, options, tags, result
        # Re-evaluate so ``aux`` belongs to the returned point; the step's
        # aux is that of the last trial point, which may be the other end.
        _, aux = fn(state.x_best, args)
        return state.x_best, aux, {}

init

init(fn: Callable[[Array, Any], tuple[Array, Any]], y: Array, args: PyTree, options: dict[str, Any], f_struct: Any, aux_struct: Any, tags: frozenset[object]) -> _ChandrupatlaState

Set up the bracket b = lower, a = c = upper and t = ½.

The arguments are those of optimistix.AbstractRootFinder.init.

Raises:

Type Description
ValueError

If fn's output is not one array of y's shape.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/chandrupatla.py
def init(
    self,
    fn: Callable[[Array, Any], tuple[Array, Any]],
    y: Array,
    args: PyTree,
    options: dict[str, Any],
    f_struct: Any,
    aux_struct: Any,
    tags: frozenset[object],
) -> _ChandrupatlaState:
    """Set up the bracket b = lower, a = c = upper and t = ½.

    The arguments are those of ``optimistix.AbstractRootFinder.init``.

    Raises:
        ValueError: If ``fn``'s output is not one array of ``y``'s shape.
    """
    del aux_struct, tags
    if not isinstance(
        f_struct, jax.ShapeDtypeStruct
    ) or f_struct.shape != jnp.shape(y):
        raise ValueError(
            "Chandrupatla needs an elementwise function: the output must be "
            "a single array with the same shape as y."
        )
    shape, dtype = f_struct.shape, jnp.result_type(y)
    lower = jnp.broadcast_to(jnp.asarray(options["lower"], dtype), shape)
    upper = jnp.broadcast_to(jnp.asarray(options["upper"], dtype), shape)
    f_lower, _ = fn(lower, args)
    f_upper, _ = fn(upper, args)
    # Scherer's initialisation: b = lower, a = c = upper.
    a, b, c = upper, lower, upper
    fa, fb, fc = f_upper, f_lower, f_upper
    # NaN-aware: a finite residual always beats a NaN one.
    # |f_a| < |f_b|, or f_b is NaN
    a_better = (jnp.abs(fa) < jnp.abs(fb)) | jnp.isnan(fb)
    # x_m = argmin over a, b of |f|
    x_best = jnp.where(a_better, a, b)
    # f(x_m)
    f_best = jnp.where(a_better, fa, fb)
    # An infinite endpoint makes the convex-combination step NaN, so it
    # counts as unbracketed (finite brackets only).
    # f_a f_b ≤ 0, with a and b finite
    bracketed = (
        (jnp.sign(fa) * jnp.sign(fb) <= 0) & jnp.isfinite(a) & jnp.isfinite(b)
    )
    # tol = rtol |x_m| + atol
    tol = self.rtol * jnp.abs(x_best) + self.atol
    # done if unbracketed, f(x_m) = 0 or |b - a| < tol
    done = (~bracketed) | (f_best == 0) | (jnp.abs(b - a) < tol)
    return _ChandrupatlaState(
        a=a,
        b=b,
        c=c,
        fa=fa,
        fb=fb,
        fc=fc,
        t=jnp.full(shape, 0.5, dtype),
        x_best=x_best,
        done=done,
    )

step

step(fn: Callable[[Array, Any], tuple[Array, Any]], y: Array, args: PyTree, options: dict[str, Any], state: _ChandrupatlaState, tags: frozenset[object]) -> tuple[Array, _ChandrupatlaState, Any]

One Chandrupatla step on every entry that has not converged.

x_t = (1 − t) a + t b

The arguments are those of optimistix.AbstractRootFinder.step; it returns the best point x_m, the new state and fn's aux at x_t.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/chandrupatla.py
def step(
    self,
    fn: Callable[[Array, Any], tuple[Array, Any]],
    y: Array,
    args: PyTree,
    options: dict[str, Any],
    state: _ChandrupatlaState,
    tags: frozenset[object],
) -> tuple[Array, _ChandrupatlaState, Any]:
    """One Chandrupatla step on every entry that has not converged.

        x_t = (1 − t) a + t b

    The arguments are those of ``optimistix.AbstractRootFinder.step``;
    it returns the best point x_m, the new state and ``fn``'s aux at
    x_t.
    """
    del y, options, tags
    previous = state
    # The convex combination cannot overflow for finite a, b, unlike
    # a + t (b - a) on a bracket wider than the largest float.
    # x_t = (1 - t) a + t b
    x_t = (1 - previous.t) * previous.a + previous.t * previous.b
    # x_t ∈ {a, b}: the bracket is down to adjacent floats
    stalled = (x_t == previous.a) | (x_t == previous.b)
    f_t, aux = fn(x_t, args)

    # --- update the bracket ---
    # sign f(x_t) = sign f_a
    same_sign = jnp.sign(f_t) == jnp.sign(previous.fa)
    # c ← a if the signs agree, else c ← b
    c = jnp.where(same_sign, previous.a, previous.b)
    fc = jnp.where(same_sign, previous.fa, previous.fb)
    # b ← a if the signs differ
    b = jnp.where(same_sign, previous.b, previous.a)
    fb = jnp.where(same_sign, previous.fb, previous.fa)
    # a ← x_t
    a, fa = x_t, f_t

    # --- convergence ---
    # |f_a| < |f_b|, or f_b is NaN
    a_better = (jnp.abs(fa) < jnp.abs(fb)) | jnp.isnan(fb)
    # x_m = argmin over a, b of |f|
    x_best = jnp.where(a_better, a, b)
    # f(x_m)
    f_best = jnp.where(a_better, fa, fb)
    # tol = rtol |x_m| + atol
    tol = self.rtol * jnp.abs(x_best) + self.atol
    # t_lim = ½ tol / |b - c|
    t_lim = 0.5 * tol / jnp.abs(b - c)
    converged = (f_best == 0) | (t_lim > 0.5) | stalled

    # --- next fraction t ---
    # The divisions below may produce inf/nan on degenerate entries;
    # those entries either fail the IQI test (nan comparisons are
    # False) and bisect, or have already converged.
    # ξ = (a - b)/(c - b)
    xi = (a - b) / (c - b)
    # Φ = (f_a - f_b)/(f_c - f_b)
    phi = (fa - fb) / (fc - fb)
    # Φ² < ξ and (1 - Φ)² < 1 - ξ
    use_iqi = (phi**2 < xi) & ((1 - phi) ** 2 < 1 - xi)
    # f_a/(f_b - f_a) · f_c/(f_b - f_c)
    iqi_first = fa / (fb - fa) * fc / (fb - fc)
    # (c - a)/(b - a) · f_a/(f_c - f_a) · f_b/(f_c - f_b)
    iqi_second = (c - a) / (b - a) * fa / (fc - fa) * fb / (fc - fb)
    # t_IQI
    t_iqi = iqi_first + iqi_second
    # t = t_IQI if accepted, else ½
    t = jnp.where(use_iqi, t_iqi, 0.5)
    # t ← clip(t, t_lim, 1 - t_lim)
    t = jnp.clip(t, t_lim, 1 - t_lim)

    updated = _ChandrupatlaState(
        a=a,
        b=b,
        c=c,
        fa=fa,
        fb=fb,
        fc=fc,
        t=t,
        x_best=x_best,
        done=converged,
    )
    # Freeze entries that had already converged.
    updated = jax.tree.map(
        lambda old, new: jnp.where(previous.done, old, new), previous, updated
    )
    return updated.x_best, updated, aux

terminate

terminate(fn: Callable[[Array, Any], tuple[Array, Any]], y: Array, args: PyTree, options: dict[str, Any], state: _ChandrupatlaState, tags: frozenset[object]) -> tuple[Bool[Array, ''], RESULTS]

Stop once every entry has converged.

The arguments are those of optimistix.AbstractRootFinder.terminate.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/chandrupatla.py
def terminate(
    self,
    fn: Callable[[Array, Any], tuple[Array, Any]],
    y: Array,
    args: PyTree,
    options: dict[str, Any],
    state: _ChandrupatlaState,
    tags: frozenset[object],
) -> tuple[Bool[Array, ""], optx.RESULTS]:  # noqa: F722
    """Stop once every entry has converged.

    The arguments are those of ``optimistix.AbstractRootFinder.terminate``.
    """
    del fn, y, args, options, tags
    return jnp.all(state.done), optx.RESULTS.successful

postprocess

postprocess(fn: Callable[[Array, Any], tuple[Array, Any]], y: Array, aux: Any, args: PyTree, options: dict[str, Any], state: _ChandrupatlaState, tags: frozenset[object], result: RESULTS) -> tuple[Array, Any, dict[str, Any]]

Return x_m with fn's aux evaluated there.

The arguments are those of optimistix.AbstractRootFinder.postprocess.

Source code in packages/gauss-flows-maps/src/gauss_flows_maps/_src/monotone/chandrupatla.py
def postprocess(
    self,
    fn: Callable[[Array, Any], tuple[Array, Any]],
    y: Array,
    aux: Any,
    args: PyTree,
    options: dict[str, Any],
    state: _ChandrupatlaState,
    tags: frozenset[object],
    result: optx.RESULTS,
) -> tuple[Array, Any, dict[str, Any]]:
    """Return x_m with ``fn``'s aux evaluated there.

    The arguments are those of
    ``optimistix.AbstractRootFinder.postprocess``.
    """
    del y, aux, options, tags, result
    # Re-evaluate so ``aux`` belongs to the returned point; the step's
    # aux is that of the last trial point, which may be the other end.
    _, aux = fn(state.x_best, args)
    return state.x_best, aux, {}