Skip to content

Expectations

An expectation is an integral over a probability space, \(\mathbb{E}[f] = \int f(x) p(x) \mathrm{d}x\), and each estimator here returns it with a standard error. monte_carlo averages draws \(x_s \sim p\), given (a NumPyro posterior, say) or drawn from a sampler, with \(\hat\sigma / \sqrt{S}\). qmc averages over \(R\) randomly shifted copies of a Sobol (Joe–Kuo) or Halton point set, and takes its error from the spread of the shifted estimates. On a smooth integrand that error falls faster than \(S^{-1/2}\). importance reweights draws from a proposal \(q\) by \(w_s = p(x_s) / q(x_s)\), self-normalised, so \(p\) is needed only up to a constant. It reports the effective sample size \((\sum_s w_s)^2 / \sum_s w_s^2\), because heavy-tailed weights make the estimate unreliable long before its standard error looks large.

integrix averages and resamples an empirical measure; sampling from a posterior stays in NumPyro and pyrox.

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

For integrands that underflow, two conveniences return log-integrals through integrix.rule.log_integrate. log_gauss_hermite computes \(\log \mathbb{E}[f(Q)]\) for a lognormal \(Q\) by Gauss–Hermite quadrature in \(\log Q\), and log_simpson computes \(\log \int_a^b f(q) \mathrm{d}q\) by Simpson's rule on a uniform grid in \(\log q\), which resolves a lognormal body and a power-law tail alike.

Two diagnostics check importance weights. effective_sample_size is \((\sum_s w_s)^2 / \sum_s w_s^2\), computed from \(\log w_s\) so no weight is exponentiated. pareto_smoothed_log_weights replaces the largest weights by the quantiles of a generalised Pareto distribution fitted to their tail (Vehtari et al.'s Pareto-smoothed importance sampling) and returns the tail shape \(\hat{k}\), where \(\hat{k} > 0.7\) means the importance estimate should not be trusted. Both are written in JAX and batch over leading axes, and importance(..., diagnostics=True) reports \(\hat{k}\) as pareto_k.

Five functions resample a weighted cloud into an equally weighted one, returning ancestor indices from unnormalised log weights so that no caller exponentiates them. resample_systematic, resample_stratified and resample_multinomial are one inverse CDF \(a^{(m)} = \min\{k : F_k > u^{(m)}\}\) on different uniforms (one shared uniform, one per stratum, or independent ones), and resample_residual keeps \(\lfloor M W_k \rfloor\) copies of each sample before drawing the rest. Each is unbiased, \(\mathbb{E}[O_k] = M W_k\) for the number of copies \(O_k\) of sample \(k\) (Douc and Cappé, 2005). resample_conditional holds one ancestor at a fixed slot, which particle Gibbs needs. filterax's particle filters and tempered SMC resample through them.

Three names integrate a kernel against a Gaussian input \(x \sim \mathcal{N}(\mu_x, \Sigma_x)\), the Gaussian-measure case of a kernel mean. kernel_expectations returns \(\Psi_0 = \mathbb{E}[k(x, x)]\), \(\Psi_1 = \mathbb{E}[k(x, Z)]\) and \(\Psi_2 = \mathbb{E}[k(Z, x) k(x, Z)]\) by a gaussx rule (Gauss–Hermite, unscented, cubature, Taylor or Monte Carlo), evaluating the kernel once per point of the rule. compute_psi_statistics uses a kernel's closed forms when it implements the AnalyticalPsiStatistics protocol and falls back to kernel_expectations otherwise. The Gaussian is a gaussx_infer.GaussianState; integrix adds no Gaussian class. These are the statistics that GPs at uncertain inputs need, and pyrox-gp builds its uncertain-input predictions on them.

Bayesian quadrature puts a GP prior with kernel \(k\) on the integrand \(g\) and returns the integral \(I = \int g \mathrm{d}\Pi\) with a posterior standard deviation from the values \(\mathbf{g}\) at a few nodes: \(\mathbb{E}[I \mid \mathbf{g}] = \mathbf{z}^\top \mathbf{K}^{-1} \mathbf{g}\) and \(\mathbb{V}[I \mid \mathbf{g}] = \iint k \mathrm{d}\Pi \mathrm{d}\Pi - \mathbf{z}^\top \mathbf{K}^{-1} \mathbf{z}\), where \(z_n = \int k(x, x_n) \mathrm{d}\Pi(x)\) are the kernel means. bayes_quad returns it as an Expectation, conditioning the joint Gaussian of \((\mathbf{g}, I)\) once with gaussx_infer.conditional. The measure is a probability measure: Box, WeightedBox (a density on a box, a spectral response, say), Sphere, Empirical or a gaussx_infer.GaussianState. kernel_mean and initial_error use a kernel's closed forms when it defines them (the methods listed on KernelLike) and otherwise integrate with Gauss–Legendre split at each node, so a Matérn kernel's kink costs no accuracy. rule_error is the worst-case error of any rule against the same measure (the maximum mean discrepancy), which equals the posterior standard deviation for the weights \(\mathbf{K}^{-1} \mathbf{z}\). The method is from Briol et al. (2019), Probabilistic integration: a role in statistical computation?

expect

Expectations: 𝔼[f] by Monte Carlo, randomised QMC and importance sampling.

Each estimator returns an Expectation with a standard error. monte_carlo averages draws already made (NumPyro's posterior samples, say) or drawn from a sampler; qmc averages over randomly shifted Sobol or Halton points; importance reweights draws from a proposal. log_gauss_hermite and log_simpson return log-integrals for heavy-tailed integrands that underflow. effective_sample_size and pareto_smoothed_log_weights diagnose importance weights. kernel_expectations and compute_psi_statistics integrate a kernel against a Gaussian input, the Ψ statistics of uncertain-input GPs. bayes_quad returns an integral with a posterior standard deviation from a few evaluations, against a measure (Box, WeightedBox, Sphere, Empirical or a gaussx_infer.GaussianState), through kernel_mean and initial_error; rule_error scores any rule against the same measure. resample_systematic, resample_stratified, resample_multinomial, resample_residual and resample_conditional turn a weighted cloud into an equally weighted one. integrix averages and resamples an empirical measure; sampling from a posterior stays in NumPyro and pyrox.

KernelLike

Bases: Protocol

A kernel: anything with pairwise(x, x′) returning k(x, x′).

kernellib's pointwise kernels satisfy it structurally. A kernel may also define closed forms, looked up by name and called with plain arrays; a method that raises NotImplementedError (a ν or a dimension it does not cover) falls back to numerical integration:

  • gaussian_kernel_mean(mean, cov, nodes): (D,), (D, D), (N, D) → (N,)
  • gaussian_initial_error(mean, cov): (D,), (D, D) → ()
  • box_kernel_mean(lower, upper, nodes): (D,), (D,), (N, D) → (N,)
  • box_initial_error(lower, upper): (D,), (D,) → ()

The box methods integrate against the uniform probability measure, so they return averages, not volumes. A kernel with AnalyticalPsiStatistics supplies Gaussian kernel means through psi1.

integrix.operator looks up three more optional extras by name:

  • features(x): (P, D) → (P, R) features with k(x, x′) = φ(x)ᵀ φ(x′), which IntegralOperator uses for its low-rank path.
  • cell_average(cell_size): (D,) → (), the kernel averaged over a cell of that size centred on the source, used in place of k(x, x) where a singular kernel meets a coincident point.
  • is_translation_invariant: an attribute, True when k(x, x′) depends only on x − x′, which lets convolution use the FFT.

Examples:

>>> import jax.numpy as jnp
>>> class Linear:
...     def pairwise(self, x, x_prime):
...         return jnp.dot(x, x_prime)
>>> float(Linear().pairwise(jnp.ones(2), jnp.ones(2)))
2.0
pairwise
pairwise(x: Float[Array, ' dim'], x_prime: Float[Array, ' dim']) -> Float[Array, '']

Evaluate k(x, x′) at one pair of points.

Parameters:

Name Type Description Default
x Float[Array, ' dim']

The first point.

required
x_prime Float[Array, ' dim']

The second point.

required

Returns:

Type Description
Float[Array, '']

The kernel value.

Source code in src/integrix/_src/expect/_bayes_quad.py
def pairwise(
    self, x: Float[Array, " dim"], x_prime: Float[Array, " dim"]
) -> Float[Array, ""]:
    """Evaluate k(x, x′) at one pair of points.

    Args:
        x: The first point.
        x_prime: The second point.

    Returns:
        The kernel value.
    """
    ...

Expectation

Bases: Module

An estimate of 𝔼[f] with its standard error.

Attributes:

Name Type Description
value Float[Array, '*out']

The estimate Î, one per output entry.

standard_error Float[Array, '*out']

Its standard error σ̂, the same shape.

n_samples int

The number of integrand evaluations S.

effective_sample_size Float[Array, ''] | None

(∑ wₛ)² / ∑ wₛ² for importance sampling; None otherwise.

pareto_k Float[Array, ''] | None

The Pareto tail shape k̂ of the importance weights, when importance ran with diagnostics=True (k̂ > 0.7: do not trust the estimate); None otherwise.

Examples:

>>> import jax.numpy as jnp
>>> estimate = monte_carlo(lambda x: x, jnp.array([1.0, 2.0, 3.0]))
>>> bool(estimate.value == 2.0), estimate.n_samples
(True, 3)

AnalyticalPsiStatistics

Bases: Protocol

Protocol for kernels with closed-form Ψ statistics.

Ψ₀ = 𝔼[k(x, x)]
Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)],    x ~ 𝒩(μ_x, Σ_x)

Ψ statistics are required for uncertain-input GP models (e.g., BGPLVM). A kernel implementing this protocol provides analytical formulae instead of requiring numerical integration.

Examples:

The check is structural, so a class needs all three methods:

>>> import jax.numpy as jnp
>>> class ConstantKernel:
...     def psi0(self, state):
...         return jnp.ones(())
...
...     def psi1(self, state, X_train):
...         return jnp.ones(X_train.shape[0])
...
...     def psi2(self, state, X_train):
...         return jnp.ones((X_train.shape[0], X_train.shape[0]))
>>> isinstance(ConstantKernel(), AnalyticalPsiStatistics)
True
>>> isinstance(lambda x, x_prime: 1.0, AnalyticalPsiStatistics)
False
psi0
psi0(state: GaussianState) -> Float[Array, '']

Compute Ψ₀ = 𝔼[k(x, x)].

Parameters:

Name Type Description Default
state GaussianState

Input Gaussian 𝒩(μ_x, Σ_x).

required

Returns:

Type Description
Float[Array, '']

The scalar statistic Ψ₀.

Source code in src/integrix/_src/expect/_kernel_expectations.py
def psi0(self, state: GaussianState) -> Float[Array, ""]:
    """Compute Ψ₀ = 𝔼[k(x, x)].

    Args:
        state: Input Gaussian 𝒩(μ_x, Σ_x).

    Returns:
        The scalar statistic Ψ₀.
    """
    ...
psi1
psi1(state: GaussianState, X_train: Float[Array, 'M D']) -> Float[Array, ' M']

Compute Ψ₁ᵢ = 𝔼[k(x, xᵢ)].

Parameters:

Name Type Description Default
state GaussianState

Input Gaussian 𝒩(μ_x, Σ_x).

required
X_train Float[Array, 'M D']

Training or inducing inputs, whose rows are the xᵢ.

required

Returns:

Type Description
Float[Array, ' M']

The vector statistic Ψ₁.

Source code in src/integrix/_src/expect/_kernel_expectations.py
def psi1(
    self,
    state: GaussianState,
    X_train: Float[Array, "M D"],
) -> Float[Array, " M"]:
    """Compute Ψ₁ᵢ = 𝔼[k(x, xᵢ)].

    Args:
        state: Input Gaussian 𝒩(μ_x, Σ_x).
        X_train: Training or inducing inputs, whose rows are the xᵢ.

    Returns:
        The vector statistic Ψ₁.
    """
    ...
psi2
psi2(state: GaussianState, X_train: Float[Array, 'M D']) -> Float[Array, 'M M']

Compute Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)].

Parameters:

Name Type Description Default
state GaussianState

Input Gaussian 𝒩(μ_x, Σ_x).

required
X_train Float[Array, 'M D']

Training or inducing inputs, whose rows are the xᵢ.

required

Returns:

Type Description
Float[Array, 'M M']

The matrix statistic Ψ₂.

Source code in src/integrix/_src/expect/_kernel_expectations.py
def psi2(
    self,
    state: GaussianState,
    X_train: Float[Array, "M D"],
) -> Float[Array, "M M"]:
    """Compute Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)].

    Args:
        state: Input Gaussian 𝒩(μ_x, Σ_x).
        X_train: Training or inducing inputs, whose rows are the xᵢ.

    Returns:
        The matrix statistic Ψ₂.
    """
    ...

Box

Bases: Module

The uniform probability measure on a box [l, u] ⊂ ℝᴰ.

dΠ(x) = dx / ∏_d (u_d − l_d),    x ∈ [l, u]

Attributes:

Name Type Description
lower Float[Array, ' dim']

The lower corner l.

upper Float[Array, ' dim']

The upper corner u, each entry above the matching l_d.

Raises:

Type Description
ValidationError

If the corners are not vectors of one length.

Examples:

>>> import jax.numpy as jnp
>>> band = Box(jnp.array([0.0]), jnp.array([2.0]))
>>> band.lower.shape
(1,)

Empirical

Bases: Module

A weighted empirical measure: Π = ∑ₛ wₛ δ(x − xₛ) / ∑ₛ wₛ.

Kernel means against it are finite sums, so they are exact.

Attributes:

Name Type Description
samples Float[Array, 'sample dim']

The atoms xₛ, one row each.

weights Float[Array, ' sample']

Their non-negative weights wₛ, normalised by their sum; None weighs every atom equally.

Raises:

Type Description
ValidationError

If samples is not (S, D) or weights is not (S,).

EquinoxRuntimeError

If weights has a negative or non-finite entry or sums to zero (checked with eqx.error_if, so the check holds under jit).

Examples:

>>> import jax.numpy as jnp
>>> cloud = Empirical(jnp.zeros((4, 2)))
>>> cloud.weights.shape
(4,)

Sphere

Bases: Module

The uniform probability measure on the sphere of radius R in ℝ³.

dΠ(x) = dA(x) / (4π R²),    |x| = R

Points are Cartesian (x, y, z), so a kernel on ℝ³ sees chordal distances.

Attributes:

Name Type Description
radius Float[Array, '']

R, positive.

Examples:

>>> sphere = Sphere(6371.0)
>>> float(sphere.radius)
6371.0

WeightedBox

Bases: Module

A probability measure on a box with a density, normalised over the box.

dΠ(x) = ρ(x) dx / ∫_[l, u] ρ(x′) dx′,    x ∈ [l, u]

The density ρ need not be normalised: integrix divides by its integral over the box, computed with the same rule as the kernel means.

Attributes:

Name Type Description
density Callable[[Float[Array, ' dim']], Float[Array, '']]

ρ, mapping one point (D,) to a non-negative scalar.

lower Float[Array, ' dim']

The lower corner l.

upper Float[Array, ' dim']

The upper corner u.

Raises:

Type Description
ValidationError

If the corners are not vectors of one length.

Examples:

A spectral response on a band of wavelengths:

>>> import jax.numpy as jnp
>>> response = lambda x: jnp.exp(-0.5 * ((x[0] - 1.0) / 0.3) ** 2)
>>> band = WeightedBox(response, jnp.array([0.0]), jnp.array([2.0]))
>>> band.upper.shape
(1,)

bayes_quad

bayes_quad(kernel: KernelLike, measure: Measure, nodes: Float[Array, 'node dim'], values: Float[Array, ' node'], *, rule: object = None, jitter: float = 1e-10) -> Expectation

Bayesian quadrature: I = ∫ g dΠ with its posterior mean and standard deviation.

𝔼[I ∣ g] = zᵀ K⁻¹ g
𝕍[I ∣ g] = ∬ k dΠ dΠ − zᵀ K⁻¹ z

with g ~ GP(0, k), its values g at the nodes, K the kernel matrix and z the kernel means (kernel_mean).

Algorithm
  1. K, z and the initial error ∬ k dΠ dΠ (initial_error).
  2. The joint covariance of (g, I): [[K + ε k̄ I, z], [zᵀ, ∬ k dΠ dΠ]], with the jitter ε scaled by the mean prior variance k̄ of K's diagonal.
  3. Condition on the first N entries with gaussx_infer.conditional.

Parameters:

Name Type Description Default
kernel KernelLike

The kernel k of the prior on g.

required
measure Measure

The probability measure Π.

required
nodes Float[Array, 'node dim']

The nodes xₙ.

required
values Float[Array, ' node']

The integrand's values gₙ = g(xₙ).

required
rule object

As in kernel_mean.

None
jitter float

ε, relative to the mean of K's diagonal. Smooth kernels make K ill-conditioned, so the default adds 10⁻¹⁰ of it; 0 adds none.

1e-10

Returns:

Type Description
Expectation

An Expectation whose value is 𝔼[I ∣ g], standard_error is

Expectation

√𝕍[I ∣ g] (clipped at zero) and n_samples is N.

Raises:

Type Description
ValidationError

If values is not (N,) for N nodes, or as kernel_mean.

References

Briol, F.-X., Oates, C. J., Girolami, M., Osborne, M. A. and Sejdinovic, D. (2019). Probabilistic integration: a role in statistical computation? Statistical Science 34(1), 1–22.

Examples:

Under a Brownian-motion kernel min(x, x′) on [0, 1] the posterior mean is the trapezoid rule through g(0) = 0:

>>> import jax.numpy as jnp
>>> class Brownian:
...     def pairwise(self, x, x_prime):
...         return jnp.minimum(x, x_prime)[0]
>>> box = Box(jnp.array([0.0]), jnp.array([1.0]))
>>> nodes = jnp.array([[0.25], [0.5], [1.0]])
>>> values = jnp.array([1.0, 0.5, 2.0])
>>> result = bayes_quad(Brownian(), box, nodes, values, jitter=0.0)
>>> trapezoid = (
...     0.25 * (0 + 1) / 2 + 0.25 * (1 + 0.5) / 2 + 0.5 * (0.5 + 2) / 2
... )
>>> bool(jnp.allclose(result.value, trapezoid))
True
>>> result.standard_error.shape, result.n_samples
((), 3)
Source code in src/integrix/_src/expect/_bayes_quad.py
def bayes_quad(
    kernel: KernelLike,
    measure: Measure,
    nodes: Float[Array, "node dim"],
    values: Float[Array, " node"],
    *,
    rule: object = None,
    jitter: float = 1e-10,
) -> Expectation:
    """Bayesian quadrature: I = ∫ g dΠ with its posterior mean and standard deviation.

        𝔼[I ∣ g] = zᵀ K⁻¹ g
        𝕍[I ∣ g] = ∬ k dΠ dΠ − zᵀ K⁻¹ z

    with g ~ GP(0, k), its values g at the nodes, K the kernel matrix and z
    the kernel means (`kernel_mean`).

    Algorithm:
        1. K, z and the initial error ∬ k dΠ dΠ (`initial_error`).
        2. The joint covariance of (g, I): [[K + ε k̄ I, z], [zᵀ, ∬ k dΠ dΠ]],
           with the jitter ε scaled by the mean prior variance k̄ of K's
           diagonal.
        3. Condition on the first N entries with `gaussx_infer.conditional`.

    Args:
        kernel: The kernel k of the prior on g.
        measure: The probability measure Π.
        nodes: The nodes xₙ.
        values: The integrand's values gₙ = g(xₙ).
        rule: As in `kernel_mean`.
        jitter: ε, relative to the mean of K's diagonal. Smooth kernels make
            K ill-conditioned, so the default adds 10⁻¹⁰ of it; 0 adds none.

    Returns:
        An `Expectation` whose ``value`` is 𝔼[I ∣ g], ``standard_error`` is
        √𝕍[I ∣ g] (clipped at zero) and ``n_samples`` is N.

    Raises:
        ValidationError: If ``values`` is not (N,) for N nodes, or as
            `kernel_mean`.

    References:
        Briol, F.-X., Oates, C. J., Girolami, M., Osborne, M. A. and
        Sejdinovic, D. (2019). Probabilistic integration: a role in
        statistical computation? Statistical Science 34(1), 1–22.

    Examples:
        Under a Brownian-motion kernel min(x, x′) on [0, 1] the posterior mean
        is the trapezoid rule through g(0) = 0:

        >>> import jax.numpy as jnp
        >>> class Brownian:
        ...     def pairwise(self, x, x_prime):
        ...         return jnp.minimum(x, x_prime)[0]
        >>> box = Box(jnp.array([0.0]), jnp.array([1.0]))
        >>> nodes = jnp.array([[0.25], [0.5], [1.0]])
        >>> values = jnp.array([1.0, 0.5, 2.0])
        >>> result = bayes_quad(Brownian(), box, nodes, values, jitter=0.0)
        >>> trapezoid = (
        ...     0.25 * (0 + 1) / 2 + 0.25 * (1 + 0.5) / 2 + 0.5 * (0.5 + 2) / 2
        ... )
        >>> bool(jnp.allclose(result.value, trapezoid))
        True
        >>> result.standard_error.shape, result.n_samples
        ((), 3)
    """
    values = jnp.asarray(values)
    nodes = jnp.asarray(nodes)
    if values.shape != nodes.shape[:1]:
        raise ValidationError(
            f"'values' must have one entry per node, got shape {values.shape} "
            f"for {nodes.shape[0]} nodes"
        )
    gram, means, prior_variance = _moments(kernel, measure, nodes, rule)
    count = nodes.shape[0]
    # K + ε k̄ I
    scale = jitter * jnp.mean(jnp.diagonal(gram))
    noisy_gram = gram + scale * jnp.eye(count, dtype=gram.dtype)
    # the joint covariance of (g, I)
    joint = jnp.block(
        [
            [noisy_gram, einx.id("node -> node 1", means)],
            [einx.id("node -> 1 node", means), einx.id(" -> 1 1", prior_variance)],
        ]
    )
    covariance = lx.MatrixLinearOperator(joint, lx.positive_semidefinite_tag)
    posterior_mean, posterior_cov = gaussx_infer.conditional(
        jnp.zeros(count + 1, joint.dtype),
        covariance,
        jnp.arange(count),
        values,
    )
    variance = posterior_cov.as_matrix()[0, 0]
    return Expectation(
        value=posterior_mean[0],
        standard_error=_safe_sqrt(variance),
        n_samples=count,
    )

initial_error

initial_error(kernel: KernelLike, measure: Measure, *, rule: object = None) -> Float[Array, '']

The initial error ∬ k(x, x′) dΠ(x) dΠ(x′), the variance of I before any node.

Algorithm
  1. A Gaussian or a box: the kernel's closed form when it defines the matching method of KernelLike.
  2. An empirical measure, a sphere, or a Gaussian with a gaussx integrator: wᵀ K w over its points.
  3. Otherwise, ∫ z(x′) dΠ(x′): the outer integral with the rule split at the box's centre, and each inner kernel mean z(x′) by kernel_mean's rule split at x′.

Parameters:

Name Type Description Default
kernel KernelLike

The kernel k.

required
measure Measure

The probability measure Π.

required
rule object

As in kernel_mean.

None

Returns:

Type Description
Float[Array, '']

The initial error, a scalar.

Raises:

Type Description
ValidationError

If the rule does not suit the measure.

Examples:

A constant kernel has initial error equal to the constant:

>>> import jax.numpy as jnp
>>> class Constant:
...     def pairwise(self, x, x_prime):
...         return jnp.asarray(2.0)
>>> box = Box(jnp.zeros(2), jnp.ones(2))
>>> bool(jnp.allclose(initial_error(Constant(), box), 2.0))
True
Source code in src/integrix/_src/expect/_bayes_quad.py
def initial_error(
    kernel: KernelLike,
    measure: Measure,
    *,
    rule: object = None,
) -> Float[Array, ""]:
    """The initial error ∬ k(x, x′) dΠ(x) dΠ(x′), the variance of I before any node.

    Algorithm:
        1. A Gaussian or a box: the kernel's closed form when it defines the
           matching method of `KernelLike`.
        2. An empirical measure, a sphere, or a Gaussian with a gaussx
           integrator: wᵀ K w over its points.
        3. Otherwise, ∫ z(x′) dΠ(x′): the outer integral with the rule split at
           the box's centre, and each inner kernel mean z(x′) by
           `kernel_mean`'s rule split at x′.

    Args:
        kernel: The kernel k.
        measure: The probability measure Π.
        rule: As in `kernel_mean`.

    Returns:
        The initial error, a scalar.

    Raises:
        ValidationError: If the rule does not suit the measure.

    Examples:
        A constant kernel has initial error equal to the constant:

        >>> import jax.numpy as jnp
        >>> class Constant:
        ...     def pairwise(self, x, x_prime):
        ...         return jnp.asarray(2.0)
        >>> box = Box(jnp.zeros(2), jnp.ones(2))
        >>> bool(jnp.allclose(initial_error(Constant(), box), 2.0))
        True
    """
    if isinstance(measure, gaussx_infer.GaussianState):
        cov = measure.cov.as_matrix()
        closed = _closed_form(kernel, "gaussian_initial_error", measure.mean, cov)
        if closed is not None:
            return closed
    if isinstance(measure, Box):
        closed = _closed_form(kernel, "box_initial_error", measure.lower, measure.upper)
        if closed is not None:
            return closed

    atoms = _atoms(measure, rule)
    if atoms is not None:
        points, weights = atoms
        # wᵀ K w
        return einx.dot(
            "row, row col, col ->", weights, _gram(kernel, points, points), weights
        )

    base = _base_rule(rule)
    chart = _chart(measure, base)
    centre = 0.5 * (chart.lower + chart.upper)
    outer, outer_weights = _tensor_rule(chart.lower, chart.upper, centre, base)
    # vₚ dΠ/dξ(ξₚ)
    outer_masses = outer_weights * chart.density(outer)
    inner = _chart_means(kernel, chart, base, outer, chart.to_points(outer))
    # ∬ k dΠ dΠ = ∑ₚ vₚ z(xₚ), summed pairwise
    return integrate(outer_masses, inner).value

