Algorithm Search⌘K

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
Properties
conservativedeterministic
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 nn 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 NN charges qjq_j at rjr_j in a cubic box of side LL and volume VV, the Ewald parameter α\alpha, a grid of KK points per side, and the B-spline order n≥3n \ge 3. We use Gaussian units. The output is an approximation E~\tilde E of the reciprocal energy

Erec=2πV∑m≠0G(m)∣S(m)∣2,G(m)=e−k2/4α2k2,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 k = \frac{2\pi m}{L},

with S(m)=∑jqje2πim⋅uj/KS(m) = \sum_j q_j e^{2\pi i m \cdot u_j / K} and uj=Krj/Lu_j = K r_j / L, and the forces −∇E~-\nabla \tilde E.

The algorithm

The cardinal B-spline MnM_n is a piecewise polynomial of degree n−1n - 1 on [0,n][0, n], built by M2(x)=1−∣x−1∣M_2(x) = 1 - |x - 1| and Mn(x)=xn−1Mn−1(x)+n−xn−1Mn−1(x−1)M_n(x) = \frac{x}{n-1} M_{n-1}(x) + \frac{n-x}{n-1} M_{n-1}(x-1). The Euler exponential spline gives

e2πimu/K≈b(m)∑gMn(u−g)e2πimg/K,b(m)=(∑j=0n−1Mn(j)e−2πimj/K)−1,e^{2\pi i m u / K} \approx b(m) \sum_g M_n(u - g) e^{2\pi i m g / K}, \qquad b(m) = \Bigl(\sum_{j=0}^{n-1} M_n(j) e^{-2\pi i m j / K}\Bigr)^{-1},

exact at the grid points. So S(m)≈b(m1)b(m2)b(m3)∑gQ(g)e2πim⋅g/KS(m) \approx b(m_1) b(m_2) b(m_3) \sum_g Q(g) e^{2\pi i m \cdot g / K}, with Q(g)=∑jqj∏aMn(uja−ga)Q(g) = \sum_j q_j \prod_a M_n(u_{ja} - g_a). Let C(m)=4πVG(m)C(m) = \frac{4\pi}{V} G(m) and B(m)=∏a∣b(ma)∣2B(m) = \prod_a |b(m_a)|^2.

  1. SPME-RECIPROCAL(q, r, L, α, K, n)
  2. 1for 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
  3. 2Q(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
  4. 3F ← conj(FFT3(Q))
  5. 4for each m ≠ 0 with -K/2 < m_a ≤ K/2 do
  6. 5E ← E + ½ C(m) B(m) |F(m)|²; P(m) ← C(m) B(m) F(m)
  7. 6φ ← Re FFT3(P) ▷ φ = Θ ∗ Q, a convolution on the grid
  8. 7for 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)
  9. 8return (E, F_j = -q_j (K / L) g_j for each j)

The derivative of line L1 is Mn′(x)=Mn−1(x)−Mn−1(x−1)M_n'(x) = M_{n-1}(x) - M_{n-1}(x - 1), so it comes from the same recursion. For odd nn and 2ma=K2 m_a = K, b(ma)b(m_a) is undefined; the code sets B=0B = 0 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: N=8N = 8 random charges with zero sum (seed 7), L=6L = 6, α=0.8\alpha = 0.8, and the exact reciprocal energy 0.74256444800.7425644480. Relative errors of SPME, and the largest component of the net force:

KK nn energy error force error net force
8 4 1.26×10−21.26 \times 10^{-2} 4.90×10−24.90 \times 10^{-2} 1.0×10−21.0 \times 10^{-2}
8 6 2.19×10−32.19 \times 10^{-3} 7.83×10−37.83 \times 10^{-3} 2.0×10−32.0 \times 10^{-3}
8 8 7.89×10−47.89 \times 10^{-4} 2.19×10−32.19 \times 10^{-3} 6.2×10−46.2 \times 10^{-4}
16 4 5.27×10−45.27 \times 10^{-4} 4.60×10−34.60 \times 10^{-3} 5.8×10−45.8 \times 10^{-4}
16 6 1.07×10−51.07 \times 10^{-5} 1.02×10−41.02 \times 10^{-4} 1.6×10−51.6 \times 10^{-5}
16 8 4.43×10−74.43 \times 10^{-7} 4.29×10−64.29 \times 10^{-6} 7.1×10−77.1 \times 10^{-7}

