Algorithm Search⌘K

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
Properties
deterministiciterativesymplectictime reversible
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 NN atoms with positions xix_i, velocities viv_i, 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) with σc(x)=∣xi−xj∣2−dc2\sigma_c(x) = |x_i - x_j|^2 - d_c^2. Let G(x)G(x) be the matrix with rows 12∇σc(x)\frac12 \nabla \sigma_c(x), so the velocity constraint is G(x)v=0G(x) v = 0. Given (x0,v0)(x^0, v^0) with σ(x0)=0\sigma(x^0) = 0 and G(x0)v0=0G(x^0) v^0 = 0, and the step hh, find

v1/2=v0+h2Wf(x0)−WG(x0)Tγ,x1=x0+hv1/2,σ(x1)=0,v^{1/2} = v^0 + \tfrac{h}{2} W f(x^0) - W G(x^0)^{\mathsf T} \gamma, \qquad x^1 = x^0 + h v^{1/2}, \qquad \sigma(x^1) = 0,
v1=v1/2+h2Wf(x1)−WG(x1)Tδ,G(x1)v1=0,v^1 = v^{1/2} + \tfrac{h}{2} W f(x^1) - W G(x^1)^{\mathsf T} \delta, \qquad G(x^1) v^1 = 0,

where WW is the diagonal matrix of the wiw_i and γ,δ\gamma, \delta are multipliers.

The algorithm

  1. RATTLE-STEP(x, v, f, w, force, h, bonds, τ)
  2. 1v' ← v + (h/2) W f ▷ half kick
  3. 2x' ← x + h v' ▷ drift
  4. 3repeat sweeps over the constraints c = (i, j, d), until each has |d² - |x'_i - x'_j|²| ≤ 2τd²
  5. 4g ← (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
  6. 5f' ← force(x')
  7. 6v'' ← v' + (h/2) W f' ▷ second half kick
  8. 7repeat sweeps over the constraints, until each has |r' · (v''_i - v''_j)| ≤ τ d²
  9. 8k ← -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'
  10. 9return (x', v'', f')

Here s=xi′−xj′s = x'_i - x'_j, r=xi−xjr = x_i - x_j is the old bond, and r′=xi′−xj′r' = x'_i - x'_j is the new bond. The velocity equations are linear in δ\delta, 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 g=1g = 1, as an anchor with w=0w = 0 and a bob joined by one constraint. Released at rest from the angle θ0=1\theta_0 = 1, its exact period is 2π/agm(1,cos⁡(θ0/2))=6.6999756642\pi / \mathrm{agm}(1, \cos(\theta_0/2)) = 6.699975664. The period from RATTLE, measured from the crossings of the vertical:

step hh period error
0.04 9.83×10−49.83 \times 10^{-4}
0.02 2.47×10−42.47 \times 10^{-4}
0.01 6.16×10−56.16 \times 10^{-5}

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 10−1210^{-12}.

Released from θ0=1.5\theta_0 = 1.5, close to horizontal, and run to the time 200, about 25 periods, the energy error is at most 8.50×10−48.50 \times 10^{-4} with h=0.05h = 0.05 and 2.13×10−42.13 \times 10^{-4} with h=0.025h = 0.025. 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:

  1. The position stage returns x1=x0+hv1/2x^1 = x^0 + h v^{1/2}, with the velocity corrections along the rows of G(x0)G(x^0), and every bond within the tolerance.
  2. The velocity stage returns v1v^1 with corrections along the rows of G(x1)G(x^1), and every velocity constraint within the tolerance.
  3. Time reversal. One step from (x1,−v1)(x^1, -v^1) returns to (x0,−v0)(x^0, -v^0), when the equations have locally unique solutions.
  4. 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.
  5. 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 10−910^{-9}, the preserved area of the pendulum map, the energy band, and agreement with the SHAKE positions to 10−1010^{-10}.

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 NN atoms with inverse masses wi≥0w_i \ge 0, forces f(x)f(x), and constraints c=(i,j,dc)c = (i, j, d_c) with σc(x)=12(∣xi−xj∣2−dc2)\sigma_c(x) = \frac12 (|x_i - x_j|^2 - d_c^2). Let G(x)G(x) be the C×3NC \times 3N matrix whose row cc is ∇σc(x)\nabla \sigma_c(x): it has xi−xjx_i - x_j at atom ii, −(xi−xj)-(x_i - x_j) at atom jj and 0 elsewhere. Let WW be the diagonal matrix of inverse masses. The RATTLE equations of Andersen (1983) for one step from (x0,v0)(x^0, v^0) are

