Algorithmadvanced
Fast mass-spring simulation
Also called Liu fast mass-spring.
Solve implicit Euler for mass-spring systems by block coordinate descent that alternates a local spring direction step and a prefactored global solve.
- Solves
- Cloth simulation
- Time
- Θ(m + n b) iterationO(n b^2) prefactorO(k (m + n b)) step
- Space
- O(n b) factor
- Where
- b = the half bandwidth of the matrix in the particle order; k = the number of local and global iterations per step; m = the number of springs; n = the number of particles
- Model
- Real RAM
- Properties
- deterministicnot exactmomentum conservingmonotone objectiveunconditionally stable
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Tiantian Liu, Adam W. Bargteil, James F. O'Brien, Ladislav Kavan, 2013
Fast mass-spring simulation solves the backward Euler step of a mass-spring system without a Newton solve. Liu, Bargteil, O'Brien and Kavan (2013) noticed that the energy of a Hooke spring is the smallest squared distance between the spring vector and any vector of the rest length. With the spring directions as extra unknowns, the step becomes a minimization that is easy in each block: the best directions for given positions are a normalization per spring, and the best positions for given directions are one linear solve with a matrix that never changes. The matrix is factored once, so each iteration is cheap. The method converges to the exact implicit Euler solution; a few iterations give a stable and plausible step.
In plain words
An implicit step asks for the positions at the end of the step that balance the pull of the springs against the motion each particle already has. With stiff springs, finding these positions is a hard nonlinear problem.
The trick is to split each spring into two parts: a direction and a length. If the directions were known, every spring would act like a simple linear rubber band toward a known target, and the positions would come from one linear solve. If the positions were known, the best direction of each spring is just the line between its two ends.
So the method guesses the positions, then finds the directions, then solves for the positions, and repeats. Each round can only lower the quantity the step minimizes. The linear solve uses the same matrix every time, so the computer prepares it once and reuses it.
The problem
Given positions , velocities , masses, springs , external forces and a step , find with
and . This is backward Euler for . Its solutions are the stationary points of
In cloth simulation the springs are stiff, so an explicit step would need to be tiny, and a Newton step needs a new matrix at each iteration.
The algorithm
The key fact (Liu et al., Section 4, the Lemma) is
with the minimum at . Put a vector of length into each spring term. The objective becomes
where is the graph Laplacian of the springs weighted by , and puts on one end of spring and on the other (equations (11) to (14)). Then , and the step minimizes by turns:
FAST-MASS-SPRING-STEP(x_n, v_n, h)- 1
once: factor A = M + h^2 L by Cholesky ▷ A does not depend on the state - 2
y <- x_n + h alpha v_n ▷ alpha = 1 means no damping - 3
x <- y - 4
repeat k times: - 5
for each spring i = (a, b, r): d_i <- r (x_a - x_b) / |x_a - x_b| ▷ local step - 6
c <- M y + h^2 (J d + f_ext) - 7
x <- the solution of A x = c, one solve per coordinate with the factor ▷ global step - 8
x_{n+1} <- x, v_{n+1} <- (x - x_n) / h
Local step (L5). For fixed positions, each appears in one term only, and Lemma 1 gives the best one: the current spring direction scaled to the rest length. This is a normalization per spring, cheap and parallel.
Global step (L6, L7). For fixed , is a quadratic in with the Hessian , which is symmetric positive definite and acts on each coordinate separately. Its factor from line L1 holds while , the masses, the stiffnesses, the springs and the pins stay the same, so each global step is a forward and a backward substitution.
Pins. A pinned particle is a constant. Its spring terms add to the right side at the free end, and its row leaves the matrix.
Damping and collisions. Liu et al. (Section 4.1) damp by replacing with in , with slightly below 1, a tuning value. They handle collisions outside the solver, by moving positions with a collision method; the code of this page has no collisions.
The code builds on a 2D grid in row order, so it is banded, and uses a banded Cholesky factor. Liu et al. use a sparse Cholesky factor from a library on 3D meshes.
Example
One spring by hand. One particle of kg hangs on a horizontal spring of N/m and rest length 1 m from a pin at the origin, with no gravity. It starts at rest at m, a stretch m, and s, so . Then , and the local step gives for the spring from the particle to the pin. The global step solves , so and m/s. The stretch went from to , and the energy went from J to J, half of it. Backward Euler multiplies the energy by at each step, so the spring stops swinging after a few steps. The step is stable, and stable is not accurate.
Convergence, measured. An 8 by 8 grid with spacing m, particles of kg, structural springs of N/m and shear springs of N/m (210 springs) hangs from two corners with s. For the first step from rest, the relative error , with from Newton's method, is
| iterations | 1 | 2 | 5 | 10 | 20 | 50 |
|---|---|---|---|---|---|---|
| relative error | 0.377 | 0.208 | 0.053 | 0.0068 | 1.2e-4 | 1.1e-9 |
The decrease is linear, as Liu et al. report in their Figure 2. Here rad/s and , so symplectic Euler with the same step blows up, and the test checks that.
Timings, measured by the authors. Liu et al. (Table 1) simulate a curtain of 6561 vertices and 32158 springs with ms and 10 iterations per frame, at 5 ms per iteration on one core of an Intel i7-3720QM, with a factorization of 113 ms done once.
Correctness
The claims are proved in proofs/correctness.md.
- The splitting is exact (proved). , by the Lemma.
- Descent (proved). Each local and global step does not increase , because each block step minimizes in its block.
- Fixed points are solutions (proved). A fixed point of the iteration with no spring of zero length is a stationary point of , so it solves the backward Euler step. The objective is not convex, so the limit is a stationary point, not always the global minimum. The linear rate is a measurement.
- Momentum (proved). Without pins, every global step keeps , after any number of iterations. The test checks the momentum to relative after 1 and 3 iterations per step for 100 steps.
- The constant matrix (proved). is symmetric positive definite and does not depend on the state, so one factorization serves all steps.
The tests check the Lemma against a scan of directions, the banded factor against a dense solve, the forces against central differences of the energy and zero force at rest and after a rotation, the descent at every iteration, the converged step against Newton's method to m, the momentum, the exact energy factor of the oscillator, and the bounded run at .
Proof: The local and global steps decrease the backward Euler objective, keep momentum, and stop only at a solutionfull
We use the notation of the page. The free particles are the unknowns; a pinned particle is a constant. is the diagonal mass matrix, the step, for the free particles, and a spring joins and with rest length and stiffness . The objective of one backward Euler step is
Its gradient is , so is the backward Euler equation with (Liu et al. 2013, equations (5) to (8), with ).
The spring terms as a minimum
Lemma 1 (Liu et al. 2013, Section 4). For and , , and for the minimum is at .
Proof. For , the reverse triangle inequality gives . For , , which has the length . Equality in the reverse triangle inequality for and needs to point along , so the minimizer is unique then.
Define, for spring vectors with ,
By Lemma 1, , and the minimum is at the of line L5 (the local step).
The global step
Lemma 2. For a fixed , has exactly one minimizer, the solution of in each coordinate, where on the free particles and holds the pinned terms. Lines L6 and L7 compute it.
Proof. Expand the spring sum: with the graph Laplacian weighted by (diagonal entry over the springs at a particle, off-diagonal entry ), and , where has at and at . When a spring has one pinned end , the terms with are constants or linear in the free unknowns, and they give , which is at the free end. So is a quadratic with the Hessian in each coordinate. is positive semidefinite, because (with pinned ends set to zero), and is diagonal with positive masses, so is symmetric positive definite. The minimizer is the unique solution of , which is the stated system. does not depend on , or , so its Cholesky factor from line L1 serves every iteration and every step, as long as , the masses, the stiffnesses, the pins and the springs stay the same.
The banded factor. The code orders the particles row by row, so for , with the half bandwidth. The Cholesky formulas give for by induction on : every product with has , so it is zero. So the code may skip the entries outside the band, and it computes the same factor as a dense Cholesky decomposition.
Descent and fixed points
Theorem 3. Each local step followed by a global step does not increase .
Proof. Let be the local step at and the global step for . Then . The first inequality is the minimum over , the second is Lemma 2, and the last equality is Lemma 1.
The sequence is bounded below, because , which is bounded below. So the values converge.
Theorem 4. If is a fixed point of the iteration and no spring has length zero at , then , so solves the backward Euler step.
Proof. Let be the local step at . A fixed point means that minimizes , so . The function is at least zero everywhere (Lemma 1) and is zero at . Both terms are differentiable near , since no spring has length zero there, so is a minimum of and . Hence .
is not convex in general, so the iteration finds a stationary point of , not always the global minimum. The rate of convergence is linear in the measurements of the page and of Liu et al. (Figure 2); this page proves no rate.
Momentum
Theorem 5. With no pins, after any number of iterations, . With the step keeps the linear momentum of the backward Euler step exactly in exact arithmetic.
Proof. Sum the rows of the system of Lemma 2. Each row of sums to zero, so , and adds and for each spring, so its sum is zero. So after the global step, whatever was. Subtract and divide by , using and line L8.
Stable is not accurate
Theorem 6. Let one particle of mass move on a line, joined to a pinned particle by one spring along the line, with no gravity and . If the spring length stays positive, one iteration gives the exact backward Euler step, and the energy , with the stretch, is multiplied by at each step, .
Proof. The direction of the spring does not change, so the local step at already gives the of the solution, and the global step solves the linear backward Euler equations , . So and . Then . The cross terms cancel, and the numerator is .
With N/m, kg and s, and each step halves the energy. The step is stable for every , and the energy loss is a property of backward Euler, not of the spring.
Complexity
The factorization is done once. For a banded matrix of half bandwidth it costs time and space; for a 2D grid of width in row order, with shear springs, so . One iteration costs for the local step and the right side, and for the two substitutions per coordinate. A step with iterations costs . With a fill-reducing order and a sparse factor, the solve costs the number of nonzeros of the factor. A Newton step instead needs a new matrix and a new factorization or an iterative solve at every iteration.
Properties
- Stable for every step size. Every iteration lowers , and the global step is a well-posed solve. Large steps lose energy, as backward Euler does.
- Monotone. The objective never increases, so the iteration needs no line search.
- Constant matrix. The system matrix changes only when , a mass, a stiffness, a spring or a pin changes. Tearing or changing the step means a new factorization.
- Linear convergence. Early iterations make large progress; later ones are slow. Newton's method converges faster near the solution but costs much more per iteration.
- Momentum conserving. Without pins and with , linear momentum changes only by the external forces.
- Springs only. The splitting needs an energy that is a squared distance to a set. Bending, volume and other energies need the generalization of projective dynamics.
Variants and improvements
- Projective dynamics. Bouaziz et al. (2014) generalized the local step to the projection onto any constraint set, which covers triangles, tetrahedra, bending and volume. See projective dynamics.
- Acceleration. Later work speeds up the linear convergence, for example with Chebyshev or Anderson acceleration of the iterates.
- Warm start. Starting from is the choice of the paper. Starting from an extrapolation of the last steps can save iterations.
- Newton after descent. For an exact solution, a few iterations give a good start for Newton's method on the same objective, as in optimization time integration. Liu et al. (Section 5) observed that their iterations beat damped Newton steps early on.
- Other energies by descent. Vertex block descent also lowers the backward Euler objective by blocks, one vertex at a time, with no global solve.
When to use it
Use it for stiff mass-spring cloth, hair or soft bodies with a fixed step and fixed connectivity, where a stable and plausible step at a fixed cost matters more than an exact solution: games, previews and real-time tools.
Do not use it when the connectivity changes every step, as in tearing or cutting, because every change needs a new factorization. When an accurate solution of the implicit step is needed, finish with Newton's method. For energies that are not springs, use projective dynamics or a Newton-type solver.
Pitfalls
- Few iterations are not the solution. With a fixed small number of iterations the answer is not the implicit Euler solution. In practice the cloth then looks softer than its springs; the amount depends on the scene and the step, and it is an observation, not a bound.
- Zero-length springs. The local step divides by the spring length. A spring that collapses has no direction; the code then picks any direction of the right length, which is a minimizer too.
- Changing the step. Changing changes . A variable step needs a new factorization, which removes the main gain.
- Collisions in the solve. A collision handled by forces would change the matrix. Handle contact outside the solve, as the authors do, or add it as a constraint in projective dynamics.
- Damping by . The ether drag also slows rigid motion, including free fall, because it scales the whole velocity.
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
# 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
fast_mass_spring.py 207 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-mass-spring/. The authors are listed in prov/CQQNYH.jsonl.
"""Fast simulation of mass-spring systems (Liu, Bargteil, O'Brien and Kavan 2013), in 2D.
One backward Euler step of a spring system is the minimization of
g(x) = 1/2 (x - y)^T M (x - y) + h^2 (E(x) - x^T f_ext), y = x_n + h alpha v_n,
with E(x) = sum 1/2 k (|x_a - x_b| - r)^2. Each spring term equals
min over |d| = r of 1/2 k |(x_a - x_b) - d|^2, so g is the minimum over the
spring directions d of a function that is quadratic in x. Block coordinate
descent alternates a local step (best d for fixed x: d = r (x_a - x_b) / |x_a - x_b|)
and a global step (best x for fixed d: one solve with the constant matrix
M + h^2 L, factored once by Cholesky). In 2D the matrix acts on the x and the
y coordinates separately.
Springs are tuples (a, b, rest, k). Particles in the set `fixed` do not move.
"""
import math
GRAVITY = (0.0, -9.81)
# ---------------------------------------------------------------- banded Cholesky
def bandwidth(a):
n = len(a)
bw = 0
for i in range(n):
for j in range(i):
if a[i][j] != 0.0:
bw = max(bw, i - j)
return bw
def cholesky_band(a, bw):
"""Lower triangular R with R R^T = a, for a symmetric positive definite a of half bandwidth bw."""
n = len(a)
r = [[0.0] * n for _ in range(n)]
for i in range(n):
lo = max(0, i - bw)
for j in range(lo, i + 1):
s = a[i][j]
ri, rj = r[i], r[j]
for k in range(max(lo, j - bw), j):
s -= ri[k] * rj[k]
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
ri[i] = math.sqrt(s)
else:
ri[j] = s / rj[j]
return r
def cholesky_solve(r, bw, b):
"""Solve R R^T x = b by a forward and a backward substitution."""
n = len(r)
z = [0.0] * n
for i in range(n):
s = b[i]
ri = r[i]
for k in range(max(0, i - bw), i):
s -= ri[k] * z[k]
z[i] = s / ri[i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
s = z[i]
for k in range(i + 1, min(n, i + bw + 1)):
s -= r[k][i] * x[k]
x[i] = s / r[i][i]
return x
# ---------------------------------------------------------------- the solver
class FastMassSpring:
def __init__(self, n, springs, mass, h, fixed=(), alpha=1.0, gravity=GRAVITY):
self.n = n
self.springs = list(springs)
self.mass = list(mass)
self.h = h
self.alpha = alpha # the velocity in y is alpha v_n (ether drag, Liu et al. Section 4.1)
self.fixed = set(fixed)
self.free = [i for i in range(n) if i not in self.fixed]
self.slot = {p: s for s, p in enumerate(self.free)}
self.f_ext = [(m * gravity[0], m * gravity[1]) for m in self.mass]
# A = M + h^2 L on the free particles; L is the stiffness-weighted graph Laplacian
nf = len(self.free)
a = [[0.0] * nf for _ in range(nf)]
for p in self.free:
a[self.slot[p]][self.slot[p]] = self.mass[p]
self.coupling = [] # (free slot, fixed particle, h^2 k): the right side gets + h^2 k x_fixed
h2 = h * h
for sa, sb, rest, k in self.springs:
for p, q in ((sa, sb), (sb, sa)):
if p in self.fixed:
continue
a[self.slot[p]][self.slot[p]] += h2 * k
if q in self.fixed:
self.coupling.append((self.slot[p], q, h2 * k))
else:
a[self.slot[p]][self.slot[q]] -= h2 * k
self.bw = bandwidth(a)
self.r = cholesky_band(a, self.bw) # @line L1
def local_step(self, x):
"""The best rest-length vector d of each spring for fixed x."""
d = []
for a, b, rest, k in self.springs:
dx = x[a][0] - x[b][0]
dy = x[a][1] - x[b][1]
length = math.hypot(dx, dy)
if length == 0.0:
d.append((rest, 0.0)) # any direction is optimal for a spring of length zero
else:
d.append((rest * dx / length, rest * dy / length)) # @line L5
return d
def global_step(self, x, d, y):
"""The best free positions for fixed d: solve (M + h^2 L) x = M y + h^2 (J d + f_ext)."""
h2 = self.h * self.h
nf = len(self.free)
rhs = [[self.mass[p] * y[p][c] + h2 * self.f_ext[p][c] for p in self.free] for c in range(2)]
for (a, b, rest, k), di in zip(self.springs, d):
for c in range(2):
if a not in self.fixed:
rhs[c][self.slot[a]] += h2 * k * di[c] # @line L6
if b not in self.fixed:
rhs[c][self.slot[b]] -= h2 * k * di[c]
for s, q, w in self.coupling:
for c in range(2):
rhs[c][s] += w * x[q][c]
cols = [cholesky_solve(self.r, self.bw, rhs[c]) for c in range(2)] # @line L7
out = list(x)
for s in range(nf):
out[self.free[s]] = (cols[0][s], cols[1][s])
return out
def inertial_target(self, x, v):
return [x[i] if i in self.fixed else
(x[i][0] + self.h * self.alpha * v[i][0], x[i][1] + self.h * self.alpha * v[i][1])
for i in range(self.n)] # @line L2
def step(self, x, v, iterations=10):
"""One step of backward Euler by `iterations` local and global steps. Return (x, v)."""
y = self.inertial_target(x, v)
z = list(y) # @line L3
for _ in range(iterations): # @line L4
d = self.local_step(z)
z = self.global_step(z, d, y)
new_v = [((z[i][0] - x[i][0]) / self.h, (z[i][1] - x[i][1]) / self.h) for i in range(self.n)] # @line L8
return z, new_v
# ------------------------------------------------------------ energies for checks
def spring_energy(self, x):
e = 0.0
for a, b, rest, k in self.springs:
e += 0.5 * k * (math.dist(x[a], x[b]) - rest) ** 2
return e
def objective(self, x, y):
"""g(x) = 1/2 (x - y)^T M (x - y) + h^2 (E(x) - x^T f_ext) over the free particles."""
h2 = self.h * self.h
s = 0.0
for p in self.free:
s += 0.5 * self.mass[p] * ((x[p][0] - y[p][0]) ** 2 + (x[p][1] - y[p][1]) ** 2)
s -= h2 * (x[p][0] * self.f_ext[p][0] + x[p][1] * self.f_ext[p][1])
return s + h2 * self.spring_energy(x)
def spring_forces(self, x):
"""Elastic forces -dE/dx on every particle."""
f = [[0.0, 0.0] for _ in range(self.n)]
for a, b, rest, k in self.springs:
dx = x[a][0] - x[b][0]
dy = x[a][1] - x[b][1]
length = math.hypot(dx, dy)
s = k * (length - rest) / length
f[a][0] -= s * dx
f[a][1] -= s * dy
f[b][0] += s * dx
f[b][1] += s * dy
return f
def grid(nx, ny, spacing, k_struct, k_shear=0.0):
"""A grid with row j = 0 at the top (y = 0) and rows going down. Return (x, springs)."""
def idx(i, j):
return j * nx + i
x = [(i * spacing, -j * spacing) for j in range(ny) for i in range(nx)]
springs = []
for j in range(ny):
for i in range(nx):
if i + 1 < nx:
springs.append((idx(i, j), idx(i + 1, j), spacing, k_struct))
if j + 1 < ny:
springs.append((idx(i, j), idx(i, j + 1), spacing, k_struct))
if k_shear > 0.0 and i + 1 < nx and j + 1 < ny:
springs.append((idx(i, j), idx(i + 1, j + 1), spacing * math.sqrt(2.0), k_shear))
springs.append((idx(i + 1, j), idx(i, j + 1), spacing * math.sqrt(2.0), k_shear))
return x, springs
test_fast_mass_spring.py 196 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/fast-mass-spring/. The authors are listed in prov/CQQNYH.jsonl.
"""Tests of fast mass-spring simulation against brute force, Newton's method and exact values."""
import math
import random
from anim import num_grad, solve
import fast_mass_spring as fms
def test_lemma_by_brute_force():
"""(|p| - r)^2 = min over |d| = r of |p - d|^2, by a scan of directions."""
rng = random.Random(1)
for _ in range(20):
p = (rng.uniform(-2, 2), rng.uniform(-2, 2))
r = rng.uniform(0.0, 2.0)
best = min((p[0] - r * math.cos(t)) ** 2 + (p[1] - r * math.sin(t)) ** 2
for t in (2 * math.pi * i / 20000 for i in range(20000)))
assert abs(best - (math.hypot(*p) - r) ** 2) < 1e-6
def test_banded_cholesky_against_dense_solve():
rng = random.Random(2)
x, springs = fms.grid(5, 4, 0.1, 30.0, 10.0)
s = fms.FastMassSpring(len(x), springs, [rng.uniform(0.5, 1.5) for _ in x], 0.05, fixed={0, 4})
nf = len(s.free)
a = [[0.0] * nf for _ in range(nf)]
for i in range(nf):
for j in range(nf):
a[i][j] = sum(s.r[i][k] * s.r[j][k] for k in range(nf))
b = [rng.uniform(-1, 1) for _ in range(nf)]
got = fms.cholesky_solve(s.r, s.bw, b)
want = solve(a, b)
assert max(abs(p - q) for p, q in zip(got, want)) < 1e-12
assert s.bw == 6 # a 5 wide grid with shear springs couples i and i + 6
def test_forces_against_num_grad_rest_and_rotation():
rng = random.Random(3)
x, springs = fms.grid(4, 4, 0.2, 50.0, 20.0)
s = fms.FastMassSpring(len(x), springs, [1.0] * len(x), 0.05)
y = [(p[0] + rng.uniform(-0.05, 0.05), p[1] + rng.uniform(-0.05, 0.05)) for p in x]
f = s.spring_forces(y)
def energy(flat):
return s.spring_energy([(flat[2 * i], flat[2 * i + 1]) for i in range(len(y))])
g = num_grad(energy, [c for p in y for c in p], 1e-6)
scale = max(abs(c) for c in g)
for i in range(len(y)):
for c in range(2):
assert abs(f[i][c] + g[2 * i + c]) <= 1e-6 * scale
for th in (0.0, 1.1):
cs, sn = math.cos(th), math.sin(th)
z = [(cs * p[0] - sn * p[1] + 0.3, sn * p[0] + cs * p[1] - 0.7) for p in x]
assert max(abs(c) for fi in s.spring_forces(z) for c in fi) < 1e-10
def hanging_scene(rng, nx=4, ny=4, h=0.05, k=200.0):
x, springs = fms.grid(nx, ny, 0.1, k, k / 2)
mass = [rng.uniform(0.02, 0.05) for _ in x]
s = fms.FastMassSpring(len(x), springs, mass, h, fixed={0, nx - 1})
v = [(0.0, 0.0) if i in s.fixed else (rng.uniform(-1, 1), rng.uniform(-1, 1)) for i in range(len(x))]
x = [p if i in s.fixed else (p[0] + rng.uniform(-0.02, 0.02), p[1] + rng.uniform(-0.02, 0.02))
for i, p in enumerate(x)]
return s, x, v
def test_objective_never_increases():
s, x, v = hanging_scene(random.Random(4))
y = s.inertial_target(x, v)
z = list(y)
prev = s.objective(z, y)
for _ in range(40):
z = s.global_step(z, s.local_step(z), y)
cur = s.objective(z, y)
assert cur <= prev + 1e-12 * abs(prev)
prev = cur
def newton_reference(s, x, v):
"""Backward Euler by Newton's method with a dense Hessian and a backtracking line search."""
y = s.inertial_target(x, v)
z = list(y)
h2 = s.h * s.h
nf = len(s.free)
for _ in range(200):
fs = s.spring_forces(z)
grad = []
for p in s.free:
for c in range(2):
grad.append(s.mass[p] * (z[p][c] - y[p][c]) - h2 * (fs[p][c] + s.f_ext[p][c]))
if max(abs(g) for g in grad) < 1e-13:
break
hess = [[0.0] * (2 * nf) for _ in range(2 * nf)]
for i, p in enumerate(s.free):
hess[2 * i][2 * i] += s.mass[p]
hess[2 * i + 1][2 * i + 1] += s.mass[p]
for a, b, rest, k in s.springs:
d = (z[a][0] - z[b][0], z[a][1] - z[b][1])
length = math.hypot(*d)
u = (d[0] / length, d[1] / length)
# the transverse term is clamped at zero, which keeps the Hessian positive definite
blk = [[h2 * k * (max(0.0, 1 - rest / length) * ((1.0 if r == c else 0.0) - u[r] * u[c]) + u[r] * u[c])
for c in range(2)] for r in range(2)]
for p, q, sg in ((a, a, 1), (b, b, 1), (a, b, -1), (b, a, -1)):
if p in s.fixed or q in s.fixed:
continue
for r in range(2):
for c in range(2):
hess[2 * s.slot[p] + r][2 * s.slot[q] + c] += sg * blk[r][c]
step = solve(hess, [-g for g in grad])
t = 1.0
g0 = s.objective(z, y)
while True:
trial = list(z)
for i, p in enumerate(s.free):
trial[p] = (z[p][0] + t * step[2 * i], z[p][1] + t * step[2 * i + 1])
if s.objective(trial, y) <= g0 or t < 1e-8:
break
t *= 0.5
z = trial
return z
def test_converges_to_the_backward_euler_solution():
s, x, v = hanging_scene(random.Random(5))
ref = newton_reference(s, x, v)
z, _ = s.step(x, v, iterations=300)
assert max(math.dist(p, q) for p, q in zip(z, ref)) < 1e-9
# and z solves M (z - y) = h^2 (f(z) + f_ext) to rounding
y = s.inertial_target(x, v)
fs = s.spring_forces(z)
for p in s.free:
for c in range(2):
res = s.mass[p] * (z[p][c] - y[p][c]) - s.h ** 2 * (fs[p][c] + s.f_ext[p][c])
assert abs(res) < 1e-10
def test_momentum_after_any_number_of_iterations():
rng = random.Random(6)
x, springs = fms.grid(4, 3, 0.1, 100.0, 50.0)
mass = [rng.uniform(0.5, 2.0) for _ in x]
s = fms.FastMassSpring(len(x), springs, mass, 0.02)
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in x]
total = sum(mass)
for iters in (1, 3):
xs, vs = list(x), list(v)
p0 = [sum(m * vi[c] for m, vi in zip(mass, vs)) for c in range(2)]
for n in range(1, 101):
xs, vs = s.step(xs, vs, iterations=iters)
for c in range(2):
want = p0[c] + n * 0.02 * total * fms.GRAVITY[c]
got = sum(m * vi[c] for m, vi in zip(mass, vs))
assert abs(got - want) <= 1e-10 * max(1.0, abs(want))
def test_linear_oscillator_loses_energy_as_backward_euler():
"""One mass on a spring along a line: each step multiplies the energy by 1 / (1 + (omega h)^2)."""
s = fms.FastMassSpring(2, [(0, 1, 1.0, 100.0)], [1.0, 1.0], 0.1, fixed={0}, gravity=(0.0, 0.0))
x = [(0.0, 0.0), (1.5, 0.0)]
v = [(0.0, 0.0), (0.0, 0.0)]
def energy(x, v):
return 0.5 * v[1][0] ** 2 + 0.5 * 100.0 * (x[1][0] - 1.0) ** 2
e = energy(x, v)
for _ in range(20):
x, v = s.step(x, v, iterations=1)
e1 = energy(x, v)
assert abs(e1 / e - 0.5) < 1e-12 # omega h = 10 * 0.1 = 1
e = e1
def test_large_step_stays_bounded_where_symplectic_euler_fails():
nx = 6
x0, springs = fms.grid(nx, nx, 0.1, 1e4, 5e3)
mass = [0.01] * len(x0)
h = 1.0 / 30.0
s = fms.FastMassSpring(len(x0), springs, mass, h, fixed={0, nx - 1})
x, v = list(x0), [(0.0, 0.0)] * len(x0)
for _ in range(30):
x, v = s.step(x, v, iterations=10)
assert s.spring_energy(x) < 10.0 and max(math.hypot(*vi) for vi in v) < 10.0
# symplectic Euler with the same step blows up: omega = 1000 rad/s, omega h = 33
x, v = list(x0), [(0.0, 0.0)] * len(x0)
x = [p if i in s.fixed else (p[0], p[1] - 0.001 * (i % 3)) for i, p in enumerate(x)]
for _ in range(10):
f = s.spring_forces(x)
v = [(0.0, 0.0) if i in s.fixed else (v[i][0] + h * (f[i][0] / mass[i]),
v[i][1] + h * (f[i][1] / mass[i] + fms.GRAVITY[1]))
for i in range(len(x))]
x = [(x[i][0] + h * v[i][0], x[i][1] + h * v[i][1]) for i in range(len(x))]
assert s.spring_energy(x) > 1e6
History
Tiantian Liu, Adam W. Bargteil, James F. O'Brien and Ladislav Kavan presented the method at SIGGRAPH Asia 2013. The local and global structure came from as-rigid-as-possible shape deformation, where Sorkine and Alexa (2007) had alternated rotations and positions. Liu et al. saw that a spring direction plays the role of a rotation, and that the implicit Euler objective fits the same scheme. One year later Bouaziz, Martin, Liu, Kavan and Pauly generalized it to projective dynamics, which became a standard solver for real-time deformable bodies.
References
- Tiantian Liu, Adam W. Bargteil, James F. O'Brien and Ladislav Kavan, Fast simulation of mass-spring systems, ACM Transactions on Graphics 32(6), 2013, Section 3, equations (1) to (8) (implicit Euler as a minimization), Section 4, the Lemma and equations (9) to (14) (the local and global steps), Section 4.1 (damping and collisions), Section 5, Table 1 and Figure 2 (timings and convergence)
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 CQQNYH Edit this page History Report an error Markdown