Algorithmadvanced
Smooth particle mesh Ewald
Also called SPME.
A variant of particle mesh Ewald that spreads charges with cardinal B-splines, so the forces are the exact gradient of a smooth approximate energy and need only two FFTs.
- Time
- O(N n^3 + K^3 log K) worst
- Space
- O(K^3 + N n) extra
- Where
- K = the number of grid points per side; N = the number of charges; n = the B-spline order
- Model
- Real RAM
- Properties
- conservativedeterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ulrich Essmann, Lalith Perera, Max L. Berkowitz, Tom Darden, Hsing Lee, Lee G. Pedersen, 1995
Smooth particle mesh Ewald (SPME) computes the reciprocal-space part of the Ewald sum on a grid, like particle mesh Ewald, but it spreads each charge with cardinal B-splines of order instead of Lagrange weights. B-splines are smooth, so the approximate energy is a differentiable function of the positions, and the forces are its exact gradient, computed by differentiating the weights. The method needs two FFTs per step, against four for PME, and a run with SPME forces conserves energy well. The price is that the forces no longer sum exactly to zero: the net force is a small random vector of the size of the force error. The P3M method also uses smooth assignment functions, which are B-splines in another form, with an optimised influence function in place of the Ewald factor.
In plain words
Particle mesh methods share each charge between nearby grid points, find the waves of the grid with a fast Fourier transform, and get the energy from the waves. Plain PME shares charge with weights that change sharply as a charge moves past a grid point, so the forces have small jumps.
Smooth PME uses weights shaped like smooth bumps. As a charge moves, its share of each grid point changes smoothly. The energy is then a smooth function of the positions, and the force is simply how fast the energy changes when a charge moves. Because force and energy match exactly, a simulation keeps its energy well. The grid does break the exact balance of action and reaction a little, so the forces do not add up to exactly zero.
The problem
The input is charges at in a cubic box of side and volume , the Ewald parameter , a grid of points per side, and the B-spline order . We use Gaussian units. The output is an approximation of the reciprocal energy
with and , and the forces .
The algorithm
The cardinal B-spline is a piecewise polynomial of degree on , built by and . The Euler exponential spline gives
exact at the grid points. So , with . Let and .
SPME-RECIPROCAL(q, r, L, α, K, n)- 1
for each charge j and axis a: u ← K r_ja / L, the n values M_n(u - g) and M_n'(u - g) for the n grid points g ≤ u - 2
Q(g) ← Σ_j q_j M_n(u_j1 - g_1) M_n(u_j2 - g_2) M_n(u_j3 - g_3), indices modulo K - 3
F ← conj(FFT3(Q)) - 4
for each m ≠ 0 with -K/2 < m_a ≤ K/2 do - 5
E ← E + ½ C(m) B(m) |F(m)|²; P(m) ← C(m) B(m) F(m) - 6
φ ← Re FFT3(P) ▷ φ = Θ ∗ Q, a convolution on the grid - 7
for each charge j: g_j ← Σ_g ∇_u[M_n(u_j1 - g_1) M_n(u_j2 - g_2) M_n(u_j3 - g_3)] φ(g) - 8
return (E, F_j = -q_j (K / L) g_j for each j)
The derivative of line L1 is , so it comes from the same recursion. For odd and , is undefined; the code sets there, as Essmann et al. suggest. The full Ewald energy adds the real-space and self parts.
Example
Take the same system as on the PME page: random charges with zero sum (seed 7), , , and the exact reciprocal energy . Relative errors of SPME, and the largest component of the net force:
| energy error | force error | net force | ||
|---|---|---|---|---|
| 8 | 4 | |||
| 8 | 6 | |||
| 8 | 8 | |||
| 16 | 4 | |||
| 16 | 6 | |||
| 16 | 8 |
On the grid with , order 6 gives an energy error 50 times smaller than PME with six Lagrange points, . The net force shrinks with the force error, but it is never zero. The forces agree with central differences of (step , , ) to , which is the error of the difference formula: they are the gradient of the approximate energy, even where they are not close to the exact forces.
For the B-spline is the cubic , with and . A charge exactly on a grid point gives , , of its charge to that point and its two neighbours on each axis.
Correctness
The proof below shows these claims:
- The spline identity is exact at the grid points, and between them its error is bounded by a constant times , a theorem of Essmann et al. (1995).
- What the code computes. Lines L1 to L5 compute , the reciprocal energy with the spline structure factor.
- The convolution. Line L6 gives the real array , and .
- The forces are the exact gradient of , and they are continuous for .
- The net force averages to zero. The energy is periodic under shifts of all charges by one grid spacing, so the net force has mean zero over a cell, but it is not zero in general.
The tests check the B-spline values and their derivatives, the zeros of for odd order, the gradient against central differences, the fall of the error with and , and a net force that is not zero but much smaller than the forces.
Proof: SPME computes a B-spline approximation of the reciprocal Ewald energy, and its forces are the exact gradient of that energyfull
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, and are the scaled coordinates of charge . The cardinal B-spline of order is on and 0 elsewhere, and
It is a piecewise polynomial of degree , positive on and zero outside, with continuous derivatives, for all , and . The exact reciprocal energy with is proved on the Ewald summation page.
Claim 1 (the spline identity is exact at the grid points). Let and suppose . Then for each integer ,
Proof. Put . Then , and the sum over is over because vanishes at the other integers.
Between grid points the right side is a spline interpolant of , and Essmann et al. (1995) show that its error is bounded by a constant times . So with for one coordinate,
where is the forward discrete Fourier transform, and the grid indices are reduced modulo , which does not change the sum because has period in . The energy depends only on , so the code needs only up to a phase: the function bspline_moduli uses , which is times the complex conjugate of because , so it has the same modulus. For odd and , ; the code sets there, as Essmann et al. suggest.
Claim 2 (lines L2 to L5 compute the SPME energy). Line L5 gives
which is .
Proof. Line L1 puts the weight on the grid point for . These are exactly the grid points with , since must lie in . Line L2 adds the products of the three weights, times , so the array is . Line L3 takes the conjugate of its FFT, which has the modulus of . The rest is the definition.
Claim 3 (the energy as a convolution). Let , the array of line L6. Then is real, for the real, even kernel whose transform is , and .
Proof. is real and even in , so is real and even, and the convolution theorem gives , with no factor because of this normalisation of . Since is real, is real. Since , .
Claim 4 (the forces are the exact gradient). Lines L7 and L8 give , and for the forces are continuous functions of the positions.
Proof. is a quadratic form in with a symmetric matrix , so . For the first coordinate, , and the other two are alike. The function bspline computes by the identity , from the values of that the recursion has at that point. Line L7 sums these products against and line L8 multiplies by . has a continuous first derivative for , so is in the positions and the forces are continuous.
So a run with SPME forces and a symplectic integrator conserves a shadow of the approximate energy plus the other Ewald parts, without a drift from the mesh (see the shadow Hamiltonian page for what this means and what can break it).
Claim 5 (the net force averages to zero but is not zero). For a shift of all charges, let . Then , has period in each direction, and the mean of over in one grid cell is 0.
Proof. The first part is the chain rule. Moving every by one grid spacing moves by one index, which does not change , so is periodic. The mean of the gradient of a periodic function over one period is 0.
Translation by a fraction of a cell does change , so in general ; the test finds a net force of of the scale of the forces at , . The exact energy is translation invariant, so the net force has the size of the force error, as Essmann et al. (1995) state.
Cost. Lines L1, L2 and L7 cost , lines L3 and L6 are two 3D FFTs, , and lines L4 and L5 cost . With at a fixed density, the total is .
Complexity
Spreading and the forces cost . The two FFTs cost and the loop over wave vectors . With a fixed grid spacing, , so the total is . The factors depend only on and and can be computed once. Memory is .
Properties
- Energy conserving. The forces are the gradient of , so a symplectic integrator keeps a shadow of the total energy without a drift from the mesh. This is a consequence of the shadow Hamiltonian theory, given a smooth enough total potential.
- Not momentum conserving. The net force is the gradient of under a common shift of all charges, which is not exactly constant. Essmann et al. (1995) note that the method conserves energy but not momentum, and that the average net force can be removed.
- High order. With or 8, a modest grid gives errors of or better in the example.
- Smoothness. has continuous derivatives, so the forces are in the positions.
Variants and improvements
- Other kernels. The same machinery computes the dispersion sum , and any kernel with a known Fourier transform.
- Multipoles. Point dipoles and higher multipoles are spread by derivatives of the B-splines.
- Removing the net force. Subtract the mean net force from each atom, or the mass-weighted mean, so that the centre of mass does not drift.
- Parallel FFTs. Large codes split the grid over processors, and some run the reciprocal part on fewer processors than the real-space part.
When to use it
SPME is the default method for long-range electrostatics in biomolecular simulation programs. Use it whenever the system is periodic and has more than a few thousand charges. For small systems, or to test an implementation, use the plain Ewald sum. For systems that are not periodic, or are periodic in fewer than three directions, other methods fit better.
Pitfalls
- An order that is too low. With the force is only continuous, not smooth, and the accuracy is poor. Use .
- Odd order and even . is undefined at . Set that term to zero or use an even order.
- Forgetting . Without the factors the energy is the energy of the smeared charges, with a large error at large .
- The net force. Over a long run it can accelerate the whole system. Remove it, or check the centre of mass.
- Off-grid derivatives. The forces need the derivative of the weights, not an interpolated field. Mixing the two loses the energy conservation.
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/smooth-particle-mesh-ewald/. The authors are listed in prov/WR206R.jsonl.
"""Smooth particle mesh Ewald (SPME): the reciprocal Ewald sum with cardinal B-splines.
This is the method of Essmann, Perera, Berkowitz, Darden, Lee and Pedersen
(1995). Units are Gaussian (the energy of two charges is q_i q_j / r). The box
is a cube of side L with K grid points per side, K a power of two. With the
scaled coordinate u = K x / L, each charge is spread to n grid points in each
direction with the cardinal B-spline weights M_n(u - g). Then
S(m) ~ b(m_1) b(m_2) b(m_3) F(Q)(m),
E_rec = (1/2) sum over m != 0 of C(m) B(m) |F(Q)(m)|^2,
C(m) = (4 pi / V) exp(-k^2 / (4 alpha^2)) / k^2, B(m) = |b(m_1) b(m_2) b(m_3)|^2,
with F(Q)(m) = sum_g Q(g) exp(2 pi i m.g / K) and k = 2 pi m / L. The energy is
E_rec = (1/2) sum_g Q(g) phi(g), with phi the convolution of Q with the
inverse transform of C B. The forces are the exact gradient of this
approximate energy: F_i = -sum_g (dQ(g) / dr_i) phi(g), and dM_n / du =
M_(n-1)(u) - M_(n-1)(u - 1).
Cost: Theta(N n^3) for spreading and forces, Theta(K^3 log K) for two FFTs.
Memory Theta(K^3). The forces conserve the approximate energy but their sum
is not exactly zero.
"""
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)]
for i, v in zip(idx, fft([g[i] for i in idx])):
g[i] = v
for y in range(k):
for z in range(k):
idx = [(x * k + y) * k + z for x in range(k)]
for i, v in zip(idx, fft([g[i] for i in idx])):
g[i] = v
return g
def bspline(w: float, n: int) -> tuple[list[float], list[float]]:
"""Values M_n(w + j) and derivatives M_n'(w + j) for j = 0, ..., n - 1, with 0 <= w < 1 and n >= 3."""
m = [w, 1.0 - w] # M_2(w), M_2(w + 1)
deriv = []
for order in range(3, n + 1):
if order == n:
# M_n'(x) = M_(n-1)(x) - M_(n-1)(x - 1)
deriv = [(m[j] if j < len(m) else 0.0) - (m[j - 1] if j >= 1 else 0.0) for j in range(n)]
new = []
for j in range(order):
x = w + j
a = m[j] if j < len(m) else 0.0
b = m[j - 1] if j >= 1 else 0.0
new.append((x * a + (order - x) * b) / (order - 1))
m = new
return m, deriv
def bspline_moduli(k: int, n: int) -> list[float]:
"""|b(m)|^2 for m = 0, ..., K - 1; set to 0 where the denominator vanishes (odd n, 2m = K)."""
at_int, _ = bspline(0.0, n) # M_n(j) for j = 0, ..., n - 1
out = []
for m in range(k):
den = sum(at_int[j + 1] * cmath.exp(2j * math.pi * m * j / k) for j in range(n - 1))
out.append(0.0 if abs(den) < 1e-10 else 1.0 / (abs(den) ** 2))
return out
def spme_reciprocal(
q: list[float], pos: list[Vec], box: float, alpha: float, kgrid: int, n: int,
) -> tuple[float, list[Vec]]:
"""Reciprocal Ewald energy and forces by smooth PME with B-splines of order n (degree n - 1)."""
k, npart = kgrid, len(q)
vol = box ** 3
stencils = []
for r in pos: # @line L1
st = []
for a in range(3):
u = (r[a] / box) * k % k
fl = math.floor(u)
vals, ders = bspline(u - fl, n)
# grid point fl - j has weight M_n(u - fl + j)
st.append(([(fl - j) % k for j in range(n)], vals, ders))
stencils.append(st)
grid = [0j] * (k * k * k)
for i in range(npart): # @line L2
(gx, mx, _), (gy, my, _), (gz, mz, _) = stencils[i]
for a in range(n):
for b in range(n):
base = (gx[a] * k + gy[b]) * k
wab = q[i] * mx[a] * my[b]
for c in range(n):
grid[base + gz[c]] += wab * mz[c]
fq = [v.conjugate() for v in fft3(grid, k)] # @line L3: F(Q)(m)
bmod = bspline_moduli(k, n)
tpl = 2.0 * math.pi / box
energy = 0.0
prod = [0j] * (k * k * k)
for ix in range(k): # @line L4
kx = tpl * (ix if ix <= k // 2 else ix - k)
for iy in range(k):
ky = tpl * (iy if iy <= k // 2 else iy - k)
for iz in range(k):
if ix == 0 and iy == 0 and iz == 0:
continue
kz = tpl * (iz if iz <= k // 2 else iz - k)
k2 = kx * kx + ky * ky + kz * kz
cb = (4.0 * math.pi / vol) * math.exp(-k2 / (4.0 * alpha * alpha)) / k2 * bmod[ix] * bmod[iy] * bmod[iz]
idx = (ix * k + iy) * k + iz
s = fq[idx]
energy += 0.5 * cb * (s.real * s.real + s.imag * s.imag) # @line L5
prod[idx] = cb * s
# line L6: phi(g) = sum_m C B F(Q)(m) exp(-2 pi i m.g / K), the convolution of theta_rec with Q
phi = [v.real for v in fft3(prod, k)] # @line L6
forces = []
scale = k / box
for i in range(npart): # @line L7
(gx, mx, dx), (gy, my, dy), (gz, mz, dz) = stencils[i]
f = [0.0, 0.0, 0.0]
for a in range(n):
for b in range(n):
base = (gx[a] * k + gy[b]) * k
for c in range(n):
p = phi[base + gz[c]]
f[0] -= dx[a] * my[b] * mz[c] * p
f[1] -= mx[a] * dy[b] * mz[c] * p
f[2] -= mx[a] * my[b] * dz[c] * p
forces.append([q[i] * scale * x for x in f]) # @line L8
return energy, forces
test_smooth_particle_mesh_ewald.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/smooth-particle-mesh-ewald/. The authors are listed in prov/WR206R.jsonl.
import math
import random
from smooth_particle_mesh_ewald import bspline, bspline_moduli, spme_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 SPME."""
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_bspline_values() -> None:
# M_4 at the integers is 1/6, 4/6, 1/6, and the weights form a partition of unity
vals, _ = bspline(0.0, 4)
assert all(abs(a - b) < 1e-15 for a, b in zip(vals, [0.0, 1 / 6, 4 / 6, 1 / 6]))
for n in (3, 4, 5, 6, 8):
for w in (0.0, 0.25, 0.5, 0.9):
vals, ders = bspline(w, n)
assert abs(sum(vals) - 1.0) < 1e-14
assert abs(sum(ders)) < 1e-14
h = 1e-6
vp, _ = bspline(w + h, n) if w + h < 1 else bspline(w, n)
vm, _ = bspline(w - h, n) if w - h >= 0 else bspline(w, n)
if 0 < w - h and w + h < 1:
for j in range(n):
assert abs((vp[j] - vm[j]) / (2 * h) - ders[j]) < 1e-7
def test_moduli_vanish_only_for_odd_order_at_nyquist() -> None:
assert bspline_moduli(8, 5)[4] == 0.0
assert min(bspline_moduli(8, 4)) > 0.0
assert abs(bspline_moduli(8, 4)[0] - 1.0) < 1e-14
def test_forces_are_the_exact_gradient_of_the_spme_energy() -> None:
q, pos = system(7, 6)
k, n = 8, 4
_, f = spme_reciprocal(q, pos, BOX, ALPHA, k, n)
h = 1e-6
for i in range(len(q)):
for a in range(3):
pp = [list(p) for p in pos]
pm = [list(p) for p in pos]
pp[i][a] += h
pm[i][a] -= h
num = -(spme_reciprocal(q, pp, BOX, ALPHA, k, n)[0] - spme_reciprocal(q, pm, BOX, ALPHA, k, n)[0]) / (2 * h)
assert abs(num - f[i][a]) < 1e-6 * max(1.0, abs(f[i][a]))
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 n in (4, 6, 8):
e, f = spme_reciprocal(q, pos, BOX, ALPHA, k, n)
errs[k, n] = (abs(e - e0) / abs(e0), rel_force_error(f, f0))
for k in (8, 16):
assert errs[k, 4][0] > errs[k, 6][0] > errs[k, 8][0]
assert errs[k, 4][1] > errs[k, 6][1] > errs[k, 8][1]
assert errs[16, 8][0] < 2e-6 and errs[16, 8][1] < 2e-5
def test_net_force_is_small_but_not_zero() -> None:
q, pos = system(7, 8)
_, f = spme_reciprocal(q, pos, BOX, ALPHA, 8, 4)
norm = math.sqrt(sum(x * x for fi in f for x in fi))
net = max(abs(sum(fi[a] for fi in f)) for a in range(3))
assert 1e-8 < net < 0.1 * norm
History
Darden, York and Pedersen (1993) introduced particle mesh Ewald with Lagrange interpolation. Two years later, Essmann, Perera, Berkowitz, Darden, Lee and Pedersen (1995) replaced the Lagrange weights by cardinal B-splines, an idea based on the Euler exponential spline. In the 1995 paper they used splines of order 4, 6 and 8, cubic, fifth and seventh degree, for low, medium and high accuracy. They wrote that the earlier PME obeyed Newton's third law to machine precision but did not conserve energy, and that the new method conserves energy but not momentum. The method is now the standard choice in programs for biomolecular simulation.
References
- 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 IV (cardinal B-spline interpolation, the factors b(m) and the analytic forces) and Section VI (results)
- 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 original method that SPME changes
- 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
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 WR206R Edit this page History Report an error Markdown