Algorithm Search⌘K

Algorithmresearch

Kernel-independent fast multipole method

Also called KIFMM.

An FMM that replaces analytic expansions by equivalent densities on surfaces around each box, fitted by small solves, so it works for many kernels.

Time
Θ(N^2) worstΘ(N P^2 / s + N s + L P^3) averageΘ(N P) best
Space
Θ(N + N P / s + L P^2) extra
Where
L = the leaf level; N = the number of charges; P = the number of points on each circle; s = the mean number of charges in a leaf box
Properties
deterministic
Origin
Lexing Ying, George Biros, Denis Zorin, 2004

The kernel-independent fast multipole method (KIFMM) 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, but it never expands the kernel KK. The far field of the charges in a box is represented by an equivalent density: values at PP points on a circle (in 3D, a sphere or a cube surface) around the box, chosen so that the potential of these points matches the potential of the real charges on a larger check circle. The field of all far charges inside a box is represented in the same way, by a density on a circle outside the box that matches on a check circle inside. Every translation is then a set of kernel evaluations and a small linear solve. The kernel must be the fundamental solution of an elliptic equation, for example the Laplace, modified Laplace (Yukawa), Stokes or Navier kernels. Ying, Biros and Zorin (2004) gave the method, building on the "FMM without multipoles" of Anderson (1992).

In plain words

The plain FMM needs a formula for how the pull of a group changes with distance, and a different formula for each kind of pull. The KIFMM uses a trick that needs no formula. Put a ring of fake charges around a box. Choose their sizes so that, on a second, bigger ring, they pull exactly like the real charges. Then they pull like the real charges everywhere outside the bigger ring too, for the kinds of pull that come from a smooth physical law.

So each box keeps the sizes of its fake charges instead of a formula. Every step of the FMM becomes: compute the pull of some fake charges on a ring, then solve a small system to get new fake charges. You only need a function that gives the pull of one charge on one point.

The problem

The input is NN real 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 PP of points on each circle. 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 the Green's function of a constant coefficient elliptic equation, so that the Dirichlet problems inside and outside a circle have unique solutions, and here it must depend on x−yx - y only, so that the matrices can be computed once per level. The examples use K=log⁡∣x−y∣K = \log|x - y| and K=K0(2∣x−y∣)K = K_0(2 |x - y|), the modified Bessel function.

The algorithm

A box of half-width hh and center cc has four circles of PP equally spaced points: the upward equivalent circle (radius 1.5h1.5h) and the upward check circle (radius 2.5h2.5h) for the far field of its own charges, and the downward check circle (radius 1.5h1.5h) and the downward equivalent circle (radius 2.5h2.5h) for the field of the far charges inside it. The box fits in the radius 2 h\sqrt{2}\, h. The matrices Aup=[K(upward checki,upward equivalentj)]A_{\text{up}} = [K(\text{upward check}_i, \text{upward equivalent}_j)] and Adown=[K(downward checki,downward equivalentj)]A_{\text{down}} = [K(\text{downward check}_i, \text{downward equivalent}_j)] are inverted once per level.

  1. KIFMM(q, z, K, P, L)
  2. 1for each leaf B: φ ← potential of the charges of B at the upward check points of B; σ↑_B ← A_up⁻¹ φ
  3. 2for l ← L - 1 down to 2: for each box B at level l: φ ← potential of σ↑ of the children at the upward check points of B; σ↑_B ← A_up⁻¹ φ
  4. for l ← 2 to L do
  5. for each box T at level l do
  6. 3ψ_T ← Σ potential of σ↑_C at the downward check points of T, over C in the interaction list of T
  7. 4if l > 2 then ψ_T ← ψ_T + potential of σ↓ of the parent at the downward check points of T
  8. 5σ↓_T ← A_down⁻¹ ψ_T
  9. 6for each leaf T and charge j in T: u_j ← potential of σ↓_T at z_j
  10. 7add the direct terms of all charges i ≠ j in T and its near neighbours; return u

Lines L1 to L7 match the steps of the fast multipole method: source to upward (P2M), upward to upward (M2M), the interaction list (M2L, called VLI in the paper), downward to downward (L2L) and downward to targets (L2P). Each translation from a fixed offset is a P×PP \times P matrix of kernel values, also computed once per level and offset: 4 child offsets for each of M2M and L2L, and the 72−32=407^2 - 3^2 = 40 offsets of the interaction list.

