Skip to content

Adaptive quadrature

Adaptive quadrature computes \(I = \int_a^b f(x) \mathrm{d}x\) to a tolerance, with an error estimate. On each subinterval the Kronrod rule \(K_{2n+1}\) gives the value and its embedded Gauss rule \(G_n\) the error, \(E \approx \lvert K_{2n+1}(f) - G_n(f) \rvert\), for no extra evaluations; the subinterval with the largest error is bisected until \(E \le \max(\text{atol}, \text{rtol} \lvert I \rvert)\) or the static buffer of subintervals is full. The search runs inside jax.lax.while_loop with static shapes, so it traces under jit and vmap, and converged is returned rather than raised. Reverse mode cannot run through that loop, so the derivative is that of the final rule on the final partition, held fixed (a custom JVP), in the integrand's parameters and in the limits.

TanhSinh substitutes \(x = \tanh(\frac{\pi}{2} \sinh t)\) (exp–sinh or sinh–sinh for infinite limits), so an integrand singular at an endpoint, such as \(\log x\) or \(x^{-1/2}\), decays double-exponentially in \(t\) and the trapezoid rule in \(t\) converges fast. Romberg extrapolates trapezoid estimates by Richardson, for smooth integrands. Both compute every level up to max_levels with static shapes and return the first within tolerance, so they differentiate directly. cumulative_adaptive integrates each interval between consecutive nodes with GaussKronrod and prefix-sums them.

The Gauss–Kronrod nodes and weights are QUADPACK's (Piessens et al., 1983). The design follows quadax, with no dependency on it; quadax and scipy.integrate.quad are test references only.

The theory is in the Adaptivity chapter of the mathematical reference.

adapt

Adaptive quadrature: integrals to a tolerance, with an error estimate.

GaussKronrod integrates on a finite interval to a tolerance, under jit with a static buffer of subintervals, and differentiates through a custom JVP. TanhSinh handles endpoint singularities and infinite limits, Romberg smooth integrands, and cumulative_adaptive the running integral to each node. Each returns an integrix.rule.Integral whose error and converged are filled in. Written on quadax's design, with no dependency on quadax.

GaussKronrod

Bases: Module

Adaptive Gauss–Kronrod quadrature to a tolerance, with an error estimate.

I = ∫ₐᵇ f(x) dx. On each subinterval the Kronrod rule K₂ₙ₊₁ gives the value and its embedded Gauss rule Gₙ the error, E ≈ |K₂ₙ₊₁(f) − Gₙ(f)|, for no extra evaluations (the Gauss nodes are a subset of the Kronrod ones). Endpoint singularities need tanh–sinh, not Gauss–Kronrod.

Algorithm
  1. Evaluate the pair on [a, b].
  2. While the summed error of any output entry exceeds max(atol, rtol |I|) and the buffer of max_intervals subintervals has room, bisect the subinterval with the largest error and evaluate the pair on both halves.
  3. Return the summed value and error, the number of evaluations, and converged (never raised: under jit it is a flag to check).

The derivative, forward or reverse, is that of the final Kronrod rule on the final partition held fixed: in the integrand's parameters (through args or closed-over arrays) and in the limits a and b.

Attributes:

Name Type Description
order int

The number of Kronrod points 2n + 1: 15, 21, 31, 41, 51 or 61.

rtol float

The relative tolerance on the summed error, ≥ 0.

atol float

The absolute tolerance on the summed error, ≥ 0.

max_intervals int

The size of the static subinterval buffer, ≥ 1.

Raises:

Type Description
ValidationError

If order has no table, a tolerance is negative or not finite, or max_intervals is not a positive integer.

References

Piessens, R. et al. (1983). QUADPACK: A Subroutine Package for Automatic Integration. Springer.

Examples:

>>> import jax.numpy as jnp
>>> result = GaussKronrod(rtol=1e-6)(jnp.exp, 0.0, 1.0)
>>> bool(jnp.allclose(result.value, jnp.e - 1.0)), bool(result.converged)
(True, True)

A peaked integrand takes more subintervals:

>>> peak = lambda x, width: 1.0 / (width**2 + (x - 0.3) ** 2)
>>> result = GaussKronrod(rtol=1e-6)(peak, 0.0, 1.0, args=0.01)
>>> bool(result.converged), int(result.n_evaluations) > 15
(True, True)

Romberg

Bases: Module

Romberg integration of a smooth integrand on a finite interval.

The trapezoid estimates T(h), T(h/2), … have the error expansion T(h) = I + c₁h² + c₂h⁴ + …, so Richardson extrapolation Rℓ,ₘ = Rℓ,ₘ₋₁ + (Rℓ,ₘ₋₁ − Rℓ₋₁,ₘ₋₁)/(4ᵐ − 1) removes one term per column. It suits smooth and periodic-like integrands; a singular one needs tanh–sinh and a peaked one Gauss–Kronrod.