On the grid with K=16K = 16, order 6 gives an energy error 50 times smaller than PME with six Lagrange points, 5.32×10−45.32 \times 10^{-4}. The net force shrinks with the force error, but it is never zero. The forces agree with central differences of E~\tilde E (step 10−610^{-6}, K=8K = 8, n=4n = 4) to 1.3×10−91.3 \times 10^{-9}, 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 n=4n = 4 the B-spline is the cubic M4M_4, with M4(1)=M4(3)=1/6M_4(1) = M_4(3) = 1/6 and M4(2)=2/3M_4(2) = 2/3. A charge exactly on a grid point gives 1/61/6, 2/32/3, 1/61/6 of its charge to that point and its two neighbours on each axis.

Correctness

The proof below shows these claims:

  1. The spline identity is exact at the grid points, and between them its error is bounded by a constant times (2∣m∣/K)n(2|m| / K)^n, a theorem of Essmann et al. (1995).
  2. What the code computes. Lines L1 to L5 compute E~=12∑CB∣FQ∣2\tilde E = \frac12 \sum C B |\mathcal{F}Q|^2, the reciprocal energy with the spline structure factor.
  3. The convolution. Line L6 gives the real array ϕ=Θ∗Q\phi = \Theta * Q, and E~=12∑gQ(g)ϕ(g)\tilde E = \frac12 \sum_g Q(g) \phi(g).
  4. The forces are the exact gradient of E~\tilde E, and they are continuous for n≥3n \ge 3.
  5. 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 bb for odd order, the gradient against central differences, the fall of the error with KK and nn, 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 LL and volume VV, with KK grid points per side, and uj=Krj/Lu_j = K r_j / L are the scaled coordinates of charge jj. The cardinal B-spline of order nn is M2(x)=1−∣x−1∣M_2(x) = 1 - |x - 1| on [0,2][0, 2] and 0 elsewhere, and

Mn(x)=xn−1Mn−1(x)+n−xn−1Mn−1(x−1).M_n(x) = \frac{x}{n-1} M_{n-1}(x) + \frac{n - x}{n-1} M_{n-1}(x - 1).

It is a piecewise polynomial of degree n−1n - 1, positive on (0,n)(0, n) and zero outside, with n−2n - 2 continuous derivatives, ∑gMn(x−g)=1\sum_g M_n(x - g) = 1 for all xx, and Mn′(x)=Mn−1(x)−Mn−1(x−1)M_n'(x) = M_{n-1}(x) - M_{n-1}(x - 1). The exact reciprocal energy Erec=2πV∑m≠0G(m)∣S(m)∣2E_{\text{rec}} = \frac{2\pi}{V} \sum_{m \ne 0} G(m) |S(m)|^2 with G(m)=e−k2/4α2/k2G(m) = e^{-k^2/4\alpha^2} / k^2 is proved on the Ewald summation page.

Claim 1 (the spline identity is exact at the grid points). Let β(m)=∑j=0n−1Mn(j)e−2πimj/K\beta(m) = \sum_{j=0}^{n-1} M_n(j) e^{-2\pi i m j / K} and suppose β(m)≠0\beta(m) \ne 0. Then for each integer uu,

e2πimu/K=1β(m)∑gMn(u−g)e2πimg/K.e^{2\pi i m u / K} = \frac{1}{\beta(m)} \sum_g M_n(u - g) e^{2\pi i m g / K}.

Proof. Put g=u−jg = u - j. Then ∑gMn(u−g)e2πimg/K=e2πimu/K∑jMn(j)e−2πimj/K\sum_g M_n(u - g) e^{2\pi i m g / K} = e^{2\pi i m u / K} \sum_j M_n(j) e^{-2\pi i m j / K}, and the sum over jj is over 0≤j≤n−10 \le j \le n - 1 because MnM_n vanishes at the other integers. □\square

Between grid points the right side is a spline interpolant of e2πimu/Ke^{2\pi i m u / K}, and Essmann et al. (1995) show that its error is bounded by a constant times (2∣m∣/K)n(2|m| / K)^n. So with b(m)=1/β(m)b(m) = 1/\beta(m) for one coordinate,

