Algorithm Search⌘K

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
Properties
deterministic
Origin
J. Carrier, Leslie Greengard, Vladimir Rokhlin, 1988

The adaptive fast multipole method computes the potentials and fields of NN 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 ss 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 VV list does the usual multipole-to-local translations between boxes of one size. The WW and XX lists connect a leaf with smaller boxes near it, and the UU 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 NN real charges qiq_i at distinct points ziz_i of the unit square, written as complex numbers, a number of terms pp and a leaf size ss. 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},

with the field written as a complex number, ϕ′(zj)‾\overline{\phi'(z_j)} for ϕ(z)=∑iqilog⁡(z−zi)\phi(z) = \sum_i q_i \log(z - z_i). 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 bb:

  • U(b)U(b) is the set of leaves adjacent to bb, with bb itself.
  • V(b)V(b), defined for every box at level 2 or deeper, is the set of children of the colleagues of the parent of bb that are not adjacent to bb. It is the interaction list of the uniform FMM, at most 27 boxes.
  • W(b)W(b) is the set of boxes that descend from a colleague of bb, are not adjacent to bb, but have a parent that is adjacent to bb. They are smaller than bb.
  • X(d)X(d) is the set of leaves bb with d∈W(b)d \in W(b). It is the inverse of WW.
  1. ADAPTIVE-FMM(q, z, p, s)
  2. 1build the tree: split each box with more than s charges, and drop empty boxes
  3. 2build U(b) and W(b) for each leaf b, V(b) for each box b, and X as the inverse of W
  4. 3for 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
  5. for each box B from the root down do
  6. 4b_B ← Σ M2L(a_C) over C in V(B) + Σ P2L(charges of C) over C in X(B)
  7. 5b_B ← b_B + L2L(b_P), where P is the parent of B
  8. for each leaf T and each charge j in T do
  9. 6u_j, field_j ← local expansion b_T at z_j + Σ multipole expansion a_C at z_j over C in W(T)
  10. 7add 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 WW list): evaluate the multipole expansion a0log⁡(z−c)+∑kak(z−c)−ka_0 \log(z - c) + \sum_k a_k (z - c)^{-k} of a small box at each target of the leaf, and its derivative a0/(z−c)−∑kkak(z−c)−k−1a_0 / (z - c) - \sum_k k a_k (z - c)^{-k-1}.
  • P2L, line L4 (the XX list): add the charges of a large leaf directly into the local expansion about the center cc of a small box, with b0+=qlog⁡(c−zi)b_0 \mathrel{+}= q \log(c - z_i) and bl+=−q/(l(zi−c)l)b_l \mathrel{+}= -q / (l (z_i - c)^l).

The leaf bb can find its lists without a search over all boxes. The coarser leaves of U(b)U(b) are leaf colleagues of the ancestors of bb. The finer leaves of U(b)U(b) and all of W(b)W(b) come from one descent from the colleagues of bb: a child that touches bb is followed further, and a child that does not touch bb goes into W(b)W(b).

Example

Take N=400N = 400 charges uniform in [−1,1][-1, 1]: 85 percent of the points are in three Gaussian clusters of standard deviation 0.020.02 about (0.2,0.3)(0.2, 0.3), (0.7,0.75)(0.7, 0.75) and (0.8,0.2)(0.8, 0.2), and the rest are uniform in the unit square (the generator of the test file, seed 3). With s=10s = 10 the tree has 144 boxes and 104 leaves at the levels 2 to 7. The lists have 750 (UU), 850 (VV), 310 (WW) and 310 (XX) entries in total, and no VV list has more than 15 boxes. The near field uses 14266 ordered pairs, against 400⋅399=159600400 \cdot 399 = 159600 for direct summation. Against direct summation:

