Algorithmadvanced
Adaptive fast multipole method
Also called Carrier-Greengard-Rokhlin algorithm.
Refines the FMM tree only where particles are dense and uses four interaction lists (U, V, W and X), so the cost stays near linear in N for strongly nonuniform distributions.
- Time
- O(D N (p^2 / s + p + s)) worstΘ(N p^2 / s + N s) averageΘ(N p) best
- Space
- O(N + D N p / s) extra
- Where
- D = the number of levels of the tree; N = the number of charges; p = the number of terms of each expansion; s = the largest number of charges in a leaf
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- J. Carrier, Leslie Greengard, Vladimir Rokhlin, 1988
The adaptive fast multipole method computes the potentials and fields of charges on each other, like the fast multipole method, but on a tree that follows the charges. A box of the quadtree is split only when it holds more than charges, and empty boxes are dropped, so dense clusters get deep, small leaves and empty regions get none. Leaves of different sizes can then touch, and the single interaction list of the uniform method is replaced by four lists. The list does the usual multipole-to-local translations between boxes of one size. The and lists connect a leaf with smaller boxes near it, and the list holds the adjacent leaves for the direct sum. Carrier, Greengard and Rokhlin (1988) gave the method in 2D; this page uses the list names of Ying, Biros and Zorin (2004).
In plain words
The plain FMM cuts the square into equal boxes. If most particles sit in a few small clumps, most boxes are empty and a few boxes are full, and the full boxes make the near sums slow. The adaptive FMM cuts a box again only when it has too many particles. So the boxes are small where the particles are crowded and large where they are thin.
Now a big box can touch small boxes. A small box that is near a big box but does not touch it is still far enough for a short summary. The method uses the summary of the small box at each particle of the big box, and it turns the particles of the big box into a summary for the small box. All other steps are as in the plain FMM.
The problem
The input is real charges at distinct points of the unit square, written as complex numbers, a number of terms and a leaf size . The output is an approximation of each potential and field
with the field written as a complex number, for . The charges can be distributed in any way; the method should not slow down much when they are strongly clustered.
The algorithm
Two boxes are adjacent if their closed squares share a point, and colleagues if they are adjacent and of the same level. For a leaf :
- is the set of leaves adjacent to , with itself.
- , defined for every box at level 2 or deeper, is the set of children of the colleagues of the parent of that are not adjacent to . It is the interaction list of the uniform FMM, at most 27 boxes.
- is the set of boxes that descend from a colleague of , are not adjacent to , but have a parent that is adjacent to . They are smaller than .
- is the set of leaves with . It is the inverse of .
ADAPTIVE-FMM(q, z, p, s)- 1
build the tree: split each box with more than s charges, and drop empty boxes - 2
build U(b) and W(b) for each leaf b, V(b) for each box b, and X as the inverse of W - 3
for each box B from the finest level up: a_B ← P2M of the charges of B if B is a leaf, else Σ M2M(a_C) over the children C for each box B from the root down do- 4
b_B ← Σ M2L(a_C) over C in V(B) + Σ P2L(charges of C) over C in X(B) - 5
b_B ← b_B + L2L(b_P), where P is the parent of B for each leaf T and each charge j in T do- 6
u_j, field_j ← local expansion b_T at z_j + Σ multipole expansion a_C at z_j over C in W(T) - 7
add the direct terms of all charges i ≠ j in the leaves of U(T); return u, field
P2M, M2M, M2L and L2L are the translations of the fast multipole method. The two new operations are:
- M2P, line L6 (the list): evaluate the multipole expansion of a small box at each target of the leaf, and its derivative .
- P2L, line L4 (the list): add the charges of a large leaf directly into the local expansion about the center of a small box, with and .
The leaf can find its lists without a search over all boxes. The coarser leaves of are leaf colleagues of the ancestors of . The finer leaves of and all of come from one descent from the colleagues of : a child that touches is followed further, and a child that does not touch goes into .
Example
Take charges uniform in : 85 percent of the points are in three Gaussian clusters of standard deviation about , and , and the rest are uniform in the unit square (the generator of the test file, seed 3). With the tree has 144 boxes and 104 leaves at the levels 2 to 7. The lists have 750 (), 850 (), 310 () and 310 () entries in total, and no list has more than 15 boxes. The near field uses 14266 ordered pairs, against for direct summation. Against direct summation:
| relative error of (2-norm) | largest error of | relative error of the field (2-norm) | |
|---|---|---|---|
| 3 | |||
| 6 | |||
| 9 | |||
| 12 | |||
| 16 | |||
| 20 |
These are measurements. The errors fall at the same rate as for the uniform FMM on uniform points. For the same charges, the uniform FMM of the fast multipole method page with leaves at level 3 uses 47596 ordered pairs in the near field. With leaves at level 6 it uses 14180 pairs, but it needs 5404 M2L translations, against 850 here, because a uniform tree that is deep enough for the clusters has many boxes in the thin background.
Correctness
The proof is in the proof file. Adjacency of the ancestors of two leaves holds at an initial range of levels. A case analysis on the level where it first fails, and on which leaf is coarser, shows that each source leaf reaches each target leaf by exactly one of the four routes: the direct sum (), one M2L at a common level (), one multipole evaluation of a smaller box (), or one direct local expansion into a smaller box () (Lemma 3). The boxes are separated as in the uniform method, so Lemma 4.7 of Beatson and Greengard bounds their error with the ratio . A box of is at least of its own sides from every point of , so the truncation bound applies with the ratio , and the same holds for (Lemma 4). The translations M2M and L2L are exact, so the total error is at most times a factor that tends to 0 as grows (Theorem).
Proof: The four lists of the adaptive FMM use each source leaf exactly once for each target leaf, and every far route is well separatedfull
We use exact complex arithmetic. The tree is the one of line L1: a box of side at level is split when it holds more than charges, and empty children are dropped. So every box holds at least one charge, and a box is a leaf exactly when it has no children. Two boxes are adjacent if their closed squares share at least one point; a box is adjacent to itself. Colleagues are adjacent boxes of the same level. For a box at level and , is the ancestor of at level , with . The lists are as in line L2:
- , for a leaf : the leaves adjacent to .
- , for a box at level : the children of the colleagues of that are not adjacent to .
- , for a leaf : the boxes that are descendants of a colleague of , are not adjacent to , and whose parent is adjacent to .
- : the leaves with .
Lemma 1 (adjacency is inherited upward). If boxes and are adjacent, so are their parents, and so are and the parent of . Hence, along the ancestors of two leaves, the levels at which and are adjacent form an initial segment , and along the ancestors of , the boxes adjacent to a fixed box form an initial segment too.
Proof. A box is contained in its parent, so a shared point of and is a shared point of the larger boxes. Level 0 is the root, which is adjacent to itself.
Lemma 2 (the lists computed by the code are the lists defined above). For a leaf , the code puts into the box , the leaf colleagues of the proper ancestors of that are adjacent to , and the leaves reached by a descent from the colleagues of through adjacent boxes; it puts into the children met in this descent that are not adjacent to .
Proof. Let be a leaf adjacent to at level . If , the ancestor contains , so is adjacent to and is a colleague of it. If , the ancestor is adjacent to by Lemma 1 and is a colleague of , and : if then , and if then has children while the leaf has none. All the boxes between and are adjacent to by Lemma 1, so the descent, which follows every adjacent child, reaches . Conversely, each box the code adds to is a leaf adjacent to , and each leaf is added once, at its own level. For : the descent visits exactly the descendants of colleagues of whose ancestors down to the colleague are all adjacent to , and it records a child exactly when it is not adjacent; by Lemma 1 this is the set of descendants that are not adjacent to and have an adjacent parent.
Lemma 3 (each pair of leaves is covered exactly once). Let and be leaves at levels and . Then exactly one of the following holds:
- ;
- for some (and then is unique);
- for some (unique);
- for some (unique).
Proof. Let , and let be the levels at which and are adjacent (Lemma 1), with .
Case A: . At , the boxes and exist, are not adjacent, and have adjacent parents, which are colleagues. So . A relation between an ancestor of and an ancestor of needs the same level, non-adjacency at that level and adjacency one level up, so is the only one. Route 1 fails, because and are inside the non-adjacent boxes and . Route 3 would need an ancestor with whose parent is adjacent to ; then , which contains that parent, would be adjacent to , but . Route 4 fails in the same way with the roles exchanged.
Case B: and . Then and are adjacent leaves, so route 1 holds. Route 2 needs non-adjacency at a level at most . Routes 3 and 4 need a box of one leaf at a level finer than the other leaf, which is not an ancestor of a leaf of the same level.
Case C: . The box is adjacent to , and it is not , since is a leaf and has the descendant ; so it is a colleague of . Route 2 fails, since . Route 4 fails, since needs , a box finer than , but . If is adjacent to , route 1 holds and route 3 fails, since all ancestors of contain and are adjacent to . If not, let be the coarsest ancestor of that is not adjacent to . By Lemma 1, , the parent is adjacent to , and descends from the colleague , so , and by Lemma 1 it is the only ancestor of in . Route 1 fails because is not adjacent to .
Case D: . This is Case C with and exchanged: either , or the coarsest ancestor of that is not adjacent to has , that is , and no other route holds.
Lemma 4 (separation). (a) If , both of side , the centers are at least apart. (b) If , the box has side smaller than the side of , and every point of is at distance at least from the center of . So the charges of , which lie within of its center, and the points of satisfy . (c) The same ratio holds for , with the charges in and the targets in and its descendants.
Proof. (a) Two boxes of one level that are not adjacent are at least one side apart in one coordinate, so their centers differ by at least in it. (b) The box descends from a colleague of , so its level is finer. The boundaries of lie on the grid of spacing . The closed squares of and are disjoint, so in one coordinate they are separated by a gap of at least , and each point of differs from the center of by at least in that coordinate. (c) The pairs are the same as in (b), and the descendants of lie in .
Theorem. Let be the output for a charge in leaf , the exact potential without the self term, and . With and ,
The bound tends to as .
Proof. By Lemma 3 the charges other than are split into disjoint groups, one for each source leaf , and each group reaches by exactly one route. Route 1 is the direct sum of line L7, which is exact and leaves out . The multipole coefficients of each box are exact after line L3 (P2M at the leaves, then the exact M2M of Lemma 2 of the fast multipole method proof). The L2L shifts of line L5 are exact (Lemma 3 of the same proof). So the only errors are the truncations of the far routes. Route 2: by Lemma 4(a), Lemma 4.7 of Beatson and Greengard bounds the error of the M2L step for the box , at every point of , by times the first factor, as in Lemma 4 of the FMM proof. Route 3: the box is evaluated at from its -term multipole expansion; by Lemma 4(b) and the 2D truncation bound the error is at most times the second factor. Route 4: the local expansion of the charges of about the center of is the series , and by Lemma 4(c) the tail after is at most . The errors add, and the sums over the disjoint source groups add to at most .
The same argument with the derivatives of the series gives the convergence of the field. Since , the and routes converge faster than the route, and the first factor is the larger one for every ; so the bound is the same as for the uniform FMM.
Complexity
The model is the real RAM, with the number of levels of the tree.
- Boxes (theorem). A box is split only if it holds more than charges, and the boxes of one level are disjoint, so each level has at most split boxes and at most boxes. The tree has boxes.
- Lists (theorem). Each list has at most 27 boxes. A leaf touches only a bounded number of leaves that are at least as large as it, so the lists have entries in total. A box is in only for leaves that touch the parent of and are at least as large as it, so the and lists also have entries in total.
- Work. P2M and L2P cost ; M2M, L2L and M2L cost per box and list entry; M2P and P2L cost per list entry; the direct sum costs per entry of . The total is . For a depth that does not grow with , this is for fixed and .
- Any distribution. The depth can grow without bound if two charges are very close, so the bound above is not for every input. Nabors, Korsmeyer, Leighton and White (1994) proved an bound for every distribution for an adaptive scheme that also compresses chains of boxes with one child.
- Measured. For the clustered generator of the example, with and , the near field uses 38.4, 39.7 and 41.5 ordered pairs per charge, and the tree has 165, 611 and 2388 boxes, for , and : both grow linearly with .
- Reported. Carrier, Greengard and Rokhlin report that, for 25600 particles in a strongly nonuniform distribution, their code was about 200 times faster than direct summation, about 3 times faster than the nonadaptive FMM and needed about a quarter of its storage.
- Space. for the charges and coefficients per box, so .
Properties
- Same accuracy as the uniform FMM. The new routes and have a smaller ratio than , so the error bound is the one of the uniform method.
- Linear in the charges. The output is a linear function of , so the method is a fast matrix-vector product inside iterative solvers.
- Exact near field. All pairs of adjacent leaves, of any sizes, are summed directly.
- Deterministic. The tree and the lists depend only on the positions and on , not on the order of the charges.
Variants and improvements
- Kernel independent and black box versions. The kernel-independent FMM uses the same four lists with equivalent densities, and the black-box FMM with Chebyshev interpolation.
- Three dimensions. The same lists work on an octree; the list has up to 189 boxes.
- Level-restricted trees. Many codes refine the tree further so that adjacent leaves differ by at most one level (a 2:1 balance). Then the and lists are short and the cost per box is bounded.
- Pruning only. Beatson and Greengard (Section 4.2) describe a simpler adaptive scheme that only drops empty boxes of a uniform tree.
- Parallel trees. A hashed oct-tree with keys on a Z-order curve lets parallel codes distribute the boxes and find the lists by key arithmetic.
When to use it
Use the adaptive FMM when the charges are strongly nonuniform, for example particles in clusters, boundary points of complicated curves, or vortex sheets that roll up, and you need a guaranteed accuracy. For nearly uniform points, the uniform FMM is simpler and as fast. For low accuracy, the Barnes-Hut algorithm, which is adaptive by nature, is simpler. For small , use direct summation.
Pitfalls
- Missing or double interactions. The four lists must cover each pair of leaves exactly once. A small error in the definition of adjacency, for example open instead of closed squares, loses corner neighbours or counts them twice. Test the coverage of every pair of leaves on a small clustered input.
- The order of the downward pass. The contributions are added into the local expansion of a box before L2L passes it to the children. If they are added at the leaves only, the descendants of a box of miss them.
- Coincident points. Two equal points make every box that holds them split forever. Limit the depth, and treat equal points by the near field.
- Long and lists. Without a 2:1 balance, a large leaf next to a deeply refined region can have very long lists. The total is bounded, but the work per box is not.
- Leaf size. A small makes many boxes and many translations; a large makes the direct sums slow. Choose near in 2D and measure.
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/adaptive-fast-multipole-method/. The authors are listed in prov/B4084E.jsonl.
"""Adaptive fast multipole method of Carrier, Greengard and Rokhlin for the 2D logarithmic kernel.
Charges q[i] sit at distinct points z[i] (complex numbers) of the unit square
[0, 1) x [0, 1). The potential at charge j is
u_j = sum over i != j of q_i log|z_j - z_i|,
and the field grad u_j is returned as a complex number, conj(phi'(z_j)).
A box is split when it holds more than s charges, so the leaves are at many
levels. Empty boxes are dropped. A box is a key (level, ix, iy). Each leaf b
has four lists, with the names of Ying, Biros and Zorin:
U(b) the leaves adjacent to b, b included (direct sum)
V(b) the children of the colleagues of the parent
of b that are not adjacent to b (any box b) (multipole to local)
W(b) the descendants of colleagues of b that are
not adjacent to b but whose parent is (multipole to target)
X(b) the boxes c with b in W(c) (source to local)
Colleagues are adjacent boxes of the same level. The expansions are the
complex Laurent and Taylor series of Beatson and Greengard, Section 4.
"""
import cmath
import math
from math import comb
from typing import Sequence
Box = tuple[int, int, int]
def binomials(p: int) -> list[list[int]]:
"""Table C[n][k] = n choose k for 0 <= n, k <= 2p."""
return [[comb(n, k) for k in range(2 * p + 1)] for n in range(2 * p + 1)]
def box_center(b: Box) -> complex:
l, ix, iy = b
h = 1.0 / (1 << l)
return complex((ix + 0.5) * h, (iy + 0.5) * h)
def adjacent(a: Box, b: Box) -> bool:
"""True if the closed squares of a and b share at least one point."""
la, ax, ay = a
lb, bx, by = b
top = max(la, lb)
sa = 1 << (top - la)
sb = 1 << (top - lb)
return (ax * sa <= (bx + 1) * sb and bx * sb <= (ax + 1) * sa
and ay * sa <= (by + 1) * sb and by * sb <= (ay + 1) * sa)
def build_tree(z: Sequence[complex], s: int, max_level: int = 30):
"""Split every box with more than s charges. Returns (members, children)."""
members: dict[Box, list[int]] = {(0, 0, 0): list(range(len(z)))}
children: dict[Box, list[Box]] = {}
stack = [(0, 0, 0)]
while stack:
b = stack.pop()
l = b[0]
idx = members[b]
if len(idx) <= s or l >= max_level:
children[b] = []
continue
m = 1 << (l + 1)
parts: dict[Box, list[int]] = {}
for i in idx:
key = (l + 1, min(int(z[i].real * m), m - 1), min(int(z[i].imag * m), m - 1))
parts.setdefault(key, []).append(i)
children[b] = sorted(parts)
for key, sub in parts.items():
members[key] = sub
stack.append(key)
return members, children
def colleagues(b: Box, children: dict) -> list[Box]:
"""Boxes of the tree at the level of b that are adjacent to b, b included."""
l, ix, iy = b
return [(l, ix + dx, iy + dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1) if (l, ix + dx, iy + dy) in children]
def build_lists(children: dict):
"""The U, W lists of every leaf, the V list of every box and the X lists."""
U: dict[Box, list[Box]] = {}
V: dict[Box, list[Box]] = {}
W: dict[Box, list[Box]] = {}
X: dict[Box, list[Box]] = {b: [] for b in children}
for b in children:
l, ix, iy = b
V[b] = []
if l >= 2:
for col in colleagues((l - 1, ix >> 1, iy >> 1), children):
for ch in children[col]:
if max(abs(ch[1] - ix), abs(ch[2] - iy)) > 1:
V[b].append(ch)
for b in children:
if children[b]:
continue
l, ix, iy = b
u = [b]
w = []
for k in range(l - 1, -1, -1):
anc = (k, ix >> (l - k), iy >> (l - k))
for col in colleagues(anc, children):
if not children[col] and adjacent(col, b):
u.append(col)
stack = [col for col in colleagues(b, children) if col != b]
while stack:
c = stack.pop()
if not children[c]:
u.append(c)
continue
for ch in children[c]:
if adjacent(ch, b):
stack.append(ch)
else:
w.append(ch)
U[b] = u
W[b] = w
for d in w:
X[d].append(b)
return U, V, W, X
def p2m(q, z, idx, center: complex, p: int) -> list[complex]:
"""a_0 = sum q_i and a_k = -sum q_i (z_i - c)^k / k."""
a = [0j] * (p + 1)
for i in idx:
d = z[i] - center
a[0] += q[i]
t = 1 + 0j
for k in range(1, p + 1):
t *= d
a[k] -= q[i] * t / k
return a
def m2m(a: Sequence[complex], z0: complex, C) -> list[complex]:
"""Shift a multipole expansion centered at z0 to the origin (exact)."""
p = len(a) - 1
pw = [1 + 0j] * (p + 1)
for k in range(1, p + 1):
pw[k] = pw[k - 1] * z0
b = [a[0]] + [0j] * p
for l in range(1, p + 1):
s = -a[0] * pw[l] / l
for k in range(1, l + 1):
s += a[k] * pw[l - k] * C[l - 1][k - 1]
b[l] = s
return b
def m2l(a: Sequence[complex], z0: complex, C) -> list[complex]:
"""Local expansion about the origin of a multipole expansion centered at z0."""
p = len(a) - 1
inv = 1 / z0
ip = [1 + 0j] * (p + 1)
for k in range(1, p + 1):
ip[k] = ip[k - 1] * inv
t = [((-1) ** k) * a[k] * ip[k] for k in range(p + 1)]
b = [0j] * (p + 1)
b[0] = a[0] * cmath.log(-z0) + sum(t[1:])
for l in range(1, p + 1):
s = -a[0] / l
for k in range(1, p + 1):
s += t[k] * C[l + k - 1][k - 1]
b[l] = s * ip[l]
return b
def p2l(q, z, idx, center: complex, p: int) -> list[complex]:
"""Local expansion about center of far charges: b_0 = sum q log(c - z_i), b_l = -sum q / (l (z_i - c)^l)."""
b = [0j] * (p + 1)
for i in idx:
d = z[i] - center
b[0] += q[i] * cmath.log(-d)
inv = 1 / d
t = 1 + 0j
for l in range(1, p + 1):
t *= inv
b[l] -= q[i] * t / l
return b
def l2l(b: Sequence[complex], z0: complex) -> list[complex]:
"""Shift a local expansion sum_k b_k (w - z0)^k to the origin by Horner's scheme (exact)."""
a = list(b)
p = len(a) - 1
for j in range(p):
for k in range(p - j - 1, p):
a[k] -= z0 * a[k + 1]
return a
def eval_multipole(a: Sequence[complex], center: complex, w: complex) -> tuple[complex, complex]:
"""Value and derivative of a_0 log(w - c) + sum_k a_k / (w - c)^k."""
d = w - center
inv = 1 / d
v = 0j
dv = 0j
for k in range(len(a) - 1, 0, -1):
v = (v + a[k]) * inv
dv = (dv + k * a[k]) * inv
return a[0] * cmath.log(d) + v, a[0] * inv - dv * inv
def eval_local(b: Sequence[complex], center: complex, w: complex) -> tuple[complex, complex]:
"""Value and derivative of sum_l b_l (w - c)^l."""
d = w - center
v = 0j
dv = 0j
for k in range(len(b) - 1, -1, -1):
dv = dv * d + v
v = v * d + b[k]
return v, dv
def _add(acc: list[complex], b: Sequence[complex]) -> None:
for k in range(len(acc)):
acc[k] += b[k]
def adaptive_fmm(q: Sequence[float], z: Sequence[complex], p: int = 12, s: int = 10, max_level: int = 30):
"""Potentials u_j and fields grad u_j (as complex numbers) of all charges.
Returns (u, field, stats); stats counts the ordered pairs of the near field
("p2p"), the translations of the V list ("m2l"), the W list evaluations
("m2p", box and target pairs) and the X list expansions ("p2l", box pairs).
"""
n = len(z)
u = [0.0] * n
field = [0j] * n
stats = {"p2p": 0, "m2l": 0, "m2p": 0, "p2l": 0}
if n == 0:
return u, field, stats
C = binomials(p)
members, children = build_tree(z, s, max_level) # @line L1
U, V, W, X = build_lists(children) # @line L2
order = sorted(children, key=lambda b: b[0])
mult: dict[Box, list[complex]] = {}
for b in reversed(order): # @line L3
c = box_center(b)
if not children[b]:
mult[b] = p2m(q, z, members[b], c, p)
else:
acc = [0j] * (p + 1)
for ch in children[b]:
_add(acc, m2m(mult[ch], box_center(ch) - c, C))
mult[b] = acc
local: dict[Box, list[complex]] = {}
for b in order:
c = box_center(b)
acc = [0j] * (p + 1)
for src in V[b]: # @line L4
_add(acc, m2l(mult[src], box_center(src) - c, C))
stats["m2l"] += 1
for src in X[b]:
_add(acc, p2l(q, z, members[src], c, p))
stats["p2l"] += 1
l, ix, iy = b
if l > 0:
parent = (l - 1, ix >> 1, iy >> 1)
_add(acc, l2l(local[parent], box_center(parent) - c)) # @line L5
local[b] = acc
for b in order:
if children[b]:
continue
c = box_center(b)
for j in members[b]: # @line L6
v, dv = eval_local(local[b], c, z[j])
for src in W[b]:
mv, mdv = eval_multipole(mult[src], box_center(src), z[j])
v += mv
dv += mdv
stats["m2p"] += 1
u[j] += v.real
field[j] += dv.conjugate()
for src in U[b]: # @line L7
for i in members[src]:
for j in members[b]:
if i != j:
d = z[j] - z[i]
u[j] += q[i] * math.log(abs(d))
field[j] += q[i] / d.conjugate()
stats["p2p"] += 1
return u, field, stats
def direct(q: Sequence[float], z: Sequence[complex]):
"""Direct summation over all ordered pairs: the reference."""
n = len(z)
u = [0.0] * n
field = [0j] * n
for j in range(n):
for i in range(n):
if i != j:
d = z[j] - z[i]
u[j] += q[i] * math.log(abs(d))
field[j] += q[i] / d.conjugate()
return u, field
test_adaptive_fast_multipole_method.py 173 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-fast-multipole-method/. The authors are listed in prov/B4084E.jsonl.
"""Tests for the adaptive fast multipole method: the tree, the four lists and the accuracy against direct summation."""
import math
import random
import unittest
from adaptive_fast_multipole_method import (
adaptive_fmm,
adjacent,
box_center,
build_lists,
build_tree,
direct,
eval_local,
eval_multipole,
p2l,
p2m,
)
def clustered(n, seed):
"""Three tight Gaussian clusters and a thin uniform background."""
rng = random.Random(seed)
centers = [complex(0.2, 0.3), complex(0.7, 0.75), complex(0.8, 0.2)]
z = []
while len(z) < n:
if rng.random() < 0.85:
c = centers[rng.randrange(3)]
w = c + complex(rng.gauss(0, 0.02), rng.gauss(0, 0.02))
else:
w = complex(rng.random(), rng.random())
if 0 <= w.real < 1 and 0 <= w.imag < 1:
z.append(w)
q = [rng.uniform(-1, 1) for _ in range(n)]
return q, z
def rel(a, b):
num = math.sqrt(sum(abs(x - y) ** 2 for x, y in zip(a, b)))
den = math.sqrt(sum(abs(y) ** 2 for y in b))
return num / den
def ancestors(b):
l, x, y = b
return [(k, x >> (l - k), y >> (l - k)) for k in range(l + 1)]
class TestTree(unittest.TestCase):
def setUp(self):
self.q, self.z = clustered(400, 3)
self.members, self.children = build_tree(self.z, 10)
self.leaves = [b for b in self.children if not self.children[b]]
def test_leaves_are_small_and_at_many_levels(self):
for b in self.leaves:
self.assertLessEqual(len(self.members[b]), 10)
self.assertGreater(len(self.members[b]), 0)
self.assertGreaterEqual(len({b[0] for b in self.leaves}), 4)
def test_leaves_partition_the_charges(self):
seen = sorted(i for b in self.leaves for i in self.members[b])
self.assertEqual(seen, list(range(400)))
for b in self.leaves:
l, ix, iy = b
h = 1.0 / (1 << l)
for i in self.members[b]:
self.assertTrue(ix * h <= self.z[i].real < (ix + 1) * h)
self.assertTrue(iy * h <= self.z[i].imag < (iy + 1) * h)
def test_each_leaf_pair_is_covered_once(self):
U, V, W, X = build_lists(self.children)
for t in self.leaves:
at = ancestors(t)
for c in self.leaves:
ac = set(ancestors(c))
routes = int(c in U[t])
routes += sum(1 for a in at for v in V[a] if v in ac)
routes += sum(1 for w in W[t] if w in ac)
routes += sum(1 for a in at for x in X[a] if x == c)
self.assertEqual(routes, 1, (t, c))
self.assertEqual(c in U[t], adjacent(c, t))
def test_lists_are_well_separated(self):
U, V, W, X = build_lists(self.children)
for b, vs in V.items():
for c in vs:
self.assertEqual(c[0], b[0])
self.assertGreaterEqual(abs(box_center(c) - box_center(b)), 2.0 / (1 << b[0]) - 1e-12)
for b, ws in W.items():
for d in ws:
self.assertGreater(d[0], b[0])
self.assertFalse(adjacent(d, b))
self.assertTrue(adjacent(ancestors(d)[-2], b))
self.assertIn(b, X[d])
class TestTranslations(unittest.TestCase):
def test_p2l_and_multipole_field(self):
rng = random.Random(1)
q = [rng.uniform(-1, 1) for _ in range(6)]
z = [complex(0.75 + 0.2 * rng.random(), 0.1 + 0.2 * rng.random()) for _ in range(6)]
idx = range(6)
center = complex(0.2, 0.2)
w = complex(0.25, 0.15)
exact_u = sum(qi * math.log(abs(w - zi)) for qi, zi in zip(q, z))
exact_f = sum(qi / (w - zi).conjugate() for qi, zi in zip(q, z))
v, dv = eval_local(p2l(q, z, idx, center, 25), center, w)
self.assertAlmostEqual(v.real, exact_u, places=10)
self.assertLess(abs(dv.conjugate() - exact_f), 1e-9)
src = complex(0.85, 0.2)
mv, mdv = eval_multipole(p2m(q, z, idx, src, 25), src, w)
self.assertAlmostEqual(mv.real, exact_u, places=10)
self.assertLess(abs(mdv.conjugate() - exact_f), 1e-9)
class TestAdaptiveFMM(unittest.TestCase):
def test_matches_direct_and_improves_with_p(self):
q, z = clustered(400, 3)
ud, fd = direct(q, z)
errs = []
for p in (3, 6, 12, 20):
u, f, st = adaptive_fmm(q, z, p=p, s=10)
errs.append((rel(u, ud), rel(f, fd)))
for k in range(3):
self.assertLess(errs[k + 1][0], errs[k][0] / 10)
self.assertLess(errs[k + 1][1], errs[k][1] / 10)
self.assertLess(errs[-1][0], 1e-10)
self.assertLess(errs[-1][1], 1e-8)
def test_near_field_is_small_for_clusters(self):
q, z = clustered(400, 3)
u, f, st = adaptive_fmm(q, z, p=4, s=10)
self.assertLess(st["p2p"], 400 * 399 // 8)
self.assertGreater(st["m2p"], 0)
self.assertGreater(st["p2l"], 0)
def test_uniform_points(self):
rng = random.Random(8)
z = [complex(rng.random(), rng.random()) for _ in range(300)]
q = [rng.uniform(-1, 1) for _ in range(300)]
ud, fd = direct(q, z)
u, f, st = adaptive_fmm(q, z, p=16, s=8)
self.assertLess(rel(u, ud), 1e-8)
self.assertLess(rel(f, fd), 1e-7)
def test_linear_in_the_charges(self):
q, z = clustered(120, 4)
rng = random.Random(9)
r = [rng.uniform(-1, 1) for _ in range(120)]
u1, f1, _ = adaptive_fmm(q, z, p=8, s=6)
u2, f2, _ = adaptive_fmm(r, z, p=8, s=6)
u3, f3, _ = adaptive_fmm([2 * a - b for a, b in zip(q, r)], z, p=8, s=6)
for a, b, c in zip(u1, u2, u3):
self.assertAlmostEqual(c, 2 * a - b, places=9)
def test_small_inputs(self):
self.assertEqual(adaptive_fmm([], [], p=4)[0], [])
u, f, _ = adaptive_fmm([2.0], [complex(0.3, 0.3)], p=4)
self.assertEqual(u, [0.0])
self.assertEqual(f, [0j])
q = [1.0, -1.0, 0.5]
z = [complex(0.1, 0.1), complex(0.9, 0.9), complex(0.5, 0.2)]
u, f, _ = adaptive_fmm(q, z, p=6, s=1)
ud, fd = direct(q, z)
for a, b in zip(u, ud):
self.assertAlmostEqual(a, b, places=4)
if __name__ == "__main__":
unittest.main()
History
Greengard and Rokhlin (1987) gave the fast multipole method on a uniform tree. Carrier, Greengard and Rokhlin (1988) made the tree adaptive and added the lists for boxes of different sizes, which kept the cost close to linear for strongly nonuniform charges. Nabors, Korsmeyer, Leighton and White (1994) proved an bound for any distribution for an adaptive multipole scheme in 3D. Ying, Biros and Zorin (2004) used the same lists, named , , and , in their kernel-independent adaptive FMM.
References
- J. Carrier, L. Greengard and V. Rokhlin, A fast adaptive multipole algorithm for particle simulations, SIAM Journal on Scientific and Statistical Computing 9, 1988, 669-686, the adaptive tree, the lists of boxes of different sizes and the numerical results for nonuniform distributions
- Rick Beatson and Leslie Greengard, A short course on fast multipole methods, in Wavelets, Multilevel Methods and Elliptic PDEs, Oxford University Press, 1997, Lemma 4.7 for the error of the multipole-to-local step; Section 4.2 for a simpler adaptive scheme that only prunes empty boxes
- Lexing Ying, George Biros and Denis Zorin, A kernel-independent adaptive fast multipole algorithm in two and three dimensions, Journal of Computational Physics 196(2), 2004, 591-626, the names U, V, W and X of the four lists of an adaptive tree
- Keith Nabors, F. T. Korsmeyer, F. T. Leighton and Jacob White, Preconditioned, adaptive, multipole-accelerated iterative methods for three-dimensional first-kind integral equations of potential theory, SIAM Journal on Scientific Computing 15(3), 1994, 713-735, the proof that an adaptive multipole algorithm costs O(N) for any distribution of the charges
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 B4084E Edit this page History Report an error Markdown