The radii are chosen so that each fit is valid where it is used. The upward check circle of a box encloses the upward equivalent circles of its children. The downward check circle of a box in the interaction list is at least 4h−1.5h=2.5h4h - 1.5h = 2.5h from the center of the source box, so it is outside the source's upward check circle. The far charges of a box are at least 4h−2 h≈2.59h4h - \sqrt{2}\, h \approx 2.59h from its center, outside its downward equivalent circle.

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:

PP relative error, log⁡\log kernel (2-norm) largest error, log⁡\log kernel relative error, K0(2r)K_0(2r) kernel
4 3.5×10−23.5 \times 10^{-2} 1.21.2
8 2.3×10−32.3 \times 10^{-3} 8.5×10−28.5 \times 10^{-2} 3.3×10−33.3 \times 10^{-3}
12 2.2×10−42.2 \times 10^{-4} 9.1×10−39.1 \times 10^{-3}
16 2.0×10−52.0 \times 10^{-5} 6.5×10−46.5 \times 10^{-4} 2.8×10−52.8 \times 10^{-5}
24 2.3×10−72.3 \times 10^{-7} 7.4×10−67.4 \times 10^{-6} 3.3×10−73.3 \times 10^{-7}
32 3.0×10−93.0 \times 10^{-9} 1.4×10−71.4 \times 10^{-7} 4.3×10−94.3 \times 10^{-9}
40 5.0×10−115.0 \times 10^{-11} 3.0×10−93.0 \times 10^{-9}

These are measurements. The two kernels use the same code; only the function KK changes. The error falls by about a factor of 10 for every 4 more points. A density of PP real values holds about as much as an analytic expansion of P/2P / 2 complex terms, and the analytic FMM with p=12p = 12 on these points has the relative error 3.0×10−83.0 \times 10^{-8}, against 2.3×10−72.3 \times 10^{-7} here with P=24P = 24.

The fit matters. If the inverses are replaced by the regularized normal equations (ATA+λI)−1AT(A^T A + \lambda I)^{-1} A^T with λ=10−13\lambda = 10^{-13} times the mean of the diagonal, the errors for P=24P = 24, 3232 and 4040 are 2.3×10−72.3 \times 10^{-7}, 7.6×10−87.6 \times 10^{-8} and 6.0×10−66.0 \times 10^{-6}: they stop falling and then grow, because ATAA^T A squares the condition number of AA.

Correctness

The proof file is partial. It proves three things for the log⁡\log kernel. First, the tree and the lists are those of the uniform FMM, so each charge reaches each target exactly once (Lemma 1). Second, the matrix of log⁡∣xi−yj∣\log|x_i - y_j| between two concentric circles of PP equally spaced points is circulant, with the eigenvalues log⁡(R>P−R<P)\log(R_>^P - R_<^P) and −P2∑k≡±mρk/k-\frac{P}{2} \sum_{k \equiv \pm m} \rho^k / k; so the fits exist whenever R>P−R<P≠1R_>^P - R_<^P \ne 1, which holds for all radii below 1, and the condition number grows like ρ−P/2\rho^{-P/2} (Lemma 2). Third, a continuous density that matches the potential on the whole check circle matches it in the whole far region, by the uniqueness of the exterior and interior Dirichlet problems; so with exact fits every step is exact (Lemma 3). A bound on the error of the PP-point fits, which alias the Fourier modes they do not resolve, is not proved there; the convergence in PP is measured above.

Proof: The KIFMM uses each far box once, its fits are well defined for the log kernel, and exact fits give exact far fieldspartial

This file proves three parts of the correctness of the implementation on the page, for the kernel K(x,y)=log⁡∣x−y∣K(x, y) = \log|x - y| in 2D. It does not prove a bound on the error as a function of the number PP of points on each circle; that error is measured on the page. We use exact arithmetic. A box at level l≥2l \ge 2 has side w=2−lw = 2^{-l}, half-width h=w/2h = w / 2 and center cc. Its upward equivalent and downward check circles have radius 1.5h1.5 h, and its upward check and downward equivalent circles have radius 2.5h2.5 h, each with the PP points c+Rωkc + R \omega^k, ω=e2πi/P\omega = e^{2\pi \mathrm{i} / P}, k=0,…,P−1k = 0, \ldots, P - 1.

