Algorithmcore
Ewald summation
Also called Ewald method.
Computes the Coulomb energy and forces of charges in a periodic box by splitting each interaction into a short-range sum in real space and a smooth sum over wave vectors.
- Time
- O(N^2 + N M^3) worst
- Space
- O(N) extra
- Where
- M = the largest wave-vector index m_max; N = the number of charges
- Model
- Real RAM
- Properties
- deterministic
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Paul Peter Ewald, Simon W. de Leeuw, John W. Perram, Edward R. Smith, 1921
Ewald summation computes the electrostatic energy and forces of point charges in a periodic box, where each charge interacts with every other charge and with all of their periodic images. The direct sum over images converges slowly, and only conditionally: its value depends on the order of the terms. Ewald's method writes as . The first part is short range, so it is summed over the neighbours inside a cutoff. The second part is smooth, so its periodic sum converges fast as a Fourier series over wave vectors. A self term and, if needed, a surface term complete the result. With a well chosen , the cost is for charges. Particle mesh Ewald and smooth particle mesh Ewald keep the real-space part and compute the reciprocal part on a grid with the fast Fourier transform, in time. The P3M method is an older grid method for the same sum.
In plain words
Charges in a crystal or a liquid push and pull each other over long distances. In a simulation the box repeats in every direction, so each charge feels an endless number of copies. Adding up those copies one by one is slow, and the answer even depends on the order in which you add them.
Ewald's trick is to put a soft cloud of opposite charge around each point charge. The point and its cloud together act only at short range, so you add up only the near neighbours. Then you add back the clouds. A sum of smooth clouds is easy to compute as a sum of waves, and only a few waves matter. One correction removes the energy of each cloud with its own charge. The two sums together give the exact answer, and the width of the cloud only moves work from one sum to the other.
The problem
The input is point charges at positions in a cubic box of side and volume , with , and the boundary condition at infinity. We use Gaussian units, so two charges at distance have energy . The output is the energy
and the forces . The sum runs over integer vectors , and the prime leaves out when . The series converges only conditionally. We take the limit of sums over growing spheres of images, with either a conductor around the sphere (tin foil boundary conditions, the usual choice in simulations) or a vacuum.
The algorithm
With , for integer vectors , and , the energy is
with for tin foil and for a vacuum.
EWALD(q, r, L, α, r_c, m_max, surface)- 1
V ← L³; E_real, E_rec ← 0; f_i ← 0 for each i - 2
for each pair i ≤ j and each image n with d = |r_ij + nL| < r_c, leaving out i = j, n = 0 do - 3
E_real ← E_real + w q_i q_j erfc(α d) / d ▷ w = 1/2 if i = j, else 1 - 4
if i ≠ j then add the pair force to f_i and subtract it from f_j - 5
for each m with 0 < |m| ≤ m_max, one of each pair m, -m do - 6
k ← 2π m / L; S ← Σ_j q_j exp(i k · r_j) - 7
E_rec ← E_rec + 2 (2π / V) G(k) |S|² ▷ G(k) = exp(-k² / 4α²) / k² - 8
f_i ← f_i + 2 (4π / V) q_i G(k) Im(exp(i k · r_i) conj(S)) k for each i - 9
E_self ← -(α / √π) Σ_i q_i² - 10
if surface = vacuum then E_surf ← (2π / 3V) |M|², f_i ← f_i - (4π / 3V) q_i M, with M = Σ_i q_i r_i - 11
return (E_real + E_rec + E_self + E_surf, f)
The pair force of line L4 is . The terms for and in line L7 are equal, since is the complex conjugate of , so the loop visits half of the wave vectors and doubles each term. The implementation visits all pairs; a production code finds the pairs within with a linked cell list.
Example
The Madelung constant of rock salt. Put 8 ions of charge on the corners of a cube of side , alternating in sign, in a periodic box of side . This is the conventional cell of NaCl. The energy per ion pair is , where is the Madelung constant, so . With and , so that both sums have converged:
| 1.0 | 0.008283 | 1.7475646 | ||
| 1.5 | 0.506084 | 1.7475646 | ||
| 2.0 | 2.146908 | 1.7475646 | ||
| 2.5 | 4.303281 | 1.7475646 |
The parts change by orders of magnitude, but their sum does not. The value agrees with the known Madelung constant of NaCl, 1.747565. A small puts the work in real space, and a large puts it in reciprocal space. With , and the result is already .
The order of summation matters. Take four charges at random positions (seed 5) in a box of side 3. Sum directly over all images inside a sphere of boxes:
| 4 | 8 | 16 | |
|---|---|---|---|
| direct sum |
The spherical sums converge to the Ewald energy with a vacuum outside the sphere, . The tin foil energy is . The difference, , is the surface term of the dipole moment of the box. Neither value is wrong: they are the energies of two different physical systems.
Correctness
The proof below shows these claims:
- The split is exact. For each , the four parts add up to the limit of the spherical sums. The erfc part converges absolutely. The erf part is the potential of a lattice of Gaussian charges, and the Poisson equation turns it into the Fourier series . The self term removes the energy of each Gaussian with its own point charge. This is a theorem.
- The code computes the truncated sums. Lines L2 to L8 compute over the images inside and over .
- The forces are the exact gradient of the computed energy, between the moments when an image crosses the cutoff sphere.
- Truncation error. Each left-out term is at most of size , up to slowly changing factors, with . That the total error behaves the same way is a heuristic, supported by the estimates of Kolafa and Perram (1992).
The tests check the Madelung constant, the independence of to , the limit of the spherical sums, the forces against central differences of the energy, zero net force, and periodicity.
Proof: The Ewald split gives the periodic Coulomb energy, and the code computes its truncated sums and their exact gradientfull
We use Gaussian units and the line numbers of the pseudocode. There are point charges at in a cubic box of side and volume , with . Write , and let be the sum over integer vectors that leaves out when . The periodic Coulomb energy is
This series converges only conditionally, so its value depends on the order of summation. We take the limit of sums over growing spheres of images, as in de Leeuw, Perram and Smith (1980).
Claim 1 (the split). For each and , , and is the potential at distance of a unit charge spread as the Gaussian .
Proof. The first part holds because . For the second, Gauss's law says that the field of a spherical charge at distance is the charge inside radius divided by . The charge of inside radius is , and this is times . Both potentials go to 0 as , so they are equal.
Claim 2 (the four parts). In the limit of spheres, with
, for integer vectors , and .
Proof. Split each term of by Claim 1. The erfc part decays faster than any power, so it converges absolutely, in any order, to . For the erf part, add the missing terms , , whose value is the limit as . With the factor they add , which takes away again. The full smooth sum is , where is the potential of a periodic lattice of Gaussians. The sum over diverges for one pair, but the sum weighted by converges for a neutral system, and an additive constant in cancels because . The density is smooth and periodic, with Fourier coefficients , and the Poisson equation gives the coefficients for . The term is where the order of summation enters: for a neutral system it is with conducting (tin foil) surroundings, and for a sphere of images in a vacuum it is the dipole term , by the analysis of de Leeuw, Perram and Smith (1980), which we do not repeat. Then
which is .
So the sum of the four parts does not depend on . The test checks this to .
Claim 3 (the code computes the truncated parts). Lines L2 and L3 compute over the images with . Lines L5 to L7 compute over . Lines L9 and L10 compute and .
Proof. The double sum over ordered pairs is twice the sum over , so the factor goes away for and stays for , as in line L3. The images of are the same for every representative of modulo , so the code may first take the minimum image and then visit all shifts with , which include every image closer than . In line L7, , so the terms for and are equal. The code visits one of each pair, the ones after in lexicographic order, and doubles the term.
Claim 4 (the forces are the exact gradient). For fixed sets of images and wave vectors, lines L4, L8 and L10 give of the computed energy.
Proof. For , , and the force on is with . This is the factor of line L4, which adds it to and subtracts it from . Terms with do not depend on . For line L8, , and . Multiplying by gives the force of line L8, doubled for the pair . For line L10, with .
The test checks Claim 4 against central differences of the energy. The energy as a function of the positions jumps when an image crosses the sphere of radius , by at most , so Claim 4 holds between such crossings.
Claim 5 (truncation error, heuristic). Each omitted real-space term is at most , and each omitted reciprocal term is at most with .
Proof. The bound for follows from . The second bound uses and that falls with .
The number of omitted terms grows only like a power of and , so with both tails are times a factor that changes slowly. This is a heuristic for the size of the error, not a bound on the sum of the tails. Sharper estimates, with the constants, are in Kolafa and Perram (1992).
Claim 6 (cost). Take fixed and free. At a fixed density , the real-space part costs with a cell list, and the reciprocal part costs . The sum is smallest for , that is, , and then both parts cost .
Proof. Each charge meets about charges inside , and there are about wave vectors, each costing . The product of the two costs is , which does not depend on , so their sum is smallest when they are equal, at .
The implementation does not use a cell list: its real-space loop visits all pairs, so its cost is for the real part.
Complexity
The real-space part costs one evaluation of erfc per pair within . The reciprocal part costs per wave vector. With the error level fixed, the real part costs about with a cell list and the reciprocal part about . The product does not depend on , so the sum is smallest when the two are equal, at , and the total is (Perram, Petersen and de Leeuw 1988). The implementation visits all pairs, so it costs with , and extra space. Mesh methods reduce the reciprocal part to with a fixed small cutoff.
Properties
- Exact in the limit. Every truncation error goes to 0 as and grow, at any fixed .
- Smooth forces. The reciprocal forces are smooth functions of the positions, and with a large enough the jump of the real-space energy at the cutoff is negligible.
- Momentum. The pair forces of line L4 cancel, and the reciprocal forces sum to zero because is real.
- Needs a neutral box. For a net charge the term diverges. Codes add a uniform background charge, which changes the energy by a constant.
Variants and improvements
- Particle mesh methods. Particle mesh Ewald, smooth particle mesh Ewald and P3M spread the charges on a grid and compute with FFTs in time.
- Other potentials. The same split works for dispersion, , and for dipoles and higher multipoles.
- Slabs. For a system periodic in two directions, a correction for the dipole normal to the slab, or a two-dimensional form of the sum, is used.
- Tree and multipole methods. The fast multipole method computes the sum in time without Fourier transforms.
When to use it
Use the Ewald sum for charged or polar systems in a periodic box: ionic crystals, molten salts, water, proteins in solution. In its plain form it is good for a few hundred to a few thousand charges, and as a reference to test a mesh method. For large systems use a mesh method. Do not use a plain cutoff for Coulomb forces: the error is large and the structure of water and ions changes.
Pitfalls
- A net charge. The sum is not defined. Neutralise the box, or know that the background charge adds a constant.
- The wrong boundary condition. Tin foil and vacuum give different energies and different forces when the box has a dipole moment, as the example shows. Most codes use tin foil.
- Badly balanced parameters. If is small, the real-space error is large, and if is small, the reciprocal error is large. Check that the energy does not change with .
- A cutoff longer than half the box with the minimum image only. The real-space sum then misses images. The implementation loops over all images inside .
- The self term. Forgetting it, or using it with the wrong , shifts the energy by a large constant, as the column shows.
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/ewald-summation/. The authors are listed in prov/674E3C.jsonl.
"""Ewald summation of the Coulomb energy and forces of point charges in a cubic periodic box.
Units are Gaussian: the energy of two charges at distance r is q_i q_j / r.
The splitting parameter alpha has the unit 1 / length. The energy is
E = E_real + E_rec + E_self + E_surf,
E_real = sum over pairs and images |r_ij + n L| < r_c of q_i q_j erfc(alpha d) / d,
E_rec = (2 pi / V) sum over k != 0 of exp(-k^2 / (4 alpha^2)) / k^2 |S(k)|^2,
S(k) = sum_j q_j exp(i k . r_j), k = 2 pi m / L for integer vectors m,
E_self = -(alpha / sqrt(pi)) sum_i q_i^2,
E_surf = 0 for tin foil (conducting) boundary conditions, or
(2 pi / (3 V)) |sum_i q_i r_i|^2 for a vacuum outside a large sphere.
The system must be neutral. Cost: the real-space loop visits the pairs and
images inside r_c, and the reciprocal loop costs Theta(N) for each of the
O(m_max^3) wave vectors.
"""
import math
Vec = list[float]
def ewald(
q: list[float], pos: list[Vec], box: float, alpha: float, rc: float,
mmax: int, surface: str = "tinfoil",
) -> tuple[float, list[Vec], dict]:
"""Ewald energy, forces and the parts of the energy for a neutral system in a cubic box."""
n = len(q)
if abs(sum(q)) > 1e-12 * max(1.0, sum(abs(x) for x in q)):
raise ValueError("the system must be neutral")
vol = box ** 3 # @line L1
f = [[0.0, 0.0, 0.0] for _ in range(n)]
# real-space sum over pairs i < j and over the images of each pair; i = j only for n != 0
e_real = 0.0
nimg = int(math.ceil(rc / box)) + 1
rc2 = rc * rc
two_a_sqrtpi = 2.0 * alpha / math.sqrt(math.pi)
for i in range(n): # @line L2
for j in range(i, n):
d0 = [pos[i][a] - pos[j][a] for a in range(3)]
d0 = [x - box * round(x / box) for x in d0]
for nx in range(-nimg, nimg + 1):
for ny in range(-nimg, nimg + 1):
for nz in range(-nimg, nimg + 1):
if i == j and nx == 0 and ny == 0 and nz == 0:
continue
d = [d0[0] + nx * box, d0[1] + ny * box, d0[2] + nz * box]
r2 = d[0] * d[0] + d[1] * d[1] + d[2] * d[2]
if r2 >= rc2:
continue
r = math.sqrt(r2)
w = 0.5 if i == j else 1.0
e_real += w * q[i] * q[j] * math.erfc(alpha * r) / r # @line L3
if i != j:
# -dU/dr / r for U = q_i q_j erfc(alpha r) / r
g = q[i] * q[j] * (math.erfc(alpha * r) / r + two_a_sqrtpi * math.exp(-alpha * alpha * r2)) / r2
for a in range(3): # @line L4
f[i][a] += g * d[a]
f[j][a] -= g * d[a]
# reciprocal sum over a half space of m (k and -k give the same term)
e_rec = 0.0
tpl = 2.0 * math.pi / box
for mx in range(0, mmax + 1): # @line L5
for my in range(-mmax, mmax + 1):
for mz in range(-mmax, mmax + 1):
if (mx, my, mz) <= (0, 0, 0): # keep one of each pair m, -m
continue
if mx * mx + my * my + mz * mz > mmax * mmax:
continue
k = (tpl * mx, tpl * my, tpl * mz)
k2 = k[0] * k[0] + k[1] * k[1] + k[2] * k[2]
gk = math.exp(-k2 / (4.0 * alpha * alpha)) / k2
cs = [math.cos(k[0] * p[0] + k[1] * p[1] + k[2] * p[2]) for p in pos]
sn = [math.sin(k[0] * p[0] + k[1] * p[1] + k[2] * p[2]) for p in pos]
sre = sum(qj * c for qj, c in zip(q, cs)) # @line L6
sim = sum(qj * s for qj, s in zip(q, sn))
e_rec += 2.0 * (2.0 * math.pi / vol) * gk * (sre * sre + sim * sim) # @line L7
for i in range(n):
# Im(exp(i k.r_i) S*) = sin_i Re S - cos_i Im S
c = 2.0 * (4.0 * math.pi / vol) * q[i] * gk * (sn[i] * sre - cs[i] * sim)
for a in range(3): # @line L8
f[i][a] += c * k[a]
e_self = -alpha / math.sqrt(math.pi) * sum(x * x for x in q) # @line L9
e_surf = 0.0
if surface == "vacuum": # @line L10
dip = [sum(q[i] * pos[i][a] for i in range(n)) for a in range(3)]
e_surf = 2.0 * math.pi / (3.0 * vol) * sum(x * x for x in dip)
for i in range(n):
for a in range(3):
f[i][a] -= 4.0 * math.pi / (3.0 * vol) * q[i] * dip[a]
elif surface != "tinfoil":
raise ValueError("surface must be 'tinfoil' or 'vacuum'")
parts = {"real": e_real, "rec": e_rec, "self": e_self, "surf": e_surf}
return e_real + e_rec + e_self + e_surf, f, parts # @line L11
def nacl_cell(a: float = 1.0) -> tuple[list[float], list[Vec], float]:
"""The conventional cubic cell of rock salt: 8 ions, nearest-neighbour distance a, box 2a."""
q, pos = [], []
for ix in range(2):
for iy in range(2):
for iz in range(2):
pos.append([ix * a, iy * a, iz * a])
q.append(1.0 if (ix + iy + iz) % 2 == 0 else -1.0)
return q, pos, 2.0 * a
def madelung_nacl(alpha: float = 2.5, rc: float = 2.5, mmax: int = 9) -> float:
"""The Madelung constant of NaCl from the Ewald energy: E = -(N / 2) M q^2 / a."""
q, pos, box = nacl_cell(1.0)
e, _, _ = ewald(q, pos, box, alpha, rc, mmax)
return -e / (len(q) / 2)
test_ewald_summation.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ewald-summation/. The authors are listed in prov/674E3C.jsonl.
import math
import random
import pytest
from ewald_summation import ewald, madelung_nacl, nacl_cell
def random_system(seed: int, n: int, box: float) -> 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 test_madelung_constant_of_nacl() -> None:
# 1.747565 is the Madelung constant of rock salt for the nearest-neighbour distance
assert abs(madelung_nacl() - 1.747565) < 1e-6
assert abs(madelung_nacl(2.0, 3.0, 8) - madelung_nacl(3.0, 2.2, 11)) < 1e-9
def test_energy_does_not_depend_on_alpha() -> None:
q, pos = random_system(1, 6, 4.0)
energies = [ewald(q, pos, 4.0, a, 9.0, 12)[0] for a in (0.8, 1.0, 1.3)]
assert max(energies) - min(energies) < 1e-8
parts = [ewald(q, pos, 4.0, a, 9.0, 12)[2] for a in (0.8, 1.3)]
assert abs(parts[0]["real"] - parts[1]["real"]) > 1e-2 # the split moves, the sum does not
def test_vacuum_energy_is_the_limit_of_spherical_direct_sums() -> None:
q, pos, box = [1.0, -1.0, 0.5, -0.5], None, 3.0
rng = random.Random(5)
pos = [[rng.uniform(0, box) for _ in range(3)] for _ in range(4)]
e_vac = ewald(q, pos, box, 1.2, 7.0, 10, "vacuum")[0]
def direct(radius: int) -> float:
e = 0.0
for nx in range(-radius, radius + 1):
for ny in range(-radius, radius + 1):
for nz in range(-radius, radius + 1):
if nx * nx + ny * ny + nz * nz > radius * radius:
continue
for i in range(4):
for j in range(4):
if i == j and nx == ny == nz == 0:
continue
d = [pos[i][0] - pos[j][0] + nx * box, pos[i][1] - pos[j][1] + ny * box, pos[i][2] - pos[j][2] + nz * box]
e += 0.5 * q[i] * q[j] / math.sqrt(d[0] ** 2 + d[1] ** 2 + d[2] ** 2)
return e
e4, e8 = direct(4), direct(8)
assert abs(e8 - e_vac) < 2e-5
assert abs(e8 - e_vac) < abs(e4 - e_vac)
@pytest.mark.parametrize("surface", ["tinfoil", "vacuum"])
def test_forces_are_minus_the_gradient(surface: str) -> None:
box = 4.0
q, pos = random_system(2, 5, box)
_, f, _ = ewald(q, pos, box, 1.0, 6.5, 9, surface)
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 = -(ewald(q, pp, box, 1.0, 6.5, 9, surface)[0] - ewald(q, pm, box, 1.0, 6.5, 9, surface)[0]) / (2 * h)
assert abs(num - f[i][a]) < 1e-6 * max(1.0, abs(f[i][a]))
def test_newton_third_law_and_lattice_symmetry() -> None:
box = 4.0
q, pos = random_system(3, 6, box)
_, f, _ = ewald(q, pos, box, 1.0, 9.0, 12)
for a in range(3):
assert abs(sum(fi[a] for fi in f)) < 1e-10
# each ion of the perfect crystal is at a centre of symmetry, so its force is zero
q, pos, box = nacl_cell()
_, f, _ = ewald(q, pos, box, 2.5, 2.5, 9)
assert max(abs(x) for fi in f for x in fi) < 1e-12
def test_tinfoil_energy_is_periodic_in_each_position() -> None:
box = 4.0
q, pos = random_system(4, 4, box)
e0 = ewald(q, pos, box, 1.0, 9.0, 12)[0]
moved = [list(p) for p in pos]
moved[2][1] += box
assert abs(ewald(q, moved, box, 1.0, 9.0, 12)[0] - e0) < 1e-10
def test_charged_system_is_rejected() -> None:
with pytest.raises(ValueError):
ewald([1.0, 1.0], [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]], 3.0, 1.0, 5.0, 5)
History
Ewald (1921) introduced the method to compute the optical and electrostatic potentials of crystal lattices. Simulations of ionic liquids and of water later used it for the Coulomb forces in a periodic box. De Leeuw, Perram and Smith (1980) worked out how the sum depends on the order of summation and on the medium around the system, which explains the surface term. Perram, Petersen and de Leeuw (1988) showed that a good choice of gives a cost of order . Darden, York and Pedersen (1993) replaced the reciprocal sum by an FFT on a grid, which led to the particle mesh Ewald methods used today.
References
- Paul P. Ewald, Die Berechnung optischer und elektrostatischer Gitterpotentiale, Annalen der Physik 369(3), 1921, 253-287, the split of the lattice sum into a real-space part and a reciprocal-space part
- Simon W. de Leeuw, John W. Perram and Edward R. Smith, Simulation of electrostatic systems in periodic boundary conditions. I. Lattice sums and dielectric constants, Proceedings of the Royal Society of London A 373(1752), 1980, 27-56, the dependence of the sum on the order of summation and the surface term for a vacuum outside a large sphere
- John W. Perram, Henrik G. Petersen and Simon W. de Leeuw, An algorithm for the simulation of condensed matter which grows as the 3/2 power of the number of particles, Molecular Physics 65(4), 1988, 875-893, the choice of the splitting parameter that gives a cost of order N^(3/2)
- Jiri Kolafa and John W. Perram, Cutoff errors in the Ewald summation formulae for point charge systems, Molecular Simulation 9(5), 1992, 351-368, estimates of the real-space and reciprocal-space truncation errors
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 6.2, The Ewald sum
- Daan Frenkel and Berend Smit, Understanding Molecular Simulation, From Algorithms to Applications, second edition, Academic Press, 2002, the section on Ewald sums in the chapter on long-range interactions
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 674E3C Edit this page History Report an error Markdown