Algorithm Search⌘K

Algorithmcore

SHAKE constraint algorithm

Also called SHAKE.

Holds bond lengths fixed during Verlet integration by adjusting positions along the bonds, one constraint at a time, until all hold to a tolerance.

Time
O(N + s C) worst
Space
O(N) extra
Where
C = the number of constraints; N = the number of atoms; s = the number of sweeps
Properties
deterministiciterativetime reversible
Origin
Jean Paul Ryckaert, Giovanni Ciccotti, Herman J. C. Berendsen, 1977

SHAKE keeps chosen distances between pairs of particles fixed while a Verlet integrator moves them. Each such distance is a constraint: in a molecule it is a bond length, or the distance between two hydrogens of a rigid water. The integrator first takes a free step that ignores the constraints. SHAKE then moves the particles back, each pair along its bond direction at the start of the step, with shifts weighted by the inverse masses, and goes over the constraints one at a time until all of them hold to a tolerance. Position-based dynamics in graphics also projects positions one constraint at a time, but it usually stops after a fixed number of passes. SHAKE adds three things: the corrections are the forces of Lagrange multipliers, so the result is the constrained Verlet step of mechanics; it iterates to a set tolerance; and with the velocities from RATTLE the method is time reversible and symplectic. LINCS solves the same equations with a matrix series instead of a sweep.

In plain words

Some parts of a molecule move very fast, such as a hydrogen atom that vibrates along its bond. To follow that motion, a simulation needs a tiny time step. If we hold those bonds at a fixed length, the fast motion is gone and the step can be larger.

SHAKE does this after each normal step. The step moves every atom as if the bonds were not there, so the bonds stretch or shrink a little. SHAKE looks at one bond, and pulls or pushes its two atoms along the line they had before the step until the bond has the right length. The light atom moves more than the heavy one. Fixing one bond can upset its neighbours, so SHAKE goes over all the bonds again and again until every bond is right to the requested accuracy.

The problem

There are NN atoms with positions xix_i, masses mim_i and inverse masses wi=1/miw_i = 1/m_i (zero for a fixed atom), a force f(x)f(x), and CC constraints c=(i,j,dc)c = (i, j, d_c), each asking σc(x)=∣xi−xj∣2−dc2=0\sigma_c(x) = |x_i - x_j|^2 - d_c^2 = 0. Given xn−1x^{n-1} and xnx^n that satisfy the constraints, and the step hh, find xn+1x^{n+1} and multipliers λ\lambda with

xn+1=2xn−xn−1+h2Wf(xn)−h2W∇σ(xn)Tλ,σ(xn+1)=0,x^{n+1} = 2 x^n - x^{n-1} + h^2 W f(x^n) - h^2 W \nabla \sigma(x^n)^{\mathsf T} \lambda, \qquad \sigma(x^{n+1}) = 0,

where WW is the diagonal matrix of the wiw_i. The constraint forces act along the old bond vectors rc=xin−xjnr_c = x^n_i - x^n_j. The equations for λ\lambda are nonlinear, and we solve them to a relative tolerance τ\tau.

The algorithm

  1. SHAKE-STEP(x_prev, x, w, f, h, bonds, τ)
  2. 1x̃ ← 2x - x_prev + h² W f(x) ▷ the free Verlet step
  3. 2repeat
  4. 3for each constraint c = (i, j, d) do
  5. 4s ← x̃_i - x̃_j; if |d² - |s|²| ≤ 2τ d² then skip this constraint
  6. 5g ← (d² - |s|²) / (2 (w_i + w_j) s · r_c) ▷ r_c = x_i - x_j, the old bond
  7. 6x̃_i ← x̃_i + w_i g r_c; x̃_j ← x̃_j - w_j g r_c
  8. 7until a whole sweep skips every constraint
  9. 8return x̃

Line L5 is one Newton step for the single constraint, with all other atoms held fixed. The code stops with an error if s⋅rc≤0s \cdot r_c \le 0, which means that a bond turned by more than a right angle in one step, and if the sweeps do not converge after a set number.

Example