pp relative error of uu (2-norm) largest error of uu relative error of the field (2-norm)
3 4.1×10−44.1 \times 10^{-4} 3.6×10−23.6 \times 10^{-2} 3.7×10−33.7 \times 10^{-3}
6 7.5×10−67.5 \times 10^{-6} 8.9×10−48.9 \times 10^{-4} 1.5×10−41.5 \times 10^{-4}
9 2.7×10−72.7 \times 10^{-7} 3.5×10−53.5 \times 10^{-5} 5.5×10−65.5 \times 10^{-6}
12 1.1×10−81.1 \times 10^{-8} 1.2×10−61.2 \times 10^{-6} 3.1×10−73.1 \times 10^{-7}
16 2.7×10−102.7 \times 10^{-10} 3.6×10−83.6 \times 10^{-8} 6.5×10−96.5 \times 10^{-9}
20 5.8×10−125.8 \times 10^{-12} 8.8×10−108.8 \times 10^{-10} 2.9×10−102.9 \times 10^{-10}

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 (UU), one M2L at a common level (VV), one multipole evaluation of a smaller box (WW), or one direct local expansion into a smaller box (XX) (Lemma 3). The VV boxes are separated as in the uniform method, so Lemma 4.7 of Beatson and Greengard bounds their error with the ratio 1/(22−1)≈0.551 / (2\sqrt{2} - 1) \approx 0.55. A box of W(b)W(b) is at least 1.51.5 of its own sides from every point of bb, so the truncation bound applies with the ratio 2/3≈0.47\sqrt{2} / 3 \approx 0.47, and the same holds for XX (Lemma 4). The translations M2M and L2L are exact, so the total error is at most ∑i∣qi∣\sum_i |q_i| times a factor that tends to 0 as pp 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 wl=2−lw_l = 2^{-l} at level ll is split when it holds more than ss 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 bb at level ll and k≤lk \le l, bkb_k is the ancestor of bb at level kk, with bl=bb_l = b. The lists are as in line L2:

  • U(b)U(b), for a leaf bb: the leaves adjacent to bb.
  • V(b)V(b), for a box bb at level l≥2l \ge 2: the children of the colleagues of bl−1b_{l-1} that are not adjacent to bb.
  • W(b)W(b), for a leaf bb: the boxes dd that are descendants of a colleague of bb, are not adjacent to bb, and whose parent is adjacent to bb.
  • X(d)X(d): the leaves bb with d∈W(b)d \in W(b).

Lemma 1 (adjacency is inherited upward). If boxes aa and cc are adjacent, so are their parents, and so are aa and the parent of cc. Hence, along the ancestors of two leaves, the levels kk at which tkt_k and ckc_k are adjacent form an initial segment {0,…,k∗}\{0, \ldots, k^*\}, and along the ancestors of cc, the boxes adjacent to a fixed box tt form an initial segment too.

Proof. A box is contained in its parent, so a shared point of aa and cc is a shared point of the larger boxes. Level 0 is the root, which is adjacent to itself. □\square

Lemma 2 (the lists computed by the code are the lists defined above). For a leaf bb, the code puts into U(b)U(b) the box bb, the leaf colleagues of the proper ancestors of bb that are adjacent to bb, and the leaves reached by a descent from the colleagues of bb through adjacent boxes; it puts into W(b)W(b) the children met in this descent that are not adjacent to bb.

Proof. Let a≠ba \ne b be a leaf adjacent to bb at level kk. If k<lk < l, the ancestor bkb_k contains bb, so aa is adjacent to bkb_k and is a colleague of it. If k≥lk \ge l, the ancestor ala_l is adjacent to bb by Lemma 1 and is a colleague of bb, and al≠ba_l \ne b: if k=lk = l then al=a≠ba_l = a \ne b, and if k>lk > l then ala_l has children while the leaf bb has none. All the boxes between ala_l and aa are adjacent to bb by Lemma 1, so the descent, which follows every adjacent child, reaches aa. Conversely, each box the code adds to U(b)U(b) is a leaf adjacent to bb, and each leaf is added once, at its own level. For W(b)W(b): the descent visits exactly the descendants of colleagues of bb whose ancestors down to the colleague are all adjacent to bb, 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 bb and have an adjacent parent. □\square

Lemma 3 (each pair of leaves is covered exactly once). Let tt and cc be leaves at levels ltl_t and lcl_c. Then exactly one of the following holds:

  1. c∈U(t)c \in U(t);
  2. ck∈V(tk)c_k \in V(t_k) for some kk (and then kk is unique);
  3. ck∈W(t)c_k \in W(t) for some kk (unique);
  4. c∈X(tk)c \in X(t_k) for some kk (unique).

