Algorithm Search⌘K

Algorithmadvanced

Fast Gauss transform

Evaluates sums of N Gaussians at M targets in O(N + M) time by Hermite and Taylor expansions on a grid of boxes.

Time
O((N + M) p^2 + b n^2 p^3) worstΘ((N + M) p^2 + b n^2 p^3) averageΘ((N + M) p^2) best
Space
Θ(N + M + b p^2) extra
Where
M = the number of targets; N = the number of sources; b = the number of nonempty boxes; n = the range in boxes; p = the number of terms in each coordinate
Properties
deterministic
Origin
Leslie Greengard, John Strain, 1991

The fast Gauss transform (FGT) evaluates the discrete Gauss transform

G(ti)=∑j=1Nqj e−∣ti−sj∣2/δ,i=1,…,M,G(t_i) = \sum_{j=1}^{N} q_j \, e^{-|t_i - s_j|^2 / \delta}, \qquad i = 1, \ldots, M,

in work proportional to N+MN + M, with a constant that depends only on the dimension and the precision. Direct evaluation costs NMNM kernel evaluations. The method puts the points in a grid of boxes of side proportional to δ\sqrt{\delta}. Because the Gaussian decays fast, only boxes within a fixed range interact. For those, the Gaussians of a source box are collected into one Hermite expansion, and the field in a target box is collected into one Taylor expansion. Greengard and Strain (1991) gave the method for sums that come from the heat equation, vortex methods and statistics, and the same sums appear in kernel density estimation and Gaussian processes.

In plain words

Each source spreads a bump around it. The bump is wide about the square root of the given width, and it is almost zero farther away. You want the total height of all bumps at many targets.

Cut the square into small boxes. A box only feels boxes a few steps away, so far boxes are skipped. For a near box with many sources, replace all its bumps by one short sum of fixed shapes centred at the box. For a target box with many targets, collect everything it receives into one short polynomial about its centre, and then read each target from that polynomial. Boxes with few points simply add bump by bump.

Every step then costs a fixed amount per point and per pair of boxes, so the total grows like the number of points.

The problem

The input is NN sources sjs_j with weights qjq_j, MM targets tit_i, all in the unit square, a width δ>0\delta > 0, a number pp of terms in each coordinate and a range nn. The output is an approximation of every G(ti)G(t_i), with an error at most a fixed small multiple of Q=∑j∣qj∣Q = \sum_j |q_j|.

The algorithm

Scale every coordinate by 1/δ1 / \sqrt{\delta}, so the kernel is e−∣x−y∣2e^{-|x - y|^2}. Let hk(x)=(−1)kdkdxke−x2h_k(x) = (-1)^k \frac{d^k}{dx^k} e^{-x^2} be the Hermite functions, computed by hk+1=2xhk−2khk−1h_{k+1} = 2x h_k - 2k h_{k-1}, and use the multi-index notation α=(α1,α2)\alpha = (\alpha_1, \alpha_2), α!=α1! α2!\alpha! = \alpha_1! \, \alpha_2! and hα(x)=hα1(x1)hα2(x2)h_\alpha(x) = h_{\alpha_1}(x_1) h_{\alpha_2}(x_2). For a source yy near a center cc and a target xx near a center c′c', the Hermite and Taylor expansions are

