Algorithm Search⌘K

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
Properties
deterministic
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 eik⋅rje^{i k \cdot r_j} 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 O(Nlog⁡N)O(N \log N), against O(N3/2)O(N^{3/2}) 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 NN charges qjq_j at rjr_j in a cubic box of side LL, volume VV, the Ewald parameter α\alpha, a grid of KK points per side, with KK a power of two, and an interpolation order 2p2p. We use Gaussian units. The output is an approximation of the reciprocal energy

Erec=2πV∑m≠0G(m)∣S(m)∣2,G(m)=e−k2/4α2k2,S(m)=∑jqjeik⋅rj,k=2πmL,E_{\text{rec}} = \frac{2\pi}{V} \sum_{m \ne 0} G(m) |S(m)|^2, \qquad G(m) = \frac{e^{-k^2/4\alpha^2}}{k^2}, \qquad S(m) = \sum_j q_j e^{i k \cdot r_j}, \qquad k = \frac{2\pi m}{L},

and of the reciprocal forces. With the scaled coordinates uj=Krj/Lu_j = K r_j / L, the factor eik⋅rj=e2πim⋅uj/Ke^{i k \cdot r_j} = e^{2\pi i m \cdot u_j / K} is a product of three factors, one per axis.

The algorithm

For one axis, W(u,g)W(u, g) is the weight of the grid point gg in the Lagrange interpolation of a function at uu from the 2p2p points ⌊u⌋−p+1,…,⌊u⌋+p\lfloor u \rfloor - p + 1, \ldots, \lfloor u \rfloor + p. Then e2πimu/K≈∑gW(u,g)e2πimg/Ke^{2\pi i m u / K} \approx \sum_g W(u, g) e^{2\pi i m g / K}, and S(m)≈∑gQ(g)e2πim⋅g/KS(m) \approx \sum_g Q(g) e^{2\pi i m \cdot g / K} for the charge grid QQ.

  1. PME-RECIPROCAL(q, r, L, α, K, p)
  2. 1for each charge j: u_j ← K r_j / L, and the 2p Lagrange weights W(u_ja, ·) for each axis a
  3. 2Q(g) ← Σ_j q_j W(u_j1, g_1) W(u_j2, g_2) W(u_j3, g_3), indices modulo K
  4. 3S̃ ← conj(FFT3(Q))
  5. 4for each m ≠ 0 with -K/2 < m_a ≤ K/2 do
  6. 5E ← E + (2π / V) G(m) |S̃(m)|²; A_d(m) ← k_d G(m) S̃(m) for d = 1, 2, 3
  7. 6field_d(g) ← -(4π / V) Im FFT3(A_d)(g) for d = 1, 2, 3
  8. 7F_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
  9. 8return (E, F)

Line L5 leaves out the Nyquist component 2md=K2 m_d = K of AdA_d, 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 O(N)O(N) time.

Example

Take N=8N = 8 random charges with zero sum (seed 7) in a box of side L=6L = 6, with α=0.8\alpha = 0.8. The exact reciprocal energy, summed term by term over ∣ma∣≤9|m_a| \le 9, is 0.74256444800.7425644480. The table shows the relative errors of PME:

KK order 2p2p energy error force error
8 2 2.51×10−12.51 \times 10^{-1} 1.71×10−11.71 \times 10^{-1}
8 4 5.85×10−25.85 \times 10^{-2} 2.01×10−22.01 \times 10^{-2}
8 6 2.15×10−22.15 \times 10^{-2} 7.82×10−37.82 \times 10^{-3}
16 2 7.57×10−27.57 \times 10^{-2} 3.56×10−23.56 \times 10^{-2}
16 4 4.62×10−34.62 \times 10^{-3} 1.26×10−31.26 \times 10^{-3}
16 6 5.32×10−45.32 \times 10^{-4} 2.63×10−42.63 \times 10^{-4}

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 2×10−162 \times 10^{-16}, zero up to rounding.

For one charge, the weights of line L1 are those of Lagrange interpolation. With p=1p = 1 and u=2.3u = 2.3, the two points are 2 and 3, with weights 0.7 and 0.3. With p=2p = 2 the four points are 1 to 4, with weights −0.0595,0.7735,0.3315,−0.0455-0.0595, 0.7735, 0.3315, -0.0455, and these reproduce 1,u,u2,u31, u, u^2, u^3 exactly.

Correctness

The proof below shows these claims:

  1. Interpolation error. For each wave vector, the interpolated Fourier factor differs from the exact one by at most (p!)2(2p)!(2π∣m∣/K)2p\frac{(p!)^2}{(2p)!} (2\pi |m| / K)^{2p}, a theorem. Essmann et al. (1995) give a sharper bound of the same form.
  2. 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.
  3. 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.
  4. 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 KK and pp, 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 LL and volume VV, with KK grid points per side. For a charge at rjr_j, write uj=Krj/Lu_j = K r_j / L for its scaled coordinates. The exact reciprocal energy is

