Algorithm Search⌘K

Algorithmadvanced

Particle-particle particle-mesh method

Also called P3M.

Splits the force into a short-range part summed directly over near neighbors and a smooth long-range part computed on a mesh by FFT.

Time
Θ(N^2) worstΘ(N P^2 + M^2 log M + N^2 r^2) averageΘ(N P^2 + M^2 log M) best
Space
Θ(N + M^2) extra
Where
M = the number of mesh points per side; N = the number of particles; P = the order of the charge assignment; r = the cutoff radius of the short-range part in units of the box
Properties
deterministic
Origin
Roger W. Hockney, James W. Eastwood, 1981

The particle-particle particle-mesh method (P3M) computes the forces of NN particles that interact by a long-range law, such as gravity or the Coulomb force, in a periodic box. It splits each pair force into a short-range part, which falls off fast and is summed directly over the pairs closer than a cutoff rcr_c, and a smooth long-range part, which is computed for all particles at once on a mesh with the fast Fourier transform. The mesh part assigns the charges to the mesh, solves the Poisson equation in Fourier space with an influence function G(k)G(k), and interpolates the field back. Hockney and Eastwood chose GG to minimize the force error of the mesh, which makes P3M the most accurate of the mesh versions of Ewald summation. With a fixed number of neighbours per particle, the work is O(N+M2log⁡M)O(N + M^2 \log M) for M2M^2 mesh points, instead of O(N2)O(N^2).

In plain words

Every particle pulls on every other one. Near pulls change quickly with the distance; far pulls change slowly.

So cut each pull into two pieces. The near piece is strong only at short range, and you add it up pair by pair, but only for close pairs. The far piece is smooth, so you can blur the particles onto a regular grid, find the pull of the blurred grid with a fast wave method, and read the pull at each particle back from the grid.

The grid makes small errors, mostly where particles sit between grid points. P3M picks the grid formula that makes these errors as small as possible on average. A finer grid, or a smoother blur, gives smaller errors.

The problem

The input is NN charges qiq_i at positions xix_i in the periodic unit square, a mesh size MM (a power of 2), an assignment order PP, a splitting parameter α\alpha and a cutoff rc<12r_c < \frac12. The output is an approximation of the force on each charge,

Fi=∑j∑n∈Z2′ qiqjxi−xj+n∣xi−xj+n∣2,F_i = \sum_j \sum_{n \in \mathbb{Z}^2}{}' \, q_i q_j \frac{x_i - x_j + n}{|x_i - x_j + n|^2},

the force of the 2D Coulomb potential −qiqjlog⁡r-q_i q_j \log r over all periodic images, defined by Ewald summation; the prime omits j=ij = i, n=0n = 0. For gravity, replace qiqjq_i q_j by −mimj-m_i m_j, up to the constant.

The algorithm

The pair force 1/r1/r is split as

1r=e−α2r2r⏟short range+1−e−α2r2r⏟long range.\frac{1}{r} = \underbrace{\frac{e^{-\alpha^2 r^2}}{r}}_{\text{short range}} + \underbrace{\frac{1 - e^{-\alpha^2 r^2}}{r}}_{\text{long range}}.

The long-range part is the force between Gaussian clouds of width 1/α1/\alpha, and its potential has the Fourier coefficients ϕ^(k)=2πk2e−k2/(4α2)\hat\phi(k) = \frac{2\pi}{k^2} e^{-k^2/(4\alpha^2)}. The mesh has M×MM \times M points of spacing h=1/Mh = 1/M. The assignment function WW is CIC (cloud in cell, P=2P = 2) or TSC (triangular shaped cloud, P=3P = 3); its Fourier transform is U^(k)=∏csinc(kch/2)P\hat U(k) = \prod_c \mathrm{sinc}(k_c h / 2)^P. The optimal influence function is

G(k)=∑mU^2(km) (k⋅km) ϕ^(km)∣k∣2(∑mU^2(km))2,km=k+2πmh,G(k) = \frac{\sum_m \hat U^2(k_m) \, (k \cdot k_m) \, \hat\phi(k_m)}{|k|^2 \big( \sum_m \hat U^2(k_m) \big)^2}, \qquad k_m = k + \frac{2\pi m}{h},

where the sums over the alias vectors mm run over ∣mc∣≤2|m_c| \le 2.

  1. P3M(q, x, M, P, α, r_c)
  2. 1Q_g ← Σ_i q_i W(x_i - x_g) for each mesh point g (charge assignment)
  3. 2ρ̂ ← FFT(Q)
  4. 3Ê(k) ← -i k G(k) ρ̂(k) for each k, with k_c = 0 at the Nyquist index
  5. 4E ← inverse FFT(Ê), one transform for each component
  6. 5F_i ← q_i Σ_g W(x_i - x_g) E_g for each particle (interpolation)
  7. 6for each pair i ≠ j with minimum image distance r < r_c: F_i ← F_i + q_i q_j e^{-α²r²} (x_i - x_j) / r²
  8. 7return F