Lemma 1 (each pair once). The tree, the near neighbours and the interaction lists are those of the uniform fast multipole method. So, for a target in leaf tt, every charge is used exactly once: in the near field if its leaf is a near neighbour of tt, and otherwise through exactly one pair (cl,tl)(c_l, t_l) of ancestors with clc_l in the interaction list of tlt_l.

Proof. This is Lemma 1 of the proof of the fast multipole method, which uses only the tree and the lists. The downward check potential of tlt_l receives the M2L term of clc_l at line L3, and the D2D step at line L4 passes the downward density of each box to all its children, so the term reaches the leaf tt once. □\square

Lemma 2 (the fits are well defined). Let xi=Rxωix_i = R_x \omega^i and yj=Ryωjy_j = R_y \omega^j with Rx≠RyR_x \ne R_y, and let R>=max⁡(Rx,Ry)R_> = \max(R_x, R_y), R<=min⁡(Rx,Ry)R_< = \min(R_x, R_y) and ρ=R</R>\rho = R_< / R_>. The matrix Aij=log⁡∣xi−yj∣A_{ij} = \log|x_i - y_j| is circulant, with the eigenvalues

λ0=log⁡(R>P−R<P),λm=−P2∑k≥1,  k≡±m(modP)ρkk(1≤m≤P−1).\lambda_0 = \log\left( R_>^P - R_<^P \right), \qquad \lambda_m = -\frac{P}{2} \sum_{k \ge 1,\; k \equiv \pm m \pmod P} \frac{\rho^k}{k} \quad (1 \le m \le P - 1).

So AA is invertible if and only if R>P−R<P≠1R_>^P - R_<^P \ne 1. In the implementation R>=2.5h≤2.5/8<1R_> = 2.5 h \le 2.5 / 8 < 1, so every fit matrix A−1A^{-1} exists.

Proof. Write xi−yj=R>ζ(1−ρeiψ)x_i - y_j = R_> \zeta (1 - \rho e^{\mathrm{i} \psi}) with ∣ζ∣=1|\zeta| = 1 and ψ=±2π(i−j)/P\psi = \pm 2\pi (i - j) / P. For ρ<1\rho < 1, log⁡∣1−ρeiψ∣=−∑k≥1ρkcos⁡(kψ)/k\log|1 - \rho e^{\mathrm{i}\psi}| = -\sum_{k \ge 1} \rho^k \cos(k \psi) / k, so Aij=a(i−j) mod PA_{ij} = a_{(i - j) \bmod P} with ad=log⁡R>−∑k≥1ρkkcos⁡(2πkd/P)a_d = \log R_> - \sum_{k \ge 1} \frac{\rho^k}{k} \cos(2\pi k d / P). A circulant matrix has the eigenvectors vm=(ωmi)iv_m = (\omega^{m i})_i and the eigenvalues λm=∑dadω−md\lambda_m = \sum_d a_d \omega^{-m d}. Now ∑dω−md=P\sum_d \omega^{-md} = P if m≡0m \equiv 0 and 00 otherwise, and ∑dcos⁡(2πkd/P)ω−md=P2([k≡m]+[k≡−m])\sum_d \cos(2\pi k d / P) \omega^{-md} = \frac{P}{2} ([k \equiv m] + [k \equiv -m]). This gives λm\lambda_m for m≠0m \ne 0, a sum of positive terms with a minus sign, so λm<0\lambda_m < 0. For m=0m = 0, both brackets hold exactly for k=jPk = jP, so λ0=Plog⁡R>−P∑j≥1ρjPjP=Plog⁡R>+log⁡(1−ρP)=log⁡(R>P−R<P)\lambda_0 = P \log R_> - P \sum_{j \ge 1} \frac{\rho^{jP}}{jP} = P \log R_> + \log(1 - \rho^P) = \log(R_>^P - R_<^P). A matrix is invertible exactly when no eigenvalue is 0. Finally R>P−R<P<R>P<1R_>^P - R_<^P < R_>^P < 1. □\square