S(m)≈S~(m)=b(m1)b(m2)b(m3) FQ(m)‾,Q(g)=∑jqj∏aMn(uja−ga),S(m) \approx \tilde S(m) = b(m_1) b(m_2) b(m_3) \, \overline{\mathcal{F}Q(m)}, \qquad Q(g) = \sum_j q_j \prod_a M_n(u_{ja} - g_a),

where F\mathcal{F} is the forward discrete Fourier transform, and the grid indices are reduced modulo KK, which does not change the sum because e2πimg/Ke^{2\pi i m g / K} has period KK in gg. The energy depends only on ∣b∣2|b|^2, so the code needs β\beta only up to a phase: the function bspline_moduli uses ∑j=0n−2Mn(j+1)e2πimj/K\sum_{j=0}^{n-2} M_n(j+1) e^{2\pi i m j/K}, which is e−2πim/Ke^{-2 \pi i m/K} times the complex conjugate of β(m)\beta(m) because Mn(0)=0M_n(0) = 0, so it has the same modulus. For odd nn and 2m=K2m = K, β(m)=0\beta(m) = 0; the code sets ∣b∣2=0|b|^2 = 0 there, as Essmann et al. suggest.

Claim 2 (lines L2 to L5 compute the SPME energy). Line L5 gives

E~=12∑m≠0C(m)B(m)∣FQ(m)∣2,C(m)=4πVG(m),B(m)=∏a∣b(ma)∣2,\tilde E = \frac12 \sum_{m \ne 0} C(m) B(m) |\mathcal{F}Q(m)|^2, \qquad C(m) = \frac{4\pi}{V} G(m), \quad B(m) = \prod_a |b(m_a)|^2,

which is 2πV∑G(m)∣S~(m)∣2\frac{2\pi}{V} \sum G(m) |\tilde S(m)|^2.

Proof. Line L1 puts the weight Mn(u−⌊u⌋+j)M_n(u - \lfloor u \rfloor + j) on the grid point ⌊u⌋−j\lfloor u \rfloor - j for j=0,…,n−1j = 0, \ldots, n - 1. These are exactly the grid points gg with Mn(u−g)≠0M_n(u - g) \ne 0, since u−gu - g must lie in (0,n)(0, n). Line L2 adds the products of the three weights, times qjq_j, so the array is QQ. Line L3 takes the conjugate of its FFT, which has the modulus of FQ\mathcal{F}Q. The rest is the definition. □\square

Claim 3 (the energy as a convolution). Let ϕ(g)=∑mC(m)B(m)FQ(m)‾ e−2πim⋅g/K\phi(g) = \sum_m C(m) B(m) \overline{\mathcal{F}Q(m)}\, e^{-2\pi i m \cdot g / K}, the array of line L6. Then ϕ\phi is real, ϕ=Θ∗Q\phi = \Theta * Q for the real, even kernel Θ\Theta whose transform is CBC B, and E~=12∑gQ(g)ϕ(g)\tilde E = \frac12 \sum_g Q(g) \phi(g).

Proof. C(m)B(m)C(m) B(m) is real and even in mm, so Θ(g)=∑mC(m)B(m)e−2πim⋅g/K\Theta(g) = \sum_m C(m) B(m) e^{-2\pi i m \cdot g / K} is real and even, and the convolution theorem gives ϕ=Θ∗Q\phi = \Theta * Q, with no factor 1/K31/K^3 because of this normalisation of Θ\Theta. Since QQ is real, ϕ\phi is real. Since ∑gQ(g)e−2πim⋅g/K=FQ(m)\sum_g Q(g) e^{-2\pi i m \cdot g / K} = \mathcal{F}Q(m), ∑gQ(g)ϕ(g)=∑mCB∣FQ(m)∣2=2E~\sum_g Q(g) \phi(g) = \sum_m C B |\mathcal{F}Q(m)|^2 = 2 \tilde E. □\square

Claim 4 (the forces are the exact gradient). Lines L7 and L8 give Fj=−∇rjE~F_j = -\nabla_{r_j} \tilde E, and for n≥3n \ge 3 the forces are continuous functions of the positions.