Lines L1 to L5 are a particle-mesh solver with the smooth kernel and the optimal GG. Line L6 finds the close pairs with a chaining mesh, the cell list of Hockney and Eastwood: cells of side at least rcr_c, so that each close pair lies in the same or in adjacent cells. The GG table depends only on MM, PP and α\alpha, and is computed once.

Example

Take N=200N = 200 charges, alternately +1+1 and −1-1, uniform in the unit square (seed 21), with α=12\alpha = 12 and rc=0.25r_c = 0.25. The short-range sum uses 7632 ordered pairs. The reference is an Ewald sum with α=8\alpha = 8, 3 by 3 images and all wave vectors with ∣nc∣≤14|n_c| \le 14; with α=6\alpha = 6 it agrees to 2×10−152 \times 10^{-15}. The relative error of the forces in the 2-norm is:

mesh assignment plain G=ϕ^G = \hat\phi deconvolved G=ϕ^/U^2G = \hat\phi / \hat U^2 optimal GG
16×1616 \times 16 CIC 4.7×10−24.7 \times 10^{-2} 1.8×10−21.8 \times 10^{-2} 1.7×10−21.7 \times 10^{-2}
16×1616 \times 16 TSC 6.5×10−26.5 \times 10^{-2} 5.6×10−35.6 \times 10^{-3} 5.5×10−35.5 \times 10^{-3}
32×3232 \times 32 CIC 1.3×10−21.3 \times 10^{-2} 3.9×10−33.9 \times 10^{-3} 3.9×10−33.9 \times 10^{-3}
32×3232 \times 32 TSC 1.9×10−21.9 \times 10^{-2} 4.4×10−44.4 \times 10^{-4} 4.4×10−44.4 \times 10^{-4}
64×6464 \times 64 CIC 3.4×10−33.4 \times 10^{-3} 8.8×10−48.8 \times 10^{-4} 8.8×10−48.8 \times 10^{-4}
64×6464 \times 64 TSC 5.0×10−35.0 \times 10^{-3} 4.6×10−54.6 \times 10^{-5} 4.6×10−54.6 \times 10^{-5}

These are measurements. Without correction for the blur of the assignment, the mesh force is too weak at short wavelengths, and the error is 3 to 100 times larger. Here the long-range kernel is smooth on the mesh, so the plain deconvolution is already close to optimal. The optimal GG gains more when the kernel is rough on the mesh: with M=16M = 16, α=24\alpha = 24 and CIC, the errors are 9.3×10−29.3 \times 10^{-2} deconvolved and 8.2×10−28.2 \times 10^{-2} optimal.

The parameter α\alpha moves work between the two parts. On the 32×3232 \times 32 mesh with CIC and αrc=3\alpha r_c = 3:

α\alpha rcr_c short-range pairs relative error
8 0.375 17418 1.7×10−31.7 \times 10^{-3}
10 0.3 11118 2.6×10−32.6 \times 10^{-3}
12 0.25 7632 3.9×10−33.9 \times 10^{-3}
16 0.1875 4402 6.9×10−36.9 \times 10^{-3}
20 0.15 2840 1.1×10−21.1 \times 10^{-2}

The sum of all P3M forces is 2.5×10−132.5 \times 10^{-13}, against a typical force of about 99.

Correctness

The proof file is partial. It proves that the split is exact and that the long-range part has the Fourier coefficients ϕ^(k)S(k)\hat\phi(k) S(k) (Lemma 1). It proves that the chaining mesh adds the short-range term of every pair closer than rcr_c once and of no other pair, and that the omitted short-range force is O(e−α2rc2)O(e^{-\alpha^2 r_c^2}) (Lemma 2). It proves that, for any real even GG and the same weights for assignment and interpolation, the mesh forces add up to zero, so the total momentum is conserved and a lone particle feels no force from itself (Lemma 3). It does not prove that the mesh force converges to the long-range force, nor that Hockney and Eastwood's GG minimizes the mean square force error; it states the formula and leaves the accuracy to the measurements above and to the error estimate of Deserno and Holm.

Proof: The P3M split is exact, the short-range sum finds every close pair, and the mesh force conserves total momentumpartial

