Algorithm Search⌘K

Algorithmcore

Particle-mesh method

Also called PM method.

Assigns particle mass or charge to a grid, solves Poisson's equation on the grid by FFT and interpolates the forces back, in O(N + M log M) per step for M grid points.

Time
Θ(N + M log M) worst
Space
Θ(M) extra
Where
M = the number of grid points; N = the number of particles
Properties
conservativedeterministic
Origin
Roger W. Hockney, James W. Eastwood, 1981

The particle-mesh (PM) method computes the gravitational or electrostatic forces among NN particles in a periodic box with a grid of MM points. It assigns the particle masses or charges to the grid, solves Poisson's equation on the grid with the fast Fourier transform, takes the gradient of the potential on the grid, and interpolates the field back to the particles. One force evaluation costs Θ(N+Mlog⁡M)\Theta(N + M \log M), against Θ(N2)\Theta(N^2) for direct summation. The price is resolution: the grid cannot resolve forces at separations of a few cells or less, so PM suits systems where the long-range collective field matters most, such as collisionless plasmas and the large-scale structure of the universe.

In plain words

Adding up the pull of every particle on every other particle is slow when there are millions of particles. The particle-mesh method avoids this. It first lays a regular grid over the box and lets each particle share its mass with the nearby grid points, so the grid holds a smooth picture of where the mass is.

On a regular grid, the equation that turns mass into a pull can be solved very fast with a standard tool for waves. The method then has the pull at every grid point. Each particle reads the pull at its own place from the same nearby points, and moves. The cost grows only a little faster than the number of grid points plus the number of particles. The pull between two particles that are very close is too weak, because the grid blurs it.

The problem

The input is a periodic box [0,Lx)×[0,Ly)[0, L_x) \times [0, L_y) with an nx×nyn_x \times n_y grid, M=nxnyM = n_x n_y, spacings Δx=Lx/nx\Delta x = L_x / n_x and Δy=Ly/ny\Delta y = L_y / n_y, and NN particles with positions xi\mathbf{x}_i, inertial masses mim_i and source weights wiw_i. The field is the solution of

∇2ϕ=s (ρ−ρˉ),g=−∇ϕ,Fi=wi g(xi),\nabla^2 \phi = s \, (\rho - \bar\rho), \qquad \mathbf{g} = -\nabla \phi, \qquad \mathbf{F}_i = w_i \, \mathbf{g}(\mathbf{x}_i),

where ρ\rho is the density of the weights and ρˉ\bar\rho its mean. For gravity in units with G=1G = 1, s=4πs = 4\pi and wi=miw_i = m_i. For a plasma in normalized units with ϵ0=1\epsilon_0 = 1, s=−1s = -1, wi=qiw_i = q_i and g\mathbf{g} is the electric field E\mathbf{E}. The mean is removed because a periodic Poisson problem has a solution only for a source of zero mean; for a plasma it is the uniform neutralizing background, and in cosmology it is the background density of the expanding universe. With ny=1n_y = 1 the method is the 1D method. The output is the force on each particle and, with a time integrator, the trajectories.

The algorithm

The grid step uses the 5-point Laplacian and the centred difference. Its eigenvalue for the Fourier mode (kx,ky)(k_x, k_y) is

λ(kx,ky)=−4Δx2sin⁡2πkxnx−4Δy2sin⁡2πkyny,\lambda(k_x, k_y) = -\frac{4}{\Delta x^2} \sin^2 \frac{\pi k_x}{n_x} - \frac{4}{\Delta y^2} \sin^2 \frac{\pi k_y}{n_y},

which is zero only for the mode (0,0)(0, 0).

  1. PM-FORCES(x[1..N], w[1..N], grid, s)
  2. 1ρ ← CIC-DEPOSIT(x, w) ▷ density on the n_x × n_y grid
  3. 2ρ̂ ← FFT2(ρ)
  4. 3φ̂(k) ← s ρ̂(k) / λ(k) for k ≠ (0, 0); φ̂(0, 0) ← 0
  5. 4φ ← inverse FFT2(φ̂)
  6. 5g_x[i, j] ← -(φ[i+1, j] - φ[i-1, j]) / (2 Δx); g_y[i, j] ← -(φ[i, j+1] - φ[i, j-1]) / (2 Δy)
  7. 6g(x_p) ← CIC-INTERPOLATE(g, x_p) for p = 1, ..., N
  8. 7return F_p = w_p g(x_p) for p = 1, ..., N
  9. PM-RUN(x, v, m, w, grid, s, h, T)
  10. 8F ← PM-FORCES(x, w, grid, s)
  11. 9for n ← 1 to T do
  12. 10v_p ← v_p + (h / 2) F_p / m_p for every p
  13. 11x_p ← (x_p + h v_p) mod (L_x, L_y) for every p
  14. 12F ← PM-FORCES(x, w, grid, s)
  15. 13v_p ← v_p + (h / 2) F_p / m_p for every p
  16. 14return x, v

