Algorithm Search⌘K

Modelintro

Mass-spring system

Also called mass-spring model, spring-mass system.

Point masses joined by damped Hooke springs along their lines. Simple and fast, but the response depends on the mesh, and stiff springs force small explicit time steps.

A mass-spring system models a deformable object as point masses joined by springs. Each spring pulls or pushes its two masses along the line between them, with a force that grows with the change of its length. Cloth, hair, ropes and soft bodies in graphics were first built this way, and the model is still the usual first step. It differs from a particle system, where the particles do not interact, and from the finite element method, where the forces come from a continuum energy with material parameters: a spring network has no continuum behind it, so its response depends on the mesh.

The machine

The state is a set of nn particles with masses mim_i (kg), positions xi\mathbf x_i (m) and velocities vi\mathbf v_i (m/s), and a set of mm springs. A spring (i,j)(i, j) has a rest length LL (m), a stiffness kk (N/m) and a damping coefficient cc (N s/m). Write xij=xj−xi\mathbf x_{ij} = \mathbf x_j - \mathbf x_i, l=∣xij∣l = |\mathbf x_{ij}|, x^ij=xij/l\hat{\mathbf x}_{ij} = \mathbf x_{ij} / l and vij=vj−vi\mathbf v_{ij} = \mathbf v_j - \mathbf v_i. The spring puts the force

fj=−(k(l−L)+c vij⋅x^ij)x^ij,fi=−fj\mathbf f_j = -\left(k (l - L) + c \, \mathbf v_{ij} \cdot \hat{\mathbf x}_{ij}\right) \hat{\mathbf x}_{ij}, \qquad \mathbf f_i = -\mathbf f_j

on its two ends. The first term is Hooke's law for the spring and the second is a damper along the spring. The elastic part is the negative gradient of the energy

E(x)=∑(i,j)12k (∣xij∣−L)2.E(\mathbf x) = \sum_{(i,j)} \tfrac12 k \, (|\mathbf x_{ij}| - L)^2 .

Each particle then follows Newton's second law mix¨i=∑fi+migm_i \ddot{\mathbf x}_i = \sum \mathbf f_i + m_i \mathbf g with gravity g=(0,−9.81,0)\mathbf g = (0, -9.81, 0) m/s2^2. A particle with infinite mass (inverse mass 0) is fixed.

On a rectangular grid of particles, as for cloth, Provot (1995, Section 2.1) uses three kinds of springs. Structural springs join [i,j][i, j] to [i+1,j][i+1, j] and [i,j+1][i, j+1] and resist stretch. Shear springs join the two diagonals of each cell. Bending (flexion) springs join [i,j][i, j] to [i+2,j][i+2, j] and [i,j+2][i, j+2] and resist folding, but only weakly and only through a change of length.

The standing assumptions are: all forces are central (along the line of the two particles); the springs are linear in the change of length, which is a modelling choice and not a law of the material; and the parameters kk, cc and LL are set per spring by the user. Hooke's law is a good model of a real spring for small changes of length, but a spring network is not a discretization of a continuum material.

In time the model is a system of ordinary differential equations, and any integrator can advance it. The usual explicit choice is symplectic Euler, velocity first:

  1. MASS-SPRING-STEP(x, v, dt)
  2. 1for each particle i: f_i <- m_i g
  3. 2for each spring (i, j, L, k): d <- x_j - x_i, l <- |d|, u <- d / l
  4. 3s <- k (l - L) + c (v_j - v_i) . u
  5. 4f_i <- f_i + s u, f_j <- f_j - s u
  6. 5for each free particle i: v_i <- v_i + dt f_i / m_i
  7. 6x_i <- x_i + dt v_i

The code with this page is this step in 2D, with the grid builder for the three kinds of springs.

What it counts

The model gives the forces on the particles, the elastic energy EE and, through an integrator, the motion. One force evaluation costs Θ(n+m)\Theta(n + m) time, and a step of an explicit method costs the same. A grid of nn particles with all three kinds of springs has m<6nm < 6n springs.

The quantities are the ones of a real mechanical network of springs. When the network stands for cloth or a soft solid, kk and cc are tuned until the motion looks right, and they do not map in a simple way to the Young's modulus or the Poisson ratio of the material.

Relation to other models