Algorithm
  1. Evaluate f once on 2^L + 1 equally spaced points.
  2. For each level ℓ = 0, …, L, the trapezoid sum Tℓ = Rℓ,₀ on every 2^{L−ℓ}-th point, and its extrapolations Rℓ,ₘ, m = 1, …, ℓ.
  3. The diagonal Rℓ,ℓ is level ℓ's estimate and |Rℓ,ℓ − Rℓ₋₁,ℓ₋₁| its error; return the first level within max(atol, rtol |I|), or the last, with converged.

Attributes:

Name Type Description
rtol float

The relative tolerance, ≥ 0.

atol float

The absolute tolerance, ≥ 0.

max_levels int

The number of halvings L ≥ 1 (2^L + 1 evaluations).

min_levels int

The coarsest level ℓ ≥ 1 that may be accepted. A periodic integrand whose zeros fall on a coarse grid (sin²(8πx) on [0, 1] vanishes at every node up to 9 points) fools any level difference, so levels below this are never accepted.

Raises:

Type Description
ValidationError

If a tolerance is negative or not finite, or max_levels or min_levels is out of range.

References

Romberg, W. (1955). Vereinfachte numerische Integration. Det Kongelige Norske Videnskabers Selskab Forhandlinger 28, 30–36.

Examples:

>>> import jax.numpy as jnp
>>> result = Romberg(rtol=1e-6)(jnp.exp, 0.0, 1.0)
>>> bool(jnp.allclose(result.value, jnp.e - 1.0)), bool(result.converged)
(True, True)

TanhSinh

Bases: Module

Tanh–sinh (double-exponential) quadrature, for singular ends and infinite limits.

I = ∫ₐᵇ f(x) dx with x = c + d tanh(u), u = (π/2) sinh t, c = (a + b)/2, d = (b − a)/2, so dx = d (π/2) cosh t sech²(u) dt decays like e^{−(π/2)e^{|t|}} and the trapezoid rule in t converges double-exponentially, even for f(x) = log x or x^{−1/2} at an endpoint. For [a, ∞) the map is exp–sinh, x = a + e^{u}; for (−∞, ∞) it is sinh–sinh, x = sinh(u).

Algorithm
  1. Evaluate f once on the finest grid t = k h, h = 2^{−L}, |t| ≤ 4. Near a finite endpoint the distance (b − a)/(1 + e^{2|u|}) is formed directly, so x never rounds onto the endpoint; a node that still does gets weight zero.
  2. For each level ℓ = 0, …, L, the trapezoid sum Tℓ on every 2^{L−ℓ}-th node; the error of level ℓ is |Tℓ − Tℓ₋₁|.
  3. Return the first level within max(atol, rtol |I|), or the last, with converged.

Attributes:

Name Type Description
rtol float

The relative tolerance, ≥ 0.

atol float

The absolute tolerance, ≥ 0.

max_levels int

The number of step halvings L ≥ 1; the finest grid has 8 · 2^L + 1 nodes (9 · 2^L + 1 for a half-infinite interval).

min_levels int

The coarsest level ℓ ≥ 1 that may be accepted, against a coarse grid whose nodes all land on the integrand's zeros.

The integrand sees x, not the distance to the end: near a singular endpoint at a ≠ 0, x − a is quantised to the spacing of floats at a, so f(x) = (x − a)^{−1/2} loses accuracy there. Shift the variable so the singularity sits at 0.

Raises:

Type Description
ValidationError

If a tolerance is negative or not finite, or max_levels or min_levels is out of range.

References

Takahasi, H. and Mori, M. (1974). Double exponential formulas for numerical integration. Publ. RIMS Kyoto Univ. 9, 721–741.

Examples:

>>> import jax.numpy as jnp
>>> result = TanhSinh(rtol=1e-6)(jnp.log, 0.0, 1.0)
>>> bool(jnp.allclose(result.value, -1.0)), bool(result.converged)
(True, True)
>>> result = TanhSinh(rtol=1e-6)(lambda x: jnp.exp(-x), 0.0, float("inf"))
>>> bool(jnp.allclose(result.value, 1.0))
True

cumulative_adaptive

cumulative_adaptive(rule: GaussKronrod, fn: Callable[..., ArrayLike], nodes: ArrayLike, *, args: Any = None) -> Integral

∫ from x₀ to each node xₖ of f, each interval integrated adaptively.

Fₖ = ∑ⱼ≤ₖ ∫ from xⱼ₋₁ to xⱼ of f, with F₀ = 0: each interval between consecutive nodes gets its own adaptive Gauss–Kronrod integral (run under jax.vmap), and the interval integrals are prefix-summed with jax.lax.associative_scan, as integrix.scan.cumulative does with trapezoid increments.

