Algorithmcore
Particle mesh Ewald
Also called PME.
Computes the reciprocal-space part of the Ewald sum by spreading charges on a grid with Lagrange interpolation and using FFTs, in O(N log N) time for N charges.
- Time
- O(N p^3 + K^3 log K) worst
- Space
- O(K^3 + N p) extra
- Where
- K = the number of grid points per side; N = the number of charges; p = half the interpolation order
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tom Darden, Darrin York, Lee Pedersen, 1993
Particle mesh Ewald (PME) computes the long-range part of the electrostatic energy and forces in a periodic box, the reciprocal sum of Ewald summation, on a regular grid. Each charge is spread to the nearest grid points with the weights of Lagrange interpolation, so that each Fourier factor is replaced by its interpolant. The structure factor of all charges is then one 3D fast Fourier transform of the charge grid, and the reciprocal field is three more FFTs. The cost is , against for the tuned Ewald sum. The real-space part of the Ewald sum is kept as it is, with a short cutoff. Smooth particle mesh Ewald replaces the Lagrange weights by B-splines, which makes the forces the exact gradient of the energy. The older P3M method of Hockney and Eastwood also uses a grid and FFTs, but it builds an optimal influence function for its assignment scheme instead of interpolating the Ewald sum term by term.
In plain words
The slow part of Ewald summation adds up waves: for every wave, it visits every charge. That gets slow when there are many charges.
PME puts a grid of points into the box and gives each charge to the grid points around it, the way you share a weight between nearby posts. Once all charges sit on the grid, a fast Fourier transform finds the strength of every wave at once. The energy follows from those strengths. To get the forces, the method turns the waves back into a field on the grid, and each charge picks up the field from the same grid points it was given to. A finer grid and more points per charge give a more accurate answer.
The problem
The input is charges at in a cubic box of side , volume , the Ewald parameter , a grid of points per side, with a power of two, and an interpolation order . We use Gaussian units. The output is an approximation of the reciprocal energy
and of the reciprocal forces. With the scaled coordinates , the factor is a product of three factors, one per axis.
The algorithm
For one axis, is the weight of the grid point in the Lagrange interpolation of a function at from the points . Then , and for the charge grid .
PME-RECIPROCAL(q, r, L, α, K, p)- 1
for each charge j: u_j ← K r_j / L, and the 2p Lagrange weights W(u_ja, ·) for each axis a - 2
Q(g) ← Σ_j q_j W(u_j1, g_1) W(u_j2, g_2) W(u_j3, g_3), indices modulo K - 3
S̃ ← conj(FFT3(Q)) - 4
for each m ≠ 0 with -K/2 < m_a ≤ K/2 do - 5
E ← E + (2π / V) G(m) |S̃(m)|²; A_d(m) ← k_d G(m) S̃(m) for d = 1, 2, 3 - 6
field_d(g) ← -(4π / V) Im FFT3(A_d)(g) for d = 1, 2, 3 - 7
F_j ← q_j Σ_g W(u_j1, g_1) W(u_j2, g_2) W(u_j3, g_3) field(g) for each charge j - 8
return (E, F)
Line L5 leaves out the Nyquist component of , which has no sign. The total Ewald energy adds the real-space and self parts of the Ewald summation page, with a cutoff small enough that a linked cell list finds the pairs in time.
Example
Take random charges with zero sum (seed 7) in a box of side , with . The exact reciprocal energy, summed term by term over , is . The table shows the relative errors of PME:
| order | energy error | force error | |
|---|---|---|---|
| 8 | 2 | ||
| 8 | 4 | ||
| 8 | 6 | ||
| 16 | 2 | ||
| 16 | 4 | ||
| 16 | 6 |
The force error is the root mean square of the error vectors divided by that of the exact forces. Both errors fall with a finer grid and with a higher order, and the order helps more on the finer grid. In every run the sum of the forces is below , zero up to rounding.
For one charge, the weights of line L1 are those of Lagrange interpolation. With and , the two points are 2 and 3, with weights 0.7 and 0.3. With the four points are 1 to 4, with weights , and these reproduce exactly.
Correctness
The proof below shows these claims:
- Interpolation error. For each wave vector, the interpolated Fourier factor differs from the exact one by at most , a theorem. Essmann et al. (1995) give a sharper bound of the same form.
- What the code computes. Lines L1 to L5 compute the reciprocal energy with the interpolated structure factor, over the wave vectors that the grid resolves.
- The field. Line L6 is the exact reciprocal field of the interpolated charges at the grid points, and line L7 interpolates it back with the same weights.
- Zero net force. Because the same weights spread the charges and pick up the field, the forces add up to exactly zero in exact arithmetic.
The forces are not the gradient of the computed energy, because the Lagrange weights are not differentiable at the grid points. So a PME run does not conserve energy exactly, even with a symplectic integrator. The tests check the FFT against its definition, the Lagrange weights against polynomials, the fall of the errors with and , the zero net force, and the invariance under a shift by one grid spacing.
Proof: PME computes an interpolated reciprocal Ewald sum whose error falls with the grid and the order, and its forces sum to zerofull
We use Gaussian units and the line numbers of the pseudocode. The box is a cube of side and volume , with grid points per side. For a charge at , write for its scaled coordinates. The exact reciprocal energy is
with , as proved on the Ewald summation page. For one coordinate, is the weight that piecewise Lagrange interpolation with the points gives to the point , and 0 for other points.
Claim 1 (interpolation error). For each integer and real ,
Proof. Let and . The sum is the value at of the polynomial of degree less than that interpolates at the points . Apply the Lagrange remainder to the real and imaginary parts, or use the Hermite integral form of the remainder for complex : the error is at most . With , the points below or at are at distances , each at most , and the points above are at distances , each at most . So the product is at most .
Essmann et al. (1995) give a sharper bound of the same form. In both, the error falls with at the rate for each fixed , and the large terms, where the bound is poor, carry the small factor .
Claim 2 (what lines L1 to L5 compute). Line L3 gives , and line L5 gives over with .
Proof. Line L2 adds to , with the indices reduced modulo . Since has period in , the reduction does not change , which is the complex conjugate of the forward FFT of the real array . Line L4 maps each FFT index to the representative of modulo in .
By Claim 1, for each as or at fixed small. The wave vectors with are left out, and their terms are at most , which is small when .
Claim 3 (the grid field). Line L6 gives, for each grid point and direction ,
with the Nyquist components left out, and line L7 gives with .
Proof. The forward FFT of the array is , and . Multiplying by gives the formula. The exact reciprocal force on a charge at is times the same expression with replaced by and by (see the Ewald page), so is the reciprocal field at the grid points, and line L7 interpolates it to the charges with the weights of line L2.
The Nyquist component is left out because and are the same index, and the field term has opposite signs for the two. Its true weight is small when the grid is fine enough.
Claim 4 (zero net force). in exact arithmetic.
Proof. By Claim 3 and line L2, . For direction , since is real,
What is not claimed. The forces are not the gradient of : the gradient would need the derivative of the weights, and piecewise Lagrange weights are not differentiable at the integers. So a run with PME forces does not conserve any energy exactly, even with a symplectic integrator. Essmann et al. (1995) report this: the original PME conserves momentum to machine precision but not energy. The smooth particle mesh Ewald method makes the opposite choice.
Cost. Lines L1, L2 and L7 cost for grid points per charge. Lines L3 and L6 are four 3D FFTs of points, . Lines L4 and L5 cost . With the grid spacing fixed as grows at a fixed density, , and the total is for the reciprocal part. The real-space part with a fixed cutoff costs with a cell list.
Complexity
Spreading and interpolation cost , since each charge touches grid points. The four FFTs of points cost , and the loop over wave vectors costs . At a fixed density and accuracy, the grid spacing is fixed, so and the total is . The memory is for the grids. The real-space part costs with a fixed cutoff.
Properties
- Momentum conservation. The forces sum to zero up to rounding, so the centre of mass does not drift.
- No energy conservation. The forces are not the gradient of any function, so the total energy can drift slowly over a long run.
- Accuracy is tunable. Error falls like for each wave vector, and the large wave vectors that interpolate badly carry the small factor .
- Parallel structure. The work is local spreading and interpolation plus FFTs, the same pattern as the particle mesh method of gravity codes.
Variants and improvements
- Smooth PME. Smooth particle mesh Ewald uses cardinal B-splines and gets the forces by differentiating the weights: two FFTs, smooth forces, and energy conservation, at the cost of a small net force.
- P3M. The P3M method uses an assignment such as cloud-in-cell and an influence function optimised for that assignment.
- Analytic differentiation. The forces can also come from the derivative of the weights, as in SPME, or from finite differences on the grid.
- Other potentials. The same mesh approach works for the dispersion sum.
When to use it
Use PME for the long-range electrostatics of large periodic systems, such as proteins and membranes in water, where the plain Ewald sum is too slow. Today most programs use the smooth variant. PME with Lagrange interpolation still matters when the exact cancellation of the net force is more important than the conservation of energy, and as a step to understand SPME.
Pitfalls
- A coarse grid with a large . If is not well above , the wave vectors that the grid cannot resolve carry real weight, and the error is large. Raise or lower and lengthen the real-space cutoff.
- Energy drift. With interpolated forces, a long run can gain or lose energy. Check the drift, or use SPME.
- Wrong signs in the FFT. The structure factor uses , and most FFT libraries use in the forward transform. A conjugate in the wrong place gives the right energy and wrong forces.
- The Nyquist component. It has no defined sign for the field. Drop it, or use an odd .
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-ewald/. The authors are listed in prov/QV4418.jsonl.
"""Particle mesh Ewald (PME) with Lagrange interpolation: the reciprocal part of the Ewald sum on a grid.
This is the method of Darden, York and Pedersen (1993). Units are Gaussian
(the energy of two charges is q_i q_j / r). The box is a cube of side L with a
grid of K points per side, K a power of two. Each charge is spread to the 2p
nearest grid points in each direction with the weights of piecewise Lagrange
interpolation of order 2p, so exp(i k . r_j) is replaced by its interpolant.
The structure factor is then one 3D FFT of the charge grid, and
E_rec = (2 pi / V) sum over m != 0 of exp(-k^2 / (4 alpha^2)) / k^2 |S(m)|^2,
with k = 2 pi m / L for |m_a| <= K / 2. The forces come from the reciprocal
electric field, computed on the grid by multiplying by i k in Fourier space
(three more FFTs), and interpolated back to the charges with the same weights.
Because the same weights spread the charges and pick up the field, the
reciprocal forces sum to zero up to rounding, but they are not exactly
minus the gradient of the interpolated energy.
Cost: Theta(N p^3) for spreading and interpolation, Theta(K^3 log K) for the
four FFTs. Memory Theta(K^3). The real-space and self parts of the Ewald sum
are not computed here: see the ewald-summation page.
"""
import cmath
import math
Vec = list[float]
def fft(a: list[complex]) -> list[complex]:
"""Radix-2 FFT, X_m = sum_g a_g exp(-2 pi i m g / n), for len(a) a power of two."""
n = len(a)
if n == 1:
return list(a)
even, odd = fft(a[0::2]), fft(a[1::2])
out = [0j] * n
for m in range(n // 2):
t = cmath.exp(-2j * math.pi * m / n) * odd[m]
out[m] = even[m] + t
out[m + n // 2] = even[m] - t
return out
def fft3(grid: list[complex], k: int) -> list[complex]:
"""3D FFT of a K^3 grid stored flat with index (x K + y) K + z."""
g = list(grid)
for x in range(k):
for y in range(k):
base = (x * k + y) * k
g[base:base + k] = fft(g[base:base + k])
for x in range(k):
for z in range(k):
idx = [(x * k + y) * k + z for y in range(k)]
col = fft([g[i] for i in idx])
for i, v in zip(idx, col):
g[i] = v
for y in range(k):
for z in range(k):
idx = [(x * k + y) * k + z for x in range(k)]
col = fft([g[i] for i in idx])
for i, v in zip(idx, col):
g[i] = v
return g
def lagrange_weights(u: float, p: int) -> tuple[int, list[float]]:
"""Weights of the 2p grid points floor(u) - p + 1, ..., floor(u) + p for Lagrange interpolation at u."""
first = math.floor(u) - p + 1
xs = [first + j for j in range(2 * p)]
w = []
for j, xj in enumerate(xs):
c = 1.0
for l, xl in enumerate(xs):
if l != j:
c *= (u - xl) / (xj - xl)
w.append(c)
return first, w
def pme_reciprocal(
q: list[float], pos: list[Vec], box: float, alpha: float, kgrid: int, p: int,
) -> tuple[float, list[Vec]]:
"""Reciprocal Ewald energy and forces by PME with Lagrange interpolation of order 2p."""
n, k = len(q), kgrid
vol = box ** 3
# line L1: scaled coordinates and the interpolation weights of each charge
stencils = []
for r in pos: # @line L1
stencils.append([lagrange_weights((r[a] / box) * k % k, p) for a in range(3)])
grid = [0j] * (k * k * k)
for i in range(n): # @line L2
(fx, wx), (fy, wy), (fz, wz) = stencils[i]
for a, wa in enumerate(wx):
gx = (fx + a) % k
for b, wb in enumerate(wy):
gy = (fy + b) % k
for c, wc in enumerate(wz):
grid[(gx * k + gy) * k + (fz + c) % k] += q[i] * wa * wb * wc
# line L3: S(m) = sum_g Q(g) exp(+2 pi i m.g / K) is the conjugate of the forward FFT
sk = [v.conjugate() for v in fft3(grid, k)] # @line L3
energy = 0.0
tpl = 2.0 * math.pi / box
ak = [[0j] * (k * k * k) for _ in range(3)]
for mx in range(k): # @line L4
kx = tpl * (mx if mx <= k // 2 else mx - k)
for my in range(k):
ky = tpl * (my if my <= k // 2 else my - k)
for mz in range(k):
if mx == 0 and my == 0 and mz == 0:
continue
kz = tpl * (mz if mz <= k // 2 else mz - k)
k2 = kx * kx + ky * ky + kz * kz
g = math.exp(-k2 / (4.0 * alpha * alpha)) / k2
idx = (mx * k + my) * k + mz
s = sk[idx]
energy += (2.0 * math.pi / vol) * g * (s.real * s.real + s.imag * s.imag) # @line L5
# i k derivative; the Nyquist component of each direction has no sign, so it is dropped
for d, kd, md in ((0, kx, mx), (1, ky, my), (2, kz, mz)):
if 2 * md != k:
ak[d][idx] = kd * g * s
# line L6: field on the grid, E_d(g) = -(4 pi / V) Im sum_m k_d G(m) S(m) exp(-2 pi i m.g / K)
field = [[-(4.0 * math.pi / vol) * v.imag for v in fft3(ak[d], k)] for d in range(3)] # @line L6
forces = []
for i in range(n): # @line L7
(fx, wx), (fy, wy), (fz, wz) = stencils[i]
f = [0.0, 0.0, 0.0]
for a, wa in enumerate(wx):
gx = (fx + a) % k
for b, wb in enumerate(wy):
gy = (fy + b) % k
for c, wc in enumerate(wz):
idx = (gx * k + gy) * k + (fz + c) % k
w = q[i] * wa * wb * wc
for d in range(3):
f[d] += w * field[d][idx]
forces.append(f)
return energy, forces # @line L8
test_particle_mesh_ewald.py 97 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/particle-mesh-ewald/. The authors are listed in prov/QV4418.jsonl.
import math
import random
from particle_mesh_ewald import fft, lagrange_weights, pme_reciprocal
BOX, ALPHA = 6.0, 0.8
def system(seed: int, n: int) -> tuple[list[float], list[list[float]]]:
rng = random.Random(seed)
pos = [[rng.uniform(0, BOX) for _ in range(3)] for _ in range(n)]
q = [rng.uniform(-1, 1) for _ in range(n - 1)]
q.append(-sum(q))
return q, pos
def exact_reciprocal(q, pos, box, alpha, mmax):
"""The reciprocal Ewald sum term by term, the reference for PME."""
vol = box ** 3
e, f = 0.0, [[0.0] * 3 for _ in q]
for mx in range(-mmax, mmax + 1):
for my in range(-mmax, mmax + 1):
for mz in range(-mmax, mmax + 1):
if mx == my == mz == 0:
continue
k = [2 * math.pi * m / box for m in (mx, my, mz)]
k2 = sum(x * x for x in k)
g = math.exp(-k2 / (4 * alpha * alpha)) / k2
ph = [sum(a * b for a, b in zip(k, p)) for p in pos]
sr = sum(qi * math.cos(t) for qi, t in zip(q, ph))
si = sum(qi * math.sin(t) for qi, t in zip(q, ph))
e += 2 * math.pi / vol * g * (sr * sr + si * si)
for i in range(len(q)):
c = 4 * math.pi / vol * q[i] * g * (math.sin(ph[i]) * sr - math.cos(ph[i]) * si)
for a in range(3):
f[i][a] += c * k[a]
return e, f
def rel_force_error(f, f0) -> float:
num = sum((a - b) ** 2 for u, v in zip(f, f0) for a, b in zip(u, v))
den = sum(a * a for u in f0 for a in u)
return math.sqrt(num / den)
def test_fft_against_the_definition() -> None:
rng = random.Random(11)
a = [complex(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(16)]
out = fft(a)
for m in range(16):
ref = sum(a[g] * complex(math.cos(2 * math.pi * m * g / 16), -math.sin(2 * math.pi * m * g / 16)) for g in range(16))
assert abs(out[m] - ref) < 1e-12
def test_lagrange_weights_reproduce_polynomials() -> None:
for p in (1, 2, 3):
for u in (0.0, 0.3, 4.71, 9.99):
first, w = lagrange_weights(u, p)
for deg in range(2 * p):
val = sum(wj * (first + j) ** deg for j, wj in enumerate(w))
assert abs(val - u ** deg) < 1e-9 * max(1.0, u ** deg)
def test_error_falls_with_order_and_grid() -> None:
q, pos = system(7, 8)
e0, f0 = exact_reciprocal(q, pos, BOX, ALPHA, 9)
errs = {}
for k in (8, 16):
for p in (1, 2, 3):
e, f = pme_reciprocal(q, pos, BOX, ALPHA, k, p)
errs[k, p] = (abs(e - e0) / abs(e0), rel_force_error(f, f0))
for k in (8, 16):
assert errs[k, 1][0] > errs[k, 2][0] > errs[k, 3][0]
assert errs[k, 1][1] > errs[k, 2][1] > errs[k, 3][1]
for p in (1, 2, 3):
assert errs[16, p][0] < errs[8, p][0]
assert errs[16, 3][0] < 2e-3 and errs[16, 3][1] < 1e-3
def test_reciprocal_forces_sum_to_zero() -> None:
q, pos = system(8, 10)
for k, p in ((8, 1), (8, 3), (16, 2)):
_, f = pme_reciprocal(q, pos, BOX, ALPHA, k, p)
for a in range(3):
assert abs(sum(fi[a] for fi in f)) < 1e-12
def test_shift_by_one_grid_spacing_changes_nothing() -> None:
q, pos = system(9, 6)
e, f = pme_reciprocal(q, pos, BOX, ALPHA, 8, 2)
shifted = [[x + BOX / 8 for x in p] for p in pos]
e2, f2 = pme_reciprocal(q, shifted, BOX, ALPHA, 8, 2)
assert abs(e - e2) < 1e-12
assert rel_force_error(f2, f) < 1e-10
History
Darden, York and Pedersen (1993) introduced particle mesh Ewald with Lagrange interpolation of the Fourier factors, as an method for Ewald sums in large systems. Essmann, Perera, Berkowitz, Darden, Lee and Pedersen (1995) replaced the Lagrange weights by B-splines, and compared the two in their Table I. In that paper they note that the original PME conserved momentum to machine precision, because the forces were interpolated symmetrically, but did not conserve energy. The P3M method of Hockney and Eastwood is an earlier grid method for the same sum.
References
- Tom Darden, Darrin York and Lee Pedersen, Particle mesh Ewald, An N log(N) method for Ewald sums in large systems, Journal of Chemical Physics 98(12), 1993, 10089-10092, the method with Lagrange interpolation of the structure factor
- Ulrich Essmann, Lalith Perera, Max L. Berkowitz, Tom Darden, Hsing Lee and Lee G. Pedersen, A smooth particle mesh Ewald method, Journal of Chemical Physics 103(19), 1995, 8577-8593, Section III (piecewise Lagrangian interpolation and its error bound) and Table I (accuracy of Lagrange and B-spline PME)
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 6.3, Particle-particle particle-mesh methods
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 QV4418 Edit this page History Report an error Markdown