Known results in the model

  1. Forces from the energy (proved). Without damping, f=−∇E\mathbf f = -\nabla E. The force is zero at the rest shape and after any rigid motion of the rest shape, because EE depends only on the lengths. The test checks the gradient against central differences with h=10−6h = 10^{-6} and a relative tolerance of 10−610^{-6} (num_grad of the shared helper), and the zero force after three rigid motions.

  2. Momentum (proved). The two forces of a spring are equal and opposite, so the total linear momentum changes only by the external forces. They also lie on the line of the two particles, so their torques cancel and the angular momentum is kept as well. Symplectic Euler keeps both exactly in exact arithmetic: xn+1×vn+1=xn×vn+1\mathbf x_{n+1} \times \mathbf v_{n+1} = \mathbf x_n \times \mathbf v_{n+1}, and the change xn×Δt f(xn,vn)\mathbf x_n \times \Delta t \, \mathbf f(\mathbf x_n, \mathbf v_n) sums to zero over central pair forces. The damper is central too. The test runs 300 damped steps of a free random grid and finds no change above 10−1010^{-10} relative.

  3. Damping dissipates (proved). In the continuous system the damper takes the power c (vij⋅x^ij)2≥0c \, (\mathbf v_{ij} \cdot \hat{\mathbf x}_{ij})^2 \ge 0 out of the kinetic plus elastic energy. Damping along the spring does not slow a rigid rotation.

  4. Step limit (proved). For one mass mm on a spring kk to a fixed point, ω=k/m\omega = \sqrt{k / m}, and symplectic Euler is stable if and only if ωΔt<2\omega \Delta t < 2. With k=100k = 100 N/m and m=1m = 1 kg, ω=10\omega = 10 rad/s and the limit is Δt=0.2\Delta t = 0.2 s. The test finds the motion bounded at 0.190.19 s and growing past 10310^3 at 0.210.21 s. For a network the limit is 2/ωmax⁡2 / \omega_{\max}, where ωmax⁡2\omega_{\max}^2 is the largest eigenvalue of M−1KM^{-1} K for the stiffness matrix KK at the current state. For cloth with a fixed material and a grid spacing hh, the mass per particle scales as h2h^2 while the stiffness of a stretch spring stays the same, so ωmax⁡\omega_{\max} grows like 1/h1/h and the stable step shrinks like hh. Stretch springs are stiff, so explicit cloth needs small steps. Penalty contact has the same limit.

  5. Energy band of symplectic Euler (proved). For the oscillator above, Q=ω2x2+v2−ω2Δt xvQ = \omega^2 x^2 + v^2 - \omega^2 \Delta t \, x v is kept exactly by the step, where xx is the stretch. So the energy E=(ω2x2+v2)/2E = (\omega^2 x^2 + v^2)/2 stays in [E0/(1+ωΔt/2),E0/(1−ωΔt/2)][E_0 / (1 + \omega\Delta t/2), E_0 / (1 - \omega\Delta t/2)] for a start at rest, and does not drift. With k=m=1k = m = 1, a stretch of 1 and Δt=0.1\Delta t = 0.1 s, the band is [0.476190,0.526316][0.476190, 0.526316]. The test runs 10410^4 steps and finds the energy inside the band and close to both ends.

  6. The response depends on the mesh (proved for the square lattice). Stretch an infinite square lattice of spacing LL by a small strain ε\varepsilon along the direction (cos⁡ϕ,sin⁡ϕ)(\cos\phi, \sin\phi). A spring of direction e\mathbf e changes length by lε(e⋅d)2l \varepsilon (\mathbf e \cdot \mathbf d)^2 to first order, and summing the four springs of a cell gives the energy per cell

    12L2ε2(k+kd+cos⁡2ϕsin⁡2ϕ (4kd−2k))\tfrac12 L^2 \varepsilon^2 \left(k + k_d + \cos^2\phi \sin^2\phi \, (4 k_d - 2 k)\right)

    for structural springs kk and diagonal springs kdk_d. With structural springs only, the cloth is half as stiff at 45 degrees as along the grid lines. The choice kd=k/2k_d = k / 2 makes the uniaxial stiffness the same in all directions. Even then the network cannot match a chosen material: its small strain stiffness tensor is Cabcd=L−2∑k l2eaebecedC_{abcd} = L^{-2} \sum k \, l^2 e_a e_b e_c e_d over the springs of a cell, which is symmetric in all four indices, so the Lamé parameters satisfy λ=μ\lambda = \mu (the Cauchy relation) and the 2D Poisson ratio is fixed at 1/31/3. On an irregular triangle mesh the stiffness changes from triangle to triangle with the shapes. So a spring network does not converge to a chosen continuum elastic model as the mesh is refined, and its behaviour depends on the mesh. The test checks the formula against the energy of a strained patch and the two special cases.

  7. Super-elasticity (measured). Provot (1995, Section 3) hung a 17 by 17 grid by two corners and found that, with a stiffness low enough for a stable step, the most stretched springs passed 100% elongation, while woven cloth stretches by about 10% at most. This is the reason for Provot's strain limiting.

