Algorithm Search⌘K

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
Properties
deterministic
Origin
Leslie Greengard, Vladimir Rokhlin, 1987

The fast multipole method (FMM) computes the potentials and forces of NN 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 pp terms in each expansion, the error falls geometrically in pp by the truncation bound, and for a fixed pp and a uniform distribution the cost is O(N)O(N) instead of the Θ(N2)\Theta(N^2) 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 NN real charges qiq_i at distinct points zi=xi+iyiz_i = x_i + \mathrm{i} y_i of the unit square, written as complex numbers, and a number of terms pp. The output is an approximation of each potential and field

uj=∑i≠jqilog⁡∣zj−zi∣,∇uj=∑i≠jqizj−zi∣zj−zi∣2,u_j = \sum_{i \ne j} q_i \log|z_j - z_i|, \qquad \nabla u_j = \sum_{i \ne j} q_i \frac{z_j - z_i}{|z_j - z_i|^2},

where the field is written as a complex number. The potential uu is the real part of the complex potential ϕ(z)=∑iqilog⁡(z−zi)\phi(z) = \sum_i q_i \log(z - z_i), and ∇u=ϕ′(z)‾\nabla u = \overline{\phi'(z)}. In 2D gravity with G=1G = 1, the potential of a mass mim_i is milog⁡∣z−zi∣m_i \log|z - z_i| and the acceleration is −∇u-\nabla u. The error is measured against direct summation and is bounded in terms of pp and A=∑i∣qi∣A = \sum_i |q_i|.

The algorithm

Level ll of the tree has 4l4^l boxes of side 2−l2^{-l}. The leaves are at level LL, chosen so that a leaf holds about ss 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.

  1. FMM(q, z, p, L)
  2. 1for each leaf B: a_B ← P2M of the charges of B about the center of B
  3. 2for l ← L - 1 down to 2: for each box B at level l: a_B ← Σ M2M(a_C) over the children C of B
  4. for l ← 2 to L do
  5. 3for each box B at level l: for each box T in the interaction list of B: b_T ← b_T + M2L(a_B)
  6. 4if l < L then for each box T at level l: for each child D of T: b_D ← b_D + L2L(b_T)
  7. for each leaf T and each charge j in T do
  8. 5u_j ← Re of the local expansion b_T at z_j; field_j ← conj of its derivative
  9. 6add the direct terms of all charges i ≠ j in T and in the near neighbours of T
  10. 7return u, field

The four translations are, with all centers moved so that the new center is 00 and the old center is z0z_0 (Lemmas 4.2 and 4.6 to 4.8 of Beatson and Greengard):

  • P2M, line L1: a0=∑qia_0 = \sum q_i and ak=−∑qi(zi−c)k/ka_k = -\sum q_i (z_i - c)^k / k for 1≤k≤p1 \le k \le p, so that ϕ(z)≈a0log⁡(z−c)+∑k=1pak/(z−c)k\phi(z) \approx a_0 \log(z - c) + \sum_{k=1}^{p} a_k / (z - c)^k.
  • M2M, line L2: b0=a0b_0 = a_0 and bl=−a0z0l/l+∑k=1lakz0l−k(l−1k−1)b_l = -a_0 z_0^l / l + \sum_{k=1}^{l} a_k z_0^{l-k} \binom{l-1}{k-1}.
  • M2L, line L3: b0=a0log⁡(−z0)+∑k=1p(−1)kakz0−kb_0 = a_0 \log(-z_0) + \sum_{k=1}^{p} (-1)^k a_k z_0^{-k} and bl=−a0/(lz0l)+z0−l∑k=1p(−1)kakz0−k(l+k−1k−1)b_l = -a_0 / (l z_0^l) + z_0^{-l} \sum_{k=1}^{p} (-1)^k a_k z_0^{-k} \binom{l+k-1}{k-1}; see multipole-to-local translation.
  • L2L, line L4: the Taylor shift of the polynomial ∑kbk(z−z0)k\sum_k b_k (z - z_0)^k, 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 ll 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 N=400N = 400 charges uniform in [−1,1][-1, 1] at points uniform in the unit square (seed 5), and L=3L = 3, so the 64 leaves hold 6.25 charges on average. Direct summation uses 400⋅399=159600400 \cdot 399 = 159600 ordered pairs. The FMM of the implementation uses 18302 ordered pairs in the near field and 1272 M2L translations, the same for every pp. Against direct summation:

pp relative error of uu (2-norm) largest error of uu relative error of the field (2-norm)
3 6.6×10−46.6 \times 10^{-4} 2.7×10−22.7 \times 10^{-2} 3.9×10−33.9 \times 10^{-3}
6 1.8×10−51.8 \times 10^{-5} 1.0×10−31.0 \times 10^{-3} 1.6×10−41.6 \times 10^{-4}
9 6.4×10−76.4 \times 10^{-7} 3.2×10−53.2 \times 10^{-5} 7.7×10−67.7 \times 10^{-6}
12 3.0×10−83.0 \times 10^{-8} 1.7×10−61.7 \times 10^{-6} 4.7×10−74.7 \times 10^{-7}
16 7.3×10−107.3 \times 10^{-10} 5.3×10−85.3 \times 10^{-8} 1.5×10−81.5 \times 10^{-8}
20 1.8×10−111.8 \times 10^{-11} 1.6×10−91.6 \times 10^{-9} 4.8×10−104.8 \times 10^{-10}

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 γ=22−1≈1.83\gamma = 2\sqrt{2} - 1 \approx 1.83 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 pp-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 2w2w apart, and their charges and targets lie within w/2w / \sqrt{2} of the centers. Lemma 4.7 of Beatson and Greengard then bounds the error of each M2L step by a constant times Ac(1/γ)p+1A_c (1/\gamma)^{p+1}, with γ=22−1\gamma = 2\sqrt{2} - 1 and AcA_c the total absolute charge of the source box. The errors add over the disjoint source boxes, so the total error is at most ∑i∣qi∣\sum_i |q_i| times the same factor, and it tends to 0 as p→∞p \to \infty (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 qiq_i sit at ziz_i in the unit square. The tree is uniform: level ll has the 4l4^l boxes of side wl=2−lw_l = 2^{-l}, and the leaves are at level L≥2L \ge 2. 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 bb at level l≥2l \ge 2 is the set of children of the near neighbours of the parent of bb that are not near neighbours of bb. For a box bb at level ll, bkb_k is its ancestor at level k≤lk \le l. The potential is u(z)=∑iqilog⁡∣z−zi∣u(z) = \sum_i q_i \log|z - z_i|, the real part of ϕ(z)=∑iqilog⁡(z−zi)\phi(z) = \sum_i q_i \log(z - z_i).

Lemma 1 (each pair is counted once). Let tt and cc be two leaves. If tt and cc are near neighbours, no level l∈{2,…,L}l \in \{2, \ldots, L\} has clc_l in the interaction list of tlt_l. Otherwise exactly one level l∈{2,…,L}l \in \{2, \ldots, L\} has clc_l in the interaction list of tlt_l.

Proof. If ckc_k and tkt_k are not near neighbours, then ck+1c_{k+1} and tk+1t_{k+1} are not near neighbours, because they lie inside ckc_k and tkt_k, and a shared point of the children would be a shared point of the parents. So the set of levels kk at which ckc_k and tkt_k are near neighbours is an initial segment {0,1,…,k∗}\{0, 1, \ldots, k^*\}. 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, clc_l is in the interaction list of tlt_l exactly when cl−1c_{l-1} and tl−1t_{l-1} are near neighbours and clc_l and tlt_l are not, that is, exactly when l=k∗+1l = k^* + 1. If tt and cc are near neighbours, k∗=Lk^* = L and no such l≤Ll \le L exists. Otherwise k∗∈{1,…,L−1}k^* \in \{1, \ldots, L - 1\} and l=k∗+1l = k^* + 1 is the only level. □\square

So, for a target in leaf tt, every charge is used exactly once: in the near field of line L6 if its leaf is a near neighbour of tt, and otherwise through the one box clc_l that line L3 converts into the local expansion of tlt_l.

Lemma 2 (the multipole shift is exact). Let a0,…,apa_0, \ldots, a_p be the multipole coefficients of a set of charges about z0z_0, that is a0=∑qia_0 = \sum q_i and ak=−∑qi(zi−z0)k/ka_k = -\sum q_i (z_i - z_0)^k / k. Then the coefficients b0,…,bpb_0, \ldots, b_p of line L2 (Lemma 4.6 of Beatson and Greengard) are the multipole coefficients of the same charges about 00.

Proof. Write ζi=zi−z0\zeta_i = z_i - z_0. The multipole coefficient of order l≥1l \ge 1 about 00 is −∑iqi(ζi+z0)l/l-\sum_i q_i (\zeta_i + z_0)^l / l. By the binomial theorem this is −∑iqi(z0l+∑k=1l(lk)ζikz0l−k)/l-\sum_i q_i \left( z_0^l + \sum_{k=1}^{l} \binom{l}{k} \zeta_i^k z_0^{l-k} \right) / l. The first term gives −a0z0l/l-a_0 z_0^l / l. For the second, (lk)/l=(l−1k−1)/k\binom{l}{k} / l = \binom{l-1}{k-1} / k, so it gives ∑k=1l(l−1k−1)z0l−k(−∑iqiζik/k)=∑k=1lakz0l−k(l−1k−1)\sum_{k=1}^{l} \binom{l-1}{k-1} z_0^{l-k} \left( -\sum_i q_i \zeta_i^k / k \right) = \sum_{k=1}^{l} a_k z_0^{l-k} \binom{l-1}{k-1}. The coefficient of order 0 is ∑qi=a0\sum q_i = a_0 for both centers. Only a0,…,ala_0, \ldots, a_l appear in blb_l, so the truncation at pp loses nothing. □\square

By Lemma 2 and induction from the leaves up, after line L2 each box holds the exact pp-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 ∑k=0pbk(w−z0)k\sum_{k=0}^{p} b_k (w - z_0)^k to the coefficients of the same polynomial in powers of ww.

Proof. Each pass of the outer loop is one step of synthetic division by w−z0w - z_0 in the variable w−z0w - z_0, so after pp 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 pp is its own Taylor polynomial of degree pp, so nothing is lost. □\square

Lemma 4 (one M2L step). Let a box cc at level ll be in the interaction list of tt, with side w=wlw = w_l. The charges of cc lie in the disk of radius R=w/2R = w / \sqrt{2} about its center, and the distance of the two centers is at least 2w=22 R2w = 2\sqrt{2}\, R. Let γ=22−1≈1.83\gamma = 2\sqrt{2} - 1 \approx 1.83. Then for each zz in the disk of radius RR about the center ztz_t of tt, which contains the closed square of tt and of all its descendants, the pp-term local expansion produced at line L3 from the pp-term multipole expansion of cc satisfies

∣ϕc(z)−∑l′=0pbl′(z−zt)l′∣≤Ac 4e(p+γ)(γ+1)+γ2γ(γ−1)(1γ)p+1,\left| \phi_c(z) - \sum_{l'=0}^{p} b_{l'} (z - z_t)^{l'} \right| \le A_c \, \frac{4e(p + \gamma)(\gamma + 1) + \gamma^2}{\gamma (\gamma - 1)} \left(\frac{1}{\gamma}\right)^{p+1},

where ϕc\phi_c is the complex potential of the charges of cc and Ac=∑i∈c∣qi∣A_c = \sum_{i \in c} |q_i|.

Proof. Two boxes of one level that are not near neighbours have centers at least two sides apart in one coordinate. Move ztz_t to the origin. For each γ′\gamma' with 1<γ′<γ1 < \gamma' < \gamma the distance of the centers is 2w>(γ′+1)R2w > (\gamma' + 1) R, so Lemma 4.7 of Beatson and Greengard (their cc is our γ′\gamma') gives the bound with γ′\gamma' in place of γ\gamma, as a strict inequality. The right side is continuous in γ′\gamma', so the bound with γ\gamma follows as γ′→γ\gamma' \to \gamma. The real part of the left side is the error of the potential uu, and it is at most the modulus. □\square

Theorem. Let uju_j be the output of line L7 for the charge jj in leaf tt. Then

∣uj−u(zj)∣≤(∑i∣qi∣)4e(p+γ)(γ+1)+γ2γ(γ−1)(1γ)p+1,|u_j - u(z_j)| \le \left( \sum_{i} |q_i| \right) \frac{4e(p + \gamma)(\gamma + 1) + \gamma^2}{\gamma (\gamma - 1)} \left(\frac{1}{\gamma}\right)^{p+1},

where u(zj)u(z_j) is the exact potential without the self term. The bound tends to 00 as p→∞p \to \infty, so the FMM converges to direct summation.

Proof. By Lemma 1 the far charges for tt are split into the disjoint boxes clc_l of the interaction lists of the ancestors tlt_l, 2≤l≤L2 \le l \le L, and the near charges are summed exactly at line L6, without i=ji = j. 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 zjz_j, which lies in the disk of radius wl/2w_l / \sqrt{2} about the center of each ancestor tlt_l. The errors add, and ∑cAc≤∑i∣qi∣\sum_c A_c \le \sum_i |q_i| because the boxes are disjoint. □\square

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 ss charges per leaf, so that there are about N/sN / s leaves.

  • Operation count (theorem for the uniform tree). Beatson and Greengard count about NpN p operations for P2M, 29(N/s)p229 (N/s) p^2 for the M2M, M2L and L2L translations, NpN p for L2P and 9Ns9 N s for the near field. With s=ps = p the total is about 40Np40 N p. Each translation costs O(p2)O(p^2) in 2D, and there are at most 2727 M2L translations per box and 44 M2M and 44 L2L translations per parent. The total is Θ(Np2/s+Ns+Np)\Theta(N p^2 / s + N s + N p), which is Θ(Np)\Theta(N p) for ss near pp, and O(N)O(N) for a fixed pp.
  • Measured. With s=8s = 8, p=10p = 10 and random charges (seed 7), the near field uses 44.5, 58.2 and 64.4 ordered pairs per charge for N=125N = 125, 500500 and 20002000. The count per charge tends to a constant near 9s9 s, as the operation count says; it is smaller for small NN, because more boxes are at the edge.
  • Accuracy and cost together. For an accuracy ε\varepsilon, the bound needs p=O(log⁡(1/ε))p = O(\log(1/\varepsilon)) terms, so with s≈ps \approx p the cost is O(Nlog⁡(1/ε))O(N \log(1/\varepsilon)).
  • Worst case. A uniform tree does not follow the charges. If all charges fall into a few leaves, the near field is Θ(N2)\Theta(N^2). The adaptive FMM fixes this for a tree of bounded depth, and Nabors, Korsmeyer, Leighton and White (1994) proved an O(N)O(N) bound for every distribution for their adaptive scheme.
  • Space. Θ(N)\Theta(N) for the charges and Θ(p)\Theta(p) coefficients per box, so Θ(N+Np/s)\Theta(N + N p / s).
  • Three dimensions. An expansion has (p+1)2(p + 1)^2 terms, an interior box has an interaction list of 189 boxes, and a direct M2L costs O(p4)O(p^4). This is why the faster 3D translations of the variants below matter.

Properties

  • Error control. The error is bounded in terms of pp 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 qq. 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 O(p3)O(p^3), 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 NN is large, for example N≥104N \ge 10^4 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 NN, 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 pp, the powers z0kz_0^k and aka_k overflow or underflow. Store the coefficients scaled by the box size, ak/wka_k / w^k and blwlb_l w^l.
  • The branch of the logarithm. The imaginary part of log⁡(−z0)\log(-z_0) 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 pp. 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 Θ(N2)\Theta(N^2). 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.

fast_multipole_method.pyI0RawGitHub
# 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

  1. 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
  2. Rick Beatson and Leslie Greengard, A short course on fast multipole methods, in Wavelets, Multilevel Methods and Elliptic PDEs, Oxford University Press, 1997, Section 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)
  3. 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
  4. 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.

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