Erec=2πV∑m≠0G(m)∣S(m)∣2,G(m)=e−k2/4α2k2,S(m)=∑jqje2πim⋅uj/K,E_{\text{rec}} = \frac{2\pi}{V} \sum_{m \ne 0} G(m) |S(m)|^2, \qquad G(m) = \frac{e^{-k^2/4\alpha^2}}{k^2}, \qquad S(m) = \sum_j q_j e^{2\pi i m \cdot u_j / K},

with k=2πm/Lk = 2\pi m / L, as proved on the Ewald summation page. For one coordinate, W(u,g)W(u, g) is the weight that piecewise Lagrange interpolation with the 2p2p points ⌊u⌋−p+1,…,⌊u⌋+p\lfloor u \rfloor - p + 1, \ldots, \lfloor u \rfloor + p gives to the point gg, and 0 for other points.

Claim 1 (interpolation error). For each integer mm and real uu,

∣e2πimu/K−∑gW(u,g)e2πimg/K∣≤(p!)2(2p)!(2π∣m∣K)2p.\Bigl| e^{2\pi i m u / K} - \sum_g W(u, g) e^{2\pi i m g / K} \Bigr| \le \frac{(p!)^2}{(2p)!} \Bigl(\frac{2\pi |m|}{K}\Bigr)^{2p}.

Proof. Let θ=2πm/K\theta = 2\pi m / K and f(t)=eiθtf(t) = e^{i\theta t}. The sum is the value at uu of the polynomial of degree less than 2p2p that interpolates ff at the 2p2p points xjx_j. Apply the Lagrange remainder to the real and imaginary parts, or use the Hermite integral form of the remainder for complex ff: the error is at most max⁡∣f(2p)∣∏j∣u−xj∣/(2p)!=∣θ∣2p∏j∣u−xj∣/(2p)!\max |f^{(2p)}| \prod_j |u - x_j| / (2p)! = |\theta|^{2p} \prod_j |u - x_j| / (2p)!. With w=u−⌊u⌋∈[0,1)w = u - \lfloor u \rfloor \in [0, 1), the points below or at ⌊u⌋\lfloor u \rfloor are at distances w,1+w,…,p−1+ww, 1 + w, \ldots, p - 1 + w, each at most 1,2,…,p1, 2, \ldots, p, and the points above are at distances 1−w,…,p−w1 - w, \ldots, p - w, each at most 1,…,p1, \ldots, p. So the product is at most (p!)2(p!)^2. □\square

Essmann et al. (1995) give a sharper bound of the same form. In both, the error falls with KK at the rate K−2pK^{-2p} for each fixed mm, and the large ∣m∣|m| terms, where the bound is poor, carry the small factor G(m)G(m).

Claim 2 (what lines L1 to L5 compute). Line L3 gives S~(m)=∑jqj∏a=13∑gaW(uja,ga)e2πimaga/K\tilde S(m) = \sum_j q_j \prod_{a=1}^{3} \sum_{g_a} W(u_{ja}, g_a) e^{2\pi i m_a g_a / K}, and line L5 gives E~=2πV∑G(m)∣S~(m)∣2\tilde E = \frac{2\pi}{V} \sum G(m) |\tilde S(m)|^2 over m≠0m \ne 0 with −K/2<ma≤K/2-K/2 < m_a \le K/2.

Proof. Line L2 adds qjW(uj1,g1)W(uj2,g2)W(uj3,g3)q_j W(u_{j1}, g_1) W(u_{j2}, g_2) W(u_{j3}, g_3) to Q(g)Q(g), with the indices gag_a reduced modulo KK. Since e2πimg/Ke^{2\pi i m g / K} has period KK in gg, the reduction does not change ∑gQ(g)e2πim⋅g/K\sum_g Q(g) e^{2\pi i m \cdot g / K}, which is the complex conjugate of the forward FFT of the real array QQ. Line L4 maps each FFT index to the representative of mm modulo KK in (−K/2,K/2](-K/2, K/2]. □\square

By Claim 1, S~(m)→S(m)\tilde S(m) \to S(m) for each mm as K→∞K \to \infty or p→∞p \to \infty at fixed m/Km / K small. The wave vectors with ∣ma∣>K/2|m_a| > K/2 are left out, and their terms are at most G(m)(∑j∣qj∣)2G(m) (\sum_j |q_j|)^2, which is small when πK/L≫2α\pi K / L \gg 2\alpha.

Claim 3 (the grid field). Line L6 gives, for each grid point gg and direction dd,

