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′), whichIntegralOperatoruses 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,Truewhen k(x, x′) depends only on x − x′, which letsconvolutionuse 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
¶
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
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;
|
pareto_k |
Float[Array, ''] | None
|
The Pareto tail shape k̂ of the importance weights, when
|
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
¶
Compute Ψ₀ = 𝔼[k(x, x)].
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
GaussianState
|
Input Gaussian 𝒩(μ_x, Σ_x). |
required |
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
The scalar statistic Ψ₀. |
psi1
¶
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
psi2
¶
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
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;
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
EquinoxRuntimeError
|
If |
Examples:
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:
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
- K, z and the initial error ∬ k dΠ dΠ (
initial_error). - 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.
- 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 |
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
|
√𝕍[I ∣ g] (clipped at zero) and |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 | |
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
- A Gaussian or a box: the kernel's closed form when it defines the
matching method of
KernelLike. - An empirical measure, a sphere, or a Gaussian with a gaussx integrator: wᵀ K w over its points.
- 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 |
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
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
- A Gaussian or a box: the kernel's closed form when it defines the
matching method of
KernelLike(or, for a Gaussian,psi1ofAnalyticalPsiStatistics). - An empirical measure, a sphere, or a Gaussian with a gaussx integrator: the weighted sum over its points.
- 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 |
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
( |
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
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 | |
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 |
None
|
Returns:
| Type | Description |
|---|---|
Float[Array, '']
|
e(w), clipped at zero before the square root. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
effective_sample_size
¶
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 |
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
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
- Shift log w so its maximum is 0; with M ≥ S there is no tail, so normalise and return k̂ = NaN.
- 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.
- Fit (k, σ) to the exceedances: the Zhang–Stephens posterior mean over m = 30 + ⌊√M⌋ candidate values, vectorised, then shrink k towards ½.
- 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']
|
|
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 |
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
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]
|
|
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 |
False
|
key
|
PRNGKeyArray
|
The PRNG key for the proposal. |
required |
Returns:
| Type | Description |
|---|---|
Expectation
|
The |
Expectation
|
|
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 | |
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
- The draws: as given, or
sampler(key, n). - fₛ = f(xₛ) under
jax.vmap. - Î = (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
|
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 |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If a sampler has no |
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
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
- 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.
- R random shifts from one key: a digital shift (XOR of 32-bit integers) for Sobol, a rotation (uᵢ + Δᵣ) mod 1 for Halton.
- Map each point through
transform(to a Gaussian withjax.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'
|
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
|
key
|
PRNGKeyArray
|
The PRNG key for the shifts. |
required |
Returns:
| Type | Description |
|---|---|
Expectation
|
The |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 | |
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
|
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 |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Float[Array, ''], Float[Array, ' M'], Float[Array, 'M M']]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
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
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 | |
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
- Ask the rule for its points χₚ and mean weights wₚ.
- With points, evaluate k on them once and take the weighted sums.
- Without points, take
gaussx_infer.mean_expectationof 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 |
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
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 | |
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
- The Hermite nodes xₖ and weights wₖ on the host (static n).
- The rates qₖ = exp(μ + √2 σ xₖ), node axis first, batched over the broadcast shape of μ and σ.
integrix.rule.log_integratewith 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 |
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 |
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:
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
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
- 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. integrix.rule.log_integratewith 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 |
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
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 |
0
|
scheme
|
Literal['multinomial']
|
The base scheme; only |
'multinomial'
|
Returns:
| Type | Description |
|---|---|
Int[Array, ' num_samples']
|
Ancestor indices in [0, N) with |
Int[Array, ' num_samples']
|
sorted. |
Raises:
| Type | Description |
|---|---|
ValidationError
|
If |
EquinoxRuntimeError
|
If |
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
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 |
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
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 |
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
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 |
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
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 |
Examples:
>>> import jax, jax.numpy as jnp
>>> ancestors = resample_systematic(jax.random.key(0), jnp.zeros(4), 4)
>>> ancestors.tolist()
[0, 1, 2, 3]