Algorithmcore
Fast multipole method
Also called Greengard-Rokhlin fast multipole method.
Evaluates all pairwise interactions of N particles to a set accuracy in O(N) time, with multipole and local expansions on a tree and translations between them.
- Time
- Θ(N^2) worstΘ(N p^2 / s + N s) averageΘ(N p) best
- Space
- Θ(N + N p / s) extra
- Where
- N = the number of charges; p = the number of terms of each expansion; s = the mean number of charges in a leaf box
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Leslie Greengard, Vladimir Rokhlin, 1987
The fast multipole method (FMM) computes the potentials and forces of charges or masses on each other to a set accuracy. It puts the particles in a tree of boxes, a quadtree in 2D and an octree in 3D. Each box gets a multipole expansion of its own particles, built from the leaves up. Each box then gets a local (Taylor) expansion of the field of all particles that are not near it, built from the root down: a multipole-to-local translation brings in the boxes of its interaction list, and the parent passes down the rest. At the leaves, the local expansion gives the far field at each particle, and the near field is summed directly. With terms in each expansion, the error falls geometrically in by the truncation bound, and for a fixed and a uniform distribution the cost is instead of the of direct summation. This page gives the 2D method of Greengard and Rokhlin (1987) for the logarithmic kernel.
In plain words
The pull of a far group of particles is smooth, so a short list of numbers describes it well. The FMM uses two kinds of such lists. The first kind says how one box pulls on everything far from it. The second kind says how everything far away pulls on the points inside one box.
Put the particles in boxes, and cut each box into four smaller ones, a few times. Make the first list for each small box, then merge the lists of four boxes into the list of their parent. Then, for each box, turn the first lists of the boxes at a medium distance into a second list for this box, and add the second list of its parent. At the bottom, each particle reads the far pull from the second list of its box and adds the pull of its close neighbours one by one.
The problem
The input is real charges at distinct points of the unit square, written as complex numbers, and a number of terms . The output is an approximation of each potential and field
where the field is written as a complex number. The potential is the real part of the complex potential , and . In 2D gravity with , the potential of a mass is and the acceleration is . The error is measured against direct summation and is bounded in terms of and .
The algorithm
Level of the tree has boxes of side . The leaves are at level , chosen so that a leaf holds about charges. Two boxes of one level are near neighbours if they touch, even at a corner. The interaction list of a box is the set of children of the near neighbours of its parent that are not near neighbours of the box; it has at most 27 boxes.
FMM(q, z, p, L)- 1
for each leaf B: a_B ← P2M of the charges of B about the center of B - 2
for l ← L - 1 down to 2: for each box B at level l: a_B ← Σ M2M(a_C) over the children C of B for l ← 2 to L do- 3
for each box B at level l: for each box T in the interaction list of B: b_T ← b_T + M2L(a_B) - 4
if l < L then for each box T at level l: for each child D of T: b_D ← b_D + L2L(b_T) for each leaf T and each charge j in T do- 5
u_j ← Re of the local expansion b_T at z_j; field_j ← conj of its derivative - 6
add the direct terms of all charges i ≠ j in T and in the near neighbours of T - 7
return u, field
The four translations are, with all centers moved so that the new center is and the old center is (Lemmas 4.2 and 4.6 to 4.8 of Beatson and Greengard):
- P2M, line L1: and for , so that .
- M2M, line L2: and .
- M2L, line L3: and ; see multipole-to-local translation.
- L2L, line L4: the Taylor shift of the polynomial , done in place by Horner's scheme.
Lines L1 and L2 are the upward pass, and lines L3 and L4 the downward pass. The order matters only in one place: the local expansion of a box at level must hold all its M2L terms before line L4 passes it to the children. Levels 0 and 1 have empty interaction lists, because all their boxes touch.
Example
Take charges uniform in at points uniform in the unit square (seed 5), and , so the 64 leaves hold 6.25 charges on average. Direct summation uses ordered pairs. The FMM of the implementation uses 18302 ordered pairs in the near field and 1272 M2L translations, the same for every . 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. Each extra term gains a factor of about 2.5 in the potential. The worst-case bound of the proof falls by a factor per term, so it is pessimistic for random charges. The field loses about one digit against the potential, because a derivative of the expansion has larger coefficients.
The 1272 translations follow from the interaction lists: each of the 16 boxes at level 2 and each of the 64 boxes at level 3 sends its expansion to every box of its list, and boxes at the edge of the square have shorter lists than the 27 of an interior box.
Correctness
The proof is in the proof file. The near-neighbour relation of two leaves holds at an initial range of levels, so each far charge is used exactly once, through the one ancestor pair at which the relation first fails (Lemma 1). The M2M and L2L steps are exact for -term expansions (Lemmas 2 and 3), so the only errors come from the truncations in M2L. Two boxes of the interaction list have centers at least apart, and their charges and targets lie within of the centers. Lemma 4.7 of Beatson and Greengard then bounds the error of each M2L step by a constant times , with and the total absolute charge of the source box. The errors add over the disjoint source boxes, so the total error is at most times the same factor, and it tends to 0 as (Theorem).
Proof: The FMM counts each pair once, its translations are exact or bounded, and its error is controlled by pfull
We use exact complex arithmetic. The charges sit at in the unit square. The tree is uniform: level has the boxes of side , and the leaves are at level . Two boxes of one level are near neighbours if their closed squares share at least one point; a box is its own near neighbour. The interaction list of a box at level is the set of children of the near neighbours of the parent of that are not near neighbours of . For a box at level , is its ancestor at level . The potential is , the real part of .
Lemma 1 (each pair is counted once). Let and be two leaves. If and are near neighbours, no level has in the interaction list of . Otherwise exactly one level has in the interaction list of .
Proof. If and are not near neighbours, then and are not near neighbours, because they lie inside and , and a shared point of the children would be a shared point of the parents. So the set of levels at which and are near neighbours is an initial segment . It contains 0 and 1, because the root is one box and the four boxes of level 1 share the center point. By the definition, is in the interaction list of exactly when and are near neighbours and and are not, that is, exactly when . If and are near neighbours, and no such exists. Otherwise and is the only level.
So, for a target in leaf , every charge is used exactly once: in the near field of line L6 if its leaf is a near neighbour of , and otherwise through the one box that line L3 converts into the local expansion of .
Lemma 2 (the multipole shift is exact). Let be the multipole coefficients of a set of charges about , that is and . Then the coefficients of line L2 (Lemma 4.6 of Beatson and Greengard) are the multipole coefficients of the same charges about .
Proof. Write . The multipole coefficient of order about is . By the binomial theorem this is . The first term gives . For the second, , so it gives . The coefficient of order 0 is for both centers. Only appear in , so the truncation at loses nothing.
By Lemma 2 and induction from the leaves up, after line L2 each box holds the exact -term multipole coefficients of the charges inside it.
Lemma 3 (the local shift is exact). The Horner loop of line L4 (Lemma 4.8) maps the coefficients of a polynomial to the coefficients of the same polynomial in powers of .
Proof. Each pass of the outer loop is one step of synthetic division by in the variable , so after passes the coefficients are those of the Taylor expansion of the same polynomial about the new center (the triangle of the passes is the scheme of Horner for a shift of origin). A polynomial of degree is its own Taylor polynomial of degree , so nothing is lost.
Lemma 4 (one M2L step). Let a box at level be in the interaction list of , with side . The charges of lie in the disk of radius about its center, and the distance of the two centers is at least . Let . Then for each in the disk of radius about the center of , which contains the closed square of and of all its descendants, the -term local expansion produced at line L3 from the -term multipole expansion of satisfies
where is the complex potential of the charges of and .
Proof. Two boxes of one level that are not near neighbours have centers at least two sides apart in one coordinate. Move to the origin. For each with the distance of the centers is , so Lemma 4.7 of Beatson and Greengard (their is our ) gives the bound with in place of , as a strict inequality. The right side is continuous in , so the bound with follows as . The real part of the left side is the error of the potential , and it is at most the modulus.
Theorem. Let be the output of line L7 for the charge in leaf . Then
where is the exact potential without the self term. The bound tends to as , so the FMM converges to direct summation.
Proof. By Lemma 1 the far charges for are split into the disjoint boxes of the interaction lists of the ancestors , , and the near charges are summed exactly at line L6, without . By Lemma 2 each box holds its exact multipole coefficients. Line L3 makes a local expansion for each pair, with the error of Lemma 4. Line L4 moves these expansions down without error by Lemma 3, and line L5 evaluates the sum at , which lies in the disk of radius about the center of each ancestor . The errors add, and because the boxes are disjoint.
The same argument with the derivatives gives the convergence of the field. The bound is a worst case; the measured error falls faster, by about a factor of 2.5 for each extra term in the example on the page. The cost bound of the page is a separate statement and needs a bounded number of charges per leaf.
Complexity
The model is the real RAM. Each step is counted in complex operations, for a uniform distribution with charges per leaf, so that there are about leaves.
- Operation count (theorem for the uniform tree). Beatson and Greengard count about operations for P2M, for the M2M, M2L and L2L translations, for L2P and for the near field. With the total is about . Each translation costs in 2D, and there are at most M2L translations per box and M2M and L2L translations per parent. The total is , which is for near , and for a fixed .
- Measured. With , and random charges (seed 7), the near field uses 44.5, 58.2 and 64.4 ordered pairs per charge for , and . The count per charge tends to a constant near , as the operation count says; it is smaller for small , because more boxes are at the edge.
- Accuracy and cost together. For an accuracy , the bound needs terms, so with the cost is .
- Worst case. A uniform tree does not follow the charges. If all charges fall into a few leaves, the near field is . The adaptive FMM fixes this for a tree of bounded depth, and Nabors, Korsmeyer, Leighton and White (1994) proved an bound for every distribution for their adaptive scheme.
- Space. for the charges and coefficients per box, so .
- Three dimensions. An expansion has terms, an interior box has an interaction list of 189 boxes, and a direct M2L costs . This is why the faster 3D translations of the variants below matter.
Properties
- Error control. The error is bounded in terms of by a theorem, not set by a rule of thumb as the opening angle of the Barnes-Hut algorithm is. The bound is a worst case and is usually far above the measured error.
- Linear in the charges. The output is a linear function of . This is what lets the FMM act as a fast matrix-vector product inside an iterative solver such as GMRES for boundary element equations.
- Exact translations. M2M and L2L lose nothing; all the truncation error is in P2M, M2L and L2P.
- Not symmetric. Like a tree code, the FMM does not apply equal and opposite forces to each pair, so momentum is conserved only up to the error.
- Deterministic. The result does not depend on the order of the charges, up to rounding.
Variants and improvements
- Adaptive trees. The adaptive FMM of Carrier, Greengard and Rokhlin (1988) refines only where there are many charges and adds two more lists for boxes of different sizes.
- Faster 3D translations. Rotation-based translations cost , and the plane-wave (exponential) expansions of Greengard and Rokhlin (1997) cut the M2L work further. FFT-based M2L uses the Toeplitz structure of the operator.
- Kernel independent and black box versions. The kernel-independent FMM replaces the expansions with equivalent densities on circles or surfaces, and the black-box FMM uses Chebyshev interpolation; both need only kernel evaluations.
- Other kernels. The same tree with Hermite expansions gives the fast Gauss transform, and expansions in Bessel functions give FMMs for the Helmholtz and Yukawa kernels.
- Mesh hybrids. For periodic gravity, P3M and TreePM combine a mesh for the long range with direct sums or a tree for the short range.
When to use it
Use the FMM when you need many potentials or forces with a guaranteed accuracy and is large, for example in 2D: in vortex methods, electrostatics, boundary integral equations solved by iteration, and charged particle simulations. For low accuracy (one percent) the Barnes-Hut algorithm is simpler and often as fast. For periodic systems, a mesh method such as particle-mesh Ewald is usually easier. For small , use direct summation.
Pitfalls
- Using M2L for near boxes. The M2L series converges only when the boxes are well separated. Converting a near neighbour gives wrong results without a warning. Build the interaction list exactly by the definition.
- The order of the downward pass. A box must receive all its M2L terms before L2L passes its expansion to its children.
- Scaling. For large , the powers and overflow or underflow. Store the coefficients scaled by the box size, and .
- The branch of the logarithm. The imaginary part of in M2L depends on the branch. The potential uses only the real part, which is safe, but code that uses the imaginary part (the stream function) must keep the branch cuts consistent.
- Measuring the error of one example only. The error depends on the distribution, on the signs of the charges and on . Check against direct summation on a sample of targets for the real problem.
- Unbalanced trees. With a uniform tree, a clustered distribution puts many charges in a few leaves, and the near field becomes . Use the adaptive version.
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-multipole-method/. The authors are listed in prov/2RM7MC.jsonl.
"""Fast multipole method of Greengard and Rokhlin for the 2D logarithmic kernel.
Charges q[i] sit at points z[i] (complex numbers) in 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|,
the real part of the complex potential phi(z) = sum_i q_i log(z - z_i).
The field grad u is returned as the complex number conj(phi'(z)).
The tree is uniform: level l has 4^l boxes of side 2^-l, and the leaves are
at level L. Each box keeps p + 1 coefficients. The translation formulas are
those of Beatson and Greengard, "A short course on fast multipole methods",
Lemma 4.2 (P2M), Lemma 4.6 (M2M), Lemma 4.7 (M2L) and Lemma 4.8 (L2L).
"""
import cmath
import math
from math import comb
from typing import Optional, Sequence
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 p2m(q: Sequence[float], z: Sequence[complex], center: complex, p: int) -> list[complex]:
"""Multipole coefficients about center: a_0 = sum q_i, a_k = -sum q_i (z_i - c)^k / k."""
a = [0j] * (p + 1)
for qi, zi in zip(q, z):
d = zi - center
a[0] += qi
t = 1 + 0j
for k in range(1, p + 1):
t *= d
a[k] -= qi * t / k
return a
def eval_multipole(a: Sequence[complex], center: complex, w: complex) -> complex:
"""phi(w) = a_0 log(w - c) + sum_k a_k / (w - c)^k."""
d = w - center
s = 0j
for k in range(len(a) - 1, 0, -1):
s = (s + a[k]) / d
return a[0] * cmath.log(d) + s
def m2m(a: Sequence[complex], z0: complex, C: list[list[int]]) -> list[complex]:
"""Shift a multipole expansion centered at z0 to the origin (Lemma 4.6).
b_0 = a_0 and b_l = -a_0 z0^l / l + sum_{k=1}^{l} a_k z0^(l-k) C(l-1, k-1).
The p + 1 new coefficients use only a_0, ..., a_p, so the shift is exact.
"""
p = len(a) - 1
pw = [1 + 0j] * (p + 1)
for k in range(1, p + 1):
pw[k] = pw[k - 1] * z0
b = [0j] * (p + 1)
b[0] = a[0]
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[list[int]]) -> list[complex]:
"""Convert a multipole expansion centered at z0 into a local expansion about the origin (Lemma 4.7).
b_0 = a_0 log(-z0) + sum_k (-1)^k a_k / z0^k and, for l >= 1,
b_l = -a_0 / (l z0^l) + z0^(-l) sum_k (-1)^k a_k z0^(-k) C(l+k-1, k-1).
"""
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 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 (Lemma 4.8). 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_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 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 _add(acc: list[complex], b: Sequence[complex]) -> None:
for k in range(len(acc)):
acc[k] += b[k]
def fmm(q: Sequence[float], z: Sequence[complex], p: int = 12, levels: Optional[int] = None, s: int = 8):
"""Potentials u_j and fields grad u_j (as complex numbers) of all charges.
levels is the leaf level L (at least 2); by default L is chosen so that a
leaf holds at most about s charges on average. Returns (u, field, stats),
where stats counts the ordered pairs of the near field ("p2p") and the
multipole-to-local translations ("m2l").
"""
n = len(z)
if levels is None:
levels = max(2, math.ceil(math.log(n / s, 4))) if n > s else 2
L = levels
C = binomials(p)
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[i] for i in idx], [z[i] for i in idx], box_center(*key, L), p)
for l in range(L - 1, 1, -1): # @line L2
for (cx, cy), a in mult[l + 1].items():
key = (cx // 2, cy // 2)
z0 = box_center(cx, cy, l + 1) - box_center(*key, l)
_add(mult[l].setdefault(key, [0j] * (p + 1)), m2m(a, z0, C))
local: list[dict] = [dict() for _ in range(L + 1)]
n_m2l = 0
for l in range(2, L + 1):
for key, a in mult[l].items(): # @line L3
for tgt in interaction_list(*key, l):
if l == L and tgt not in leaf:
continue
z0 = box_center(*key, l) - box_center(*tgt, l)
_add(local[l].setdefault(tgt, [0j] * (p + 1)), m2l(a, z0, C))
n_m2l += 1
if l < L:
for (px, py), b in local[l].items(): # @line L4
for cx in (2 * px, 2 * px + 1):
for cy in (2 * py, 2 * py + 1):
z0 = box_center(px, py, l) - box_center(cx, cy, l + 1)
_add(local[l + 1].setdefault((cx, cy), [0j] * (p + 1)), l2l(b, z0))
u = [0.0] * n
field = [0j] * n
n_p2p = 0
for key, idx in leaf.items():
b = local[L].get(key)
c = box_center(*key, L)
if b is not None:
for j in idx: # @line L5
v, dv = eval_local(b, c, z[j])
u[j] += v.real
field[j] += dv.conjugate()
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:
d = z[j] - z[i]
u[j] += q[i] * math.log(abs(d))
field[j] += q[i] / d.conjugate()
n_p2p += 1
return u, field, {"p2p": n_p2p, "m2l": n_m2l} # @line L7
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_fast_multipole_method.py 137 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-multipole-method/. The authors are listed in prov/2RM7MC.jsonl.
import cmath
import math
import random
from fast_multipole_method import (
binomials,
direct,
eval_local,
eval_multipole,
fmm,
interaction_list,
l2l,
m2l,
m2m,
p2m,
)
def charges(n, seed):
rng = random.Random(seed)
z = [complex(rng.random(), rng.random()) for _ in range(n)]
q = [rng.uniform(-1.0, 1.0) for _ in range(n)]
return q, z
def rel_err(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 test_p2m_error_bound_lemma_4_2():
rng = random.Random(1)
r = 0.5
q = [rng.uniform(-1, 1) for _ in range(20)]
z = [cmath.rect(r * rng.random(), rng.uniform(0, 2 * math.pi)) for _ in q]
A = sum(abs(x) for x in q)
for p in (2, 5, 10, 20):
a = p2m(q, z, 0j, p)
for w in (1.0 + 0j, 1.3j, -0.8 - 0.9j):
exact = sum(qi * math.log(abs(w - zi)) for qi, zi in zip(q, z))
c = abs(w) / r
err = abs(eval_multipole(a, 0j, w).real - exact)
bound = A / (p + 1) / (c - 1) * (1 / c) ** p
assert err <= bound * (1 + 1e-9) + 1e-13
def test_m2m_is_exact():
q, z = charges(15, 2)
C = binomials(10)
old, new = complex(0.3, 0.4), complex(0.5, 0.5)
b = m2m(p2m(q, z, old, 10), old - new, C)
ref = p2m(q, z, new, 10)
assert max(abs(x - y) for x, y in zip(b, ref)) < 1e-12
def test_l2l_is_exact():
rng = random.Random(3)
b = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(9)]
old, new = complex(0.2, -0.1), complex(-0.3, 0.25)
c = l2l(b, old - new)
for w in (0j, complex(0.1, 0.2), complex(-0.4, 0.3)):
v1, d1 = eval_local(b, old, w)
v2, d2 = eval_local(c, new, w)
assert abs(v1 - v2) < 1e-12 and abs(d1 - d2) < 1e-11
def test_m2l_against_direct_and_lemma_4_7():
rng = random.Random(4)
src = complex(3.0, 1.0)
R = math.sqrt(0.5)
c = abs(src) / R - 1
q = [rng.uniform(-1, 1) for _ in range(12)]
z = [src + complex(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in q]
A = sum(abs(x) for x in q)
errs = []
for p in (4, 8, 16):
b = m2l(p2m(q, z, src, p), src, binomials(p))
e = 0.0
for w in (0j, complex(0.4, -0.3), complex(-0.5, 0.5)):
ref = sum(qi * math.log(abs(w - zi)) for qi, zi in zip(q, z))
e = max(e, abs(eval_local(b, 0j, w)[0].real - ref))
bound = A * (4 * math.e * (p + c) * (c + 1) + c * c) / (c * (c - 1)) * (1 / c) ** (p + 1)
assert e < bound
errs.append(e)
assert errs[0] > errs[1] > errs[2]
assert errs[2] < 1e-8
def test_interaction_list():
assert len(interaction_list(5, 5, 4)) == 27
assert len(interaction_list(0, 0, 2)) == 12
for ix, iy in ((0, 0), (3, 2), (7, 7)):
for nx, ny in interaction_list(ix, iy, 3):
assert max(abs(nx - ix), abs(ny - iy)) >= 2
assert max(abs(nx // 2 - ix // 2), abs(ny // 2 - iy // 2)) <= 1
def test_fmm_matches_direct_and_improves_with_p():
q, z = charges(400, 5)
u0, f0 = direct(q, z)
eu, ef = [], []
for p in (3, 6, 12, 20):
u, f, _ = fmm(q, z, p=p, levels=3)
eu.append(rel_err(u, u0))
ef.append(rel_err(f, f0))
assert all(eu[k] > eu[k + 1] for k in range(3))
assert all(ef[k] > ef[k + 1] for k in range(3))
assert eu[-1] < 1e-8 and ef[-1] < 1e-7
def test_near_field_pairs():
q, z = charges(300, 6)
u, f, st = fmm(q, z, p=16, levels=3)
box = [(min(int(w.real * 8), 7), min(int(w.imag * 8), 7)) for w in z]
near = sum(
1
for j in range(len(z))
for i in range(len(z))
if i != j and max(abs(box[i][0] - box[j][0]), abs(box[i][1] - box[j][1])) <= 1
)
assert st["p2p"] == near
assert st["p2p"] < len(z) * (len(z) - 1)
u0, _ = direct(q, z)
assert rel_err(u, u0) < 1e-8
def test_small_inputs():
u, f, st = fmm([2.0], [complex(0.3, 0.3)], p=5)
assert u == [0.0] and f == [0j]
q, z = [1.0, -1.0], [complex(0.1, 0.1), complex(0.9, 0.9)]
u, f, _ = fmm(q, z, p=20)
u0, f0 = direct(q, z)
assert max(abs(a - b) for a, b in zip(u, u0)) < 1e-10
assert max(abs(a - b) for a, b in zip(f, f0)) < 1e-10
History
Rokhlin (1985) used multipole ideas for the integral equations of potential theory. Greengard and Rokhlin (1987) published the fast multipole method for particle simulations in 2D, with the complex form of the logarithmic potential, the translations and the error bounds. Greengard's thesis, published by MIT Press in 1988, extended the method to 3D with spherical harmonics. Carrier, Greengard and Rokhlin (1988) gave the adaptive version, and Greengard and Rokhlin (1997) a faster 3D version with plane-wave expansions. Later work gave kernel independent forms (Ying, Biros and Zorin 2004) and black box forms (Fong and Darve 2009).
References
- Leslie Greengard and Vladimir Rokhlin, A fast algorithm for particle simulations, Journal of Computational Physics 73(2), 1987, 325-348, the 2D algorithm with the logarithmic kernel, the translation lemmas, the error bound and the operation count
- 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 (Lemmas 4.2 and 4.6 to 4.8, the interaction list and the operation count of the FMM) and Section 5 (three dimensions)
- Leslie Greengard, The Rapid Evaluation of Potential Fields in Particle Systems, MIT Press, 1988, the 3D algorithm with spherical harmonic expansions and its error bounds
- 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
Where this leads
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 2RM7MC Edit this page History Report an error Markdown