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
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Leslie Greengard, John Strain, 1991
The fast Gauss transform (FGT) evaluates the discrete Gauss transform
in work proportional to , with a constant that depends only on the dimension and the precision. Direct evaluation costs kernel evaluations. The method puts the points in a grid of boxes of side proportional to . 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 sources with weights , targets , all in the unit square, a width , a number of terms in each coordinate and a range . The output is an approximation of every , with an error at most a fixed small multiple of .
The algorithm
Scale every coordinate by , so the kernel is . Let be the Hermite functions, computed by , and use the multi-index notation , and . For a source near a center and a target near a center , the Hermite and Taylor expansions are
Cut the square into boxes of side . A source box is big if it has more than sources, and a target box is big if it has more than targets. Each target box looks at the source boxes at most boxes away in each coordinate.
FGT(q, s, t, δ, p, n)- 1
for each big source box B: A_B(α) ← Σ_{j in B} q_j (s_j - c_B)^α / α!, for α_1, α_2 < p for each target box C and each source box B at most n boxes away do- 2
if 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 - 3
if B is small and C is big: T_C(β) += Σ_{j in B} q_j h_β(s_j - c_C) / β! - 4
if B is big and C is small: G(t_i) += Σ_α A_B(α) h_α(t_i - c_B) for each t_i in C - 5
if B and C are big: T_C(β) += ((-1)^{|β|} / β!) Σ_α A_B(α) h_{α+β}(c_C - c_B) - 6
for each big target box C and t_i in C: G(t_i) += Σ_β T_C(β) (t_i - c_C)^β - 7
return G
Line L5 converts a Hermite expansion into a Taylor expansion. Since , it is done one coordinate at a time in operations instead of . Greengard and Strain take and of order in dimension , which balances the four kinds of work; the code takes . Their boxes have side with ; this page uses , the side of the short course of Beatson and Greengard for the heat kernel .
Example
Take sources and targets uniform in the unit square, weights uniform in (seed 11), and . The boxes have side , so there are 25 boxes and, with , all 625 pairs interact. Forcing one of the three expansion methods for all pairs gives the largest error divided by :
| sources to Taylor (L3) | Hermite to targets (L4) | Hermite to Taylor (L5) | bound of the proof | |
|---|---|---|---|---|
| 2 | ||||
| 4 | ||||
| 6 | ||||
| 8 | ||||
| 10 | ||||
| 12 |
These are measurements, and the last column is the bound of the proof. Each two more terms give about two more digits. With the cutoffs and , 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 .
The range matters when the boxes are small. With there are boxes, and with all pairs direct, the error divided by for the ranges is , , , , and , below the bounds , which are , , , , and .
Correctness
The proof file proves the bound . 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 (), the Taylor part () or both. Cramér's inequality , with , and bound the omitted terms by , because the offsets are at most . A product of two such factors has the error at most . Sources in skipped boxes are at least away in the scaled coordinates, so they contribute at most 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 , in which the kernel is and the boxes have side . So a point and the center of its box differ by at most in each coordinate. Let , where is the Hermite polynomial, and let .
The double series. Fix a source in box (center ) and a target in box (center ), and look at one coordinate. Write , and , so and . Taylor's theorem for the entire function gives , and since , also . Hence
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 . Line L3 (sources to Taylor) computes ; since and , this is . Line L5 with line L6 (Hermite to Taylor) computes : the Taylor coefficient of order is , with the Hermite coefficients . In 2D, the coefficients are products over the two coordinates, so for each source the algorithm computes the product of two such partial sums, while the true term is with . In every case the omitted terms of a coordinate have or .
Lemma 1 (tails). Let and . Then , where .
Proof. Cramér's inequality for Hermite polynomials, as stated in Section 2 of Greengard and Strain (1991), says for all real , with , so . Since , we have . With ,
The sum over and all is at most , and so is the sum over and all .
Lemma 2 (range). If is more than boxes from in some coordinate, then every source in and target in satisfy .
Proof. The index difference is at least , so at least whole boxes of side lie between and in that coordinate, and .
Theorem. For every target , the output of the algorithm satisfies
Proof. Each source contributes through exactly one pair of boxes, the pair of its box and the box of , so the error is a sum over sources. For a source in a skipped box, the error is by Lemma 2. For any other source, by Lemma 1, , and , so and
Multiply by and add.
For , the factor is about , , , and . The bound does not depend on , , the positions or , and it decays faster than geometrically in , since is about .
Complexity
The model is the real RAM, with counted as one operation.
- Linear work (theorem). Line L1 costs per source and line L6 per target. With , every pair of boxes costs : a direct pair has at most kernel evaluations, the pairs of lines L3 and L4 at most , and line L5 is by the product form. There are at most pairs, so the total is , and is at most and at most the number of boxes, .
- Constant set by the precision. For a fixed error, and are fixed, so the work is . Greengard and Strain report, for their 2D Fortran code with terms and , a time of 205 seconds for 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 .
- Dimension. In dimensions the expansions have terms and the range has boxes, so the constant grows exponentially with ; this is the limit that the improved FGT addresses.
- Space. for the points and 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 , not of . Where the field is small compared with , 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 , so the method is a fast product with the matrix .
- 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 , about instead of , 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 . Forgetting the scaling, or using boxes much larger than , 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 can be much larger than the result.
- Range too small. The cutoff error is about in the scaled units of this page. For the same precision, smaller boxes need a larger .
- Too many terms in many dimensions. In dimensions the tensor expansions have terms; for 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 .
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.
# 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 dimensions, a grid of boxes of side proportional to , four ways for a pair of boxes chosen by the cutoffs and , 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
- 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag PHV9XM Edit this page History Report an error Markdown