Skip to content

Rules

A rule integrates by weights against samples, \(I \approx \sum_n w_n f(x_n)\). The weights come from functax's rules, from a tuple of 1-D rules (a tensor rule, one axis each), or from a plain array such as a spectral response or cell areas; integrix only sums with them. Every sum is pairwise, so a float32 sum over a long spectrum does not drift.

Both integrate and weighted_mean take where=, a boolean mask that broadcasts against the values (a plume over an image, the valid levels of each column), and nan_policy=: "propagate" (the default, so a NaN among the kept samples gives NaN) or "omit" (NaN samples are left out, like np.nansum). A dropped sample adds nothing to the sum and gets an exactly zero, finite gradient, and weighted_mean renormalises over the samples it keeps.

weighted_mean's weight may also be a batch of weight functions: the rule's shape with extra leading axes, one mean per leading index, with the values' batch axes first. An instrument's \(B\) band responses on \(G\) wavelengths reduce \(P\) spectra in one call, radiance \((P, G)\) and responses \((B, G)\) giving \((P, B)\).

log_integrate is the log-sum-exp twin of integrate: it takes \(\log f\) and returns \(\log I = \log \sum_n w_n f_n\) without leaving log space, so an integrand whose values underflow (a heavy-tailed density far from its mode) still has a finite log-integral. Its weights must be positive, and where= drops nodes by making their terms \(-\infty\).

The Spatial integrals guide works through the IME, the cross-sectional flux in its strip and sampled forms, and a NaN-propagating column. The theory is in the Rules chapter of the mathematical reference.

rule

Rules: integrals as weights against samples, I ≈ ∑ₙ wₙ f(xₙ).

