Skip to content

Integral operators

An integral operator with kernel \(k\) and a measure \(\mu\) is \((\mathcal{K} f)(\vect{x}) = \int k(\vect{x}, \vect{s}) f(\vect{s}) \mathrm{d}\mu(\vect{s})\). On a rule with nodes \(\vect{s}_j\) and weights \(w_j\) it becomes \((\mathcal{K} f)(\vect{x}_i) \approx \sum_j k(\vect{x}_i, \vect{s}_j) w_j f(\vect{s}_j)\), the quadrature method. IntegralOperator applies it at any \(M\) targets for any KernelLike kernel and any functax rule, in blocks of chunk targets mapped with jax.lax.map, so memory is \(O(\text{chunk} \times N)\) and the \(M \times N\) kernel matrix is never formed. A kernel with exact features \(\phi\), \(k(\vect{x}, \vect{x}') = \phi(\vect{x})^\top \phi(\vect{x}')\), takes the low-rank path \(\phi(\vect{x})^\top (\mat{\Phi}_s^\top (\vect{w} \odot \vect{f}))\) instead.

The adjoint has the transposed kernel \(k^*(\vect{s}, \vect{x}) = k(\vect{x}, \vect{s})\). On rules the measures become diagonal weights, and the \(L^2\) adjoint of \(\mat{K}\mat{W}\) between a target rule with weights \(\mat{V}\) and the node rule is \(\mat{W}^{-1} (\mat{K}\mat{W})^\top \mat{V}\). adjoint returns the plain transpose \((\mat{K}\mat{W})^\top \vect{r}\), which is the reverse-mode derivative of the forward pass (each block's kernel matrix is recomputed on the backward pass, so reverse mode keeps the forward pass's memory, and forward mode and Hessians work too), and weighted_adjoint returns the \(L^2\) one. operator() gives a lineax view for solves.

The kernel mean of Expectations is \(\mathcal{K}\) applied to the constant 1 under a probability measure. With an RBF of length 0.2 and a 32-node Gauss–Legendre rule on \([0, 1]\), IntegralOperator(kernel, rule, targets)(ones) matches kernel_mean(kernel, Box(0, 1), targets) to \(10^{-12}\), which the tests check.

convolution applies a translation-invariant kernel (one with is_translation_invariant = True) on a regular grid by FFT, with the sum stopping at the grid's edge ("constant") or wrapping around a periodic domain ("wrap"); any other kernel gets a dense IntegralOperator on the grid.

solve_second_kind solves the Fredholm equation of the second kind \(u - \lambda \mathcal{K} u = f\) by the quadrature method: collocated at the rule's nodes it is the \(N \times N\) system \((\mat{I} - \lambda \mat{K}\mat{W}) \vect{u} = \vect{f}\), solved matrix-free by GMRES, or, for a symmetric kernel, the symmetrised system \((\mat{I} - \lambda \mat{W}^{1/2} \mat{K} \mat{W}^{1/2}) \vect{z} = \mat{W}^{1/2} \vect{f}\), by CG only when the caller promises it is positive definite (it becomes indefinite, though still invertible, once \(\lambda\) passes \(1 / \rho(\mat{W}^{1/2} \mat{K} \mat{W}^{1/2})\)). The returned SecondKindSolution extends the nodal values to any point by the Nyström interpolant \(u(\vect{x}) = f(\vect{x}) + \lambda \sum_j k(\vect{x}, \vect{s}_j) w_j u_j\), which converges at the rule's order: on \(k = e^{-(x - s)^2}\), \(\lambda = \frac{1}{2}\), \(f = \cos \pi x\) the error is \(4 \times 10^{-5}\), \(5 \times 10^{-12}\) and \(2 \times 10^{-16}\) with 4, 8 and 16 Gauss–Legendre nodes, against \(4 \times 10^{-3}\), \(8 \times 10^{-4}\) and \(2 \times 10^{-4}\) for the trapezoid rule. Gradients in \(f\), \(\lambda\) and the kernel are implicit, through lineax; a failed solve raises ConvergenceError. The first-kind equation \(\mathcal{K} u = f\) is ill-posed and needs a regulariser, which is argminax's or vardax's.

VolterraOperator is the causal operator \((\mathcal{V} f)(t) = \int_{t_0}^{t} \alpha e^{-\beta (t - s)} f(s) \mathrm{d}s\). Its output solves \(\mathrm{d}y / \mathrm{d}t = -\beta y + \alpha f\), so it is a recursion with one state: each interval of width \(\Delta\) is integrated exactly for \(f\) linear on it, with the decay \(e^{-\beta \Delta}\) and end weights from \(\varphi_1(z) = (1 - e^{-z}) / z\) and \(\varphi_2(z) = (1 - e^{-z} - z e^{-z}) / z^2\) at \(z = \beta \Delta\), so irregular times need no Euler step. The steps \(y \mapsto a y + b\) are affine, so they compose by jax.lax.associative_scan, whose work is linear in the number of times and whose sums are pairwise; the decays are kept as exponents \(-\beta \Delta\) and summed, so float32 stays within a few \(10^{-7}\) of float64 over \(10^6\) times. Integer and boolean inputs (an event mask) take the floating dtype of the times and coefficients, and \(\beta\) must be non-negative. atoms applies it to point masses and returns the left limits \(\sum_{t_j < t_k} \alpha e^{-\beta (t_k - t_j)} m_j\); with unit masses at the events of a point process this is the excitation of an exponential Hawkes intensity \(\lambda(t) = \mu + \int_0^{t^-} \alpha e^{-\beta (t - s)} \mathrm{d}N(s)\). causal_quadrature is the dense \(O(T^2)\) fallback for a kernel with no recursive form: a running trapezoid integral of \(k(t_k, t_j) f_j\) over \(j \le k\) for each \(k\).