kernel_mean

kernel_mean(kernel: KernelLike, measure: Measure, nodes: Float[Array, 'node dim'], *, rule: object = None) -> Float[Array, ' node']

Kernel means zₙ = ∫ k(x, xₙ) dΠ(x), in closed form when the kernel has one.

Algorithm
  1. A Gaussian or a box: the kernel's closed form when it defines the matching method of KernelLike (or, for a Gaussian, psi1 of AnalyticalPsiStatistics).
  2. An empirical measure, a sphere, or a Gaussian with a gaussx integrator: the weighted sum over its points.
  3. Otherwise, a box in the measure's coordinates (whitened and cut at ±9 for a Gaussian), with the rule on [l_d, xₙ_d] and [xₙ_d, u_d] in each dimension, so a kernel's kink at xₙ sits on the pieces' edges.

Each node costs (2m)ᴰ kernel evaluations for an m-point rule in step 3, so this suits the few dimensions of a band or a field point.

Parameters:

Name Type Description Default
kernel KernelLike

The kernel k.

required
measure Measure

The probability measure Π: a gaussx_infer.GaussianState, Box, WeightedBox, Sphere or Empirical.

required
nodes Float[Array, 'node dim']

The nodes xₙ.

required
rule object

For step 3, a one-dimensional rule on [−1, 1] (32-point Gauss–Legendre by default); for a Gaussian, a gaussx integrator instead; for a sphere, a functax sphere rule (sphere_gauss_legendre(32) by default).

None

Returns:

Type Description
Float[Array, ' node']

The kernel means z.

Raises:

Type Description
ValidationError

If the nodes do not match the measure's dimension or the rule does not suit the measure.

Examples:

The RBF mean against the uniform measure on [−1, 1]:

>>> import jax.numpy as jnp
>>> 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))
>>> box = Box(jnp.array([-1.0]), jnp.array([1.0]))
>>> z = kernel_mean(RBF(), box, jnp.array([[0.0]]))
>>> exact = jnp.sqrt(jnp.pi / 2) * erf(1 / jnp.sqrt(2.0))
>>> bool(jnp.allclose(z, exact, rtol=1e-12))
True

An empirical measure gives an exact average:

>>> cloud = Empirical(jnp.array([[0.0], [1.0]]))
>>> kernel_mean(RBF(), cloud, jnp.array([[0.0]])).shape
(1,)
Source code in src/integrix/_src/expect/_bayes_quad.py
def kernel_mean(
    kernel: KernelLike,
    measure: Measure,
    nodes: Float[Array, "node dim"],
    *,
    rule: object = None,
) -> Float[Array, " node"]:
    """Kernel means zₙ = ∫ k(x, xₙ) dΠ(x), in closed form when the kernel has one.

    Algorithm:
        1. A Gaussian or a box: the kernel's closed form when it defines the
           matching method of `KernelLike` (or, for a Gaussian, `psi1` of
           `AnalyticalPsiStatistics`).
        2. An empirical measure, a sphere, or a Gaussian with a gaussx
           integrator: the weighted sum over its points.
        3. Otherwise, a box in the measure's coordinates (whitened and cut at
           ±9 for a Gaussian), with the rule on [l_d, xₙ_d] and [xₙ_d, u_d] in
           each dimension, so a kernel's kink at xₙ sits on the pieces' edges.

    Each node costs (2m)ᴰ kernel evaluations for an m-point rule in step 3, so
    this suits the few dimensions of a band or a field point.

    Args:
        kernel: The kernel k.
        measure: The probability measure Π: a `gaussx_infer.GaussianState`, `Box`,
            `WeightedBox`, `Sphere` or `Empirical`.
        nodes: The nodes xₙ.
        rule: For step 3, a one-dimensional rule on [−1, 1] (32-point
            Gauss–Legendre by default); for a Gaussian, a gaussx integrator
            instead; for a sphere, a functax sphere rule
            (``sphere_gauss_legendre(32)`` by default).

    Returns:
        The kernel means z.

    Raises:
        ValidationError: If the nodes do not match the measure's dimension or
            the rule does not suit the measure.

    Examples:
        The RBF mean against the uniform measure on [−1, 1]:

        >>> import jax.numpy as jnp
        >>> 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))
        >>> box = Box(jnp.array([-1.0]), jnp.array([1.0]))
        >>> z = kernel_mean(RBF(), box, jnp.array([[0.0]]))
        >>> exact = jnp.sqrt(jnp.pi / 2) * erf(1 / jnp.sqrt(2.0))
        >>> bool(jnp.allclose(z, exact, rtol=1e-12))
        True

        An empirical measure gives an exact average:

        >>> cloud = Empirical(jnp.array([[0.0], [1.0]]))
        >>> kernel_mean(RBF(), cloud, jnp.array([[0.0]])).shape
        (1,)
    """
    nodes = jnp.asarray(nodes)
    _check_nodes(measure, nodes)
    if isinstance(measure, gaussx_infer.GaussianState):
        cov = measure.cov.as_matrix()
        closed = _closed_form(kernel, "gaussian_kernel_mean", measure.mean, cov, nodes)
        if closed is not None:
            return closed
        if isinstance(kernel, AnalyticalPsiStatistics):
            return kernel.psi1(measure, nodes)
    if isinstance(measure, Box):
        closed = _closed_form(
            kernel, "box_kernel_mean", measure.lower, measure.upper, nodes
        )
        if closed is not None:
            return closed

    atoms = _atoms(measure, rule)
    if atoms is not None:
        points, weights = atoms
        # zₙ = ∑ₚ wₚ k(xₚ, xₙ), summed pairwise over the atoms
        return integrate(weights, _gram(kernel, points, nodes), axis=0).value

    base = _base_rule(rule)
    chart = _chart(measure, base)
    return _chart_means(kernel, chart, base, chart.to_chart(nodes), nodes)

rule_error

rule_error(kernel: KernelLike, measure: Measure, nodes: Float[Array, 'node dim'], weights: Float[Array, ' node'], *, rule: object = None) -> Float[Array, '']

The worst-case error of a rule over the unit ball of the kernel's RKHS.

e(w)² = ∬ k dΠ dΠ − 2 wᵀ z + wᵀ K w

the maximum mean discrepancy between Π and the rule ∑ₙ wₙ δ(x − xₙ). With the Bayesian-quadrature weights w = K⁻¹ z it equals √𝕍[I ∣ g].

Parameters:

Name Type Description Default
kernel KernelLike

The kernel k.

required
measure Measure

The probability measure Π.

required
nodes Float[Array, 'node dim']

The rule's nodes xₙ.

required
weights Float[Array, ' node']

Its weights wₙ, for an average against Π (they sum to about one for a probability measure).

required
rule object

As in kernel_mean, for the integrals the error needs.

None

Returns:

Type Description
Float[Array, '']

e(w), clipped at zero before the square root.

Raises:

Type Description
ValidationError

If weights is not (N,) for N nodes, or as kernel_mean.

Examples:

The midpoint rule on [0, 1] under a Brownian-motion kernel:

>>> import jax.numpy as jnp
>>> class Brownian:
...     def pairwise(self, x, x_prime):
...         return jnp.minimum(x, x_prime)[0]
>>> box = Box(jnp.array([0.0]), jnp.array([1.0]))
>>> error = rule_error(
...     Brownian(), box, jnp.array([[0.5]]), jnp.array([1.0])
... )
>>> bool(error > 0)
True
Source code in src/integrix/_src/expect/_bayes_quad.py
def rule_error(
    kernel: KernelLike,
    measure: Measure,
    nodes: Float[Array, "node dim"],
    weights: Float[Array, " node"],
    *,
    rule: object = None,
) -> Float[Array, ""]:
    """The worst-case error of a rule over the unit ball of the kernel's RKHS.

        e(w)² = ∬ k dΠ dΠ − 2 wᵀ z + wᵀ K w

    the maximum mean discrepancy between Π and the rule ∑ₙ wₙ δ(x − xₙ). With
    the Bayesian-quadrature weights w = K⁻¹ z it equals √𝕍[I ∣ g].

    Args:
        kernel: The kernel k.
        measure: The probability measure Π.
        nodes: The rule's nodes xₙ.
        weights: Its weights wₙ, for an average against Π (they sum to about
            one for a probability measure).
        rule: As in `kernel_mean`, for the integrals the error needs.

    Returns:
        e(w), clipped at zero before the square root.

    Raises:
        ValidationError: If ``weights`` is not (N,) for N nodes, or as
            `kernel_mean`.

    Examples:
        The midpoint rule on [0, 1] under a Brownian-motion kernel:

        >>> import jax.numpy as jnp
        >>> class Brownian:
        ...     def pairwise(self, x, x_prime):
        ...         return jnp.minimum(x, x_prime)[0]
        >>> box = Box(jnp.array([0.0]), jnp.array([1.0]))
        >>> error = rule_error(
        ...     Brownian(), box, jnp.array([[0.5]]), jnp.array([1.0])
        ... )
        >>> bool(error > 0)
        True
    """
    weights = jnp.asarray(weights)
    nodes = jnp.asarray(nodes)
    if weights.shape != nodes.shape[:1]:
        raise ValidationError(
            f"'weights' must have one entry per node, got shape {weights.shape} "
            f"for {nodes.shape[0]} nodes"
        )
    gram, means, prior_variance = _moments(kernel, measure, nodes, rule)
    # wᵀ K w
    quadratic = einx.dot("row, row col, col ->", weights, gram, weights)
    # 2 wᵀ z
    cross = 2.0 * einx.dot("node, node ->", weights, means)
    squared = prior_variance - cross + quadratic
    return _safe_sqrt(squared)

effective_sample_size

effective_sample_size(log_weights: Float[ArrayLike, '*batch draw']) -> Float[Array, '*batch']

ESS = (∑ₛ wₛ)² / ∑ₛ wₛ² from log weights, along the last axis.

log ESS = 2 logsumexp(log wₛ) − logsumexp(2 log wₛ), so no weight is exponentiated and the result is the same for weights scaled by any constant. It equals S for equal weights and falls towards 1 as one weight dominates.

Parameters:

Name Type Description Default
log_weights Float[ArrayLike, '*batch draw']

Unnormalised log importance weights log wₛ, the S draws along the last axis, any batch in front.

required

Returns:

Type Description
Float[Array, '*batch']

The effective sample size, one per batch entry.

Raises:

Type Description
ValidationError

If log_weights has no draw axis.

Examples:

>>> import jax.numpy as jnp
>>> bool(jnp.allclose(effective_sample_size(jnp.zeros(8)), 8.0))
True
>>> # one weight e times the others: (e + 3)² / (e² + 3)
>>> ess = effective_sample_size(jnp.array([1.0, 0.0, 0.0, 0.0]))
>>> bool(jnp.allclose(ess, (jnp.e + 3) ** 2 / (jnp.e**2 + 3)))
True
Source code in src/integrix/_src/expect/_diagnostics.py
def effective_sample_size(
    log_weights: Float[ArrayLike, "*batch draw"],
) -> Float[Array, "*batch"]:
    """ESS = (∑ₛ wₛ)² / ∑ₛ wₛ² from log weights, along the last axis.

    log ESS = 2 logsumexp(log wₛ) − logsumexp(2 log wₛ), so no weight is
    exponentiated and the result is the same for weights scaled by any
    constant. It equals S for equal weights and falls towards 1 as one weight
    dominates.

    Args:
        log_weights: Unnormalised log importance weights log wₛ, the S draws
            along the last axis, any batch in front.

    Returns:
        The effective sample size, one per batch entry.

    Raises:
        ValidationError: If ``log_weights`` has no draw axis.

    Examples:
        >>> import jax.numpy as jnp
        >>> bool(jnp.allclose(effective_sample_size(jnp.zeros(8)), 8.0))
        True
        >>> # one weight e times the others: (e + 3)² / (e² + 3)
        >>> ess = effective_sample_size(jnp.array([1.0, 0.0, 0.0, 0.0]))
        >>> bool(jnp.allclose(ess, (jnp.e + 3) ** 2 / (jnp.e**2 + 3)))
        True
    """
    log_weights = _as_log_weights(log_weights)
    # 2 log ∑ₛ wₛ
    log_sum = einx.logsumexp("... s -> ...", log_weights)
    # log ∑ₛ wₛ²
    log_sum_of_squares = einx.logsumexp("... s -> ...", 2.0 * log_weights)
    # log ESS = 2 log ∑ wₛ − log ∑ wₛ²
    return jnp.exp(2.0 * log_sum - log_sum_of_squares)

pareto_smoothed_log_weights

pareto_smoothed_log_weights(log_weights: Float[ArrayLike, '*batch draw']) -> tuple[Float[Array, '*batch draw'], Float[Array, '*batch']]

Pareto-smoothed log importance weights and the tail shape k̂.

