Algorithmresearch
Vertex block descent
Also called VBD.
Minimize the implicit Euler energy by block coordinate descent over single vertices, each a 3x3 Newton step, in parallel over a graph coloring.
- Time
- O(K (n + s)) stepΘ(n + s) sweep
- Space
- Θ(n + s) step
- Where
- K = the number of sweeps per step; n = the number of free vertices; s = the number of elements (springs here)
- Model
- Real RAM
- Properties
- deterministicnot exactnot linear momentum conservingmonotone objective with line searchnot monotone objective without line searchnot penetration free
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Anka He Chen, Ziheng Liu, Yin Yang, Cem Yuksel, 2024
Vertex block descent (VBD) solves the backward Euler step of a deformable body by updating one vertex at a time. Each update keeps all other vertices fixed and takes one Newton step on the energy terms of that vertex, a system in 3D ( in the 2D code). Chen, Liu, Yang and Yuksel (2024) run the updates in parallel on a GPU over the classes of a graph coloring, because vertices of one color share no element and their updates do not interact. The method is block coordinate descent on the backward Euler objective; with a line search no update increases it, and without one, which is the default of the paper, there is no such guarantee.
In plain words
Picture a cloth as a net of knots joined by springs. The best position of all the knots after one frame is the one that balances inertia against the springs. Finding it for all knots at once means solving one big system. Instead, pick one knot, hold all the others still, and move just this knot to the best place for it. That is a tiny problem. Do this for every knot, and repeat. Knots that share no spring do not affect each other, so you can color the net so that no spring joins two knots of the same color and then move all knots of one color at the same time. Each round brings the net closer to the balanced position.
The problem
The input is a mesh or a mass-spring system with masses , positions , velocities , a step and elastic energies on elements. The output is the next state of the backward Euler step in variational form,
equations (1) to (3) of the paper, with its written as . This is the form that this site also uses for optimization time integration, projective dynamics, incremental potential contact and affine body dynamics. The code uses 2D springs , up and m/s²; the paper works with 3D cloth and tetrahedral meshes, and the code is a 2D version.
The algorithm
VBD-STEP(x, v, colors, Δt, K)- 1
y <- x + Δt v + Δt² g ▷ pinned vertices stay - 2
z <- y ▷ initial guess (Section 3.7 discusses others) - 3
repeat K times: - 4
for each color c: - 5
for each vertex i of color c, in parallel: - 6
f_i <- -(m_i/Δt²)(z_i - y_i) - Σ_{j ∋ i} ∂E_j/∂x_i; H_i <- (m_i/Δt²) I + Σ_{j ∋ i} ∂²E_j/∂x_i² - 7
if |det H_i| > ε: Δx_i <- H_i⁻¹ f_i (optional backtracking line search) else Δx_i <- 0 - 8
z_i <- z_i + Δx_i for every vertex i of color c - 9
v <- (z - x)/Δt; x <- z
The vertex step (L6, L7). The terms of that depend on are its inertia term and the elements that touch it. Their gradient and Hessian with respect to give the force and the matrix , and the Newton step solves (equations (7) and (9)). For a spring with length and direction , , which is indefinite when the spring is compressed. The paper does not project to a positive definite matrix. It skips the vertex when .
Line search. A full Newton step can overshoot or go uphill. The paper makes a backtracking line search on the local energy optional and reports that it costs about 40% more time. The code offers both.
Coloring (L4, L5). A vertex update reads only the vertices that share an element with it. A coloring in which no element joins two vertices of one color lets all vertices of a color update at once from the same state, and the result equals updating them one by one (claim 2). The code uses greedy coloring. The paper reports 8 colors for a mesh of 3891 vertices (Fig. 8).
More parts of the paper. Section 3.3 adds damping to the vertex step (equations (10) and (11)). Section 3.5 handles collisions with penalty energies in the same vertex steps. Section 3.8 accelerates the sweeps by blending iterates with the weights of the Chebyshev semi-iterative method, , , , where is an estimated spectral radius. The code leaves these out.
Example
One spring by hand. A vertex of mass 1 at is joined to a pin at the origin by a spring with and , at rest, with and no gravity. Then , and . The step is , so the vertex goes to , the backward Euler value . One update is exact here because the energy is quadratic along the spring and the vertex does not move across it.
Convergence on a hanging cloth (measured). A cloth of vertices of 0.01 kg with spacing 0.1 m has structural, shear and bending springs with N/m (158 springs), and its two top corners are pinned. The greedy coloring uses 7 colors. After 10 steps of s, the largest entry of after sweeps of one step is
| sweeps | 1 | 2 | 5 | 10 | 20 | 50 | 100 | 200 |
|---|---|---|---|---|---|---|---|---|
| largest gradient entry (N) | 1.9 | 1.5 | 1.1 | 0.87 | 0.47 | 0.074 |
The values with and without the line search agree here, since the line search accepts every full step. The convergence is linear and slow at first.
A crumpled start (measured). The same cloth without pins and without gravity starts at 0.4 times its rest size with small random offsets, so most springs are compressed, with s. The objective starts at .
| after 1 sweep | 10 sweeps | 100 sweeps | 300 sweeps | |
|---|---|---|---|---|
| no line search | 4067 | 746 | ||
| line search | 382.9 | 86.0 | 54.89 | 54.78 |
Without the line search the first sweep raises by a factor of about , and rises in 4 of the 300 sweeps; with it, falls at every vertex update, as claim 3 proves.
Correctness
The claims are proved in proofs/correctness.md.
- The local problem (proved). equals the local energy of vertex plus terms without , so L6 gives the exact gradient and Hessian of in . The test checks both against central differences.
- Colors (proved). Updates of vertices that share no element commute, so the parallel updates of a color equal the sequential ones in any order. The test checks this to the last bit. The greedy coloring is proper and uses at most one more color than the largest vertex degree.
- Descent with a line search (proved). With the line search no update increases ; with a positive definite the search always finds a decrease. The test checks every color of 60 sweeps on the crumpled cloth.
- No guarantee without it (measured). The crumpled start above raises ; the test fixes this case.
- Fixed points (proved). If every is nonsingular, a sweep leaves unchanged exactly when , the backward Euler equation. Convergence and its rate are not proved; the table measures them, and the test reaches a gradient below after 250 sweeps.
- Momentum (proved for the limit, measured otherwise). A converged step keeps the linear momentum without pins and gravity, but a finite number of sweeps does not. On a free cloth with total mass 0.8 kg and momentum kg m/s, the drift after 1, 10, 50 and 200 sweeps is 0.051, 0.028, and kg m/s.
The tests also check the one spring example, that a vertex with a singular is skipped, and free fall against the symplectic Euler value m after 10 steps of s.
Proof: Vertex updates of one color commute, a line search makes the descent monotone, and fixed points are backward Euler stepsfull
We use the notation of the page, for a 2D mass-spring system. The free vertices have masses and positions ; pinned vertices are fixed. Spring has rest length , stiffness and energy . With the objective of the step is
For a free vertex , let be the set of springs that touch it, and let the local energy be .
The local problem
Lemma 1. , where does not depend on . So and , and for a spring with and ,
Proof. The terms of that contain are the inertia term of and the springs of , which are exactly the terms of . For the spring, and , so , and differentiating again gives .
These are equations (7) and (9) of Chen et al. (2024) for this energy, in 2D. The second term of the spring Hessian is negative when the spring is compressed (), so can be indefinite or singular; the code skips the vertex when .
Colors
Lemma 2 (updates of one color commute). Let be free vertices that no spring joins. Then does not depend on , so the update of computed before or after the update of is the same. Hence, for a set of vertices of one color, computing all updates from the same state and then applying them gives the same result as applying them one after another, in any order.
Proof. contains only through a spring of with the other end , and there is none. The update of is a function of only (the Newton step, the determinant test and the line search all use ), so it does not change when changes. By induction over the order of the updates in the color, every update sees the same data as in the parallel version.
Lemma 3. The greedy coloring of the code is proper and uses at most colors, where is the largest number of springs at a vertex.
Proof. Each vertex gets the smallest color that none of its colored neighbors has, so no spring joins two vertices of one color. A vertex has at most neighbors, so one of the colors is free.
Descent
Theorem 4 (monotone with a line search). With the line search, no vertex update increases . So never increases during a step.
Proof. The line search accepts a step only if , and otherwise returns zero. By Lemma 1, changes by the same amount as . Within a color, Lemma 2 shows that the parallel updates equal the sequential ones, and each of those does not increase .
Lemma 5. If is positive definite and , the Newton step is a descent direction of , and the backtracking line search accepts some with a strict decrease, provided is smooth near .
Proof. . By Taylor's theorem for all small enough , and halving reaches such a .
Without a line search there is no such guarantee: a full Newton step can overshoot, and with an indefinite it can point uphill. The paper notes that the Newton step does not guarantee a decrease and makes the line search optional. The page shows a crumpled start where one plain sweep raises by a factor of about .
Theorem 6 (fixed points). Suppose that at every satisfies . Then a sweep leaves unchanged if and only if , that is, if satisfies the backward Euler equation on the free vertices.
Proof. Without the line search, the update of is , which is zero exactly when . With the line search, a zero update can also come from a failed search, but if and is positive definite, Lemma 5 rules this out; we state the theorem for the plain update and for this case. If , every by Lemma 1, so every update is zero. Conversely, if the sweep leaves unchanged, the first update of each color is computed at (Lemma 2), so every , and .
The theorem does not say that the sweeps converge or how fast. Block coordinate descent converges linearly at best, and the page measures the rate.
Corollary 7 (one spring). For one free vertex joined to a pin at the origin by a spring of rest length , with , , and the start , one update gives , the backward Euler step.
Proof. Here , and is diagonal with first entry . So , and . At this point : the second component is zero by symmetry, and the first is by the formula.
Momentum
Lemma 8. With no pins and no gravity, every stationary point of satisfies , so a converged step keeps the linear momentum. A finite number of sweeps does not keep it in general.
Proof. Each is invariant under a common translation of its two ends, so . Summing over gives , and with and this is . A single vertex update changes by , which is not zero unless , and nothing in a sweep cancels it exactly; the test measures a nonzero drift after 1 and 10 sweeps.
Cost
Lemma 9. A sweep costs for free vertices and springs, and the memory is .
Proof. The update of vertex costs for the force, the Hessian and the solve; the line search multiplies this by at most a constant number of trials. Summing over the vertices gives , because each spring touches two vertices. The adjacency lists and the colors take memory.
Complexity
A vertex update costs , so a sweep costs and a step , with memory for the adjacency lists and colors. There is no global matrix and no linear solve. On a GPU the time of a sweep is set by the number of colors and the size of the largest color. The number of sweeps for a given accuracy is a property of the scene.
Properties
- Matrix free. Only systems per vertex; the memory is linear and the work is local.
- Parallel. All vertices of a color update at once.
- Descent only with a line search. Without it the objective can rise (claim 4). The paper reports good results without it in its scenes; that is a measurement, not a guarantee.
- Not momentum conserving per sweep. The step keeps linear momentum only in the limit of many sweeps.
- Contacts. Penalty collisions in the paper do not guarantee a result without penetration (Section 7). Incremental potential contact gives that guarantee with barriers and continuous collision checks, at a higher cost.
- Approximate when stopped early. With few sweeps the step is a partial minimization, which adds numerical damping.
Variants and improvements
- Chebyshev acceleration. Section 3.8 uses the Chebyshev weights above to speed up the sweeps.
- Initialization. Section 3.7 compares starting guesses, including an adaptive one (equation (17)); a better guess reduces the sweeps needed.
- Damping. Section 3.3 adds damping to the vertex step.
- Relation to other solvers. Gauss-Seidel on the Newton system updates one unknown at a time for a fixed linearization; VBD relinearizes at every vertex update. XPBD updates one constraint at a time, and projective dynamics alternates local projections with a global solve.
When to use it
Use VBD for large cloth and soft body scenes on a GPU where a global sparse solve is too slow and the energy is a sum of element energies, such as mass-spring systems or FEM materials. It handles large steps when a line search is used.
Do not use it when a guaranteed descent is needed without the line search, when contact must be free of penetration, or when an accurate solve with few iterations is needed on a very stiff and well connected mesh; use Newton based optimization time integration or incremental potential contact then.
Pitfalls
- Indefinite vertex Hessians. Compressed springs and inverted elements make indefinite; a plain Newton step can go uphill. Use the line search, or make positive definite.
- Singular vertex Hessians. A vertex whose is close to singular must be skipped, as in L7, not solved.
- Coloring errors. Two vertices of one color that share an element give races on a GPU and a result that depends on timing.
- Stopping early. A fixed small number of sweeps makes the cloth softer and more damped than the material.
- Momentum drift. Free bodies drift a little with few sweeps (claim 6).
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
vertex_block_descent.py 191 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-block-descent/. The authors are listed in prov/B1423N.jsonl.
"""Vertex block descent (Chen, Liu, Yang and Yuksel 2024) for a 2D mass-spring system.
One backward Euler step minimizes
G(x) = sum_i m_i / (2 dt^2) |x_i - y_i|^2 + sum_springs (k / 2) (|x_a - x_b| - r)^2,
with y = x_n + dt v_n + dt^2 g. Vertex block descent updates one vertex at a
time with all others fixed: a Newton step on the local energy G_i, which is
the inertia term of vertex i plus the springs that touch it,
H_i dx_i = f_i, f_i = -grad_i G, H_i = m_i / dt^2 I + sum_springs d^2 E / d x_i^2
(equations (7) and (9) of the paper, here 2 by 2). The vertex is skipped if
|det H_i| <= eps. An optional backtracking line search on G_i makes every
update a descent step. Vertices of one color of a graph coloring share no
spring, so their updates do not interact and can run in parallel.
The 2D mass-spring setting is a version of the 3D meshes of the paper.
"""
import math
GRAVITY = (0.0, -9.81)
class System:
def __init__(self, rest, springs, masses, pinned=()):
"""springs are tuples (a, b, rest_length, stiffness)."""
self.rest = [tuple(p) for p in rest]
self.springs = [tuple(s) for s in springs]
self.mass = list(masses)
self.pinned = set(pinned)
self.adj = [[] for _ in rest]
for k, (a, b, _, _) in enumerate(self.springs):
self.adj[a].append(k)
self.adj[b].append(k)
def greedy_coloring(system):
"""Color the free vertices so that no spring joins two vertices of one color. Return the color classes."""
color = {}
for i in range(len(system.rest)):
if i in system.pinned:
continue
used = set()
for k in system.adj[i]:
a, b, _, _ = system.springs[k]
j = b if a == i else a
if j in color:
used.add(color[j])
c = 0
while c in used:
c += 1
color[i] = c
classes = [[] for _ in range(1 + max(color.values(), default=-1))]
for i, c in color.items():
classes[c].append(i)
return classes
def spring_terms(system, x, i, k):
"""The gradient and the Hessian of spring k with respect to x_i."""
a, b, r, stiff = system.springs[k]
j = b if a == i else a
dx, dy = x[i][0] - x[j][0], x[i][1] - x[j][1]
ln = math.hypot(dx, dy)
n = (dx / ln, dy / ln)
g = (stiff * (ln - r) * n[0], stiff * (ln - r) * n[1])
s = 1.0 - r / ln
h = [[stiff * (n[p] * n[q] + s * ((1.0 if p == q else 0.0) - n[p] * n[q])) for q in range(2)] for p in range(2)]
return g, h
def local_energy(system, x, y, dt, i, xi):
"""G_i: the terms of G that depend on x_i, with x_i replaced by xi."""
m = system.mass[i]
e = m / (2.0 * dt * dt) * ((xi[0] - y[i][0]) ** 2 + (xi[1] - y[i][1]) ** 2)
for k in system.adj[i]:
a, b, r, stiff = system.springs[k]
j = b if a == i else a
e += 0.5 * stiff * (math.dist(xi, x[j]) - r) ** 2
return e
def force_and_hessian(system, x, y, dt, i):
m = system.mass[i]
c = m / (dt * dt)
f = [-c * (x[i][0] - y[i][0]), -c * (x[i][1] - y[i][1])]
h = [[c, 0.0], [0.0, c]]
for k in system.adj[i]:
g, hk = spring_terms(system, x, i, k)
f[0] -= g[0]
f[1] -= g[1]
for p in range(2):
for q in range(2):
h[p][q] += hk[p][q]
return f, h
def vertex_update(system, x, y, dt, i, eps=1e-12, line_search=False):
"""The displacement of vertex i, computed from the state x."""
f, h = force_and_hessian(system, x, y, dt, i) # @line L6
d = h[0][0] * h[1][1] - h[0][1] * h[1][0]
if abs(d) <= eps:
return (0.0, 0.0)
dx = ((h[1][1] * f[0] - h[0][1] * f[1]) / d, (-h[1][0] * f[0] + h[0][0] * f[1]) / d) # @line L7
if not line_search:
return dx
e0 = local_energy(system, x, y, dt, i, x[i])
t = 1.0
for _ in range(30):
xi = (x[i][0] + t * dx[0], x[i][1] + t * dx[1])
if local_energy(system, x, y, dt, i, xi) <= e0:
return (t * dx[0], t * dx[1])
t *= 0.5
return (0.0, 0.0)
def predict(system, x, v, dt, gravity=GRAVITY):
return [(p[0] + dt * u[0] + dt * dt * gravity[0], p[1] + dt * u[1] + dt * dt * gravity[1])
if i not in system.pinned else tuple(p) for i, (p, u) in enumerate(zip(x, v))]
def vbd_iteration(system, colors, z, y, dt, line_search=False):
"""One sweep over all colors. Within a color all updates use the same state."""
z = list(z)
for group in colors: # @line L4
moves = [(i, vertex_update(system, z, y, dt, i, line_search=line_search)) for i in group] # @line L5
for i, d in moves:
z[i] = (z[i][0] + d[0], z[i][1] + d[1]) # @line L8
return z
def vbd_step(system, colors, x, v, dt, iterations, gravity=GRAVITY, line_search=False):
"""One backward Euler step by vertex block descent. Return (x, v)."""
y = predict(system, x, v, dt, gravity) # @line L1
z = list(y) # @line L2
for _ in range(iterations): # @line L3
z = vbd_iteration(system, colors, z, y, dt, line_search)
v_new = [((p[0] - q[0]) / dt, (p[1] - q[1]) / dt) for p, q in zip(z, x)] # @line L9
return z, v_new
def objective(system, x, y, dt):
e = 0.0
for i in range(len(x)):
if i not in system.pinned:
m = system.mass[i]
e += m / (2.0 * dt * dt) * ((x[i][0] - y[i][0]) ** 2 + (x[i][1] - y[i][1]) ** 2)
for a, b, r, stiff in system.springs:
e += 0.5 * stiff * (math.dist(x[a], x[b]) - r) ** 2
return e
def gradient_norm(system, x, y, dt):
worst = 0.0
for i in range(len(x)):
if i in system.pinned:
continue
f, _ = force_and_hessian(system, x, y, dt, i)
worst = max(worst, abs(f[0]), abs(f[1]))
return worst
def cloth(nx, ny, spacing, stiffness, mass=1.0, pin_top=True):
"""A grid of nx by ny vertices with structural, shear and bending springs; the top corners are pinned."""
rest = [(i * spacing, -j * spacing) for j in range(ny) for i in range(nx)]
springs = []
def add(a, b):
springs.append((a, b, math.dist(rest[a], rest[b]), stiffness))
for j in range(ny):
for i in range(nx):
v = j * nx + i
if i + 1 < nx:
add(v, v + 1)
if j + 1 < ny:
add(v, v + nx)
if i + 1 < nx and j + 1 < ny:
add(v, v + nx + 1)
add(v + 1, v + nx)
if i + 2 < nx:
add(v, v + 2)
if j + 2 < ny:
add(v, v + 2 * nx)
pinned = [0, nx - 1] if pin_top else []
return System(rest, springs, [mass] * len(rest), pinned)
test_vertex_block_descent.py 153 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/vertex-block-descent/. The authors are listed in prov/B1423N.jsonl.
"""Tests of vertex block descent: derivatives, the coloring, descent and convergence to backward Euler."""
import math
import random
from anim import num_grad
import vertex_block_descent as vb
def crumpled(seed):
rng = random.Random(seed)
s = vb.cloth(6, 6, 0.1, 1000.0, mass=0.01, pin_top=False)
x = [(0.4 * p[0] + rng.uniform(-0.01, 0.01), 0.4 * p[1] + rng.uniform(-0.01, 0.01)) for p in s.rest]
return s, x
def test_example_one_spring():
"""A pinned spring and one vertex: a single Newton step is exact for the backward Euler step along the line."""
s = vb.System([(0.0, 0.0), (1.5, 0.0)], [(0, 1, 1.0, 100.0)], [1.0, 1.0], pinned=[0])
cols = vb.greedy_coloring(s)
x1, v1 = vb.vbd_step(s, cols, [(0.0, 0.0), (1.5, 0.0)], [(0.0, 0.0)] * 2, 0.1, 1, gravity=(0.0, 0.0))
assert math.dist(x1[1], (1.25, 0.0)) < 1e-14 and math.dist(v1[1], (-2.5, 0.0)) < 1e-12
def test_force_and_hessian_against_num_grad():
rng = random.Random(41)
s = vb.cloth(4, 4, 0.1, 500.0, mass=0.02)
x = [(p[0] + rng.uniform(-0.03, 0.03), p[1] + rng.uniform(-0.03, 0.03)) for p in s.rest]
y = [(p[0] + 0.01, p[1] - 0.01) for p in x]
dt = 0.02
for i in range(len(x)):
if i in s.pinned:
continue
f, h = vb.force_and_hessian(s, x, y, dt, i)
def gi(z):
return vb.local_energy(s, x, y, dt, i, (z[0], z[1]))
ng = num_grad(gi, list(x[i]))
assert max(abs(ng[d] + f[d]) for d in range(2)) < 1e-5 * max(1.0, abs(f[0]) + abs(f[1]))
for q in range(2):
def gq(z, q=q):
xs = list(x)
xs[i] = (z[0], z[1])
return -vb.force_and_hessian(s, xs, y, dt, i)[0][q]
col = num_grad(gq, list(x[i]))
for p in range(2):
assert abs(col[p] - h[q][p]) < 1e-4 * max(1.0, abs(h[q][p]))
assert abs(h[0][1] - h[1][0]) < 1e-12
def test_coloring_is_proper_and_small():
s = vb.cloth(8, 8, 0.1, 100.0)
cols = vb.greedy_coloring(s)
color = {i: c for c, group in enumerate(cols) for i in group}
assert set(color) == set(range(64)) - s.pinned
for a, b, _, _ in s.springs:
if a in color and b in color:
assert color[a] != color[b]
assert len(cols) <= 1 + max(len(adj) for adj in s.adj)
def test_parallel_updates_in_a_color_equal_sequential_updates():
s, x = crumpled(42)
y = [(p[0], p[1] - 0.001) for p in x]
cols = vb.greedy_coloring(s)
group = cols[0]
par = list(x)
moves = [(i, vb.vertex_update(s, x, y, 1.0 / 30.0, i)) for i in group]
for i, d in moves:
par[i] = (par[i][0] + d[0], par[i][1] + d[1])
seq = list(x)
for i in group:
d = vb.vertex_update(s, seq, y, 1.0 / 30.0, i)
seq[i] = (seq[i][0] + d[0], seq[i][1] + d[1])
assert par == seq
def test_line_search_never_increases_the_objective():
s, x = crumpled(5)
dt = 1.0 / 30.0
y = vb.predict(s, x, [(0.0, 0.0)] * len(x), dt, (0.0, 0.0))
cols = vb.greedy_coloring(s)
z, prev = list(y), vb.objective(s, y, y, dt)
for _ in range(60):
for group in cols:
z = vb.vbd_iteration(s, [group], z, y, dt, line_search=True)
g = vb.objective(s, z, y, dt)
assert g <= prev * (1.0 + 1e-14)
prev = g
def test_without_line_search_the_objective_can_increase():
"""Measured: from a crumpled start, a plain Newton sweep raises the objective."""
s, x = crumpled(5)
dt = 1.0 / 30.0
y = vb.predict(s, x, [(0.0, 0.0)] * len(x), dt, (0.0, 0.0))
z = vb.vbd_iteration(s, vb.greedy_coloring(s), y, y, dt)
assert vb.objective(s, z, y, dt) > 1e3 * vb.objective(s, y, y, dt)
def test_converges_to_a_backward_euler_step():
s = vb.cloth(6, 6, 0.1, 1000.0, mass=0.01)
cols = vb.greedy_coloring(s)
dt = 1.0 / 60.0
x, v = list(s.rest), [(0.0, 0.0)] * 36
for _ in range(10):
x, v = vb.vbd_step(s, cols, x, v, dt, 20)
y = vb.predict(s, x, v, dt)
z = list(y)
norms = []
for it in range(1, 251):
z = vb.vbd_iteration(s, cols, z, y, dt)
if it in (10, 100, 250):
norms.append(vb.gradient_norm(s, z, y, dt))
assert norms[0] > norms[1] > norms[2] and norms[2] < 1e-6
def test_singular_vertex_is_skipped():
"""In compression the tangent stiffness m/dt^2 + k (1 - r/l) is zero at l = r k / (k + m/dt^2)."""
k, m, dt, r = 100.0, 1.0, 0.1, 1.0
ln = r * k / (k + m / dt ** 2)
s = vb.System([(0.0, 0.0), (ln, 0.0)], [(0, 1, r, k)], [m, m], pinned=[0])
x = [(0.0, 0.0), (ln, 0.0)]
assert vb.vertex_update(s, x, x, dt, 1, eps=1e-9) == (0.0, 0.0)
def test_momentum_error_shrinks_as_the_iterations_converge():
"""Block descent does not keep momentum exactly per sweep; the converged step does (measured)."""
rng = random.Random(43)
s = vb.cloth(4, 4, 0.1, 300.0, mass=0.05, pin_top=False)
x = [(p[0] + rng.uniform(-0.01, 0.01), p[1] + rng.uniform(-0.01, 0.01)) for p in s.rest]
v = [(rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)) for _ in x]
cols = vb.greedy_coloring(s)
p0 = [sum(m * u[d] for m, u in zip(s.mass, v)) for d in range(2)]
errs = []
for it in (1, 10, 200):
_, v1 = vb.vbd_step(s, cols, x, v, 1.0 / 30.0, it, gravity=(0.0, 0.0))
p1 = [sum(m * u[d] for m, u in zip(s.mass, v1)) for d in range(2)]
errs.append(max(abs(a - b) for a, b in zip(p0, p1)))
assert errs[0] > errs[1] > errs[2] and errs[2] < 1e-7
def test_free_fall_is_symplectic_euler():
s = vb.System([(0.0, 0.0)], [], [1.0])
x, v = [(0.0, 0.0)], [(0.0, 0.0)]
for _ in range(10):
x, v = vb.vbd_step(s, [[0]], x, v, 0.1, 2)
assert abs(x[0][1] + 5.3955) < 1e-12
History
Block coordinate descent and nonlinear Gauss-Seidel, which relax one block of unknowns at a time, are old methods of numerical optimization. Chen, Liu, Yang and Yuksel (2024) applied it to the variational backward Euler step with vertex blocks, a coloring for the GPU, Chebyshev acceleration and penalty collisions, and presented it at SIGGRAPH 2024.
References
- Anka He Chen, Ziheng Liu, Yin Yang and Cem Yuksel, Vertex block descent, ACM Transactions on Graphics 43(4), 2024 (SIGGRAPH 2024), Section 3 (equations (1) to (3) the objective, equations (7) and (9) the vertex Newton step), Section 3.3 (damping), Section 3.5 (collisions), Section 3.7 (initialization, equation (17)), Section 3.8 (Chebyshev acceleration), Section 3.9 (parallelization by coloring), Section 7 (limitations)
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 B1423N Edit this page History Report an error Markdown