Proof. Let m=min⁡(lt,lc)m = \min(l_t, l_c), and let {0,…,k∗}\{0, \ldots, k^*\} be the levels at which tkt_k and ckc_k are adjacent (Lemma 1), with k∗≤mk^* \le m.

Case A: k∗<mk^* < m. At k=k∗+1≤mk = k^* + 1 \le m, the boxes tkt_k and ckc_k exist, are not adjacent, and have adjacent parents, which are colleagues. So ck∈V(tk)c_k \in V(t_k). A VV relation between an ancestor of tt and an ancestor of cc needs the same level, non-adjacency at that level and adjacency one level up, so k=k∗+1k = k^* + 1 is the only one. Route 1 fails, because tt and cc are inside the non-adjacent boxes tkt_k and ckc_k. Route 3 would need an ancestor cjc_j with j>ltj > l_t whose parent is adjacent to tt; then cltc_{l_t}, which contains that parent, would be adjacent to t=tltt = t_{l_t}, but lt≥k>k∗l_t \ge k > k^*. Route 4 fails in the same way with the roles exchanged.

Case B: k∗=mk^* = m and lt=lcl_t = l_c. Then tt and cc are adjacent leaves, so route 1 holds. Route 2 needs non-adjacency at a level at most mm. 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: k∗=m=lt<lck^* = m = l_t < l_c. The box cltc_{l_t} is adjacent to tt, and it is not tt, since tt is a leaf and cltc_{l_t} has the descendant cc; so it is a colleague of tt. Route 2 fails, since k∗=mk^* = m. Route 4 fails, since X(tk)∋cX(t_k) \ni c needs tk∈W(c)t_k \in W(c), a box finer than cc, but lt<lcl_t < l_c. If cc is adjacent to tt, route 1 holds and route 3 fails, since all ancestors of cc contain cc and are adjacent to tt. If not, let cjc_j be the coarsest ancestor of cc that is not adjacent to tt. By Lemma 1, j>ltj > l_t, the parent cj−1c_{j-1} is adjacent to tt, and cjc_j descends from the colleague cltc_{l_t}, so cj∈W(t)c_j \in W(t), and by Lemma 1 it is the only ancestor of cc in W(t)W(t). Route 1 fails because cc is not adjacent to tt.

Case D: k∗=m=lc<ltk^* = m = l_c < l_t. This is Case C with tt and cc exchanged: either c∈U(t)c \in U(t), or the coarsest ancestor tjt_j of tt that is not adjacent to cc has tj∈W(c)t_j \in W(c), that is c∈X(tj)c \in X(t_j), and no other route holds. □\square

Lemma 4 (separation). (a) If c∈V(b)c \in V(b), both of side ww, the centers are at least 2w2w apart. (b) If d∈W(b)d \in W(b), the box dd has side wdw_d smaller than the side of bb, and every point of bb is at distance at least 32wd\frac{3}{2} w_d from the center of dd. So the charges of dd, which lie within r=wd/2r = w_d / \sqrt{2} of its center, and the points xx of bb satisfy r/∣x−cd∣≤ρ=2/3r / |x - c_d| \le \rho = \sqrt{2} / 3. (c) The same ratio holds for b∈X(d)b \in X(d), with the charges in bb and the targets in dd 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 2w2w in it. (b) The box dd descends from a colleague of bb, so its level is finer. The boundaries of bb lie on the grid of spacing wdw_d. The closed squares of dd and bb are disjoint, so in one coordinate they are separated by a gap of at least wdw_d, and each point of bb differs from the center of dd by at least wd/2+wdw_d / 2 + w_d in that coordinate. (c) The pairs are the same as in (b), and the descendants of dd lie in dd. □\square

Theorem. Let uju_j be the output for a charge jj in leaf tt, u(zj)u(z_j) the exact potential without the self term, and A=∑i∣qi∣A = \sum_i |q_i|. With γ=22−1\gamma = 2\sqrt{2} - 1 and ρ=2/3\rho = \sqrt{2} / 3,