The largest M = ⌈min(S/5, 3√S)⌉ weights are replaced by the expected order statistics of a generalised Pareto distribution fitted to their exceedances over the cutoff (Zhang and Stephens' estimator, with the weakly informative prior on the shape), capped at the largest raw weight, and the weights are normalised to logsumexp 0. The quantile is F⁻¹(p) = σ((1 − p)^(−k) − 1)/k. k̂ > 0.7 means the importance estimate should not be trusted.

Algorithm
  1. Shift log w so its maximum is 0; with M ≥ S there is no tail, so normalise and return k̂ = NaN.
  2. Sort, take the top M as the tail and the next weight as the cutoff; weights tied at the cutoff are masked out of the fit.
  3. Fit (k, σ) to the exceedances: the Zhang–Stephens posterior mean over m = 30 + ⌊√M⌋ candidate values, vectorised, then shrink k towards ½.
  4. Replace the tail by min(log(F⁻¹((z − ½)/M) + cutoff), 0), z = 1, …, M, when k̂ is finite, and normalise.

The fit sorts and selects, so it is piecewise in the weights: the tail replacement and k̂ are wrapped in jax.lax.stop_gradient, and the gradient flows only through the untouched weights and the normalisation. Batched over any leading axes, and traceable (S is static).

Parameters:

Name Type Description Default
log_weights Float[ArrayLike, '*batch draw']

Unnormalised log importance weights, the S draws along the last axis.

required

Returns:

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

(smoothed, k̂): the normalised smoothed log weights (logsumexp 0

Float[Array, '*batch']

along the last axis) and the fitted shape, NaN when fewer than five

tuple[Float[Array, '*batch draw'], Float[Array, '*batch']]

weights exceed the cutoff (equal weights need no smoothing).

Raises:

Type Description
ValidationError

If log_weights has no draw axis.

Examples:

>>> import jax
>>> import jax.numpy as jnp
>>> log_weights = 0.3 * jax.random.normal(jax.random.key(0), (1000,))
>>> smoothed, k_hat = pareto_smoothed_log_weights(log_weights)
>>> bool(jnp.allclose(jax.nn.logsumexp(smoothed), 0.0, atol=1e-5))
True
>>> bool(k_hat < 0.7)
True
>>> # equal weights: nothing to smooth, k̂ is NaN
>>> _, k_equal = pareto_smoothed_log_weights(jnp.zeros(100))
>>> bool(jnp.isnan(k_equal))
True
References

Vehtari, A., Simpson, D., Gelman, A., Yao, Y. & Gabry, J. Pareto smoothed importance sampling. arXiv:1507.02646. Zhang, J. & Stephens, M. A. (2009). A new and efficient estimation method for the generalized Pareto distribution. Technometrics 51, 316–325.

Source code in src/integrix/_src/expect/_diagnostics.py
def pareto_smoothed_log_weights(
    log_weights: Float[ArrayLike, "*batch draw"],
) -> tuple[Float[Array, "*batch draw"], Float[Array, "*batch"]]:
    """Pareto-smoothed log importance weights and the tail shape k̂.

    The largest M = ⌈min(S/5, 3√S)⌉ weights are replaced by the expected order
    statistics of a generalised Pareto distribution fitted to their
    exceedances over the cutoff (Zhang and Stephens' estimator, with the
    weakly informative prior on the shape), capped at the largest raw weight,
    and the weights are normalised to logsumexp 0. The quantile is
    F⁻¹(p) = σ((1 − p)^(−k) − 1)/k. k̂ > 0.7 means the importance estimate
    should not be trusted.

    Algorithm:
        1. Shift log w so its maximum is 0; with M ≥ S there is no tail, so
           normalise and return k̂ = NaN.
        2. Sort, take the top M as the tail and the next weight as the cutoff;
           weights tied at the cutoff are masked out of the fit.
        3. Fit (k, σ) to the exceedances: the Zhang–Stephens posterior mean
           over m = 30 + ⌊√M⌋ candidate values, vectorised, then shrink k
           towards ½.
        4. Replace the tail by min(log(F⁻¹((z − ½)/M) + cutoff), 0), z = 1, …, M,
           when k̂ is finite, and normalise.

    The fit sorts and selects, so it is piecewise in the weights: the tail
    replacement and k̂ are wrapped in ``jax.lax.stop_gradient``, and the
    gradient flows only through the untouched weights and the normalisation.
    Batched over any leading axes, and traceable (S is static).

    Args:
        log_weights: Unnormalised log importance weights, the S draws along
            the last axis.

    Returns:
        ``(smoothed, k̂)``: the normalised smoothed log weights (logsumexp 0
        along the last axis) and the fitted shape, NaN when fewer than five
        weights exceed the cutoff (equal weights need no smoothing).

    Raises:
        ValidationError: If ``log_weights`` has no draw axis.

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> log_weights = 0.3 * jax.random.normal(jax.random.key(0), (1000,))
        >>> smoothed, k_hat = pareto_smoothed_log_weights(log_weights)
        >>> bool(jnp.allclose(jax.nn.logsumexp(smoothed), 0.0, atol=1e-5))
        True
        >>> bool(k_hat < 0.7)
        True
        >>> # equal weights: nothing to smooth, k̂ is NaN
        >>> _, k_equal = pareto_smoothed_log_weights(jnp.zeros(100))
        >>> bool(jnp.isnan(k_equal))
        True

    References:
        Vehtari, A., Simpson, D., Gelman, A., Yao, Y. & Gabry, J. Pareto
        smoothed importance sampling. arXiv:1507.02646.
        Zhang, J. & Stephens, M. A. (2009). A new and efficient estimation
        method for the generalized Pareto distribution. Technometrics 51,
        316–325.
    """
    log_weights = _as_log_weights(log_weights)
    smooth = jnp.vectorize(_smooth_one, signature="(s)->(s),()")
    return smooth(log_weights)

importance

importance(fn: Callable[[PyTree], Array], proposal_sample: Callable[[PRNGKeyArray, int], PyTree], proposal_log_prob: Callable[[PyTree], Array], target_log_prob: Callable[[PyTree], Array], n: int, *, diagnostics: bool = False, key: PRNGKeyArray) -> Expectation

Self-normalised importance sampling: Î = ∑ₛ wₛ f(xₛ) / ∑ₛ wₛ, xₛ ~ q.

The weights wₛ = p(xₛ)/q(xₛ) need p only up to a constant. The standard error is the delta-method one, σ̂² = ∑ₛ w̃ₛ² (fₛ − Î)², with w̃ the normalised weights, and the effective sample size (∑ wₛ)²/∑ wₛ² is reported: heavy-tailed weights make the estimate unreliable long before σ̂ looks large.

Parameters:

Name Type Description Default
fn Callable[[PyTree], Array]

The integrand f, applied to one draw.

required
proposal_sample Callable[[PRNGKeyArray, int], PyTree]

(key, n) -> draws from the proposal q.

required
proposal_log_prob Callable[[PyTree], Array]

log q(x) for one draw.

required
target_log_prob Callable[[PyTree], Array]

log p(x) for one draw, up to an additive constant.

required
n int

The number of draws S ≥ 2.

required
diagnostics bool

Also fit the Pareto tail of the weights and report its shape k̂ as pareto_k (pareto_smoothed_log_weights); the estimate itself is not smoothed.

False
key PRNGKeyArray

The PRNG key for the proposal.

required

Returns:

Type Description
Expectation

The Expectation, with effective_sample_size and, with

Expectation

diagnostics=True, pareto_k.

Raises:

Type Description
ValidationError

If n is below 2.

Examples:

>>> import jax
>>> import jax.numpy as jnp
>>> import jax.scipy.stats as stats
>>> estimate = importance(
...     jnp.square,
...     lambda key, n: 2.0 * jax.random.normal(key, (n,)),
...     lambda x: stats.norm.logpdf(x, scale=2.0),
...     lambda x: stats.norm.logpdf(x),
...     4096,
...     key=jax.random.key(0),
... )
>>> bool(abs(estimate.value - 1.0) < 4 * estimate.standard_error)
True
Source code in src/integrix/_src/expect/_expectation.py
def importance(
    fn: Callable[[PyTree], Array],
    proposal_sample: Callable[[PRNGKeyArray, int], PyTree],
    proposal_log_prob: Callable[[PyTree], Array],
    target_log_prob: Callable[[PyTree], Array],
    n: int,
    *,
    diagnostics: bool = False,
    key: PRNGKeyArray,
) -> Expectation:
    """Self-normalised importance sampling: Î = ∑ₛ wₛ f(xₛ) / ∑ₛ wₛ, xₛ ~ q.

    The weights wₛ = p(xₛ)/q(xₛ) need p only up to a constant. The standard
    error is the delta-method one, σ̂² = ∑ₛ w̃ₛ² (fₛ − Î)², with w̃ the
    normalised weights, and the effective sample size (∑ wₛ)²/∑ wₛ² is
    reported: heavy-tailed weights make the estimate unreliable long before
    σ̂ looks large.

    Args:
        fn: The integrand f, applied to one draw.
        proposal_sample: ``(key, n) -> draws`` from the proposal q.
        proposal_log_prob: log q(x) for one draw.
        target_log_prob: log p(x) for one draw, up to an additive constant.
        n: The number of draws S ≥ 2.
        diagnostics: Also fit the Pareto tail of the weights and report its
            shape k̂ as ``pareto_k`` (`pareto_smoothed_log_weights`); the
            estimate itself is not smoothed.
        key: The PRNG key for the proposal.

    Returns:
        The `Expectation`, with ``effective_sample_size`` and, with
        ``diagnostics=True``, ``pareto_k``.

    Raises:
        ValidationError: If ``n`` is below 2.

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> import jax.scipy.stats as stats
        >>> estimate = importance(
        ...     jnp.square,
        ...     lambda key, n: 2.0 * jax.random.normal(key, (n,)),
        ...     lambda x: stats.norm.logpdf(x, scale=2.0),
        ...     lambda x: stats.norm.logpdf(x),
        ...     4096,
        ...     key=jax.random.key(0),
        ... )
        >>> bool(abs(estimate.value - 1.0) < 4 * estimate.standard_error)
        True
    """
    if isinstance(n, bool) or not isinstance(n, int) or n < 2:
        raise ValidationError(f"'n' must be an integer of at least 2, got {n!r}")
    draws = proposal_sample(key, n)
    log_target = jax.vmap(target_log_prob)(draws)
    log_proposal = jax.vmap(proposal_log_prob)(draws)
    log_weights = log_target - log_proposal
    # w̃ₛ = wₛ / ∑ wₛ, from log wₛ = log p(xₛ) − log q(xₛ), stably
    normalised = jax.nn.softmax(log_weights)
    values = _as_float(jax.vmap(lambda draw: jnp.asarray(fn(draw)))(draws))
    normalised = normalised.astype(jnp.result_type(values.dtype, normalised.dtype))
    # Î = ∑ₛ w̃ₛ fₛ
    value = pairwise_sum(einx.multiply("s, s ... -> s ...", normalised, values))
    deviation = values - value
    # σ̂² = ∑ₛ w̃ₛ² (fₛ − Î)²
    variance = pairwise_sum(
        einx.multiply("s, s ... -> s ...", normalised**2, deviation**2)
    )
    # ESS = (∑ₛ wₛ)² / ∑ₛ wₛ², from the log weights
    effective = effective_sample_size(log_weights)
    pareto_k = None
    if diagnostics:
        _, pareto_k = pareto_smoothed_log_weights(log_weights)
    # a target with no support on any draw leaves no weight at all
    value = eqx.error_if(
        value,
        ~jnp.any(jnp.isfinite(log_weights)),
        "importance: the target has zero density at every proposal draw",
    )
    return Expectation(
        value=value,
        standard_error=jnp.sqrt(variance),
        n_samples=n,
        effective_sample_size=effective,
        pareto_k=pareto_k,
    )

monte_carlo

monte_carlo(fn: Callable[[PyTree], Array], samples_or_sampler: PyTree | Callable[[PRNGKeyArray, int], PyTree], n: int | None = None, *, key: PRNGKeyArray | None = None) -> Expectation

Plain Monte Carlo: Î = (1/S) ∑ₛ f(xₛ), with standard error σ̂/√S.

The draws xₛ ~ p are given (an array or pytree with a leading sample axis, NumPyro's posterior samples, say) or drawn as sampler(key, n).

Algorithm
  1. The draws: as given, or sampler(key, n).
  2. fₛ = f(xₛ) under jax.vmap.
  3. Î = (1/S) ∑ₛ fₛ and s² = ∑ₛ (fₛ − Î)² / (S − 1), both summed pairwise; σ̂ = s / √S.

Parameters:

Name Type Description Default
fn Callable[[PyTree], Array]

The integrand f, applied to one draw.

required
samples_or_sampler PyTree | Callable[[PRNGKeyArray, int], PyTree]

The draws, leading axis S ≥ 2, or a sampler (key, n) -> draws.

required
n int | None

The number of draws for a sampler (must match the draws if given).

None
key PRNGKeyArray | None

The PRNG key for a sampler.

None

Returns:

Type Description
Expectation

The Expectation.

Raises:

Type Description
ValidationError

If a sampler has no key or n, fewer than two draws are given, or n disagrees with the draws.

Examples:

>>> import jax
>>> import jax.numpy as jnp
>>> sampler = lambda key, n: jax.random.normal(key, (n,))
>>> estimate = monte_carlo(jnp.square, sampler, 4096, key=jax.random.key(0))
>>> bool(abs(estimate.value - 1.0) < 4 * estimate.standard_error)
True
Source code in src/integrix/_src/expect/_expectation.py
def monte_carlo(
    fn: Callable[[PyTree], Array],
    samples_or_sampler: PyTree | Callable[[PRNGKeyArray, int], PyTree],
    n: int | None = None,
    *,
    key: PRNGKeyArray | None = None,
) -> Expectation:
    """Plain Monte Carlo: Î = (1/S) ∑ₛ f(xₛ), with standard error σ̂/√S.

    The draws xₛ ~ p are given (an array or pytree with a leading sample axis,
    NumPyro's posterior samples, say) or drawn as ``sampler(key, n)``.

    Algorithm:
        1. The draws: as given, or ``sampler(key, n)``.
        2. fₛ = f(xₛ) under `jax.vmap`.
        3. Î = (1/S) ∑ₛ fₛ and s² = ∑ₛ (fₛ − Î)² / (S − 1), both summed
           pairwise; σ̂ = s / √S.

    Args:
        fn: The integrand f, applied to one draw.
        samples_or_sampler: The draws, leading axis S ≥ 2, or a sampler
            ``(key, n) -> draws``.
        n: The number of draws for a sampler (must match the draws if given).
        key: The PRNG key for a sampler.

    Returns:
        The `Expectation`.

    Raises:
        ValidationError: If a sampler has no ``key`` or ``n``, fewer than two
            draws are given, or ``n`` disagrees with the draws.

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> sampler = lambda key, n: jax.random.normal(key, (n,))
        >>> estimate = monte_carlo(jnp.square, sampler, 4096, key=jax.random.key(0))
        >>> bool(abs(estimate.value - 1.0) < 4 * estimate.standard_error)
        True
    """
    if callable(samples_or_sampler):
        if key is None or n is None:
            raise ValidationError(
                "monte_carlo needs 'key' and 'n' to draw from a sampler"
            )
        draws = samples_or_sampler(key, n)
    else:
        draws = samples_or_sampler
    count = _sample_count(draws)
    if n is not None and n != count:
        raise ValidationError(f"'n' is {n} but the draws have {count} samples")
    values = _as_float(jax.vmap(lambda draw: jnp.asarray(fn(draw)))(draws))
    value, standard_error = _mean_and_error(values)
    return Expectation(value=value, standard_error=standard_error, n_samples=count)

qmc

qmc(fn: Callable[[Array], Array], dim: int, n: int, *, sequence: Literal['sobol', 'halton'] = 'sobol', n_shifts: int = 16, transform: Callable[[Array], PyTree] | None = None, key: PRNGKeyArray) -> Expectation

Randomised quasi-Monte Carlo over [0, 1)^D, with an error from random shifts.

Î = (1/R) ∑ᵣ Îᵣ, where Îᵣ = (1/n) ∑ᵢ f(T(uᵢ ⊕ Δᵣ)) averages over the low-discrepancy points uᵢ shifted by the r-th random shift Δᵣ, and σ̂ = sᵣ / √R from the spread of the R shifted estimates. For a smooth integrand the error falls faster than S^{−1/2}. An unshifted sequence has no error estimate, so R ≥ 2.

Algorithm
  1. The first n points of the Sobol (Joe–Kuo, Gray-code order, n a power of two is best) or Halton sequence in D dimensions.
  2. R random shifts from one key: a digital shift (XOR of 32-bit integers) for Sobol, a rotation (uᵢ + Δᵣ) mod 1 for Halton.
  3. Map each point through transform (to a Gaussian with jax.scipy.special.ndtri, say), evaluate f, average per shift, then over shifts.

Parameters:

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

The integrand f, applied to one (transformed) point.

required
dim int

The dimension D ≥ 1 (Sobol: at most 64).

required
n int

The number of points per shift, n ≥ 1.

required
sequence Literal['sobol', 'halton']

"sobol" or "halton".

'sobol'
n_shifts int

The number of random shifts R ≥ 2.

16
transform Callable[[Array], PyTree] | None

Maps a point u ∈ [0, 1)^D to the integration space T(u); the identity when None.

None
key PRNGKeyArray

The PRNG key for the shifts.

required

Returns:

Type Description
Expectation

The Expectation, with S = n R evaluations.

Raises:

Type Description
ValidationError

If dim, n or n_shifts is out of range, or sequence is unknown.

References

Owen, A. B. (2013). Monte Carlo theory, methods and examples, ch. 17 (randomised quasi-Monte Carlo).

Examples:

>>> import jax
>>> import jax.numpy as jnp
>>> cosine = lambda u: jnp.prod(jnp.cos(u))
>>> estimate = qmc(cosine, 3, 256, key=jax.random.key(0))
>>> bool(
...     abs(estimate.value - jnp.sin(1.0) ** 3)
...     < 4 * estimate.standard_error
... )
True
Source code in src/integrix/_src/expect/_expectation.py
def qmc(
    fn: Callable[[Array], Array],
    dim: int,
    n: int,
    *,
    sequence: Literal["sobol", "halton"] = "sobol",
    n_shifts: int = 16,
    transform: Callable[[Array], PyTree] | None = None,
    key: PRNGKeyArray,
) -> Expectation:
    """Randomised quasi-Monte Carlo over [0, 1)^D, with an error from random shifts.

    Î = (1/R) ∑ᵣ Îᵣ, where Îᵣ = (1/n) ∑ᵢ f(T(uᵢ ⊕ Δᵣ)) averages over the
    low-discrepancy points uᵢ shifted by the r-th random shift Δᵣ, and
    σ̂ = sᵣ / √R from the spread of the R shifted estimates. For a smooth
    integrand the error falls faster than S^{−1/2}. An unshifted sequence has
    no error estimate, so R ≥ 2.

    Algorithm:
        1. The first n points of the Sobol (Joe–Kuo, Gray-code order, n a
           power of two is best) or Halton sequence in D dimensions.
        2. R random shifts from one key: a digital shift (XOR of 32-bit
           integers) for Sobol, a rotation (uᵢ + Δᵣ) mod 1 for Halton.
        3. Map each point through ``transform`` (to a Gaussian with
           `jax.scipy.special.ndtri`, say), evaluate f, average per shift,
           then over shifts.

    Args:
        fn: The integrand f, applied to one (transformed) point.
        dim: The dimension D ≥ 1 (Sobol: at most 64).
        n: The number of points per shift, n ≥ 1.
        sequence: ``"sobol"`` or ``"halton"``.
        n_shifts: The number of random shifts R ≥ 2.
        transform: Maps a point u ∈ [0, 1)^D to the integration space T(u);
            the identity when ``None``.
        key: The PRNG key for the shifts.

    Returns:
        The `Expectation`, with S = n R evaluations.

    Raises:
        ValidationError: If ``dim``, ``n`` or ``n_shifts`` is out of range, or
            ``sequence`` is unknown.

    References:
        Owen, A. B. (2013). Monte Carlo theory, methods and examples, ch. 17
        (randomised quasi-Monte Carlo).

    Examples:
        >>> import jax
        >>> import jax.numpy as jnp
        >>> cosine = lambda u: jnp.prod(jnp.cos(u))
        >>> estimate = qmc(cosine, 3, 256, key=jax.random.key(0))
        >>> bool(
        ...     abs(estimate.value - jnp.sin(1.0) ** 3)
        ...     < 4 * estimate.standard_error
        ... )
        True
    """
    for name, value, smallest in (
        ("dim", dim, 1),
        ("n", n, 1),
        ("n_shifts", n_shifts, 2),
    ):
        if isinstance(value, bool) or not isinstance(value, int) or value < smallest:
            raise ValidationError(
                f"'{name}' must be an integer of at least {smallest}, got {value!r}"
            )
    dtype = jnp.result_type(float)
    if sequence == "sobol":
        integers = jnp.asarray(sobol_integers(n, dim))
        # a digital shift per replicate: uᵢ ⊕ Δᵣ, bit by bit
        shifts = jax.random.bits(key, (n_shifts, dim), dtype=jnp.uint32)
        tiled_points = einx.id("i d -> r i d", integers, r=n_shifts)
        tiled_shifts = einx.id("r d -> r i d", shifts, i=n)
        shifted = jnp.bitwise_xor(tiled_points, tiled_shifts)
        # keep p leading bits (23 in float32, 32 in float64) so the midpoint
        # of the top 2^{−p} cell, 1 − 2^{−p−1}, is a float below 1: no point is
        # 0 or 1
        precision = min(SOBOL_BITS, jnp.finfo(dtype).nmant)
        leading = shifted >> jnp.uint32(SOBOL_BITS - precision)
        points = (leading.astype(dtype) + 0.5) / 2.0**precision
    elif sequence == "halton":
        base = jnp.asarray(halton_points(n, dim), dtype=dtype)
        shifts = jax.random.uniform(key, (n_shifts, dim), dtype=dtype)
        # a Cranley–Patterson rotation: (uᵢ + Δᵣ) mod 1
        rotated = jnp.mod(einx.add("i d, r d -> r i d", base, shifts), 1.0)
        # (u + Δ) can round onto 1, which mod sends to 0: keep inside (0, 1)
        half_eps = 0.5 * jnp.finfo(dtype).eps
        points = jnp.clip(rotated, half_eps, 1.0 - half_eps)
    else:
        raise ValidationError(
            f"'sequence' must be 'sobol' or 'halton', got {sequence!r}"
        )

    def evaluate(point: Array) -> Array:
        mapped = point if transform is None else transform(point)
        return jnp.asarray(fn(mapped))

    values = _as_float(jax.vmap(jax.vmap(evaluate))(points))
    # Îᵣ = (1/n) ∑ᵢ fᵣᵢ, one estimate per shift
    per_shift = jax.vmap(lambda shift_values: pairwise_sum(shift_values) / n)(values)
    value, standard_error = _mean_and_error(per_shift)
    return Expectation(
        value=value, standard_error=standard_error, n_samples=n * n_shifts
    )

compute_psi_statistics

compute_psi_statistics(kernel: object, state: GaussianState, X_train: Float[Array, 'M D'], *, integrator: AbstractIntegrator | None = None) -> tuple[Float[Array, ''], Float[Array, ' M'], Float[Array, 'M M']]

Compute Ψ statistics, dispatching to analytical or numerical.

Ψ₀ = 𝔼[k(x, x)]
Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)],    x ~ 𝒩(μ_x, Σ_x)

