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
- Model
- Real RAM
- Properties
- conservativedeterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Roger W. Hockney, James W. Eastwood, 1981
The particle-mesh (PM) method computes the gravitational or electrostatic forces among particles in a periodic box with a grid of 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 , against 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 with an grid, , spacings and , and particles with positions , inertial masses and source weights . The field is the solution of
where is the density of the weights and its mean. For gravity in units with , and . For a plasma in normalized units with , , and is the electric field . 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 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 is
which is zero only for the mode .
PM-FORCES(x[1..N], w[1..N], grid, s)- 1
ρ ← CIC-DEPOSIT(x, w) ▷ density on the n_x × n_y grid - 2
ρ̂ ← FFT2(ρ) - 3
φ̂(k) ← s ρ̂(k) / λ(k) for k ≠ (0, 0); φ̂(0, 0) ← 0 - 4
φ ← inverse FFT2(φ̂) - 5
g_x[i, j] ← -(φ[i+1, j] - φ[i-1, j]) / (2 Δx); g_y[i, j] ← -(φ[i, j+1] - φ[i, j-1]) / (2 Δy) - 6
g(x_p) ← CIC-INTERPOLATE(g, x_p) for p = 1, ..., N - 7
return F_p = w_p g(x_p) for p = 1, ..., N PM-RUN(x, v, m, w, grid, s, h, T)- 8
F ← PM-FORCES(x, w, grid, s) - 9
for n ← 1 to T do - 10
v_p ← v_p + (h / 2) F_p / m_p for every p - 11
x_p ← (x_p + h v_p) mod (L_x, L_y) for every p - 12
F ← PM-FORCES(x, w, grid, s) - 13
v_p ← v_p + (h / 2) F_p / m_p for every p - 14
return 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 .
Example
Take a 1D grid with , (so ), and two unit masses on the grid points and . Line L1 gives with mean . Lines L2 to L4 give
At point 2, , as the equation requires. Line L5 gives
Both particles sit on grid points, so line L6 reads and . 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 is , 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 whose 5-point Laplacian is , because the Fourier modes diagonalize the periodic 5-point Laplacian and only the mode 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 to 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 by in each step, and the integrator is time reversible: running steps, reversing all velocities and running 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 (a theorem on the truncation error). The tests measure an error ratio between 3.8 and 4.2 when 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 are taken mod . Write for the periodic 5-point Laplacian, , and for the Fourier mode .
Claim 1 (the Poisson solve). Lines L2 to L4 return the unique grid function with and .
Proof. A direct computation gives with , which equals the formula on the page because . Each term is at most 0, and the sum is 0 only if and . The modes form a basis of the grid functions, and line L2 computes the coefficients of in this basis (up to the factor that the inverse in L4 restores). The mode is the constant function, and its coefficient is . Line L3 sets the coefficient of to for and to 0 for . Then has the coefficients for and 0 for , which are the coefficients of ; and has zero mean. For uniqueness, if then every coefficient of with is 0, so is constant, and a constant with zero mean is 0.
Claim 2 (zero total force). The forces of line L7 satisfy . For the force is zero.
Proof. By Claim 1, for the grid function with coefficients for and 0 for (the star is the periodic convolution). Since and is real, is real and even: . Line L5 is the convolution with the stencil that has , and 0 elsewhere, which is odd. So with , and . An odd kernel sums to 0, so and . The same holds for .
Let be the CIC weight of particle on grid point , summed over the periodic images. Line L1 gives , and line L6 gives with the same (the cloud-in-cell page proves both forms). So
Exchanging the names and and using shows that the double sum equals its own negative, so it is 0. The same holds for the component. For the sum is the force on the single particle.
Claim 3 (momentum). Each pass through lines L10 to L13 leaves unchanged.
Proof. Line L10 adds to , 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 for the new forces.
Claim 4 (time reversibility). Let one pass of lines L10 to L13 map with forces to . Then the same pass maps to .
Proof. The forces depend only on the positions (Claim 1 and lines L1, L5 to L7). Write for the velocity after line L10, so and . Start the pass at . Line L10 gives . Line L11 gives , mod the box. Line L12 computes , and line L13 gives . The wrap mod the box does not matter, because the forces are periodic functions of the positions.
Complexity
In the real-RAM model with and , powers of 2: line L1 costs , lines L2 and L4 cost each (row transforms then column transforms), lines L3 and L5 cost , and lines L6 and L7 cost . So one force evaluation costs time and extra space, and steps of PM-RUN cost . The same holds in 3D with 8 grid points per particle. For comparison, direct summation costs per step, and a Barnes-Hut tree 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 , and the Green's function 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 . Gravity has and electrostatics . With the wrong sign, like masses repel.
- Not removing the mean. If line L3 divides by , the result is infinite or NaN. The mode 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 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 below about , where is the fastest frequency, for example the plasma frequency 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.
# 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
- 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)
- 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
- 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.
| 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 Y8XKSA Edit this page History Report an error Markdown