v1/2=v0+h2W(f(x0)−G(x0)Tλ),x1=x0+hv1/2,σ(x1)=0,v1=v1/2+h2W(f(x1)−G(x1)Tμ),G(x1)v1=0.\begin{aligned} v^{1/2} &= v^0 + \tfrac{h}{2} W \bigl(f(x^0) - G(x^0)^{\mathsf T} \lambda\bigr), & x^1 &= x^0 + h v^{1/2}, & \sigma(x^1) &= 0, \\ v^1 &= v^{1/2} + \tfrac{h}{2} W \bigl(f(x^1) - G(x^1)^{\mathsf T} \mu\bigr), & & & G(x^1) v^1 &= 0. \end{aligned}

The unknowns are x1x^1, v1/2v^{1/2}, v1v^1 and the multipliers λ,μ∈RC\lambda, \mu \in \mathbb{R}^C. The equation G(x)v=0G(x) v = 0 is the time derivative of σ(x)=0\sigma(x) = 0: each bond has zero relative velocity along itself.

Claim 1 (the position stage). After the loop of line L3, x1=x0+hv1/2x^1 = x^0 + h v^{1/2}, v1/2−v0−h2Wf(x0)=−WG(x0)Tγv^{1/2} - v^0 - \frac{h}{2} W f(x^0) = -W G(x^0)^{\mathsf T} \gamma for some γ\gamma, and every bond holds to the tolerance.

Proof. Lines L1 and L2 start the identities with γ=0\gamma = 0. Each update of line L4 adds wigrcw_i g r_c to xix_i and wigrc/hw_i g r_c / h to viv_i, and subtracts the same from atom jj, where rcr_c is the bond vector at x0x^0. So x−hv1/2x - h v^{1/2} does not change, and v1/2v^{1/2} changes by ghW\frac{g}{h} W times row cc of G(x0)G(x^0), so the identity holds with γc\gamma_c the sum of the values −g/h-g / h for constraint cc. The formula for gg 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. □\square

With λ=2γ/h\lambda = 2\gamma / h this is the first line of the RATTLE equations.

Claim 2 (the velocity stage). After the loop of line L7, v1−v1/2−h2Wf(x1)=−WG(x1)Tδv^1 - v^{1/2} - \frac{h}{2} W f(x^1) = -W G(x^1)^{\mathsf T} \delta for some δ\delta, and ∣G(x1)v1∣c≤τdc2|G(x^1) v^1|_c \le \tau d_c^2 for every constraint.

Proof. Line L6 starts the identity with δ=0\delta = 0. Line L8 adds wikrw_i k r to viv_i and subtracts wjkrw_j k r from vjv_j, where r=xi1−xj1r = x^1_i - x^1_j is row cc of G(x1)G(x^1) at atom ii. Its change of r⋅(vi−vj)r \cdot (v_i - v_j) is (wi+wj)k∣r∣2(w_i + w_j) k |r|^2, and since ∣r∣=dc|r| = d_c up to the tolerance of Claim 1, k=−r⋅vij/((wi+wj)dc2)k = -r \cdot v_{ij} / ((w_i + w_j) d_c^2) makes r⋅vijr \cdot v_{ij} zero up to that tolerance. The loop ends only after a sweep in which every constraint passed the test. □\square

