Algorithm Search⌘K

Algorithmresearch

Black-box fast multipole method

Also called bbFMM, Chebyshev fast multipole method.

An FMM for any smooth kernel that interpolates the kernel at Chebyshev nodes and compresses the multipole-to-local operators by singular value decomposition.

Time
Θ(N^2) worstΘ(N n^2 + N n^4 / s + N s + L n^4) averageΘ(N n^2) best
Space
Θ(N + N n^2 / s + L n^4) extra
Where
L = the leaf level; N = the number of charges; n = the number of Chebyshev nodes in each coordinate; s = the mean number of charges in a leaf box
Properties
deterministic
Origin
William Fong, Eric Darve, 2009

The black-box fast multipole method (bbFMM) computes sums uj=∑i≠jqiK(zj,zi)u_j = \sum_{i \ne j} q_i K(z_j, z_i) with the tree and the lists of the fast multipole method, for any kernel KK that is smooth away from x=yx = y and that the code can only evaluate. For two well separated boxes, it replaces KK by its Chebyshev interpolant in all coordinates of both points. The multipole expansion of a box becomes a set of weights at the Chebyshev nodes of the box, the local expansion becomes a set of values at the same nodes, and the multipole-to-local operator becomes a matrix of kernel values between two sets of nodes. Fong and Darve (2009) gave the method and compressed these matrices with the singular value decomposition, so that the far field uses close to the smallest number of coefficients for a given accuracy.

In plain words

The plain FMM needs a formula for how the pull of a group of charges changes with distance. The black-box FMM only asks for a function that gives the pull of one charge on one point.

For two boxes that are far apart, the pull changes smoothly across each box. A smooth function is well described by its values on a small grid of special points, packed more closely near the edges. So each box spreads its charges onto its grid points, the pull is computed only from grid points to grid points, and each target reads its value back from the grid of its own box. Passing values between a box and its children is exact, because a parent's smooth shape is also smooth inside each child.

More grid points give more digits. Near boxes are still added one pair at a time.

The problem

The input is NN charges qiq_i at points ziz_i of the unit square, a kernel K(x,y)K(x, y) given as a function, and a number nn of nodes in each coordinate. The output is an approximation of each potential

uj=∑i≠jqiK(zj,zi).u_j = \sum_{i \ne j} q_i K(z_j, z_i).

The kernel must be smooth when xx and yy lie in two well separated boxes; it does not have to solve any equation. Here it must also depend on x−yx - y only, so that the matrices can be computed once per level. The examples use log⁡∣x−y∣\log|x - y|, 1/∣x−y∣1 / |x - y| and the inverse multiquadric (∣x−y∣2+0.01)−1/2(|x - y|^2 + 0.01)^{-1/2}.

The algorithm

Let xˉm=cos⁡((2m−1)π/(2n))\bar x_m = \cos((2m - 1)\pi / (2n)), m=1,…,nm = 1, \ldots, n, be the Chebyshev nodes on [−1,1][-1, 1], and

Sn(xˉm,t)=1n+2n∑k=1n−1Tk(xˉm)Tk(t),S_n(\bar x_m, t) = \frac{1}{n} + \frac{2}{n} \sum_{k=1}^{n-1} T_k(\bar x_m) T_k(t),

which is the Lagrange polynomial of the node xˉm\bar x_m. Map each box BB to [−1,1]2[-1, 1]^2 and write SB(m,x)=Sn(xˉm1,ξ1)Sn(xˉm2,ξ2)S_B(m, x) = S_n(\bar x_{m_1}, \xi_1) S_n(\bar x_{m_2}, \xi_2) for the n2n^2 tensor nodes xˉmB\bar x^B_m of BB, where ξ\xi is the mapped point. For a target box TT and a source box CC in its interaction list,