The operator lives in integrix rather than beside functax's kernel interpolation plans (geostack's open question GS-O1): it sums a kernel against a rule, and its relatives (the kernel means, Bayesian quadrature, and the Fredholm and Volterra operators that build on it) are here. The design is missing_operators.md in geostack.

operator

Integral operators: a kernel summed against a rule, applied without forming K.

IntegralOperator is (𝒦f)(xᵢ) ≈ ∑ⱼ k(xᵢ, sⱼ) wⱼ f(sⱼ) for any KernelLike kernel k and a functax rule (sⱼ, wⱼ), applied in blocks of targets, with its transpose adjoint, its L² weighted_adjoint and a lineax view. convolution applies a translation-invariant kernel on a regular grid by FFT. The kernel mean of integrix.expect is 𝒦 applied to the constant 1. solve_second_kind solves the Fredholm equation u − λ𝒦u = f by the quadrature method and returns a SecondKindSolution with its Nyström interpolant. VolterraOperator is the causal operator with an exponential kernel, (𝒱f)(t) = ∫ α e^(−β(t − s)) f(s) ds up to t, as a one-state scan, and causal_quadrature its dense fallback for any kernel.

SecondKindSolution

Bases: Module

The solution of u − λ𝒦u = f at a rule's nodes, and its Nyström interpolant.

u(x) = f(x) + λ ∑ⱼ k(x, sⱼ) wⱼ uⱼ

Attributes:

Name Type Description
operator IntegralOperator

𝒦 with its targets on the rule's nodes.

coupling Float[Array, '']

λ.

values Float[Array, ' node']

The solution uⱼ at the nodes.

rhs Callable[[Float[Array, ' dim']], Float[Array, '']]

f, mapping one point (D,) to a scalar.

Examples:

>>> import jax.numpy as jnp
>>> from functax.quad import gauss_legendre
>>> class Product:
...     def pairwise(self, x, s):
...         return jnp.sum(x * s)
>>> rule = gauss_legendre(8, (0.0, 1.0))
>>> solution = solve_second_kind(Product(), rule, lambda x: x[0], 1.0)
>>> points = jnp.array([[0.2], [0.9]])
>>> bool(jnp.allclose(solution.at(points), 1.5 * points[:, 0]))
True
at
at(points: Float[Array, 'point dim']) -> Float[Array, ' point']

The Nyström interpolant u(x) = f(x) + λ ∑ⱼ k(x, sⱼ) wⱼ uⱼ.

It equals the nodal solution at the nodes and converges at the rule's order everywhere else.

Parameters:

Name Type Description Default
points Float[Array, 'point dim']

The points x, one row each, in the nodes' dimension.

required

Returns:

Type Description
Float[Array, ' point']

u at the points.

Raises:

Type Description
ValidationError

If the points are not a matrix in the nodes' dimension.

Source code in src/integrix/_src/operator/_fredholm.py
def at(self, points: Float[Array, "point dim"]) -> Float[Array, " point"]:
    """The Nyström interpolant u(x) = f(x) + λ ∑ⱼ k(x, sⱼ) wⱼ uⱼ.

    It equals the nodal solution at the nodes and converges at the rule's
    order everywhere else.

    Args:
        points: The points x, one row each, in the nodes' dimension.

    Returns:
        u at the points.

    Raises:
        ValidationError: If the points are not a matrix in the nodes'
            dimension.
    """
    interpolate = IntegralOperator(
        self.operator.kernel,
        self.operator.rule,
        points,
        chunk=self.operator.chunk,
    )
    forcing = jax.vmap(self.rhs)(interpolate.targets)
    return forcing + self.coupling * interpolate(self.values)

IntegralOperator

Bases: Module

The discretised integral operator, applied without forming K.

(𝒦f)(xᵢ) ≈ ∑ⱼ k(xᵢ, sⱼ) wⱼ f(sⱼ),    i = 1, …, M,  j = 1, …, N

The kernel k comes through integrix's KernelLike protocol, the nodes sⱼ and weights wⱼ from a rule (functax's Rule), and the targets xᵢ are any M points. A rule whose weights keep a grid's shape is read in row-major order, so values carry one flat axis of N entries.

Algorithm
  1. Low-rank path, when the kernel has features(x) returning φ(x) of shape (P, R): (𝒦f)(x) = φ(x)ᵀ (Φ_sᵀ (w ⊙ f)).
  2. Otherwise map over blocks of chunk targets with jax.lax.map, evaluate k(xᵢ, sⱼ) for the block and contract it with w ⊙ f over the nodes, so memory is O(chunk × N), never O(M × N).

Each block's kernel matrix is recomputed rather than stored (jax.checkpoint), so reverse mode keeps the forward pass's memory: the derivative in the values is the blocked transpose, adjoint, and the kernel's parameters, the targets and the rule are differentiated through the same recomputed blocks. Forward mode (jax.jvp, jax.jacfwd) and Hessians work as for any JAX function. The result takes the values' floating dtype (the rule and the kernel are cast to it).

Attributes:

Name Type Description
kernel KernelLike

k, any KernelLike (pairwise(x, x′) at one pair of points).

rule RuleLike

The nodes sⱼ and weights wⱼ.

targets Float[Array, 'target dim']

The target points xᵢ, one row each.

chunk int

Targets per block on the dense path.

Raises:

Type Description
ValidationError

If the targets are not a matrix, their dimension differs from the nodes', or chunk is not positive.

Examples:

𝒦 applied to the constant 1 under the uniform measure on [0, 1] is the kernel mean, ∫₀¹ k(x, s) ds:

>>> import jax.numpy as jnp
>>> from functax.quad import gauss_legendre
>>> from jax.scipy.special import erf
>>> class RBF:
...     def pairwise(self, x, x_prime):
...         return jnp.exp(-0.5 * jnp.sum((x - x_prime) ** 2) / 0.2**2)
>>> targets = jnp.linspace(0.0, 1.0, 5)[:, None]
>>> op = IntegralOperator(RBF(), gauss_legendre(32, (0.0, 1.0)), targets)
>>> scale = 0.2 * jnp.sqrt(2.0)
>>> exact = (
...     0.2
...     * jnp.sqrt(jnp.pi / 2)
...     * (erf((1 - targets[:, 0]) / scale) + erf(targets[:, 0] / scale))
... )
>>> bool(jnp.allclose(op(jnp.ones(32)), exact, atol=1e-12))
True

Leading axes of the values are batch axes:

>>> op(jnp.ones((3, 32))).shape
(3, 5)
num_nodes property
num_nodes: int

N, the number of nodes of the rule.

adjoint
adjoint(residual: Float[Array, '*batch target']) -> Float[Array, '*batch node']

The transpose (K W)ᵀ r: gⱼ = wⱼ ∑ᵢ k(xᵢ, sⱼ) rᵢ.

This is the Euclidean adjoint, ⟨𝒦f, r⟩ = ⟨f, 𝒦ᵀr⟩ with plain dot products on both sides, and the reverse-mode derivative of __call__ in the values.

Parameters:

Name Type Description Default
residual Float[Array, '*batch target']

The residual rᵢ at the targets.

required

Returns:

Type Description
Float[Array, '*batch node']

The adjoint gⱼ at the nodes.

Raises:

Type Description
ValidationError

If the residual does not have M entries along its last axis.

Source code in src/integrix/_src/operator/_integral.py
def adjoint(
    self, residual: Float[Array, "*batch target"]
) -> Float[Array, "*batch node"]:
    """The transpose (K W)ᵀ r: gⱼ = wⱼ ∑ᵢ k(xᵢ, sⱼ) rᵢ.

    This is the Euclidean adjoint, ⟨𝒦f, r⟩ = ⟨f, 𝒦ᵀr⟩ with plain dot
    products on both sides, and the reverse-mode derivative of
    ``__call__`` in the values.

    Args:
        residual: The residual rᵢ at the targets.

    Returns:
        The adjoint gⱼ at the nodes.

    Raises:
        ValidationError: If the residual does not have M entries along its
            last axis.
    """
    residual = jnp.asarray(residual)
    self._check_last_axis(residual, "residual", self.targets.shape[0])
    _, weights = _rule_arrays(self.rule)
    kernel_sum = _transpose_sum(self, residual)
    weights = weights.astype(kernel_sum.dtype)
    return einx.multiply("... node, node -> ... node", kernel_sum, weights)
weighted_adjoint
weighted_adjoint(residual: Float[Array, '*batch target'], target_weights: Float[Array, ' target']) -> Float[Array, '*batch node']

The L² adjoint on a target rule: gⱼ = ∑ᵢ k(xᵢ, sⱼ) vᵢ rᵢ.

With weights vᵢ on the targets, ⟨𝒦f, r⟩_v = ∑ᵢ vᵢ rᵢ (𝒦f)ᵢ equals ⟨f, g⟩_w = ∑ⱼ wⱼ fⱼ gⱼ: the operator with the transposed kernel k*(s, x) = k(x, s), integrated against the target rule. In matrix form it is W⁻¹ (K W)ᵀ V.

Parameters:

Name Type Description Default
residual Float[Array, '*batch target']

The residual rᵢ at the targets.

required
target_weights Float[Array, ' target']

The weights vᵢ of a rule on the targets.

required

Returns:

Type Description
Float[Array, '*batch node']

The L² adjoint gⱼ at the nodes.

Raises:

Type Description
ValidationError

If the residual or the target weights do not have M entries along their last axis.

Source code in src/integrix/_src/operator/_integral.py
def weighted_adjoint(
    self,
    residual: Float[Array, "*batch target"],
    target_weights: Float[Array, " target"],
) -> Float[Array, "*batch node"]:
    """The L² adjoint on a target rule: gⱼ = ∑ᵢ k(xᵢ, sⱼ) vᵢ rᵢ.

    With weights vᵢ on the targets, ⟨𝒦f, r⟩_v = ∑ᵢ vᵢ rᵢ (𝒦f)ᵢ equals
    ⟨f, g⟩_w = ∑ⱼ wⱼ fⱼ gⱼ: the operator with the transposed kernel
    k*(s, x) = k(x, s), integrated against the target rule. In matrix
    form it is W⁻¹ (K W)ᵀ V.

    Args:
        residual: The residual rᵢ at the targets.
        target_weights: The weights vᵢ of a rule on the targets.

    Returns:
        The L² adjoint gⱼ at the nodes.

    Raises:
        ValidationError: If the residual or the target weights do not have
            M entries along their last axis.
    """
    residual = jnp.asarray(residual)
    target_weights = jnp.asarray(target_weights)
    num_targets = self.targets.shape[0]
    self._check_last_axis(residual, "residual", num_targets)
    if target_weights.shape != (num_targets,):
        raise ValidationError(
            f"'target_weights' must have shape ({num_targets},), got "
            f"{target_weights.shape}"
        )
    weighted = einx.multiply(
        "... target, target -> ... target", residual, target_weights
    )
    return _transpose_sum(self, weighted)
operator
operator() -> FunctionLinearOperator

𝒦 as a lineax operator from the N node values to the M targets.

Its mv is __call__ without the shape check; lineax transposes it and differentiates a solve through it.

Returns:

Type Description
FunctionLinearOperator

The operator, on vectors of the rule's dtype.