Code

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.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D vectors."""
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    )


def q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
mass_spring_system.py 115 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mass-spring-system/. The authors are listed in prov/4B6KHP.jsonl.

"""A 2D mass-spring system with damped springs, advanced by symplectic Euler.

A spring (i, j, L, k) pulls its two particles with the force
f_i = (k (l - L) + c (v_j - v_i) . u) u and f_j = -f_i, where d = x_j - x_i,
l = |d| and u = d / l. The damping acts along the spring only, so every force
is central. A particle with inverse mass 0 is fixed. Positions are (x, y) with
y up, in metres; gravity is (0, -9.81) m/s^2.
"""

import math

GRAVITY = (0.0, -9.81)


def grid(nx, ny, spacing, k_struct, k_shear=0.0, k_bend=0.0):
    """A regular nx by ny grid of particles and its springs.

    Structural springs join (i, j) to (i + 1, j) and (i, j + 1); shear springs
    join the two diagonals of each cell; bending springs join (i, j) to
    (i + 2, j) and (i, j + 2), as in Provot 1995, Section 2.1. Return
    (positions, springs) with springs as tuples (a, b, rest, k).
    """
    def idx(i, j):
        return j * nx + i

    x = [(i * spacing, j * spacing) for j in range(ny) for i in range(nx)]
    springs = []

    def add(a, b, k):
        if k > 0.0:
            springs.append((a, b, math.dist(x[a], x[b]), k))

    for j in range(ny):
        for i in range(nx):
            if i + 1 < nx:
                add(idx(i, j), idx(i + 1, j), k_struct)
            if j + 1 < ny:
                add(idx(i, j), idx(i, j + 1), k_struct)
            if i + 1 < nx and j + 1 < ny:
                add(idx(i, j), idx(i + 1, j + 1), k_shear)
                add(idx(i + 1, j), idx(i, j + 1), k_shear)
            if i + 2 < nx:
                add(idx(i, j), idx(i + 2, j), k_bend)
            if j + 2 < ny:
                add(idx(i, j), idx(i, j + 2), k_bend)
    return x, springs


def forces(x, v, mass, springs, damping=0.0, gravity=(0.0, 0.0)):
    """Total force on each particle: gravity, spring and spring damping."""
    f = [[m * gravity[0], m * gravity[1]] for m in mass]  # @line L1
    for a, b, rest, k in springs:
        dx = x[b][0] - x[a][0]
        dy = x[b][1] - x[a][1]
        length = math.hypot(dx, dy)  # @line L2
        ux, uy = dx / length, dy / length
        rel = (v[b][0] - v[a][0]) * ux + (v[b][1] - v[a][1]) * uy
        s = k * (length - rest) + damping * rel  # @line L3
        f[a][0] += s * ux  # @line L4
        f[a][1] += s * uy
        f[b][0] -= s * ux
        f[b][1] -= s * uy
    return f


def step(x, v, inv_mass, mass, springs, dt, damping=0.0, gravity=(0.0, 0.0)):
    """One symplectic Euler step (velocity first). Return new lists (x, v)."""
    f = forces(x, v, mass, springs, damping, gravity)
    nv = []
    nx_ = []
    for i in range(len(x)):
        w = inv_mass[i]
        vi = (v[i][0] + dt * w * f[i][0], v[i][1] + dt * w * f[i][1])  # @line L5
        nv.append(vi)
        nx_.append((x[i][0] + dt * vi[0], x[i][1] + dt * vi[1]))  # @line L6
    return nx_, nv


def spring_energy(x, springs):
    """Elastic energy sum of k (l - L)^2 / 2."""
    e = 0.0
    for a, b, rest, k in springs:
        e += 0.5 * k * (math.dist(x[a], x[b]) - rest) ** 2
    return e


def kinetic_energy(v, mass):
    return sum(0.5 * m * (vi[0] ** 2 + vi[1] ** 2) for vi, m in zip(v, mass))


def momentum(x, v, mass):
    """Linear momentum (px, py) and angular momentum about the origin."""
    px = sum(m * vi[0] for vi, m in zip(v, mass))
    py = sum(m * vi[1] for vi, m in zip(v, mass))
    lz = sum(m * (xi[0] * vi[1] - xi[1] * vi[0]) for xi, vi, m in zip(x, v, mass))
    return px, py, lz


def step_limit(k, m):
    """Largest stable symplectic Euler step for one mass m on a spring k to a fixed point: 2 / omega."""
    return 2.0 / math.sqrt(k / m)


def uniaxial_energy_per_cell(k, k_d, spacing, strain, angle):
    """Small-strain energy of one cell of the square lattice under uniaxial strain.

    Leading term of the energy of an infinite lattice with structural springs k
    and diagonal springs k_d, stretched by strain along the direction angle:
    (spacing^2 strain^2 / 2) (k + k_d + c^2 s^2 (4 k_d - 2 k)).
    """
    c, s = math.cos(angle), math.sin(angle)
    return 0.5 * spacing ** 2 * strain ** 2 * (k + k_d + c * c * s * s * (4.0 * k_d - 2.0 * k))
test_mass_spring_system.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mass-spring-system/. The authors are listed in prov/4B6KHP.jsonl.

"""Tests of the mass-spring system: forces, momentum, the step limit and lattice anisotropy."""

import math
import random

from anim import num_grad
import mass_spring_system as ms


def perturbed_grid(rng, nx=4, ny=3, amount=0.15):
    x, springs = ms.grid(nx, ny, 1.0, 100.0, 50.0, 20.0)
    x = [(p[0] + rng.uniform(-amount, amount), p[1] + rng.uniform(-amount, amount)) for p in x]
    return x, springs


def test_force_is_minus_gradient():
    rng = random.Random(1)
    x, springs = perturbed_grid(rng)
    n = len(x)
    zero_v = [(0.0, 0.0)] * n
    f = ms.forces(x, zero_v, [1.0] * n, springs)

    def energy(flat):
        pts = [(flat[2 * i], flat[2 * i + 1]) for i in range(n)]
        return ms.spring_energy(pts, springs)

    flat = [c for p in x for c in p]
    g = num_grad(energy, flat, 1e-6)
    scale = max(abs(c) for c in g)
    for i in range(n):
        for d in range(2):
            assert abs(f[i][d] + g[2 * i + d]) <= 1e-6 * scale


def test_zero_force_at_rest_and_after_rigid_motion():
    x, springs = ms.grid(4, 4, 0.5, 80.0, 40.0, 10.0)
    n = len(x)
    zv = [(0.0, 0.0)] * n
    for th, t in ((0.0, (0.0, 0.0)), (0.7, (1.0, -2.0)), (2.5, (0.3, 0.4))):
        c, s = math.cos(th), math.sin(th)
        y = [(c * p[0] - s * p[1] + t[0], s * p[0] + c * p[1] + t[1]) for p in x]
        f = ms.forces(y, zv, [1.0] * n, springs)
        assert max(abs(v) for fi in f for v in fi) < 1e-10


def test_momentum_conserved_with_damping():
    rng = random.Random(4)
    x, springs = perturbed_grid(rng, 5, 4, 0.2)
    n = len(x)
    mass = [rng.uniform(0.5, 2.0) for _ in range(n)]
    inv = [1.0 / m for m in mass]
    v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in range(n)]
    p0 = ms.momentum(x, v, mass)
    for _ in range(300):
        x, v = ms.step(x, v, inv, mass, springs, 0.005, damping=0.5)
    p1 = ms.momentum(x, v, mass)
    ref = max(1.0, max(abs(c) for c in p0))
    for a, b in zip(p0, p1):
        assert abs(a - b) <= 1e-10 * ref


def oscillator(dt, steps, k=100.0, m=1.0):
    """One mass on a spring of rest length 1 to a fixed point; return the largest |stretch|."""
    x = [(0.0, 0.0), (1.1, 0.0)]
    v = [(0.0, 0.0), (0.0, 0.0)]
    springs = [(0, 1, 1.0, k)]
    big = 0.0
    for _ in range(steps):
        x, v = ms.step(x, v, [0.0, 1.0 / m], [1.0, m], springs, dt)
        big = max(big, abs(x[1][0] - 1.0))
        if big > 1e6:
            break
    return big


def test_step_limit_check_value():
    assert abs(ms.step_limit(100.0, 1.0) - 0.2) < 1e-15
    assert oscillator(0.19, 2000) < 1.0
    assert oscillator(0.21, 2000) > 1e3


def test_energy_band_symplectic_euler():
    # k = m = 1, stretch 1, dt = 0.1: E stays in [0.5 / 1.05, 0.5 / 0.95].
    # The rest length is 10, so the spring never passes through zero length.
    x = [(0.0, 0.0), (11.0, 0.0)]
    v = [(0.0, 0.0), (0.0, 0.0)]
    springs = [(0, 1, 10.0, 1.0)]
    lo, hi = 1.0, 0.0
    for _ in range(10000):
        x, v = ms.step(x, v, [0.0, 1.0], [1.0, 1.0], springs, 0.1)
        e = ms.spring_energy(x, springs) + ms.kinetic_energy(v, [0.0, 1.0])
        lo, hi = min(lo, e), max(hi, e)
    assert 0.476190 <= lo and hi <= 0.526316
    assert lo < 0.4763 and hi > 0.5262


def lattice_energy(k, k_d, strain, angle, cells=6):
    """Energy per cell of a periodic patch under the affine map x -> x + strain (d . x) d."""
    x, springs = ms.grid(cells + 2, cells + 2, 1.0, k, k_d, 0.0)
    c, s = math.cos(angle), math.sin(angle)
    y = [(p[0] + strain * (c * p[0] + s * p[1]) * c, p[1] + strain * (c * p[0] + s * p[1]) * s) for p in x]
    # count only the springs whose lower left end is inside the inner cells x cells block,
    # so that each lattice cell holds one horizontal, one vertical and two diagonal springs
    e = 0.0
    n = cells + 2
    for a, b, rest, kk in springs:
        ia, ja = a % n, a // n
        ib, jb = b % n, b // n
        lo_i, lo_j = min(ia, ib), min(ja, jb)
        if 0 <= lo_i < cells and 0 <= lo_j < cells:
            e += 0.5 * kk * (math.dist(y[a], y[b]) - rest) ** 2
    return e / cells ** 2


def test_lattice_anisotropy():
    eps = 1e-4
    for k_d in (0.0, 25.0, 50.0):
        for ang in (0.0, 0.3, math.pi / 4):
            got = lattice_energy(100.0, k_d, eps, ang)
            want = ms.uniaxial_energy_per_cell(100.0, k_d, 1.0, eps, ang)
            assert abs(got - want) <= 1e-3 * want
    # structural springs only: half as stiff at 45 degrees as along an axis
    r = ms.uniaxial_energy_per_cell(100.0, 0.0, 1.0, 1.0, math.pi / 4) / ms.uniaxial_energy_per_cell(100.0, 0.0, 1.0, 1.0, 0.0)
    assert abs(r - 0.5) < 1e-12
    # k_d = k / 2 gives the same uniaxial stiffness in every direction
    vals = [ms.uniaxial_energy_per_cell(100.0, 50.0, 1.0, 1.0, a) for a in (0.0, 0.2, 0.5, math.pi / 4)]
    assert max(vals) - min(vals) < 1e-9

References

  1. Xavier Provot, Deformation constraints in a mass-spring model to describe rigid cloth behavior, Graphics Interface 95, 147-154, 1995, Section 2.1 (structural, shear and flexion springs on a grid), Section 2.2 (the forces) and Section 4, equation (3) (the critical stiffness for a given step)
  2. Donald H. House and David E. Breen (editors), Cloth Modeling and Animation, A K Peters, 2000, the chapters on particle and spring models of cloth (general locator)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/4B6KHP/text.yaml