We use exact arithmetic. The charges are in the periodic unit square, the mesh has M×MM \times M points xg=g/Mx_g = g / M with MM even, h=1/Mh = 1 / M, and rc<12r_c < \frac12. The exact force on charge ii is Fi=∑j∑n∈Z2′qiqjxi−xj+n∣xi−xj+n∣2F_i = \sum_j \sum_{n \in \mathbb{Z}^2}' q_i q_j \frac{x_i - x_j + n}{|x_i - x_j + n|^2}, where the prime omits j=ij = i, n=0n = 0; it is the force of the potential −qiqjlog⁡r-q_i q_j \log r over all images, defined as the limit of the Ewald sums.

Lemma 1 (the split). For every r>0r > 0, 1r=e−α2r2r+1−e−α2r2r\frac{1}{r} = \frac{e^{-\alpha^2 r^2}}{r} + \frac{1 - e^{-\alpha^2 r^2}}{r}, and the second term is the field, at distance rr, of a unit charge spread with the density α2πe−α2∣x∣2\frac{\alpha^2}{\pi} e^{-\alpha^2 |x|^2}. In the periodic square, the potential of these Gaussian clouds has the Fourier coefficients 2πk2e−k2/(4α2)S(k)\frac{2\pi}{k^2} e^{-k^2 / (4\alpha^2)} S(k), k∈2πZ2∖{0}k \in 2\pi \mathbb{Z}^2 \setminus \{0\}, with S(k)=∑jqje−ik⋅xjS(k) = \sum_j q_j e^{-i k \cdot x_j}.

Proof. The identity is algebra. The density has total charge ∫0∞α2πe−α2ρ22πρ dρ=1\int_0^\infty \frac{\alpha^2}{\pi} e^{-\alpha^2 \rho^2} 2\pi\rho \, d\rho = 1, and the charge inside the radius rr is 1−e−α2r21 - e^{-\alpha^2 r^2}. In 2D, Gauss's law for the potential −log⁡r-\log r gives the radial field (charge inside) /r/ r. The potential solves −∇2ϕ=2πρ-\nabla^2 \phi = 2\pi \rho, and the Fourier transform of the density is e−k2/(4α2)e^{-k^2 / (4\alpha^2)}; dividing by k2k^2 gives the coefficients. The mode k=0k = 0 adds a constant to the potential and no force. □\square

So Fi=Fishort+FilongF_i = F_i^{\text{short}} + F_i^{\text{long}}, where FishortF_i^{\text{short}} is the sum of qiqje−α2r2(xi−xj+n)/r2q_i q_j e^{-\alpha^2 r^2} (x_i - x_j + n) / r^2 over all images, which converges absolutely, and Filong=qi∑k≠02πk2e−k2/(4α2) k Im(S(k)eik⋅xi)F_i^{\text{long}} = q_i \sum_{k \ne 0} \frac{2\pi}{k^2} e^{-k^2/(4\alpha^2)} \, k \, \mathrm{Im}\big(S(k) e^{i k \cdot x_i}\big), which converges absolutely too. This is the Ewald sum that the reference function computes.

Lemma 2 (the short-range sum). Line L6 adds the short-range term of every ordered pair (i,j)(i, j), i≠ji \ne j, whose minimum image distance is below rcr_c, exactly once, and of no other pair. The omitted short-range force on charge ii is at most ∑j∣qiqj∣ e−α2rc2/rc\sum_{j} |q_i q_j| \, e^{-\alpha^2 r_c^2} / r_c times a factor that tends to 1, and in particular it is O(e−α2rc2)O(e^{-\alpha^2 r_c^2}).

Proof. The chaining mesh has nc=⌊1/rc⌋n_c = \lfloor 1 / r_c \rfloor cells per side, of side 1/nc≥rc1 / n_c \ge r_c. If nc≥3n_c \ge 3, two charges closer than rcr_c in the minimum image lie in the same or in adjacent cells (modulo the period), and the 9 offsets visit each adjacent cell once, because nc≥3n_c \ge 3 makes them distinct. If nc≤2n_c \le 2, all pairs of cells are visited once. Since rc<12r_c < \frac12, an image closer than rcr_c is the minimum image, and it is unique. The test r2<rc2r^2 < r_c^2 then keeps exactly the pairs claimed. For the omitted part, every omitted image is at distance at least rcr_c, and the sum of e−α2r2/re^{-\alpha^2 r^2} / r over the images of a pair at distances r≥rcr \ge r_c is e−α2rc2/rce^{-\alpha^2 r_c^2} / r_c times a factor bounded by a sum of Gaussian tails over the lattice, which tends to 1 as αrc\alpha r_c grows. □\square

Lemma 3 (total momentum). For any influence function with G(−k)=G(k)G(-k) = G(k) real, if the same weights WW are used for the assignment (line L1) and for the interpolation (line L5), and the derivative is set to 0 at the Nyquist index, then the mesh forces satisfy ∑iFimesh=0\sum_i F_i^{\text{mesh}} = 0. In particular, a single charge feels no mesh force from itself.