Source code in src/integrix/_src/operator/_integral.py
def operator(self) -> lx.FunctionLinearOperator:
    """𝒦 as a lineax operator from the N node values to the M targets.

    Its ``mv`` is ``__call__`` without the shape check; lineax transposes
    it and differentiates a solve through it.

    Returns:
        The operator, on vectors of the rule's dtype.
    """
    _, weights = _rule_arrays(self.rule)
    structure = jax.ShapeDtypeStruct((self.num_nodes,), weights.dtype)
    return lx.FunctionLinearOperator(self._plain_apply, structure)

VolterraOperator

Bases: Module

The causal integral operator with an exponential kernel, as a one-state scan.

(𝒱f)(t) = ∫_{t₀}^t α e^(−β(t − s)) f(s) ds,    dy/dt = −β y + α f

Each interval carries y with the exact solution of the ODE over it, so the times may be irregular and there is no Euler step; the steps are affine, y ↦ a y + b, and compose by an associative scan whose work is linear in the number of times T and whose sums are pairwise.

Algorithm
  1. For each interval [tₖ₋₁, tₖ] of width Δ, z = βΔ: the decay e⁻ᶻ and the end weights Δ φ₂(z), Δ (φ₁(z) − φ₂(z)) of the samples, exact when f is linear on the interval.
  2. Compose yₖ = e⁻ᶻ yₖ₋₁ + α (Δ φ₂ fₖ₋₁ + Δ (φ₁ − φ₂) fₖ) from y₀ = 0 with jax.lax.associative_scan.

Attributes:

Name Type Description
scale Float[Array, '']

α.

decay Float[Array, '']

β, non-negative.

Raises:

Type Description
ValidationError

If α or β is not a scalar, or β is negative (checked here when concrete, and under jax.jit by equinox.error_if).

Examples:

With β = 0 the operator is α times the running trapezoid integral:

>>> import jax.numpy as jnp
>>> times = jnp.array([0.0, 0.5, 2.0])
>>> flat = VolterraOperator(2.0, 0.0)
>>> bool(jnp.allclose(flat(times, jnp.ones(3)), 2.0 * times))
True

A constant input relaxes to α/β:

>>> relax = VolterraOperator(3.0, 1.5)
>>> late = relax(jnp.array([0.0, 40.0]), jnp.ones(2))
>>> bool(jnp.allclose(late[-1], 2.0))
True
atoms
atoms(times: Float[Array, ' time'], masses: Shaped[Array, '*batch time']) -> Float[Array, '*batch time']

Apply 𝒱 to point masses, just before each time.

(𝒱μ)(tₖ⁻) = ∑_{j<k} α e^(−β(tₖ − tⱼ)) mⱼ,    μ = ∑ⱼ mⱼ δ_{tⱼ}

With unit masses at the events of a point process this is the excitation of an exponential Hawkes intensity, λ(t) = μ₀ + (𝒱N)(t⁻). Times without an event carry a zero mass, so the intensity can be read anywhere by merging those times in.

Parameters:

Name Type Description Default
times Float[Array, ' time']

The times tⱼ, ascending.

required
masses Shaped[Array, '*batch time']

The masses mⱼ at them (a boolean event mask works).

required

Returns:

Type Description
Float[Array, '*batch time']

The left limits (𝒱μ)(tₖ⁻); the mass at tₖ itself is not included,

Float[Array, '*batch time']

and equal times count in index order. The dtype is the masses'

Float[Array, '*batch time']

floating dtype, or that of the times and coefficients.

Raises:

Type Description
ValidationError

If the times are not a non-empty vector or the masses do not have one entry per time along their last axis.

Source code in src/integrix/_src/operator/_volterra.py
def atoms(
    self, times: Float[Array, " time"], masses: Shaped[Array, "*batch time"]
) -> Float[Array, "*batch time"]:
    """Apply 𝒱 to point masses, just before each time.

        (𝒱μ)(tₖ⁻) = ∑_{j<k} α e^(−β(tₖ − tⱼ)) mⱼ,    μ = ∑ⱼ mⱼ δ_{tⱼ}

    With unit masses at the events of a point process this is the
    excitation of an exponential Hawkes intensity, λ(t) = μ₀ + (𝒱N)(t⁻).
    Times without an event carry a zero mass, so the intensity can be read
    anywhere by merging those times in.

    Args:
        times: The times tⱼ, ascending.
        masses: The masses mⱼ at them (a boolean event mask works).

    Returns:
        The left limits (𝒱μ)(tₖ⁻); the mass at tₖ itself is not included,
        and equal times count in index order. The dtype is the masses'
        floating dtype, or that of the times and coefficients.

    Raises:
        ValidationError: If the times are not a non-empty vector or the
            masses do not have one entry per time along their last axis.
    """
    times = jnp.asarray(times)
    masses = jnp.asarray(masses)
    _check_series(times, masses, "masses")
    dtype = self._dtype(times, masses)
    widths = (times[1:] - times[:-1]).astype(dtype)
    decay = _checked_decay(self.decay).astype(dtype)
    exponents = -decay * widths
    decayed = jnp.exp(exponents)
    weights = einx.id("... time -> time ...", masses.astype(dtype))
    # bₖ = e^(−β(tₖ − tₖ₋₁)) α mₖ₋₁
    scaled = self.scale.astype(dtype) * weights[:-1]
    increments = _scale_rows(decayed, scaled)
    # yₖ = e^(−β(tₖ − tₖ₋₁)) yₖ₋₁ + bₖ from y₀ = 0
    states = _affine_prefix(exponents, increments)
    return einx.id("time ... -> ... time", states)

solve_second_kind

solve_second_kind(kernel: KernelLike, rule: RuleLike, rhs: Callable[[Float[Array, ' dim']], Float[Array, '']], coupling: float | Float[Array, ''], *, solver: AbstractLinearSolver | None = None, symmetric: bool = False, positive_definite: bool = False) -> SecondKindSolution

