Skip to content

Special functions (optix.special)

Quadrature, batched Newton solvers and KL divergences, written to avoid cancellation. See Probability distributions.

Special functions: quadrature, Newton solvers, KL divergences and censored-Gaussian moments.

gauss_hermite

gauss_hermite(n, *, dtype=None, device=None)

Gauss-Hermite nodes and log-weights for the weight exp(−x²).

Computed with the Golub-Welsch algorithm: the nodes are the eigenvalues of the symmetric Jacobi matrix of the (physicists') Hermite polynomials, and the weights are √π · v₀² where v₀ holds the first components of the normalised eigenvectors. Here the (equivalent) Christoffel formula wᵢ = 1 / (n pₙ₋₁(xᵢ)²) is used, with pₖ the orthonormal Hermite polynomials, because tiny eigenvector components are not accurate in floating point. Everything runs in float64 on the CPU; the results are then cast and moved.

Note

sum(exp(logw) * f(nodes)) ≈ ∫ f(x) exp(−x²) dx, exactly for polynomials of degree ≤ 2n − 1. For a Gaussian expectation use the change of variables x = μ + √2 σ t::

E[f(x)] ≈ sum(exp(logw) * f(mu + sqrt(2) * sigma * nodes))
          / sqrt(pi)

for x ~ N(mu, sigma²).

Parameters:

Name Type Description Default
n int

Number of nodes (≥ 1).

required
dtype optional

Output dtype and device (default: from the configuration).

None
device optional

Output dtype and device (default: from the configuration).

None

Returns:

Name Type Description
nodes (n,) Tensor

Quadrature nodes, increasing.

logw (n,) Tensor

Natural logarithm of the weights. Log-weights are returned so that large n does not underflow.

gauss_legendre

gauss_legendre(n, *, dtype=None, device=None)

Gauss-Legendre nodes and weights on [−1, 1].

The nodes are the roots of the Legendre polynomial Pₙ, found by Newton's method from xᵢ ≈ cos(π (i − ¼) / (n + ½)), with Pₙ and Pₙ₋₁ evaluated by the three-term recurrence; the weights are wᵢ = 2 / ((1 − xᵢ²) Pₙ′(xᵢ)²). This costs O(n²) operations, against O(n³) for the eigenvalues of the Jacobi matrix. Everything runs in float64 on the CPU (results are cached by n); copies are then cast and moved, so the caller may modify them in place.

Note

sum(weights * f(nodes)) ≈ ∫₋₁¹ f(x) dx, exactly for polynomials of degree ≤ 2n − 1.

References

  1. Abramowitz M, Stegun IA. Handbook of Mathematical Functions, formula 25.4.29. National Bureau of Standards, 1964.
BibTeX
@book{abramowitz1964handbook,
  author    = {Abramowitz, Milton and Stegun, Irene A.},
  title     = {Handbook of Mathematical Functions},
  publisher = {National Bureau of Standards},
  year      = {1964}
}

Parameters:

Name Type Description Default
n int

Number of nodes (≥ 1).

required
dtype optional

Output dtype and device (default: from the configuration).

None
device optional

Output dtype and device (default: from the configuration).

None

Returns:

Name Type Description
nodes (n,) Tensor

Quadrature nodes, increasing.

weights (n,) Tensor

Quadrature weights.

log_minus_digamma

log_minus_digamma(a)

log a − ψ(a), elementwise, without cancellation.

Parameters:

Name Type Description Default
a Tensor

Positive argument.

required

Returns:

Type Description
Tensor

log a − ψ(a). For a > 10 the asymptotic series 1/(2a) + 1/(12a²) − 1/(120a⁴) + 1/(252a⁶) is used, which keeps full relative precision where the direct difference loses its digits.

stirling_residual

stirling_residual(a)

log Γ(a) − ((a − ½) log a − a + ½ log(2π)), elementwise.

Parameters:

Name Type Description Default
a Tensor

Positive argument.

required

Returns:

Type Description
Tensor

The remainder of Stirling's formula. For a > 10 the series 1/(12a) − 1/(360a³) + 1/(1260a⁵) − 1/(1680a⁷) is used (absolute error below 1e-12), which keeps full relative precision where the direct difference of log Γ and its approximation would cancel.

ratio_minus_log

ratio_minus_log(num, den=1.0, diff=None)

y − 1 − log y with y = num / den > 0, without cancellation.

Parameters:

Name Type Description Default
num Tensor

Positive numerator and denominator of the ratio y.

required
den Tensor

Positive numerator and denominator of the ratio y.

required
diff Tensor

num - den, when the caller has a more accurate value than the rounded difference (e.g. a sum of elementwise differences).

None

Returns:

Type Description
Tensor

Non-negative, ≈ x² / 2 with x = (num − den) / den. Near y = 1 (|x| < 0.2), x − log(1 + x) is computed as 2u² / (1 − u) − 2 (atanh u − u) with u = x / (2 + x) and a series for atanh u − u; x is formed from the difference, so it keeps its relative precision. Elsewhere the direct y − 1 − log y is accurate, and finite for ratios too small for 1 + x to be represented.

fit_gamma_shape

fit_gamma_shape(c, niter=16)

Solve log ν − ψ(ν) = c for ν > 0, elementwise.

This is the maximum-likelihood equation of the Gamma shape, with c = log(mean(x)) − mean(log x) > 0 (the Jensen gap).

Note

Uses Minka's initialisation ν = (3 − c + √((c − 3)² + 24c)) / (12c) and Newton's method on 1/ν. For ν > 10 the residual and its derivative use asymptotic series, which avoids the cancellation in log ν − ψ(ν).

References

  1. Minka TP. Estimating a Gamma distribution. Technical report, Microsoft Research, 2002. microsoft.com/en-us/research
BibTeX
@techreport{minka2002gamma,
  author = {Minka, T.},
  title = {Estimating a Gamma distribution},
  institution = {Microsoft Research},
  year = {2002},
  url = {https://www.microsoft.com/en-us/research/publication/estimating-gamma-distribution/}
}

Parameters:

Name Type Description Default
c Tensor

Right-hand side. Values ≤ 0 (which round-off can produce) are clamped to ε / 2, which caps ν at about 1 / ε, where ε is the machine epsilon of the dtype. Values above 1 / ε (including inf) are clamped to 1 / ε, which keeps ν ≳ ε and the result finite.

required
niter int

Number of Newton iterations.

16

Returns:

Type Description
Tensor

Shape parameter ν, same shape and dtype as c.

inv_digamma

inv_digamma(y, niter=5)

Inverse of the digamma function, elementwise.

Note

Minka's initialisation: exp(y) + ½ for y ≥ −2.22, else −1 / (y + γ) with γ the Euler-Mascheroni constant; then Newton's method.

Parameters:

Name Type Description Default
y Tensor

Values of ψ(x).

required
niter int

Number of Newton iterations.

5

Returns:

Type Description
Tensor

x > 0 such that ψ(x) = y.

dirichlet_elog

dirichlet_elog(alpha)

Expected log-probabilities under a Dirichlet.

Parameters:

Name Type Description Default
alpha (..., K) Tensor

Concentration parameters (last dim = categories).

required

Returns:

Type Description
(..., K) Tensor

E[log π] = ψ(α) − ψ(α₀) with α₀ = ∑ₖ αₖ, computed as log(α / α₀) − lmd(α) + lmd(α₀) with lmd = log_minus_digamma, which does not cancel for large concentrations.

fit_dirichlet

fit_dirichlet(elogpi, alpha, niter=16, *, bounds=None)

Dirichlet maximum likelihood given expected log-probabilities.

Maximises log Γ(∑ₖ aₖ) − ∑ₖ log Γ(aₖ) + ∑ₖ (aₖ − 1) elogpiₖ over a > 0 with Newton's method, using the diagonal-plus-rank-one structure of the Hessian.

Note

Whenever a Newton step would make any component of a vector non-positive, that vector takes the fixed-point update a = ψ⁻¹(ψ(∑ₖ aₖ) + elogpi) instead, which always stays positive (and is also taken when the Newton step is not finite).

Convergence is only local: Newton's method needs a warm start (for example the previous estimate) to converge in a few iterations, and from a poor initial guess it may need many iterations or settle on the slower fixed-point steps.

References

  1. Minka TP. Estimating a Dirichlet distribution. Technical report, Microsoft Research, 2000. microsoft.com/en-us/research
BibTeX
@techreport{minka2000dirichlet,
  author = {Minka, T.},
  title = {Estimating a Dirichlet distribution},
  institution = {Microsoft Research},
  year = {2000},
  url = {https://www.microsoft.com/en-us/research/publication/estimating-dirichlet-distribution/}
}

Parameters:

Name Type Description Default
elogpi (..., K) Tensor

Mean log-probabilities (sufficient statistics), last dim = categories.

required
alpha (..., K) Tensor

Initial concentration parameters (broadcast against elogpi).

required
niter int

Number of iterations.

16
bounds (float, float)

Box constraint (lo, hi) on every concentration: the start and each iterate are clamped to it (projected Newton). It keeps the concentrations finite when the maximum lies at infinity (for example, when every observation is the same point of the simplex).

None

Returns:

Type Description
(..., K) Tensor

Fitted concentration parameters (strictly positive).

kl_gamma

kl_gamma(shape_q, rate_q, shape_p, rate_p)

KL(Gamma(shape_q, rate_q) ‖ Gamma(shape_p, rate_p)), elementwise.

Note

With shapes a and rates b,

KL = (a_q − a_p) ψ(a_q) − log Γ(a_q) + log Γ(a_p)
     + a_p log(b_q/b_p) + a_q (b_p − b_q) / b_q

rewritten with stirling_residual r, log_minus_digamma lmd and ratio_minus_log g as

a_p (g(a_q/a_p) + g(b_p/b_q)) + ½ log(a_q/a_p)
+ (a_q − a_p) ((b_p − b_q) / b_q − lmd(a_q)) + r(a_p) − r(a_q)

which has no cancellation between large log Γ / ψ values (float32 stays accurate at shapes ≈ 1e6).

Parameters:

Name Type Description Default
shape_q Tensor

Shape and rate of q.

required
rate_q Tensor

Shape and rate of q.

required
shape_p Tensor

Shape and rate of p.

required
rate_p Tensor

Shape and rate of p.

required

Returns:

Type Description
Tensor

Divergence (broadcast shape of the inputs).

kl_dirichlet

kl_dirichlet(a, b)

KL(Dir(a) ‖ Dir(b)).

Note

With a₀ = ∑ₖ aₖ and b₀ = ∑ₖ bₖ, KL = log Γ(a₀) − log Γ(b₀) − ∑ₖ (log Γ(aₖ) − log Γ(bₖ)) + ∑ₖ (aₖ − bₖ) (ψ(aₖ) − ψ(a₀)), rewritten with stirling_residual r, log_minus_digamma lmd and ratio_minus_log g as

∑ₖ (bₖ g(aₖ/bₖ) + ½ log(aₖ/bₖ)) − (b₀ g(a₀/b₀) + ½ log(a₀/b₀))
+ r(a₀) − r(b₀) − ∑ₖ (r(aₖ) − r(bₖ))
− ∑ₖ (aₖ − bₖ) lmd(aₖ) + (a₀ − b₀) lmd(a₀)

so that the log Γ terms of large concentrations cancel exactly.

Parameters:

Name Type Description Default
a (..., K) Tensor

Concentration parameters of q and p (last dim = categories).

required
b (..., K) Tensor

Concentration parameters of q and p (last dim = categories).

required

Returns:

Type Description
(...) Tensor

Divergence, summed over the last dim.

kl_normal

kl_normal(mean_q, var_q, mean_p, var_p)

KL(N(mean_q, var_q) ‖ N(mean_p, var_p)), elementwise.

Parameters:

Name Type Description Default
mean_q Tensor

Mean and variance of q.

required
var_q Tensor

Mean and variance of q.

required
mean_p Tensor

Mean and variance of p.

required
var_p Tensor

Mean and variance of p.

required

Returns:

Type Description
Tensor

Divergence (broadcast shape of the inputs).

clipped_normal_moments

clipped_normal_moments(mean, std, low=0.0, high=1.0)

Mean and standard deviation of clip(z, low, high).

The variable is z ~ 𝒩(μ, σ²), with μ = mean and σ = std. With t ~ 𝒩(0, 1), α = (low − μ)/σ and β = (high − μ)/σ, clip(z) = μ + σ·clip(t, α, β), and

m  = E[clip(t)]  = α Φ(α) + β Φ(−β) + φ(α) − φ(β)
s² = E[clip(t)²] = α² Φ(α) + β² Φ(−β) + Φ(β) − Φ(α)
                   + α φ(α) − β φ(β)
E[clip(z)]   = μ + σ m
Var[clip(z)] = σ² (s² − m²)

Note

Writing the moments about μ in units of σ avoids the cancellation of E[z²] − E[z]² when clipping is negligible: then m → 0 and s² → 1. Φ(−β) is used instead of 1 − Φ(β). Compute in float64 when nearly every sample is clipped, because s² − m² then cancels.

Parameters:

Name Type Description Default
mean Tensor

Parameters of the unclipped Gaussian (std > 0).

required
std Tensor

Parameters of the unclipped Gaussian (std > 0).

required
low float or None

Clipping bounds (None: no clipping on that side).

0.0
high float or None

Clipping bounds (None: no clipping on that side).

0.0

Returns:

Type Description
mean, std : Tensor

Moments of the clipped variable.

poisson_normal_mean

poisson_normal_mean(data, rate, variance, *, offset=0.0, max_terms=_MAX_TERMS)

Conditional mean E[n | r] of Poisson counts under Gaussian noise.

With r = n + g, n ~ Poisson(μ) and g ~ N(m, σ²) independent,

E[n | r] = ∑ₙ n μⁿ/n! · exp(−(r − n − m)²/2σ²)
         / ∑ₙ μⁿ/n! · exp(−(r − n − m)²/2σ²),

the function F[r, μ, σ] of Snyder et al. (1993, Eq. 21).

The sums are evaluated in log space (largest term factored out) and in float64, over the integers n ≥ 0 within a window around the mode of the summand, outside of which every term is below e⁻⁵⁰ times the largest one. The window adapts per element to the Poisson and Gaussian spreads; the series are evaluated in batches of at most max_terms terms. As σ → 0 the result tends to r − m, which is returned where σ² = 0.

References

  1. Snyder DL, Hammoud AM, White RL. Image recovery from data acquired with a charge-coupled-device camera. J Opt Soc Am A 10(5):1014-1023, 1993. doi:10.1364/JOSAA.10.001014
BibTeX
@article{snyder1993image,
  author  = {Snyder, Donald L. and Hammoud, Abed M. and
             White, Richard L.},
  title   = {Image recovery from data acquired with a
             charge-coupled-device camera},
  journal = {Journal of the Optical Society of America A},
  volume  = {10},
  number  = {5},
  pages   = {1014--1023},
  year    = {1993},
  doi     = {10.1364/JOSAA.10.001014}
}

Parameters:

Name Type Description Default
data Tensor

Observations r.

required
rate Tensor or float

Poisson mean μ ≥ 0.

required
variance Tensor or float

Gaussian variance σ² ≥ 0.

required
offset Tensor or float

Gaussian mean m.

0.0
max_terms int

Number of series terms evaluated at once (memory bound).

_MAX_TERMS

Returns:

Type Description
Tensor

E[n | r], in the dtype of data (broadcast shape).

poisson_normal_logpdf

poisson_normal_logpdf(data, rate, variance, *, offset=0.0, max_terms=_MAX_TERMS)

Log-density of r = n + g, n ~ Poisson(μ), g ~ N(m, σ²).

log p(r) = −μ − ½ log(2πσ²)
           + log ∑ₙ μⁿ/n! · exp(−(r − n − m)²/2σ²),

the per-pixel term of the log-likelihood of Snyder et al. (1993, Eq. 10). The series is evaluated as in poisson_normal_mean, with the Poisson terms written through Stirling's remainder so that the large, nearly equal n log μ, log n! and μ never have to cancel. Where σ² = 0 the Poisson log-probability of r − m is returned, (r − m) log μ − μ − log Γ(r − m + 1).

Parameters:

Name Type Description Default
data Tensor

Observations r.

required
rate Tensor or float

Poisson mean μ ≥ 0.

required
variance Tensor or float

Gaussian variance σ² ≥ 0.

required
offset Tensor or float

Gaussian mean m.

0.0
max_terms int

Number of series terms evaluated at once (memory bound).

_MAX_TERMS

Returns:

Type Description
Tensor

log p(r), in the dtype of data (broadcast shape).

poisson_normal_ratio

poisson_normal_ratio(data, rate, variance, *, offset=0.0, max_terms=_MAX_TERMS)

Ratio ξ(μ) = s(μ, x − 1)/s(μ, x) of Poisson–Gaussian series.

With x = r − m and

s(μ, b) = ∑ₙ μⁿ/n! · exp(−(b − n)²/2σ²),

ξ is the derivative term of the Poisson–Gaussian negative log-likelihood: −∂/∂μ log p(r) = 1 − ξ(μ), with p(r) the density of poisson_normal_logpdf (Chouzenoux et al. 2015, Eqs. 2.8, 2.10, 2.12). It equals E[n | r]/μ (see poisson_normal_mean).

Both series are summed in log space and in float64 over one window of n around the mode of the summand of s(μ, x), widened by one term on each side (every term left out is below e⁻⁵⁰ times the largest one); the terms of s(μ, x − 1) are indexed from n − 1 rather than formed as n·μⁿ⁻¹/n!, so that the ratio stays accurate for μ → 0. At μ = 0 the closed form ξ(0) = exp((2x − 1)/2σ²) is returned (Chouzenoux et al. 2015, Eq. 2.29); where σ² = 0, ξ = x/μ (Poisson).

References

  1. Chouzenoux E, Jezierska A, Pesquet J-C, Talbot H. A convex approach for image restoration with exact Poisson–Gaussian likelihood. SIAM J Imaging Sci 8(4):2662-2682, 2015. doi:10.1137/15M1014395
BibTeX
@article{chouzenoux2015convex,
  author  = {Chouzenoux, Emilie and Jezierska, Anna and
             Pesquet, Jean-Christophe and Talbot, Hugues},
  title   = {A Convex Approach for Image Restoration with
             Exact {Poisson}--{Gaussian} Likelihood},
  journal = {SIAM Journal on Imaging Sciences},
  volume  = {8},
  number  = {4},
  pages   = {2662--2682},
  year    = {2015},
  doi     = {10.1137/15M1014395}
}

Parameters:

Name Type Description Default
data Tensor

Observations r.

required
rate Tensor or float

Poisson mean μ ≥ 0.

required
variance Tensor or float

Gaussian variance σ² ≥ 0.

required
offset Tensor or float

Gaussian mean m.

0.0
max_terms int

Number of series terms evaluated at once (memory bound).

_MAX_TERMS

Returns:

Type Description
Tensor

ξ(μ), in the dtype of data (broadcast shape).

bessel_j0

bessel_j0(x)

Bessel function of the first kind of order 0, J₀(x).

In float64 for |x| < 25, J₀ (and J₁, J₂: see bessel_j012) is computed from Bessel's integral

Jₙ(x) = (1/2π) ∫₀^{2π} cos(nτ − x sin τ) dτ

by the trapezoidal rule on 64 points. The integrand is periodic and entire, so the rule converges geometrically: its error is the aliased term 2 |J₆₄(x)|, about 10⁻¹⁹ for |x| < 25, and the result is accurate to rounding (~10⁻¹⁶), where torch's float64 J₀ and J₁ have absolute errors up to ~5·10⁻⁷. By the symmetries τ → π − τ and τ → τ + π only the 17 points of a quarter period are distinct, and one cos(x sin τ) and one sin(x sin τ) per point give the three orders:

J₀(x) = ∑ⱼ wⱼ cos(x sin τⱼ),
J₁(x) = ∑ⱼ wⱼ sin τⱼ sin(x sin τⱼ),
J₂(x) = ∑ⱼ wⱼ cos 2τⱼ cos(x sin τⱼ),

with τⱼ = 2πj/64, j = 0 … 16, and wⱼ = 1/16 (1/32 at both ends). The absolute error of the rule is ~10⁻¹⁷ near 0, a poor relative one for J₁ and J₂ there: J₁ = x/2 for |x| < 10⁻⁸, and J₂ is its three-term series x²/8 − x⁴/96 + x⁶/3072 for |x| < 10⁻², both exact to rounding. The input is processed in blocks, so the memory is bounded. Above 25, torch.special.bessel_j0 and bessel_j1 are used, with J₂ = 2J₁/x − J₀. In float32 (and other floating dtypes), bessel_j0 and bessel_j1 return the torch functions unchanged (their error, ~4·10⁻⁷, is at the level of the dtype), whereas bessel_j012 uses the rule below 25, since the recurrence for J₂ cancels near 0. Integer input is cast to the default dtype.

References

  1. Watson GN. A Treatise on the Theory of Bessel Functions, 2nd ed., section 2.2 (Bessel's integral). Cambridge University Press, 1944.
  2. Trefethen LN, Weideman JAC. The exponentially convergent trapezoidal rule. SIAM Rev 56(3):385–458, 2014. doi:10.1137/130932132
BibTeX
@book{watson1944treatise,
  author    = {Watson, G. N.},
  title     = {A Treatise on the Theory of {Bessel} Functions},
  edition   = {2},
  publisher = {Cambridge University Press},
  year      = {1944}
}
@article{trefethen2014exponentially,
  author  = {Trefethen, Lloyd N. and Weideman, J. A. C.},
  title   = {The exponentially convergent trapezoidal rule},
  journal = {SIAM Review},
  volume  = {56},
  number  = {3},
  pages   = {385--458},
  year    = {2014},
  doi     = {10.1137/130932132}
}

Parameters:

Name Type Description Default
x Tensor

Real argument.

required

Returns:

Type Description
Tensor

J₀(x), same shape, dtype and device.

bessel_j1

bessel_j1(x)

Bessel function of the first kind of order 1, J₁(x).

Computed as described in bessel_j0.

Parameters:

Name Type Description Default
x Tensor

Real argument.

required

Returns:

Type Description
Tensor

J₁(x), same shape, dtype and device.

bessel_j012

bessel_j012(x)

Bessel functions of the first kind J₀(x), J₁(x) and J₂(x).

Computed together as described in bessel_j0: below |x| = 25, one cosine and one sine per node give the three orders, in every floating dtype.

Parameters:

Name Type Description Default
x Tensor

Real argument.

required

Returns:

Type Description
j0, j1, j2 : Tensor

Same shape, dtype and device as x.