The smallest eigenvalues in absolute value are near m=P/2m = P / 2, of size about ρP/2\rho^{P/2}, so the condition number of AA grows like ρ−P/2\rho^{-P/2}. With ρ=0.6\rho = 0.6 this is about 3×1043 \times 10^4 for P=40P = 40. The normal equations ATAA^T A square it, which explains the loss of digits measured on the page.

Lemma 3 (exact fits give exact far fields). Let f(x)=∑iqilog⁡∣x−zi∣f(x) = \sum_i q_i \log|x - z_i| for charges ziz_i in a box BB with center 00, and let g(x)=∫σ(y)log⁡∣x−y∣ ds(y)g(x) = \int \sigma(y) \log|x - y| \, ds(y) be the potential of a continuous density on the circle of radius 1.5h1.5h. If g=fg = f on the whole circle of radius 2.5h2.5 h, then g=fg = f for all ∣x∣≥2.5h|x| \ge 2.5 h. In the same way, if a density on the circle of radius 2.5h2.5h matches, on the whole circle of radius 1.5h1.5 h, a potential whose charges all lie outside the radius 2.5h2.5 h, then it matches it in the whole disk of radius 1.5h1.5 h.

Proof. The charges lie within 2 h<1.5h\sqrt{2}\, h < 1.5 h of the center. For ∣x∣>1.5h|x| > 1.5 h, both ff and gg are harmonic and have expansions Alog⁡∣x∣+∑k≥1Re(bkx−k)A \log|x| + \sum_{k \ge 1} \mathrm{Re}(b_k x^{-k}) without a constant term, because log⁡∣x−y∣=log⁡∣x∣−Re∑k≥1(y/x)k/k\log|x - y| = \log|x| - \mathrm{Re} \sum_{k \ge 1} (y / x)^k / k for ∣y∣<∣x∣|y| < |x|. The difference f−gf - g has such an expansion, and it is 0 on ∣x∣=2.5h|x| = 2.5h. The constant Fourier mode on that circle is (Af−Ag)log⁡(2.5h)(A_f - A_g) \log(2.5 h), and log⁡(2.5h)≠0\log(2.5h) \ne 0, so Af=AgA_f = A_g; each mode k≥1k \ge 1 gives bkf=bkgb_k^f = b_k^g. So f=gf = g for ∣x∣>1.5h|x| > 1.5 h. For the interior statement, both potentials are harmonic in the disk of radius 2.5h2.5 h, and a harmonic function in a disk is fixed by its values on a smaller circle by the maximum principle. □\square

What remains. With exact fits, Lemma 3 shows that every step of the method is exact: the upward density of a box reproduces the field of its charges outside its upward check circle, which contains the upward equivalent circles of its children (they reach (2+1.5)hchild<1.5h(\sqrt{2} + 1.5) h_{\text{child}} < 1.5 h from the center). The downward check circle of a box in its V list is at least 4h−1.5h=2.5h4h - 1.5h = 2.5h from its center, so the M2L step gives the true far field there. The charges of the far field of a box are at least 4h−2 h>2.5h4h - \sqrt{2}\, h > 2.5h from its center, so its downward density reproduces the far field inside its downward check circle, which contains the downward check circles of its children (they reach (2+1.5)hchild<3hchild(\sqrt{2} + 1.5) h_{\text{child}} < 3 h_{\text{child}}). Then Lemma 1 gives the exact potential. The implementation matches only at PP points, so the fits are exact for the Fourier modes that the PP points resolve and alias the others. A bound on this aliasing error, which falls geometrically in PP, is not proved here.

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, so the counts of the operation count of Beatson and Greengard hold with P×PP \times P matrix-vector products in place of the p2p^2 translations: Θ(NP)\Theta(N P) for L1 and L6, Θ((N/s)P2)\Theta((N / s) P^2) for L2 to L5, and Θ(Ns)\Theta(N s) for L7.
  • Precomputation. Per level: two P×PP \times P inverses, O(P3)O(P^3), and 4848 matrices of P2P^2 kernel values. For a kernel that is homogeneous, such as 1/r1 / r, the matrices are the same at every level after scaling.
  • Faster M2L. The M2L matrices dominate. In 3D, the paper uses the FFT: on a regular grid of equivalent points, the translation is a convolution. In 2D it compresses them with the SVD.
  • Worst case. With a uniform tree, clustered charges make the near field Θ(N2)\Theta(N^2); the paper uses the adaptive tree with the lists of the adaptive FMM.
  • Space. Θ(N+NP/s)\Theta(N + N P / s) for the densities, plus the precomputed matrices.