One bond. Atom 0 has w0=1w_0 = 1, atom 1 has w1=0.25w_1 = 0.25, and the old bond is r=x0−x1=(−1,0,0)r = x_0 - x_1 = (-1, 0, 0) with d=1d = 1. The free step puts the atoms at (0.05,0.1,−0.02)(0.05, 0.1, -0.02) and (1.2,−0.05,0.03)(1.2, -0.05, 0.03), so s=(−1.15,0.15,−0.05)s = (-1.15, 0.15, -0.05) and ∣s∣2=1.3475|s|^2 = 1.3475. The exact correction solves the quadratic ∣s+1.25gr∣2=1|s + 1.25 g r|^2 = 1 for gg. SHAKE takes Newton steps on this equation and reaches the smaller root to 10−1210^{-12}.

Water. A rigid water molecule has three constraints: two O-H bonds of 0.9572 Å and the H-H distance 1.5139 Å, with masses 16 and 1.008. Move each coordinate by a random amount in [−0.02,0.02][-0.02, 0.02] Å (seed 1), which breaks the bonds by up to 1.8%1.8\%. The number of sweeps for three tolerances:

tolerance τ\tau sweeps largest relative bond error
10−410^{-4} 5 8.9×10−58.9 \times 10^{-5}
10−810^{-8} 23 9.2×10−99.2 \times 10^{-9}
10−1210^{-12} 41 9.4×10−139.4 \times 10^{-13}

Each factor of 10 in the tolerance costs about 4.5 sweeps, the sign of linear convergence. The three constraints of water form a triangle, and they are strongly coupled.

A chain. Four atoms of masses 1, 2, 2, 1 with three rigid bonds and soft springs between atoms that are not neighbours, run from rest for a time of 20. All bonds hold to 10−1110^{-11}. The total energy moves within a band of width 4.86×10−44.86 \times 10^{-4} for h=0.02h = 0.02 and 1.21×10−41.21 \times 10^{-4} for h=0.01h = 0.01: halving the step divides the band by 4, and the energy does not drift.

Correctness

The proof below shows these claims:

  1. The form of the result. At every moment of the loop, the positions are the free step plus corrections along the old bond vectors, weighted by the inverse masses. So the result has the form of the constrained Verlet step.
  2. Line L5 is a Newton step for the single constraint as a function of its multiplier.
  3. The stopping test. When the loop returns, every constraint holds to the relative tolerance, so the result solves the constrained Verlet equations to that tolerance.
  4. The centre of mass does not move during the corrections.
  5. Local convergence. For a small step and constraints that are not nearly dependent, the sweeps converge, and the error falls by a fixed factor in each sweep, the spectral radius of a Gauss-Seidel iteration matrix.

The tests check one bond against the root of the quadratic, a branched molecule against a full Newton solve of all the constraints, the centre of mass, a fixed atom, the energy band of the chain, and the error for a set of constraints that cannot all hold.

Proof: SHAKE returns positions of the constrained Verlet form that satisfy every bond, keeps the centre of mass, and converges near a solutionfull

We use the line numbers of the pseudocode. There are NN atoms with inverse masses wi=1/mi≥0w_i = 1/m_i \ge 0 and CC constraints c=(i,j,dc)c = (i, j, d_c), each asking σc(x)=∣xi−xj∣2−dc2=0\sigma_c(x) = |x_i - x_j|^2 - d_c^2 = 0. Write rc=xiold−xjoldr_c = x^{\text{old}}_i - x^{\text{old}}_j for the bond vector at the old positions xnx^n. The constrained position Verlet method of Ryckaert, Ciccotti and Berendsen (1977) asks for xn+1x^{n+1} and multipliers λ\lambda with

xn+1=2xn−xn−1+h2Wf(xn)−h2W∇σ(xn)Tλ,σ(xn+1)=0,x^{n+1} = 2x^n - x^{n-1} + h^2 W f(x^n) - h^2 W \nabla\sigma(x^n)^{\mathsf T} \lambda, \qquad \sigma(x^{n+1}) = 0,

where WW is the diagonal matrix of inverse masses. The gradient of σc\sigma_c at xnx^n is 2rc2 r_c at atom ii, −2rc-2 r_c at atom jj and 0 elsewhere.

Claim 1 (the form of the result). At every point of the loop, x=xunc+∑cgc Wbcx = x^{\text{unc}} + \sum_c g_c \, W b_c for some numbers gcg_c, where xuncx^{\text{unc}} is the result of line L1 and bcb_c has rcr_c at atom ii, −rc-r_c at atom jj and 0 elsewhere.