Line L1 is cloud-in-cell assignment, which gives each particle bilinear weights on the 4 grid points around it. Lines L2 to L4 solve the discrete Poisson equation exactly: the Fourier modes are the eigenvectors of the periodic 5-point Laplacian, so dividing each coefficient by its eigenvalue inverts it on the mean-free part. Line L5 differences the potential, and line L6 reads the field at the particles with the same CIC weights as line L1. Lines L8 to L14 are the kick-drift-kick form of the leapfrog (Verlet) integrator with step hh.

Example

Take a 1D grid with M=8M = 8, L=8L = 8 (so Δx=1\Delta x = 1), s=1s = 1 and two unit masses on the grid points x=2x = 2 and x=5x = 5. Line L1 gives ρ=(0,0,1,0,0,1,0,0)\rho = (0, 0, 1, 0, 0, 1, 0, 0) with mean ρˉ=0.25\bar\rho = 0.25. Lines L2 to L4 give

ϕ=(0.375,  0.125,  −0.375,  −0.125,  −0.125,  −0.375,  0.125,  0.375).\phi = (0.375, \; 0.125, \; -0.375, \; -0.125, \; -0.125, \; -0.375, \; 0.125, \; 0.375).

At point 2, (ϕ1−2ϕ2+ϕ3)/Δx2=0.125+0.75−0.125=0.75=ρ2−ρˉ(\phi_1 - 2\phi_2 + \phi_3) / \Delta x^2 = 0.125 + 0.75 - 0.125 = 0.75 = \rho_2 - \bar\rho, as the equation requires. Line L5 gives

g=(0.125,  0.375,  0.125,  −0.125,  0.125,  −0.125,  −0.375,  −0.125).g = (0.125, \; 0.375, \; 0.125, \; -0.125, \; 0.125, \; -0.125, \; -0.375, \; -0.125).

Both particles sit on grid points, so line L6 reads g2=0.125g_2 = 0.125 and g5=−0.125g_5 = -0.125. The particles attract each other along the short way round the ring (distance 3, not 5), and the two forces cancel. The continuum answer for two masses on a periodic line at distance dd is s m1m2(1/2−d/L)=1/2−3/8=0.125s \, m_1 m_2 (1/2 - d / L) = 1/2 - 3/8 = 0.125, so the grid force is exact here. This holds for any two particles on grid points at least 2 cells apart in both directions round the ring, because the discrete potential of one particle is the continuum quadratic at the grid points, and the centred difference of a quadratic is exact.

Correctness