integrate contracts values (or an integrand evaluated at a rule's nodes) with quadrature weights over one axis or several, batched over the rest; weighted_mean divides by the integral of a weight function, as a band radiance does; log_integrate returns log I from log f for integrands that underflow. The rules themselves (nodes and weights) come from functax, or are a plain weights array such as a spectral response or cell areas.

Integral

Bases: Module

The result of an integral: its value, an error estimate and diagnostics.

A plain rule has no error estimate, so error is None and converged is True; adaptive procedures (integrix.adapt) fill both.

Attributes:

Name Type Description
value Inexact[Array, '*batch']

The integral I, one per batch entry.

error Inexact[Array, '*batch'] | None

An estimate of |I − Î|, or None for a plain rule.

n_evaluations Int[Array, '']

The number of integrand values summed.

converged Bool[Array, '']

Whether the error target was met.

Examples:

>>> import jax.numpy as jnp
>>> result = integrate(jnp.array([0.5, 0.5]), jnp.array([1.0, 3.0]))
>>> bool(result.value == 2.0), result.error, bool(result.converged)
(True, None, True)

log_integrate

log_integrate(rule: Rule, log_values_or_fn: ArrayLike | Callable[..., Any], *, axis: Axes | None = None, args: Any = None, where: ArrayLike | None = None) -> Float[Array, '*batch']

log I from log f: the log-sum-exp twin of integrate.

log I = log ∑ₙ wₙ fₙ = logsumexp over n of (log wₙ + log fₙ), so an integrand whose values underflow (log fₙ ≈ −800, a heavy-tailed density far from its mode) still gives a finite log-integral. The weights must be positive; a mask leaves nodes out by making their term −∞.

Algorithm
  1. Read the weights w as integrate does, and check that they are positive.
  2. Get log f: the log-values as given, or log_f(nodes) (with args, log_f(nodes, args)), node axes first.
  3. Form tₙ = log wₙ + log fₙ, with −∞ for nodes where drops (their log fₙ replaced by 0 first, so neither a NaN nor its gradient leaks).
  4. Return logsumexp over the node axes.

Parameters:

Name Type Description Default
rule Rule

A rule with positive weights, a tuple of 1-D rules, or a positive weights array w, as in integrate.

required
log_values_or_fn ArrayLike | Callable[..., Any]

The log-samples log fₙ, or a callable log f evaluated at the rule's nodes and returning its node axes first.

required
axis Axes | None

The axes to integrate over, as in integrate.

None
args Any

Extra arguments passed to the callable as log_f(nodes, args).

None
where ArrayLike | None

A boolean mask that broadcasts against the log-samples; nodes where it is false are left out. With no node kept the result is −∞, the log of an empty sum.

None

Returns:

Type Description
Float[Array, '*batch']

log I, with the shape of the log-samples without the integrated axes.

Raises:

Type Description
ValidationError

As integrate (an unknown rule, a bad axis, the wrong number of samples or a bad mask), if the log-samples are complex, or if a weight is not positive (checked under jit too).

Examples:

>>> import jax.numpy as jnp
>>> weights = jnp.array([0.25, 0.75])
>>> log_total = log_integrate(weights, jnp.log(jnp.array([2.0, 4.0])))
>>> bool(jnp.allclose(log_total, jnp.log(3.5)))
True

Values far below the smallest float still have a log-integral:

>>> tiny = jnp.full(2, -800.0)
>>> bool(jnp.allclose(log_integrate(jnp.array([0.5, 0.5]), tiny), -800.0))
True

A mask drops a node:

>>> keep = jnp.array([True, False])
>>> masked = log_integrate(
...     weights, jnp.log(jnp.array([2.0, 4.0])), where=keep
... )
>>> bool(jnp.allclose(masked, jnp.log(0.5)))
True
Source code in src/integrix/_src/rule/_log.py
def log_integrate(
    rule: Rule,
    log_values_or_fn: ArrayLike | Callable[..., Any],
    *,
    axis: Axes | None = None,
    args: Any = None,
    where: ArrayLike | None = None,
) -> Float[Array, "*batch"]:
    """log I from log f: the log-sum-exp twin of `integrate`.

    log I = log ∑ₙ wₙ fₙ = logsumexp over n of (log wₙ + log fₙ), so an
    integrand whose values underflow (log fₙ ≈ −800, a heavy-tailed density
    far from its mode) still gives a finite log-integral. The weights must be
    positive; a mask leaves nodes out by making their term −∞.

    Algorithm:
        1. Read the weights w as `integrate` does, and check that they are
           positive.
        2. Get log f: the log-values as given, or ``log_f(nodes)`` (with
           ``args``, ``log_f(nodes, args)``), node axes first.
        3. Form tₙ = log wₙ + log fₙ, with −∞ for nodes ``where`` drops (their
           log fₙ replaced by 0 first, so neither a NaN nor its gradient
           leaks).
        4. Return logsumexp over the node axes.

    Args:
        rule: A rule with positive ``weights``, a tuple of 1-D rules, or a
            positive weights array w, as in `integrate`.
        log_values_or_fn: The log-samples log fₙ, or a callable log f
            evaluated at the rule's ``nodes`` and returning its node axes
            first.
        axis: The axes to integrate over, as in `integrate`.
        args: Extra arguments passed to the callable as ``log_f(nodes, args)``.
        where: A boolean mask that broadcasts against the log-samples; nodes
            where it is false are left out. With no node kept the result is
            −∞, the log of an empty sum.

    Returns:
        log I, with the shape of the log-samples without the integrated axes.

    Raises:
        ValidationError: As `integrate` (an unknown rule, a bad axis, the
            wrong number of samples or a bad mask), if the log-samples are
            complex, or if a weight is not positive (checked under ``jit``
            too).

    Examples:
        >>> import jax.numpy as jnp
        >>> weights = jnp.array([0.25, 0.75])
        >>> log_total = log_integrate(weights, jnp.log(jnp.array([2.0, 4.0])))
        >>> bool(jnp.allclose(log_total, jnp.log(3.5)))
        True

        Values far below the smallest float still have a log-integral:

        >>> tiny = jnp.full(2, -800.0)
        >>> bool(jnp.allclose(log_integrate(jnp.array([0.5, 0.5]), tiny), -800.0))
        True

        A mask drops a node:

        >>> keep = jnp.array([True, False])
        >>> masked = log_integrate(
        ...     weights, jnp.log(jnp.array([2.0, 4.0])), where=keep
        ... )
        >>> bool(jnp.allclose(masked, jnp.log(0.5)))
        True
    """
    weights, nodes = _read_rule(rule)
    if callable(log_values_or_fn):
        if nodes is None:
            raise ValidationError(
                "'rule' must have 'nodes' to evaluate a callable integrand"
            )
        if axis is not None:
            raise ValidationError(
                "'axis' must be None for a callable integrand, whose node axes "
                "come first"
            )
        log_fn = log_values_or_fn
        evaluated = log_fn(nodes) if args is None else log_fn(nodes, args)
        log_values = jnp.asarray(evaluated)
        axes = tuple(range(weights.ndim))
    else:
        log_values = jnp.asarray(log_values_or_fn)
        axes = normalise_axes(axis, log_values.ndim, weights.ndim)
    check_node_shape(log_values, axes, weights.shape)
    if jnp.issubdtype(log_values.dtype, jnp.complexfloating):
        raise ValidationError(
            f"'log_values_or_fn' must be real, got dtype {log_values.dtype}"
        )
    keep = _kept_samples(log_values, where, "propagate")

    dtype = working_dtype(log_values.dtype, weights.dtype)
    log_samples = nodes_first(log_values.astype(dtype), axes)
    flat_weights = flatten(weights).astype(dtype)
    flat_weights = eqx.error_if(
        flat_weights,
        jnp.any(flat_weights <= 0),
        "'rule' must have positive weights for log_integrate",
    )
    # log wₙ
    log_weights = jnp.log(flat_weights)
    if keep is not None:
        kept = nodes_first(keep, axes) > 0
        zero = jnp.zeros((), dtype)
        # 0 in place of every dropped log fₙ, so its NaN cannot leak
        log_samples = jnp.where(kept, log_samples, zero)
    # tₙ = log wₙ + log fₙ
    terms = einx.add("n ..., n -> n ...", log_samples, log_weights)
    if keep is not None:
        minus_infinity = jnp.asarray(-jnp.inf, dtype)
        # a dropped node adds e^(−∞) = 0 to the sum
        terms = jnp.where(kept, terms, minus_infinity)
    # log I = logsumexp over n of tₙ
    return einx.logsumexp("n ... -> ...", terms)

integrate

integrate(rule: Rule, values_or_fn: ArrayLike | Callable[..., Any], *, axis: Axes | None = None, args: Any = None, where: ArrayLike | None = None, nan_policy: NanPolicy = 'propagate') -> Integral

Integrate values, or an integrand, against a rule's weights.

I ≈ ∑ₙ wₙ f(xₙ), contracted over one axis or several and batched over the rest; with a mask or nan_policy="omit", I ≈ ∑ over kept n of wₙ fₙ.

Algorithm
  1. Read the weights w: a rule's weights, the outer product of a tuple of 1-D rules (a tensor rule, one axis each), or a plain array (a spectral response, cell areas).
  2. Get the samples: the values as given, or f(nodes) (with args, f(nodes, args)), whose node axes come first.
  3. Keep the samples where where holds and, with nan_policy="omit", that are not NaN; put 0 in place of every other sample, so it adds nothing and gets a zero gradient.
  4. Move the node axes first and flatten them into one, (N, …).
  5. Cast w to the samples' dtype and sum wₙ fₙ pairwise over N.

Parameters:

Name Type Description Default
rule Rule

A rule with weights (functax's Rule), a tuple of 1-D rules, or a weights array w.

required
values_or_fn ArrayLike | Callable[..., Any]

The samples fₙ, or a callable f evaluated at the rule's nodes and returning its node axes first.

required
axis Axes | None

The axes of the samples to integrate over, one per weights axis. None takes the last ones (-1 for a 1-D rule); a callable's node axes are always first, so it takes no axis.

None
args Any

Extra arguments passed to the callable as f(nodes, args).

None
where ArrayLike | None

A boolean mask that broadcasts against the samples (a plume over an image, the valid levels of each column); samples where it is false are left out. None keeps every sample.

None
nan_policy NanPolicy

"propagate" (a NaN among the kept samples makes the integral NaN, as without the argument) or "omit" (NaN samples are left out, like np.nansum). A callable's own derivative is not guarded: if f itself produces a NaN in a gradient, mask inside f.

'propagate'

Returns:

Type Description
Integral

An Integral whose value has the shape of the samples without

Integral

the integrated axes; error is None.

Raises:

Type Description
ValidationError

If the rule has no weights, a tensor rule holds a rule that is not 1-D, a callable meets a rule without nodes or an axis, an axis is out of range or repeated, the samples do not have one entry per node along the integrated axes, where is not boolean or does not broadcast to the samples, or nan_policy is neither "propagate" nor "omit".

Examples:

>>> import jax.numpy as jnp
>>> weights = jnp.array([0.25, 0.75])
>>> total = integrate(weights, jnp.array([[1.0, 2.0], [10.0, 20.0]]))
>>> bool(jnp.allclose(total.value, jnp.array([1.75, 17.5])))
True

A callable returns its node axis first:

>>> import equinox as eqx
>>> class Trapezoid(eqx.Module):
...     nodes: jnp.ndarray
...     weights: jnp.ndarray
>>> rule = Trapezoid(jnp.array([0.0, 1.0]), jnp.array([0.5, 0.5]))
>>> total = integrate(rule, lambda x: jnp.outer(x, jnp.array([1.0, 10.0])))
>>> bool(jnp.allclose(total.value, jnp.array([0.5, 5.0])))
True

A tensor rule integrates two axes, one rule each:

>>> image = jnp.ones((2, 2, 4))
>>> integrate((rule, rule), image, axis=(0, 1)).value.shape
(4,)

A mask and a NaN, both left out (np.nansum over the mask):

>>> enhancement = jnp.array([1.0, jnp.nan, 3.0, 4.0])
>>> plume = jnp.array([True, True, True, False])
>>> mass = integrate(
...     jnp.ones(4), enhancement, where=plume, nan_policy="omit"
... )
>>> bool(mass.value == 4.0)
True
Source code in src/integrix/_src/rule/_rule.py
def integrate(
    rule: Rule,
    values_or_fn: ArrayLike | Callable[..., Any],
    *,
    axis: Axes | None = None,
    args: Any = None,
    where: ArrayLike | None = None,
    nan_policy: NanPolicy = "propagate",
) -> Integral:
    """Integrate values, or an integrand, against a rule's weights.

    I ≈ ∑ₙ wₙ f(xₙ), contracted over one axis or several and batched over the
    rest; with a mask or ``nan_policy="omit"``, I ≈ ∑ over kept n of wₙ fₙ.

    Algorithm:
        1. Read the weights w: a rule's ``weights``, the outer product of a
           tuple of 1-D rules (a tensor rule, one axis each), or a plain array
           (a spectral response, cell areas).
        2. Get the samples: the values as given, or ``f(nodes)`` (with
           ``args``, ``f(nodes, args)``), whose node axes come first.
        3. Keep the samples where ``where`` holds and, with
           ``nan_policy="omit"``, that are not NaN; put 0 in place of every
           other sample, so it adds nothing and gets a zero gradient.
        4. Move the node axes first and flatten them into one, (N, …).
        5. Cast w to the samples' dtype and sum wₙ fₙ pairwise over N.

    Args:
        rule: A rule with ``weights`` (functax's ``Rule``), a tuple of 1-D
            rules, or a weights array w.
        values_or_fn: The samples fₙ, or a callable f evaluated at the rule's
            ``nodes`` and returning its node axes first.
        axis: The axes of the samples to integrate over, one per weights
            axis. ``None`` takes the last ones (``-1`` for a 1-D rule); a
            callable's node axes are always first, so it takes no ``axis``.
        args: Extra arguments passed to the callable as ``f(nodes, args)``.
        where: A boolean mask that broadcasts against the samples (a plume
            over an image, the valid levels of each column); samples where it
            is false are left out. ``None`` keeps every sample.
        nan_policy: ``"propagate"`` (a NaN among the kept samples makes the
            integral NaN, as without the argument) or ``"omit"`` (NaN samples
            are left out, like ``np.nansum``). A callable's own derivative is
            not guarded: if f itself produces a NaN in a gradient, mask inside
            f.

    Returns:
        An `Integral` whose ``value`` has the shape of the samples without
        the integrated axes; ``error`` is ``None``.

    Raises:
        ValidationError: If the rule has no weights, a tensor rule holds a
            rule that is not 1-D, a callable meets a rule without ``nodes``
            or an ``axis``, an axis is out of range or repeated, the samples
            do not have one entry per node along the integrated axes,
            ``where`` is not boolean or does not broadcast to the samples, or
            ``nan_policy`` is neither ``"propagate"`` nor ``"omit"``.

    Examples:
        >>> import jax.numpy as jnp
        >>> weights = jnp.array([0.25, 0.75])
        >>> total = integrate(weights, jnp.array([[1.0, 2.0], [10.0, 20.0]]))
        >>> bool(jnp.allclose(total.value, jnp.array([1.75, 17.5])))
        True

        A callable returns its node axis first:

        >>> import equinox as eqx
        >>> class Trapezoid(eqx.Module):
        ...     nodes: jnp.ndarray
        ...     weights: jnp.ndarray
        >>> rule = Trapezoid(jnp.array([0.0, 1.0]), jnp.array([0.5, 0.5]))
        >>> total = integrate(rule, lambda x: jnp.outer(x, jnp.array([1.0, 10.0])))
        >>> bool(jnp.allclose(total.value, jnp.array([0.5, 5.0])))
        True

        A tensor rule integrates two axes, one rule each:

        >>> image = jnp.ones((2, 2, 4))
        >>> integrate((rule, rule), image, axis=(0, 1)).value.shape
        (4,)

        A mask and a NaN, both left out (``np.nansum`` over the mask):

        >>> enhancement = jnp.array([1.0, jnp.nan, 3.0, 4.0])
        >>> plume = jnp.array([True, True, True, False])
        >>> mass = integrate(
        ...     jnp.ones(4), enhancement, where=plume, nan_policy="omit"
        ... )
        >>> bool(mass.value == 4.0)
        True
    """
    weights, nodes = _read_rule(rule)
    if callable(values_or_fn):
        if nodes is None:
            raise ValidationError(
                "'rule' must have 'nodes' to evaluate a callable integrand"
            )
        if axis is not None:
            raise ValidationError(
                "'axis' must be None for a callable integrand, whose node axes "
                "come first"
            )
        evaluated = values_or_fn(nodes) if args is None else values_or_fn(nodes, args)
        values = jnp.asarray(evaluated)
        axes = tuple(range(weights.ndim))
    else:
        values = jnp.asarray(values_or_fn)
        axes = normalise_axes(axis, values.ndim, weights.ndim)
    check_node_shape(values, axes, weights.shape)
    keep = _kept_samples(values, where, nan_policy)

    dtype = working_dtype(values.dtype, weights.dtype)
    samples = nodes_first(values.astype(dtype), axes)
    if keep is not None:
        kept = nodes_first(keep, axes) > 0
        # 0 in place of every dropped sample, so wₙ · 0 carries no NaN forward
        # and the dropped sample's gradient is exactly 0
        samples = jnp.where(kept, samples, jnp.zeros((), dtype))
    flat_weights = flatten(weights).astype(dtype)
    value = _contract(flat_weights, samples)
    return Integral(
        value=value,
        error=None,
        n_evaluations=jnp.asarray(flat_weights.shape[0]),
        converged=jnp.asarray(True),
    )

weighted_mean

weighted_mean(rule: Rule, values: ArrayLike, *, weight: ArrayLike, axis: Axes | None = None, where: ArrayLike | None = None, nan_policy: NanPolicy = 'propagate') -> Inexact[Array, '*batch']

The mean of the values under a weight function, with one rule for both sums.

L̄ = ∫ L(x) R(x) dx / ∫ R(x) dx ≈ ∑ₙ wₙ Rₙ Lₙ / ∑ₙ wₙ Rₙ, a band radiance from a spectrum L and a spectral response R, say. With a mask or nan_policy="omit", both sums run over the kept samples K only, so the mean renormalises: ∑ over K of wₙ Rₙ Lₙ / ∑ over K of wₙ Rₙ. A batch of weight functions R_b (an instrument's band responses) gives one mean per b, L̄_b = ∑ₙ wₙ R_bn Lₙ / ∑ₙ wₙ R_bn.

Algorithm
  1. Place R along the integrated axes (or use it as given when it has the values' shape); a batch of weight functions keeps its leading axes.
  2. Keep the samples as integrate does, with 0 in place of the others in both sums.
  3. Sum wₙ Rₙ Lₙ and wₙ Rₙ pairwise with the same weights.
  4. Divide.

Parameters:

Name Type Description Default
rule Rule

A rule with weights, a tuple of 1-D rules, or a weights array w, as in integrate.

required
values ArrayLike

The values Lₙ.

required
weight ArrayLike

The weight function Rₙ, with the shape of values (one per sample, laid out like the values), of the rule's weights (one per node, in the rule's order), or of the rule's weights with extra leading axes (a batch of weight functions, such as B band responses). The checks run in that order, so a weight with the values' shape is always read per sample.

required
axis Axes | None

The axes to average over, as in integrate.

None
where ArrayLike | None

A boolean mask that broadcasts against the values, as in integrate.

None
nan_policy NanPolicy

"propagate" or "omit", as in integrate; only NaN values are omitted, not NaN weights.

'propagate'

Returns:

Type Description
Inexact[Array, '*batch']

The weighted mean, with the shape of values without the averaged

Inexact[Array, '*batch']

axes, followed by a batch of weights' leading axes: radiance (P, G)

Inexact[Array, '*batch']

and responses (B, G) give (P, B). A weight that sums to zero, or a

Inexact[Array, '*batch']

mean with no kept sample, gives nan.

Raises:

Type Description
ValidationError

As integrate, or if weight has neither the values' shape nor the weights' shape, with or without leading axes.

Examples:

>>> import jax.numpy as jnp
>>> weights = jnp.array([0.5, 1.0, 0.5])
>>> radiance = jnp.array([[1.0, 2.0, 3.0], [2.0, 2.0, 2.0]])
>>> response = jnp.array([0.0, 1.0, 1.0])
>>> band = weighted_mean(weights, radiance, weight=response)
>>> bool(jnp.allclose(band, jnp.array([7.0 / 3.0, 2.0])))
True

A NaN sample is left out and the mean renormalises over the rest:

>>> cloudy = jnp.array([[1.0, 2.0, jnp.nan]])
>>> band = weighted_mean(
...     weights, cloudy, weight=response, nan_policy="omit"
... )
>>> bool(jnp.allclose(band, jnp.array([2.0])))
True

Three band responses at once, one mean per pixel and band:

>>> responses = jnp.array(
...     [[0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 1.0]]
... )
>>> bands = weighted_mean(weights, radiance, weight=responses)
>>> bands.shape
(2, 3)
>>> expected = jnp.array([[7.0 / 3.0, 1.0, 2.0], [2.0, 2.0, 2.0]])
>>> bool(jnp.allclose(bands, expected))
True
Source code in src/integrix/_src/rule/_rule.py
def weighted_mean(
    rule: Rule,
    values: ArrayLike,
    *,
    weight: ArrayLike,
    axis: Axes | None = None,
    where: ArrayLike | None = None,
    nan_policy: NanPolicy = "propagate",
) -> Inexact[Array, "*batch"]:
    """The mean of the values under a weight function, with one rule for both sums.

    L̄ = ∫ L(x) R(x) dx / ∫ R(x) dx ≈ ∑ₙ wₙ Rₙ Lₙ / ∑ₙ wₙ Rₙ, a band radiance
    from a spectrum L and a spectral response R, say. With a mask or
    ``nan_policy="omit"``, both sums run over the kept samples K only, so the
    mean renormalises: ∑ over K of wₙ Rₙ Lₙ / ∑ over K of wₙ Rₙ. A batch of
    weight functions R_b (an instrument's band responses) gives one mean per
    b, L̄_b = ∑ₙ wₙ R_bn Lₙ / ∑ₙ wₙ R_bn.

    Algorithm:
        1. Place R along the integrated axes (or use it as given when it has
           the values' shape); a batch of weight functions keeps its leading
           axes.
        2. Keep the samples as `integrate` does, with 0 in place of the
           others in both sums.
        3. Sum wₙ Rₙ Lₙ and wₙ Rₙ pairwise with the same weights.
        4. Divide.

    Args:
        rule: A rule with ``weights``, a tuple of 1-D rules, or a weights
            array w, as in `integrate`.
        values: The values Lₙ.
        weight: The weight function Rₙ, with the shape of ``values`` (one per
            sample, laid out like the values), of the rule's weights (one per
            node, in the rule's order), or of the rule's weights with extra
            leading axes (a batch of weight functions, such as B band
            responses). The checks run in that order, so a weight with the
            values' shape is always read per sample.
        axis: The axes to average over, as in `integrate`.
        where: A boolean mask that broadcasts against the values, as in
            `integrate`.
        nan_policy: ``"propagate"`` or ``"omit"``, as in `integrate`; only NaN
            values are omitted, not NaN weights.

    Returns:
        The weighted mean, with the shape of ``values`` without the averaged
        axes, followed by a batch of weights' leading axes: radiance (P, G)
        and responses (B, G) give (P, B). A weight that sums to zero, or a
        mean with no kept sample, gives ``nan``.

    Raises:
        ValidationError: As `integrate`, or if ``weight`` has neither the
            values' shape nor the weights' shape, with or without leading
            axes.

    Examples:
        >>> import jax.numpy as jnp
        >>> weights = jnp.array([0.5, 1.0, 0.5])
        >>> radiance = jnp.array([[1.0, 2.0, 3.0], [2.0, 2.0, 2.0]])
        >>> response = jnp.array([0.0, 1.0, 1.0])
        >>> band = weighted_mean(weights, radiance, weight=response)
        >>> bool(jnp.allclose(band, jnp.array([7.0 / 3.0, 2.0])))
        True

        A NaN sample is left out and the mean renormalises over the rest:

        >>> cloudy = jnp.array([[1.0, 2.0, jnp.nan]])
        >>> band = weighted_mean(
        ...     weights, cloudy, weight=response, nan_policy="omit"
        ... )
        >>> bool(jnp.allclose(band, jnp.array([2.0])))
        True

        Three band responses at once, one mean per pixel and band:

        >>> responses = jnp.array(
        ...     [[0.0, 1.0, 1.0], [1.0, 0.0, 0.0], [1.0, 1.0, 1.0]]
        ... )
        >>> bands = weighted_mean(weights, radiance, weight=responses)
        >>> bands.shape
        (2, 3)
        >>> expected = jnp.array([[7.0 / 3.0, 1.0, 2.0], [2.0, 2.0, 2.0]])
        >>> bool(jnp.allclose(bands, expected))
        True
    """
    weights, _ = _read_rule(rule)
    values = jnp.asarray(values)
    weight = jnp.asarray(weight)
    axes = normalise_axes(axis, values.ndim, weights.ndim)
    check_node_shape(values, axes, weights.shape)
    keep = _kept_samples(values, where, nan_policy)

    dtype = working_dtype(values.dtype, weights.dtype, weight.dtype)
    samples = nodes_first(values.astype(dtype), axes)
    flat_weights = flatten(weights).astype(dtype)
    zero = jnp.zeros((), dtype)
    kept = None if keep is None else nodes_first(keep, axes) > 0
    if kept is not None:
        # 0 in place of every dropped sample, as in `integrate`
        samples = jnp.where(kept, samples, zero)
    # A weight shaped like the values is read per sample, in the values'
    # layout, even when it also has the weights' shape (a square grid).
    if weight.shape == values.shape:
        # one Rₙ per sample: the same contraction on R ⊙ L and on R
        response = nodes_first(weight.astype(dtype), axes)
        if kept is not None:
            # a dropped sample leaves the denominator too: ∑ over K of wₙ Rₙ
            response = jnp.where(kept, response, zero)
        numerator = _contract(flat_weights, response * samples)
        denominator = _contract(flat_weights, response)
    elif weight.shape == weights.shape:
        # one Rₙ per node, in the rule's order: wₙ Rₙ
        flat_response = flatten(weight).astype(dtype)
        combined = flat_weights * flat_response
        numerator = _contract(combined, samples)
        if kept is None:
            denominator = pairwise_sum(combined)
        else:
            # ∑ over K of wₙ Rₙ, one sum per batch entry
            denominator = _contract(combined, kept.astype(dtype))
    elif (
        weight.ndim > weights.ndim
        and weight.shape[weight.ndim - weights.ndim :] == weights.shape
    ):
        response = weight.astype(dtype)
        return _batched_mean(flat_weights, response, weights.ndim, samples, kept)
    else:
        raise ValidationError(
            f"'weight' must have the values' shape {values.shape} or the rule's "
            f"weights shape {weights.shape}, with or without leading axes, got "
            f"{weight.shape}"
        )
    # L̄ = ∑ wR L / ∑ wR
    return numerator / denominator