Proof. Line L6 adds wigrcw_i g r_c to xix_i and subtracts wjgrcw_j g r_c from xjx_j, which adds gWbcg W b_c to xx. By induction over the updates, the sum of the gg values for each constraint is gcg_c. □\square

Since bc=12∇σc(xn)b_c = \frac12 \nabla \sigma_c(x^n), the result has the form of the constrained Verlet step with λc=−gc/(2h2)\lambda_c = -g_c / (2h^2).

Claim 2 (line L5 is a Newton step). For one constraint cc with the others fixed, line L5 is one Newton step at g=0g = 0 for the equation ψ(g)=dc2−∣s+(wi+wj)grc∣2=0\psi(g) = d_c^2 - |s + (w_i + w_j) g r_c|^2 = 0, where s=xi−xjs = x_i - x_j.

Proof. Line L6 changes ss to s+(wi+wj)grcs + (w_i + w_j) g r_c. Then ψ(0)=dc2−∣s∣2\psi(0) = d_c^2 - |s|^2 and ψ′(0)=−2(wi+wj)s⋅rc\psi'(0) = -2 (w_i + w_j) s \cdot r_c, so the Newton step is g=(dc2−∣s∣2)/(2(wi+wj)s⋅rc)g = (d_c^2 - |s|^2) / \bigl(2 (w_i + w_j) s \cdot r_c\bigr), the formula of line L5. □\square

The code refuses the step when wi+wj=0w_i + w_j = 0 or s⋅rc≤0s \cdot r_c \le 0, where the Newton step has no meaning. This happens when a bond has rotated by more than a right angle in one step, which a usable time step never does.

Claim 3 (the stopping test). If the loop returns, every constraint holds to the relative tolerance: ∣dc2−∣xi−xj∣2∣≤2τdc2|d_c^2 - |x_i - x_j|^2| \le 2 \tau d_c^2, so ∣∣xi−xj∣−dc∣≤τdc(1+O(τ))\bigl| |x_i - x_j| - d_c \bigr| \le \tau d_c (1 + O(\tau)).

Proof. The loop returns at line L7 only after a sweep in which line L4 found every constraint within the tolerance. In such a sweep line L6 never runs, so xx does not change during the sweep, and every test of line L4 applied to the final xx. For the second form, ∣a2−d2∣=∣a−d∣(a+d)≥∣a−d∣d|a^2 - d^2| = |a - d| (a + d) \ge |a - d| d. □\square

With Claim 1, the returned positions solve the constrained Verlet equations up to the tolerance. Otherwise the code raises an error after max_sweeps sweeps, so it never returns positions that break a constraint.

Claim 4 (the centre of mass). If no atom is fixed, ∑imixi\sum_i m_i x_i is the same before and after the loop.

Proof. Line L6 changes it by miwigrc−mjwjgrc=grc−grc=0m_i w_i g r_c - m_j w_j g r_c = g r_c - g r_c = 0. □\square

With position Verlet, the velocity estimate (xn+1−xn−1)/2h(x^{n+1} - x^{n-1})/2h then keeps the total momentum when ff is a sum of pair forces.

Claim 5 (local convergence). Let x⋆x^\star be a solution of the form of Claim 1, and let Jcd=2bc(x⋆)TWbdJ_{cd} = 2 b_c(x^\star)^{\mathsf T} W b_d, where bc(x⋆)b_c(x^\star) is built like bcb_c from the bond vectors xi⋆−xj⋆x^\star_i - x^\star_j. If the Gauss-Seidel iteration matrix of JJ has spectral radius ρ<1\rho < 1, then for xuncx^{\text{unc}} close enough to x⋆x^\star the sweeps converge to x⋆x^\star, and the error falls asymptotically by the factor ρ\rho in each sweep.

Proof. In the variables gg, the equations are Φc(g)=dc2−∣sc(g)∣2=0\Phi_c(g) = d_c^2 - |s_c(g)|^2 = 0, and their Jacobian at the solution is −J-J. One sweep of lines L3 to L6 is a nonlinear Gauss-Seidel sweep in which each unknown gets one Newton step (Claim 2). The derivative of this sweep map at the solution is the Gauss-Seidel iteration matrix of JJ, the same as for the linear system with matrix JJ. A fixed-point map whose derivative at the fixed point has spectral radius ρ<1\rho < 1 converges locally, with the rate ρ\rho. □\square