Proof. Let Qg=∑iqiW(xi−xg)Q_g = \sum_i q_i W(x_i - x_g) be the mesh charge, ρ^(k)=∑gQge−ik⋅xg\hat\rho(k) = \sum_g Q_g e^{-i k \cdot x_g}, and Eg=∑k(−ik~)G(k)ρ^(k)eik⋅xgE_g = \sum_k (-i \tilde k) G(k) \hat\rho(k) e^{i k \cdot x_g}, where k~\tilde k is kk with the Nyquist components set to 0. Then

∑iFimesh=∑iqi∑gW(xi−xg)Eg=∑gQgEg=∑k(−ik~)G(k)ρ^(k)ρ^(k)‾,\sum_i F_i^{\text{mesh}} = \sum_i q_i \sum_g W(x_i - x_g) E_g = \sum_g Q_g E_g = \sum_k (-i \tilde k) G(k) \hat\rho(k) \overline{\hat\rho(k)},

because QgQ_g is real, so ∑gQgeik⋅xg=ρ^(k)‾\sum_g Q_g e^{i k \cdot x_g} = \overline{\hat\rho(k)}. The map k↦−kk \mapsto -k on the FFT indices fixes exactly the indices whose components are 0 or Nyquist, where k~\tilde k has the corresponding component 0, and it pairs the other indices. Along each pair, GG and ∣ρ^∣2|\hat\rho|^2 are equal and k~\tilde k changes sign, so the terms cancel, and every fixed index contributes a zero vector component. □\square

The short-range forces satisfy Newton's third law pair by pair, so the total P3M force is zero, as the test checks to rounding.

What is not proved here. The mesh force is an approximation of FilongF_i^{\text{long}} with an error from the charge assignment and from aliasing. Hockney and Eastwood derive the optimal influence function

G(k)=∑mU^2(km) (k⋅km) ϕ^(km)∣k∣2(∑mU^2(km))2,km=k+2πmh,G(k) = \frac{\sum_m \hat U^2(k_m) \, (k \cdot k_m) \, \hat\phi(k_m)}{|k|^2 \big(\sum_m \hat U^2(k_m)\big)^2}, \qquad k_m = k + \frac{2\pi m}{h},

with ϕ^(k)=2πk2e−k2/(4α2)\hat\phi(k) = \frac{2\pi}{k^2} e^{-k^2/(4\alpha^2)} and the assignment function U^(k)=∏csinc(kch/2)P\hat U(k) = \prod_c \mathrm{sinc}(k_c h / 2)^P (P=2P = 2 for CIC, P=3P = 3 for TSC), as the minimizer of the mean square force error, averaged over the positions of the charges, for this assignment and ik differentiation. We do not prove this, nor a rate of convergence of the mesh force as h→0h \to 0; the code sums the aliases with ∣mc∣≤2|m_c| \le 2, and the errors against the Ewald sum are measured on the page.

Complexity

The model is the real RAM.

  • Mesh part (theorem). Lines L1 and L5 cost Θ(P2)\Theta(P^2) per particle in 2D (P3P^3 in 3D). Line L2 is one FFT and line L4 two, Θ(M2log⁡M)\Theta(M^2 \log M) each. Line L3 is Θ(M2)\Theta(M^2), and so is the GG table, up to the alias sums.
  • Short-range part. Line L6 costs Θ(N)\Theta(N) to fill the chaining mesh plus the number of pairs examined. For a uniform distribution, each particle has about πrc2N\pi r_c^2 N neighbours, so the part costs Θ(N2rc2)\Theta(N^2 r_c^2). P3M keeps rc2Nr_c^2 N bounded by choosing α\alpha and the mesh with NN, which gives O(N+M2log⁡M)O(N + M^2 \log M) with M2M^2 proportional to NN.
  • Worst case. If the particles cluster, many pairs fall inside rcr_c and line L6 costs up to Θ(N2)\Theta(N^2). This is the weakness that the TreePM method and adaptive P3M address.
  • Space. Θ(N+M2)\Theta(N + M^2).

Properties

  • Exact split. The two parts add up to the exact force law; all the error comes from the mesh and from the cutoff.
  • Momentum. With ik differentiation and the same assignment and interpolation, the total mesh force is zero, and the short-range part obeys Newton's third law. Single pair forces of the mesh are not exactly antisymmetric, and they depend slightly on the positions relative to the mesh.
  • Periodic. The FFT makes the result periodic, so P3M suits periodic systems: plasmas, molecular dynamics and cosmological boxes. For open boundaries, the mesh must be doubled in each direction and padded with zeros.
  • Tunable. MM, PP, α\alpha and rcr_c trade accuracy against time, and the error estimate of Deserno and Holm predicts the force error before the run.
  • Deterministic. The result does not depend on the order of the particles, up to rounding.