Solve u − λ𝒦u = f by the quadrature method; .at(x) is the Nyström interpolant.

uᵢ − λ ∑ⱼ k(sᵢ, sⱼ) wⱼ uⱼ = f(sᵢ),    i = 1, …, N

By the Fredholm alternative a unique solution exists for every f unless 1/λ is an eigenvalue of 𝒦, and with a Gauss rule and a smooth kernel the quadrature method converges at the rule's (spectral) order.

A symmetric kernel makes the symmetrised system symmetric but not definite: once λ passes 1/ρ(W^(1/2) K W^(1/2)) it is indefinite yet invertible, and CG can break down on it. CG is therefore chosen only on the caller's promise of definiteness, which holds for a positive semi-definite kernel when λ ≤ 0 or λ < 1/ρ(W^(1/2) K W^(1/2)).

Algorithm
  1. Build 𝒦 with targets on the nodes (IntegralOperator).
  2. Form I − λKW, or I − λW^(1/2) K W^(1/2) when symmetric (the weights must then be positive), as a matrix-free lineax operator.
  3. Solve with CG when positive_definite (which requires symmetric), otherwise GMRES, both to 1000 ε of the dtype; gradients in f, λ and the kernel's arrays are implicit, through lineax.linear_solve.

Parameters:

Name Type Description Default
kernel KernelLike

k, any KernelLike.

required
rule RuleLike