For a small step, xi⋆−xj⋆x^\star_i - x^\star_j is close to rcr_c, so JJ is close to Jcd0=2bcTWbdJ^0_{cd} = 2 b_c^{\mathsf T} W b_d. J0J^0 is symmetric and positive definite when the vectors W1/2bcW^{1/2} b_c are linearly independent, and then its Gauss-Seidel iteration matrix has spectral radius below 1, by the classical theorem on the Gauss-Seidel method. The spectral radius depends continuously on the matrix, so ρ<1\rho < 1 for small steps. This fails, and SHAKE slows down or stops converging, when the bonds form a nearly flat ring or another nearly dependent set. The water triangle of the example needs about 4.5 sweeps for each factor of 10 in the tolerance, which shows the linear rate.

What is not claimed. The velocities of position Verlet are not on the tangent space of the constraints, and the method is not written in velocity form. The RATTLE algorithm adds the velocity constraint, and it gives the same positions as SHAKE from the same two starting positions.

Complexity

The free step costs Θ(N)\Theta(N) plus the force. One sweep costs Θ(C)\Theta(C), so the step costs Θ(N+sC)\Theta(N + sC) for ss sweeps. The number of sweeps is about log⁡(1/τ)/log⁡(1/ρ)\log(1/\tau) / \log(1/\rho), where ρ\rho is the convergence factor of Claim 5. It is small for isolated bonds and large for rings and long chains of coupled bonds. Extra memory is Θ(N)\Theta(N) for the old bond vectors.

Properties

  • Time reversible. The constrained Verlet step is symmetric in time, if the constraints are solved exactly.
  • Symplectic positions. SHAKE gives the same positions as RATTLE, which is a symplectic method on the constraint manifold (Leimkuhler and Skeel, 1994). So the energy stays in a band and does not drift.
  • Momentum. The corrections keep the centre of mass, and with pair forces the total momentum is kept.
  • Sequential. Each correction uses the result of the one before, which makes the sweep hard to run in parallel.
  • Order two. The positions have the global error O(h2)O(h^2) of Verlet.

Variants and improvements

  • RATTLE. RATTLE puts the same idea into velocity Verlet, and adds a second loop that makes the velocities tangent to the constraints.
  • LINCS. LINCS replaces the sweep by a truncated matrix series, which is faster and runs in parallel, at a fixed cost per step.
  • SETTLE. For a rigid water, the three constraints have a closed-form solution, so no iteration is needed.
  • Over-relaxation. Multiplying the correction by a factor between 1 and 2 can cut the number of sweeps, as in successive over-relaxation.
  • Matrix SHAKE. A Newton method on all multipliers at once, with a sparse matrix, converges in fewer iterations for large rigid systems.

When to use it

Use SHAKE to hold bonds to hydrogen fixed in a molecular simulation, which allows a step of about 2 fs instead of about 1 fs. It is simple to code and reliable for small groups of coupled constraints. For large rigid molecules on many processors, use LINCS. For rigid water, use a closed-form method. If the integrator is velocity Verlet, use RATTLE, which contains SHAKE as its position stage.

Pitfalls

  • A loose tolerance. The energy then drifts, because the step is no longer exactly reversible. Use a relative tolerance of 10−810^{-8} or smaller in double precision.
  • Coupled angles. Constraining bond angles as well as bonds makes the constraints nearly dependent, and the sweeps converge slowly or not at all. Constrain angles through a third distance, and only where the geometry stays far from flat.
  • A step that is too large. A bond that turns by a right angle in one step has s⋅rc≤0s \cdot r_c \le 0, and the Newton step breaks down.
  • Velocities. Position Verlet gives velocities as differences of positions, which do not satisfy the velocity constraints. Kinetic energy and temperature then have a small error.
  • Degrees of freedom. Each constraint removes one degree of freedom. Count them when you compute a temperature from the kinetic energy.

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.

