Algorithm Search⌘K

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
Properties
deterministic
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 1/r1/r as erfc⁡(αr)/r+erf⁡(αr)/r\operatorname{erfc}(\alpha r)/r + \operatorname{erf}(\alpha r)/r. 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 α\alpha, the cost is O(N3/2)O(N^{3/2}) for NN 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 O(Nlog⁡N)O(N \log N) 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 NN point charges qiq_i at positions rir_i in a cubic box of side LL and volume V=L3V = L^3, with ∑iqi=0\sum_i q_i = 0, and the boundary condition at infinity. We use Gaussian units, so two charges at distance rr have energy qiqj/rq_i q_j / r. The output is the energy

E=12∑i,j∑n′qiqj∣ri−rj+nL∣E = \frac12 \sum_{i, j} {\sum_n}' \frac{q_i q_j}{|r_i - r_j + nL|}

and the forces fi=−∇riEf_i = -\nabla_{r_i} E. The sum runs over integer vectors nn, and the prime leaves out n=0n = 0 when i=ji = j. 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 rij=ri−rjr_{ij} = r_i - r_j, k=2πm/Lk = 2\pi m / L for integer vectors mm, and S(k)=∑jqjeik⋅rjS(k) = \sum_j q_j e^{i k \cdot r_j}, the energy is