If kernel implements AnalyticalPsiStatistics, uses the closed-form methods and ignores integrator. Otherwise, falls back to numerical integration via the provided integrator, with kernel called as k(x, x′).

Parameters:

Name Type Description Default
kernel object

Kernel object, optionally implementing AnalyticalPsiStatistics.

required
state GaussianState

Input Gaussian 𝒩(μ_x, Σ_x).

required
X_train Float[Array, 'M D']

Training or inducing inputs, whose rows are the xᵢ.

required
integrator AbstractIntegrator | None

Numerical integrator for fallback. Required if kernel does not implement analytical Ψ statistics.

None

Returns:

Type Description
tuple[Float[Array, ''], Float[Array, ' M'], Float[Array, 'M M']]

Tuple (Ψ₀, Ψ₁, Ψ₂) of Ψ statistics.

Raises:

Type Description
ValidationError

If kernel has no analytical Ψ statistics and no integrator is provided (also a ValueError).

Examples:

A plain callable falls back to the integrator:

>>> import jax.numpy as jnp
>>> import lineax as lx
>>> import gaussx_infer
>>> covariance = lx.DiagonalLinearOperator(jnp.ones(2))
>>> state = gaussx_infer.GaussianState(jnp.zeros(2), covariance)
>>> X_train = jnp.zeros((3, 2))
>>> kernel = lambda x, x_prime: jnp.ones(())
>>> rule = gaussx_infer.CubatureIntegrator()
>>> _, psi_1, psi_2 = compute_psi_statistics(
...     kernel, state, X_train, integrator=rule
... )
>>> psi_1.shape, psi_2.shape
((3,), (3, 3))

And fails without one:

>>> compute_psi_statistics(kernel, state, X_train)
...
Traceback (most recent call last):
...
integrix.exceptions.ValidationError: Kernel does not implement
AnalyticalPsiStatistics and no integrator was provided. Either implement
the protocol on the kernel or pass an integrator for numerical
computation.
Source code in src/integrix/_src/expect/_kernel_expectations.py
def compute_psi_statistics(
    kernel: object,
    state: GaussianState,
    X_train: Float[Array, "M D"],
    *,
    integrator: AbstractIntegrator | None = None,
) -> tuple[Float[Array, ""], Float[Array, " M"], Float[Array, "M M"]]:
    """Compute Ψ statistics, dispatching to analytical or numerical.

        Ψ₀ = 𝔼[k(x, x)]
        Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
        Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)],    x ~ 𝒩(μ_x, Σ_x)

    If ``kernel`` implements `AnalyticalPsiStatistics`, uses the closed-form
    methods and ignores ``integrator``. Otherwise, falls back to numerical
    integration via the provided integrator, with ``kernel`` called as k(x, x′).

    Args:
        kernel: Kernel object, optionally implementing
            `AnalyticalPsiStatistics`.
        state: Input Gaussian 𝒩(μ_x, Σ_x).
        X_train: Training or inducing inputs, whose rows are the xᵢ.
        integrator: Numerical integrator for fallback. Required if ``kernel``
            does not implement analytical Ψ statistics.

    Returns:
        Tuple ``(Ψ₀, Ψ₁, Ψ₂)`` of Ψ statistics.

    Raises:
        ValidationError: If ``kernel`` has no analytical Ψ statistics and no
            integrator is provided (also a `ValueError`).

    Examples:
        A plain callable falls back to the integrator:

        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> import gaussx_infer
        >>> covariance = lx.DiagonalLinearOperator(jnp.ones(2))
        >>> state = gaussx_infer.GaussianState(jnp.zeros(2), covariance)
        >>> X_train = jnp.zeros((3, 2))
        >>> kernel = lambda x, x_prime: jnp.ones(())
        >>> rule = gaussx_infer.CubatureIntegrator()
        >>> _, psi_1, psi_2 = compute_psi_statistics(
        ...     kernel, state, X_train, integrator=rule
        ... )
        >>> psi_1.shape, psi_2.shape
        ((3,), (3, 3))

        And fails without one:

        >>> compute_psi_statistics(kernel, state, X_train)
        ... # doctest: +NORMALIZE_WHITESPACE
        Traceback (most recent call last):
        ...
        integrix.exceptions.ValidationError: Kernel does not implement
        AnalyticalPsiStatistics and no integrator was provided. Either implement
        the protocol on the kernel or pass an integrator for numerical
        computation.
    """
    if isinstance(kernel, AnalyticalPsiStatistics):
        # Ψ₀ = 𝔼[k(x, x)]
        psi0 = kernel.psi0(state)
        # Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
        psi1 = kernel.psi1(state, X_train)
        # Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)]
        psi2 = kernel.psi2(state, X_train)
        return psi0, psi1, psi2

    if integrator is None:
        msg = (
            "Kernel does not implement AnalyticalPsiStatistics and no "
            "integrator was provided. Either implement the protocol on "
            "the kernel or pass an integrator for numerical computation."
        )
        raise ValidationError(msg)

    # --- numerical fallback: one implementation, `kernel_expectations` ---
    kernel_fn = cast(Callable, kernel)
    return kernel_expectations(kernel_fn, state, X_train, integrator)

kernel_expectations

kernel_expectations(kernel_fn: Callable[[Float[Array, ' D'], Float[Array, ' D']], Float[Array, '']], state: GaussianState, X_train: Float[Array, 'N_train D'], integrator: AbstractIntegrator) -> tuple[Float[Array, ''], Float[Array, ' N_train'], Float[Array, 'N_train N_train']]

Kernel expectations Ψ₀, Ψ₁ and Ψ₂ for an uncertain input.

Ψ₀ = 𝔼[k(x, x)]
Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)],    x ~ 𝒩(μ_x, Σ_x)

These are the core quantities for GP inference with uncertain inputs. For a point-based rule with points χₚ and mean weights wₚ they are computed directly from the kernel evaluations K_pi = k(χₚ, xᵢ):

Ψ₀ = ∑ₚ wₚ k(χₚ, χₚ)
Ψ₁ᵢ = ∑ₚ wₚ K_pi
Ψ₂ᵢⱼ = ∑ₚ wₚ K_pi K_pj

so no N² × N² output covariance or per-point outer product is ever built. Integrators without points (e.g. Taylor) go through gaussx_infer.mean_expectation on the flattened outer product.

Algorithm
  1. Ask the rule for its points χₚ and mean weights wₚ.
  2. With points, evaluate k on them once and take the weighted sums.
  3. Without points, take gaussx_infer.mean_expectation of k(x, x), of the kernel row and of its flattened outer product.

Parameters:

Name Type Description Default
kernel_fn Callable[[Float[Array, ' D'], Float[Array, ' D']], Float[Array, '']]

Kernel k(x, x′), scalar-valued.

required
state GaussianState

Uncertain input 𝒩(μ_x, Σ_x).

required
X_train Float[Array, 'N_train D']

Training inputs X, whose rows are the xᵢ.

required
integrator AbstractIntegrator

A gaussx integration rule.

required

Returns:

Type Description
tuple[Float[Array, ''], Float[Array, ' N_train'], Float[Array, 'N_train N_train']]

Tuple (Ψ₀, Ψ₁, Ψ₂) of Ψ statistics.

Examples:

A constant kernel has Ψ₀ = 1 and all-ones Ψ₁ and Ψ₂:

>>> import jax.numpy as jnp
>>> import lineax as lx
>>> import gaussx_infer
>>> covariance = lx.DiagonalLinearOperator(jnp.ones(2))
>>> state = gaussx_infer.GaussianState(jnp.zeros(2), covariance)
>>> X_train = jnp.zeros((3, 2))
>>> kernel_fn = lambda x, x_prime: jnp.ones(())
>>> rule = gaussx_infer.CubatureIntegrator()
>>> psi_0, psi_1, psi_2 = kernel_expectations(
...     kernel_fn, state, X_train, rule
... )
>>> bool(jnp.allclose(psi_0, 1.0)), psi_1.shape, psi_2.shape
(True, (3,), (3, 3))

A rule without points returns the same shapes:

>>> taylor = gaussx_infer.TaylorIntegrator()
>>> _, psi_1, psi_2 = kernel_expectations(kernel_fn, state, X_train, taylor)
>>> psi_1.shape, psi_2.shape
((3,), (3, 3))
Source code in src/integrix/_src/expect/_kernel_expectations.py
def kernel_expectations(
    kernel_fn: Callable[[Float[Array, " D"], Float[Array, " D"]], Float[Array, ""]],
    state: GaussianState,
    X_train: Float[Array, "N_train D"],
    integrator: AbstractIntegrator,
) -> tuple[Float[Array, ""], Float[Array, " N_train"], Float[Array, "N_train N_train"]]:
    """Kernel expectations Ψ₀, Ψ₁ and Ψ₂ for an uncertain input.

        Ψ₀ = 𝔼[k(x, x)]
        Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
        Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)],    x ~ 𝒩(μ_x, Σ_x)

    These are the core quantities for GP inference with uncertain inputs. For
    a point-based rule with points χₚ and mean weights wₚ they are computed
    directly from the kernel evaluations K_pi = k(χₚ, xᵢ):

        Ψ₀ = ∑ₚ wₚ k(χₚ, χₚ)
        Ψ₁ᵢ = ∑ₚ wₚ K_pi
        Ψ₂ᵢⱼ = ∑ₚ wₚ K_pi K_pj

    so no N² × N² output covariance or per-point outer product is ever built.
    Integrators without points (e.g. Taylor) go through `gaussx_infer.mean_expectation`
    on the flattened outer product.

    Algorithm:
        1. Ask the rule for its points χₚ and mean weights wₚ.
        2. With points, evaluate k on them once and take the weighted sums.
        3. Without points, take `gaussx_infer.mean_expectation` of k(x, x), of the
           kernel row and of its flattened outer product.

    Args:
        kernel_fn: Kernel k(x, x′), scalar-valued.
        state: Uncertain input 𝒩(μ_x, Σ_x).
        X_train: Training inputs X, whose rows are the xᵢ.
        integrator: A gaussx integration rule.

    Returns:
        Tuple ``(Ψ₀, Ψ₁, Ψ₂)`` of Ψ statistics.

    Examples:
        A constant kernel has Ψ₀ = 1 and all-ones Ψ₁ and Ψ₂:

        >>> import jax.numpy as jnp
        >>> import lineax as lx
        >>> import gaussx_infer
        >>> covariance = lx.DiagonalLinearOperator(jnp.ones(2))
        >>> state = gaussx_infer.GaussianState(jnp.zeros(2), covariance)
        >>> X_train = jnp.zeros((3, 2))
        >>> kernel_fn = lambda x, x_prime: jnp.ones(())
        >>> rule = gaussx_infer.CubatureIntegrator()
        >>> psi_0, psi_1, psi_2 = kernel_expectations(
        ...     kernel_fn, state, X_train, rule
        ... )
        >>> bool(jnp.allclose(psi_0, 1.0)), psi_1.shape, psi_2.shape
        (True, (3,), (3, 3))

        A rule without points returns the same shapes:

        >>> taylor = gaussx_infer.TaylorIntegrator()
        >>> _, psi_1, psi_2 = kernel_expectations(kernel_fn, state, X_train, taylor)
        >>> psi_1.shape, psi_2.shape
        ((3,), (3, 3))
    """

    def kernel_row(x: Float[Array, " D"]) -> Float[Array, " N_train"]:
        def kernel_at_input(x_train: Float[Array, " D"]) -> Float[Array, ""]:
            return kernel_fn(x, x_train)

        # k(x, xᵢ)
        return jax.vmap(kernel_at_input)(X_train)

    def kernel_self(x: Float[Array, " D"]) -> Float[Array, ""]:
        return kernel_fn(x, x)

    # The patterns that an empty X_train reaches keep their axis names: einx
    # prints the pattern in its AxisSizeError.
    rule = _points_and_weights_or_none(integrator, state)
    if rule is not None:
        points, mean_weights, _ = rule
        # k(χₚ, χₚ)
        self_kernels = jax.vmap(kernel_self)(points)
        # K_pi = k(χₚ, xᵢ)
        kernel_rows = jax.vmap(kernel_row)(points)
        # Ψ₀ = ∑ₚ wₚ k(χₚ, χₚ)
        self_kernel_mean = einx.dot("p, p ->", mean_weights, self_kernels)
        # Ψ₁ᵢ = ∑ₚ wₚ K_pi
        cross_kernel_mean = einx.dot("p, p i -> i", mean_weights, kernel_rows)
        # wₚ K_pi
        weighted_rows = einx.multiply("p, p i -> p i", mean_weights, kernel_rows)
        # Ψ₂ᵢⱼ = ∑ₚ wₚ K_pi K_pj
        kernel_outer_mean = einx.dot(
            "p row, p col -> row col", weighted_rows, kernel_rows
        )
        return self_kernel_mean, cross_kernel_mean, kernel_outer_mean

    def vector_kernel_self(x: Float[Array, " D"]) -> Float[Array, " 1"]:
        return jnp.atleast_1d(kernel_fn(x, x))

    # Ψ₀ = 𝔼[k(x, x)]
    self_kernel_expectation = mean_expectation(vector_kernel_self, state, integrator)
    self_kernel_mean = self_kernel_expectation[0]

    # Ψ₁ᵢ = 𝔼[k(x, xᵢ)]
    cross_kernel_mean = mean_expectation(kernel_row, state, integrator)

    train_size = X_train.shape[0]

    def flat_kernel_outer(x: Float[Array, " D"]) -> Float[Array, " NN"]:
        # k(x, xᵢ)
        row = kernel_row(x)
        # k(x, xᵢ) k(x, xⱼ)
        outer = jnp.outer(row, row)
        return einx.id("row col -> (row col)", outer)

    # Ψ₂ᵢⱼ = 𝔼[k(x, xᵢ) k(x, xⱼ)], flattened
    flat_outer_mean = mean_expectation(flat_kernel_outer, state, integrator)
    kernel_outer_mean = einx.id(
        "(row col) -> row col", flat_outer_mean, row=train_size, col=train_size
    )

    return self_kernel_mean, cross_kernel_mean, kernel_outer_mean

log_gauss_hermite

log_gauss_hermite(log_fn: Callable[[Array], Array], mean: ArrayLike, std: ArrayLike, *, n: int = 32) -> Float[Array, '*out']

log 𝔼[f(Q)] for a lognormal Q, by Gauss–Hermite quadrature in log Q.

log Q is normal with mean μ and variance σ². With qₖ = exp(μ + √2 σ xₖ) at the Hermite nodes xₖ of weight e^(−x²), log 𝔼[f(Q)] ≈ logsumexp over k of (log wₖ − ½ log π + log f(qₖ)), so f never leaves log space. The rule is exact when f is a polynomial in log q of degree at most 2n − 1, and gives log 𝔼[Qᵃ] = aμ + a²σ²/2 to rounding for moderate aσ.

Algorithm
  1. The Hermite nodes xₖ and weights wₖ on the host (static n).
  2. The rates qₖ = exp(μ + √2 σ xₖ), node axis first, batched over the broadcast shape of μ and σ.
  3. integrix.rule.log_integrate with weights wₖ/√π.

Parameters:

Name Type Description Default
log_fn Callable[[Array], Array]

log f, applied to the rates (node axis first) and returning the node axis first.

required
mean ArrayLike

μ, the mean of log Q; broadcasts against std.

required
std ArrayLike

σ > 0, the standard deviation of log Q.

required
n int

The number of Hermite nodes, at least 1.

32

Returns:

Type Description
Float[Array, '*out']

log 𝔼[f(Q)], with the broadcast shape of μ and σ followed by any

Float[Array, '*out']

output axes of f.

Raises:

Type Description
ValidationError

If n is not an integer of at least 1.

Examples:

>>> import jax.numpy as jnp
>>> # log 𝔼[Q] = μ + σ²/2
>>> value = log_gauss_hermite(jnp.log, 0.2, 0.5)
>>> bool(jnp.allclose(value, 0.2 + 0.5 * 0.5**2))
True

A batch of (μ, σ) at once:

>>> means = jnp.array([0.0, 1.0])
>>> log_gauss_hermite(jnp.log, means, 0.3).shape
(2,)
References

Golub, G. H. & Welsch, J. H. (1969). Calculation of Gauss quadrature rules. Math. Comp. 23, 221–230.

Source code in src/integrix/_src/expect/_log.py
def log_gauss_hermite(
    log_fn: Callable[[Array], Array],
    mean: ArrayLike,
    std: ArrayLike,
    *,
    n: int = 32,
) -> Float[Array, "*out"]:
    """log 𝔼[f(Q)] for a lognormal Q, by Gauss–Hermite quadrature in log Q.

    log Q is normal with mean μ and variance σ². With qₖ = exp(μ + √2 σ xₖ)
    at the Hermite nodes xₖ of weight e^(−x²), log 𝔼[f(Q)] ≈ logsumexp over k
    of (log wₖ − ½ log π + log f(qₖ)), so f never leaves log space. The rule
    is exact when f is a polynomial in log q of degree at most 2n − 1, and
    gives log 𝔼[Qᵃ] = aμ + a²σ²/2 to rounding for moderate aσ.

    Algorithm:
        1. The Hermite nodes xₖ and weights wₖ on the host (static n).
        2. The rates qₖ = exp(μ + √2 σ xₖ), node axis first, batched over the
           broadcast shape of μ and σ.
        3. `integrix.rule.log_integrate` with weights wₖ/√π.

    Args:
        log_fn: log f, applied to the rates (node axis first) and returning
            the node axis first.
        mean: μ, the mean of log Q; broadcasts against ``std``.
        std: σ > 0, the standard deviation of log Q.
        n: The number of Hermite nodes, at least 1.

    Returns:
        log 𝔼[f(Q)], with the broadcast shape of μ and σ followed by any
        output axes of f.

    Raises:
        ValidationError: If ``n`` is not an integer of at least 1.

    Examples:
        >>> import jax.numpy as jnp
        >>> # log 𝔼[Q] = μ + σ²/2
        >>> value = log_gauss_hermite(jnp.log, 0.2, 0.5)
        >>> bool(jnp.allclose(value, 0.2 + 0.5 * 0.5**2))
        True

        A batch of (μ, σ) at once:

        >>> means = jnp.array([0.0, 1.0])
        >>> log_gauss_hermite(jnp.log, means, 0.3).shape
        (2,)

    References:
        Golub, G. H. & Welsch, J. H. (1969). Calculation of Gauss quadrature
        rules. Math. Comp. 23, 221–230.
    """
    count = _count(n, smallest=1)
    reference_nodes, reference_weights = np.polynomial.hermite.hermgauss(count)
    # μ and σ broadcast to one batch shape
    mean, std = jnp.broadcast_arrays(jnp.asarray(mean), jnp.asarray(std))
    dtype = jnp.result_type(mean, std, float)
    # xₖ and wₖ/√π, in the inputs' precision
    nodes = jnp.asarray(reference_nodes, dtype=dtype)
    weights = jnp.asarray(reference_weights / math.sqrt(math.pi), dtype=dtype)
    # √2 σ
    spread = math.sqrt(2.0) * std
    # √2 σ xₖ, node axis first
    offsets = einx.multiply("n, ... -> n ...", nodes, spread)
    # uₖ = μ + √2 σ xₖ
    log_rates = einx.add("n ..., ... -> n ...", offsets, mean)
    # qₖ = e^uₖ
    rates = jnp.exp(log_rates)
    # log 𝔼[f(Q)] = logsumexp over k of (log(wₖ/√π) + log f(qₖ))
    return log_integrate(weights, log_fn(rates), axis=0)

log_simpson

log_simpson(log_fn: Callable[[Array], Array], lower: float, upper: float, *, n: int = 2001) -> Float[Array, '*out']

log ∫ₐᵇ f(q) dq by composite Simpson on a uniform grid in u = log q.

∫ₐᵇ f(q) dq = ∫ from log a to log b of f(eᵘ) eᵘ du, and with the Simpson weights wₖ on a uniform u grid, log ∫ ≈ logsumexp over k of (log wₖ + log f(e^uₖ) + uₖ). A uniform grid in log q resolves a lognormal body and a power-law tail alike, which a uniform grid in q cannot.

Algorithm
  1. A uniform grid uₖ on [log a, log b] with an odd number of nodes, and Simpson's weights (h/3)(1, 4, 2, …, 4, 1) from functax.quad.simpson.
  2. integrix.rule.log_integrate with those weights on log f(e^uₖ) + uₖ.

Parameters:

Name Type Description Default
log_fn Callable[[Array], Array]

log f, applied to the rates e^uₖ (node axis first) and returning the node axis first.

required
lower float

a > 0, the lower limit.

required
upper float

b > a, the upper limit.

required
n int

The number of nodes, at least 3; an even count is raised by one, since Simpson's rule needs an even number of intervals.

2001

Returns:

Type Description
Float[Array, '*out']

log ∫ₐᵇ f(q) dq, with any output axes of f.

Raises:

Type Description
ValidationError

If n is not an integer of at least 3, or the limits are not 0 < a < b.

Examples:

>>> import jax.numpy as jnp
>>> # ∫₁^∞ 3 q⁻⁴ dq = 1, truncated at 10⁶
>>> value = log_simpson(lambda q: jnp.log(3.0) - 4.0 * jnp.log(q), 1.0, 1e6)
>>> bool(jnp.abs(value) < 1e-6)
True
>>> # ∫₁ᵉ dq/q = 1
>>> bool(jnp.allclose(log_simpson(lambda q: -jnp.log(q), 1.0, jnp.e), 0.0))
True
Source code in src/integrix/_src/expect/_log.py
def log_simpson(
    log_fn: Callable[[Array], Array],
    lower: float,
    upper: float,
    *,
    n: int = 2001,
) -> Float[Array, "*out"]:
    """log ∫ₐᵇ f(q) dq by composite Simpson on a uniform grid in u = log q.

    ∫ₐᵇ f(q) dq = ∫ from log a to log b of f(eᵘ) eᵘ du, and with the Simpson
    weights wₖ on a uniform u grid, log ∫ ≈ logsumexp over k of
    (log wₖ + log f(e^uₖ) + uₖ). A uniform grid in log q resolves a lognormal
    body and a power-law tail alike, which a uniform grid in q cannot.

    Algorithm:
        1. A uniform grid uₖ on [log a, log b] with an odd number of nodes,
           and Simpson's weights (h/3)(1, 4, 2, …, 4, 1) from
           ``functax.quad.simpson``.
        2. `integrix.rule.log_integrate` with those weights on
           log f(e^uₖ) + uₖ.

    Args:
        log_fn: log f, applied to the rates e^uₖ (node axis first) and
            returning the node axis first.
        lower: a > 0, the lower limit.
        upper: b > a, the upper limit.
        n: The number of nodes, at least 3; an even count is raised by one,
            since Simpson's rule needs an even number of intervals.

    Returns:
        log ∫ₐᵇ f(q) dq, with any output axes of f.

    Raises:
        ValidationError: If ``n`` is not an integer of at least 3, or the
            limits are not 0 < a < b.

    Examples:
        >>> import jax.numpy as jnp
        >>> # ∫₁^∞ 3 q⁻⁴ dq = 1, truncated at 10⁶
        >>> value = log_simpson(lambda q: jnp.log(3.0) - 4.0 * jnp.log(q), 1.0, 1e6)
        >>> bool(jnp.abs(value) < 1e-6)
        True
        >>> # ∫₁ᵉ dq/q = 1
        >>> bool(jnp.allclose(log_simpson(lambda q: -jnp.log(q), 1.0, jnp.e), 0.0))
        True
    """
    count = _count(n, smallest=3)
    # Simpson needs an even number of intervals
    count = count if count % 2 == 1 else count + 1
    lower, upper = float(lower), float(upper)
    if not (0.0 < lower < upper and math.isfinite(upper)):
        raise ValidationError(
            f"'lower' and 'upper' must satisfy 0 < lower < upper < ∞, got "
            f"({lower}, {upper})"
        )
    # uₖ, uniform in log q
    grid = np.linspace(math.log(lower), math.log(upper), count)
    log_grid = jnp.asarray(grid, dtype=jnp.result_type(float))
    # (h/3)(1, 4, 2, …, 4, 1), functax's composite Simpson rule on the grid
    weights = functax_quad.simpson(log_grid).weights
    # log f(e^uₖ) + uₖ: the Jacobian dq = eᵘ du
    log_values = einx.add("n ..., n -> n ...", log_fn(jnp.exp(log_grid)), log_grid)
    return log_integrate(weights, log_values, axis=0)

resample_conditional

resample_conditional(key: PRNGKeyArray, log_weights: Float[ArrayLike, ' sample'], num_samples: int, *, keep: Int[ArrayLike, ''], slot: Int[ArrayLike, ''] = 0, scheme: Literal['multinomial'] = 'multinomial') -> Int[Array, ' num_samples']

Conditional resampling: ancestor keep at slot, the rest drawn.

Particle Gibbs holds one reference trajectory fixed across resampling. The returned ancestors satisfy a[slot] = keep, and the other M − 1 are drawn i.i.d. from Cat(W), W = softmax(log w), which is the exact conditional of multinomial resampling given that one ancestor (Chopin & Singh, 2015). Only the multinomial base is implemented; a systematic base needs the conditional uniform of Chopin & Singh, §3.

Parameters:

Name Type Description Default
key PRNGKeyArray

A JAX PRNG key.

required
log_weights Float[ArrayLike, ' sample']

Unnormalised log weights log wₖ, one per sample.

required
num_samples int

The number M of ancestors to draw (a static int).

required
keep Int[ArrayLike, '']

The ancestor index held fixed.

required
slot Int[ArrayLike, '']

The position at which keep is placed.

0
scheme Literal['multinomial']

The base scheme; only "multinomial".

'multinomial'

Returns:

Type Description
Int[Array, ' num_samples']

Ancestor indices in [0, N) with keep at slot. They are not

Int[Array, ' num_samples']

sorted.

Raises:

Type Description
ValidationError

If log_weights is not a vector, num_samples is not positive or scheme is not "multinomial".

EquinoxRuntimeError

If keep is outside [0, N) or slot outside [0, M) (checked with eqx.error_if, so traced values are checked too).

Examples:

>>> import jax, jax.numpy as jnp
>>> ancestors = resample_conditional(
...     jax.random.key(0), jnp.zeros(5), 5, keep=3, slot=2
... )
>>> int(ancestors[2])
3
Source code in src/integrix/_src/expect/_resampling.py
def resample_conditional(
    key: PRNGKeyArray,
    log_weights: Float[ArrayLike, " sample"],
    num_samples: int,
    *,
    keep: Int[ArrayLike, ""],
    slot: Int[ArrayLike, ""] = 0,
    scheme: Literal["multinomial"] = "multinomial",
) -> Int[Array, " num_samples"]:
    """Conditional resampling: ancestor ``keep`` at ``slot``, the rest drawn.

    Particle Gibbs holds one reference trajectory fixed across resampling.
    The returned ancestors satisfy a[slot] = keep, and the other M − 1 are
    drawn i.i.d. from Cat(W), W = softmax(log w), which is the exact
    conditional of multinomial resampling given that one ancestor (Chopin &
    Singh, 2015). Only the multinomial base is implemented; a systematic
    base needs the conditional uniform of Chopin & Singh, §3.

    Args:
        key: A JAX PRNG key.
        log_weights: Unnormalised log weights log wₖ, one per sample.
        num_samples: The number M of ancestors to draw (a static int).
        keep: The ancestor index held fixed.
        slot: The position at which ``keep`` is placed.
        scheme: The base scheme; only ``"multinomial"``.

    Returns:
        Ancestor indices in [0, N) with ``keep`` at ``slot``. They are not
        sorted.

    Raises:
        ValidationError: If ``log_weights`` is not a vector, ``num_samples``
            is not positive or ``scheme`` is not ``"multinomial"``.
        EquinoxRuntimeError: If ``keep`` is outside [0, N) or ``slot`` outside
            [0, M) (checked with ``eqx.error_if``, so traced values are
            checked too).

    Examples:
        >>> import jax, jax.numpy as jnp
        >>> ancestors = resample_conditional(
        ...     jax.random.key(0), jnp.zeros(5), 5, keep=3, slot=2
        ... )
        >>> int(ancestors[2])
        3
    """
    if scheme != "multinomial":
        raise ValidationError(
            f"'scheme' must be 'multinomial', got {scheme!r}; a systematic "
            "conditional resampler is not implemented"
        )
    log_weights = _as_log_weight_vector(log_weights)
    _check_num_samples(num_samples)
    size = log_weights.shape[0]
    keep = jnp.asarray(keep, dtype=jnp.int32)
    slot = jnp.asarray(slot, dtype=jnp.int32)
    # an out-of-range keep would insert an invalid index, and an out-of-range
    # slot would drop the update silently; both may be traced
    keep = eqx.error_if(
        keep, (keep < 0) | (keep >= size), f"'keep' must be in [0, {size})"
    )
    slot = eqx.error_if(
        slot,
        (slot < 0) | (slot >= num_samples),
        f"'slot' must be in [0, {num_samples})",
    )
    # M i.i.d. draws, unsorted so the draws carry no information about the slot
    uniforms = jax.random.uniform(key, (num_samples,), dtype=log_weights.dtype)
    ancestors = _inverse_cdf(log_weights, uniforms)
    return ancestors.at[slot].set(keep)

