Algorithmresearch
Black-box fast multipole method
Also called bbFMM, Chebyshev fast multipole method.
An FMM for any smooth kernel that interpolates the kernel at Chebyshev nodes and compresses the multipole-to-local operators by singular value decomposition.
- Time
- Θ(N^2) worstΘ(N n^2 + N n^4 / s + N s + L n^4) averageΘ(N n^2) best
- Space
- Θ(N + N n^2 / s + L n^4) extra
- Where
- L = the leaf level; N = the number of charges; n = the number of Chebyshev nodes in each coordinate; s = the mean number of charges in a leaf box
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- William Fong, Eric Darve, 2009
The black-box fast multipole method (bbFMM) computes sums with the tree and the lists of the fast multipole method, for any kernel that is smooth away from and that the code can only evaluate. For two well separated boxes, it replaces by its Chebyshev interpolant in all coordinates of both points. The multipole expansion of a box becomes a set of weights at the Chebyshev nodes of the box, the local expansion becomes a set of values at the same nodes, and the multipole-to-local operator becomes a matrix of kernel values between two sets of nodes. Fong and Darve (2009) gave the method and compressed these matrices with the singular value decomposition, so that the far field uses close to the smallest number of coefficients for a given accuracy.
In plain words
The plain FMM needs a formula for how the pull of a group of charges changes with distance. The black-box FMM only asks for a function that gives the pull of one charge on one point.
For two boxes that are far apart, the pull changes smoothly across each box. A smooth function is well described by its values on a small grid of special points, packed more closely near the edges. So each box spreads its charges onto its grid points, the pull is computed only from grid points to grid points, and each target reads its value back from the grid of its own box. Passing values between a box and its children is exact, because a parent's smooth shape is also smooth inside each child.
More grid points give more digits. Near boxes are still added one pair at a time.
The problem
The input is charges at points of the unit square, a kernel given as a function, and a number of nodes in each coordinate. The output is an approximation of each potential
The kernel must be smooth when and lie in two well separated boxes; it does not have to solve any equation. Here it must also depend on only, so that the matrices can be computed once per level. The examples use , and the inverse multiquadric .
The algorithm
Let , , be the Chebyshev nodes on , and
which is the Lagrange polynomial of the node . Map each box to and write for the tensor nodes of , where is the mapped point. For a target box and a source box in its interaction list,
BBFMM(q, z, K, n, L)- 1
for each leaf C: W_C(m') ← Σ_{i in C} q_i S_C(m', z_i) - 2
for l ← L - 1 down to 2: for each box B at level l: W_B(m) ← Σ over the children C of Σ_{m'} S_B(m, x̄^C_{m'}) W_C(m') for l ← 2 to L dofor each box T at level l do- 3
g_T(m) ← Σ_{C in the interaction list of T} Σ_{m'} K(x̄^T_m, x̄^C_{m'}) W_C(m') - 4
if l < L then for each child D of T: g_D(k) ← g_D(k) + Σ_m g_T(m) S_T(m, x̄^D_k) - 5
for each leaf T and charge j in T: u_j ← Σ_m g_T(m) S_T(m, z_j) - 6
add the direct terms of all charges i ≠ j in T and its near neighbours - 7
return u
Lines L1 to L5 are the P2M, M2M, M2L, L2L and L2P steps of the FMM. Line L1 anterpolates the charges onto the nodes and line L5 interpolates the values back. The shifts of lines L2 and L4 use the matrices of the parent basis at the child nodes, once for each coordinate, so they cost per box. Line L3 uses one matrix of kernel values for each of the offsets of the interaction list, computed once per level.
Fong and Darve also compress line L3. They stack the M2L matrices of a level and take a truncated SVD, so that each translation becomes a product with a small matrix, with set by the tolerance. The code on this page applies the full matrices.
Example
Take uniform points in the unit square with charges uniform in (seed 5), and leaves at level . The near field uses 18302 ordered pairs and there are 1272 M2L products, the same counts as for the analytic FMM on these points. Against direct summation, the relative errors in the 2-norm are:
| values per box | kernel | largest error, | kernel | inverse multiquadric | |
|---|---|---|---|---|---|
| 2 | 4 | ||||
| 3 | 9 | ||||
| 4 | 16 | ||||
| 6 | 36 | ||||
| 8 | 64 | ||||
| 10 | 100 |
These are measurements. The three kernels use the same code; only the function changes. From on, the error falls by a factor of about 6 for each extra node, nearly the same for the three kernels: the rate depends mostly on how far the singularity at is from the pairs of boxes, and the three kernels have it at the same place.
The price is the number of values. With a box holds 64 values for the relative error . On the same points, the analytic FMM with complex terms (24 real values) has , and the kernel-independent FMM with 24 points on each circle has . A tensor grid of nodes holds more numbers than the far field needs, and the SVD compression of Fong and Darve removes this excess.
Correctness
The proof file proves two things. First, the shifts of lines L2 and L4 are exact: a parent basis polynomial has degree in each coordinate, also inside each child, and interpolation at nodes reproduces such polynomials (Lemmas 1 and 2). So the output is exactly the direct sum in which, for every pair of a target box and a box in its interaction list, is replaced by its tensor Chebyshev interpolant in four variables (Lemma 3). The error is then at most times the largest interpolation error over these pairs.
Second, this interpolation error tends to 0. Each 1D interpolation step has the error at most times the best polynomial error, where is the Lebesgue constant of the Chebyshev nodes, and four steps give at most times it. For the three kernels above, the singular points in each scaled coordinate lie outside the Bernstein ellipse with , because the boxes of an interaction list are one box width apart. Then the best error is by the bound on the Chebyshev coefficients of an analytic function. This is a bound on the rate; the measured rate above is faster.
Proof: The bbFMM equals direct summation with the kernel replaced by its Chebyshev interpolant on each far pair, and it converges for kernels analytic away from the diagonalfull
We use exact arithmetic. The tree is uniform, with leaves at level , and the lists are those of the fast multipole method. Let be the Chebyshev nodes on and . For a box with center and side , let , and for let , with the node .
Lemma 1 (Lagrange basis). is the polynomial of degree at most that is 1 at and 0 at the other nodes. Hence, for every polynomial of degree at most , , and the same holds in 2D for polynomials of degree at most in each coordinate.
Proof. The degree is clear. With , , and the discrete orthogonality of the cosines at these angles gives , where the prime halves the term . Multiply by : this is . A polynomial of degree at most is fixed by its values at points, which gives the reproduction. The 2D statement follows by applying the 1D one in each coordinate.
Lemma 2 (the shifts are exact). (a) If is a child of , the upward shift of line L2 maps the weights to . (b) If is a vector of values at the nodes of , the downward shift of line L4 gives values at the nodes of a child with for every .
Proof. (a) The shift computes . As a function of , is a polynomial of degree in each coordinate, also in the coordinates of the child, so by Lemma 1 the inner sum is . (b) The shift sets , and by Lemma 1 in the same way.
Lemma 3 (the output). Let be a charge in leaf , and for a box in the interaction list of an ancestor of let
the tensor Chebyshev interpolant of on with nodes in each of the four coordinates. Then the output is
where the first sum is over the charges in the near neighbours of and the second over the pairs of Lemma 1 of the FMM proof, which split the far charges into disjoint boxes.
Proof. By Lemma 2(a) and induction from the leaves up, after line L2 every box holds . Line L3 adds to the value of at the node . By Lemma 2(b) and induction from the root down, the values of the leaf satisfy for . Line L5 evaluates this at , and substituting gives the second sum. Line L6 adds the first. That the pairs split the far charges is Lemma 1 of the FMM proof, which uses only the tree and the lists.
So the error is , and
Theorem (convergence). Let , for and , be the restriction of a function that, as a function of each one of the four coordinates with the others fixed and real, extends to an analytic function bounded by in the Bernstein ellipse (in the scaled coordinate) for a fixed , for all pairs of the interaction lists. Then , where is the Lebesgue constant of the Chebyshev nodes, and the error of the bbFMM tends to 0 as .
Proof. Write , where is 1D interpolation in coordinate at the scaled nodes; these operators commute. Then . In the sup norm, , and , where is the largest, over the other coordinates, best approximation error of by polynomials of degree in coordinate . The Chebyshev coefficients of a function analytic and bounded by in satisfy (Trefethen, Theorem 8.1), so truncating the Chebyshev series after degree gives . Each term of the decomposition applies some operators to an error of itself, so only the analyticity of in each coordinate is used. The four terms are at most . Since for Chebyshev nodes, the bound tends to 0.
The kernels of the page satisfy the hypothesis. For , or , fix all coordinates but one, say . The function depends on through with (and added), and it is analytic in except where (or ). Two boxes of side in an interaction list are at least apart in one coordinate. If that coordinate is , the singular points have real part at least from the interval of , which has half-length , so they are at least at the scaled distance 2 from along the real axis. Otherwise , and they are at the scaled imaginary distance at least 2. In both cases they lie outside the open ellipse with , whose semi-axes are and 2. The ellipse is simply connected and (plus ) has no zero in it, so a branch of the log and of the square root is analytic there, and the function is bounded on the closed ellipse for any . The offsets of the interaction list and the levels are finitely many, so one and one serve all pairs. For the log kernel the scaling changes the kernel only by a constant, which the interpolation reproduces, so the bound is the same at every level.
Complexity
The model is the real RAM, with kernel evaluations counted as one operation.
- Same structure as the FMM (theorem). The tree and the lists are those of the uniform FMM. Lines L1 and L5 cost per charge, in total. Lines L2 and L4 cost per box. Line L3 costs per pair, at most 27 pairs per box, so . Line L6 costs .
- Precomputation. matrices of kernel values per level, . For a homogeneous kernel such as , the matrices of one level give all the others after scaling.
- With SVD compression. With rank , the M2L products cost each, plus per box to enter and leave the compressed basis. In 3D, with nodes per box and 189 boxes in the interaction list, this is the step that makes the method practical.
- Worst case. With a uniform tree, clustered charges make the near field ; an adaptive tree with the lists of the adaptive FMM avoids this.
- Space. for the weights and values, plus for the matrices.
Properties
- Only kernel values. The code calls only as a function, and only at nodes and at near pairs. The kernel need not solve an equation, unlike for the kernel-independent FMM.
- Exact shifts. The M2M and L2L steps add no error. All the error comes from the interpolation in the M2L step.
- Linear in the charges. The output is a linear function of , so the method is a fast matrix-vector product for iterative solvers of boundary element and integral equations, and for kernel matrices of Gaussian processes.
- Uniform accuracy across levels for the log kernel. Scaling a box changes only by a constant, which interpolation reproduces, so every level has the same relative accuracy.
- Deterministic. The result does not depend on the order of the charges, up to rounding.
Variants and improvements
- SVD compression. Fong and Darve compress the M2L operators of each level by a truncated SVD of the stacked matrices, which also gives the multipole and local bases of the smallest size for a given tolerance in the 2-norm.
- Adaptive trees. The same expansions work on an adaptive tree with the , , and lists of the adaptive FMM; the W and X lists need the conversion between charges and node values.
- Other interpolation nodes. Equispaced nodes make the M2L matrices Toeplitz, so the FFT applies them fast, at the cost of a larger Lebesgue constant and worse stability than Chebyshev nodes.
- Oscillatory kernels. For the Helmholtz kernel at high frequency, must grow with the size of a box in wavelengths, and directional variants of the interpolation are used.
- Higher dimensions. In 3D the box holds nodes and the M2L matrices have entries, so compression is needed for any practical .
When to use it
Use the bbFMM when the kernel is smooth away from the diagonal but has no convenient expansions: kernels given by a formula that is long to expand, kernels that come from a table or another computation, covariance functions, or anisotropic kernels. It is a good choice when you need to change the kernel often. For the Laplace kernel in 2D, the analytic FMM needs fewer coefficients for the same accuracy. For Green's functions of elliptic equations, the kernel-independent FMM is the other black-box choice. For small , use direct summation.
Pitfalls
- Points outside the box. The basis is a polynomial, and it grows fast outside . A charge assigned to the wrong box, for example by a rounding error at the edge of the square, is extrapolated and can give a large error. Clamp the mapped coordinates to .
- Kernels that are not smooth enough. A kernel with a singularity or a fast change at a distance comparable to a box, such as a narrow Gaussian or a kernel with a softening length close to the box size, needs many more nodes. Choose the levels so that the boxes are large or small compared with that length.
- Cost without compression. The M2L step costs per pair in 2D and in 3D. Without the SVD step, the method is slower than the analytic FMM for the same accuracy.
- Matrices per level. For a kernel that is not homogeneous, the M2L matrices differ between levels and must be computed for each level.
- Too few nodes for the accuracy. The rate of convergence on this page depends on the separation of the interaction list and on the kernel. Measure against direct summation on a small problem.
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/black-box-fast-multipole-method/. The authors are listed in prov/T616YW.jsonl.
"""Black-box fast multipole method of Fong and Darve, in 2D on a uniform tree.
Charges q[i] sit at points z[i] (complex numbers) of the unit square. The
output is u_j = sum over i != j of q_i K(z_j, z_i), for any kernel K that is
smooth away from x = y and is given as a function.
For two well separated boxes T and C, the kernel is replaced by its tensor
Chebyshev interpolant with n nodes in each of the four coordinates:
K(x, y) ~ sum_m sum_m' S_T(m, x) K(xbar_m, ybar_m') S_C(m', y),
where xbar_m are the n^2 nodes of T, ybar_m' those of C, and
S(m, x) = S_n(xbar_m1, x1) S_n(xbar_m2, x2) with
S_n(xbar, x) = 1/n + (2/n) sum_{k=1}^{n-1} T_k(xbar) T_k(x)
on [-1, 1] (the Lagrange polynomial of the Chebyshev node xbar). The
multipole weights of a box are W_C(m') = sum_i q_i S_C(m', y_i), and the
local values of a box are g_T(m) = sum K(xbar_m, ybar_m') W_C(m'). The
shifts between parent and child boxes are interpolation steps, which are
exact because S_parent(m, .) is a polynomial of degree n - 1.
"""
import math
from typing import Callable, Optional, Sequence
Kernel = Callable[[complex, complex], float]
def log_kernel(x: complex, y: complex) -> float:
return math.log(abs(x - y))
def inverse_distance(x: complex, y: complex) -> float:
return 1.0 / abs(x - y)
def cheb_nodes(n: int) -> list[float]:
"""The n Chebyshev nodes of the first kind, cos((2m - 1) pi / (2n)), m = 1..n."""
return [math.cos((2 * m - 1) * math.pi / (2 * n)) for m in range(1, n + 1)]
def cheb_T(n: int, x: float) -> list[float]:
"""T_0(x), ..., T_{n-1}(x) by the three-term recurrence."""
t = [1.0, x][:n]
while len(t) < n:
t.append(2 * x * t[-1] - t[-2])
return t
def s_weights(n: int, nodes: Sequence[float], x: float) -> list[float]:
"""[S_n(xbar_m, x) for each node xbar_m], for x in [-1, 1]."""
tx = cheb_T(n, x)
out = []
for xm in nodes:
tm = cheb_T(n, xm)
out.append(1.0 / n + (2.0 / n) * sum(tm[k] * tx[k] for k in range(1, n)))
return out
def box_center(ix: int, iy: int, level: int) -> complex:
h = 1.0 / (1 << level)
return complex((ix + 0.5) * h, (iy + 0.5) * h)
def interaction_list(ix: int, iy: int, level: int) -> list[tuple[int, int]]:
"""Children of the near neighbours of the parent that are not near neighbours of the box."""
m = 1 << level
px, py = ix // 2, iy // 2
out = []
for nx in range(2 * (px - 1), 2 * (px + 2)):
for ny in range(2 * (py - 1), 2 * (py + 2)):
if 0 <= nx < m and 0 <= ny < m and max(abs(nx - ix), abs(ny - iy)) > 1:
out.append((nx, ny))
return out
def box_nodes(center: complex, w: float, nodes: Sequence[float]) -> list[complex]:
"""The n^2 tensor Chebyshev nodes of a box of side w, index m = m1 * n + m2."""
return [center + 0.5 * w * complex(a, b) for a in nodes for b in nodes]
def p2m(q, z, idx, center: complex, w: float, n: int, nodes) -> list[float]:
"""W(m) = sum_i q_i S(m, y_i), with y_i mapped to [-1, 1]^2."""
wt = [0.0] * (n * n)
for i in idx:
sx = s_weights(n, nodes, 2 * (z[i].real - center.real) / w)
sy = s_weights(n, nodes, 2 * (z[i].imag - center.imag) / w)
for m1 in range(n):
a = q[i] * sx[m1]
for m2 in range(n):
wt[m1 * n + m2] += a * sy[m2]
return wt
def child_shift(n: int, nodes) -> dict:
"""S1[a][m][m'] = S_n(xbar_m, (xbar_m' + 2a - 1) / 2): parent basis at the child nodes, a = 0 or 1."""
return {a: [s_weights(n, nodes, (xm + 2 * a - 1) / 2) for xm in nodes] for a in (0, 1)}
def _shift_up(wc: Sequence[float], sa, sb, n: int) -> list[float]:
"""Parent weights from child weights: W_p(m1, m2) = sum S1[a][m'1][m1] S1[b][m'2][m2] W_c(m'1, m'2)."""
tmp = [0.0] * (n * n)
for k1 in range(n):
for m2 in range(n):
tmp[k1 * n + m2] = sum(sb[k2][m2] * wc[k1 * n + k2] for k2 in range(n))
out = [0.0] * (n * n)
for m1 in range(n):
for m2 in range(n):
out[m1 * n + m2] = sum(sa[k1][m1] * tmp[k1 * n + m2] for k1 in range(n))
return out
def _shift_down(gp: Sequence[float], sa, sb, n: int) -> list[float]:
"""Child values from parent values: g_c(k1, k2) = sum S1[a][k1][m1] S1[b][k2][m2] g_p(m1, m2)."""
tmp = [0.0] * (n * n)
for m1 in range(n):
for k2 in range(n):
tmp[m1 * n + k2] = sum(sb[k2][m2] * gp[m1 * n + m2] for m2 in range(n))
out = [0.0] * (n * n)
for k1 in range(n):
for k2 in range(n):
out[k1 * n + k2] = sum(sa[k1][m1] * tmp[m1 * n + k2] for m1 in range(n))
return out
def m2l_matrices(kernel: Kernel, level: int, nodes) -> dict:
"""[K(xbar_m, ybar_m')] for a target box at 0 and a source box at each offset of the interaction list."""
w = 1.0 / (1 << level)
tgt = box_nodes(0j, w, nodes)
out = {}
for dx in range(-3, 4):
for dy in range(-3, 4):
if max(abs(dx), abs(dy)) > 1:
src = box_nodes(complex(dx * w, dy * w), w, nodes)
out[(dx, dy)] = [[kernel(x, y) for y in src] for x in tgt]
return out
def bbfmm(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel, n: int = 5,
levels: Optional[int] = None, s: int = 8):
"""Potentials u_j = sum_{i != j} q_i K(z_j, z_i) with n Chebyshev nodes per coordinate.
levels is the leaf level L (at least 2). Returns (u, stats) with the
ordered pairs of the near field ("p2p") and the M2L products ("m2l").
"""
nq = len(z)
if levels is None:
levels = max(2, math.ceil(math.log(nq / s, 4))) if nq > s else 2
L = levels
nodes = cheb_nodes(n)
shift = child_shift(n, nodes)
mats = {l: m2l_matrices(kernel, l, nodes) for l in range(2, L + 1)}
m = 1 << L
leaf: dict[tuple[int, int], list[int]] = {}
for i, zi in enumerate(z):
key = (min(int(zi.real * m), m - 1), min(int(zi.imag * m), m - 1))
leaf.setdefault(key, []).append(i)
mult: list[dict] = [dict() for _ in range(L + 1)]
for key, idx in leaf.items(): # @line L1
mult[L][key] = p2m(q, z, idx, box_center(*key, L), 1.0 / m, n, nodes)
for l in range(L - 1, 1, -1): # @line L2
for (cx, cy), wc in mult[l + 1].items():
acc = mult[l].setdefault((cx // 2, cy // 2), [0.0] * (n * n))
up = _shift_up(wc, shift[cx % 2], shift[cy % 2], n)
for k in range(n * n):
acc[k] += up[k]
local: list[dict] = [dict() for _ in range(L + 1)]
n_m2l = 0
for l in range(2, L + 1):
for key, wc in mult[l].items(): # @line L3
for tgt in interaction_list(*key, l):
if l == L and tgt not in leaf:
continue
mat = mats[l][(key[0] - tgt[0], key[1] - tgt[1])]
acc = local[l].setdefault(tgt, [0.0] * (n * n))
for k in range(n * n):
acc[k] += sum(a * b for a, b in zip(mat[k], wc))
n_m2l += 1
if l < L:
for (px, py), gp in local[l].items(): # @line L4
for a in (0, 1):
for b in (0, 1):
down = _shift_down(gp, shift[a], shift[b], n)
acc = local[l + 1].setdefault((2 * px + a, 2 * py + b), [0.0] * (n * n))
for k in range(n * n):
acc[k] += down[k]
u = [0.0] * nq
n_p2p = 0
w = 1.0 / m
for key, idx in leaf.items():
g = local[L].get(key)
c = box_center(*key, L)
if g is not None:
for j in idx: # @line L5
sx = s_weights(n, nodes, 2 * (z[j].real - c.real) / w)
sy = s_weights(n, nodes, 2 * (z[j].imag - c.imag) / w)
u[j] += sum(sx[m1] * sum(sy[m2] * g[m1 * n + m2] for m2 in range(n)) for m1 in range(n))
ix, iy = key
for nx in range(ix - 1, ix + 2): # @line L6
for ny in range(iy - 1, iy + 2):
for i in leaf.get((nx, ny), ()):
for j in idx:
if i != j:
u[j] += q[i] * kernel(z[j], z[i])
n_p2p += 1
return u, {"p2p": n_p2p, "m2l": n_m2l} # @line L7
def direct(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel) -> list[float]:
"""Direct summation over all ordered pairs: the reference."""
nq = len(z)
return [sum(q[i] * kernel(z[j], z[i]) for i in range(nq) if i != j) for j in range(nq)]
test_black_box_fast_multipole_method.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/black-box-fast-multipole-method/. The authors are listed in prov/T616YW.jsonl.
"""Tests for the black-box FMM: Chebyshev interpolation, exact shifts and three kernels against direct summation."""
import math
import random
import unittest
from black_box_fast_multipole_method import (
_shift_down,
_shift_up,
bbfmm,
box_center,
cheb_nodes,
child_shift,
direct,
inverse_distance,
log_kernel,
p2m,
s_weights,
)
def inverse_multiquadric(x, y):
return 1.0 / math.sqrt(abs(x - y) ** 2 + 0.01)
def rel(a, b):
return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) / math.sqrt(sum(y * y for y in b))
def uniform(n, seed):
rng = random.Random(seed)
z = [complex(rng.random(), rng.random()) for _ in range(n)]
q = [rng.uniform(-1, 1) for _ in range(n)]
return q, z
class TestChebyshev(unittest.TestCase):
def test_lagrange_property(self):
n = 6
nodes = cheb_nodes(n)
for k, xk in enumerate(nodes):
s = s_weights(n, nodes, xk)
for m in range(n):
self.assertAlmostEqual(s[m], 1.0 if m == k else 0.0, places=12)
def test_reproduces_polynomials(self):
n = 5
nodes = cheb_nodes(n)
def poly(t):
return 3 * t ** 4 - t ** 3 + 0.5 * t - 2
for x in (-1.0, -0.3, 0.2, 0.9):
s = s_weights(n, nodes, x)
self.assertAlmostEqual(sum(poly(xm) * sm for xm, sm in zip(nodes, s)), poly(x), places=12)
class TestShifts(unittest.TestCase):
def test_upward_shift_is_exact(self):
n = 4
nodes = cheb_nodes(n)
shift = child_shift(n, nodes)
rng = random.Random(3)
level = 3
w = 1.0 / (1 << level)
child = (5, 2)
c = box_center(*child, level)
z = [c + complex((rng.random() - 0.5) * w, (rng.random() - 0.5) * w) for _ in range(7)]
q = [rng.uniform(-1, 1) for _ in range(7)]
wc = p2m(q, z, range(7), c, w, n, nodes)
up = _shift_up(wc, shift[child[0] % 2], shift[child[1] % 2], n)
wp = p2m(q, z, range(7), box_center(2, 1, 2), 2 * w, n, nodes)
for a, b in zip(up, wp):
self.assertAlmostEqual(a, b, places=12)
def test_downward_shift_is_exact(self):
n = 4
nodes = cheb_nodes(n)
shift = child_shift(n, nodes)
rng = random.Random(4)
gp = [rng.uniform(-1, 1) for _ in range(n * n)]
gc = _shift_down(gp, shift[1], shift[0], n)
for _ in range(5):
x, y = rng.uniform(-1, 1), rng.uniform(-1, 1)
px, py = (x + 1) / 2, (y - 1) / 2
sx, sy = s_weights(n, nodes, x), s_weights(n, nodes, y)
tx, ty = s_weights(n, nodes, px), s_weights(n, nodes, py)
child_val = sum(sx[a] * sy[b] * gc[a * n + b] for a in range(n) for b in range(n))
parent_val = sum(tx[a] * ty[b] * gp[a * n + b] for a in range(n) for b in range(n))
self.assertAlmostEqual(child_val, parent_val, places=12)
class TestBBFMM(unittest.TestCase):
def test_log_kernel_matches_direct(self):
q, z = uniform(400, 5)
ud = direct(q, z)
errs = []
for n in (2, 4, 6, 8):
u, st = bbfmm(q, z, n=n, levels=3)
errs.append(rel(u, ud))
for k in range(3):
self.assertLess(errs[k + 1], errs[k] / 10)
self.assertLess(errs[-1], 1e-7)
self.assertEqual(st["m2l"], 1272)
def test_other_kernels(self):
q, z = uniform(300, 6)
for kernel in (inverse_distance, inverse_multiquadric):
ud = direct(q, z, kernel)
u, _ = bbfmm(q, z, kernel=kernel, n=6, levels=3)
self.assertLess(rel(u, ud), 1e-5)
def test_leaf_level_two(self):
q, z = uniform(200, 7)
ud = direct(q, z)
u, _ = bbfmm(q, z, n=6, levels=2)
self.assertLess(rel(u, ud), 1e-5)
def test_linear_in_the_charges(self):
q, z = uniform(150, 8)
rng = random.Random(9)
r = [rng.uniform(-1, 1) for _ in range(150)]
u1, _ = bbfmm(q, z, n=4, levels=3)
u2, _ = bbfmm(r, z, n=4, levels=3)
u3, _ = bbfmm([a - 2 * b for a, b in zip(q, r)], z, n=4, levels=3)
for a, b, c in zip(u1, u2, u3):
self.assertAlmostEqual(c, a - 2 * b, places=9)
def test_small_inputs(self):
self.assertEqual(bbfmm([], [])[0], [])
self.assertEqual(bbfmm([1.0], [complex(0.4, 0.6)])[0], [0.0])
q = [1.0, -2.0, 0.5]
z = [complex(0.1, 0.1), complex(0.9, 0.8), complex(0.15, 0.85)]
u, _ = bbfmm(q, z, kernel=log_kernel, n=8)
for a, b in zip(u, direct(q, z)):
self.assertAlmostEqual(a, b, places=5)
if __name__ == "__main__":
unittest.main()
History
Interpolation of smooth kernels on hierarchical boxes was used before 2009 in several fast summation methods. Fong and Darve (2009) gave the black-box FMM: tensor Chebyshev interpolation of the kernel inside the FMM tree, with exact shifts between levels and a compression of the M2L operators by singular value decompositions. Their aim was a method for kernels that are known only numerically, or that are known analytically but are complicated, with a small precomputation time even for large systems. The kernel-independent FMM of Ying, Biros and Zorin (2004) is the other main FMM that needs no analytic expansions; it needs a kernel that is the Green's function of an elliptic equation.
References
- William Fong and Eric Darve, The black-box fast multipole method, Journal of Computational Physics 228(23), 2009, 8712-8725, the sections on Chebyshev interpolation, the black-box FMM with Chebyshev interpolation, and the fast convolution by SVD compression
- Lloyd N. Trefethen, Approximation Theory and Approximation Practice, SIAM, 2013, Chapter 8, Theorems 8.1 and 8.2, the decay of the Chebyshev coefficients and the accuracy of Chebyshev approximations of analytic functions
- Rick Beatson and Leslie Greengard, A short course on fast multipole methods, in Wavelets, Multilevel Methods and Elliptic PDEs, Oxford University Press, 1997, Section 4, the tree, the interaction list and the operation count of the FMM that the black-box method keeps
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 T616YW Edit this page History Report an error Markdown