Proof. E~=12QTΘQ\tilde E = \frac12 Q^{\mathsf T} \Theta Q is a quadratic form in QQ with a symmetric matrix Θ(g,g′)=Θ(g−g′)\Theta(g, g') = \Theta(g - g'), so ∂E~/∂rja=∑g∂Q(g)∂rja(ΘQ)(g)=∑g∂Q(g)∂rjaϕ(g)\partial \tilde E / \partial r_{ja} = \sum_g \frac{\partial Q(g)}{\partial r_{ja}} (\Theta Q)(g) = \sum_g \frac{\partial Q(g)}{\partial r_{ja}} \phi(g). For the first coordinate, ∂Q(g)∂rj1=qjKLMn′(uj1−g1)Mn(uj2−g2)Mn(uj3−g3)\frac{\partial Q(g)}{\partial r_{j1}} = q_j \frac{K}{L} M_n'(u_{j1} - g_1) M_n(u_{j2} - g_2) M_n(u_{j3} - g_3), and the other two are alike. The function bspline computes Mn′M_n' by the identity Mn′=Mn−1(x)−Mn−1(x−1)M_n' = M_{n-1}(x) - M_{n-1}(x - 1), from the values of Mn−1M_{n-1} that the recursion has at that point. Line L7 sums these products against ϕ\phi and line L8 multiplies by −qjK/L-q_j K / L. MnM_n has a continuous first derivative for n≥3n \ge 3, so E~\tilde E is C1C^1 in the positions and the forces are continuous. □\square

So a run with SPME forces and a symplectic integrator conserves a shadow of the approximate energy E~\tilde E 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 t∈R3t \in \mathbb{R}^3 of all charges, let e(t)=E~(r+t)e(t) = \tilde E(r + t). Then ∑jFj=−∇e(0)\sum_j F_j = -\nabla e(0), ee has period L/KL/K in each direction, and the mean of ∑jFj(r+t)\sum_j F_j(r + t) over tt in one grid cell is 0.

Proof. The first part is the chain rule. Moving every uju_j by one grid spacing moves QQ by one index, which does not change ∣FQ∣|\mathcal{F}Q|, so ee is periodic. The mean of the gradient of a periodic function over one period is 0. □\square

Translation by a fraction of a cell does change E~\tilde E, so in general ∇e(0)≠0\nabla e(0) \ne 0; the test finds a net force of 10−210^{-2} of the scale of the forces at K=8K = 8, n=4n = 4. 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 Θ(Nn3)\Theta(N n^3), lines L3 and L6 are two 3D FFTs, Θ(K3log⁡K)\Theta(K^3 \log K), and lines L4 and L5 cost Θ(K3)\Theta(K^3). With K3=Θ(N)K^3 = \Theta(N) at a fixed density, the total is Θ(Nlog⁡N)\Theta(N \log N).

Complexity

Spreading and the forces cost Θ(Nn3)\Theta(N n^3). The two FFTs cost Θ(K3log⁡K)\Theta(K^3 \log K) and the loop over wave vectors Θ(K3)\Theta(K^3). With a fixed grid spacing, K3=Θ(N)K^3 = \Theta(N), so the total is Θ(Nlog⁡N)\Theta(N \log N). The factors B(m)B(m) depend only on KK and nn and can be computed once. Memory is Θ(K3)\Theta(K^3).

Properties

  • Energy conserving. The forces are the gradient of E~\tilde E, 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 E~\tilde E 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 n=6n = 6 or 8, a modest grid gives errors of 10−510^{-5} or better in the example.
  • Smoothness. MnM_n has n−2n - 2 continuous derivatives, so the forces are Cn−3C^{n-3} in the positions.

Variants and improvements

  • Other kernels. The same machinery computes the dispersion sum ∑C6/r6\sum C_6 / r^6, 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 n=3n = 3 the force is only continuous, not smooth, and the accuracy is poor. Use n≥4n \ge 4.
  • Odd order and even KK. b(m)b(m) is undefined at 2m=K2m = K. Set that term to zero or use an even order.
  • Forgetting B(m)B(m). Without the factors ∣b∣2|b|^2 the energy is the energy of the smeared charges, with a large error at large ∣m∣|m|.
  • 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.

smooth_particle_mesh_ewald.pyI0RawGitHub
# 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

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

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