shake_constraint_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shake-constraint-algorithm/. The authors are listed in prov/3AE47X.jsonl.
"""SHAKE: Verlet integration with holonomic bond-length constraints.

This is the method of Ryckaert, Ciccotti and Berendsen (1977). Each
constraint (i, j, d) asks |x_i - x_j| = d. The unconstrained Verlet step
gives trial positions. The constraint forces act along the bond vectors of
the old positions, so the correct new positions are

    x_i = x_unc_i + w_i sum over constraints c of +-g_c r_old_c,

with w_i = 1 / m_i the inverse mass (0 for a fixed atom). SHAKE finds the
multipliers g_c one constraint at a time, in a Gauss-Seidel sweep, with one
linearised Newton step per constraint, and repeats the sweep until every
constraint holds to a relative tolerance.

Cost: Theta(C) per sweep for C constraints. The number of sweeps grows
when the constraints are strongly coupled (rings, long rigid chains).
"""

import math
from typing import Callable

Vec = list[float]
Bond = tuple[int, int, float]


def shake(
    x_old: list[Vec], x_unc: list[Vec], inv_mass: list[float], bonds: list[Bond],
    tol: float = 1e-12, max_sweeps: int = 1000,
) -> tuple[list[Vec], int]:
    """Correct x_unc so that every bond holds; return the positions and the number of sweeps."""
    x = [list(p) for p in x_unc]
    for sweep in range(1, max_sweeps + 1):  # @line L2
        done = True
        for i, j, d in bonds:  # @line L3
            s = [x[i][a] - x[j][a] for a in range(3)]
            diff = d * d - (s[0] * s[0] + s[1] * s[1] + s[2] * s[2])
            if abs(diff) <= 2.0 * tol * d * d:  # @line L4
                continue
            done = False
            r = [x_old[i][a] - x_old[j][a] for a in range(3)]
            dot = s[0] * r[0] + s[1] * r[1] + s[2] * r[2]
            wsum = inv_mass[i] + inv_mass[j]
            if wsum == 0.0 or dot <= 0.0:
                raise ValueError("constraint cannot be corrected along the old bond")
            g = diff / (2.0 * wsum * dot)  # @line L5
            for a in range(3):  # @line L6
                x[i][a] += inv_mass[i] * g * r[a]
                x[j][a] -= inv_mass[j] * g * r[a]
        if done:  # @line L7
            return x, sweep
    raise RuntimeError("SHAKE did not converge")


def shake_verlet_step(
    x_prev: list[Vec], x: list[Vec], inv_mass: list[float], force: Callable[[list[Vec]], list[Vec]],
    h: float, bonds: list[Bond], tol: float = 1e-12,
) -> list[Vec]:
    """One step of position Verlet with SHAKE: from x_(n-1) and x_n return x_(n+1)."""
    f = force(x)
    x_unc = [[2.0 * x[i][a] - x_prev[i][a] + h * h * inv_mass[i] * f[i][a] for a in range(3)] for i in range(len(x))]  # @line L1
    x_new, _ = shake(x, x_unc, inv_mass, bonds, tol)
    return x_new  # @line L8


def bond_error(x: list[Vec], bonds: list[Bond]) -> float:
    """Largest relative error |(|x_i - x_j| - d) / d| over the bonds."""
    return max(abs(math.dist(x[i], x[j]) - d) / d for i, j, d in bonds)
test_shake_constraint_algorithm.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/shake-constraint-algorithm/. The authors are listed in prov/3AE47X.jsonl.

import math
import random

import pytest

from shake_constraint_algorithm import bond_error, shake, shake_verlet_step


def perturbed(x, rng, size):
    return [[c + rng.uniform(-size, size) for c in p] for p in x]


def solve_dense(a, b):
    """Gaussian elimination with partial pivoting, the reference linear solver."""
    n = len(b)
    m = [list(row) + [b[i]] for i, row in enumerate(a)]
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for k in range(c, n + 1):
                m[r][k] -= f * m[c][k]
    out = [0.0] * n
    for r in range(n - 1, -1, -1):
        out[r] = (m[r][n] - sum(m[r][k] * out[k] for k in range(r + 1, n))) / m[r][r]
    return out