Properties

  • Kernel independent. The code calls KK only as a function. A new kernel needs no new formulas.
  • Linear in the charges. The output is a linear function of qq, so the method works as a fast matrix-vector product in iterative solvers for boundary element equations.
  • Not every kernel. The uniqueness argument needs a kernel that solves an elliptic equation. For a smooth kernel that does not, such as a Gaussian, the fits can fail; the black-box FMM uses interpolation instead and needs only smoothness.
  • Deterministic. The result does not depend on the order of the charges, up to rounding.

Variants and improvements

  • Adaptive trees. The original method works on an adaptive tree with the UU, VV, WW and XX lists of the adaptive FMM; this page uses a uniform tree to keep the code short.
  • FFT acceleration. With equivalent points on the surface of a cube in a regular grid, the M2L operator is a discrete convolution and the fast Fourier transform applies it in O(Plog⁡P)O(P \log P) after a zero padded transform.
  • SVD compression. The M2L matrices can be compressed by a truncated singular value decomposition, as in the 2D code of the paper and in later SVD-accelerated versions.
  • Regularized fits. When the check-to-equivalent matrices are ill conditioned, a Tikhonov regularized pseudoinverse, computed from the SVD and not from the normal equations, limits the growth of rounding errors.
  • Black box versions. The black-box FMM replaces the equivalent densities by Chebyshev interpolation, which needs no uniqueness theorem.

When to use it

Use the KIFMM when you need a fast summation for a kernel that is a Green's function but whose analytic expansions you do not have or do not want to code: Stokes and elasticity kernels, the modified Laplace kernel, or kernels of a family of equations. For the Laplace and modified Laplace kernels, Ying, Biros and Zorin report that it compares very well with the best analytic FMM codes, so it is a reasonable choice there too. For kernels that are only smooth, use the black-box FMM. For small NN, use direct summation.

Pitfalls

  • Radius 1 for the log kernel. The log⁡\log kernel matrix between concentric circles is singular when R>P−R<P=1R_>^P - R_<^P = 1, and nearly singular when it is close to 1. Scale the problem so that all circles have radius well below 1, or start the tree at a level where they do.
  • Normal equations. Forming ATAA^T A squares the condition number; in the example, the error grows from 3×10−93 \times 10^{-9} to 6×10−66 \times 10^{-6} at P=40P = 40. Invert AA directly or use an SVD.
  • Equivalent and check radii. A check circle that crosses a source box, or an equivalent circle that does not enclose the charges, breaks the uniqueness argument and gives large errors without a warning.
  • Kernels that are not Green's functions. For a Gaussian kernel, matching on a circle does not determine the field outside, and the method can give poor results.
  • Too few points for the accuracy. The error falls with PP at a rate set by the ratios of the radii, and the rate on this page does not carry over to other radii, other kernels or 3D. Measure against direct summation.

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.

kernel_independent_fast_multipole_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-independent-fast-multipole-method/. The authors are listed in prov/RS9RNM.jsonl.
"""Kernel-independent fast multipole method of Ying, Biros and Zorin, 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 a kernel K that is
given as a function. The method never expands K. It only evaluates it.

Each box B of half-width h has P points on four circles about its center:

    upward equivalent  radius 1.5 h    (holds the density sigma_up)
    upward check       radius 2.5 h
    downward check     radius 1.5 h
    downward equivalent radius 2.5 h   (holds the density sigma_down)

The upward equivalent density is fitted so that its potential on the upward
check circle equals the potential of the charges of B; then it gives the
far field of B. The downward equivalent density is fitted so that its
potential on the downward check circle equals the potential of all far
charges; then it gives the far field inside B. Each fit is a small linear
solve; the P by P matrices are inverted once per level.

The kernel must be the fundamental solution of an elliptic equation for the
fits to be unique (here the default is log|x - y|), and it must depend on
x - y only, because the matrices are computed once per level and offset.
For the log kernel the circles must not have radius 1; the tree starts at
level 2, where every radius is at most 2.5 / 8.
"""

