Algorithmcore
RATTLE algorithm
Also called RATTLE.
Extends SHAKE to velocity Verlet by also projecting velocities onto the tangent space of the constraints, giving a symplectic constrained integrator.
- 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
- deterministiciterativesymplectictime reversible
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Hans C. Andersen, 1983
RATTLE integrates the motion of particles with fixed distances between some pairs, using velocity Verlet. A fixed distance is a constraint, such as a rigid bond in a molecule or a rigid link in a mechanism, and it asks two things: that the distance has the right value, and that the two particles have no relative velocity along the line between them. The position stage is the SHAKE iteration: after a half kick and a drift, it corrects the positions and the half-step velocities along the old bond directions until every distance holds. The velocity stage, which SHAKE does not have, corrects the new velocities along the new bond directions until each one is tangent to the constraints. Both stages iterate to a tolerance. The result is symplectic and time reversible on the set of allowed states, so the energy stays in a band over long runs. Graphics methods such as position-based dynamics project positions and then take velocities from the change of position; RATTLE instead keeps the momenta as variables and treats both constraints exactly.
In plain words
Imagine a pendulum with a rigid rod. The bob must stay at the same distance from the pivot, and it must never move toward or away from the pivot. Its velocity must always point along the circle.
RATTLE moves the bob one step as if the rod were not there. Then it pulls the bob back to the right distance, as SHAKE does, and fixes the velocity it used so that it matches that move. After the new forces act, the velocity has a small part that points along the rod. RATTLE removes that part. When there are many rods that share atoms, fixing one upsets the next, so both corrections go over all the rods again and again until each one is right to the requested accuracy.
The problem
There are atoms with positions , velocities , inverse masses (zero for a fixed atom), a force , and constraints with . Let be the matrix with rows , so the velocity constraint is . Given with and , and the step , find
where is the diagonal matrix of the and are multipliers.
The algorithm
RATTLE-STEP(x, v, f, w, force, h, bonds, τ)- 1
v' ← v + (h/2) W f ▷ half kick - 2
x' ← x + h v' ▷ drift - 3
repeat sweeps over the constraints c = (i, j, d), until each has |d² - |x'_i - x'_j|²| ≤ 2τd² - 4
g ← (d² - |s|²) / (2 (w_i + w_j) s · r); shift x'_i, x'_j by ±w g r and v'_i, v'_j by ±w g r / h - 5
f' ← force(x') - 6
v'' ← v' + (h/2) W f' ▷ second half kick - 7
repeat sweeps over the constraints, until each has |r' · (v''_i - v''_j)| ≤ τ d² - 8
k ← -r' · (v''_i - v''_j) / ((w_i + w_j) d²); v''_i ← v''_i + w_i k r'; v''_j ← v''_j - w_j k r' - 9
return (x', v'', f')
Here , is the old bond, and is the new bond. The velocity equations are linear in , so the loop of line L7 is a Gauss-Seidel solve of a linear system. Each loop stops with an error if it does not converge in a set number of sweeps.
Example
Take a pendulum of length 1 and mass 1 under gravity , as an anchor with and a bob joined by one constraint. Released at rest from the angle , its exact period is . The period from RATTLE, measured from the crossings of the vertical:
| step | period error |
|---|---|
| 0.04 | |
| 0.02 | |
| 0.01 |
Each halving of the step divides the error by 4.0, the second order of velocity Verlet. In every step, the rod length and the radial velocity are zero to .
Released from , close to horizontal, and run to the time 200, about 25 periods, the energy error is at most with and with . The largest error after the time 20 is the same as before it, to three digits: the energy moves in a band and does not drift.
Correctness
The proof below shows these claims:
- The position stage returns , with the velocity corrections along the rows of , and every bond within the tolerance.
- The velocity stage returns with corrections along the rows of , and every velocity constraint within the tolerance.
- Time reversal. One step from returns to , when the equations have locally unique solutions.
- The positions are those of SHAKE. Three successive positions satisfy the constrained Verlet equations, so RATTLE and SHAKE give the same positions from the same start.
- Order and symplecticity. RATTLE has order 2 and is a symplectic map on the states that satisfy both constraints. These are theorems of Leimkuhler and Skeel (1994), cited and not proved again.
The tests check the period of the pendulum against the exact value, both constraints on every step of a chain, reversibility to , the preserved area of the pendulum map, the energy band, and agreement with the SHAKE positions to .
Proof: RATTLE solves the constrained velocity Verlet equations, keeps both constraints, is time-reversible, and gives the SHAKE positionsfull
We use the line numbers of the pseudocode. There are atoms with inverse masses , forces , and constraints with . Let be the matrix whose row is : it has at atom , at atom and 0 elsewhere. Let be the diagonal matrix of inverse masses. The RATTLE equations of Andersen (1983) for one step from are
The unknowns are , , and the multipliers . The equation is the time derivative of : each bond has zero relative velocity along itself.
Claim 1 (the position stage). After the loop of line L3, , for some , and every bond holds to the tolerance.
Proof. Lines L1 and L2 start the identities with . Each update of line L4 adds to and to , and subtracts the same from atom , where is the bond vector at . So does not change, and changes by times row of , so the identity holds with the sum of the values for constraint . The formula for is the Newton step of the SHAKE page, and the loop ends only after a sweep with no correction, so every bond holds to the tolerance.
With this is the first line of the RATTLE equations.
Claim 2 (the velocity stage). After the loop of line L7, for some , and for every constraint.
Proof. Line L6 starts the identity with . Line L8 adds to and subtracts from , where is row of at atom . Its change of is , and since up to the tolerance of Claim 1, makes zero up to that tolerance. The loop ends only after a sweep in which every constraint passed the test.
The velocity equations are linear in with the matrix , which is symmetric and positive definite when the rows of are linearly independent. Then the Gauss-Seidel sweeps of line L7 converge for every start, by the classical theorem on the Gauss-Seidel method. The position stage is the SHAKE iteration and converges near a solution under the condition proved on the SHAKE page.
Claim 3 (time reversal). Suppose satisfies both constraints, and that the RATTLE equations have locally unique solutions. If one step maps to , then one step maps to .
Proof. Start from and try the multiplier in the first stage:
by the third equation of the forward step. Then the new position is , which satisfies , so solves the position stage. In the second stage try : by the first equation of the forward step, and by the assumption on the start. By uniqueness these are the solutions.
The test runs 200 steps forward and 200 back with the velocities reversed and returns to the start within .
Claim 4 (the positions are those of SHAKE). If are three positions of a RATTLE run, then for some , and . So, from the same two starting positions, RATTLE and the constrained position Verlet method of the SHAKE page give the same positions, as long as the SHAKE equations have a locally unique solution.
Proof. From the equations of two consecutive steps, , where comes from the second stage of step and from the first stage of step . Both use . Multiply by and use and , with .
Claim 5 (order and symplecticity). RATTLE is a symplectic map on the manifold of states that satisfy both constraints, and it has order 2. These are theorems of Leimkuhler and Skeel (1994), also proved by Hairer, Lubich and Wanner (2006) for constrained mechanical systems. We do not repeat the proofs. The test checks the consequences: for a pendulum the map preserves the area to , the period error falls by a factor of 4 when is halved, and the energy error does not grow over thirty periods.
In floating-point arithmetic with a tolerance , every claim holds up to errors of size and rounding. Claim 3 needs a tight tolerance: a loose one breaks reversibility and symplecticity, and the energy then drifts.
Complexity
The kicks and the drift cost plus one force evaluation. Each sweep of either loop costs . The position loop needs a number of sweeps that grows like over the log of the convergence factor, as in SHAKE. The velocity loop solves a linear system with the same coupling, so its number of sweeps behaves in the same way. Extra memory is .
Properties
- Symplectic. On the manifold of states that satisfy both constraints, the step preserves the symplectic form, a theorem of Leimkuhler and Skeel (1994). The energy error therefore stays bounded over long runs, as explained by the shadow Hamiltonian theory.
- Time reversible, when both loops are solved to a tight tolerance.
- Order two, like velocity Verlet.
- Consistent velocities. The velocities satisfy the velocity constraints, so the kinetic energy and the temperature come out right.
- One force evaluation per step, the same as velocity Verlet without constraints.
Variants and improvements
- SHAKE. SHAKE is the position form, with the same positions and no velocity stage.
- LINCS. LINCS replaces the position loop by a matrix series, and a projection of the same kind gives the velocities.
- SETTLE. For rigid water, both stages have closed-form solutions.
- Newton solves. For large rigid molecules, solve all the multipliers of each stage at once with a sparse linear solver.
- Other splittings. The same two projections can go into the RESPA integrator or a Langevin splitting, after each position update and each velocity update.
When to use it
Use RATTLE with velocity Verlet whenever a simulation holds bonds or rigid groups fixed, and you need good velocities, for example to compute a temperature, a pressure, or a time correlation function. It is a standard choice for constrained molecular dynamics and for mechanical systems with rigid links. For very large systems in parallel, LINCS is faster. For a fixed small number of passes and visual results, position-based dynamics is cheaper.
Pitfalls
- A loose tolerance breaks reversibility and symplecticity, and the energy then drifts. Use or tighter in double precision.
- Skipping the velocity stage leaves a radial velocity of order in each bond. The positions are still those of SHAKE, but kinetic energies are wrong.
- The wrong bond vectors. The position stage corrects along the old bonds and the velocity stage along the new bonds. Mixing them up loses symplecticity.
- Fixed atoms. An atom with must not be in a constraint with another fixed atom, because then .
- Degrees of freedom. Each constraint removes one degree of freedom from the count used for the temperature.
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/rattle-algorithm/. The authors are listed in prov/VJX93A.jsonl.
"""RATTLE: velocity Verlet with bond-length constraints on positions and velocities.
This is the method of Andersen (1983). Each constraint (i, j, d) asks
|x_i - x_j| = d, and its time derivative asks (x_i - x_j) . (v_i - v_j) = 0.
One step has two constraint stages.
1. Position stage. Kick and drift as in velocity Verlet, then correct the
half-step velocities along the old bond vectors (the SHAKE iteration)
until the new positions satisfy every bond length.
2. Velocity stage. Kick with the new forces, then correct the velocities
along the new bond vectors until every bond has zero relative velocity
along its own direction.
w_i = 1 / m_i is the inverse mass (0 for a fixed atom). Both stages solve
their equations to a relative tolerance by Gauss-Seidel sweeps. If both are
solved exactly, the map is symplectic on the constraint manifold and
time-reversible.
"""
from typing import Callable
Vec = list[float]
Bond = tuple[int, int, float]
Force = Callable[[list[Vec]], list[Vec]]
def _dot(a: Vec, b: Vec) -> float:
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
def rattle_step(
x: list[Vec], v: list[Vec], f: list[Vec], inv_mass: list[float], force: Force, h: float,
bonds: list[Bond], tol: float = 1e-13, max_sweeps: int = 1000,
) -> tuple[list[Vec], list[Vec], list[Vec]]:
"""One RATTLE step from (x, v) with forces f = force(x); return the new x, v and forces."""
n = len(x)
vh = [[v[i][a] + 0.5 * h * inv_mass[i] * f[i][a] for a in range(3)] for i in range(n)] # @line L1
xn = [[x[i][a] + h * vh[i][a] for a in range(3)] for i in range(n)] # @line L2
for _ in range(max_sweeps): # @line L3
done = True
for i, j, d in bonds:
s = [xn[i][a] - xn[j][a] for a in range(3)]
diff = d * d - _dot(s, s)
if abs(diff) <= 2.0 * tol * d * d:
continue
done = False
r = [x[i][a] - x[j][a] for a in range(3)]
g = diff / (2.0 * (inv_mass[i] + inv_mass[j]) * _dot(s, r)) # @line L4
for a in range(3):
xn[i][a] += inv_mass[i] * g * r[a]
xn[j][a] -= inv_mass[j] * g * r[a]
vh[i][a] += inv_mass[i] * g * r[a] / h
vh[j][a] -= inv_mass[j] * g * r[a] / h
if done:
break
else:
raise RuntimeError("RATTLE position stage did not converge")
fn = force(xn) # @line L5
vn = [[vh[i][a] + 0.5 * h * inv_mass[i] * fn[i][a] for a in range(3)] for i in range(n)] # @line L6
for _ in range(max_sweeps): # @line L7
done = True
for i, j, d in bonds:
r = [xn[i][a] - xn[j][a] for a in range(3)]
rv = _dot(r, [vn[i][a] - vn[j][a] for a in range(3)])
if abs(rv) <= tol * d * d:
continue
done = False
k = -rv / ((inv_mass[i] + inv_mass[j]) * d * d) # @line L8
for a in range(3):
vn[i][a] += inv_mass[i] * k * r[a]
vn[j][a] -= inv_mass[j] * k * r[a]
if done:
break
else:
raise RuntimeError("RATTLE velocity stage did not converge")
return xn, vn, fn # @line L9
def constraint_errors(x: list[Vec], v: list[Vec], bonds: list[Bond]) -> tuple[float, float]:
"""Largest relative bond-length error and largest |r_ij . v_ij| / d^2."""
pos = max(abs(_dot(s, s) ** 0.5 - d) / d for s, d in (([x[i][a] - x[j][a] for a in range(3)], d) for i, j, d in bonds))
vel = max(abs(_dot([x[i][a] - x[j][a] for a in range(3)], [v[i][a] - v[j][a] for a in range(3)])) / (d * d) for i, j, d in bonds)
return pos, vel
test_rattle_algorithm.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rattle-algorithm/. The authors are listed in prov/VJX93A.jsonl.
import math
from rattle_algorithm import constraint_errors, rattle_step
def gravity(x):
return [[0.0, -1.0, 0.0] for _ in x]
def pendulum_state(theta, omega):
# the anchor (index 0) is fixed by an inverse mass of 0; the bob has mass 1 and the rod length 1
x = [[0.0, 0.0, 0.0], [math.sin(theta), -math.cos(theta), 0.0]]
v = [[0.0, 0.0, 0.0], [omega * math.cos(theta), omega * math.sin(theta), 0.0]]
return x, v
W_PEND, B_PEND = [0.0, 1.0], [(0, 1, 1.0)]
def angle_and_rate(x, v):
bx, by = x[1][0], x[1][1]
return math.atan2(bx, -by), bx * v[1][1] - by * v[1][0]
def agm(a, b):
while abs(a - b) > 1e-15:
a, b = 0.5 * (a + b), math.sqrt(a * b)
return a
def measured_period(theta0, h):
x, v = pendulum_state(theta0, 0.0)
f = gravity(x)
t, crossings = 0.0, []
while len(crossings) < 3:
xo = x[1][0]
x, v, f = rattle_step(x, v, f, W_PEND, gravity, h, B_PEND)
t += h
if (xo > 0) != (x[1][0] > 0):
crossings.append(t - h * x[1][0] / (x[1][0] - xo))
return crossings[2] - crossings[0]
def test_pendulum_period_converges_at_second_order() -> None:
theta0 = 1.0
exact = 2 * math.pi / agm(1.0, math.cos(theta0 / 2))
e1 = abs(measured_period(theta0, 0.02) - exact)
e2 = abs(measured_period(theta0, 0.01) - exact)
assert e1 < 1e-3
assert 3.0 < e1 / e2 < 5.0
def chain():
x = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.6, 0.8, 0.0], [1.4, 1.5, 0.7]]
v = [[0.3, -0.2, 0.1], [0.0, 0.4, -0.3], [-0.5, 0.1, 0.2], [0.2, 0.0, 0.6]]
bonds = [(k, k + 1, math.dist(x[k], x[k + 1])) for k in range(3)]
w = [1.0, 0.5, 0.5, 1.0]
# remove the velocity components that break the constraints before the first step
_, v, _ = rattle_step(x, v, [[0.0] * 3 for _ in x], w, lambda y: [[0.0] * 3 for _ in y], 0.0, bonds)
return x, v, w, bonds
def chain_force(x):
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 = -3.0 * (r - 1.5)
for a in range(3):
f[i][a] += mag * s[a] / r
f[j][a] -= mag * s[a] / r
return f
def test_both_constraints_hold_on_every_step() -> None:
x, v, w, bonds = chain()
f = chain_force(x)
for _ in range(400):
x, v, f = rattle_step(x, v, f, w, chain_force, 0.02, bonds)
pos, vel = constraint_errors(x, v, bonds)
assert pos < 1e-12 and vel < 1e-12
def test_reversibility() -> None:
x0, v0, w, bonds = chain()
x, v, f = x0, v0, chain_force(x0)
for _ in range(200):
x, v, f = rattle_step(x, v, f, w, chain_force, 0.05, bonds)
v = [[-c for c in p] for p in v]
for _ in range(200):
x, v, f = rattle_step(x, v, f, w, chain_force, 0.05, bonds)
assert max(math.dist(a, b) for a, b in zip(x, x0)) < 1e-9
assert max(math.dist([-c for c in a], b) for a, b in zip(v, v0)) < 1e-9
def test_map_preserves_phase_area() -> None:
def flow(theta, omega):
x, v = pendulum_state(theta, omega)
f = gravity(x)
for _ in range(10):
x, v, f = rattle_step(x, v, f, W_PEND, gravity, 0.1, B_PEND)
return angle_and_rate(x, v)
e = 1e-5
th, om = 0.7, 0.4
a = [(p - m) / (2 * e) for p, m in zip(flow(th + e, om), flow(th - e, om))]
b = [(p - m) / (2 * e) for p, m in zip(flow(th, om + e), flow(th, om - e))]
assert abs(a[0] * b[1] - a[1] * b[0] - 1.0) < 1e-7
def test_energy_error_stays_bounded() -> None:
x, v = pendulum_state(1.5, 0.0)
f = gravity(x)
e0 = 0.5 * sum(c * c for c in v[1]) + x[1][1]
worst_early = worst_late = 0.0
for step in range(4000):
x, v, f = rattle_step(x, v, f, W_PEND, gravity, 0.05, B_PEND)
err = abs(0.5 * sum(c * c for c in v[1]) + x[1][1] - e0)
if step < 400:
worst_early = max(worst_early, err)
else:
worst_late = max(worst_late, err)
assert worst_early < 2e-3
assert worst_late < 1.2 * worst_early # no drift over thirty periods
def test_positions_equal_the_shake_positions() -> None:
x, v, w, bonds = chain()
f = chain_force(x)
h = 0.03
xs = [x]
for _ in range(30):
x, v, f = rattle_step(x, v, f, w, chain_force, h, bonds)
xs.append(x)
# position Verlet with SHAKE corrections along the bonds at time n, from the same two first positions
prev, cur = xs[0], xs[1]
for k in range(2, 31):
fc = chain_force(cur)
nxt = [[2 * cur[i][a] - prev[i][a] + h * h * w[i] * fc[i][a] for a in range(3)] for i in range(4)]
for _ in range(500):
for i, j, d in bonds:
s = [nxt[i][a] - nxt[j][a] for a in range(3)]
r = [cur[i][a] - cur[j][a] for a in range(3)]
g = (d * d - sum(c * c for c in s)) / (2 * (w[i] + w[j]) * sum(p * q for p, q in zip(s, r)))
for a in range(3):
nxt[i][a] += w[i] * g * r[a]
nxt[j][a] -= w[j] * g * r[a]
assert max(math.dist(p, q) for p, q in zip(nxt, xs[k])) < 1e-10
prev, cur = cur, nxt
History
Andersen (1983) gave RATTLE as a velocity version of SHAKE, the method of Ryckaert, Ciccotti and Berendsen (1977), for velocity Verlet. Leimkuhler and Skeel (1994) proved that RATTLE is symplectic, and showed that SHAKE gives the same positions. Hairer, Lubich and Wanner give RATTLE for general constrained mechanical systems in their book on geometric integration.
References
- Hans C. Andersen, Rattle, A "velocity" version of the Shake algorithm for molecular dynamics calculations, Journal of Computational Physics 52(1), 1983, 24-34, the two constraint stages for positions and velocities
- Benedict J. Leimkuhler and Robert D. Skeel, Symplectic numerical integrators in constrained Hamiltonian systems, Journal of Computational Physics 112(1), 1994, 117-125, the proof that RATTLE is symplectic and its relation to SHAKE
- Ernst Hairer, Christian Lubich and Gerhard Wanner, Geometric Numerical Integration, second edition, Springer, 2006, the treatment of constrained mechanical systems and the RATTLE method
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 VJX93A Edit this page History Report an error Markdown