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
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Lexing Ying, George Biros, Denis Zorin, 2004
The kernel-independent fast multipole method (KIFMM) computes sums with the tree and the lists of the fast multipole method, but it never expands the kernel . The far field of the charges in a box is represented by an equivalent density: values at 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 real charges at points of the unit square, a kernel given as a function, and a number of points on each circle. The output is an approximation of each potential
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 only, so that the matrices can be computed once per level. The examples use and , the modified Bessel function.
The algorithm
A box of half-width and center has four circles of equally spaced points: the upward equivalent circle (radius ) and the upward check circle (radius ) for the far field of its own charges, and the downward check circle (radius ) and the downward equivalent circle (radius ) for the field of the far charges inside it. The box fits in the radius . The matrices and are inverted once per level.
KIFMM(q, z, K, P, L)- 1
for each leaf B: φ ← potential of the charges of B at the upward check points of B; σ↑_B ← A_up⁻¹ φ - 2
for 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⁻¹ φ for l ← 2 to L dofor each box T at level l do- 3
ψ_T ← Σ potential of σ↑_C at the downward check points of T, over C in the interaction list of T - 4
if l > 2 then ψ_T ← ψ_T + potential of σ↓ of the parent at the downward check points of T - 5
σ↓_T ← A_down⁻¹ ψ_T - 6
for each leaf T and charge j in T: u_j ← potential of σ↓_T at z_j - 7
add 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 matrix of kernel values, also computed once per level and offset: 4 child offsets for each of M2M and L2L, and the 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 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 from its center, outside its downward equivalent circle.
Example
Take uniform points in the unit square with charges uniform in (seed 5), and leaves at level . 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:
| relative error, kernel (2-norm) | largest error, kernel | relative error, kernel | |
|---|---|---|---|
| 4 | |||
| 8 | |||
| 12 | |||
| 16 | |||
| 24 | |||
| 32 | |||
| 40 |
These are measurements. The two kernels use the same code; only the function changes. The error falls by about a factor of 10 for every 4 more points. A density of real values holds about as much as an analytic expansion of complex terms, and the analytic FMM with on these points has the relative error , against here with .
The fit matters. If the inverses are replaced by the regularized normal equations with times the mean of the diagonal, the errors for , and are , and : they stop falling and then grow, because squares the condition number of .
Correctness
The proof file is partial. It proves three things for the 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 between two concentric circles of equally spaced points is circulant, with the eigenvalues and ; so the fits exist whenever , which holds for all radii below 1, and the condition number grows like (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 -point fits, which alias the Fourier modes they do not resolve, is not proved there; the convergence in 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 in 2D. It does not prove a bound on the error as a function of the number of points on each circle; that error is measured on the page. We use exact arithmetic. A box at level has side , half-width and center . Its upward equivalent and downward check circles have radius , and its upward check and downward equivalent circles have radius , each with the points , , .
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 , every charge is used exactly once: in the near field if its leaf is a near neighbour of , and otherwise through exactly one pair of ancestors with in the interaction list of .
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 receives the M2L term of 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 once.
Lemma 2 (the fits are well defined). Let and with , and let , and . The matrix is circulant, with the eigenvalues
So is invertible if and only if . In the implementation , so every fit matrix exists.
Proof. Write with and . For , , so with . A circulant matrix has the eigenvectors and the eigenvalues . Now if and otherwise, and . This gives for , a sum of positive terms with a minus sign, so . For , both brackets hold exactly for , so . A matrix is invertible exactly when no eigenvalue is 0. Finally .
The smallest eigenvalues in absolute value are near , of size about , so the condition number of grows like . With this is about for . The normal equations square it, which explains the loss of digits measured on the page.
Lemma 3 (exact fits give exact far fields). Let for charges in a box with center , and let be the potential of a continuous density on the circle of radius . If on the whole circle of radius , then for all . In the same way, if a density on the circle of radius matches, on the whole circle of radius , a potential whose charges all lie outside the radius , then it matches it in the whole disk of radius .
Proof. The charges lie within of the center. For , both and are harmonic and have expansions without a constant term, because for . The difference has such an expansion, and it is 0 on . The constant Fourier mode on that circle is , and , so ; each mode gives . So for . For the interior statement, both potentials are harmonic in the disk of radius , and a harmonic function in a disk is fixed by its values on a smaller circle by the maximum principle.
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 from the center). The downward check circle of a box in its V list is at least 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 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 ). Then Lemma 1 gives the exact potential. The implementation matches only at points, so the fits are exact for the Fourier modes that the points resolve and alias the others. A bound on this aliasing error, which falls geometrically in , 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 matrix-vector products in place of the translations: for L1 and L6, for L2 to L5, and for L7.
- Precomputation. Per level: two inverses, , and matrices of kernel values. For a kernel that is homogeneous, such as , 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 ; the paper uses the adaptive tree with the lists of the adaptive FMM.
- Space. for the densities, plus the precomputed matrices.
Properties
- Kernel independent. The code calls only as a function. A new kernel needs no new formulas.
- Linear in the charges. The output is a linear function of , 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 , , and 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 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 , use direct summation.
Pitfalls
- Radius 1 for the log kernel. The kernel matrix between concentric circles is singular when , 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 squares the condition number; in the example, the error grows from to at . Invert 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 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RS9RNM Edit this page History Report an error Markdown