def newton_reference(x_old, x_unc, w, bonds):
    """Solve all constraint equations at once by Newton's method on the multipliers."""
    nc = len(bonds)
    g = [0.0] * nc

    def positions(g):
        x = [list(p) for p in x_unc]
        for (i, j, _), gc in zip(bonds, g):
            for a in range(3):
                r = x_old[i][a] - x_old[j][a]
                x[i][a] += w[i] * gc * r
                x[j][a] -= w[j] * gc * r
        return x

    for _ in range(50):
        x = positions(g)
        res = [sum((x[i][a] - x[j][a]) ** 2 for a in range(3)) - d * d for i, j, d in bonds]
        if max(abs(v) for v in res) < 1e-15:
            break
        jac = [[0.0] * nc for _ in range(nc)]
        for c, (i, j, _) in enumerate(bonds):
            s = [x[i][a] - x[j][a] for a in range(3)]
            for e, (k, l, _) in enumerate(bonds):
                r = [x_old[k][a] - x_old[l][a] for a in range(3)]
                coef = (w[k] if k == i else 0.0) - (w[k] if k == j else 0.0) - (w[l] if l == i else 0.0) + (w[l] if l == j else 0.0)
                jac[c][e] = 2.0 * coef * sum(s[a] * r[a] for a in range(3))
        step = solve_dense(jac, [-v for v in res])
        g = [a + b for a, b in zip(g, step)]
    return positions(g)


def test_single_bond_matches_the_quadratic_root() -> None:
    x_old = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0]]
    x_unc = [[0.05, 0.1, -0.02], [1.2, -0.05, 0.03]]
    w = [1.0, 0.25]
    x, _ = shake(x_old, x_unc, w, [(0, 1, 1.0)])
    # |s + c g r|^2 = d^2 is a quadratic in g; take the root of smaller size
    s = [x_unc[0][a] - x_unc[1][a] for a in range(3)]
    r = [-1.0, 0.0, 0.0]
    c = w[0] + w[1]
    qa, qb, qc = c * c, 2 * c * sum(u * v for u, v in zip(s, r)), sum(u * u for u in s) - 1.0
    roots = [(-qb + sg * math.sqrt(qb * qb - 4 * qa * qc)) / (2 * qa) for sg in (1, -1)]
    g = min(roots, key=abs)
    exact0 = [x_unc[0][a] + w[0] * g * r[a] for a in range(3)]
    assert math.dist(x[0], exact0) < 1e-12


def test_coupled_bonds_match_a_newton_solve() -> None:
    rng = random.Random(3)
    # a branched molecule: a centre bonded to three atoms, plus one bond between two of them
    x_old = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [-0.3, 0.95, 0.0], [-0.3, -0.4, 0.87], [1.5, 0.9, 0.0]]
    bonds = [(0, 1, 1.0), (0, 2, math.dist(x_old[0], x_old[2])), (0, 3, math.dist(x_old[0], x_old[3])), (1, 4, math.dist(x_old[1], x_old[4])), (2, 4, math.dist(x_old[2], x_old[4]))]
    w = [1 / 16, 1.0, 1.0, 1 / 12, 0.5]
    x_unc = perturbed(x_old, rng, 0.05)
    x, sweeps = shake(x_old, x_unc, w, bonds)
    assert bond_error(x, bonds) < 1e-11
    ref = newton_reference(x_old, x_unc, w, bonds)
    assert max(math.dist(a, b) for a, b in zip(x, ref)) < 1e-10
    assert sweeps > 2  # the bonds are coupled, so one sweep is not enough


def test_corrections_keep_the_centre_of_mass() -> None:
    rng = random.Random(4)
    x_old = [[float(k), 0.3 * (k % 2), 0.0] for k in range(5)]
    bonds = [(k, k + 1, math.dist(x_old[k], x_old[k + 1])) for k in range(4)]
    m = [1.0, 12.0, 14.0, 1.0, 16.0]
    w = [1 / v for v in m]
    x_unc = perturbed(x_old, rng, 0.04)
    x, _ = shake(x_old, x_unc, w, bonds)
    for a in range(3):
        assert abs(sum(mi * p[a] for mi, p in zip(m, x)) - sum(mi * p[a] for mi, p in zip(m, x_unc))) < 1e-12


def test_fixed_atom_does_not_move() -> None:
    x_old = [[0.0, 0.0, 0.0], [0.0, -1.0, 0.0]]
    x_unc = [[0.0, 0.0, 0.0], [0.2, -1.05, 0.0]]
    x, _ = shake(x_old, x_unc, [0.0, 1.0], [(0, 1, 1.0)])
    assert x[0] == [0.0, 0.0, 0.0]
    assert abs(math.dist(x[0], x[1]) - 1.0) < 1e-12