Variants and improvements

  • Particle mesh Ewald. The particle mesh Ewald method of molecular dynamics uses Lagrange interpolation, and smooth particle mesh Ewald uses B-splines. Deserno and Holm found that P3M with the optimal influence function is the most accurate of these for a given mesh and order.
  • Finite difference gradients. Instead of ik differentiation (three or two inverse FFTs), the field can be taken from the mesh potential by finite differences, with one inverse FFT; the optimal GG changes accordingly.
  • Interlacing. Averaging the results of two meshes shifted by half a mesh cell cancels the main alias errors.
  • Adaptive P3M. Refined meshes over dense regions, as in the adaptive P3M codes of cosmology, keep the number of close pairs small when particles cluster.
  • Tree for the short range. Replacing the direct sum of line L6 by a Barnes-Hut tree gives the TreePM method.

When to use it

Use P3M for periodic systems with many particles and a long-range force, when the particles are spread fairly evenly: plasma simulation, molecular dynamics with charges, and cosmological simulations at early times. For strongly clustered particles, use TreePM or a fast multipole method. For non-periodic systems, use a fast multipole method, or P3M with a zero padded mesh. For small NN, direct Ewald summation is simpler.

Pitfalls

  • No deconvolution. Using G=ϕ^G = \hat\phi ignores the blur of the assignment and makes the short wavelengths too weak; in the example the errors are up to 100 times larger.
  • Cutoff too short for α\alpha. The short-range part is cut at rcr_c with an error of about e−α2rc2e^{-\alpha^2 r_c^2}. Keep αrc\alpha r_c near 3 or more.
  • Kernel too rough for the mesh. If αh\alpha h is not small, the long-range kernel has power beyond the Nyquist frequency, and aliasing dominates the error whatever GG is.
  • Different weights for assignment and interpolation. Then the total force is no longer zero, and a lone particle accelerates by itself.
  • Nyquist modes. With ik differentiation, the derivative at the Nyquist index must be set to 0, or the field gets an imaginary part and the momentum is lost.

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.

p3m_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/p3m-method/. The authors are listed in prov/J50KQM.jsonl.
"""Particle-particle particle-mesh (P3M) forces of Hockney and Eastwood, in 2D.

N charges q[i] at positions pos[i] = (x, y) in the periodic unit square
interact by the 2D Coulomb law: the potential of a pair is -q_i q_j log r and
the force on i is q_i q_j (x_i - x_j) / r^2, summed over all periodic images.

The force of a pair is split with a Gaussian of width 1/alpha:

    1/r = exp(-alpha^2 r^2) / r  +  (1 - exp(-alpha^2 r^2)) / r.

The first part is short-range and is summed directly over the pairs closer
than r_c, found with a chaining mesh. The second part is smooth; it is the
field of Gaussian charge clouds, with the Fourier potential
(2 pi / k^2) exp(-k^2 / (4 alpha^2)), and it is computed on an M x M mesh:
charge assignment (CIC or TSC), FFT, multiplication by -i k G(k), inverse
FFT and interpolation with the same weights. G is the optimal influence
function of Hockney and Eastwood, which minimizes the mean square force
error of the mesh part.
"""

import cmath
import math
from typing import Sequence

Point = tuple[float, float]