The nodes sⱼ and weights wⱼ (functax's Rule).

required
rhs Callable[[Float[Array, ' dim']], Float[Array, '']]

f, mapping one point (D,) to a scalar.

required
coupling float | Float[Array, '']

λ.

required
solver AbstractLinearSolver | None

A lineax solver to use in place of the default.

None
symmetric bool

The kernel is symmetric, k(x, s) = k(s, x), so the symmetrised system is solved.

False
positive_definite bool

The symmetrised system I − λW^(1/2) K W^(1/2) is positive definite, so CG applies.

False

Returns:

Type Description
SecondKindSolution

The solution at the nodes, with its interpolant.

Raises:

Type Description
ValidationError

If positive_definite is set without symmetric (also a ValueError).

ConvergenceError

If the solve fails (a breakdown, stagnation or the step limit), when the arrays are concrete; under jax.jit the same failure raises through equinox.error_if.

Examples:

The rank-one kernel x s with λ = 1 and f = x has u = 1.5 x:

>>> import jax.numpy as jnp
>>> from functax.quad import gauss_legendre
>>> class Product:
...     def pairwise(self, x, s):
...         return jnp.sum(x * s)
>>> rule = gauss_legendre(8, (0.0, 1.0))
>>> solution = solve_second_kind(Product(), rule, lambda x: x[0], 1.0)
>>> nodes = jnp.asarray(rule.nodes)
>>> bool(jnp.allclose(solution.values, 1.5 * nodes, atol=1e-15))
True

A symmetric positive kernel with a small λ takes CG:

>>> class Gaussian:
...     def pairwise(self, x, s):
...         return jnp.exp(-jnp.sum((x - s) ** 2))
>>> cosine = lambda x: jnp.cos(jnp.pi * x[0])
>>> definite = solve_second_kind(
...     Gaussian(),
...     rule,
...     cosine,
...     0.5,
...     symmetric=True,
...     positive_definite=True,
... )
>>> general = solve_second_kind(Gaussian(), rule, cosine, 0.5)
>>> bool(jnp.allclose(definite.values, general.values, atol=1e-12))
True
Source code in src/integrix/_src/operator/_fredholm.py
def solve_second_kind(
    kernel: KernelLike,
    rule: RuleLike,
    rhs: Callable[[Float[Array, " dim"]], Float[Array, ""]],
    coupling: float | Float[Array, ""],
    *,
    solver: lx.AbstractLinearSolver | None = None,
    symmetric: bool = False,
    positive_definite: bool = False,
) -> SecondKindSolution:
    """Solve u − λ𝒦u = f by the quadrature method; `.at(x)` is the Nyström interpolant.

        uᵢ − λ ∑ⱼ k(sᵢ, sⱼ) wⱼ uⱼ = f(sᵢ),    i = 1, …, N

    By the Fredholm alternative a unique solution exists for every f unless
    1/λ is an eigenvalue of 𝒦, and with a Gauss rule and a smooth kernel the
    quadrature method converges at the rule's (spectral) order.

    A symmetric kernel makes the symmetrised system symmetric but not
    definite: once λ passes 1/ρ(W^(1/2) K W^(1/2)) it is indefinite yet
    invertible, and CG can break down on it. CG is therefore chosen only on
    the caller's promise of definiteness, which holds for a positive
    semi-definite kernel when λ ≤ 0 or λ < 1/ρ(W^(1/2) K W^(1/2)).

    Algorithm:
        1. Build 𝒦 with targets on the nodes (`IntegralOperator`).
        2. Form I − λKW, or I − λW^(1/2) K W^(1/2) when ``symmetric`` (the
           weights must then be positive), as a matrix-free lineax operator.
        3. Solve with CG when ``positive_definite`` (which requires
           ``symmetric``), otherwise GMRES, both to 1000 ε of the dtype;
           gradients in f, λ and the kernel's arrays are implicit, through
           `lineax.linear_solve`.

    Args:
        kernel: k, any `KernelLike`.
        rule: The nodes sⱼ and weights wⱼ (functax's ``Rule``).
        rhs: f, mapping one point (D,) to a scalar.
        coupling: λ.
        solver: A lineax solver to use in place of the default.
        symmetric: The kernel is symmetric, k(x, s) = k(s, x), so the
            symmetrised system is solved.
        positive_definite: The symmetrised system I − λW^(1/2) K W^(1/2) is
            positive definite, so CG applies.

    Returns:
        The solution at the nodes, with its interpolant.

    Raises:
        ValidationError: If ``positive_definite`` is set without
            ``symmetric`` (also a `ValueError`).
        ConvergenceError: If the solve fails (a breakdown, stagnation or the
            step limit), when the arrays are concrete; under `jax.jit` the
            same failure raises through `equinox.error_if`.

    Examples:
        The rank-one kernel x s with λ = 1 and f = x has u = 1.5 x:

        >>> import jax.numpy as jnp
        >>> from functax.quad import gauss_legendre
        >>> class Product:
        ...     def pairwise(self, x, s):
        ...         return jnp.sum(x * s)
        >>> rule = gauss_legendre(8, (0.0, 1.0))
        >>> solution = solve_second_kind(Product(), rule, lambda x: x[0], 1.0)
        >>> nodes = jnp.asarray(rule.nodes)
        >>> bool(jnp.allclose(solution.values, 1.5 * nodes, atol=1e-15))
        True

        A symmetric positive kernel with a small λ takes CG:

        >>> class Gaussian:
        ...     def pairwise(self, x, s):
        ...         return jnp.exp(-jnp.sum((x - s) ** 2))
        >>> cosine = lambda x: jnp.cos(jnp.pi * x[0])
        >>> definite = solve_second_kind(
        ...     Gaussian(),
        ...     rule,
        ...     cosine,
        ...     0.5,
        ...     symmetric=True,
        ...     positive_definite=True,
        ... )
        >>> general = solve_second_kind(Gaussian(), rule, cosine, 0.5)
        >>> bool(jnp.allclose(definite.values, general.values, atol=1e-12))
        True
    """
    if positive_definite and not symmetric:
        raise ValidationError(
            "'positive_definite' needs 'symmetric': CG applies only to the "
            "symmetrised system I - λ W^(1/2) K W^(1/2)"
        )
    nodes, weights = _rule_arrays(rule)
    coupling = jnp.asarray(coupling)
    operator = IntegralOperator(kernel, rule, nodes)
    kernel_operator = operator.operator()
    structure = kernel_operator.in_structure()
    forcing = jax.vmap(rhs)(nodes)
    root_weights = jnp.sqrt(weights)

    if symmetric:
        if not isinstance(weights, Tracer) and bool(jnp.any(weights <= 0)):
            raise ValidationError("'symmetric' needs a rule with positive weights")

        # z ↦ z − λ W^(1/2) K W^(1/2) z, with K W^(1/2) z = (K W)(W^(−1/2) z)
        def matvec(scaled: Float[Array, " node"]) -> Float[Array, " node"]:
            unscaled = einx.divide("node, node -> node", scaled, root_weights)
            applied = kernel_operator.mv(unscaled)
            return scaled - coupling * einx.multiply(
                "node, node -> node", root_weights, applied
            )

        tags = [lx.symmetric_tag]
        if positive_definite:
            tags.append(lx.positive_semidefinite_tag)
        system = lx.FunctionLinearOperator(matvec, structure, tags=tags)
        vector = einx.multiply("node, node -> node", root_weights, forcing)
    else:
        # u ↦ u − λ K W u
        def matvec(values: Float[Array, " node"]) -> Float[Array, " node"]:
            return values - coupling * kernel_operator.mv(values)

        system = lx.FunctionLinearOperator(matvec, structure)
        vector = forcing

    if solver is None:
        solver = _default_solver(vector.dtype, positive_definite=positive_definite)
    solution = lx.linear_solve(system, vector, solver, throw=False)
    failed = solution.result != lx.RESULTS.successful
    if isinstance(failed, Tracer):
        unknowns = eqx.error_if(
            solution.value,
            failed,
            f"the second-kind solve with {type(solver).__name__} did not converge",
        )
    elif bool(failed):
        raise ConvergenceError(
            f"the second-kind solve with {type(solver).__name__} did not converge "
            f"({solution.result})"
        )
    else:
        unknowns = solution.value
    if symmetric:
        # u = W^(−1/2) z
        unknowns = einx.divide("node, node -> node", unknowns, root_weights)
    return SecondKindSolution(operator, coupling, unknowns, rhs)

convolution

convolution(kernel: KernelLike, grid: RuleLike, *, boundary: str = 'constant') -> IntegralOperator | FunctionLinearOperator

𝒦 on a regular grid by FFT, for a translation-invariant kernel.

(𝒦f)(xᵢ) ≈ ∑ⱼ k(xᵢ − sⱼ, 0) wⱼ fⱼ,    xᵢ, sⱼ on the grid

With targets on the grid's own nodes, a kernel that depends only on x − s makes 𝒦 a discrete convolution of k with w ⊙ f, which an FFT applies in O(N log N). A kernel declares this with the attribute is_translation_invariant = True; any other kernel falls back to a dense IntegralOperator on the grid's nodes.

Algorithm
  1. Read the grid shape (n₁, …, n_D) from the rule's weights and the spacing hₐ from its nodes.
  2. Evaluate k(Δ, 0) at the offsets Δ = o h: o ∈ {−(nₐ − 1), …, nₐ − 1} per axis for "constant" (zero outside the grid), or the minimum image of o ∈ {0, …, nₐ − 1} on the period nₐ hₐ for "wrap".
  3. Multiply the FFTs of the taps and of w ⊙ f, zero-padded to a linear convolution for "constant" and circular for "wrap", and keep the grid's own nodes.

Parameters:

Name Type Description Default
kernel KernelLike

k, any KernelLike.

required
grid RuleLike

A rule on a regular, axis-aligned grid: weights in the grid's shape (n₁, …, n_D) and nodes of shape (n₁, …, n_D, D), or of shape (n,) on a 1-D grid.

required
boundary str

"constant" (the sum stops at the grid's edge) or "wrap" (the grid is one period of a periodic domain).

'constant'

Returns:

Type Description
IntegralOperator | FunctionLinearOperator

A lineax operator on arrays of the grid's shape, or, for a kernel

IntegralOperator | FunctionLinearOperator

that is not translation invariant, an IntegralOperator from the

IntegralOperator | FunctionLinearOperator

flattened grid to itself.

Raises:

Type Description
ValidationError

If boundary is unknown, the grid is not regular, or a kernel without translation invariance is asked to wrap.

Examples:

The FFT path matches the dense operator on the grid:

>>> import jax.numpy as jnp
>>> from functax.quad import trapezoid
>>> class Gaussian:
...     is_translation_invariant = True
...
...     def pairwise(self, x, x_prime):
...         return jnp.exp(-0.5 * jnp.sum((x - x_prime) ** 2) / 0.1**2)
>>> grid = trapezoid(jnp.linspace(0.0, 1.0, 9))
>>> fft = convolution(Gaussian(), grid)
>>> dense = IntegralOperator(Gaussian(), grid, grid.nodes[:, None])
>>> values = jnp.cos(grid.nodes)
>>> bool(jnp.allclose(fft.mv(values), dense(values), atol=1e-12))
True

A kernel without the attribute gets the dense operator:

>>> class Plain:
...     def pairwise(self, x, x_prime):
...         return jnp.sum(x * x_prime)
>>> type(convolution(Plain(), grid)).__name__
'IntegralOperator'
Source code in src/integrix/_src/operator/_integral.py
def convolution(
    kernel: KernelLike, grid: RuleLike, *, boundary: str = "constant"
) -> IntegralOperator | lx.FunctionLinearOperator:
    """𝒦 on a regular grid by FFT, for a translation-invariant kernel.

        (𝒦f)(xᵢ) ≈ ∑ⱼ k(xᵢ − sⱼ, 0) wⱼ fⱼ,    xᵢ, sⱼ on the grid

    With targets on the grid's own nodes, a kernel that depends only on
    x − s makes 𝒦 a discrete convolution of k with w ⊙ f, which an FFT
    applies in O(N log N). A kernel declares this with the attribute
    ``is_translation_invariant = True``; any other kernel falls back to a
    dense `IntegralOperator` on the grid's nodes.

    Algorithm:
        1. Read the grid shape (n₁, …, n_D) from the rule's weights and the
           spacing hₐ from its nodes.
        2. Evaluate k(Δ, 0) at the offsets Δ = o h: o ∈ {−(nₐ − 1), …, nₐ − 1}
           per axis for ``"constant"`` (zero outside the grid), or the
           minimum image of o ∈ {0, …, nₐ − 1} on the period nₐ hₐ for
           ``"wrap"``.
        3. Multiply the FFTs of the taps and of w ⊙ f, zero-padded to a
           linear convolution for ``"constant"`` and circular for ``"wrap"``,
           and keep the grid's own nodes.

    Args:
        kernel: k, any `KernelLike`.
        grid: A rule on a regular, axis-aligned grid: weights in the grid's
            shape (n₁, …, n_D) and nodes of shape (n₁, …, n_D, D), or of
            shape (n,) on a 1-D grid.
        boundary: ``"constant"`` (the sum stops at the grid's edge) or
            ``"wrap"`` (the grid is one period of a periodic domain).

    Returns:
        A lineax operator on arrays of the grid's shape, or, for a kernel
        that is not translation invariant, an `IntegralOperator` from the
        flattened grid to itself.

    Raises:
        ValidationError: If ``boundary`` is unknown, the grid is not regular,
            or a kernel without translation invariance is asked to wrap.

    Examples:
        The FFT path matches the dense operator on the grid:

        >>> import jax.numpy as jnp
        >>> from functax.quad import trapezoid
        >>> class Gaussian:
        ...     is_translation_invariant = True
        ...
        ...     def pairwise(self, x, x_prime):
        ...         return jnp.exp(-0.5 * jnp.sum((x - x_prime) ** 2) / 0.1**2)
        >>> grid = trapezoid(jnp.linspace(0.0, 1.0, 9))
        >>> fft = convolution(Gaussian(), grid)
        >>> dense = IntegralOperator(Gaussian(), grid, grid.nodes[:, None])
        >>> values = jnp.cos(grid.nodes)
        >>> bool(jnp.allclose(fft.mv(values), dense(values), atol=1e-12))
        True

        A kernel without the attribute gets the dense operator:

        >>> class Plain:
        ...     def pairwise(self, x, x_prime):
        ...         return jnp.sum(x * x_prime)
        >>> type(convolution(Plain(), grid)).__name__
        'IntegralOperator'
    """
    if boundary not in _BOUNDARIES:
        raise ValidationError(
            f"'boundary' must be one of {_BOUNDARIES}, got {boundary!r}"
        )
    weights = jnp.asarray(grid.weights)
    flat_nodes, _ = _rule_arrays(grid)
    grid_shape = tuple(weights.shape)
    rank = len(grid_shape)
    if not getattr(kernel, "is_translation_invariant", False):
        if boundary != "constant":
            raise ValidationError(
                f"boundary={boundary!r} needs a translation-invariant kernel; "
                "a general kernel only has the 'constant' boundary"
            )
        return IntegralOperator(kernel, grid, flat_nodes)
    if flat_nodes.shape[1] != rank:
        raise ValidationError(
            f"'grid' nodes must have one coordinate per grid axis ({rank}), got "
            f"{flat_nodes.shape[1]}"
        )
    grid_nodes = jnp.reshape(flat_nodes, (*grid_shape, rank))
    spacing = _grid_spacing(grid_nodes, grid_shape)

    # --- the taps k(Δ, 0) at every offset the sum needs ---
    if boundary == "constant":
        offset_axes = [jnp.arange(-(n - 1), n) for n in grid_shape]
        fft_shape = tuple(3 * n - 2 for n in grid_shape)
    else:
        offset_axes = [jnp.arange(n) - n * (jnp.arange(n) > n // 2) for n in grid_shape]
        fft_shape = grid_shape
    offsets = jnp.stack(jnp.meshgrid(*offset_axes, indexing="ij"), -1)
    names = " ".join(f"g{axis}" for axis in range(rank))
    flat_offsets = einx.id(f"{names} d -> ({names}) d", offsets)
    # Δ = o ⊙ h
    displacements = einx.multiply("point d, d -> point d", flat_offsets, spacing)
    origin = jnp.zeros((1, rank), dtype=displacements.dtype)
    flat_taps = einx.id("point 1 -> point", _gram(kernel, displacements, origin))
    taps = jnp.reshape(flat_taps, offsets.shape[:-1])
    axes = tuple(range(rank))
    taps_spectrum = jnp.fft.rfftn(taps, s=fft_shape, axes=axes)

    def apply(values: Float[Array, "*grid"]) -> Float[Array, "*grid"]:
        dtype = working_dtype(values.dtype, as_inexact(weights).dtype)
        # gⱼ = wⱼ fⱼ, in the values' dtype
        weighted = values.astype(dtype) * weights.astype(dtype)
        weighted_spectrum = jnp.fft.rfftn(weighted, s=fft_shape, axes=axes)
        kernel_spectrum = taps_spectrum.astype(weighted_spectrum.dtype)
        spectrum = weighted_spectrum * kernel_spectrum
        full = jnp.fft.irfftn(spectrum, s=fft_shape, axes=axes)
        if boundary == "wrap":
            return full
        # output i reads the full linear convolution at i + (n − 1)
        window = tuple(slice(n - 1, 2 * n - 1) for n in grid_shape)
        return full[window]

    structure = jax.ShapeDtypeStruct(grid_shape, weights.dtype)
    return lx.FunctionLinearOperator(apply, structure)

causal_quadrature

causal_quadrature(kernel: KernelLike, times: Float[Array, ' time'], values: Float[Array, '*batch time']) -> Float[Array, '*batch time']

(𝒱f)(tₖ) = ∫_{t₀}^{tₖ} k(tₖ, s) f(s) ds for any kernel, by the trapezoid rule.

The dense fallback of VolterraOperator for a kernel with no recursive form: each output is a running trapezoid integral of k(tₖ, tⱼ) fⱼ over j ≤ k, so time and memory are O(T²).

Parameters:

Name Type Description Default
kernel KernelLike

k, any KernelLike; times enter it as points of one coordinate.

required
times Float[Array, ' time']

The times tₖ, ascending.

required
values Float[Array, '*batch time']

The samples fₖ = f(tₖ).

required

Returns:

Type Description
Float[Array, '*batch time']

(𝒱f)(tₖ), zero at t₀.

Raises:

Type Description
ValidationError

If the times are not a non-empty vector or the values do not have one entry per time along their last axis.

Examples:

The exponential kernel agrees with the scan to the trapezoid's order:

>>> import jax.numpy as jnp
>>> class Exponential:
...     def pairwise(self, t, s):
...         return 2.0 * jnp.exp(-0.5 * jnp.sum(t - s))
>>> times = jnp.linspace(0.0, 3.0, 301)
>>> values = jnp.sin(times)
>>> dense = causal_quadrature(Exponential(), times, values)
>>> scan = VolterraOperator(2.0, 0.5)(times, values)
>>> bool(jnp.allclose(dense, scan, atol=1e-4))
True
Source code in src/integrix/_src/operator/_volterra.py
def causal_quadrature(
    kernel: KernelLike,
    times: Float[Array, " time"],
    values: Float[Array, "*batch time"],
) -> Float[Array, "*batch time"]:
    """(𝒱f)(tₖ) = ∫_{t₀}^{tₖ} k(tₖ, s) f(s) ds for any kernel, by the trapezoid rule.

    The dense fallback of `VolterraOperator` for a kernel with no recursive
    form: each output is a running trapezoid integral of k(tₖ, tⱼ) fⱼ over
    j ≤ k, so time and memory are O(T²).

    Args:
        kernel: k, any `KernelLike`; times enter it as points of one
            coordinate.
        times: The times tₖ, ascending.
        values: The samples fₖ = f(tₖ).

    Returns:
        (𝒱f)(tₖ), zero at t₀.

    Raises:
        ValidationError: If the times are not a non-empty vector or the values
            do not have one entry per time along their last axis.

    Examples:
        The exponential kernel agrees with the scan to the trapezoid's order:

        >>> import jax.numpy as jnp
        >>> class Exponential:
        ...     def pairwise(self, t, s):
        ...         return 2.0 * jnp.exp(-0.5 * jnp.sum(t - s))
        >>> times = jnp.linspace(0.0, 3.0, 301)
        >>> values = jnp.sin(times)
        >>> dense = causal_quadrature(Exponential(), times, values)
        >>> scan = VolterraOperator(2.0, 0.5)(times, values)
        >>> bool(jnp.allclose(dense, scan, atol=1e-4))
        True
    """
    times = jnp.asarray(times)
    values = jnp.asarray(values)
    _check_series(times, values, "values")
    points = einx.id("time -> time 1", times)
    # Kₖⱼ = k(tₖ, tⱼ)
    gram = _gram(kernel, points, points)
    integrand = einx.multiply("row col, ... col -> ... row col", gram, values)
    running = cumulative(trapezoid(times), integrand)
    return jnp.diagonal(running, axis1=-2, axis2=-1)