Algorithm Search⌘K

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
Properties
deterministicnot iterativeparallel
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 I−AI - A with a coupling matrix AA that is zero on the diagonal, and replaces the inverse by the truncated series I+A+⋯+AkI + A + \cdots + A^k. 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 AA 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 NN atoms with inverse masses wiw_i, old positions xoldx^{\text{old}} that satisfy CC constraints c=(i,j,dc)c = (i, j, d_c), and free positions xuncx^{\text{unc}} from an unconstrained step. Let ncn_c be the unit vector of the old bond xiold−xjoldx^{\text{old}}_i - x^{\text{old}}_j, and let BB be the C×3NC \times 3N matrix whose row cc has ncn_c at atom ii and −nc-n_c at atom jj. Find multipliers Λ\Lambda such that

x=xunc−WBTΛx = x^{\text{unc}} - W B^{\mathsf T} \Lambda

has ∣xi−xj∣=dc|x_i - x_j| = d_c for every constraint, where WW is the diagonal matrix of the wiw_i. LINCS first asks for the linear condition Bx=dB x = d, which gives BWBTΛ=Bxunc−dB W B^{\mathsf T} \Lambda = B x^{\text{unc}} - d.

The algorithm

Let SS be diagonal with Sc=1/wi+wjS_c = 1 / \sqrt{w_i + w_j}. Then BWBT=S−1(I−A)S−1B W B^{\mathsf T} = S^{-1} (I - A) S^{-1}, where for two constraints c≠dc \ne d that share the atom aa,

Acd=−σcσd waScSd (nc⋅nd),A_{cd} = -\sigma_c \sigma_d \, w_a S_c S_d \, (n_c \cdot n_d),

with σ=+1\sigma = +1 if aa is the first atom of the constraint and −1-1 if it is the second. All other entries of AA are zero.

  1. LINCS(x_old, x_unc, w, bonds, k, t)
  2. 1for each constraint c = (i, j, d): n_c ← unit vector of x_old_i - x_old_j; S_c ← 1 / √(w_i + w_j)
  3. 2A_cd ← -σ_c σ_d w_a S_c S_d (n_c · n_d) for each pair c ≠ d that shares an atom a
  4. 3x ← x_unc; p_c ← d_c; y_c ← S_c (n_c · (x_i - x_j) - p_c)
  5. 4z ← y + A y + A² y + ... + A^k y ▷ k sparse products
  6. 5x_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
  7. 6repeat 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
  8. 7return x

The matrix AA and the factors SS 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 dcd_c on the old direction is too long, by a factor of 1/cos⁡1 / \cos 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 [−0.03,0.03][-0.03, 0.03] (seed 2), so the largest bond error is 4.6%4.6\%. The coupling matrix has the spectral radius ρ=0.232\rho = 0.232. The largest relative bond error after LINCS, for each order kk and number of rotation corrections tt:

order kk t=0t = 0 t=1t = 1 t=2t = 2 t=4t = 4
0 7.65×10−37.65 \times 10^{-3} 2.08×10−32.08 \times 10^{-3} 4.45×10−44.45 \times 10^{-4} 2.36×10−52.36 \times 10^{-5}
1 2.18×10−32.18 \times 10^{-3} 1.17×10−41.17 \times 10^{-4} 6.02×10−66.02 \times 10^{-6} 1.50×10−81.50 \times 10^{-8}
2 1.36×10−31.36 \times 10^{-3} 6.11×10−66.11 \times 10^{-6} 4.35×10−84.35 \times 10^{-8} 2.04×10−122.04 \times 10^{-12}
4 1.11×10−31.11 \times 10^{-3} 1.11×10−51.11 \times 10^{-5} 4.74×10−84.74 \times 10^{-8} 1.46×10−121.46 \times 10^{-12}
8 1.10×10−31.10 \times 10^{-3} 1.13×10−51.13 \times 10^{-5} 4.39×10−84.39 \times 10^{-8} 1.18×10−121.18 \times 10^{-12}

Without the rotation correction the error does not fall below 1.1×10−31.1 \times 10^{-3} at any order: that column is the error of the linearisation, not of the series. Once t≥1t \ge 1, 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 θ\theta, moved by up to 0.01 (seed 5), with k=8k = 8 and t=2t = 2:

angle θ\theta ρ\rho bond error
60° 0.5 3.4×10−103.4 \times 10^{-10}
120° 0.75 1.2×10−61.2 \times 10^{-6}
150° 0.933 1.5×10−41.5 \times 10^{-4}
170° 0.9924 1.8×10−41.8 \times 10^{-4}

As the triangle becomes flat, ρ\rho 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:

  1. The matrix. BWBT=S−1(I−A)S−1B W B^{\mathsf T} = S^{-1} (I - A) S^{-1}, with AA symmetric and zero on the diagonal.
  2. One projection. With an exact inverse in line L4, lines L3 to L5 give positions of the required form with Bx=pBx = p.
  3. The series. With order kk, the error of line L4 is at most ρk+1/(1−ρ)\rho^{k+1} / (1 - \rho) times the size of its input, where ρ<1\rho < 1 is the spectral radius of AA. For ρ≥1\rho \ge 1 the series does not converge.
  4. 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.
  5. The centre of mass does not move.

The tests check the series against a direct solve, the agreement with a SHAKE solution to 10−1110^{-11} at a high order, the fall of the error with kk and tt, 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 NN atoms with inverse masses wi>0w_i > 0 and CC constraints c=(i,j,dc)c = (i, j, d_c). From the old positions, ncn_c is the unit vector of xiold−xjoldx^{\text{old}}_i - x^{\text{old}}_j. BB is the C×3NC \times 3N matrix whose row cc has ncn_c at atom ii, −nc-n_c at atom jj and 0 elsewhere, WW is the diagonal matrix of inverse masses, and S=diag⁡(1/wi+wj)S = \operatorname{diag}(1/\sqrt{w_i + w_j}). For a position vector xx, (Bx)c=nc⋅(xi−xj)(Bx)_c = n_c \cdot (x_i - x_j) is the length of bond cc along its old direction.

Claim 1 (the matrix). BWBT=S−1(I−A)S−1B W B^{\mathsf T} = S^{-1} (I - A) S^{-1}, where AA is symmetric with zero diagonal, and for c≠dc \ne d

Acd=−ϵcϵd wa (nc⋅nd) ScSdA_{cd} = -\epsilon_c \epsilon_d \, w_a \, (n_c \cdot n_d) \, S_c S_d

if cc and dd share the atom aa, with ϵc=+1\epsilon_c = +1 if aa is the first atom of cc and −1-1 if it is the second, and Acd=0A_{cd} = 0 if they share no atom. Lines L1 and L2 build these numbers.

Proof. (BWBT)cd=∑awaBc,a⋅Bd,a(B W B^{\mathsf T})_{cd} = \sum_a w_a B_{c,a} \cdot B_{d,a}, a sum over atoms of the blocks of rows cc and dd. For c=dc = d the two atoms give wi+wj=Sc−2w_i + w_j = S_c^{-2}, since ∣nc∣=1|n_c| = 1. For c≠dc \ne d only a shared atom contributes, with ϵcϵdwanc⋅nd\epsilon_c \epsilon_d w_a n_c \cdot n_d. 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 S(BWBT)S=I−AS (B W B^{\mathsf T}) S = I - A with AA as stated, which is symmetric because the formula is. □\square

Claim 2 (one projection). Line L5 maps xx to x′=x−WBTΛx' = x - W B^{\mathsf T} \Lambda with Λ=S sol\Lambda = S \, \mathrm{sol}, where sol\mathrm{sol} is the output of line L4 for the right side of line L3. If line L4 returned (I−A)−1(I - A)^{-1} times its input exactly, then Bx′=pB x' = p, the target lengths.

Proof. Line L5 subtracts wiΛcncw_i \Lambda_c n_c from xix_i and adds wjΛcncw_j \Lambda_c n_c to xjx_j, which is x−WBTΛx - W B^{\mathsf T} \Lambda. With an exact solve, Λ=S(I−A)−1S(Bx−p)=(BWBT)−1(Bx−p)\Lambda = S (I - A)^{-1} S (Bx - p) = (B W B^{\mathsf T})^{-1} (Bx - p) by Claim 1, so Bx′=Bx−(Bx−p)=pB x' = Bx - (Bx - p) = p. □\square

Claim 3 (the series). Let ρ\rho be the spectral radius of AA. If ρ<1\rho < 1, the output of line L4 with order kk differs from (I−A)−1(I - A)^{-1} times its input yy by at most ρk+11−ρ∥y∥2\frac{\rho^{k+1}}{1 - \rho} \|y\|_2 in the 2-norm. If ρ≥1\rho \ge 1, the series does not converge for some inputs.

