Algorithmadvanced
LINCS algorithm
Also called linear constraint solver, LINCS.
Resets bond constraints after an unconstrained step by a truncated matrix expansion of the constraint equations, faster and more parallel than SHAKE.
- Time
- O(N + C k t) worst
- Space
- O(N + C) extra
- Where
- C = the number of constraints; N = the number of atoms; k = the expansion order; t = the number of rotation corrections
- Model
- Real RAM
- Properties
- deterministicnot iterativeparallel
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Berk Hess, Henk Bekker, Herman J. C. Berendsen, Johannes G. E. M. Fraaije, 1997
LINCS, the linear constraint solver, resets fixed bond lengths after an unconstrained molecular dynamics step. It solves the same equations as SHAKE: the new positions are the free step plus corrections along the old bond directions, with multipliers chosen so that every bond has its length. SHAKE finds the multipliers by sweeping over the constraints one at a time until they converge. LINCS writes the linearised equations as one sparse matrix system, scales it so that the matrix is with a coupling matrix that is zero on the diagonal, and replaces the inverse by the truncated series . A second solve corrects the lengthening that comes from the rotation of the bonds. The work is a fixed number of sparse matrix products, with no test for convergence, so it is fast and runs well in parallel. The price is that the series only converges when the spectral radius of is below 1, which fails for rings of constraints that are nearly flat.
In plain words
After a free step, every bond in a molecule is a little too long or too short. Each bond needs a push along its old direction to fix it. The pushes are linked, because two bonds that share an atom both move that atom.
SHAKE fixes the bonds one by one and goes round and round until all are right. LINCS instead writes down all the pushes as one system of equations and solves it with a short formula: the push each bond needs on its own, plus a correction for its neighbours, plus a correction for the neighbours of the neighbours, and so on for a fixed number of terms. Then it fixes the small error that comes from the bonds turning during the step. Every bond does the same amount of work, so many processors can share it.
The problem
There are atoms with inverse masses , old positions that satisfy constraints , and free positions from an unconstrained step. Let be the unit vector of the old bond , and let be the matrix whose row has at atom and at atom . Find multipliers such that
has for every constraint, where is the diagonal matrix of the . LINCS first asks for the linear condition , which gives .
The algorithm
Let be diagonal with . Then , where for two constraints that share the atom ,
with if is the first atom of the constraint and if it is the second. All other entries of are zero.
LINCS(x_old, x_unc, w, bonds, k, t)- 1
for each constraint c = (i, j, d): n_c ← unit vector of x_old_i - x_old_j; S_c ← 1 / √(w_i + w_j) - 2
A_cd ← -σ_c σ_d w_a S_c S_d (n_c · n_d) for each pair c ≠ d that shares an atom a - 3
x ← x_unc; p_c ← d_c; y_c ← S_c (n_c · (x_i - x_j) - p_c) - 4
z ← y + A y + A² y + ... + A^k y ▷ k sparse products - 5
x_i ← x_i - w_i S_c z_c n_c; x_j ← x_j + w_j S_c z_c n_c for each c - 6
repeat t times: q_c ← the part of x_i - x_j normal to n_c; p_c ← √(max(0, d_c² - |q_c|²)); redo L3 to L5 with these p - 7
return x
The matrix and the factors depend only on the old positions, so lines L1 and L2 run once per step. Line L6 is needed because a bond that turns during the step and keeps its projection on the old direction is too long, by a factor of of the angle it turned through.
Example
A chain. Six atoms in a zigzag chain with five bonds, masses 12, 14, 12, 16, 12 and 1, moved by random amounts in (seed 2), so the largest bond error is . The coupling matrix has the spectral radius . The largest relative bond error after LINCS, for each order and number of rotation corrections :
| order | ||||
|---|---|---|---|---|
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 4 | ||||
| 8 |
Without the rotation correction the error does not fall below at any order: that column is the error of the linearisation, not of the series. Once , an order of 2 is already enough for this chain, and the corrections bring the error down by two orders of magnitude each.
A triangle. Three atoms of mass 1 with all three distances fixed, two sides of length 1 at an angle , moved by up to 0.01 (seed 5), with and :
| angle | bond error | |
|---|---|---|
| 60° | 0.5 | |
| 120° | 0.75 | |
| 150° | 0.933 | |
| 170° | 0.9924 |
As the triangle becomes flat, tends to 1 (it is 0.99970 at 178°), the series converges slowly, and LINCS with a fixed order leaves a large error.
Correctness
The proof below shows these claims:
- The matrix. , with symmetric and zero on the diagonal.
- One projection. With an exact inverse in line L4, lines L3 to L5 give positions of the required form with .
- The series. With order , the error of line L4 is at most times the size of its input, where is the spectral radius of . For the series does not converge.
- The rotation correction. If the corrections of line L6 converge with exact solves, the limit has every bond at its length and the form of the constrained step, so it is the SHAKE solution.
- The centre of mass does not move.
The tests check the series against a direct solve, the agreement with a SHAKE solution to at a high order, the fall of the error with and , the centre of mass, and the spectral radius of the triangle.
Proof: LINCS solves the linearised constraint equations by a convergent series, and its corrected fixed point is the SHAKE solutionfull
We use the line numbers of the pseudocode. There are atoms with inverse masses and constraints . From the old positions, is the unit vector of . is the matrix whose row has at atom , at atom and 0 elsewhere, is the diagonal matrix of inverse masses, and . For a position vector , is the length of bond along its old direction.
Claim 1 (the matrix). , where is symmetric with zero diagonal, and for
if and share the atom , with if is the first atom of and if it is the second, and if they share no atom. Lines L1 and L2 build these numbers.
Proof. , a sum over atoms of the blocks of rows and . For the two atoms give , since . For only a shared atom contributes, with . Two constraints on the same pair of atoms would share two atoms; the code does not support that, and it is not a meaningful input. Then with as stated, which is symmetric because the formula is.
Claim 2 (one projection). Line L5 maps to with , where is the output of line L4 for the right side of line L3. If line L4 returned times its input exactly, then , the target lengths.
Proof. Line L5 subtracts from and adds to , which is . With an exact solve, by Claim 1, so .
Claim 3 (the series). Let be the spectral radius of . If , the output of line L4 with order differs from times its input by at most in the 2-norm. If , the series does not converge for some inputs.
Proof. Line L4 returns , and when . is symmetric, so and . If , take an eigenvector for an eigenvalue : the terms do not go to 0.
is positive definite, since it is and has independent rows for the inputs we consider, so all eigenvalues of are below 1. So is close to 1 only if an eigenvalue is close to 1, which happens when the rows of are close to dependent, as in a ring, or if an eigenvalue is close to or below . For three equal masses in a triangle of three constraints, the test measures for an equilateral triangle, at an angle of , at and at . When the triangle becomes flat, the rows of become dependent, becomes singular, and .
Claim 4 (the rotation correction). Suppose that after a projection , and let be the part of the bond normal to . Then . Line L6 sets the new target , so if the next projection does not change , the bond has length exactly after it. If the corrections of line L6 converge to a point with exact solves, then every bond of has length , and for some .
Proof. The first part is Pythagoras. At a fixed point the projection does not move , so by Claim 2 , that is, the part of the bond along has length , and its total length is . Every projection adds a vector of the form , and a sum of such vectors has the same form.
The constraint forces of SHAKE also act along the old bond directions, so the SHAKE solution has the same form, and where the solution of that form is locally unique, the fixed point of LINCS is the SHAKE solution. The test checks this to with order 16 and 4 corrections. With the usual settings, order 4 and one correction, the bonds hold to about relative error for the chain of the test, a heuristic accuracy that depends on the step size.
Claim 5 (centre of mass). Each projection keeps .
Proof. Line L5 changes it by for each constraint.
Cost. Lines L1 and L2 cost , where is the number of constraints on atom , which is at most 4 in a molecule. Each projection costs for order , with no loop that runs until convergence, so the cost of a step is known in advance and each constraint can be handled by a separate thread.
Complexity
Lines L1 and L2 cost , where is the largest number of constraints that share an atom with one constraint. Each solve costs for the sparse products, and there are solves. For molecules, is a small constant, so a step costs . There is no loop that runs to convergence, so the cost is the same in every step, and each constraint only reads its neighbours, which suits parallel machines.
Properties
- Fixed cost. The work does not depend on how far the free step broke the bonds.
- Parallel. Each sparse product needs only the values of neighbouring constraints. P-LINCS (Hess, 2008) splits the constraints between processors on this basis.
- Approximate. The result holds the bonds only to the error of the series and the corrections, not to a set tolerance.
- Centre of mass. Each projection keeps the centre of mass.
- Ring sensitive. Coupled triangles, as in angle constraints, push toward 1 and make the series slow.
Variants and improvements
- P-LINCS. The parallel version of Hess (2008) passes the coupling between processors that share constraints.
- A higher order for coupled constraints. Raising helps when is close to but below 1, at a linear cost in .
- Velocities. The same series, applied to the velocities, removes their component along the bonds, as in the velocity stage of RATTLE.
- Mixed methods. Codes often use LINCS for bonds and a closed-form method such as SETTLE for rigid water.
When to use it
Use LINCS to hold bonds to hydrogen fixed in large simulations of proteins, membranes or polymers, especially in parallel. Do not use it for angle constraints or rigid rings that are nearly flat, where the series converges slowly or not at all. There SHAKE, a direct sparse solve, or a closed-form method is safer.
Pitfalls
- No rotation correction. With every bond that turns comes out too long, by an amount of the size of the square of the angle it turned.
- A spectral radius near 1. The error then hardly falls with the order. Check for the molecules you use, for example by power iteration on .
- Energy drift. The bonds do not hold exactly, so the step is not exactly reversible. Choose and so that the bond error is well below the other errors of the simulation.
- The sign convention of . A wrong sign in gives a matrix with the right size and the wrong coupling, and the bonds then come out wrong without any error message.
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/lincs-algorithm/. The authors are listed in prov/F7HF6T.jsonl.
"""LINCS: the linear constraint solver of Hess, Bekker, Berendsen and Fraaije (1997).
Each constraint c = (i, j, d) asks |x_i - x_j| = d. Let B be the C x 3N
matrix whose row c holds the unit vector n_c of the old bond i - j at atom i
and -n_c at atom j, and W the diagonal of inverse masses. The constraint
forces act along the old bonds, so the new positions are
x = x_unc - W B^T lambda. Asking B x = p for a target p gives
B W B^T lambda = B x_unc - p.
With S = diag(1 / sqrt(w_i + w_j)), B W B^T = S^-1 (I - A) S^-1, where A is
zero on the diagonal and couples constraints that share an atom. LINCS
replaces (I - A)^-1 by the truncated series I + A + ... + A^order. The
first solve uses p = d. Because the old directions are fixed, a rotated bond
ends up too long, so each correction pass sets p_c = sqrt(d^2 - q_c^2), with
q_c the part of the bond normal to n_c, and solves again.
The series converges only when the spectral radius of A is below 1. For a
triangle of constraints it tends to 1 as the triangle becomes flat.
Cost: Theta(C (order + 1)) per solve, with a fixed number of operations per
constraint and no sweep to convergence, so it runs well in parallel.
"""
import math
Vec = list[float]
Bond = tuple[int, int, float]
def coupling(x_old: list[Vec], inv_mass: list[float], bonds: list[Bond]):
"""Directions n_c, scale factors S_c and the sparse coupling matrix A as lists of (d, A_cd)."""
dirs, scale = [], []
for i, j, _ in bonds: # @line L1
r = [x_old[i][a] - x_old[j][a] for a in range(3)]
length = math.sqrt(r[0] * r[0] + r[1] * r[1] + r[2] * r[2])
dirs.append([c / length for c in r])
scale.append(1.0 / math.sqrt(inv_mass[i] + inv_mass[j]))
by_atom: dict[int, list[tuple[int, float]]] = {}
for c, (i, j, _) in enumerate(bonds):
by_atom.setdefault(i, []).append((c, 1.0))
by_atom.setdefault(j, []).append((c, -1.0))
coup: list[list[tuple[int, float]]] = [[] for _ in bonds]
for atom, members in by_atom.items(): # @line L2
for c, sc in members:
for d, sd in members:
if c != d:
nd = sum(p * q for p, q in zip(dirs[c], dirs[d]))
coup[c].append((d, -sc * sd * inv_mass[atom] * nd * scale[c] * scale[d]))
return dirs, scale, coup
def series_solve(coup, rhs: list[float], order: int) -> list[float]:
"""Approximate (I - A)^-1 rhs by rhs + A rhs + ... + A^order rhs."""
sol, term = list(rhs), list(rhs)
for _ in range(order): # @line L4
term = [sum(a * term[d] for d, a in row) for row in coup]
sol = [s + t for s, t in zip(sol, term)]
return sol
def _project(x, inv_mass, bonds, dirs, scale, coup, target, order) -> None:
rhs = []
for c, (i, j, _) in enumerate(bonds): # @line L3
proj = sum(dirs[c][a] * (x[i][a] - x[j][a]) for a in range(3))
rhs.append(scale[c] * (proj - target[c]))
sol = series_solve(coup, rhs, order)
for c, (i, j, _) in enumerate(bonds): # @line L5
lam = scale[c] * sol[c]
for a in range(3):
x[i][a] -= inv_mass[i] * lam * dirs[c][a]
x[j][a] += inv_mass[j] * lam * dirs[c][a]
def lincs(
x_old: list[Vec], x_unc: list[Vec], inv_mass: list[float], bonds: list[Bond],
order: int = 4, n_iter: int = 1,
) -> list[Vec]:
"""Constrain x_unc with the LINCS expansion of the given order and n_iter rotation corrections."""
dirs, scale, coup = coupling(x_old, inv_mass, bonds)
x = [list(p) for p in x_unc]
_project(x, inv_mass, bonds, dirs, scale, coup, [d for _, _, d in bonds], order)
for _ in range(n_iter): # @line L6
target = []
for c, (i, j, d) in enumerate(bonds):
s = [x[i][a] - x[j][a] for a in range(3)]
along = sum(dirs[c][a] * s[a] for a in range(3))
normal2 = sum(v * v for v in s) - along * along
target.append(math.sqrt(max(0.0, d * d - normal2)))
_project(x, inv_mass, bonds, dirs, scale, coup, target, order)
return x # @line L7
def spectral_radius(coup, iters: int = 500) -> float:
"""Largest |eigenvalue| of the symmetric coupling matrix A by power iteration on A^2."""
v = [1.0 + 0.1 * c for c in range(len(coup))]
rho = 0.0
for _ in range(iters):
w = [sum(a * v[d] for d, a in row) for row in coup]
w = [sum(a * w[d] for d, a in row) for row in coup]
norm = math.sqrt(sum(c * c for c in w))
if norm == 0.0:
return 0.0
rho = math.sqrt(norm / math.sqrt(sum(c * c for c in v)))
v = [c / norm for c in w]
return rho
test_lincs_algorithm.py 94 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lincs-algorithm/. The authors are listed in prov/F7HF6T.jsonl.
import math
import random
from lincs_algorithm import coupling, lincs, series_solve, spectral_radius
def bond_error(x, bonds):
return max(abs(math.dist(x[i], x[j]) - d) / d for i, j, d in bonds)
def shake_reference(x_old, x_unc, w, bonds):
"""SHAKE iterated to rounding: the exact solution with corrections along the old bonds."""
x = [list(p) for p in x_unc]
for _ in range(2000):
for i, j, d in bonds:
s = [x[i][a] - x[j][a] for a in range(3)]
r = [x_old[i][a] - x_old[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):
x[i][a] += w[i] * g * r[a]
x[j][a] -= w[j] * g * r[a]
return x
def zigzag_chain(seed):
rng = random.Random(seed)
x_old = [[0.8 * k, 0.6 * (k % 2), 0.1 * k] for k in range(6)]
bonds = [(k, k + 1, math.dist(x_old[k], x_old[k + 1])) for k in range(5)]
w = [1 / 12, 1 / 14, 1 / 12, 1 / 16, 1 / 12, 1.0]
x_unc = [[c + rng.uniform(-0.03, 0.03) for c in p] for p in x_old]
return x_old, x_unc, w, bonds
def triangle(angle_deg, seed):
t = math.radians(angle_deg)
x_old = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [math.cos(t), math.sin(t), 0.0]]
bonds = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, math.dist(x_old[1], x_old[2]))]
rng = random.Random(seed)
x_unc = [[c + rng.uniform(-0.01, 0.01) for c in p] for p in x_old]
return x_old, x_unc, [1.0, 1.0, 1.0], bonds
def test_series_solve_matches_a_direct_inverse() -> None:
x_old, _, w, bonds = zigzag_chain(1)
_, _, coup = coupling(x_old, w, bonds)
rhs = [0.3, -0.1, 0.7, 0.2, -0.4]
sol = series_solve(coup, rhs, 60)
back = [s - sum(a * sol[d] for d, a in row) for s, row in zip(sol, coup)] # (I - A) sol
assert max(abs(p - q) for p, q in zip(back, rhs)) < 1e-14
def test_high_order_with_corrections_reaches_the_shake_solution() -> None:
x_old, x_unc, w, bonds = zigzag_chain(2)
x = lincs(x_old, x_unc, w, bonds, order=16, n_iter=4)
ref = shake_reference(x_old, x_unc, w, bonds)
assert bond_error(ref, bonds) < 1e-14
assert bond_error(x, bonds) < 1e-11
assert max(math.dist(p, q) for p, q in zip(x, ref)) < 1e-11
def test_error_falls_with_order_and_corrections() -> None:
x_old, x_unc, w, bonds = zigzag_chain(2)
by_order = [bond_error(lincs(x_old, x_unc, w, bonds, order, 2), bonds) for order in (0, 1, 2)]
assert by_order[0] > by_order[1] > by_order[2]
by_iter = [bond_error(lincs(x_old, x_unc, w, bonds, 4, n), bonds) for n in (0, 1, 2, 4)]
assert by_iter[0] > by_iter[1] > by_iter[2] > by_iter[3]
assert by_iter[0] > 1e-4 # without the rotation correction the bonds come out too long
def test_centre_of_mass_does_not_move() -> None:
x_old, x_unc, w, bonds = zigzag_chain(3)
x = lincs(x_old, x_unc, w, bonds, 4, 1)
for a in range(3):
before = sum(p[a] / wi for p, wi in zip(x_unc, w))
after = sum(p[a] / wi for p, wi in zip(x, w))
assert abs(before - after) < 1e-12
def test_flat_triangle_makes_the_series_converge_slowly() -> None:
radii = []
errors = []
for angle in (60, 120, 150, 170):
x_old, x_unc, w, bonds = triangle(angle, 5)
radii.append(spectral_radius(coupling(x_old, w, bonds)[2]))
errors.append(bond_error(lincs(x_old, x_unc, w, bonds, 8, 2), bonds))
assert abs(radii[0] - 0.5) < 1e-9 and abs(radii[1] - 0.75) < 1e-9
assert radii[1] < radii[2] < radii[3] < 1.0
assert errors[0] < 1e-9 < 1e-5 < errors[3]
# the chain without rings stays well inside the unit disc
x_old, _, w, bonds = zigzag_chain(1)
assert spectral_radius(coupling(x_old, w, bonds)[2]) < 0.3
History
Hess, Bekker, Berendsen and Fraaije (1997) gave LINCS as a faster replacement for SHAKE. They wrote the constraint equations as a matrix system, expanded the inverse as a series, and added the correction for the rotation of the bonds. Hess (2008) gave P-LINCS, a version for parallel computers.
References
- Berk Hess, Henk Bekker, Herman J. C. Berendsen and Johannes G. E. M. Fraaije, LINCS, A linear constraint solver for molecular simulations, Journal of Computational Chemistry 18(12), 1997, 1463-1472, the matrix form of the constraint equations, its series expansion, and the correction for rotation
- Berk Hess, P-LINCS, A parallel linear constraint solver for molecular simulation, Journal of Chemical Theory and Computation 4(1), 2008, 116-122, the parallel version of the method
- Michael P. Allen and Dominic J. Tildesley, Computer Simulation of Liquids, second edition, Oxford University Press, 2017, Section 7.5, Parallel constraints
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 F7HF6T Edit this page History Report an error Markdown