resample_multinomial

resample_multinomial(key: PRNGKeyArray, log_weights: Float[ArrayLike, ' sample'], num_samples: int) -> Int[Array, ' num_samples']

Multinomial resampling: M i.i.d. draws aᵐ ~ Cat(W), W = softmax(log w).

Drawn as F⁻¹ of M sorted uniforms, so the copies (O₁, …, O_N) are multinomial with 𝔼[Oₖ] = M Wₖ and 𝕍[Oₖ] = M Wₖ(1 − Wₖ), the largest variance of the four schemes.

Parameters:

Name Type Description Default
key PRNGKeyArray

A JAX PRNG key.

required
log_weights Float[ArrayLike, ' sample']

Unnormalised log weights log wₖ, one per sample.

required
num_samples int

The number M of ancestors to draw (a static int).

required

Returns:

Type Description
Int[Array, ' num_samples']

Sorted ancestor indices in [0, N), one per new sample.

Raises:

Type Description
ValidationError

If log_weights is not a vector or num_samples is not positive.

Examples:

>>> import jax, jax.numpy as jnp
>>> log_w = jnp.array([0.0, -jnp.inf, 0.0])
>>> ancestors = resample_multinomial(jax.random.key(0), log_w, 6)
>>> bool((ancestors != 1).all())
True
Source code in src/integrix/_src/expect/_resampling.py
def resample_multinomial(
    key: PRNGKeyArray,
    log_weights: Float[ArrayLike, " sample"],
    num_samples: int,
) -> Int[Array, " num_samples"]:
    """Multinomial resampling: M i.i.d. draws aᵐ ~ Cat(W), W = softmax(log w).

    Drawn as F⁻¹ of M sorted uniforms, so the copies (O₁, …, O_N) are
    multinomial with 𝔼[Oₖ] = M Wₖ and 𝕍[Oₖ] = M Wₖ(1 − Wₖ), the largest
    variance of the four schemes.

    Args:
        key: A JAX PRNG key.
        log_weights: Unnormalised log weights log wₖ, one per sample.
        num_samples: The number M of ancestors to draw (a static int).

    Returns:
        Sorted ancestor indices in [0, N), one per new sample.

    Raises:
        ValidationError: If ``log_weights`` is not a vector or
            ``num_samples`` is not positive.

    Examples:
        >>> import jax, jax.numpy as jnp
        >>> log_w = jnp.array([0.0, -jnp.inf, 0.0])
        >>> ancestors = resample_multinomial(jax.random.key(0), log_w, 6)
        >>> bool((ancestors != 1).all())
        True
    """
    log_weights = _as_log_weight_vector(log_weights)
    _check_num_samples(num_samples)
    # uᵐ i.i.d. uniform on [0, 1), sorted so the ancestors come out sorted
    uniforms = jnp.sort(
        jax.random.uniform(key, (num_samples,), dtype=log_weights.dtype)
    )
    return _inverse_cdf(log_weights, uniforms)

resample_residual

resample_residual(key: PRNGKeyArray, log_weights: Float[ArrayLike, ' sample'], num_samples: int) -> Int[Array, ' num_samples']

Residual resampling: ⌊M Wₖ⌋ copies of each k, the rest multinomial.

The R = M − ∑ₖ ⌊M Wₖ⌋ remaining ancestors are drawn i.i.d. from the residual weights M Wₖ − ⌊M Wₖ⌋, so Oₖ ≥ ⌊M Wₖ⌋ and 𝔼[Oₖ] = M Wₖ. The output keeps a static length M: the deterministic copies come first, then the residual draws fill the remaining slots.

Parameters:

Name Type Description Default
key PRNGKeyArray

A JAX PRNG key.

required
log_weights Float[ArrayLike, ' sample']

Unnormalised log weights log wₖ, one per sample.

required
num_samples int

The number M of ancestors to draw (a static int).

required

Returns:

Type Description
Int[Array, ' num_samples']

Ancestor indices in [0, N), one per new sample.

Raises:

Type Description
ValidationError

If log_weights is not a vector or num_samples is not positive.

Examples:

>>> import jax, jax.numpy as jnp
>>> log_w = jnp.log(jnp.array([0.75, 0.25]))
>>> ancestors = resample_residual(jax.random.key(0), log_w, 4)
>>> sorted(ancestors.tolist())
[0, 0, 0, 1]
Source code in src/integrix/_src/expect/_resampling.py
def resample_residual(
    key: PRNGKeyArray,
    log_weights: Float[ArrayLike, " sample"],
    num_samples: int,
) -> Int[Array, " num_samples"]:
    """Residual resampling: ⌊M Wₖ⌋ copies of each k, the rest multinomial.

    The R = M − ∑ₖ ⌊M Wₖ⌋ remaining ancestors are drawn i.i.d. from the
    residual weights M Wₖ − ⌊M Wₖ⌋, so Oₖ ≥ ⌊M Wₖ⌋ and 𝔼[Oₖ] = M Wₖ. The
    output keeps a static length M: the deterministic copies come first,
    then the residual draws fill the remaining slots.

    Args:
        key: A JAX PRNG key.
        log_weights: Unnormalised log weights log wₖ, one per sample.
        num_samples: The number M of ancestors to draw (a static int).

    Returns:
        Ancestor indices in [0, N), one per new sample.

    Raises:
        ValidationError: If ``log_weights`` is not a vector or
            ``num_samples`` is not positive.

    Examples:
        >>> import jax, jax.numpy as jnp
        >>> log_w = jnp.log(jnp.array([0.75, 0.25]))
        >>> ancestors = resample_residual(jax.random.key(0), log_w, 4)
        >>> sorted(ancestors.tolist())
        [0, 0, 0, 1]
    """
    log_weights = _as_log_weight_vector(log_weights)
    _check_num_samples(num_samples)
    size = log_weights.shape[0]
    weights = _normalised(log_weights)
    # M Wₖ, split into ⌊M Wₖ⌋ deterministic copies and a residual
    scaled = num_samples * weights
    copies = jnp.floor(scaled)
    residual = scaled - copies
    num_copies = einx.sum("sample ->", copies).astype(jnp.int32)
    # the deterministic part, padded to M; slots ≥ ∑⌊M Wₖ⌋ are overwritten
    deterministic = jnp.repeat(
        jnp.arange(size), copies.astype(jnp.int32), total_repeat_length=num_samples
    )
    # R residual draws from Cat(residual / R); draw M and keep what is needed
    log_residual = jnp.where(residual > 0, jnp.log(residual), -jnp.inf)
    log_residual = jnp.where(
        jnp.isneginf(log_residual).all(), jnp.zeros_like(log_residual), log_residual
    )
    # unsorted, so the first R slots past the copies are an i.i.d. draw
    uniforms = jax.random.uniform(key, (num_samples,), dtype=log_weights.dtype)
    drawn = _inverse_cdf(log_residual, uniforms)
    # the draws fill slots ∑⌊M Wₖ⌋, …, M − 1
    drawn = jnp.roll(drawn, num_copies)
    slot = jnp.arange(num_samples)
    return jnp.where(slot < num_copies, deterministic, drawn)

resample_stratified

resample_stratified(key: PRNGKeyArray, log_weights: Float[ArrayLike, ' sample'], num_samples: int) -> Int[Array, ' num_samples']

Stratified resampling: aᵐ = F⁻¹((m − 1 + Uᵐ)/M), one Uᵐ per stratum.

F is the cumulative sum of W = softmax(log w). Each of the M strata [(m − 1)/M, m/M) gets its own uniform, so the number of copies of k is within 2 of M Wₖ and its mean is M Wₖ.

Parameters:

Name Type Description Default
key PRNGKeyArray

A JAX PRNG key.

required
log_weights Float[ArrayLike, ' sample']

Unnormalised log weights log wₖ, one per sample.

required
num_samples int

The number M of ancestors to draw (a static int).

required

Returns:

Type Description
Int[Array, ' num_samples']

Sorted ancestor indices in [0, N), one per new sample.

Raises:

Type Description
ValidationError

If log_weights is not a vector or num_samples is not positive.

Examples:

>>> import jax, jax.numpy as jnp
>>> log_w = jnp.log(jnp.array([0.5, 0.5, 0.0]))
>>> ancestors = resample_stratified(jax.random.key(0), log_w, 4)
>>> ancestors.tolist()
[0, 0, 1, 1]
Source code in src/integrix/_src/expect/_resampling.py
def resample_stratified(
    key: PRNGKeyArray,
    log_weights: Float[ArrayLike, " sample"],
    num_samples: int,
) -> Int[Array, " num_samples"]:
    """Stratified resampling: aᵐ = F⁻¹((m − 1 + Uᵐ)/M), one Uᵐ per stratum.

    F is the cumulative sum of W = softmax(log w). Each of the M strata
    [(m − 1)/M, m/M) gets its own uniform, so the number of copies of k is
    within 2 of M Wₖ and its mean is M Wₖ.

    Args:
        key: A JAX PRNG key.
        log_weights: Unnormalised log weights log wₖ, one per sample.
        num_samples: The number M of ancestors to draw (a static int).

    Returns:
        Sorted ancestor indices in [0, N), one per new sample.

    Raises:
        ValidationError: If ``log_weights`` is not a vector or
            ``num_samples`` is not positive.

    Examples:
        >>> import jax, jax.numpy as jnp
        >>> log_w = jnp.log(jnp.array([0.5, 0.5, 0.0]))
        >>> ancestors = resample_stratified(jax.random.key(0), log_w, 4)
        >>> ancestors.tolist()
        [0, 0, 1, 1]
    """
    log_weights = _as_log_weight_vector(log_weights)
    _check_num_samples(num_samples)
    dtype = log_weights.dtype
    # uᵐ = (m − 1 + Uᵐ) / M
    uniform = jax.random.uniform(key, (num_samples,), dtype=dtype)
    uniforms = (jnp.arange(num_samples, dtype=dtype) + uniform) / num_samples
    return _inverse_cdf(log_weights, uniforms)

resample_systematic

resample_systematic(key: PRNGKeyArray, log_weights: Float[ArrayLike, ' sample'], num_samples: int) -> Int[Array, ' num_samples']

Systematic resampling: aᵐ = F⁻¹((m − 1 + U)/M) with one U uniform on [0, 1).

F is the cumulative sum of the normalised weights W = softmax(log w). Each sample k is copied ⌊M Wₖ⌋ or ⌈M Wₖ⌉ times, and 𝔼[copies of k] = M Wₖ. One uniform for the whole cloud gives the lowest variance of the four schemes in most problems (Douc & Cappé, 2005).

Parameters:

Name Type Description Default
key PRNGKeyArray

A JAX PRNG key.

required
log_weights Float[ArrayLike, ' sample']

Unnormalised log weights log wₖ, one per sample. A weight of −∞ is never selected.

required
num_samples int

The number M of ancestors to draw (a static int).

required

Returns:

Type Description
Int[Array, ' num_samples']

Sorted ancestor indices in [0, N), one per new sample.

Raises:

Type Description
ValidationError

If log_weights is not a vector or num_samples is not positive.

Examples:

>>> import jax, jax.numpy as jnp
>>> ancestors = resample_systematic(jax.random.key(0), jnp.zeros(4), 4)
>>> ancestors.tolist()
[0, 1, 2, 3]
Source code in src/integrix/_src/expect/_resampling.py
def resample_systematic(
    key: PRNGKeyArray,
    log_weights: Float[ArrayLike, " sample"],
    num_samples: int,
) -> Int[Array, " num_samples"]:
    """Systematic resampling: aᵐ = F⁻¹((m − 1 + U)/M) with one U uniform on [0, 1).

    F is the cumulative sum of the normalised weights W = softmax(log w). Each
    sample k is copied ⌊M Wₖ⌋ or ⌈M Wₖ⌉ times, and 𝔼[copies of k] = M Wₖ. One
    uniform for the whole cloud gives the lowest variance of the four schemes
    in most problems (Douc & Cappé, 2005).

    Args:
        key: A JAX PRNG key.
        log_weights: Unnormalised log weights log wₖ, one per sample. A weight
            of −∞ is never selected.
        num_samples: The number M of ancestors to draw (a static int).

    Returns:
        Sorted ancestor indices in [0, N), one per new sample.

    Raises:
        ValidationError: If ``log_weights`` is not a vector or
            ``num_samples`` is not positive.

    Examples:
        >>> import jax, jax.numpy as jnp
        >>> ancestors = resample_systematic(jax.random.key(0), jnp.zeros(4), 4)
        >>> ancestors.tolist()
        [0, 1, 2, 3]
    """
    log_weights = _as_log_weight_vector(log_weights)
    _check_num_samples(num_samples)
    dtype = log_weights.dtype
    # uᵐ = (m − 1 + U) / M
    uniform = jax.random.uniform(key, (), dtype=dtype)
    uniforms = (jnp.arange(num_samples, dtype=dtype) + uniform) / num_samples
    return _inverse_cdf(log_weights, uniforms)