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
- Model
- Real RAM
- Properties
- deterministiciterativetime reversible
- Evidence
- Proof sketchCode in 1 languages
- 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 atoms with positions , masses and inverse masses (zero for a fixed atom), a force , and constraints , each asking . Given and that satisfy the constraints, and the step , find and multipliers with
where is the diagonal matrix of the . The constraint forces act along the old bond vectors . The equations for are nonlinear, and we solve them to a relative tolerance .
The algorithm
SHAKE-STEP(x_prev, x, w, f, h, bonds, τ)- 1
x̃ ← 2x - x_prev + h² W f(x) ▷ the free Verlet step - 2
repeat - 3
for each constraint c = (i, j, d) do - 4
s ← x̃_i - x̃_j; if |d² - |s|²| ≤ 2τ d² then skip this constraint - 5
g ← (d² - |s|²) / (2 (w_i + w_j) s · r_c) ▷ r_c = x_i - x_j, the old bond - 6
x̃_i ← x̃_i + w_i g r_c; x̃_j ← x̃_j - w_j g r_c - 7
until a whole sweep skips every constraint - 8
return x̃
Line L5 is one Newton step for the single constraint, with all other atoms held fixed. The code stops with an error if , 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 , atom 1 has , and the old bond is with . The free step puts the atoms at and , so and . The exact correction solves the quadratic for . SHAKE takes Newton steps on this equation and reaches the smaller root to .
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 Å (seed 1), which breaks the bonds by up to . The number of sweeps for three tolerances:
| tolerance | sweeps | largest relative bond error |
|---|---|---|
| 5 | ||
| 23 | ||
| 41 |
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 . The total energy moves within a band of width for and for : halving the step divides the band by 4, and the energy does not drift.
Correctness
The proof below shows these claims:
- 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.
- Line L5 is a Newton step for the single constraint as a function of its multiplier.
- 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.
- The centre of mass does not move during the corrections.
- 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 atoms with inverse masses and constraints , each asking . Write for the bond vector at the old positions . The constrained position Verlet method of Ryckaert, Ciccotti and Berendsen (1977) asks for and multipliers with
where is the diagonal matrix of inverse masses. The gradient of at is at atom , at atom and 0 elsewhere.
Claim 1 (the form of the result). At every point of the loop, for some numbers , where is the result of line L1 and has at atom , at atom and 0 elsewhere.
Proof. Line L6 adds to and subtracts from , which adds to . By induction over the updates, the sum of the values for each constraint is .
Since , the result has the form of the constrained Verlet step with .
Claim 2 (line L5 is a Newton step). For one constraint with the others fixed, line L5 is one Newton step at for the equation , where .
Proof. Line L6 changes to . Then and , so the Newton step is , the formula of line L5.
The code refuses the step when or , 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: , so .
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 does not change during the sweep, and every test of line L4 applied to the final . For the second form, .
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, is the same before and after the loop.
Proof. Line L6 changes it by .
With position Verlet, the velocity estimate then keeps the total momentum when is a sum of pair forces.
Claim 5 (local convergence). Let be a solution of the form of Claim 1, and let , where is built like from the bond vectors . If the Gauss-Seidel iteration matrix of has spectral radius , then for close enough to the sweeps converge to , and the error falls asymptotically by the factor in each sweep.
Proof. In the variables , the equations are , and their Jacobian at the solution is . 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 , the same as for the linear system with matrix . A fixed-point map whose derivative at the fixed point has spectral radius converges locally, with the rate .
For a small step, is close to , so is close to . is symmetric and positive definite when the vectors 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 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 plus the force. One sweep costs , so the step costs for sweeps. The number of sweeps is about , where 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 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 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 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 , 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.
# 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
- 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
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 3AE47X Edit this page History Report an error Markdown