Ed(g)=4πV∑mkdG(m)Im⁡(e2πim⋅g/KS~(m)‾),\mathcal{E}_d(g) = \frac{4\pi}{V} \sum_m k_d G(m) \operatorname{Im}\bigl(e^{2\pi i m \cdot g / K} \overline{\tilde S(m)}\bigr),

with the Nyquist components 2md=K2 m_d = K left out, and line L7 gives Fj=qj∑gWj(g)E(g)F_j = q_j \sum_g W_j(g) \mathcal{E}(g) with Wj(g)=∏aW(uja,ga)W_j(g) = \prod_a W(u_{ja}, g_a).

Proof. The forward FFT of the array kdG(m)S~(m)k_d G(m) \tilde S(m) is ∑mkdGS~e−2πim⋅g/K\sum_m k_d G \tilde S e^{-2\pi i m \cdot g / K}, and Im⁡(S~e−iϕ)=−Im⁡(S~‾eiϕ)\operatorname{Im}(\tilde S e^{-i\phi}) = -\operatorname{Im}(\overline{\tilde S} e^{i\phi}). Multiplying by −4πV-\frac{4\pi}{V} gives the formula. The exact reciprocal force on a charge at rr is qq times the same expression with gg replaced by u=Kr/Lu = K r / L and S~\tilde S by SS (see the Ewald page), so E\mathcal{E} is the reciprocal field at the grid points, and line L7 interpolates it to the charges with the weights of line L2. □\square

The Nyquist component is left out because md=K/2m_d = K/2 and md=−K/2m_d = -K/2 are the same index, and the field term has opposite signs for the two. Its true weight G(m)G(m) is small when the grid is fine enough.

Claim 4 (zero net force). ∑jFj=0\sum_j F_j = 0 in exact arithmetic.

Proof. By Claim 3 and line L2, ∑jFj=∑g(∑jqjWj(g))E(g)=∑gQ(g)E(g)\sum_j F_j = \sum_g \bigl(\sum_j q_j W_j(g)\bigr) \mathcal{E}(g) = \sum_g Q(g) \mathcal{E}(g). For direction dd, since QQ is real,

∑gQ(g)Ed(g)=4πV∑mkdG(m)Im⁡(S~(m)‾∑gQ(g)e2πim⋅g/K)=4πV∑mkdG(m)Im⁡∣S~(m)∣2=0.□\sum_g Q(g) \mathcal{E}_d(g) = \frac{4\pi}{V} \sum_m k_d G(m) \operatorname{Im}\Bigl(\overline{\tilde S(m)} \sum_g Q(g) e^{2\pi i m \cdot g / K}\Bigr) = \frac{4\pi}{V} \sum_m k_d G(m) \operatorname{Im} |\tilde S(m)|^2 = 0. \qquad \square

What is not claimed. The forces are not the gradient of E~\tilde E: 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 Θ(Np3)\Theta(N p^3) for (2p)3(2p)^3 grid points per charge. Lines L3 and L6 are four 3D FFTs of K3K^3 points, Θ(K3log⁡K)\Theta(K^3 \log K). Lines L4 and L5 cost Θ(K3)\Theta(K^3). With the grid spacing L/KL/K fixed as NN grows at a fixed density, K3=Θ(N)K^3 = \Theta(N), and the total is Θ(Nlog⁡N)\Theta(N \log N) for the reciprocal part. The real-space part with a fixed cutoff costs Θ(N)\Theta(N) with a cell list.

Complexity

Spreading and interpolation cost Θ(Np3)\Theta(N p^3), since each charge touches (2p)3(2p)^3 grid points. The four FFTs of K3K^3 points cost Θ(K3log⁡K)\Theta(K^3 \log K), and the loop over wave vectors costs Θ(K3)\Theta(K^3). At a fixed density and accuracy, the grid spacing is fixed, so K3=Θ(N)K^3 = \Theta(N) and the total is Θ(Nlog⁡N)\Theta(N \log N). The memory is Θ(K3)\Theta(K^3) for the grids. The real-space part costs Θ(N)\Theta(N) 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 (∣m∣/K)2p(|m| / K)^{2p} for each wave vector, and the large wave vectors that interpolate badly carry the small factor G(m)G(m).
  • 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 1/r61/r^6 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 α\alpha. If πK/L\pi K / L is not well above 2α2\alpha, the wave vectors that the grid cannot resolve carry real weight, and the error is large. Raise KK or lower α\alpha 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 e+ik⋅re^{+ik \cdot r}, and most FFT libraries use e−ik⋅re^{-ik \cdot r} 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 KK.

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.

particle_mesh_ewald.pyI0RawGitHub
# 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 Nlog⁡NN \log N 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

  1. 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
  2. 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)
  3. 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.

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