Parameters:

Name Type Description Default
rule GaussKronrod

The adaptive rule for each interval, a GaussKronrod.

required
fn Callable[..., ArrayLike]

The integrand f(x), or f(x, args) when args is given.

required
nodes ArrayLike

The N ≥ 1 nodes x₀, …, x_{N−1}, ascending or descending.

required
args Any

Parameters passed to fn, differentiable.

None

Returns:

Type Description
Integral

An integrix.rule.Integral whose value is F, shape (N, …), whose

Integral

error is the running sum of the interval errors, whose

Integral

n_evaluations is their total and whose converged says every

Integral

interval converged.

Raises:

Type Description
ValidationError

If rule is not a GaussKronrod or nodes is not a non-empty vector.

Examples:

>>> import jax.numpy as jnp
>>> from integrix.adapt import GaussKronrod
>>> nodes = jnp.array([0.0, 0.5, 1.0, 2.0])
>>> running = cumulative_adaptive(GaussKronrod(rtol=1e-6), jnp.exp, nodes)
>>> bool(jnp.allclose(running.value, jnp.exp(nodes) - 1.0))
True
Source code in src/integrix/_src/adapt/_cumulative.py
def cumulative_adaptive(
    rule: GaussKronrod,
    fn: Callable[..., ArrayLike],
    nodes: ArrayLike,
    *,
    args: Any = None,
) -> Integral:
    """∫ from x₀ to each node xₖ of f, each interval integrated adaptively.

    Fₖ = ∑ⱼ≤ₖ ∫ from xⱼ₋₁ to xⱼ of f, with F₀ = 0: each interval between
    consecutive nodes gets its own adaptive Gauss–Kronrod integral (run under
    `jax.vmap`), and the interval integrals are prefix-summed with
    `jax.lax.associative_scan`, as `integrix.scan.cumulative` does with
    trapezoid increments.

    Args:
        rule: The adaptive rule for each interval, a `GaussKronrod`.
        fn: The integrand f(x), or f(x, args) when ``args`` is given.
        nodes: The N ≥ 1 nodes x₀, …, x_{N−1}, ascending or descending.
        args: Parameters passed to ``fn``, differentiable.

    Returns:
        An `integrix.rule.Integral` whose ``value`` is F, shape (N, …), whose
        ``error`` is the running sum of the interval errors, whose
        ``n_evaluations`` is their total and whose ``converged`` says every
        interval converged.

    Raises:
        ValidationError: If ``rule`` is not a `GaussKronrod` or ``nodes`` is
            not a non-empty vector.

    Examples:
        >>> import jax.numpy as jnp
        >>> from integrix.adapt import GaussKronrod
        >>> nodes = jnp.array([0.0, 0.5, 1.0, 2.0])
        >>> running = cumulative_adaptive(GaussKronrod(rtol=1e-6), jnp.exp, nodes)
        >>> bool(jnp.allclose(running.value, jnp.exp(nodes) - 1.0))
        True
    """
    if not isinstance(rule, GaussKronrod):
        raise ValidationError(
            f"'rule' must be a GaussKronrod, got {type(rule).__name__}"
        )
    nodes = jnp.asarray(nodes)
    if nodes.ndim != 1 or nodes.shape[0] == 0:
        raise ValidationError(
            f"'nodes' must be a vector of at least one node, got shape "
            f"{np.shape(nodes)}"
        )
    nodes = nodes.astype(jnp.result_type(nodes, float))
    if nodes.shape[0] == 1:
        # one node: F₀ = 0, with the integrand's output shape
        out = jax.eval_shape(lambda x: rule(fn, x, x, args=args).value, nodes[0])
        zeros = jnp.zeros((1, *out.shape), dtype=out.dtype)
        return Integral(
            value=zeros,
            error=zeros,
            n_evaluations=jnp.asarray(0),
            converged=jnp.asarray(True),
        )
    pieces = jax.vmap(lambda a, b: rule(fn, a, b, args=args))(nodes[:-1], nodes[1:])
    # Fₖ = ∑ⱼ≤ₖ Iⱼ, with F₀ = 0
    running = jax.lax.associative_scan(jnp.add, pieces.value)
    running_error = jax.lax.associative_scan(jnp.add, jnp.asarray(pieces.error))
    value = jnp.concatenate([jnp.zeros_like(running[:1]), running])
    error = jnp.concatenate([jnp.zeros_like(running_error[:1]), running_error])
    return Integral(
        value=value,
        error=error,
        n_evaluations=jnp.sum(pieces.n_evaluations),
        converged=jnp.all(pieces.converged),
    )