E=12∑i,j∑n′qiqjerfc⁡(α∣rij+nL∣)∣rij+nL∣⏟Ereal+2πV∑k≠0e−k2/4α2k2∣S(k)∣2⏟Erec−απ∑iqi2⏟Eself+Esurf,E = \underbrace{\frac12 \sum_{i,j} {\sum_n}' q_i q_j \frac{\operatorname{erfc}(\alpha |r_{ij} + nL|)}{|r_{ij} + nL|}}_{E_{\text{real}}} + \underbrace{\frac{2\pi}{V} \sum_{k \ne 0} \frac{e^{-k^2/4\alpha^2}}{k^2} |S(k)|^2}_{E_{\text{rec}}} \underbrace{- \frac{\alpha}{\sqrt\pi} \sum_i q_i^2}_{E_{\text{self}}} + E_{\text{surf}},

with Esurf=0E_{\text{surf}} = 0 for tin foil and Esurf=2π3V∣∑iqiri∣2E_{\text{surf}} = \frac{2\pi}{3V} |\sum_i q_i r_i|^2 for a vacuum.

  1. EWALD(q, r, L, α, r_c, m_max, surface)
  2. 1V ← L³; E_real, E_rec ← 0; f_i ← 0 for each i
  3. 2for each pair i ≤ j and each image n with d = |r_ij + nL| < r_c, leaving out i = j, n = 0 do
  4. 3E_real ← E_real + w q_i q_j erfc(α d) / d ▷ w = 1/2 if i = j, else 1
  5. 4if i ≠ j then add the pair force to f_i and subtract it from f_j
  6. 5for each m with 0 < |m| ≤ m_max, one of each pair m, -m do
  7. 6k ← 2π m / L; S ← Σ_j q_j exp(i k · r_j)
  8. 7E_rec ← E_rec + 2 (2π / V) G(k) |S|² ▷ G(k) = exp(-k² / 4α²) / k²
  9. 8f_i ← f_i + 2 (4π / V) q_i G(k) Im(exp(i k · r_i) conj(S)) k for each i
  10. 9E_self ← -(α / √π) Σ_i q_i²
  11. 10if surface = vacuum then E_surf ← (2π / 3V) |M|², f_i ← f_i - (4π / 3V) q_i M, with M = Σ_i q_i r_i
  12. 11return (E_real + E_rec + E_self + E_surf, f)

The pair force of line L4 is qiqj(erfc⁡(αd)/d+2απe−α2d2)(rij+nL)/d2q_i q_j \bigl(\operatorname{erfc}(\alpha d)/d + \frac{2\alpha}{\sqrt\pi} e^{-\alpha^2 d^2}\bigr) (r_{ij} + nL) / d^2. The terms for mm and −m-m in line L7 are equal, since S(−k)S(-k) is the complex conjugate of S(k)S(k), 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 rcr_c with a linked cell list.

Example

The Madelung constant of rock salt. Put 8 ions of charge ±1\pm 1 on the corners of a cube of side a=1a = 1, alternating in sign, in a periodic box of side 22. This is the conventional cell of NaCl. The energy per ion pair is −Mq2/a-M q^2 / a, where MM is the Madelung constant, so M=−E/4M = -E / 4. With rc=8r_c = 8 and mmax⁡=14m_{\max} = 14, so that both sums have converged:

α\alpha ErealE_{\text{real}} ErecE_{\text{rec}} EselfE_{\text{self}} MM
1.0 −2.485025-2.485025 0.008283 −4.513517-4.513517 1.7475646
1.5 −0.726067-0.726067 0.506084 −6.770275-6.770275 1.7475646
2.0 −0.110133-0.110133 2.146908 −9.027033-9.027033 1.7475646
2.5 −0.009747-0.009747 4.303281 −11.283792-11.283792 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 α\alpha puts the work in real space, and a large α\alpha puts it in reciprocal space. With α=2.5\alpha = 2.5, rc=2.5r_c = 2.5 and mmax⁡=9m_{\max} = 9 the result is already 1.74756459461.7475645946.

The order of summation matters. Take four charges 1,−1,0.5,−0.51, -1, 0.5, -0.5 at random positions (seed 5) in a box of side 3. Sum qiqj/rq_i q_j / r directly over all images inside a sphere of RR boxes:

RR 4 8 16
direct sum −1.1155944-1.1155944 −1.1156453-1.1156453 −1.1156499-1.1156499

The spherical sums converge to the Ewald energy with a vacuum outside the sphere, −1.1156502-1.1156502. The tin foil energy is −1.4827084-1.4827084. The difference, 0.36705820.3670582, is the surface term 2π3V∣M∣2\frac{2\pi}{3V}|M|^2 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:

  1. The split is exact. For each α>0\alpha > 0, 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 ErecE_{\text{rec}}. The self term removes the energy of each Gaussian with its own point charge. This is a theorem.
  2. The code computes the truncated sums. Lines L2 to L8 compute ErealE_{\text{real}} over the images inside rcr_c and ErecE_{\text{rec}} over ∣m∣≤mmax⁡|m| \le m_{\max}.
  3. The forces are the exact gradient of the computed energy, between the moments when an image crosses the cutoff sphere.
  4. Truncation error. Each left-out term is at most of size e−s2e^{-s^2}, up to slowly changing factors, with s=αrc=kc/2αs = \alpha r_c = k_c / 2\alpha. 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 α\alpha to 10−810^{-8}, 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 NN point charges qiq_i at rir_i in a cubic box of side LL and volume V=L3V = L^3, with ∑iqi=0\sum_i q_i = 0. Write rij=ri−rjr_{ij} = r_i - r_j, and let ∑n′\sum'_n be the sum over integer vectors nn that leaves out n=0n = 0 when i=ji = j. The periodic Coulomb energy is

E=12∑i,j∑n′qiqj∣rij+nL∣.E = \frac12 \sum_{i, j} {\sum_n}' \frac{q_i q_j}{|r_{ij} + nL|}.

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 α>0\alpha > 0 and r>0r > 0, 1r=erfc⁡(αr)r+erf⁡(αr)r\frac{1}{r} = \frac{\operatorname{erfc}(\alpha r)}{r} + \frac{\operatorname{erf}(\alpha r)}{r}, and erf⁡(αr)/r\operatorname{erf}(\alpha r)/r is the potential at distance rr of a unit charge spread as the Gaussian ρα(s)=(α/π)3e−α2s2\rho_\alpha(s) = (\alpha / \sqrt{\pi})^3 e^{-\alpha^2 s^2}.

Proof. The first part holds because erf⁡+erfc⁡=1\operatorname{erf} + \operatorname{erfc} = 1. For the second, Gauss's law says that the field of a spherical charge at distance rr is the charge inside radius rr divided by r2r^2. The charge of ρα\rho_\alpha inside radius rr is erf⁡(αr)−2αrπe−α2r2\operatorname{erf}(\alpha r) - \frac{2 \alpha r}{\sqrt\pi} e^{-\alpha^2 r^2}, and this is r2r^2 times −ddr(erf⁡(αr)/r)-\frac{d}{dr}\bigl(\operatorname{erf}(\alpha r)/r\bigr). Both potentials go to 0 as r→∞r \to \infty, so they are equal. □\square

Claim 2 (the four parts). In the limit of spheres, E=Ereal+Erec+Eself+EsurfE = E_{\text{real}} + E_{\text{rec}} + E_{\text{self}} + E_{\text{surf}} with

Ereal=12∑i,j∑n′qiqjerfc⁡(α∣rij+nL∣)∣rij+nL∣,Erec=2πV∑k≠0e−k2/4α2k2∣S(k)∣2,E_{\text{real}} = \frac12 \sum_{i, j} {\sum_n}' q_i q_j \frac{\operatorname{erfc}(\alpha |r_{ij} + nL|)}{|r_{ij} + nL|}, \qquad E_{\text{rec}} = \frac{2\pi}{V} \sum_{k \ne 0} \frac{e^{-k^2 / 4\alpha^2}}{k^2} |S(k)|^2,

S(k)=∑jqjeik⋅rjS(k) = \sum_j q_j e^{i k \cdot r_j}, k=2πm/Lk = 2\pi m / L for integer vectors mm, Eself=−απ∑iqi2E_{\text{self}} = -\frac{\alpha}{\sqrt\pi} \sum_i q_i^2 and Esurf=2π3V∣∑iqiri∣2E_{\text{surf}} = \frac{2\pi}{3V} \bigl|\sum_i q_i r_i\bigr|^2.

Proof. Split each term of EE by Claim 1. The erfc part decays faster than any power, so it converges absolutely, in any order, to ErealE_{\text{real}}. For the erf part, add the missing terms i=ji = j, n=0n = 0, whose value is the limit erf⁡(αr)/r→2α/π\operatorname{erf}(\alpha r)/r \to 2\alpha / \sqrt\pi as r→0r \to 0. With the factor 12\frac12 they add απ∑iqi2\frac{\alpha}{\sqrt\pi} \sum_i q_i^2, which EselfE_{\text{self}} takes away again. The full smooth sum is 12∑i,jqiqjϕ(rij)\frac12 \sum_{i,j} q_i q_j \phi(r_{ij}), where ϕ(r)=∑nerf⁡(α∣r+nL∣)/∣r+nL∣\phi(r) = \sum_n \operatorname{erf}(\alpha |r + nL|)/|r + nL| is the potential of a periodic lattice of Gaussians. The sum over nn diverges for one pair, but the sum weighted by qiqjq_i q_j converges for a neutral system, and an additive constant in ϕ\phi cancels because ∑i,jqiqj=0\sum_{i,j} q_i q_j = 0. The density is smooth and periodic, with Fourier coefficients e−k2/4α2/Ve^{-k^2/4\alpha^2}/V, and the Poisson equation ∇2ϕ=−4πρ\nabla^2 \phi = -4\pi \rho gives the coefficients 4πVk2e−k2/4α2\frac{4\pi}{V k^2} e^{-k^2/4\alpha^2} for k≠0k \ne 0. The k=0k = 0 term is where the order of summation enters: for a neutral system it is 00 with conducting (tin foil) surroundings, and for a sphere of images in a vacuum it is the dipole term EsurfE_{\text{surf}}, by the analysis of de Leeuw, Perram and Smith (1980), which we do not repeat. Then

12∑i,jqiqj∑k≠04πVk2e−k2/4α2eik⋅rij=2πV∑k≠0e−k2/4α2k2S(k)S(k)‾,\frac12 \sum_{i,j} q_i q_j \sum_{k \ne 0} \frac{4\pi}{V k^2} e^{-k^2/4\alpha^2} e^{i k \cdot r_{ij}} = \frac{2\pi}{V} \sum_{k \ne 0} \frac{e^{-k^2/4\alpha^2}}{k^2} S(k) \overline{S(k)},

which is ErecE_{\text{rec}}. □\square

So the sum of the four parts does not depend on α\alpha. The test checks this to 10−810^{-8}.

Claim 3 (the code computes the truncated parts). Lines L2 and L3 compute ErealE_{\text{real}} over the images with ∣rij+nL∣<rc|r_{ij} + nL| < r_c. Lines L5 to L7 compute ErecE_{\text{rec}} over 0<∣m∣≤mmax⁡0 < |m| \le m_{\max}. Lines L9 and L10 compute EselfE_{\text{self}} and EsurfE_{\text{surf}}.

Proof. The double sum over ordered pairs (i,j)(i, j) is twice the sum over i<ji < j, so the factor 12\frac12 goes away for i≠ji \ne j and stays for i=ji = j, as in line L3. The images of rijr_{ij} are the same for every representative of rijr_{ij} modulo LL, so the code may first take the minimum image and then visit all shifts with ∣na∣≤⌈rc/L⌉+1|n_a| \le \lceil r_c / L \rceil + 1, which include every image closer than rcr_c. In line L7, S(−k)=S(k)‾S(-k) = \overline{S(k)}, so the terms for mm and −m-m are equal. The code visits one mm of each pair, the ones after (0,0,0)(0, 0, 0) in lexicographic order, and doubles the term. □\square

Claim 4 (the forces are the exact gradient). For fixed sets of images and wave vectors, lines L4, L8 and L10 give fi=−∇rif_i = -\nabla_{r_i} of the computed energy.

Proof. For u(r)=qiqjerfc⁡(αr)/ru(r) = q_i q_j \operatorname{erfc}(\alpha r)/r, −u′(r)=qiqj(erfc⁡(αr)/r2+2απe−α2r2/r)-u'(r) = q_i q_j \bigl(\operatorname{erfc}(\alpha r)/r^2 + \frac{2\alpha}{\sqrt\pi} e^{-\alpha^2 r^2}/r\bigr), and the force on ii is −u′(r) d/r-u'(r) \, d / r with d=rij+nLd = r_{ij} + nL. This is the factor gg of line L4, which adds it to fif_i and subtracts it from fjf_j. Terms with i=ji = j do not depend on rir_i. For line L8, ∇ri∣S∣2=2Re⁡(ikqieik⋅riS‾)=−2qikIm⁡(eik⋅riS‾)\nabla_{r_i} |S|^2 = 2 \operatorname{Re}\bigl(i k q_i e^{i k \cdot r_i} \overline{S}\bigr) = -2 q_i k \operatorname{Im}\bigl(e^{i k \cdot r_i} \overline{S}\bigr), and Im⁡(eiθS‾)=sin⁡θRe⁡S−cos⁡θIm⁡S\operatorname{Im}(e^{i\theta} \overline{S}) = \sin\theta \operatorname{Re} S - \cos\theta \operatorname{Im} S. Multiplying by −2πVe−k2/4α2k2-\frac{2\pi}{V} \frac{e^{-k^2/4\alpha^2}}{k^2} gives the force of line L8, doubled for the pair ±m\pm m. For line L10, −∇ri2π3V∣M∣2=−4π3VqiM-\nabla_{r_i} \frac{2\pi}{3V} |M|^2 = -\frac{4\pi}{3V} q_i M with M=∑jqjrjM = \sum_j q_j r_j. □\square

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 rcr_c, by at most ∣qiqj∣erfc⁡(αrc)/rc|q_i q_j| \operatorname{erfc}(\alpha r_c) / r_c, so Claim 4 holds between such crossings.

Claim 5 (truncation error, heuristic). Each omitted real-space term is at most ∣qiqj∣erfc⁡(αrc)/rc≤∣qiqj∣e−α2rc2/(παrc2)|q_i q_j| \operatorname{erfc}(\alpha r_c)/r_c \le |q_i q_j| e^{-\alpha^2 r_c^2} / (\sqrt\pi \alpha r_c^2), and each omitted reciprocal term is at most 2πVe−kc2/4α2kc2(∑j∣qj∣)2\frac{2\pi}{V} \frac{e^{-k_c^2/4\alpha^2}}{k_c^2} \bigl(\sum_j |q_j|\bigr)^2 with kc=2πmmax⁡/Lk_c = 2\pi m_{\max} / L.

Proof. The bound erfc⁡(x)≤e−x2/(πx)\operatorname{erfc}(x) \le e^{-x^2} / (\sqrt\pi x) for x>0x > 0 follows from ∫x∞e−t2dt≤∫x∞txe−t2dt\int_x^\infty e^{-t^2} dt \le \int_x^\infty \frac{t}{x} e^{-t^2} dt. The second bound uses ∣S(k)∣≤∑j∣qj∣|S(k)| \le \sum_j |q_j| and that e−k2/4α2/k2e^{-k^2/4\alpha^2}/k^2 falls with kk. □\square

The number of omitted terms grows only like a power of rcr_c and kck_c, so with s=αrc=kc/(2α)s = \alpha r_c = k_c / (2\alpha) both tails are e−s2e^{-s^2} 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 ss fixed and α\alpha free. At a fixed density N/VN / V, the real-space part costs Θ(Nrc3N/V)=Θ(N2s3/(α3V))\Theta(N r_c^3 N / V) = \Theta(N^2 s^3 / (\alpha^3 V)) with a cell list, and the reciprocal part costs Θ(Nkc3V)=Θ(Ns3α3V)\Theta(N k_c^3 V) = \Theta(N s^3 \alpha^3 V). The sum is smallest for α3V=Θ(N)\alpha^3 V = \Theta(\sqrt N), that is, α∝N1/6/V1/3\alpha \propto N^{1/6} / V^{1/3}, and then both parts cost Θ(N3/2)\Theta(N^{3/2}).

Proof. Each charge meets about 4π3rc3N/V\frac{4\pi}{3} r_c^3 N / V charges inside rcr_c, and there are about 4π3(kcL/2π)3=Θ(kc3V)\frac{4\pi}{3} (k_c L / 2\pi)^3 = \Theta(k_c^3 V) wave vectors, each costing Θ(N)\Theta(N). The product of the two costs is Θ(N3s6)\Theta(N^3 s^6), which does not depend on α\alpha, so their sum is smallest when they are equal, at Θ(N3/2s3)\Theta(N^{3/2} s^3). □\square

The implementation does not use a cell list: its real-space loop visits all pairs, so its cost is Θ(N2)\Theta(N^2) for the real part.

Complexity

The real-space part costs one evaluation of erfc per pair within rcr_c. The reciprocal part costs Θ(N)\Theta(N) per wave vector. With the error level ss fixed, the real part costs about N2s3/(α3V)N^2 s^3 / (\alpha^3 V) with a cell list and the reciprocal part about Ns3α3VN s^3 \alpha^3 V. The product does not depend on α\alpha, so the sum is smallest when the two are equal, at α∝N1/6/V1/3\alpha \propto N^{1/6} / V^{1/3}, and the total is Θ(N3/2)\Theta(N^{3/2}) (Perram, Petersen and de Leeuw 1988). The implementation visits all pairs, so it costs O(N2+NM3)O(N^2 + N M^3) with M=mmax⁡M = m_{\max}, and O(N)O(N) extra space. Mesh methods reduce the reciprocal part to O(Nlog⁡N)O(N \log N) with a fixed small cutoff.

Properties

  • Exact in the limit. Every truncation error goes to 0 as rcr_c and mmax⁡m_{\max} grow, at any fixed α\alpha.
  • Smooth forces. The reciprocal forces are smooth functions of the positions, and with a large enough rcr_c 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 ∑iqieik⋅riS‾=∣S∣2\sum_i q_i e^{i k \cdot r_i} \overline{S} = |S|^2 is real.
  • Needs a neutral box. For a net charge the k=0k = 0 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 ErecE_{\text{rec}} with FFTs in O(Nlog⁡N)O(N \log N) time.
  • Other potentials. The same split works for dispersion, 1/r61/r^6, 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 O(N)O(N) 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 αrc\alpha r_c is small, the real-space error is large, and if kc/2αk_c / 2\alpha is small, the reciprocal error is large. Check that the energy does not change with α\alpha.
  • 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 rcr_c.
  • The self term. Forgetting it, or using it with the wrong α\alpha, shifts the energy by a large constant, as the column EselfE_{\text{self}} 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.

ewald_summation.pyI0RawGitHub
# 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 α\alpha gives a cost of order N3/2N^{3/2}. 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

  1. 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
  2. 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
  3. 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)
  4. 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
  5. Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 6.2, The Ewald sum
  6. 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.

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