def fft(a: Sequence[complex], inverse: bool = False) -> list[complex]:
    """Radix-2 FFT without normalization: sum_g a[g] exp(-+2 pi i n g / len(a))."""
    n = len(a)
    if n == 1:
        return [complex(a[0])]
    even = fft(a[0::2], inverse)
    odd = fft(a[1::2], inverse)
    sign = 1 if inverse else -1
    out = [0j] * n
    for k in range(n // 2):
        w = cmath.exp(sign * 2j * math.pi * k / n) * odd[k]
        out[k] = even[k] + w
        out[k + n // 2] = even[k] - w
    return out


def fft2(grid: list[list[complex]], inverse: bool = False) -> list[list[complex]]:
    """2D FFT of a square grid, rows then columns, without normalization."""
    rows = [fft(r, inverse) for r in grid]
    cols = [fft([rows[i][j] for i in range(len(rows))], inverse) for j in range(len(rows))]
    return [[cols[j][i] for j in range(len(cols))] for i in range(len(rows))]


def weights(x: float, m: int, order: int) -> list[tuple[int, float]]:
    """Mesh points (index mod m) and weights for one coordinate; order 2 is CIC, 3 is TSC."""
    u = x * m
    if order == 2:
        g = math.floor(u)
        t = u - g
        return [(g % m, 1 - t), ((g + 1) % m, t)]
    g = round(u)
    t = u - g
    return [((g - 1) % m, 0.5 * (0.5 - t) ** 2), (g % m, 0.75 - t * t), ((g + 1) % m, 0.5 * (0.5 + t) ** 2)]


def wavenumber(n: int, m: int) -> float:
    """The wave number 2 pi n of the FFT index n, folded to -m/2 .. m/2 - 1."""
    return 2 * math.pi * (n - m if n >= m // 2 else n)


def sinc(x: float) -> float:
    return 1.0 if x == 0 else math.sin(x) / x


def influence(m: int, alpha: float, order: int, kind: str = "optimal", alias: int = 2) -> list[list[float]]:
    """G(k) on the mesh: "optimal" (Hockney-Eastwood), "deconvolved" (phi / U^2) or "plain" (phi)."""
    h = 1.0 / m

    def phi(kx: float, ky: float) -> float:
        k2 = kx * kx + ky * ky
        return 2 * math.pi / k2 * math.exp(-k2 / (4 * alpha * alpha))

    def u2(kx: float, ky: float) -> float:
        return (sinc(kx * h / 2) * sinc(ky * h / 2)) ** (2 * order)

    g = [[0.0] * m for _ in range(m)]
    for i in range(m):
        for j in range(m):
            kx, ky = wavenumber(i, m), wavenumber(j, m)
            if i == 0 and j == 0:
                continue
            if kind == "plain":
                g[i][j] = phi(kx, ky)
            elif kind == "deconvolved":
                g[i][j] = phi(kx, ky) / u2(kx, ky)
            else:
                num = 0.0
                den = 0.0
                for ax in range(-alias, alias + 1):
                    for ay in range(-alias, alias + 1):
                        qx, qy = kx + 2 * math.pi * m * ax, ky + 2 * math.pi * m * ay
                        w = u2(qx, qy)
                        num += w * (kx * qx + ky * qy) * phi(qx, qy)
                        den += w
                g[i][j] = num / ((kx * kx + ky * ky) * den * den)
    return g


def short_range(q: Sequence[float], pos: Sequence[Point], alpha: float, r_c: float) -> tuple[list[Point], int]:
    """Short-range forces over pairs closer than r_c (minimum image), found with a chaining mesh."""
    n = len(q)
    nc = max(1, int(1 / r_c))
    cells: dict[tuple[int, int], list[int]] = {}
    for i, (x, y) in enumerate(pos):
        cells.setdefault((int(x * nc) % nc, int(y * nc) % nc), []).append(i)
    if nc >= 3:
        offsets = [(dx, dy) for dx in (-1, 0, 1) for dy in (-1, 0, 1)]
    else:
        offsets = [(dx, dy) for dx in range(nc) for dy in range(nc)]
    f = [[0.0, 0.0] for _ in range(n)]
    pairs = 0
    for (cx, cy), idx in cells.items():
        for dx, dy in offsets:
            other = cells.get(((cx + dx) % nc, (cy + dy) % nc), ())
            for i in idx:
                for j in other:
                    if i == j:
                        continue
                    rx = pos[i][0] - pos[j][0]
                    ry = pos[i][1] - pos[j][1]
                    rx -= round(rx)
                    ry -= round(ry)
                    r2 = rx * rx + ry * ry
                    if r2 < r_c * r_c:
                        c = q[i] * q[j] * math.exp(-alpha * alpha * r2) / r2
                        f[i][0] += c * rx
                        f[i][1] += c * ry
                        pairs += 1
    return [(a, b) for a, b in f], pairs


def p3m_forces(q: Sequence[float], pos: Sequence[Point], m: int = 32, alpha: float = 12.0, r_c: float = 0.25,
               order: int = 2, kind: str = "optimal"):
    """P3M forces on all charges. m is a power of 2. Returns (forces, stats)."""
    n = len(q)
    w = [(weights(x, m, order), weights(y, m, order)) for x, y in pos]
    rho = [[0j] * m for _ in range(m)]
    for i in range(n):  # @line L1
        for gx, wx in w[i][0]:
            for gy, wy in w[i][1]:
                rho[gx][gy] += q[i] * wx * wy
    rho_k = fft2(rho)  # @line L2
    g = influence(m, alpha, order, kind)
    ex_k = [[0j] * m for _ in range(m)]
    ey_k = [[0j] * m for _ in range(m)]
    for i in range(m):  # @line L3
        for j in range(m):
            kx = 0.0 if i == m // 2 else wavenumber(i, m)
            ky = 0.0 if j == m // 2 else wavenumber(j, m)
            ex_k[i][j] = -1j * kx * g[i][j] * rho_k[i][j]
            ey_k[i][j] = -1j * ky * g[i][j] * rho_k[i][j]
    ex = fft2(ex_k, inverse=True)  # @line L4
    ey = fft2(ey_k, inverse=True)
    forces = []
    for i in range(n):  # @line L5
        fx = fy = 0.0
        for gx, wx in w[i][0]:
            for gy, wy in w[i][1]:
                fx += wx * wy * ex[gx][gy].real
                fy += wx * wy * ey[gx][gy].real
        forces.append([q[i] * fx, q[i] * fy])
    sr, pairs = short_range(q, pos, alpha, r_c)  # @line L6
    out = [(a + c, b + d) for (a, b), (c, d) in zip(forces, sr)]
    return out, {"pairs": pairs, "mesh": m * m}  # @line L7


def ewald_forces(q: Sequence[float], pos: Sequence[Point], alpha: float = 8.0, kmax: int = 14) -> list[Point]:
    """Reference forces by Ewald summation: real space over 3 x 3 images, Fourier space up to |n| <= kmax."""
    n = len(q)
    f = [[0.0, 0.0] for _ in range(n)]
    for i in range(n):
        for j in range(n):
            for ix in (-1, 0, 1):
                for iy in (-1, 0, 1):
                    if i == j and ix == 0 and iy == 0:
                        continue
                    rx = pos[i][0] - pos[j][0] + ix
                    ry = pos[i][1] - pos[j][1] + iy
                    r2 = rx * rx + ry * ry
                    c = q[i] * q[j] * math.exp(-alpha * alpha * r2) / r2
                    f[i][0] += c * rx
                    f[i][1] += c * ry
    for a in range(-kmax, kmax + 1):
        for b in range(-kmax, kmax + 1):
            if a == 0 and b == 0:
                continue
            kx, ky = 2 * math.pi * a, 2 * math.pi * b
            k2 = kx * kx + ky * ky
            coef = 2 * math.pi / k2 * math.exp(-k2 / (4 * alpha * alpha))
            s = sum(qj * cmath.exp(-1j * (kx * x + ky * y)) for qj, (x, y) in zip(q, pos))
            for i, (x, y) in enumerate(pos):
                im = (s * cmath.exp(1j * (kx * x + ky * y))).imag
                f[i][0] += q[i] * coef * kx * im
                f[i][1] += q[i] * coef * ky * im
    return [(a, b) for a, b in f]
test_p3m_method.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/p3m-method/. The authors are listed in prov/J50KQM.jsonl.
"""Tests for P3M: the FFT, the assignment weights, the short-range sum, and the forces against Ewald summation."""

import cmath
import math
import random
import unittest

from p3m_method import ewald_forces, fft, fft2, p3m_forces, short_range, weights


def rms_err(f, ref):
    num = sum((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2 for a, b in zip(f, ref))
    den = sum(b[0] ** 2 + b[1] ** 2 for b in ref)
    return math.sqrt(num / den)


def charges(n, seed):
    rng = random.Random(seed)
    pos = [(rng.random(), rng.random()) for _ in range(n)]
    q = [1.0 if i % 2 == 0 else -1.0 for i in range(n)]
    return q, pos


class TestPieces(unittest.TestCase):
    def test_fft_matches_dft(self):
        rng = random.Random(1)
        a = [complex(rng.random(), rng.random()) for _ in range(16)]
        for inverse, sign in ((False, -1), (True, 1)):
            b = fft(a, inverse)
            for k in range(16):
                d = sum(a[g] * cmath.exp(sign * 2j * math.pi * k * g / 16) for g in range(16))
                self.assertAlmostEqual(abs(b[k] - d), 0.0, places=12)

    def test_fft2_round_trip(self):
        rng = random.Random(2)
        grid = [[complex(rng.random(), 0) for _ in range(8)] for _ in range(8)]
        back = fft2(fft2(grid), inverse=True)
        for i in range(8):
            for j in range(8):
                self.assertAlmostEqual(abs(back[i][j] / 64 - grid[i][j]), 0.0, places=12)

    def test_weights_conserve_charge_and_center(self):
        rng = random.Random(3)
        m = 16
        for order in (2, 3):
            for _ in range(20):
                x = rng.uniform(0.1, 0.9)
                w = weights(x, m, order)
                self.assertAlmostEqual(sum(v for _, v in w), 1.0, places=14)
                u = x * m
                center = sum(v * (g + m * round((u - g) / m)) for g, v in w)
                self.assertAlmostEqual(center, u, places=12)

    def test_short_range_matches_brute_force(self):
        q, pos = charges(120, 4)
        alpha, r_c = 12.0, 0.25
        f, pairs = short_range(q, pos, alpha, r_c)
        count = 0
        for i in range(120):
            fx = fy = 0.0
            for j in range(120):
                if i == j:
                    continue
                rx = pos[i][0] - pos[j][0]
                ry = pos[i][1] - pos[j][1]
                rx -= round(rx)
                ry -= round(ry)
                r2 = rx * rx + ry * ry
                if r2 < r_c * r_c:
                    c = q[i] * q[j] * math.exp(-alpha * alpha * r2) / r2
                    fx += c * rx
                    fy += c * ry
                    count += 1
            self.assertAlmostEqual(f[i][0], fx, places=9)
            self.assertAlmostEqual(f[i][1], fy, places=9)
        self.assertEqual(pairs, count)

    def test_ewald_does_not_depend_on_alpha(self):
        q, pos = charges(60, 5)
        self.assertLess(rms_err(ewald_forces(q, pos, alpha=6.0, kmax=12), ewald_forces(q, pos)), 1e-10)


class TestP3M(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.q, cls.pos = charges(200, 21)
        cls.ref = ewald_forces(cls.q, cls.pos)

    def test_accuracy_against_ewald(self):
        cases = ((32, 2, 5e-3), (32, 3, 6e-4), (64, 3, 1e-4))
        for m, order, tol in cases:
            f, st = p3m_forces(self.q, self.pos, m=m, order=order)
            self.assertLess(rms_err(f, self.ref), tol)
        self.assertEqual(st["mesh"], 64 * 64)

    def test_influence_functions(self):
        errs = [rms_err(p3m_forces(self.q, self.pos, m=16, alpha=16.0, r_c=0.1875, kind=k)[0], self.ref)
                for k in ("plain", "deconvolved", "optimal")]
        self.assertLess(errs[1], errs[0] / 1.5)
        self.assertLess(errs[2], errs[1])

    def test_smaller_alpha_moves_work_to_the_pairs(self):
        prev_err, prev_pairs = 0.0, 10 ** 9
        for alpha, r_c in ((8.0, 0.375), (12.0, 0.25), (20.0, 0.15)):
            f, st = p3m_forces(self.q, self.pos, m=32, alpha=alpha, r_c=r_c)
            e = rms_err(f, self.ref)
            self.assertGreater(e, prev_err)
            self.assertLess(st["pairs"], prev_pairs)
            prev_err, prev_pairs = e, st["pairs"]

    def test_total_force_is_zero(self):
        f, _ = p3m_forces(self.q, self.pos, m=32)
        scale = math.sqrt(sum(a * a + b * b for a, b in self.ref) / len(self.ref))
        self.assertLess(abs(sum(a for a, _ in f)), 1e-10 * scale)
        self.assertLess(abs(sum(b for _, b in f)), 1e-10 * scale)
        single, _ = p3m_forces([1.0], [(0.3, 0.6)], m=32)
        self.assertLess(math.hypot(*single[0]), 1e-12)

    def test_pair_force(self):
        for d in (0.05, 0.2, 0.4):
            pos2 = [(0.3, 0.5), (0.3 + d, 0.5)]
            f, _ = p3m_forces([1.0, -1.0], pos2, m=32)
            r = ewald_forces([1.0, -1.0], pos2)
            self.assertLess(abs(f[0][0] - r[0][0]), 0.01 * abs(r[0][0]))
            self.assertGreater(f[0][0], 0.0)


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

History

Hockney and Eastwood developed the particle-particle particle-mesh method for plasma and gravitational simulation and described it in their book Computer Simulation Using Particles (1981; second edition 1988), together with the chaining mesh and the optimal influence function. The method was used in cosmological simulations from the 1980s, where adaptive versions refine the mesh over clusters. Deserno and Holm (1998) compared P3M with the particle mesh Ewald methods of molecular dynamics and gave an accurate error estimate for it.

References

  1. Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, Chapter 8, the particle-particle particle-mesh algorithm, the chaining mesh and the optimal influence function
  2. Markus Deserno and Christian Holm, How to mesh up Ewald sums. I. A theoretical and numerical comparison of various particle mesh routines, Journal of Chemical Physics 109, 1998, 7678, the comparison of P3M with particle mesh Ewald and smooth particle mesh Ewald, the optimal influence function and the ik and finite difference derivatives
  3. Markus Deserno and Christian Holm, How to mesh up Ewald sums. II. An accurate error estimate for the particle-particle-particle-mesh algorithm, Journal of Chemical Physics 109, 1998, 7694, the error estimate of P3M from the optimal influence function and its use to choose the parameters

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of 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