import math
from typing import Callable, Optional, Sequence

from scimat import inv, matmul, matvec, transpose

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


def log_kernel(x: complex, y: complex) -> float:
    """K(x, y) = log|x - y|, the 2D Laplace kernel."""
    return math.log(abs(x - y))


def circle(center: complex, radius: float, n: int) -> list[complex]:
    return [center + radius * complex(math.cos(2 * math.pi * k / n), math.sin(2 * math.pi * k / n)) for k in range(n)]


def kernel_matrix(kernel: Kernel, xs: Sequence[complex], ys: Sequence[complex]) -> list[list[float]]:
    """Matrix [K(x_i, y_j)]."""
    return [[kernel(x, y) for y in ys] for x in xs]


def fit_matrix(a: list[list[float]], alpha: float = 0.0) -> list[list[float]]:
    """The matrix that maps check potentials to an equivalent density.

    With alpha = 0 it is the inverse of the square matrix a. With alpha > 0
    it is the regularized pseudoinverse (A^T A + lambda I)^-1 A^T, with
    lambda = alpha times the mean of diag(A^T A); these normal equations
    square the condition number of A and lose digits for many points.
    """
    if alpha == 0.0:
        return inv(a)
    at = transpose(a)
    g = matmul(at, a)
    lam = alpha * sum(g[i][i] for i in range(len(g))) / len(g)
    for i in range(len(g)):
        g[i][i] += lam
    return matmul(inv(g), at)


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 (the V list)."""
    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


class Operators:
    """The matrices of one level, for boxes of side w = 2^-level, centered at 0."""

    def __init__(self, kernel: Kernel, level: int, n: int, alpha: float = 0.0):
        w = 1.0 / (1 << level)
        h = w / 2
        self.ue = circle(0j, 1.5 * h, n)
        self.uc = circle(0j, 2.5 * h, n)
        self.dc = circle(0j, 1.5 * h, n)
        self.de = circle(0j, 2.5 * h, n)
        self.uc2ue = fit_matrix(kernel_matrix(kernel, self.uc, self.ue), alpha)
        self.dc2de = fit_matrix(kernel_matrix(kernel, self.dc, self.de), alpha)
        self.m2l = {}
        for dx in range(-3, 4):
            for dy in range(-3, 4):
                if max(abs(dx), abs(dy)) > 1:
                    off = complex(dx * w, dy * w)
                    self.m2l[(dx, dy)] = kernel_matrix(kernel, self.dc, [y + off for y in self.ue])
        self.w = w


def child_matrices(kernel: Kernel, parent: Operators, child: Operators):
    """K from the child upward equivalent points to the parent upward check points,
    and K from the parent downward equivalent points to the child downward check points,
    for the four child positions."""
    up, down = {}, {}
    for a in (0, 1):
        for b in (0, 1):
            off = complex((a - 0.5) * child.w, (b - 0.5) * child.w)
            up[(a, b)] = kernel_matrix(kernel, parent.uc, [y + off for y in child.ue])
            down[(a, b)] = kernel_matrix(kernel, [x + off for x in child.dc], parent.de)
    return up, down


def _addv(acc: list[float], v: Sequence[float]) -> None:
    for k in range(len(acc)):
        acc[k] += v[k]


def kifmm(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel, n_points: int = 16,
          levels: Optional[int] = None, s: int = 8, alpha: float = 0.0):
    """Potentials u_j = sum_{i != j} q_i K(z_j, z_i), with n_points points on each circle.

    levels is the leaf level L (at least 2); alpha is passed to fit_matrix.
    Returns (u, stats), where stats counts the ordered pairs of the near
    field ("p2p") and the M2L products of the V lists ("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
    ops = {l: Operators(kernel, l, n_points, alpha) for l in range(2, L + 1)}
    kids = {l: child_matrices(kernel, ops[l], ops[l + 1]) for l in range(2, L)}
    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)
    up: list[dict] = [dict() for _ in range(L + 1)]
    for key, idx in leaf.items():  # @line L1
        c = box_center(*key, L)
        check = [sum(q[i] * kernel(x + c, z[i]) for i in idx) for x in ops[L].uc]
        up[L][key] = matvec(ops[L].uc2ue, check)
    for l in range(L - 1, 1, -1):  # @line L2
        checks: dict = {}
        for (cx, cy), sig in up[l + 1].items():
            key = (cx // 2, cy // 2)
            acc = checks.setdefault(key, [0.0] * n_points)
            _addv(acc, matvec(kids[l][0][(cx % 2, cy % 2)], sig))
        for key, check in checks.items():
            up[l][key] = matvec(ops[l].uc2ue, check)
    down: list[dict] = [dict() for _ in range(L + 1)]
    n_m2l = 0
    for l in range(2, L + 1):
        mm = 1 << l
        checks = {}
        for tx in range(mm):
            for ty in range(mm):
                if l == L and (tx, ty) not in leaf:
                    continue
                acc = [0.0] * n_points
                used = False
                for src in interaction_list(tx, ty, l):  # @line L3
                    sig = up[l].get(src)
                    if sig is not None:
                        _addv(acc, matvec(ops[l].m2l[(src[0] - tx, src[1] - ty)], sig))
                        n_m2l += 1
                        used = True
                if l > 2:
                    par = down[l - 1].get((tx // 2, ty // 2))
                    if par is not None:  # @line L4
                        _addv(acc, matvec(kids[l - 1][1][(tx % 2, ty % 2)], par))
                        used = True
                if used:
                    checks[(tx, ty)] = acc
        for key, check in checks.items():  # @line L5
            down[l][key] = matvec(ops[l].dc2de, check)
    u = [0.0] * n
    n_p2p = 0
    for key, idx in leaf.items():
        c = box_center(*key, L)
        sig = down[L].get(key)
        if sig is not None:
            de = [y + c for y in ops[L].de]
            for j in idx:  # @line L6
                u[j] += sum(sk * kernel(z[j], y) for sk, y in zip(sig, de))
        ix, iy = key
        for nx in range(ix - 1, ix + 2):  # @line L7
            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}


def direct(q: Sequence[float], z: Sequence[complex], kernel: Kernel = log_kernel) -> list[float]:
    """Direct summation over all ordered pairs: the reference."""
    n = len(z)
    return [sum(q[i] * kernel(z[j], z[i]) for i in range(n) if i != j) for j in range(n)]
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_kernel_independent_fast_multipole_method.py 144 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-independent-fast-multipole-method/. The authors are listed in prov/RS9RNM.jsonl.
"""Tests for the kernel-independent FMM: the equivalent densities, two kernels and the accuracy against direct summation."""

import math
import random
import unittest

from kernel_independent_fast_multipole_method import (
    Operators,
    circle,
    direct,
    fit_matrix,
    kernel_matrix,
    kifmm,
    log_kernel,
)
from scimat import matmul, matvec

EULER_GAMMA = 0.5772156649015329


def bessel_k0(x):
    """Modified Bessel function K_0 by its power series (accurate for 0 < x <= 3)."""
    t = x * x / 4
    term = 1.0
    i0 = 1.0
    s = 0.0
    h = 0.0
    for k in range(1, 30):
        term *= t / (k * k)
        h += 1.0 / k
        i0 += term
        s += term * h
    return -(math.log(x / 2) + EULER_GAMMA) * i0 + s


def yukawa(x, y):
    """K_0(2 |x - y|), the fundamental solution of Laplace minus 4 (up to a constant)."""
    return bessel_k0(2.0 * abs(x - y))


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 TestEquivalentDensity(unittest.TestCase):
    def test_bessel_k0_values(self):
        self.assertAlmostEqual(bessel_k0(1.0), 0.4210244382, places=9)
        self.assertAlmostEqual(bessel_k0(2.5), 0.0623475532, places=9)

    def test_fit_matrix_is_an_inverse(self):
        op = Operators(log_kernel, 3, 12)
        a = kernel_matrix(log_kernel, op.uc, op.ue)
        prod = matmul(a, op.uc2ue)
        for i in range(12):
            for j in range(12):
                self.assertAlmostEqual(prod[i][j], 1.0 if i == j else 0.0, places=8)
        approx = fit_matrix(a, 1e-14)
        self.assertLess(max(abs(x - y) for ra, rb in zip(approx, op.uc2ue) for x, y in zip(ra, rb)), 1e-3 * max(abs(x) for r in op.uc2ue for x in r))

    def test_upward_density_reproduces_the_far_field(self):
        rng = random.Random(2)
        c = complex(0.5625, 0.4375)
        w = 0.125
        src = [c + complex((rng.random() - 0.5) * w, (rng.random() - 0.5) * w) for _ in range(10)]
        q = [rng.uniform(-1, 1) for _ in range(10)]
        targets = [c + complex(2 * w, 0.3 * w), c + complex(-1.5 * w, 2.5 * w), c + complex(3 * w, -3 * w)]
        errs = []
        for n in (8, 16, 32):
            op = Operators(log_kernel, 3, n)
            check = [sum(qi * log_kernel(x + c, zi) for qi, zi in zip(q, src)) for x in op.uc]
            sig = matvec(op.uc2ue, check)
            err = 0.0
            for t in targets:
                exact = sum(qi * log_kernel(t, zi) for qi, zi in zip(q, src))
                approx = sum(sk * log_kernel(t, y + c) for sk, y in zip(sig, op.ue))
                err = max(err, abs(exact - approx))
            errs.append(err)
        self.assertLess(errs[1], errs[0] / 10)
        self.assertLess(errs[2], errs[1] / 10)
        self.assertLess(errs[2], 1e-8)

    def test_circle(self):
        pts = circle(1 + 1j, 0.5, 8)
        for p in pts:
            self.assertAlmostEqual(abs(p - (1 + 1j)), 0.5, places=12)


class TestKIFMM(unittest.TestCase):
    def test_log_kernel_matches_direct(self):
        q, z = uniform(400, 5)
        ud = direct(q, z)
        errs = []
        for n in (8, 16, 24, 32):
            u, st = kifmm(q, z, n_points=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-8)
        self.assertEqual(st["m2l"], 1272)

    def test_yukawa_kernel_matches_direct(self):
        q, z = uniform(250, 6)
        ud = direct(q, z, yukawa)
        u, st = kifmm(q, z, kernel=yukawa, n_points=24, levels=3)
        self.assertLess(rel(u, ud), 1e-6)

    def test_other_leaf_levels(self):
        q, z = uniform(300, 7)
        ud = direct(q, z)
        for levels in (2, 4):
            u, st = kifmm(q, z, n_points=24, levels=levels)
            self.assertLess(rel(u, ud), 1e-6)

    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, _ = kifmm(q, z, n_points=12, levels=3)
        u2, _ = kifmm(r, z, n_points=12, levels=3)
        u3, _ = kifmm([a + 3 * b for a, b in zip(q, r)], z, n_points=12, levels=3)
        for a, b, c in zip(u1, u2, u3):
            self.assertAlmostEqual(c, a + 3 * b, places=9)

    def test_small_inputs(self):
        self.assertEqual(kifmm([], [])[0], [])
        self.assertEqual(kifmm([1.0], [complex(0.2, 0.7)])[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, _ = kifmm(q, z, n_points=24)
        for a, b in zip(u, direct(q, z)):
            self.assertAlmostEqual(a, b, places=6)


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

History

Anderson (1992) represented the multipole and local expansions of the 2D and 3D Laplace kernel by potential values on circles and spheres, through the Poisson formula, an "FMM without multipoles". Ying, Biros and Zorin (2004) turned the idea into a method for general elliptic kernels: equivalent densities fitted on check surfaces by local Dirichlet problems, inside the adaptive FMM, with the SVD in 2D and the FFT in 3D for the far field translations. They tested it on the Laplace, modified Laplace, Stokes, modified Stokes, Navier and modified Navier kernels. Fong and Darve (2009) gave the black-box FMM, based on Chebyshev interpolation, which needs only a smooth kernel.

References

  1. 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 equivalent and check surfaces, the three translations as local Dirichlet problems, and the use of the SVD in 2D and the FFT in 3D for the far field translations
  2. Christopher R. Anderson, An implementation of the fast multipole method without multipoles, SIAM Journal on Scientific and Statistical Computing 13(4), 1992, 923-947, the representation of the expansions by potential values on a circle or sphere through the Poisson formula
  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 kernel-independent 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 correctness
  • 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