Proof. Line L4 returns ∑t=0kAty\sum_{t=0}^{k} A^t y, and (I−A)−1−∑t=0kAt=Ak+1(I−A)−1(I - A)^{-1} - \sum_{t=0}^{k} A^t = A^{k+1} (I - A)^{-1} when ρ<1\rho < 1. AA is symmetric, so ∥A∥2=ρ\|A\|_2 = \rho and ∥(I−A)−1∥2≤1/(1−ρ)\|(I - A)^{-1}\|_2 \le 1/(1 - \rho). If ρ≥1\rho \ge 1, take yy an eigenvector for an eigenvalue ±ρ\pm\rho: the terms AtyA^t y do not go to 0. □\square

I−AI - A is positive definite, since it is SBWBTSS B W B^{\mathsf T} S and BB has independent rows for the inputs we consider, so all eigenvalues of AA are below 1. So ρ\rho is close to 1 only if an eigenvalue is close to 1, which happens when the rows of BB are close to dependent, as in a ring, or if an eigenvalue is close to or below −1-1. For three equal masses in a triangle of three constraints, the test measures ρ=0.5\rho = 0.5 for an equilateral triangle, 0.750.75 at an angle of 120°120°, 0.9330.933 at 150°150° and 0.9920.992 at 170°170°. When the triangle becomes flat, the rows of BB become dependent, BWBTB W B^{\mathsf T} becomes singular, and ρ→1\rho \to 1.

Claim 4 (the rotation correction). Suppose that after a projection Bx=pB x = p, and let qcq_c be the part of the bond xi−xjx_i - x_j normal to ncn_c. Then ∣xi−xj∣2=pc2+qc2|x_i - x_j|^2 = p_c^2 + q_c^2. Line L6 sets the new target pc=dc2−qc2p_c = \sqrt{d_c^2 - q_c^2}, so if the next projection does not change qcq_c, the bond has length exactly dcd_c after it. If the corrections of line L6 converge to a point x⋆x^\star with exact solves, then every bond of x⋆x^\star has length dcd_c, and x⋆=xunc−WBTΛ⋆x^\star = x^{\text{unc}} - W B^{\mathsf T} \Lambda^\star for some Λ⋆\Lambda^\star.

Proof. The first part is Pythagoras. At a fixed point the projection does not move x⋆x^\star, so by Claim 2 (Bx⋆)c=pc(B x^\star)_c = p_c, that is, the part of the bond along ncn_c has length dc2−qc2\sqrt{d_c^2 - q_c^2}, and its total length is dcd_c. Every projection adds a vector of the form WBTΛW B^{\mathsf T} \Lambda, and a sum of such vectors has the same form. □\square

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 10−1110^{-11} with order 16 and 4 corrections. With the usual settings, order 4 and one correction, the bonds hold to about 10−510^{-5} 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 ∑imixi\sum_i m_i x_i.

Proof. Line L5 changes it by −miwiΛcnc+mjwjΛcnc=0-m_i w_i \Lambda_c n_c + m_j w_j \Lambda_c n_c = 0 for each constraint. □\square

Cost. Lines L1 and L2 cost Θ(C+∑adeg⁡(a)2)\Theta(C + \sum_a \deg(a)^2), where deg⁡(a)\deg(a) is the number of constraints on atom aa, which is at most 4 in a molecule. Each projection costs Θ((k+1)⋅nnz(A))\Theta((k + 1) \cdot \mathrm{nnz}(A)) for order kk, 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 Θ(N+Cb)\Theta(N + C b), where bb is the largest number of constraints that share an atom with one constraint. Each solve costs Θ(Cbk)\Theta(C b k) for the kk sparse products, and there are t+1t + 1 solves. For molecules, bb is a small constant, so a step costs Θ(N+Ckt)\Theta(N + C k t). 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 ρ\rho 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 kk helps when ρ\rho is close to but below 1, at a linear cost in kk.
  • 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 t=0t = 0 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 ρ\rho for the molecules you use, for example by power iteration on AA.
  • Energy drift. The bonds do not hold exactly, so the step is not exactly reversible. Choose kk and tt so that the bond error is well below the other errors of the simulation.
  • The sign convention of AA. A wrong sign in σcσd\sigma_c \sigma_d 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.

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

  1. 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
  2. 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
  3. 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.

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