The full proof is in the correctness proof. It shows three facts (all theorems).

  • Lines L2 to L4 return the unique mean-free grid function ϕ\phi whose 5-point Laplacian is s(ρ−ρˉ)s (\rho - \bar\rho), because the Fourier modes diagonalize the periodic 5-point Laplacian and only the mode (0,0)(0, 0) has eigenvalue 0.
  • The forces of line L7 sum to zero exactly in exact arithmetic, and a lone particle feels no force. The map from ρ\rho to gg is a convolution with an odd kernel (an even Green's function followed by an odd difference), and lines L1 and L6 use the same weights, so the argument of the cloud-in-cell page applies.
  • Lines L10 to L13 then change the total momentum ∑pmpvp\sum_p m_p \mathbf{v}_p by h∑pFp=0h \sum_p \mathbf{F}_p = 0 in each step, and the integrator is time reversible: running TT steps, reversing all velocities and running TT steps again returns the start.

Convergence is a separate claim. For a smooth density, the 5-point Laplacian and the centred difference are both second order in the grid spacing, so the grid field has an error of O(Δx2+Δy2)O(\Delta x^2 + \Delta y^2) (a theorem on the truncation error). The tests measure an error ratio between 3.8 and 4.2 when MM doubles in 1D.

Proof: The particle-mesh method solves the discrete Poisson equation exactly, gives forces that sum to zero, and its leapfrog conserves momentum and is time reversiblefull

We use the pseudocode of the page and exact arithmetic. Grid indices (i,j)(i, j) are taken mod (nx,ny)(n_x, n_y). Write DD for the periodic 5-point Laplacian, (Dϕ)i,j=(ϕi+1,j−2ϕi,j+ϕi−1,j)/Δx2+(ϕi,j+1−2ϕi,j+ϕi,j−1)/Δy2(D\phi)_{i,j} = (\phi_{i+1,j} - 2\phi_{i,j} + \phi_{i-1,j}) / \Delta x^2 + (\phi_{i,j+1} - 2\phi_{i,j} + \phi_{i,j-1}) / \Delta y^2, and ek(i,j)=exp⁡(2πi(kxi/nx+kyj/ny))e_k(i, j) = \exp(2\pi \mathrm{i} (k_x i / n_x + k_y j / n_y)) for the Fourier mode k=(kx,ky)k = (k_x, k_y).

Claim 1 (the Poisson solve). Lines L2 to L4 return the unique grid function ϕ\phi with ∑i,jϕi,j=0\sum_{i,j} \phi_{i,j} = 0 and Dϕ=s(ρ−ρˉ)D\phi = s (\rho - \bar\rho).

Proof. A direct computation gives Dek=λ(k)ekD e_k = \lambda(k) e_k with λ(k)=(2cos⁡(2πkx/nx)−2)/Δx2+(2cos⁡(2πky/ny)−2)/Δy2\lambda(k) = (2\cos(2\pi k_x / n_x) - 2) / \Delta x^2 + (2\cos(2\pi k_y / n_y) - 2) / \Delta y^2, which equals the formula on the page because 2−2cos⁡θ=4sin⁡2(θ/2)2 - 2\cos\theta = 4 \sin^2(\theta/2). Each term is at most 0, and the sum is 0 only if kx≡0k_x \equiv 0 and ky≡0k_y \equiv 0. The MM modes form a basis of the grid functions, and line L2 computes the coefficients of ρ\rho in this basis (up to the factor 1/M1/M that the inverse in L4 restores). The mode (0,0)(0, 0) is the constant function, and its coefficient is MρˉM \bar\rho. Line L3 sets the coefficient of ϕ\phi to sρ^(k)/λ(k)s \hat\rho(k) / \lambda(k) for k≠0k \ne 0 and to 0 for k=0k = 0. Then DϕD\phi has the coefficients sρ^(k)s \hat\rho(k) for k≠0k \ne 0 and 0 for k=0k = 0, which are the coefficients of s(ρ−ρˉ)s (\rho - \bar\rho); and ϕ\phi has zero mean. For uniqueness, if Dψ=0D\psi = 0 then every coefficient of ψ\psi with k≠0k \ne 0 is 0, so ψ\psi is constant, and a constant with zero mean is 0. □\square

Claim 2 (zero total force). The forces of line L7 satisfy ∑pFp=0\sum_p \mathbf{F}_p = 0. For N=1N = 1 the force is zero.

Proof. By Claim 1, ϕ=G∗(ρ−ρˉ)\phi = G * (\rho - \bar\rho) for the grid function GG with coefficients s/λ(k)s / \lambda(k) for k≠0k \ne 0 and 0 for k=0k = 0 (the star is the periodic convolution). Since λ(−k)=λ(k)\lambda(-k) = \lambda(k) and λ\lambda is real, GG is real and even: G−i,−j=Gi,jG_{-i,-j} = G_{i,j}. Line L5 is the convolution with the stencil cxc_x that has cx(1,0)=−1/(2Δx)c_x(1, 0) = -1/(2\Delta x), cx(−1,0)=1/(2Δx)c_x(-1, 0) = 1/(2\Delta x) and 0 elsewhere, which is odd. So gx=K∗(ρ−ρˉ)g_x = K * (\rho - \bar\rho) with K=cx∗GK = c_x * G, and K−i,−j=−Ki,jK_{-i,-j} = -K_{i,j}. An odd kernel sums to 0, so K∗ρˉ=0K * \bar\rho = 0 and gx=K∗ρg_x = K * \rho. The same holds for gyg_y.

Let Wp,aW_{p,a} be the CIC weight of particle pp on grid point aa, summed over the periodic images. Line L1 gives ρa=∑pwpWp,a/(ΔxΔy)\rho_a = \sum_p w_p W_{p,a} / (\Delta x \Delta y), and line L6 gives gx(xp)=∑aWp,agx,ag_x(\mathbf{x}_p) = \sum_a W_{p,a} g_{x,a} with the same WW (the cloud-in-cell page proves both forms). So

∑pwp gx(xp)=∑agx,a∑pwpWp,a=ΔxΔy∑aρagx,a=ΔxΔy∑a∑bρaKa−bρb.\sum_p w_p \, g_x(\mathbf{x}_p) = \sum_a g_{x,a} \sum_p w_p W_{p,a} = \Delta x \Delta y \sum_a \rho_a g_{x,a} = \Delta x \Delta y \sum_a \sum_b \rho_a K_{a-b} \rho_b.

Exchanging the names aa and bb and using Kb−a=−Ka−bK_{b-a} = -K_{a-b} shows that the double sum equals its own negative, so it is 0. The same holds for the yy component. For N=1N = 1 the sum is the force on the single particle. □\square

Claim 3 (momentum). Each pass through lines L10 to L13 leaves P=∑pmpvp\mathbf{P} = \sum_p m_p \mathbf{v}_p unchanged.

Proof. Line L10 adds (h/2)∑pFp(h/2) \sum_p \mathbf{F}_p to P\mathbf{P}, which is 0 by Claim 2 for the forces of line L8 or of the last L12. Line L11 does not change any velocity. Line L13 adds (h/2)∑pFp=0(h/2) \sum_p \mathbf{F}_p = 0 for the new forces. □\square

Claim 4 (time reversibility). Let one pass of lines L10 to L13 map (x,v)(x, v) with forces F(x)F(x) to (x′,v′)(x', v'). Then the same pass maps (x′,−v′)(x', -v') to (x,−v)(x, -v).

Proof. The forces depend only on the positions (Claim 1 and lines L1, L5 to L7). Write u=v+(h/2)F(x)/mu = v + (h/2) F(x)/m for the velocity after line L10, so x′=x+hux' = x + h u and v′=u+(h/2)F(x′)/mv' = u + (h/2) F(x')/m. Start the pass at (x′,−v′)(x', -v'). Line L10 gives −v′+(h/2)F(x′)/m=−u-v' + (h/2) F(x')/m = -u. Line L11 gives x′−hu=xx' - h u = x, mod the box. Line L12 computes F(x)F(x), and line L13 gives −u+(h/2)F(x)/m=−v-u + (h/2) F(x)/m = -v. The wrap mod the box does not matter, because the forces are periodic functions of the positions. ■\blacksquare

Complexity

In the real-RAM model with M=nxnyM = n_x n_y and nxn_x, nyn_y powers of 2: line L1 costs Θ(N+M)\Theta(N + M), lines L2 and L4 cost Θ(Mlog⁡M)\Theta(M \log M) each (row transforms then column transforms), lines L3 and L5 cost Θ(M)\Theta(M), and lines L6 and L7 cost Θ(N)\Theta(N). So one force evaluation costs Θ(N+Mlog⁡M)\Theta(N + M \log M) time and Θ(M)\Theta(M) extra space, and TT steps of PM-RUN cost Θ(T(N+Mlog⁡M))\Theta(T (N + M \log M)). The same holds in 3D with 8 grid points per particle. For comparison, direct summation costs Θ(N2)\Theta(N^2) per step, and a Barnes-Hut tree O(Nlog⁡N)O(N \log N) for a fixed opening angle.

Properties

  • Momentum is conserved exactly. This needs the same assignment function in lines L1 and L6 and an odd difference operator in line L5 (Hockney and Eastwood, chapter 5).
  • Energy is not conserved exactly. The force of this scheme is not the exact gradient of an energy of the particle positions, so the total energy drifts slowly. In plasma runs with a Debye length well below a cell, the drift shows as grid heating. Birdsall and Langdon describe energy-conserving variants that give up exact momentum conservation.
  • Softened at the grid scale. The force between two particles is close to the true force at separations of several cells, and much weaker at separations of one cell or less (a heuristic; the size of the error depends on the assignment function and the Green's function). The mesh acts as a softening of about one cell.
  • Not translation invariant. The force between two particles at a fixed separation changes a little as the pair moves relative to the grid.
  • Periodic. The FFT solve gives the field of the periodic box. Isolated systems need a doubled grid with a truncated Green's function.
  • Deterministic. The method has no random choices; the run is fixed by the initial data.

Variants and improvements

  • Other assignment functions. Nearest grid point (NGP) is cheaper but noisier; triangular shaped cloud (TSC) uses 27 points per particle in 3D and gives a smoother force (see cloud-in-cell assignment).
  • Spectral differences and optimized Green's functions. Line L5 can be done in Fourier space by multiplying by −ik-i k, and the Green's function 1/λ1 / \lambda can be replaced by one that also divides out the smoothing of the assignment function. Hockney and Eastwood derive an optimal influence function that minimizes the force error for a given assignment.
  • P3M. The P3M method adds a direct sum of the short-range force over near pairs, which restores the force at separations below a few cells.
  • TreePM. The TreePM method uses a tree code for the short-range part instead of a direct sum.
  • Adaptive grids. Adaptive mesh codes refine the grid where the density is high and solve Poisson's equation on each level.
  • Particle mesh Ewald. In molecular dynamics, particle mesh Ewald uses the same steps for the long-range part of the Ewald sum.

When to use it

Use PM when the long-range field of many particles matters and the short-range force does not, as in a collisionless plasma (plasma particle-in-cell) or a dark matter simulation on scales above the grid spacing. It is also a cheap first stage inside P3M and TreePM. Do not use plain PM when close encounters matter, for example in star clusters or in molecular dynamics at short range, and do not use it for a strongly clustered system unless the grid is refined, because most of the grid then holds almost no mass.

Pitfalls

  • A wrong sign of ss. Gravity has ∇2ϕ=+4πGρ\nabla^2 \phi = +4\pi G \rho and electrostatics ∇2ϕ=−ρ/ϵ0\nabla^2 \phi = -\rho / \epsilon_0. With the wrong sign, like masses repel.
  • Not removing the mean. If line L3 divides by λ(0,0)=0\lambda(0, 0) = 0, the result is infinite or NaN. The mode (0,0)(0, 0) must be set to zero.
  • Different weights in L1 and L6. Using CIC to deposit and NGP to interpolate gives self-forces and a drift of the total momentum.
  • A one-sided difference in L5. A forward difference of ϕ\phi is not odd, so the forces no longer sum to zero.
  • Too few cells. The method resolves nothing below a cell. Results at those scales are an artefact of the grid, not physics.
  • A large time step. The leapfrog is stable only for hh below about 2/ω2 / \omega, where ω\omega is the fastest frequency, for example the plasma frequency ωp\omega_p in a plasma.

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.

particle_mesh_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-mesh-method/. The authors are listed in prov/Y8XKSA.jsonl.
"""The particle-mesh (PM) method on a periodic 2D grid, with a leapfrog integrator.

Each force evaluation assigns the particle weights (masses or charges) to an
nx by ny grid with cloud-in-cell weights, solves the periodic Poisson equation
lap phi = s (rho - mean(rho)) for the 5-point Laplacian by the FFT, takes
g = -grad phi by centred differences, and interpolates g back to the particles
with the same weights. The force on particle i is w_i g(x_i). For gravity,
s = 4 pi G and w_i is the mass; for charges, s = -1 / epsilon_0 and w_i is the
charge. A grid with ny = 1 gives the 1D method.

Preconditions: nx and ny are powers of 2 (1 is allowed), lx, ly > 0.
Cost of one force evaluation: Theta(N + M log M) time and Theta(M) extra
space, with N particles and M = nx ny grid points.
"""

import cmath
import math
from typing import Sequence

Vec = list[float]


def fft(a: list[complex], inverse: bool = False) -> list[complex]:
    """Radix-2 FFT, sum_j a_j exp(-+2 pi i j k / n); the inverse includes the factor 1/n."""
    n = len(a)
    if n & (n - 1):
        raise ValueError("length must be a power of 2")
    a = list(a)
    j = 0
    for i in range(1, n):
        bit = n >> 1
        while j & bit:
            j ^= bit
            bit >>= 1
        j |= bit
        if i < j:
            a[i], a[j] = a[j], a[i]
    size = 2
    sign = 1 if inverse else -1
    while size <= n:
        wn = cmath.exp(sign * 2j * math.pi / size)
        half = size // 2
        for start in range(0, n, size):
            w = 1 + 0j
            for k in range(start, start + half):
                u, t = a[k], w * a[k + half]
                a[k], a[k + half] = u + t, u - t
                w *= wn
        size *= 2
    if inverse:
        a = [x / n for x in a]
    return a


def fft2(g: list[list[complex]], inverse: bool = False) -> list[list[complex]]:
    """2D FFT of g[i][j] (i along x, j along y): FFT of each row, then of each column."""
    rows = [fft(r, inverse) for r in g]
    nx, ny = len(rows), len(rows[0])
    cols = [fft([rows[i][j] for i in range(nx)], inverse) for j in range(ny)]
    return [[cols[j][i] for j in range(ny)] for i in range(nx)]


def deposit(ps: Sequence[Vec], ws: Sequence[float], nx: int, ny: int, lx: float, ly: float):
    """Cloud-in-cell density on the grid, rho[i][j] at (i dx, j dy)."""
    dx, dy = lx / nx, ly / ny
    rho = [[0.0] * ny for _ in range(nx)]
    for (x, y), w in zip(ps, ws):
        sx, sy = x / dx, y / dy
        i, j = math.floor(sx), math.floor(sy)
        fx, fy = sx - i, sy - j
        c = w / (dx * dy)
        rho[i % nx][j % ny] += c * (1 - fx) * (1 - fy)
        rho[(i + 1) % nx][j % ny] += c * fx * (1 - fy)
        rho[i % nx][(j + 1) % ny] += c * (1 - fx) * fy
        rho[(i + 1) % nx][(j + 1) % ny] += c * fx * fy
    return rho


def interpolate(field, ps: Sequence[Vec], lx: float, ly: float) -> list[float]:
    """Field values at the particles with the same cloud-in-cell weights."""
    nx, ny = len(field), len(field[0])
    dx, dy = lx / nx, ly / ny
    out = []
    for x, y in ps:
        sx, sy = x / dx, y / dy
        i, j = math.floor(sx), math.floor(sy)
        fx, fy = sx - i, sy - j
        out.append(
            (1 - fx) * (1 - fy) * field[i % nx][j % ny]
            + fx * (1 - fy) * field[(i + 1) % nx][j % ny]
            + (1 - fx) * fy * field[i % nx][(j + 1) % ny]
            + fx * fy * field[(i + 1) % nx][(j + 1) % ny]
        )
    return out


def solve_poisson(rho, lx: float, ly: float, s: float):
    """Mean-free phi with (5-point Laplacian of phi) = s (rho - mean(rho)) on the periodic grid."""
    nx, ny = len(rho), len(rho[0])
    dx, dy = lx / nx, ly / ny
    rhat = fft2([[complex(v) for v in row] for row in rho])
    for kx in range(nx):
        for ky in range(ny):
            if kx == 0 and ky == 0:
                rhat[kx][ky] = 0j  # the mean of rho is removed
                continue
            lam = -4 * math.sin(math.pi * kx / nx) ** 2 / dx**2 - 4 * math.sin(math.pi * ky / ny) ** 2 / dy**2
            rhat[kx][ky] *= s / lam
    phi = fft2(rhat, inverse=True)
    return [[v.real for v in row] for row in phi]


def field_from_potential(phi, lx: float, ly: float):
    """g = -grad phi by centred differences on the periodic grid."""
    nx, ny = len(phi), len(phi[0])
    dx, dy = lx / nx, ly / ny
    gx = [[-(phi[(i + 1) % nx][j] - phi[i - 1][j]) / (2 * dx) for j in range(ny)] for i in range(nx)]
    gy = [[-(phi[i][(j + 1) % ny] - phi[i][j - 1]) / (2 * dy) for j in range(ny)] for i in range(nx)]
    return gx, gy


def pm_forces(ps: Sequence[Vec], ws: Sequence[float], nx: int, ny: int, lx: float, ly: float, s: float) -> list[Vec]:
    """Forces w_i g(x_i) from one particle-mesh evaluation."""
    rho = deposit(ps, ws, nx, ny, lx, ly)  # @line L1
    phi = solve_poisson(rho, lx, ly, s)  # @line L2 @line L3 @line L4
    gx, gy = field_from_potential(phi, lx, ly)  # @line L5
    ex = interpolate(gx, ps, lx, ly)  # @line L6
    ey = interpolate(gy, ps, lx, ly)  # @line L6
    return [[w * a, w * b] for w, a, b in zip(ws, ex, ey)]  # @line L7


def pm_run(
    ps: Sequence[Vec], vs: Sequence[Vec], ms: Sequence[float], ws: Sequence[float],
    nx: int, ny: int, lx: float, ly: float, s: float, h: float, steps: int,
) -> tuple[list[Vec], list[Vec]]:
    """Kick-drift-kick leapfrog with particle-mesh forces; positions wrap into the box.

    ms are the inertial masses and ws the weights that source the field (equal
    for gravity, the charges for a plasma).
    """
    x = [list(p) for p in ps]
    v = [list(u) for u in vs]
    f = pm_forces(x, ws, nx, ny, lx, ly, s)  # @line L8
    for _ in range(steps):  # @line L9
        for i in range(len(x)):
            v[i][0] += 0.5 * h * f[i][0] / ms[i]  # @line L10
            v[i][1] += 0.5 * h * f[i][1] / ms[i]  # @line L10
            x[i][0] = (x[i][0] + h * v[i][0]) % lx  # @line L11
            x[i][1] = (x[i][1] + h * v[i][1]) % ly  # @line L11
        f = pm_forces(x, ws, nx, ny, lx, ly, s)  # @line L12
        for i in range(len(x)):
            v[i][0] += 0.5 * h * f[i][0] / ms[i]  # @line L13
            v[i][1] += 0.5 * h * f[i][1] / ms[i]  # @line L13
    return x, v  # @line L14
test_particle_mesh_method.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-mesh-method/. The authors are listed in prov/Y8XKSA.jsonl.
import cmath
import math
import random

import pytest

from particle_mesh_method import (
    deposit,
    fft,
    fft2,
    field_from_potential,
    pm_forces,
    pm_run,
    solve_poisson,
)


def dft(a, inverse=False):
    n = len(a)
    sign = 1 if inverse else -1
    out = [sum(a[j] * cmath.exp(sign * 2j * math.pi * j * k / n) for j in range(n)) for k in range(n)]
    return [x / n for x in out] if inverse else out


def laplacian(phi, lx, ly):
    nx, ny = len(phi), len(phi[0])
    dx, dy = lx / nx, ly / ny
    out = [[0.0] * ny for _ in range(nx)]
    for i in range(nx):
        for j in range(ny):
            out[i][j] = (phi[(i + 1) % nx][j] - 2 * phi[i][j] + phi[i - 1][j]) / dx**2
            if ny > 1:
                out[i][j] += (phi[i][(j + 1) % ny] - 2 * phi[i][j] + phi[i][j - 1]) / dy**2
    return out


def test_fft_matches_dft():
    rng = random.Random(1)
    for n in (1, 2, 4, 8, 16, 32):
        a = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
        assert fft(a) == pytest.approx(dft(a), abs=1e-9)
        assert fft(a, inverse=True) == pytest.approx(dft(a, inverse=True), abs=1e-9)
        assert fft(fft(a), inverse=True) == pytest.approx(a, abs=1e-12)
    with pytest.raises(ValueError):
        fft([1, 2, 3])


def test_fft2_matches_double_dft():
    rng = random.Random(2)
    g = [[complex(rng.uniform(-1, 1)) for _ in range(4)] for _ in range(8)]
    got = fft2(g)
    for kx in range(8):
        for ky in range(4):
            want = sum(
                g[i][j] * cmath.exp(-2j * math.pi * (i * kx / 8 + j * ky / 4)) for i in range(8) for j in range(4)
            )
            assert got[kx][ky] == pytest.approx(want, abs=1e-9)


def test_poisson_solution_satisfies_discrete_equation():
    rng = random.Random(3)
    for nx, ny, lx, ly in ((8, 8, 1.0, 1.0), (16, 4, 2.0, 0.5), (32, 1, 3.0, 1.0)):
        s = rng.uniform(-3, 3)
        rho = [[rng.uniform(0, 2) for _ in range(ny)] for _ in range(nx)]
        phi = solve_poisson(rho, lx, ly, s)
        mean = sum(map(sum, rho)) / (nx * ny)
        lap = laplacian(phi, lx, ly)
        for i in range(nx):
            for j in range(ny):
                assert lap[i][j] == pytest.approx(s * (rho[i][j] - mean), abs=1e-9)
        assert sum(map(sum, phi)) == pytest.approx(0, abs=1e-9)


def test_page_example():
    f = pm_forces([[2.0, 0.0], [5.0, 0.0]], [1.0, 1.0], 8, 1, 8.0, 1.0, 1.0)
    assert f[0][0] == pytest.approx(0.125, abs=1e-12)
    assert f[1][0] == pytest.approx(-0.125, abs=1e-12)
    phi = solve_poisson(deposit([[2.0, 0.0], [5.0, 0.0]], [1, 1], 8, 1, 8.0, 1.0), 8.0, 1.0, 1.0)
    want = [0.375, 0.125, -0.375, -0.125, -0.125, -0.375, 0.125, 0.375]
    assert [p[0] for p in phi] == pytest.approx(want, abs=1e-12)


def test_1d_sawtooth_force_is_exact_on_nodes():
    # The periodic 1D force of mass m2 on mass m1 at offset d = x2 - x1 in (0, L) is s m1 m2 (1/2 - d/L).
    rng = random.Random(4)
    m, length = 16, 16.0
    for _ in range(40):
        a = rng.randrange(m)
        d = rng.randint(2, m - 2)
        b = (a + d) % m
        m1, m2 = rng.uniform(0.5, 2), rng.uniform(0.5, 2)
        s = rng.uniform(0.5, 2)
        f = pm_forces([[float(a), 0.0], [float(b), 0.0]], [m1, m2], m, 1, length, 1.0, s)
        want = s * m1 * m2 * (0.5 - d / length)
        assert f[0][0] == pytest.approx(want, abs=1e-9)
        assert f[1][0] == pytest.approx(-want, abs=1e-9)


def test_zero_self_force_and_zero_total_force():
    rng = random.Random(5)
    for _ in range(20):
        nx, ny = rng.choice([4, 8, 16]), rng.choice([1, 4, 8])
        lx, ly = rng.uniform(1, 3), rng.uniform(1, 3)
        p = [[rng.uniform(0, lx), rng.uniform(0, ly)]]
        f = pm_forces(p, [1.0], nx, ny, lx, ly, 1.0)
        assert f[0] == pytest.approx([0.0, 0.0], abs=1e-12)
        n = rng.randint(2, 40)
        ps = [[rng.uniform(0, lx), rng.uniform(0, ly)] for _ in range(n)]
        ws = [rng.uniform(-1, 2) for _ in range(n)]
        f = pm_forces(ps, ws, nx, ny, lx, ly, rng.uniform(-2, 2))
        assert sum(v[0] for v in f) == pytest.approx(0, abs=1e-12)
        assert sum(v[1] for v in f) == pytest.approx(0, abs=1e-12)


def test_grid_field_is_second_order():
    # rho = 1 + 0.5 cos(k x) gives g = -0.5 s sin(k x) / k in the continuum.
    length, s = 2.0, 3.0
    k = 2 * math.pi / length
    errs = []
    for m in (16, 32, 64):
        dx = length / m
        rho = [[1 + 0.5 * math.cos(k * i * dx)] for i in range(m)]
        gx, _ = field_from_potential(solve_poisson(rho, length, 1.0, s), length, 1.0)
        errs.append(max(abs(gx[i][0] + 0.5 * s * math.sin(k * i * dx) / k) for i in range(m)))
    for e1, e2 in zip(errs, errs[1:]):
        assert 3.8 < e1 / e2 < 4.2


def test_run_conserves_momentum_and_is_reversible():
    rng = random.Random(6)
    nx = ny = 8
    lx = ly = 1.0
    n = 30
    ps = [[rng.uniform(0, lx), rng.uniform(0, ly)] for _ in range(n)]
    vs = [[rng.uniform(-0.1, 0.1), rng.uniform(-0.1, 0.1)] for _ in range(n)]
    ms = [rng.uniform(0.5, 1.5) for _ in range(n)]
    p0 = [sum(m * v[c] for m, v in zip(ms, vs)) for c in range(2)]
    x, v = pm_run(ps, vs, ms, ms, nx, ny, lx, ly, 0.5, 0.01, 40)
    p1 = [sum(m * u[c] for m, u in zip(ms, v)) for c in range(2)]
    assert p1 == pytest.approx(p0, abs=1e-12)
    xb, vb = pm_run(x, [[-a, -b] for a, b in v], ms, ms, nx, ny, lx, ly, 0.5, 0.01, 40)
    for a, b in zip(xb, ps):
        dxp = (a[0] - b[0] + 0.5 * lx) % lx - 0.5 * lx
        dyp = (a[1] - b[1] + 0.5 * ly) % ly - 0.5 * ly
        assert abs(dxp) < 1e-9 and abs(dyp) < 1e-9
    for a, b in zip(vb, vs):
        assert [-a[0], -a[1]] == pytest.approx(b, abs=1e-9)


def test_two_body_attraction_in_2d_points_along_the_separation():
    # Two equal masses on a large grid attract along the line that joins them.
    f = pm_forces([[6.0, 8.0], [10.0, 8.0]], [1.0, 1.0], 16, 16, 16.0, 16.0, 1.0)
    assert f[0][0] > 0 and f[1][0] < 0
    assert f[0][1] == pytest.approx(0, abs=1e-12)
    assert f[0][0] == pytest.approx(-f[1][0], abs=1e-12)

History

Particle-mesh codes were used for plasma simulation and for the dynamics of galaxies in the 1960s, when the FFT made fast Poisson solvers on grids practical. Hockney and Eastwood (first edition 1981, second edition 1988) gave the standard treatment of the method, with the assignment functions NGP, CIC and TSC, the conditions for momentum conservation and the optimal influence function. Efstathiou, Davis, White and Frenk (1985) compared the force accuracy of particle-mesh schemes for cosmological simulations in a periodic cube, and made P3M a standard tool in cosmology.

References

  1. Roger W. Hockney and James W. Eastwood, Computer Simulation Using Particles, Adam Hilger, 1988, Chapter 5 (the particle-mesh force calculation) and Chapter 6 (the solution of the field equations)
  2. Charles K. Birdsall and A. Bruce Langdon, Plasma Physics via Computer Simulation, Taylor and Francis, 2004 (reprint of the IOP edition of 1991), Part 2, the chapters on the effects of the spatial grid and on energy-conserving models
  3. George Efstathiou, Marc Davis, Simon D. M. White and Carlos S. Frenk, Numerical techniques for large cosmological N-body simulations, The Astrophysical Journal Supplement Series 57, 1985, 241-260, the tests of the force accuracy of particle-mesh schemes in a periodic cube

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 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