Algorithm Search⌘K

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)
Properties
deterministicnot exactnot linear momentum conservingmonotone objective with line searchnot monotone objective without line searchnot penetration free
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 3×33 \times 3 system in 3D (2×22 \times 2 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 mim_i, positions xn\mathbf x^n, velocities vn\mathbf v^n, a step Δt\Delta t and elastic energies EjE_j on elements. The output is the next state of the backward Euler step in variational form,

xn+1=arg⁡min⁡xG(x),G(x)=∑imi2Δt2∣xi−yi∣2+∑jEj(x),y=xn+Δtvn+Δt2g,\mathbf x^{n+1} = \arg\min_{\mathbf x} G(\mathbf x), \qquad G(\mathbf x) = \sum_i \frac{m_i}{2\Delta t^2}|\mathbf x_i - \mathbf y_i|^2 + \sum_j E_j(\mathbf x), \qquad \mathbf y = \mathbf x^n + \Delta t\mathbf v^n + \Delta t^2\mathbf g,

equations (1) to (3) of the paper, with its hh written as Δt\Delta t. 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 E=k2(∣xa−xb∣−r)2E = \frac{k}{2}(|\mathbf x_a - \mathbf x_b| - r)^2, yy up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s²; the paper works with 3D cloth and tetrahedral meshes, and the code is a 2D version.

The algorithm

  1. VBD-STEP(x, v, colors, Δt, K)
  2. 1y <- x + Δt v + Δt² g ▷ pinned vertices stay
  3. 2z <- y ▷ initial guess (Section 3.7 discusses others)
  4. 3repeat K times:
  5. 4for each color c:
  6. 5for each vertex i of color c, in parallel:
  7. 6f_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²
  8. 7if |det H_i| > ε: Δx_i <- H_i⁻¹ f_i (optional backtracking line search) else Δx_i <- 0
  9. 8z_i <- z_i + Δx_i for every vertex i of color c
  10. 9v <- (z - x)/Δt; x <- z

The vertex step (L6, L7). The terms of GG that depend on xi\mathbf x_i are its inertia term and the elements that touch it. Their gradient and Hessian with respect to xi\mathbf x_i give the force fi\mathbf f_i and the matrix HiH_i, and the Newton step solves HiΔxi=fiH_i\Delta\mathbf x_i = \mathbf f_i (equations (7) and (9)). For a spring with length ℓ\ell and direction n\mathbf n, ∂2E/∂xi2=k(nnT+(1−r/ℓ)(I−nnT))\partial^2 E/\partial\mathbf x_i^2 = k(\mathbf n\mathbf n^T + (1 - r/\ell)(I - \mathbf n\mathbf n^T)), which is indefinite when the spring is compressed. The paper does not project HiH_i to a positive definite matrix. It skips the vertex when ∣det⁡Hi∣≤ε|\det H_i| \le \varepsilon.

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, ω1=1\omega_1 = 1, ω2=2/(2−ρ2)\omega_2 = 2/(2 - \rho^2), ωn=4/(4−ρ2ωn−1)\omega_n = 4/(4 - \rho^2\omega_{n-1}), where ρ\rho is an estimated spectral radius. The code leaves these out.

Example

One spring by hand. A vertex of mass 1 at (1.5,0)(1.5, 0) is joined to a pin at the origin by a spring with r=1r = 1 and k=100k = 100, at rest, with Δt=0.1\Delta t = 0.1 and no gravity. Then y=(1.5,0)\mathbf y = (1.5, 0), f=(−100⋅0.5,0)=(−50,0)\mathbf f = (-100 \cdot 0.5, 0) = (-50, 0) and H=diag⁡(100+100,100+100⋅13)H = \operatorname{diag}(100 + 100, 100 + 100 \cdot \frac13). The step is Δx=(−0.25,0)\Delta\mathbf x = (-0.25, 0), so the vertex goes to (1.25,0)(1.25, 0), the backward Euler value (1⋅1.5+0.01⋅100⋅1)/(1+0.01⋅100)=1.25(1 \cdot 1.5 + 0.01 \cdot 100 \cdot 1)/(1 + 0.01 \cdot 100) = 1.25. 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 6×66 \times 6 vertices of 0.01 kg with spacing 0.1 m has structural, shear and bending springs with k=1000k = 1000 N/m (158 springs), and its two top corners are pinned. The greedy coloring uses 7 colors. After 10 steps of Δt=1/60\Delta t = 1/60 s, the largest entry of ∇G\nabla G after KK sweeps of one step is

sweeps KK 1 2 5 10 20 50 100 200
largest gradient entry (N) 1.9 1.5 1.1 0.87 0.47 0.074 3.3×10−33.3 \times 10^{-3} 6.7×10−66.7 \times 10^{-6}

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 Δt=1/30\Delta t = 1/30 s. The objective starts at G=621.4G = 621.4.

after 1 sweep 10 sweeps 100 sweeps 300 sweeps
no line search 5.99×1075.99 \times 10^{7} 1.18×1041.18 \times 10^{4} 4067 746
line search 382.9 86.0 54.89 54.78

Without the line search the first sweep raises GG by a factor of about 10510^5, and GG rises in 4 of the 300 sweeps; with it, GG falls at every vertex update, as claim 3 proves.

Correctness

The claims are proved in proofs/correctness.md.

  1. The local problem (proved). GG equals the local energy of vertex ii plus terms without xi\mathbf x_i, so L6 gives the exact gradient and Hessian of GG in xi\mathbf x_i. The test checks both against central differences.
  2. 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.
  3. Descent with a line search (proved). With the line search no update increases GG; with a positive definite HiH_i the search always finds a decrease. The test checks every color of 60 sweeps on the crumpled cloth.
  4. No guarantee without it (measured). The crumpled start above raises GG; the test fixes this case.
  5. Fixed points (proved). If every HiH_i is nonsingular, a sweep leaves x\mathbf x unchanged exactly when ∇G=0\nabla G = 0, the backward Euler equation. Convergence and its rate are not proved; the table measures them, and the test reaches a gradient below 10−610^{-6} after 250 sweeps.
  6. 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 4×44 \times 4 cloth with total mass 0.8 kg and momentum (0.079,0.037)(0.079, 0.037) kg m/s, the drift after 1, 10, 50 and 200 sweeps is 0.051, 0.028, 1.1×10−31.1 \times 10^{-3} and 6.4×10−96.4 \times 10^{-9} kg m/s.

The tests also check the one spring example, that a vertex with a singular HiH_i is skipped, and free fall against the symplectic Euler value −5.3955-5.3955 m after 10 steps of 0.10.1 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 mi>0m_i > 0 and positions xi\mathbf x_i; pinned vertices are fixed. Spring s=(a,b)s = (a, b) has rest length rs>0r_s > 0, stiffness ks>0k_s > 0 and energy Es=ks2(∣xa−xb∣−rs)2E_s = \frac{k_s}{2}(|\mathbf x_a - \mathbf x_b| - r_s)^2. With y=xn+Δtvn+Δt2g\mathbf y = \mathbf x^n + \Delta t\mathbf v^n + \Delta t^2\mathbf g the objective of the step is

G(x)=∑imi2Δt2∣xi−yi∣2+∑sEs(x).G(\mathbf x) = \sum_i \frac{m_i}{2\Delta t^2}|\mathbf x_i - \mathbf y_i|^2 + \sum_s E_s(\mathbf x).

For a free vertex ii, let Fi\mathcal F_i be the set of springs that touch it, and let the local energy be Gi(z)=mi2Δt2∣z−yi∣2+∑s∈FiEs(x with xi=z)G_i(\mathbf z) = \frac{m_i}{2\Delta t^2}|\mathbf z - \mathbf y_i|^2 + \sum_{s \in \mathcal F_i} E_s(\mathbf x \text{ with } \mathbf x_i = \mathbf z).

The local problem

Lemma 1. G(x)=Gi(xi)+ciG(\mathbf x) = G_i(\mathbf x_i) + c_i, where cic_i does not depend on xi\mathbf x_i. So fi=−∇Gi(xi)=−∇iG(x)\mathbf f_i = -\nabla G_i(\mathbf x_i) = -\nabla_i G(\mathbf x) and Hi=∇2Gi(xi)=∇ii2G(x)H_i = \nabla^2 G_i(\mathbf x_i) = \nabla^2_{ii} G(\mathbf x), and for a spring with ℓ=∣xi−xj∣>0\ell = |\mathbf x_i - \mathbf x_j| > 0 and n=(xi−xj)/ℓ\mathbf n = (\mathbf x_i - \mathbf x_j)/\ell,

∇iEs=ks(ℓ−rs) n,∇ii2Es=ks(nnT+(1−rsℓ)(I−nnT)).\nabla_i E_s = k_s(\ell - r_s)\,\mathbf n, \qquad \nabla_{ii}^2 E_s = k_s\Big(\mathbf n\mathbf n^T + \big(1 - \tfrac{r_s}{\ell}\big)(I - \mathbf n\mathbf n^T)\Big).

Proof. The terms of GG that contain xi\mathbf x_i are the inertia term of ii and the springs of Fi\mathcal F_i, which are exactly the terms of GiG_i. For the spring, ∇iℓ=n\nabla_i \ell = \mathbf n and ∇in=(I−nnT)/ℓ\nabla_i \mathbf n = (I - \mathbf n\mathbf n^T)/\ell, so ∇iEs=ks(ℓ−rs)n\nabla_i E_s = k_s(\ell - r_s)\mathbf n, and differentiating again gives ksnnT+ks(ℓ−rs)(I−nnT)/ℓk_s\mathbf n\mathbf n^T + k_s(\ell - r_s)(I - \mathbf n\mathbf n^T)/\ell. □\square

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 (ℓ<rs\ell < r_s), so HiH_i can be indefinite or singular; the code skips the vertex when ∣det⁡Hi∣≤ε|\det H_i| \le \varepsilon.

Colors

Lemma 2 (updates of one color commute). Let i≠ji \ne j be free vertices that no spring joins. Then GiG_i does not depend on xj\mathbf x_j, so the update of ii computed before or after the update of jj 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. GiG_i contains xj\mathbf x_j only through a spring of Fi\mathcal F_i with the other end jj, and there is none. The update of ii is a function of GiG_i only (the Newton step, the determinant test and the line search all use GiG_i), so it does not change when xj\mathbf x_j changes. By induction over the order of the updates in the color, every update sees the same data as in the parallel version. □\square

Lemma 3. The greedy coloring of the code is proper and uses at most Δ+1\Delta + 1 colors, where Δ\Delta 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 Δ\Delta neighbors, so one of the colors 0,…,Δ0, \dots, \Delta is free. □\square

Descent

Theorem 4 (monotone with a line search). With the line search, no vertex update increases GG. So GG never increases during a step.

Proof. The line search accepts a step tΔxit\Delta\mathbf x_i only if Gi(xi+tΔxi)≤Gi(xi)G_i(\mathbf x_i + t\Delta\mathbf x_i) \le G_i(\mathbf x_i), and otherwise returns zero. By Lemma 1, GG changes by the same amount as GiG_i. Within a color, Lemma 2 shows that the parallel updates equal the sequential ones, and each of those does not increase GG. □\square

Lemma 5. If HiH_i is positive definite and fi≠0\mathbf f_i \ne 0, the Newton step Δxi=Hi−1fi\Delta\mathbf x_i = H_i^{-1}\mathbf f_i is a descent direction of GiG_i, and the backtracking line search accepts some t=2−q>0t = 2^{-q} > 0 with a strict decrease, provided GiG_i is smooth near xi\mathbf x_i.

Proof. ∇Gi⋅Δxi=−fiTHi−1fi<0\nabla G_i \cdot \Delta\mathbf x_i = -\mathbf f_i^T H_i^{-1}\mathbf f_i < 0. By Taylor's theorem Gi(xi+tΔxi)<Gi(xi)G_i(\mathbf x_i + t\Delta\mathbf x_i) < G_i(\mathbf x_i) for all small enough t>0t > 0, and halving reaches such a tt. □\square

Without a line search there is no such guarantee: a full Newton step can overshoot, and with an indefinite HiH_i 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 GG by a factor of about 10510^5.

Theorem 6 (fixed points). Suppose that at x∗\mathbf x^* every HiH_i satisfies ∣det⁡Hi∣>ε|\det H_i| > \varepsilon. Then a sweep leaves x∗\mathbf x^* unchanged if and only if ∇G(x∗)=0\nabla G(\mathbf x^*) = 0, that is, if x∗\mathbf x^* satisfies the backward Euler equation M(x∗−y)/Δt2=−∇∑sEs(x∗)M(\mathbf x^* - \mathbf y)/\Delta t^2 = -\nabla\sum_s E_s(\mathbf x^*) on the free vertices.

Proof. Without the line search, the update of ii is Hi−1fiH_i^{-1}\mathbf f_i, which is zero exactly when fi=0\mathbf f_i = 0. With the line search, a zero update can also come from a failed search, but if fi≠0\mathbf f_i \ne 0 and HiH_i is positive definite, Lemma 5 rules this out; we state the theorem for the plain update and for this case. If ∇G(x∗)=0\nabla G(\mathbf x^*) = 0, every fi=0\mathbf f_i = 0 by Lemma 1, so every update is zero. Conversely, if the sweep leaves x∗\mathbf x^* unchanged, the first update of each color is computed at x∗\mathbf x^* (Lemma 2), so every fi(x∗)=0\mathbf f_i(\mathbf x^*) = 0, and ∇G(x∗)=0\nabla G(\mathbf x^*) = 0. □\square

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 rr, with yi=(y,0)\mathbf y_i = (y, 0), y>0y > 0, and the start xi=yi\mathbf x_i = \mathbf y_i, one update gives xi=(my+Δt2krm+Δt2k,0)\mathbf x_i = (\frac{m y + \Delta t^2 k r}{m + \Delta t^2 k}, 0), the backward Euler step.

Proof. Here n=(1,0)\mathbf n = (1, 0), fi=(−k(y−r),0)\mathbf f_i = (-k(y - r), 0) and HiH_i is diagonal with first entry m/Δt2+km/\Delta t^2 + k. So Δxi=(−k(y−r)/(m/Δt2+k),0)\Delta\mathbf x_i = (-k(y - r)/(m/\Delta t^2 + k), 0), and y+Δx=(my+Δt2kr)/(m+Δt2k)y + \Delta x = (m y + \Delta t^2 k r)/(m + \Delta t^2 k). At this point fi=0\mathbf f_i = 0: the second component is zero by symmetry, and the first is −mΔt2(x−y)−k(x−r)=0-\frac{m}{\Delta t^2}(x - y) - k(x - r) = 0 by the formula. □\square

Momentum

Lemma 8. With no pins and no gravity, every stationary point of GG satisfies ∑imixi=∑imiyi\sum_i m_i\mathbf x_i = \sum_i m_i\mathbf y_i, so a converged step keeps the linear momentum. A finite number of sweeps does not keep it in general.

Proof. Each EsE_s is invariant under a common translation of its two ends, so ∑i∇iEs=0\sum_i \nabla_i E_s = 0. Summing ∇iG=0\nabla_i G = 0 over ii gives ∑imi(xi−yi)/Δt2=0\sum_i m_i(\mathbf x_i - \mathbf y_i)/\Delta t^2 = 0, and with y=xn+Δtvn\mathbf y = \mathbf x^n + \Delta t\mathbf v^n and vn+1=(x−xn)/Δt\mathbf v^{n+1} = (\mathbf x - \mathbf x^n)/\Delta t this is ∑mivin+1=∑mivin\sum m_i\mathbf v^{n+1}_i = \sum m_i \mathbf v^n_i. A single vertex update changes ∑mjxj\sum m_j\mathbf x_j by miΔxim_i\Delta\mathbf x_i, which is not zero unless fi=0\mathbf f_i = 0, and nothing in a sweep cancels it exactly; the test measures a nonzero drift after 1 and 10 sweeps. □\square

Cost

Lemma 9. A sweep costs Θ(n+s)\Theta(n + s) for nn free vertices and ss springs, and the memory is Θ(n+s)\Theta(n + s).

Proof. The update of vertex ii costs O(1+∣Fi∣)O(1 + |\mathcal F_i|) for the force, the 2×22 \times 2 Hessian and the solve; the line search multiplies this by at most a constant number of trials. Summing over the vertices gives Θ(n+∑i∣Fi∣)=Θ(n+s)\Theta(n + \sum_i|\mathcal F_i|) = \Theta(n + s), because each spring touches two vertices. The adjacency lists and the colors take Θ(n+s)\Theta(n + s) memory. □\square

Complexity

A vertex update costs O(1+deg⁡i)O(1 + \deg i), so a sweep costs Θ(n+s)\Theta(n + s) and a step O(K(n+s))O(K(n + s)), with Θ(n+s)\Theta(n + s) 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 3×33 \times 3 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 HiH_i indefinite; a plain Newton step can go uphill. Use the line search, or make HiH_i positive definite.
  • Singular vertex Hessians. A vertex whose HiH_i 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.

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
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

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.step
  • a full proof of time.sweep
  • a full proof of space.step
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • at least three sources
  • a scene preset for the example