def chain_force(x):
    # springs between atoms two apart in a rigid chain of four, and a soft wall in z
    f = [[0.0] * 3 for _ in x]
    for i, j in ((0, 2), (1, 3), (0, 3)):
        s = [x[i][a] - x[j][a] for a in range(3)]
        r = math.sqrt(sum(c * c for c in s))
        mag = -2.0 * (r - 1.6)
        for a in range(3):
            f[i][a] += mag * s[a] / r
            f[j][a] -= mag * s[a] / r
    return f


def chain_energy(x, v, m):
    e = sum(0.5 * mi * sum(c * c for c in vi) for mi, vi in zip(m, v))
    for i, j in ((0, 2), (1, 3), (0, 3)):
        e += (math.dist(x[i], x[j]) - 1.6) ** 2
    return e


def run_chain(h: float, t_end: float) -> tuple[float, float]:
    m = [1.0, 2.0, 2.0, 1.0]
    w = [1 / v for v in m]
    x0 = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.5, 0.85, 0.1], [2.4, 1.1, -0.3]]
    bonds = [(k, k + 1, math.dist(x0[k], x0[k + 1])) for k in range(3)]
    # start at rest: x_(-1) = x_0 is a consistent start with zero velocity
    xs = [x0, shake_verlet_step(x0, x0, w, chain_force, h, bonds)]
    xs[1] = [[0.5 * (a + b) for a, b in zip(p, q)] for p, q in zip(x0, xs[1])]
    xs[1], _ = shake(x0, xs[1], w, bonds)
    steps = int(round(t_end / h))
    worst = 0.0
    energies = []
    for _ in range(steps):
        xs.append(shake_verlet_step(xs[-2], xs[-1], w, chain_force, h, bonds))
        worst = max(worst, bond_error(xs[-1], bonds))
        v = [[(a - b) / (2 * h) for a, b in zip(p, q)] for p, q in zip(xs[-1], xs[-3])]
        energies.append(chain_energy(xs[-2], v, m))
        xs = xs[-2:]
    return max(energies) - min(energies), worst


def test_bonds_hold_and_energy_stays_bounded() -> None:
    spread_h, worst = run_chain(0.02, 20.0)
    assert worst < 1e-11
    spread_h2, _ = run_chain(0.01, 20.0)
    assert spread_h < 0.05
    assert 2.5 < spread_h / spread_h2 < 6.0  # second order: halving h divides the fluctuation by about 4


def test_divergence_is_reported() -> None:
    with pytest.raises(RuntimeError):
        x_old = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0]]
        x_unc = [[0.0, 0.0, 0.0], [1.0, 0.3, 0.0], [2.0, 0.0, 0.0]]
        shake(x_old, x_unc, [1.0, 1.0, 1.0], [(0, 1, 1.0), (1, 2, 1.0), (0, 2, 1.9)], max_sweeps=20)

History

Ryckaert, Ciccotti and Berendsen (1977) gave the method for molecular dynamics of n-alkanes with rigid bonds. They wrote the Verlet step with Lagrange multipliers and solved for the multipliers iteratively, one constraint at a time. Andersen (1983) gave RATTLE, the velocity version. Leimkuhler and Skeel (1994) showed that RATTLE is symplectic and that SHAKE gives the same positions. Hess, Bekker, Berendsen and Fraaije (1997) gave LINCS as a faster and more parallel replacement.

References

  1. Jean-Paul Ryckaert, Giovanni Ciccotti and Herman J. C. Berendsen, Numerical integration of the cartesian equations of motion of a system with constraints, molecular dynamics of n-alkanes, Journal of Computational Physics 23(3), 1977, 327-341, the constrained Verlet equations and their iterative solution, one constraint at a time
  2. Benedict J. Leimkuhler and Robert D. Skeel, Symplectic numerical integrators in constrained Hamiltonian systems, Journal of Computational Physics 112(1), 1994, 117-125, the relation of SHAKE and RATTLE, and their symplecticity
  3. Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Chapter 3, Molecular dynamics, the section on constraint dynamics

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