K(x,y)≈∑m∑m′ST(m,x) K(xˉmT,xˉm′C) SC(m′,y).K(x, y) \approx \sum_m \sum_{m'} S_T(m, x) \, K(\bar x^T_m, \bar x^C_{m'}) \, S_C(m', y).
  1. BBFMM(q, z, K, n, L)
  2. 1for each leaf C: W_C(m') ← Σ_{i in C} q_i S_C(m', z_i)
  3. 2for l ← L - 1 down to 2: for each box B at level l: W_B(m) ← Σ over the children C of Σ_{m'} S_B(m, x̄^C_{m'}) W_C(m')
  4. for l ← 2 to L do
  5. for each box T at level l do
  6. 3g_T(m) ← Σ_{C in the interaction list of T} Σ_{m'} K(x̄^T_m, x̄^C_{m'}) W_C(m')
  7. 4if l < L then for each child D of T: g_D(k) ← g_D(k) + Σ_m g_T(m) S_T(m, x̄^D_k)
  8. 5for each leaf T and charge j in T: u_j ← Σ_m g_T(m) S_T(m, z_j)
  9. 6add the direct terms of all charges i ≠ j in T and its near neighbours
  10. 7return u

Lines L1 to L5 are the P2M, M2M, M2L, L2L and L2P steps of the FMM. Line L1 anterpolates the charges onto the nodes and line L5 interpolates the values back. The shifts of lines L2 and L4 use the n×nn \times n matrices Sn(xˉm,(xˉm′±1)/2)S_n(\bar x_m, (\bar x_{m'} \pm 1)/2) of the parent basis at the child nodes, once for each coordinate, so they cost O(n3)O(n^3) per box. Line L3 uses one n2×n2n^2 \times n^2 matrix of kernel values for each of the 72−32=407^2 - 3^2 = 40 offsets of the interaction list, computed once per level.

Fong and Darve also compress line L3. They stack the M2L matrices of a level and take a truncated SVD, so that each translation becomes a product with a small r×rr \times r matrix, with rr set by the tolerance. The code on this page applies the full matrices.

Example

Take N=400N = 400 uniform points in the unit square with charges uniform in [−1,1][-1, 1] (seed 5), and leaves at level L=3L = 3. The near field uses 18302 ordered pairs and there are 1272 M2L products, the same counts as for the analytic FMM on these points. Against direct summation, the relative errors in the 2-norm are:

nn values per box log⁡\log kernel largest error, log⁡\log 1/r1/r kernel inverse multiquadric
2 4 8.7×10−38.7 \times 10^{-3} 4.4×10−14.4 \times 10^{-1} 6.1×10−36.1 \times 10^{-3} 1.0×10−21.0 \times 10^{-2}
3 9 1.0×10−31.0 \times 10^{-3} 3.5×10−23.5 \times 10^{-2} 9.7×10−49.7 \times 10^{-4} 1.5×10−31.5 \times 10^{-3}
4 16 9.5×10−59.5 \times 10^{-5} 4.7×10−34.7 \times 10^{-3} 1.2×10−41.2 \times 10^{-4} 1.4×10−41.4 \times 10^{-4}
6 36 2.2×10−62.2 \times 10^{-6} 8.8×10−58.8 \times 10^{-5} 3.5×10−63.5 \times 10^{-6} 3.2×10−63.2 \times 10^{-6}
8 64 5.8×10−85.8 \times 10^{-8} 2.6×10−62.6 \times 10^{-6} 9.7×10−89.7 \times 10^{-8} 7.8×10−87.8 \times 10^{-8}
10 100 1.5×10−91.5 \times 10^{-9} 8.8×10−88.8 \times 10^{-8} 2.6×10−92.6 \times 10^{-9} 2.0×10−92.0 \times 10^{-9}

These are measurements. The three kernels use the same code; only the function KK changes. From n=4n = 4 on, the error falls by a factor of about 6 for each extra node, nearly the same for the three kernels: the rate depends mostly on how far the singularity at x=yx = y is from the pairs of boxes, and the three kernels have it at the same place.

The price is the number of values. With n=8n = 8 a box holds 64 values for the relative error 5.8×10−85.8 \times 10^{-8}. On the same points, the analytic FMM with p=12p = 12 complex terms (24 real values) has 3.0×10−83.0 \times 10^{-8}, and the kernel-independent FMM with 24 points on each circle has 2.3×10−72.3 \times 10^{-7}. A tensor grid of n2n^2 nodes holds more numbers than the far field needs, and the SVD compression of Fong and Darve removes this excess.

Correctness

The proof file proves two things. First, the shifts of lines L2 and L4 are exact: a parent basis polynomial SB(m,⋅)S_B(m, \cdot) has degree n−1n - 1 in each coordinate, also inside each child, and interpolation at nn nodes reproduces such polynomials (Lemmas 1 and 2). So the output is exactly the direct sum in which, for every pair of a target box and a box in its interaction list, KK is replaced by its tensor Chebyshev interpolant in four variables (Lemma 3). The error is then at most ∑i∣qi∣\sum_i |q_i| times the largest interpolation error over these pairs.

Second, this interpolation error tends to 0. Each 1D interpolation step has the error at most 1+Λn1 + \Lambda_n times the best polynomial error, where Λn=O(log⁡n)\Lambda_n = O(\log n) is the Lebesgue constant of the Chebyshev nodes, and four steps give at most 4(1+Λn)44 (1 + \Lambda_n)^4 times it. For the three kernels above, the singular points in each scaled coordinate lie outside the Bernstein ellipse with ρ=2+5\rho = 2 + \sqrt{5}, because the boxes of an interaction list are one box width apart. Then the best error is O(ρ−n)O(\rho^{-n}) by the bound on the Chebyshev coefficients of an analytic function. This is a bound on the rate; the measured rate above is faster.

Proof: The bbFMM equals direct summation with the kernel replaced by its Chebyshev interpolant on each far pair, and it converges for kernels analytic away from the diagonalfull

We use exact arithmetic. The tree is uniform, with leaves at level L≥2L \ge 2, and the lists are those of the fast multipole method. Let xˉ1,…,xˉn\bar x_1, \ldots, \bar x_n be the Chebyshev nodes cos⁡((2m−1)π/(2n))\cos((2m - 1)\pi / (2n)) on [−1,1][-1, 1] and Sn(xˉm,t)=1n+2n∑k=1n−1Tk(xˉm)Tk(t)S_n(\bar x_m, t) = \frac{1}{n} + \frac{2}{n} \sum_{k=1}^{n-1} T_k(\bar x_m) T_k(t). For a box BB with center cBc_B and side wBw_B, let ξB(x)=2(x−cB)/wB∈[−1,1]2\xi_B(x) = 2 (x - c_B) / w_B \in [-1, 1]^2, and for m=(m1,m2)m = (m_1, m_2) let SB(m,x)=Sn(xˉm1,ξB,1(x)) Sn(xˉm2,ξB,2(x))S_B(m, x) = S_n(\bar x_{m_1}, \xi_{B,1}(x)) \, S_n(\bar x_{m_2}, \xi_{B,2}(x)), with the node xˉmB=cB+wB2(xˉm1,xˉm2)\bar x^B_m = c_B + \frac{w_B}{2} (\bar x_{m_1}, \bar x_{m_2}).

Lemma 1 (Lagrange basis). Sn(xˉm,⋅)S_n(\bar x_m, \cdot) is the polynomial of degree at most n−1n - 1 that is 1 at xˉm\bar x_m and 0 at the other nodes. Hence, for every polynomial ff of degree at most n−1n - 1, ∑mf(xˉm)Sn(xˉm,t)=f(t)\sum_m f(\bar x_m) S_n(\bar x_m, t) = f(t), and the same holds in 2D for polynomials of degree at most n−1n - 1 in each coordinate.

Proof. The degree is clear. With θj=(2j−1)π/(2n)\theta_j = (2j - 1)\pi / (2n), Tk(xˉj)=cos⁡(kθj)T_k(\bar x_j) = \cos(k \theta_j), and the discrete orthogonality of the cosines at these angles gives ∑k=0n−1′cos⁡(kθm)cos⁡(kθj)=n2[m=j]\sum_{k=0}^{n-1}{}' \cos(k\theta_m) \cos(k\theta_j) = \frac{n}{2} [m = j], where the prime halves the term k=0k = 0. Multiply by 2/n2/n: this is Sn(xˉm,xˉj)=[m=j]S_n(\bar x_m, \bar x_j) = [m = j]. A polynomial of degree at most n−1n - 1 is fixed by its values at nn points, which gives the reproduction. The 2D statement follows by applying the 1D one in each coordinate. □\square

Lemma 2 (the shifts are exact). (a) If CC is a child of BB, the upward shift of line L2 maps the weights WC(m′)=∑i∈CqiSC(m′,yi)W_C(m') = \sum_{i \in C} q_i S_C(m', y_i) to ∑i∈CqiSB(m,yi)\sum_{i \in C} q_i S_B(m, y_i). (b) If gg is a vector of values at the nodes of BB, the downward shift of line L4 gives values g′g' at the nodes of a child DD with ∑kg′(k)SD(k,x)=∑mg(m)SB(m,x)\sum_{k} g'(k) S_D(k, x) = \sum_m g(m) S_B(m, x) for every x∈Dx \in D.

Proof. (a) The shift computes ∑m′SB(m,xˉm′C)WC(m′)=∑iqi∑m′SB(m,xˉm′C)SC(m′,yi)\sum_{m'} S_B(m, \bar x^C_{m'}) W_C(m') = \sum_i q_i \sum_{m'} S_B(m, \bar x^C_{m'}) S_C(m', y_i). As a function of y∈Cy \in C, SB(m,y)S_B(m, y) is a polynomial of degree n−1n - 1 in each coordinate, also in the coordinates ξC\xi_C of the child, so by Lemma 1 the inner sum is SB(m,yi)S_B(m, y_i). (b) The shift sets g′(k)=∑mg(m)SB(m,xˉkD)g'(k) = \sum_m g(m) S_B(m, \bar x^D_k), and ∑kg′(k)SD(k,x)=∑mg(m)∑kSB(m,xˉkD)SD(k,x)=∑mg(m)SB(m,x)\sum_k g'(k) S_D(k, x) = \sum_m g(m) \sum_k S_B(m, \bar x^D_k) S_D(k, x) = \sum_m g(m) S_B(m, x) by Lemma 1 in the same way. □\square

Lemma 3 (the output). Let jj be a charge in leaf tt, and for a box CC in the interaction list of an ancestor TT of tt let

K~T,C(x,y)=∑m∑m′ST(m,x) K(xˉmT,xˉm′C) SC(m′,y),\tilde K_{T,C}(x, y) = \sum_{m} \sum_{m'} S_T(m, x) \, K(\bar x^T_m, \bar x^C_{m'}) \, S_C(m', y),

the tensor Chebyshev interpolant of KK on T×CT \times C with nn nodes in each of the four coordinates. Then the output is

uj=∑i nearqiK(zj,zi)+∑(T,C)∑i∈CqiK~T,C(zj,zi),u_j = \sum_{i \text{ near}} q_i K(z_j, z_i) + \sum_{(T, C)} \sum_{i \in C} q_i \tilde K_{T,C}(z_j, z_i),

where the first sum is over the charges i≠ji \ne j in the near neighbours of tt and the second over the pairs of Lemma 1 of the FMM proof, which split the far charges into disjoint boxes.

Proof. By Lemma 2(a) and induction from the leaves up, after line L2 every box CC holds WC(m′)=∑i∈CqiSC(m′,zi)W_C(m') = \sum_{i \in C} q_i S_C(m', z_i). Line L3 adds ∑m′K(xˉmT,xˉm′C)WC(m′)\sum_{m'} K(\bar x^T_m, \bar x^C_{m'}) W_C(m') to the value of TT at the node mm. By Lemma 2(b) and induction from the root down, the values gtg_t of the leaf satisfy ∑kgt(k)St(k,x)=∑(T,C)∑mST(m,x)∑m′K(xˉmT,xˉm′C)WC(m′)\sum_k g_t(k) S_t(k, x) = \sum_{(T, C)} \sum_m S_T(m, x) \sum_{m'} K(\bar x^T_m, \bar x^C_{m'}) W_C(m') for x∈tx \in t. Line L5 evaluates this at zjz_j, and substituting WCW_C gives the second sum. Line L6 adds the first. That the pairs split the far charges is Lemma 1 of the FMM proof, which uses only the tree and the lists. □\square

So the error is ∑(T,C)∑i∈Cqi(K~T,C−K)(zj,zi)\sum_{(T, C)} \sum_{i \in C} q_i (\tilde K_{T,C} - K)(z_j, z_i), and

∣uj−u(zj)∣≤(∑i∣qi∣)max⁡(T,C)sup⁡T×C∣K−K~T,C∣.|u_j - u(z_j)| \le \Big( \sum_i |q_i| \Big) \max_{(T, C)} \sup_{T \times C} |K - \tilde K_{T,C}|.

Theorem (convergence). Let K(x,y)K(x, y), for x∈Tx \in T and y∈Cy \in C, be the restriction of a function that, as a function of each one of the four coordinates with the others fixed and real, extends to an analytic function bounded by MM in the Bernstein ellipse EρE_\rho (in the scaled coordinate) for a fixed ρ>1\rho > 1, for all pairs (T,C)(T, C) of the interaction lists. Then sup⁡∣K−K~T,C∣≤4(1+Λn)42Mρ1−nρ−1\sup |K - \tilde K_{T,C}| \le 4 (1 + \Lambda_n)^4 \frac{2 M \rho^{1-n}}{\rho - 1}, where Λn\Lambda_n is the Lebesgue constant of the nn Chebyshev nodes, and the error of the bbFMM tends to 0 as n→∞n \to \infty.

Proof. Write K~=I1I2I3I4K\tilde K = I_1 I_2 I_3 I_4 K, where IdI_d is 1D interpolation in coordinate dd at the scaled nodes; these operators commute. Then K−K~=(K−I1K)+I1(K−I2K)+I1I2(K−I3K)+I1I2I3(K−I4K)K - \tilde K = (K - I_1 K) + I_1 (K - I_2 K) + I_1 I_2 (K - I_3 K) + I_1 I_2 I_3 (K - I_4 K). In the sup norm, ∥Idf∥≤Λn∥f∥\|I_d f\| \le \Lambda_n \|f\|, and ∥f−Idf∥≤(1+Λn)Ed\|f - I_d f\| \le (1 + \Lambda_n) E_d, where EdE_d is the largest, over the other coordinates, best approximation error of ff by polynomials of degree n−1n - 1 in coordinate dd. The Chebyshev coefficients of a function analytic and bounded by MM in EρE_\rho satisfy ∣ak∣≤2Mρ−k|a_k| \le 2 M \rho^{-k} (Trefethen, Theorem 8.1), so truncating the Chebyshev series after degree n−1n - 1 gives Ed≤E:=∑k≥n2Mρ−k=2Mρ1−n/(ρ−1)E_d \le E := \sum_{k \ge n} 2 M \rho^{-k} = 2 M \rho^{1-n} / (\rho - 1). Each term of the decomposition applies some operators IdI_d to an error K−IeKK - I_e K of KK itself, so only the analyticity of KK in each coordinate is used. The four terms are at most (1+Λn)E(1+Λn+Λn2+Λn3)≤4(1+Λn)4E(1 + \Lambda_n) E (1 + \Lambda_n + \Lambda_n^2 + \Lambda_n^3) \le 4 (1 + \Lambda_n)^4 E. Since Λn=O(log⁡n)\Lambda_n = O(\log n) for Chebyshev nodes, the bound tends to 0. □\square

The kernels of the page satisfy the hypothesis. For K=log⁡∣x−y∣K = \log|x - y|, 1/∣x−y∣1/|x - y| or (∣x−y∣2+c2)−1/2(|x - y|^2 + c^2)^{-1/2}, fix all coordinates but one, say x1x_1. The function depends on x1x_1 through (x1−y1)2+δ2(x_1 - y_1)^2 + \delta^2 with δ=∣x2−y2∣\delta = |x_2 - y_2| (and c2c^2 added), and it is analytic in x1x_1 except where (x1−y1)2=−δ2(x_1 - y_1)^2 = -\delta^2 (or −δ2−c2-\delta^2 - c^2). Two boxes of side ww in an interaction list are at least ww apart in one coordinate. If that coordinate is x1x_1, the singular points have real part at least ww from the interval of x1x_1, which has half-length w/2w / 2, so they are at least at the scaled distance 2 from [−1,1][-1, 1] along the real axis. Otherwise δ≥w\delta \ge w, and they are at the scaled imaginary distance at least 2. In both cases they lie outside the open ellipse EρE_\rho with ρ=2+5\rho = 2 + \sqrt{5}, whose semi-axes are 5<3\sqrt{5} < 3 and 2. The ellipse is simply connected and (x1−y1)2+δ2(x_1 - y_1)^2 + \delta^2 (plus c2c^2) has no zero in it, so a branch of the log and of the square root is analytic there, and the function is bounded on the closed ellipse Eρ′E_{\rho'} for any ρ′<ρ\rho' < \rho. The offsets of the interaction list and the levels are finitely many, so one ρ′>1\rho' > 1 and one MM serve all pairs. For the log kernel the scaling changes the kernel only by a constant, which the interpolation reproduces, so the bound is the same at every level. □\square

Complexity

The model is the real RAM, with kernel evaluations counted as one operation.

  • Same structure as the FMM (theorem). The tree and the lists are those of the uniform FMM. Lines L1 and L5 cost Θ(n2)\Theta(n^2) per charge, Θ(Nn2)\Theta(N n^2) in total. Lines L2 and L4 cost O(n3)O(n^3) per box. Line L3 costs n4n^4 per pair, at most 27 pairs per box, so Θ((N/s)n4)\Theta((N / s) n^4). Line L6 costs Θ(Ns)\Theta(N s).
  • Precomputation. 4040 matrices of n4n^4 kernel values per level, Θ(Ln4)\Theta(L n^4). For a homogeneous kernel such as 1/r1 / r, the matrices of one level give all the others after scaling.
  • With SVD compression. With rank rr, the M2L products cost O(r2)O(r^2) each, plus O(n2r)O(n^2 r) per box to enter and leave the compressed basis. In 3D, with n3n^3 nodes per box and 189 boxes in the interaction list, this is the step that makes the method practical.
  • Worst case. With a uniform tree, clustered charges make the near field Θ(N2)\Theta(N^2); an adaptive tree with the lists of the adaptive FMM avoids this.
  • Space. Θ(N+Nn2/s)\Theta(N + N n^2 / s) for the weights and values, plus Θ(Ln4)\Theta(L n^4) for the matrices.

Properties

  • Only kernel values. The code calls KK only as a function, and only at nodes and at near pairs. The kernel need not solve an equation, unlike for the kernel-independent FMM.
  • Exact shifts. The M2M and L2L steps add no error. All the error comes from the interpolation in the M2L step.
  • Linear in the charges. The output is a linear function of qq, so the method is a fast matrix-vector product for iterative solvers of boundary element and integral equations, and for kernel matrices of Gaussian processes.
  • Uniform accuracy across levels for the log kernel. Scaling a box changes log⁡∣x−y∣\log|x - y| only by a constant, which interpolation reproduces, so every level has the same relative accuracy.
  • Deterministic. The result does not depend on the order of the charges, up to rounding.

Variants and improvements

  • SVD compression. Fong and Darve compress the M2L operators of each level by a truncated SVD of the stacked matrices, which also gives the multipole and local bases of the smallest size for a given tolerance in the 2-norm.
  • Adaptive trees. The same expansions work on an adaptive tree with the UU, VV, WW and XX lists of the adaptive FMM; the W and X lists need the conversion between charges and node values.
  • Other interpolation nodes. Equispaced nodes make the M2L matrices Toeplitz, so the FFT applies them fast, at the cost of a larger Lebesgue constant and worse stability than Chebyshev nodes.
  • Oscillatory kernels. For the Helmholtz kernel at high frequency, nn must grow with the size of a box in wavelengths, and directional variants of the interpolation are used.
  • Higher dimensions. In 3D the box holds n3n^3 nodes and the M2L matrices have n6n^6 entries, so compression is needed for any practical nn.

When to use it

Use the bbFMM when the kernel is smooth away from the diagonal but has no convenient expansions: kernels given by a formula that is long to expand, kernels that come from a table or another computation, covariance functions, or anisotropic kernels. It is a good choice when you need to change the kernel often. For the Laplace kernel in 2D, the analytic FMM needs fewer coefficients for the same accuracy. For Green's functions of elliptic equations, the kernel-independent FMM is the other black-box choice. For small NN, use direct summation.

Pitfalls

  • Points outside the box. The basis SnS_n is a polynomial, and it grows fast outside [−1,1][-1, 1]. A charge assigned to the wrong box, for example by a rounding error at the edge of the square, is extrapolated and can give a large error. Clamp the mapped coordinates to [−1,1][-1, 1].
  • Kernels that are not smooth enough. A kernel with a singularity or a fast change at a distance comparable to a box, such as a narrow Gaussian or a kernel with a softening length close to the box size, needs many more nodes. Choose the levels so that the boxes are large or small compared with that length.
  • Cost without compression. The M2L step costs n4n^4 per pair in 2D and n6n^6 in 3D. Without the SVD step, the method is slower than the analytic FMM for the same accuracy.
  • Matrices per level. For a kernel that is not homogeneous, the M2L matrices differ between levels and must be computed for each level.
  • Too few nodes for the accuracy. The rate of convergence on this page depends on the separation of the interaction list and on the kernel. Measure against direct summation on a small problem.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

black_box_fast_multipole_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/black-box-fast-multipole-method/. The authors are listed in prov/T616YW.jsonl.
"""Black-box fast multipole method of Fong and Darve, in 2D on a uniform tree.

Charges q[i] sit at points z[i] (complex numbers) of the unit square. The
output is u_j = sum over i != j of q_i K(z_j, z_i), for any kernel K that is
smooth away from x = y and is given as a function.

For two well separated boxes T and C, the kernel is replaced by its tensor
Chebyshev interpolant with n nodes in each of the four coordinates:

    K(x, y) ~ sum_m sum_m' S_T(m, x) K(xbar_m, ybar_m') S_C(m', y),

where xbar_m are the n^2 nodes of T, ybar_m' those of C, and
S(m, x) = S_n(xbar_m1, x1) S_n(xbar_m2, x2) with

    S_n(xbar, x) = 1/n + (2/n) sum_{k=1}^{n-1} T_k(xbar) T_k(x)

on [-1, 1] (the Lagrange polynomial of the Chebyshev node xbar). The
multipole weights of a box are W_C(m') = sum_i q_i S_C(m', y_i), and the
local values of a box are g_T(m) = sum K(xbar_m, ybar_m') W_C(m'). The
shifts between parent and child boxes are interpolation steps, which are
exact because S_parent(m, .) is a polynomial of degree n - 1.
"""

import math
from typing import Callable, Optional, Sequence

Kernel = Callable[[complex, complex], float]


def log_kernel(x: complex, y: complex) -> float:
    return math.log(abs(x - y))


def inverse_distance(x: complex, y: complex) -> float:
    return 1.0 / abs(x - y)


def cheb_nodes(n: int) -> list[float]:
    """The n Chebyshev nodes of the first kind, cos((2m - 1) pi / (2n)), m = 1..n."""
    return [math.cos((2 * m - 1) * math.pi / (2 * n)) for m in range(1, n + 1)]


def cheb_T(n: int, x: float) -> list[float]:
    """T_0(x), ..., T_{n-1}(x) by the three-term recurrence."""
    t = [1.0, x][:n]
    while len(t) < n:
        t.append(2 * x * t[-1] - t[-2])
    return t


def s_weights(n: int, nodes: Sequence[float], x: float) -> list[float]:
    """[S_n(xbar_m, x) for each node xbar_m], for x in [-1, 1]."""
    tx = cheb_T(n, x)
    out = []
    for xm in nodes:
        tm = cheb_T(n, xm)
        out.append(1.0 / n + (2.0 / n) * sum(tm[k] * tx[k] for k in range(1, n)))
    return out


def box_center(ix: int, iy: int, level: int) -> complex:
    h = 1.0 / (1 << level)
    return complex((ix + 0.5) * h, (iy + 0.5) * h)


def interaction_list(ix: int, iy: int, level: int) -> list[tuple[int, int]]:
    """Children of the near neighbours of the parent that are not near neighbours of the box."""
    m = 1 << level
    px, py = ix // 2, iy // 2
    out = []
    for nx in range(2 * (px - 1), 2 * (px + 2)):
        for ny in range(2 * (py - 1), 2 * (py + 2)):
            if 0 <= nx < m and 0 <= ny < m and max(abs(nx - ix), abs(ny - iy)) > 1:
                out.append((nx, ny))
    return out


def box_nodes(center: complex, w: float, nodes: Sequence[float]) -> list[complex]:
    """The n^2 tensor Chebyshev nodes of a box of side w, index m = m1 * n + m2."""
    return [center + 0.5 * w * complex(a, b) for a in nodes for b in nodes]


def p2m(q, z, idx, center: complex, w: float, n: int, nodes) -> list[float]:
    """W(m) = sum_i q_i S(m, y_i), with y_i mapped to [-1, 1]^2."""
    wt = [0.0] * (n * n)
    for i in idx:
        sx = s_weights(n, nodes, 2 * (z[i].real - center.real) / w)
        sy = s_weights(n, nodes, 2 * (z[i].imag - center.imag) / w)
        for m1 in range(n):
            a = q[i] * sx[m1]
            for m2 in range(n):
                wt[m1 * n + m2] += a * sy[m2]
    return wt


def child_shift(n: int, nodes) -> dict:
    """S1[a][m][m'] = S_n(xbar_m, (xbar_m' + 2a - 1) / 2): parent basis at the child nodes, a = 0 or 1."""
    return {a: [s_weights(n, nodes, (xm + 2 * a - 1) / 2) for xm in nodes] for a in (0, 1)}


def _shift_up(wc: Sequence[float], sa, sb, n: int) -> list[float]:
    """Parent weights from child weights: W_p(m1, m2) = sum S1[a][m'1][m1] S1[b][m'2][m2] W_c(m'1, m'2)."""
    tmp = [0.0] * (n * n)
    for k1 in range(n):
        for m2 in range(n):
            tmp[k1 * n + m2] = sum(sb[k2][m2] * wc[k1 * n + k2] for k2 in range(n))
    out = [0.0] * (n * n)
    for m1 in range(n):
        for m2 in range(n):
            out[m1 * n + m2] = sum(sa[k1][m1] * tmp[k1 * n + m2] for k1 in range(n))
    return out


def _shift_down(gp: Sequence[float], sa, sb, n: int) -> list[float]:
    """Child values from parent values: g_c(k1, k2) = sum S1[a][k1][m1] S1[b][k2][m2] g_p(m1, m2)."""
    tmp = [0.0] * (n * n)
    for m1 in range(n):
        for k2 in range(n):
            tmp[m1 * n + k2] = sum(sb[k2][m2] * gp[m1 * n + m2] for m2 in range(n))
    out = [0.0] * (n * n)
    for k1 in range(n):
        for k2 in range(n):
            out[k1 * n + k2] = sum(sa[k1][m1] * tmp[m1 * n + k2] for m1 in range(n))
    return out


def m2l_matrices(kernel: Kernel, level: int, nodes) -> dict:
    """[K(xbar_m, ybar_m')] for a target box at 0 and a source box at each offset of the interaction list."""
    w = 1.0 / (1 << level)
    tgt = box_nodes(0j, w, nodes)
    out = {}
    for dx in range(-3, 4):
        for dy in range(-3, 4):
            if max(abs(dx), abs(dy)) > 1:
                src = box_nodes(complex(dx * w, dy * w), w, nodes)
                out[(dx, dy)] = [[kernel(x, y) for y in src] for x in tgt]
    return out


def bbfmm(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel, n: int = 5,
          levels: Optional[int] = None, s: int = 8):
    """Potentials u_j = sum_{i != j} q_i K(z_j, z_i) with n Chebyshev nodes per coordinate.

    levels is the leaf level L (at least 2). Returns (u, stats) with the
    ordered pairs of the near field ("p2p") and the M2L products ("m2l").
    """
    nq = len(z)
    if levels is None:
        levels = max(2, math.ceil(math.log(nq / s, 4))) if nq > s else 2
    L = levels
    nodes = cheb_nodes(n)
    shift = child_shift(n, nodes)
    mats = {l: m2l_matrices(kernel, l, nodes) for l in range(2, L + 1)}
    m = 1 << L
    leaf: dict[tuple[int, int], list[int]] = {}
    for i, zi in enumerate(z):
        key = (min(int(zi.real * m), m - 1), min(int(zi.imag * m), m - 1))
        leaf.setdefault(key, []).append(i)
    mult: list[dict] = [dict() for _ in range(L + 1)]
    for key, idx in leaf.items():  # @line L1
        mult[L][key] = p2m(q, z, idx, box_center(*key, L), 1.0 / m, n, nodes)
    for l in range(L - 1, 1, -1):  # @line L2
        for (cx, cy), wc in mult[l + 1].items():
            acc = mult[l].setdefault((cx // 2, cy // 2), [0.0] * (n * n))
            up = _shift_up(wc, shift[cx % 2], shift[cy % 2], n)
            for k in range(n * n):
                acc[k] += up[k]
    local: list[dict] = [dict() for _ in range(L + 1)]
    n_m2l = 0
    for l in range(2, L + 1):
        for key, wc in mult[l].items():  # @line L3
            for tgt in interaction_list(*key, l):
                if l == L and tgt not in leaf:
                    continue
                mat = mats[l][(key[0] - tgt[0], key[1] - tgt[1])]
                acc = local[l].setdefault(tgt, [0.0] * (n * n))
                for k in range(n * n):
                    acc[k] += sum(a * b for a, b in zip(mat[k], wc))
                n_m2l += 1
        if l < L:
            for (px, py), gp in local[l].items():  # @line L4
                for a in (0, 1):
                    for b in (0, 1):
                        down = _shift_down(gp, shift[a], shift[b], n)
                        acc = local[l + 1].setdefault((2 * px + a, 2 * py + b), [0.0] * (n * n))
                        for k in range(n * n):
                            acc[k] += down[k]
    u = [0.0] * nq
    n_p2p = 0
    w = 1.0 / m
    for key, idx in leaf.items():
        g = local[L].get(key)
        c = box_center(*key, L)
        if g is not None:
            for j in idx:  # @line L5
                sx = s_weights(n, nodes, 2 * (z[j].real - c.real) / w)
                sy = s_weights(n, nodes, 2 * (z[j].imag - c.imag) / w)
                u[j] += sum(sx[m1] * sum(sy[m2] * g[m1 * n + m2] for m2 in range(n)) for m1 in range(n))
        ix, iy = key
        for nx in range(ix - 1, ix + 2):  # @line L6
            for ny in range(iy - 1, iy + 2):
                for i in leaf.get((nx, ny), ()):
                    for j in idx:
                        if i != j:
                            u[j] += q[i] * kernel(z[j], z[i])
                            n_p2p += 1
    return u, {"p2p": n_p2p, "m2l": n_m2l}  # @line L7


def direct(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel) -> list[float]:
    """Direct summation over all ordered pairs: the reference."""
    nq = len(z)
    return [sum(q[i] * kernel(z[j], z[i]) for i in range(nq) if i != j) for j in range(nq)]
test_black_box_fast_multipole_method.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/black-box-fast-multipole-method/. The authors are listed in prov/T616YW.jsonl.
"""Tests for the black-box FMM: Chebyshev interpolation, exact shifts and three kernels against direct summation."""

import math
import random
import unittest

from black_box_fast_multipole_method import (
    _shift_down,
    _shift_up,
    bbfmm,
    box_center,
    cheb_nodes,
    child_shift,
    direct,
    inverse_distance,
    log_kernel,
    p2m,
    s_weights,
)


def inverse_multiquadric(x, y):
    return 1.0 / math.sqrt(abs(x - y) ** 2 + 0.01)


def rel(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b))) / math.sqrt(sum(y * y for y in b))


def uniform(n, seed):
    rng = random.Random(seed)
    z = [complex(rng.random(), rng.random()) for _ in range(n)]
    q = [rng.uniform(-1, 1) for _ in range(n)]
    return q, z


class TestChebyshev(unittest.TestCase):
    def test_lagrange_property(self):
        n = 6
        nodes = cheb_nodes(n)
        for k, xk in enumerate(nodes):
            s = s_weights(n, nodes, xk)
            for m in range(n):
                self.assertAlmostEqual(s[m], 1.0 if m == k else 0.0, places=12)

    def test_reproduces_polynomials(self):
        n = 5
        nodes = cheb_nodes(n)

        def poly(t):
            return 3 * t ** 4 - t ** 3 + 0.5 * t - 2

        for x in (-1.0, -0.3, 0.2, 0.9):
            s = s_weights(n, nodes, x)
            self.assertAlmostEqual(sum(poly(xm) * sm for xm, sm in zip(nodes, s)), poly(x), places=12)


class TestShifts(unittest.TestCase):
    def test_upward_shift_is_exact(self):
        n = 4
        nodes = cheb_nodes(n)
        shift = child_shift(n, nodes)
        rng = random.Random(3)
        level = 3
        w = 1.0 / (1 << level)
        child = (5, 2)
        c = box_center(*child, level)
        z = [c + complex((rng.random() - 0.5) * w, (rng.random() - 0.5) * w) for _ in range(7)]
        q = [rng.uniform(-1, 1) for _ in range(7)]
        wc = p2m(q, z, range(7), c, w, n, nodes)
        up = _shift_up(wc, shift[child[0] % 2], shift[child[1] % 2], n)
        wp = p2m(q, z, range(7), box_center(2, 1, 2), 2 * w, n, nodes)
        for a, b in zip(up, wp):
            self.assertAlmostEqual(a, b, places=12)

    def test_downward_shift_is_exact(self):
        n = 4
        nodes = cheb_nodes(n)
        shift = child_shift(n, nodes)
        rng = random.Random(4)
        gp = [rng.uniform(-1, 1) for _ in range(n * n)]
        gc = _shift_down(gp, shift[1], shift[0], n)
        for _ in range(5):
            x, y = rng.uniform(-1, 1), rng.uniform(-1, 1)
            px, py = (x + 1) / 2, (y - 1) / 2
            sx, sy = s_weights(n, nodes, x), s_weights(n, nodes, y)
            tx, ty = s_weights(n, nodes, px), s_weights(n, nodes, py)
            child_val = sum(sx[a] * sy[b] * gc[a * n + b] for a in range(n) for b in range(n))
            parent_val = sum(tx[a] * ty[b] * gp[a * n + b] for a in range(n) for b in range(n))
            self.assertAlmostEqual(child_val, parent_val, places=12)


class TestBBFMM(unittest.TestCase):
    def test_log_kernel_matches_direct(self):
        q, z = uniform(400, 5)
        ud = direct(q, z)
        errs = []
        for n in (2, 4, 6, 8):
            u, st = bbfmm(q, z, n=n, levels=3)
            errs.append(rel(u, ud))
        for k in range(3):
            self.assertLess(errs[k + 1], errs[k] / 10)
        self.assertLess(errs[-1], 1e-7)
        self.assertEqual(st["m2l"], 1272)

    def test_other_kernels(self):
        q, z = uniform(300, 6)
        for kernel in (inverse_distance, inverse_multiquadric):
            ud = direct(q, z, kernel)
            u, _ = bbfmm(q, z, kernel=kernel, n=6, levels=3)
            self.assertLess(rel(u, ud), 1e-5)

    def test_leaf_level_two(self):
        q, z = uniform(200, 7)
        ud = direct(q, z)
        u, _ = bbfmm(q, z, n=6, levels=2)
        self.assertLess(rel(u, ud), 1e-5)

    def test_linear_in_the_charges(self):
        q, z = uniform(150, 8)
        rng = random.Random(9)
        r = [rng.uniform(-1, 1) for _ in range(150)]
        u1, _ = bbfmm(q, z, n=4, levels=3)
        u2, _ = bbfmm(r, z, n=4, levels=3)
        u3, _ = bbfmm([a - 2 * b for a, b in zip(q, r)], z, n=4, levels=3)
        for a, b, c in zip(u1, u2, u3):
            self.assertAlmostEqual(c, a - 2 * b, places=9)

    def test_small_inputs(self):
        self.assertEqual(bbfmm([], [])[0], [])
        self.assertEqual(bbfmm([1.0], [complex(0.4, 0.6)])[0], [0.0])
        q = [1.0, -2.0, 0.5]
        z = [complex(0.1, 0.1), complex(0.9, 0.8), complex(0.15, 0.85)]
        u, _ = bbfmm(q, z, kernel=log_kernel, n=8)
        for a, b in zip(u, direct(q, z)):
            self.assertAlmostEqual(a, b, places=5)


if __name__ == "__main__":
    unittest.main()

History

Interpolation of smooth kernels on hierarchical boxes was used before 2009 in several fast summation methods. Fong and Darve (2009) gave the black-box FMM: tensor Chebyshev interpolation of the kernel inside the FMM tree, with exact shifts between levels and a compression of the M2L operators by singular value decompositions. Their aim was a method for kernels that are known only numerically, or that are known analytically but are complicated, with a small precomputation time even for large systems. The kernel-independent FMM of Ying, Biros and Zorin (2004) is the other main FMM that needs no analytic expansions; it needs a kernel that is the Green's function of an elliptic equation.

References

  1. William Fong and Eric Darve, The black-box fast multipole method, Journal of Computational Physics 228(23), 2009, 8712-8725, the sections on Chebyshev interpolation, the black-box FMM with Chebyshev interpolation, and the fast convolution by SVD compression
  2. Lloyd N. Trefethen, Approximation Theory and Approximation Practice, SIAM, 2013, Chapter 8, Theorems 8.1 and 8.2, the decay of the Chebyshev coefficients and the accuracy of Chebyshev approximations of analytic functions
  3. Rick Beatson and Leslie Greengard, A short course on fast multipole methods, in Wavelets, Multilevel Methods and Elliptic PDEs, Oxford University Press, 1997, Section 4, the tree, the interaction list and the operation count of the FMM that the black-box method keeps

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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