The velocity equations are linear in δ\delta with the matrix G(x1)WG(x1)TG(x^1) W G(x^1)^{\mathsf T}, which is symmetric and positive definite when the rows of W1/2G(x1)W^{1/2} G(x^1) 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 (x0,v0)(x^0, v^0) satisfies both constraints, and that the RATTLE equations have locally unique solutions. If one step maps (x0,v0)(x^0, v^0) to (x1,v1)(x^1, v^1), then one step maps (x1,−v1)(x^1, -v^1) to (x0,−v0)(x^0, -v^0).

Proof. Start from (x1,−v1)(x^1, -v^1) and try the multiplier μ\mu in the first stage:

−v1+h2W(f(x1)−G(x1)Tμ)=−v1/2,-v^1 + \tfrac{h}{2} W \bigl(f(x^1) - G(x^1)^{\mathsf T} \mu\bigr) = -v^{1/2},

by the third equation of the forward step. Then the new position is x1−hv1/2=x0x^1 - h v^{1/2} = x^0, which satisfies σ(x0)=0\sigma(x^0) = 0, so μ\mu solves the position stage. In the second stage try λ\lambda: −v1/2+h2W(f(x0)−G(x0)Tλ)=−v0-v^{1/2} + \frac{h}{2} W (f(x^0) - G(x^0)^{\mathsf T} \lambda) = -v^0 by the first equation of the forward step, and G(x0)(−v0)=0G(x^0)(-v^0) = 0 by the assumption on the start. By uniqueness these are the solutions. □\square

The test runs 200 steps forward and 200 back with the velocities reversed and returns to the start within 10−910^{-9}.

Claim 4 (the positions are those of SHAKE). If xn−1,xn,xn+1x^{n-1}, x^n, x^{n+1} are three positions of a RATTLE run, then xn+1=2xn−xn−1+h2Wf(xn)−h2WG(xn)Tνx^{n+1} = 2x^n - x^{n-1} + h^2 W f(x^n) - h^2 W G(x^n)^{\mathsf T} \nu for some ν\nu, and σ(xn+1)=0\sigma(x^{n+1}) = 0. 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, vn+1/2−vn−1/2=hWf(xn)−h2WG(xn)T(μn−1+λn)v^{n+1/2} - v^{n-1/2} = h W f(x^n) - \frac{h}{2} W G(x^n)^{\mathsf T} (\mu_{n-1} + \lambda_n), where μn−1\mu_{n-1} comes from the second stage of step nn and λn\lambda_n from the first stage of step n+1n + 1. Both use G(xn)G(x^n). Multiply by hh and use xn+1−xn=hvn+1/2x^{n+1} - x^n = h v^{n+1/2} and xn−xn−1=hvn−1/2x^n - x^{n-1} = h v^{n-1/2}, with ν=12(μn−1+λn)\nu = \frac12 (\mu_{n-1} + \lambda_n). □\square

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 dθ dωd\theta \, d\omega to 10−710^{-7}, the period error falls by a factor of 4 when hh is halved, and the energy error does not grow over thirty periods.

In floating-point arithmetic with a tolerance τ\tau, every claim holds up to errors of size τ\tau 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 Θ(N)\Theta(N) plus one force evaluation. Each sweep of either loop costs Θ(C)\Theta(C). The position loop needs a number of sweeps that grows like log⁡(1/τ)\log(1/\tau) 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 Θ(N)\Theta(N).

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 10−810^{-8} or tighter in double precision.
  • Skipping the velocity stage leaves a radial velocity of order hh 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 w=0w = 0 must not be in a constraint with another fixed atom, because then wi+wj=0w_i + w_j = 0.
  • 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.

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

  1. 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
  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 proof that RATTLE is symplectic and its relation to SHAKE
  3. 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.

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