∣uj−u(zj)∣≤Amax⁡(4e(p+γ)(γ+1)+γ2γ(γ−1)(1γ)p+1,  ρp+1(p+1)(1−ρ)).|u_j - u(z_j)| \le A \max\left( \frac{4e(p + \gamma)(\gamma + 1) + \gamma^2}{\gamma (\gamma - 1)} \left( \frac{1}{\gamma} \right)^{p+1}, \; \frac{\rho^{p+1}}{(p + 1)(1 - \rho)} \right).

The bound tends to 00 as p→∞p \to \infty.

Proof. By Lemma 3 the charges other than jj are split into disjoint groups, one for each source leaf cc, and each group reaches tt by exactly one route. Route 1 is the direct sum of line L7, which is exact and leaves out i=ji = j. 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 ckc_k, at every point of tkt_k, by AckA_{c_k} times the first factor, as in Lemma 4 of the FMM proof. Route 3: the box ck∈W(t)c_k \in W(t) is evaluated at zjz_j from its pp-term multipole expansion; by Lemma 4(b) and the 2D truncation bound the error is at most AckA_{c_k} times the second factor. Route 4: the local expansion of the charges of cc about the center x0x_0 of tkt_k is the series qilog⁡(w−zi)=qilog⁡(x0−zi)−qi∑l≥11l(w−x0zi−x0)lq_i \log(w - z_i) = q_i \log(x_0 - z_i) - q_i \sum_{l \ge 1} \frac{1}{l} \left( \frac{w - x_0}{z_i - x_0} \right)^l, and by Lemma 4(c) the tail after l=pl = p is at most ∣qi∣ρp+1/((p+1)(1−ρ))|q_i| \rho^{p+1} / ((p+1)(1 - \rho)). The errors add, and the sums AcA_c over the disjoint source groups add to at most AA. □\square

The same argument with the derivatives of the series gives the convergence of the field. Since ρ<1/γ\rho < 1 / \gamma, the WW and XX routes converge faster than the VV route, and the first factor is the larger one for every pp; so the bound is the same as for the uniform FMM.

Complexity

The model is the real RAM, with DD the number of levels of the tree.

  • Boxes (theorem). A box is split only if it holds more than ss charges, and the boxes of one level are disjoint, so each level has at most N/sN / s split boxes and at most 4N/s4 N / s boxes. The tree has O(DN/s)O(D N / s) boxes.
  • Lists (theorem). Each VV 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 UU lists have O(DN/s)O(D N / s) entries in total. A box dd is in W(b)W(b) only for leaves bb that touch the parent of dd and are at least as large as it, so the WW and XX lists also have O(DN/s)O(D N / s) entries in total.
  • Work. P2M and L2P cost O(Np)O(N p); M2M, L2L and M2L cost O(p2)O(p^2) per box and list entry; M2P and P2L cost O(sp)O(s p) per list entry; the direct sum costs O(s2)O(s^2) per entry of UU. The total is O(Np+DN(p2/s+p+s))O(N p + D N (p^2 / s + p + s)). For a depth DD that does not grow with NN, this is O(N)O(N) for fixed pp and ss.
  • Any distribution. The depth can grow without bound if two charges are very close, so the bound above is not O(N)O(N) for every input. Nabors, Korsmeyer, Leighton and White (1994) proved an O(N)O(N) 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 s=10s = 10 and p=10p = 10, 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 N=500N = 500, 20002000 and 80008000: both grow linearly with NN.
  • 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. O(N)O(N) for the charges and O(p)O(p) coefficients per box, so O(N+DNp/s)O(N + D N p / s).

Properties

  • Same accuracy as the uniform FMM. The new routes WW and XX have a smaller ratio than VV, so the error bound is the one of the uniform method.
  • Linear in the charges. The output is a linear function of qq, 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 ss, 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 VV 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 WW and XX 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 NN, 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 XX 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 WW 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 UU and WW 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 ss makes many boxes and many translations; a large ss makes the direct sums slow. Choose ss near pp 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.

adaptive_fast_multipole_method.pyI0RawGitHub
# 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 O(N)O(N) bound for any distribution for an adaptive multipole scheme in 3D. Ying, Biros and Zorin (2004) used the same lists, named UU, VV, WW and XX, in their kernel-independent adaptive FMM.

References

  1. 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
  2. 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
  3. 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
  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

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