e−∣x−y∣2=∑α(y−c)αα!hα(x−c)=∑β(x−c′)ββ!hβ(y−c′).e^{-|x - y|^2} = \sum_{\alpha} \frac{(y - c)^\alpha}{\alpha!} h_\alpha(x - c) = \sum_{\beta} \frac{(x - c')^\beta}{\beta!} h_\beta(y - c').

Cut the square into boxes of side δ/2\sqrt{\delta} / 2. A source box BB is big if it has more than NFN_F sources, and a target box CC is big if it has more than MLM_L targets. Each target box looks at the source boxes at most nn boxes away in each coordinate.

  1. FGT(q, s, t, δ, p, n)
  2. 1for each big source box B: A_B(α) ← Σ_{j in B} q_j (s_j - c_B)^α / α!, for α_1, α_2 < p
  3. for each target box C and each source box B at most n boxes away do
  4. 2if B and C are small: G(t_i) += Σ_{j in B} q_j e^{-|t_i - s_j|^2} for each t_i in C
  5. 3if B is small and C is big: T_C(β) += Σ_{j in B} q_j h_β(s_j - c_C) / β!
  6. 4if B is big and C is small: G(t_i) += Σ_α A_B(α) h_α(t_i - c_B) for each t_i in C
  7. 5if B and C are big: T_C(β) += ((-1)^{|β|} / β!) Σ_α A_B(α) h_{α+β}(c_C - c_B)
  8. 6for each big target box C and t_i in C: G(t_i) += Σ_β T_C(β) (t_i - c_C)^β
  9. 7return G

Line L5 converts a Hermite expansion into a Taylor expansion. Since hα+β(w)=hα1+β1(w1) hα2+β2(w2)h_{\alpha + \beta}(w) = h_{\alpha_1 + \beta_1}(w_1) \, h_{\alpha_2 + \beta_2}(w_2), it is done one coordinate at a time in O(p3)O(p^3) operations instead of O(p4)O(p^4). Greengard and Strain take NFN_F and MLM_L of order pd−1p^{d-1} in dimension dd, which balances the four kinds of work; the code takes NF=ML=pN_F = M_L = p. Their boxes have side r2δr \sqrt{2\delta} with r≤12r \le \frac12; this page uses r=1/(22)r = 1 / (2\sqrt{2}), the side T\sqrt{T} of the short course of Beatson and Greengard for the heat kernel e−∣x∣2/4Te^{-|x|^2 / 4T}.

Example

Take N=M=300N = M = 300 sources and targets uniform in the unit square, weights uniform in [0,1][0, 1] (seed 11), and δ=0.16\delta = 0.16. The boxes have side 0.20.2, so there are 25 boxes and, with n=8n = 8, all 625 pairs interact. Forcing one of the three expansion methods for all pairs gives the largest error divided by QQ:

pp sources to Taylor (L3) Hermite to targets (L4) Hermite to Taylor (L5) bound of the proof
2 1.2×10−21.2 \times 10^{-2} 6.6×10−36.6 \times 10^{-3} 1.9×10−21.9 \times 10^{-2} 2.72.7
4 1.5×10−41.5 \times 10^{-4} 7.8×10−57.8 \times 10^{-5} 2.1×10−42.1 \times 10^{-4} 1.3×10−11.3 \times 10^{-1}
6 3.0×10−63.0 \times 10^{-6} 1.3×10−61.3 \times 10^{-6} 3.4×10−63.4 \times 10^{-6} 5.4×10−35.4 \times 10^{-3}
8 4.9×10−84.9 \times 10^{-8} 1.8×10−81.8 \times 10^{-8} 5.2×10−85.2 \times 10^{-8} 1.8×10−41.8 \times 10^{-4}
10 5.7×10−105.7 \times 10^{-10} 2.1×10−102.1 \times 10^{-10} 5.8×10−105.8 \times 10^{-10} 4.7×10−64.7 \times 10^{-6}
12 5.3×10−125.3 \times 10^{-12} 2.1×10−122.1 \times 10^{-12} 5.3×10−125.3 \times 10^{-12} 2.1×10−72.1 \times 10^{-7}

These are measurements, and the last column is the bound 2εp+εp22\varepsilon_p + \varepsilon_p^2 of the proof. Each two more terms give about two more digits. With the cutoffs NF=ML=8N_F = M_L = 8 and p=8p = 8, the code uses all four ways: 6 pairs direct, 44 sources to Taylor, 69 Hermite to targets and 506 Hermite to Taylor, with the error 5.2×10−8Q5.2 \times 10^{-8} Q.

The range matters when the boxes are small. With δ=0.01\delta = 0.01 there are 20×2020 \times 20 boxes, and with all pairs direct, the error divided by QQ for the ranges n=1,…,6n = 1, \ldots, 6 is 2.4×10−22.4 \times 10^{-2}, 8.9×10−38.9 \times 10^{-3}, 1.8×10−31.8 \times 10^{-3}, 2.4×10−42.4 \times 10^{-4}, 2.9×10−52.9 \times 10^{-5} and 1.2×10−61.2 \times 10^{-6}, below the bounds e−n2/4e^{-n^2/4}, which are 0.780.78, 0.370.37, 0.110.11, 1.8×10−21.8 \times 10^{-2}, 1.9×10−31.9 \times 10^{-3} and 1.2×10−41.2 \times 10^{-4}.

Correctness

The proof file proves the bound ∣G~(ti)−G(ti)∣≤Q(2εp+εp2+e−n2/4)|\tilde G(t_i) - G(t_i)| \le Q (2\varepsilon_p + \varepsilon_p^2 + e^{-n^2/4}). In each coordinate, the Gaussian for one source and one target is a double series in the offset of the source from its center and the offset of the target from its center, and the four ways compute partial sums of it: all terms, the Hermite part (m<pm < p), the Taylor part (n<pn < p) or both. Cramér's inequality ∣Hk(z)∣≤K2k/2k! ez2/2|H_k(z)| \le K 2^{k/2} \sqrt{k!} \, e^{z^2/2}, with K<1.09K < 1.09, and (m+n)!≤2m+nm! n!(m + n)! \le 2^{m+n} m! \, n! bound the omitted terms by εp=2KC0∑k≥p2−k/k!\varepsilon_p = 2 K C_0 \sum_{k \ge p} 2^{-k} / \sqrt{k!}, because the offsets are at most 14\frac14. A product of two such factors has the error at most 2εp+εp22\varepsilon_p + \varepsilon_p^2. Sources in skipped boxes are at least n/2n / 2 away in the scaled coordinates, so they contribute at most e−n2/4e^{-n^2/4} each. The original error estimate of Greengard and Strain for Hermite expansions was later corrected by Baxter and Roussos; the bound here is derived directly and does not use it.

Proof: The fast Gauss transform with p terms per coordinate and range n_r has error at most Q (2ε_p + ε_p² + e^{-n_r²/4})full

We use exact arithmetic and the scaled coordinates x/δx / \sqrt{\delta}, in which the kernel is e−∣x−y∣2e^{-|x - y|^2} and the boxes have side 12\frac12. So a point and the center of its box differ by at most 14\frac14 in each coordinate. Let hn(x)=(−1)ndndxne−x2=Hn(x)e−x2h_n(x) = (-1)^n \frac{d^n}{dx^n} e^{-x^2} = H_n(x) e^{-x^2}, where HnH_n is the Hermite polynomial, and let Q=∑j∣qj∣Q = \sum_j |q_j|.

The double series. Fix a source yy in box BB (center cBc_B) and a target xx in box CC (center cCc_C), and look at one coordinate. Write a=y−cBa = y - c_B, u=x−cCu = x - c_C and w=cC−cBw = c_C - c_B, so x−y=w+u−ax - y = w + u - a and ∣a∣,∣u∣≤14|a|, |u| \le \frac14. Taylor's theorem for the entire function f(z)=e−z2f(z) = e^{-z^2} gives f(z−a)=∑m(−a)mm!f(m)(z)=∑mamm!hm(z)f(z - a) = \sum_m \frac{(-a)^m}{m!} f^{(m)}(z) = \sum_m \frac{a^m}{m!} h_m(z), and since hm(n)=(−1)nhm+nh_m^{(n)} = (-1)^n h_{m+n}, also hm(w+u)=∑nunn!(−1)nhm+n(w)h_m(w + u) = \sum_n \frac{u^n}{n!} (-1)^n h_{m+n}(w). Hence

e−(w+u−a)2=∑m≥0∑n≥0T(m,n),T(m,n)=amm!unn!(−1)nhm+n(w),e^{-(w + u - a)^2} = \sum_{m \ge 0} \sum_{n \ge 0} T(m, n), \qquad T(m, n) = \frac{a^m}{m!} \frac{u^n}{n!} (-1)^n h_{m+n}(w),

with absolute convergence by Lemma 1 below.

The four ways compute partial sums. In one coordinate, line L2 (direct) computes the full sum. Line L4 (Hermite to targets) computes ∑m<pamm!hm(w+u)=∑m<p∑nT(m,n)\sum_{m < p} \frac{a^m}{m!} h_m(w + u) = \sum_{m < p} \sum_n T(m, n). Line L3 (sources to Taylor) computes ∑n<punn!hn(a−w)\sum_{n < p} \frac{u^n}{n!} h_n(a - w); since hn(−z)=(−1)nhn(z)h_n(-z) = (-1)^n h_n(z) and ∑m(−a)mm!hn(m)(w)=hn(w−a)\sum_m \frac{(-a)^m}{m!} h_n^{(m)}(w) = h_n(w - a), this is ∑n<p∑mT(m,n)\sum_{n < p} \sum_m T(m, n). Line L5 with line L6 (Hermite to Taylor) computes ∑m<p∑n<pT(m,n)\sum_{m < p} \sum_{n < p} T(m, n): the Taylor coefficient of order nn is (−1)nn!∑m<pAmhm+n(w)\frac{(-1)^n}{n!} \sum_{m < p} A_m h_{m+n}(w), with the Hermite coefficients Am=∑qamm!A_m = \sum q \frac{a^m}{m!}. In 2D, the coefficients are products over the two coordinates, so for each source the algorithm computes the product g1g2g_1 g_2 of two such partial sums, while the true term is f1f2f_1 f_2 with fk=e−(xk−yk)2f_k = e^{-(x_k - y_k)^2}. In every case the omitted terms of a coordinate have m≥pm \ge p or n≥pn \ge p.

Lemma 1 (tails). Let C0=∑n≥02−n/n!C_0 = \sum_{n \ge 0} 2^{-n} / \sqrt{n!} and σp=∑n≥p2−n/n!\sigma_p = \sum_{n \ge p} 2^{-n} / \sqrt{n!}. Then ∑m≥p or n≥p∣T(m,n)∣≤εp:=2KC0σp\sum_{m \ge p \text{ or } n \ge p} |T(m, n)| \le \varepsilon_p := 2 K C_0 \sigma_p, where K=1.09K = 1.09.

Proof. Cramér's inequality for Hermite polynomials, as stated in Section 2 of Greengard and Strain (1991), says ∣Hk(z)∣≤K2k/2k! ez2/2|H_k(z)| \le K 2^{k/2} \sqrt{k!} \, e^{z^2/2} for all real zz, with K<1.09K < 1.09, so ∣hk(w)∣≤K2k/2k!|h_k(w)| \le K 2^{k/2} \sqrt{k!}. Since (m+nm)≤2m+n\binom{m+n}{m} \le 2^{m+n}, we have (m+n)!≤2m+nm! n!(m + n)! \le 2^{m+n} m! \, n!. With ∣a∣,∣u∣≤14|a|, |u| \le \frac14,

∣T(m,n)∣≤4−m−nm! n!K 2(m+n)/2 2(m+n)/2m! n!=K2−mm!2−nn!.|T(m, n)| \le \frac{4^{-m-n}}{m! \, n!} K \, 2^{(m+n)/2} \, 2^{(m+n)/2} \sqrt{m! \, n!} = K \frac{2^{-m}}{\sqrt{m!}} \frac{2^{-n}}{\sqrt{n!}}.

The sum over m≥pm \ge p and all nn is at most KσpC0K \sigma_p C_0, and so is the sum over n≥pn \ge p and all mm. □\square

Lemma 2 (range). If BB is more than nrn_r boxes from CC in some coordinate, then every source yy in BB and target xx in CC satisfy e−∣x−y∣2≤e−nr2/4e^{-|x - y|^2} \le e^{-n_r^2 / 4}.

Proof. The index difference is at least nr+1n_r + 1, so at least nrn_r whole boxes of side 12\frac12 lie between BB and CC in that coordinate, and ∣x−y∣≥nr/2|x - y| \ge n_r / 2. □\square

Theorem. For every target tit_i, the output G~(ti)\tilde G(t_i) of the algorithm satisfies

∣G~(ti)−G(ti)∣≤Q (2εp+εp2+e−nr2/4).|\tilde G(t_i) - G(t_i)| \le Q \, \big( 2 \varepsilon_p + \varepsilon_p^2 + e^{-n_r^2 / 4} \big).

Proof. Each source contributes through exactly one pair of boxes, the pair of its box and the box of tit_i, so the error is a sum over sources. For a source in a skipped box, the error is ∣qj∣e−∣x−y∣2≤∣qj∣e−nr2/4|q_j| e^{-|x - y|^2} \le |q_j| e^{-n_r^2/4} by Lemma 2. For any other source, by Lemma 1, ∣fk−gk∣≤εp|f_k - g_k| \le \varepsilon_p, and ∣fk∣≤1|f_k| \le 1, so ∣g1∣≤1+εp|g_1| \le 1 + \varepsilon_p and

∣f1f2−g1g2∣≤∣f1−g1∣ ∣f2∣+∣g1∣ ∣f2−g2∣≤εp+(1+εp)εp.|f_1 f_2 - g_1 g_2| \le |f_1 - g_1| \, |f_2| + |g_1| \, |f_2 - g_2| \le \varepsilon_p + (1 + \varepsilon_p) \varepsilon_p.

Multiply by ∣qj∣|q_j| and add. □\square

For p=4,6,8,10,12p = 4, 6, 8, 10, 12, the factor 2εp+εp22 \varepsilon_p + \varepsilon_p^2 is about 1.3×10−11.3 \times 10^{-1}, 5.4×10−35.4 \times 10^{-3}, 1.8×10−41.8 \times 10^{-4}, 4.7×10−64.7 \times 10^{-6} and 2.1×10−72.1 \times 10^{-7}. The bound does not depend on NN, MM, the positions or δ\delta, and it decays faster than geometrically in pp, since σp\sigma_p is about 2−p/p!2^{-p} / \sqrt{p!}.

Complexity

The model is the real RAM, with exe^x counted as one operation.

  • Linear work (theorem). Line L1 costs O(p2)O(p^2) per source and line L6 O(p2)O(p^2) per target. With NF=ML=pN_F = M_L = p, every pair of boxes costs O(p3)O(p^3): a direct pair has at most p2p^2 kernel evaluations, the pairs of lines L3 and L4 at most p⋅p2p \cdot p^2, and line L5 is O(p3)O(p^3) by the product form. There are at most b(2n+1)2b (2n + 1)^2 pairs, so the total is O((N+M)p2+bn2p3)O((N + M) p^2 + b n^2 p^3), and bb is at most N+MN + M and at most the number of boxes, ⌈2/δ⌉2\lceil 2 / \sqrt{\delta} \rceil^2.
  • Constant set by the precision. For a fixed error, pp and nn are fixed, so the work is O(N+M)O(N + M). Greengard and Strain report, for their 2D Fortran code with p2=82p^2 = 8^2 terms and δ=1\delta = 1, a time of 205 seconds for N=M=102400N = M = 102400 uniform points, against an estimated 622780 seconds for direct evaluation, and more than 3000 times faster than direct evaluation for 102400 points on a circle with δ=0.01\delta = 0.01.
  • Dimension. In dd dimensions the expansions have pdp^d terms and the range has (2n+1)d(2n + 1)^d boxes, so the constant grows exponentially with dd; this is the limit that the improved FGT addresses.
  • Space. Θ(N+M)\Theta(N + M) for the points and Θ(bp2)\Theta(b p^2) for the expansions.

Properties

  • No tree. The boxes form one flat grid, because the Gaussian has a fixed width; unlike the fast multipole method, there is no hierarchy.
  • Error relative to the total weight. The bound is a multiple of QQ, not of ∣G(ti)∣|G(t_i)|. Where the field is small compared with QQ, the relative error can be large.
  • Independent of the distribution. The error bound does not depend on the positions. The work is smallest when the points are clustered into few boxes.
  • Linear in the weights. The output is a linear function of qq, so the method is a fast product with the matrix [e−∣ti−sj∣2/δ][e^{-|t_i - s_j|^2 / \delta}].
  • Deterministic. The result does not depend on the order of the points, up to rounding.

Variants and improvements

  • Improved FGT. Yang, Duraiswami, Gumerov and Davis (2003) use a multivariate Taylor expansion with terms of total degree below pp, about (p+d−1d)\binom{p + d - 1}{d} instead of pdp^d, and cluster the sources with farthest point clustering instead of a grid, which makes the method usable in more dimensions.
  • New versions of the FGT. Later versions of Greengard and coworkers replace the Hermite expansions by plane wave (Fourier) expansions, which diagonalize the translations, and add adaptive trees for sources spread over many scales.
  • Variable widths. Strain extended the method to Gaussians whose width changes from source to source.
  • Heat equation solvers. The FGT evaluates heat potentials in integral equation methods for the heat equation.
  • Tree codes for Gaussians. For high dimensions and small widths, dual tree methods on a k-d tree prune far pairs with error bounds.

When to use it

Use the FGT for sums of Gaussians with one width in two or three dimensions, with many sources and targets: kernel density estimation, mean shift clustering, Gaussian radial basis functions, Gaussian process regression with a squared exponential kernel, and heat potentials. If the width is so small that each target sees only a few sources, a grid of cells with direct sums is enough. If the width is so large that the Gaussian is nearly constant, a few Taylor terms over one box are enough. In more than three or four dimensions, use the improved FGT or a tree method.

Pitfalls

  • Wrong scaling. The expansions use the offsets divided by δ\sqrt{\delta}. Forgetting the scaling, or using boxes much larger than δ\sqrt{\delta}, makes the offsets large and the series converge slowly or not at all in floating point.
  • Error relative to Q. If the weights have mixed signs and cancel, the error bound in terms of Q=∑∣qj∣Q = \sum |q_j| can be much larger than the result.
  • Range too small. The cutoff error is about e−n2/4e^{-n^2/4} in the scaled units of this page. For the same precision, smaller boxes need a larger nn.
  • Too many terms in many dimensions. In dd dimensions the tensor expansions have pdp^d terms; for d≥4d \ge 4 the method can be slower than direct evaluation.
  • Old error formula. The error estimate in Lemma 2.1 of the 1991 paper was shown to be wrong by Baxter and Roussos. Use a corrected bound, such as the one in the proof file, when you choose pp.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

fast_gauss_transform.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-gauss-transform/. The authors are listed in prov/PHV9XM.jsonl.
"""Fast Gauss transform of Greengard and Strain, in 2D.

Sources s[j] with weights q[j] and targets t[i] are points (complex numbers)
of the unit square. The output is

    G(t_i) = sum_j q_j exp(-|t_i - s_j|^2 / delta).

The square is cut into boxes of side sqrt(delta) / 2. In the scaled
coordinates x / sqrt(delta), each coordinate of the Gaussian has the
Hermite expansion about a source center and the Taylor expansion about a
target center,

    exp(-(u - v)^2) = sum_n v^n / n! h_n(u) = sum_n u^n / n! h_n(v),

with the Hermite functions h_n(x) = (-1)^n d^n/dx^n exp(-x^2). A pair of
boxes is handled in one of four ways, set by the number of sources and
targets in the boxes: direct, sources to Taylor, Hermite to targets, or
Hermite to Taylor. Boxes more than n_range boxes apart in a coordinate are
skipped; their terms are below exp(-n_range^2 / 4).
"""

import math
from typing import Optional, Sequence


def hermite_functions(n: int, x: float) -> list[float]:
    """h_0(x), ..., h_{n-1}(x) by h_{k+1} = 2 x h_k - 2 k h_{k-1}."""
    h = [math.exp(-x * x), 2 * x * math.exp(-x * x)][:n]
    while len(h) < n:
        k = len(h) - 1
        h.append(2 * x * h[k] - 2 * k * h[k - 1])
    return h


def powers_over_factorial(n: int, x: float) -> list[float]:
    """x^k / k! for k = 0..n-1."""
    out = [1.0]
    for k in range(1, n):
        out.append(out[-1] * x / k)
    return out[:n]


def direct(q: Sequence[float], s: Sequence[complex], t: Sequence[complex], delta: float) -> list[float]:
    """Direct summation over all source and target pairs: the reference."""
    return [sum(qj * math.exp(-abs(ti - sj) ** 2 / delta) for qj, sj in zip(q, s)) for ti in t]


def fgt(q: Sequence[float], s: Sequence[complex], t: Sequence[complex], delta: float, p: int = 8,
        n_range: int = 8, n_f: Optional[int] = None, m_l: Optional[int] = None):
    """G(t_i) with p terms per coordinate in every expansion.

    A source box is "big" if it holds more than n_f sources, a target box if
    it holds more than m_l targets (both default to p). Returns (G, stats)
    with the number of box pairs handled in each of the four ways.
    """
    if n_f is None:
        n_f = p
    if m_l is None:
        m_l = p
    sd = math.sqrt(delta)
    h = sd / 2
    nb = max(1, math.ceil(1 / h))

    def key(z: complex) -> tuple[int, int]:
        return (min(int(z.real / h), nb - 1), min(int(z.imag / h), nb - 1))

    def center(k: tuple[int, int]) -> complex:
        return complex((k[0] + 0.5) * h, (k[1] + 0.5) * h)

    src: dict[tuple[int, int], list[int]] = {}
    for j, z in enumerate(s):
        src.setdefault(key(z), []).append(j)
    tgt: dict[tuple[int, int], list[int]] = {}
    for i, z in enumerate(t):
        tgt.setdefault(key(z), []).append(i)
    fact = [math.factorial(k) for k in range(p)]
    herm: dict[tuple[int, int], list[float]] = {}
    for b, idx in src.items():
        if len(idx) > n_f:  # @line L1
            c = center(b)
            a = [0.0] * (p * p)
            for j in idx:
                px = powers_over_factorial(p, (s[j].real - c.real) / sd)
                py = powers_over_factorial(p, (s[j].imag - c.imag) / sd)
                for a1 in range(p):
                    for a2 in range(p):
                        a[a1 * p + a2] += q[j] * px[a1] * py[a2]
            herm[b] = a
    g = [0.0] * len(t)
    taylor: dict[tuple[int, int], list[float]] = {}
    stats = {"direct": 0, "s2l": 0, "h2t": 0, "h2l": 0}
    for cb, tidx in tgt.items():
        big_t = len(tidx) > m_l
        cc = center(cb)
        if big_t:
            taylor[cb] = [0.0] * (p * p)
        near = [(cb[0] + dx, cb[1] + dy) for dx in range(-n_range, n_range + 1)
                for dy in range(-n_range, n_range + 1)]
        for b in near:
            sidx = src.get(b)
            if sidx is None:
                continue
            big_s = b in herm
            if not big_s and not big_t:  # @line L2
                for i in tidx:
                    g[i] += sum(q[j] * math.exp(-abs(t[i] - s[j]) ** 2 / delta) for j in sidx)
                stats["direct"] += 1
            elif not big_s:  # @line L3
                bc = taylor[cb]
                for j in sidx:
                    hx = hermite_functions(p, (s[j].real - cc.real) / sd)
                    hy = hermite_functions(p, (s[j].imag - cc.imag) / sd)
                    for b1 in range(p):
                        for b2 in range(p):
                            bc[b1 * p + b2] += q[j] * hx[b1] * hy[b2] / (fact[b1] * fact[b2])
                stats["s2l"] += 1
            elif not big_t:  # @line L4
                a = herm[b]
                c = center(b)
                for i in tidx:
                    hx = hermite_functions(p, (t[i].real - c.real) / sd)
                    hy = hermite_functions(p, (t[i].imag - c.imag) / sd)
                    g[i] += sum(a[a1 * p + a2] * hx[a1] * hy[a2] for a1 in range(p) for a2 in range(p))
                stats["h2t"] += 1
            else:  # @line L5
                a = herm[b]
                w = (cc - center(b)) / sd
                hx = hermite_functions(2 * p - 1, w.real)
                hy = hermite_functions(2 * p - 1, w.imag)
                tmp = [[sum(hy[a2 + b2] * a[a1 * p + a2] for a2 in range(p)) for b2 in range(p)] for a1 in range(p)]
                bc = taylor[cb]
                for b1 in range(p):
                    for b2 in range(p):
                        val = sum(hx[a1 + b1] * tmp[a1][b2] for a1 in range(p))
                        bc[b1 * p + b2] += (-1) ** (b1 + b2) * val / (fact[b1] * fact[b2])
                stats["h2l"] += 1
    for cb, bc in taylor.items():
        cc = center(cb)
        for i in tgt[cb]:  # @line L6
            ux = (t[i].real - cc.real) / sd
            uy = (t[i].imag - cc.imag) / sd
            px = [ux ** k for k in range(p)]
            py = [uy ** k for k in range(p)]
            g[i] += sum(bc[b1 * p + b2] * px[b1] * py[b2] for b1 in range(p) for b2 in range(p))
    return g, stats  # @line L7
test_fast_gauss_transform.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-gauss-transform/. The authors are listed in prov/PHV9XM.jsonl.
"""Tests for the fast Gauss transform: Hermite functions, the four ways of handling a pair of boxes, and the error bound."""

import math
import random
import unittest

from fast_gauss_transform import direct, fgt, hermite_functions, powers_over_factorial

BIG = 10 ** 9


def points(n, m, seed):
    rng = random.Random(seed)
    s = [complex(rng.random(), rng.random()) for _ in range(n)]
    t = [complex(rng.random(), rng.random()) for _ in range(m)]
    q = [rng.random() for _ in range(n)]
    return q, s, t


def bound(p):
    """2 e + e^2 with e = 2 K C sigma_p, the bound of the proof for one source of weight 1."""
    c = sum(2.0 ** -n / math.sqrt(math.factorial(n)) for n in range(60))
    sig = sum(2.0 ** -n / math.sqrt(math.factorial(n)) for n in range(p, 80))
    e = 2 * 1.09 * c * sig
    return 2 * e + e * e


def max_err(g, gd, q):
    return max(abs(a - b) for a, b in zip(g, gd)) / sum(abs(x) for x in q)


class TestHermite(unittest.TestCase):
    def test_generating_function(self):
        for x in (-1.3, 0.0, 0.4, 2.1):
            for y in (-0.25, 0.1, 0.25):
                h = hermite_functions(40, x)
                yp = powers_over_factorial(40, y)
                self.assertAlmostEqual(sum(a * b for a, b in zip(h, yp)), math.exp(-(x - y) ** 2), places=13)

    def test_derivative_relation(self):
        x, eps = 0.7, 1e-5
        hp = hermite_functions(6, x + eps)
        hm = hermite_functions(6, x - eps)
        h = hermite_functions(7, x)
        for n in range(6):
            self.assertAlmostEqual((hp[n] - hm[n]) / (2 * eps), -h[n + 1], places=6)

    def test_cramer_inequality(self):
        for n in range(30):
            for k in range(-60, 61):
                x = k / 10
                hn = hermite_functions(n + 1, x)[n]
                rhs = 1.09 * 2 ** (n / 2) * math.sqrt(math.factorial(n)) * math.exp(-x * x / 2)
                self.assertLessEqual(abs(hn), rhs)


class TestFGT(unittest.TestCase):
    def test_all_direct_is_exact(self):
        q, s, t = points(200, 200, 1)
        g, st = fgt(q, s, t, 0.16, p=4, n_f=BIG, m_l=BIG)
        self.assertEqual(st["s2l"] + st["h2t"] + st["h2l"], 0)
        for a, b in zip(g, direct(q, s, t, 0.16)):
            self.assertAlmostEqual(a, b, places=12)

    def test_each_way_within_the_bound(self):
        q, s, t = points(300, 300, 11)
        gd = direct(q, s, t, 0.16)
        for name, nf, ml in (("s2l", BIG, -1), ("h2t", -1, BIG), ("h2l", -1, -1)):
            prev = 1.0
            for p in (4, 6, 8, 10):
                g, st = fgt(q, s, t, 0.16, p=p, n_f=nf, m_l=ml)
                self.assertEqual(st[name], 625)
                e = max_err(g, gd, q)
                self.assertLess(e, bound(p))
                self.assertLess(e, prev / 20)
                prev = e
            self.assertLess(prev, 1e-9)

    def test_default_mixes_the_four_ways(self):
        q, s, t = points(300, 300, 11)
        g, st = fgt(q, s, t, 0.16, p=8)
        self.assertTrue(all(v > 0 for v in st.values()))
        self.assertEqual(sum(st.values()), 625)
        self.assertLess(max_err(g, direct(q, s, t, 0.16), q), 1e-7)

    def test_range_cutoff(self):
        q, s, t = points(300, 300, 11)
        gd = direct(q, s, t, 0.01)
        for nr in (2, 4, 6):
            g, _ = fgt(q, s, t, 0.01, p=6, n_range=nr, n_f=BIG, m_l=BIG)
            self.assertLess(max_err(g, gd, q), math.exp(-nr * nr / 4))

    def test_linear_in_the_weights(self):
        q, s, t = points(150, 120, 4)
        rng = random.Random(5)
        r = [rng.uniform(-1, 1) for _ in q]
        g1, _ = fgt(q, s, t, 0.09, p=6, n_f=-1, m_l=-1)
        g2, _ = fgt(r, s, t, 0.09, p=6, n_f=-1, m_l=-1)
        g3, _ = fgt([a + 3 * b for a, b in zip(q, r)], s, t, 0.09, p=6, n_f=-1, m_l=-1)
        for a, b, c in zip(g1, g2, g3):
            self.assertAlmostEqual(c, a + 3 * b, places=10)

    def test_small_inputs(self):
        self.assertEqual(fgt([], [], [0.5 + 0.5j], 0.1)[0], [0.0])
        self.assertEqual(fgt([1.0], [0.5 + 0.5j], [], 0.1)[0], [])
        g, _ = fgt([2.0], [0.2 + 0.3j], [0.25 + 0.3j, 1.0 + 1.0j], 4.0, p=10, n_f=-1, m_l=-1)
        for a, b in zip(g, direct([2.0], [0.2 + 0.3j], [0.25 + 0.3j, 1.0 + 1.0j], 4.0)):
            self.assertLess(abs(a - b), 2.0 * bound(10))


if __name__ == "__main__":
    unittest.main()

History

Greengard and Strain (1991) gave the fast Gauss transform: Hermite and Taylor expansions in dd dimensions, a grid of boxes of side proportional to δ\sqrt{\delta}, four ways for a pair of boxes chosen by the cutoffs NFN_F and MLM_L, and 2D experiments with up to about 100000 sources and targets. Beatson and Greengard (1997) presented it for the heat kernel in their short course on fast multipole methods. Baxter and Roussos (2002) showed that the error estimate of Lemma 2.1 of the original paper is wrong and gave a new one. Yang, Duraiswami, Gumerov and Davis (2003) gave the improved FGT for kernel density estimation in higher dimensions.

References

  1. Leslie Greengard and John Strain, The fast Gauss transform, SIAM Journal on Scientific and Statistical Computing 12(1), 1991, 79-94, Section 2, the Hermite and Taylor expansions and Cramér's inequality; Section 3, the boxes of side r√(2δ), the range of (2n + 1)^d boxes and the four ways with the cutoffs N_F and M_L; Section 4, the formal algorithm; Section 5, the 2D experiments
  2. Rick Beatson and Leslie Greengard, A short course on fast multipole methods, in Wavelets, Multilevel Methods and Elliptic PDEs, Oxford University Press, 1997, Section 3, the fast Gauss transform for the heat kernel, with boxes of side √T and Hermite expansions
  3. Brad J. C. Baxter and George Roussos, A new error estimate of the fast Gauss transform, SIAM Journal on Scientific Computing, 2002, the correction of the error estimate of Lemma 2.1 of Greengard and Strain
  4. Changjiang Yang, Ramani Duraiswami, Nail A. Gumerov and Larry Davis, Improved fast Gauss transform and efficient kernel density estimation, Proceedings of the Ninth IEEE International Conference on Computer Vision, 2003, 664-671, the improved fast Gauss transform for higher dimensions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example