Algorithm Search⌘K

Algorithmadvanced

Projective dynamics

Also called projective implicit dynamics.

Solve implicit Euler by alternating local projections of elements onto constraint sets and a global linear solve with a constant prefactored matrix.

Time
Θ(T + z) iterationO(n^3) setupO(K (T + z)) step
Space
O(n + T + z) step
Where
K = the number of local and global iterations per step; T = the number of elements; n = the number of free vertices; z = the number of nonzeros of the Cholesky factor
Properties
constant system matrixdeterministicnot exactlinear momentum conservingmonotone objective
Origin
Sofien Bouaziz, Sebastian Martin, Tiantian Liu, Ladislav Kavan, Mark Pauly, 2014

Projective dynamics (PD) takes a backward Euler step of a deformable body by minimizing the inertia term plus a sum of energies of a special form: the squared distance of each element from a constraint set, such as the set of rotations. Bouaziz, Martin, Liu, Kavan and Pauly (2014) solve this minimization by alternating two steps. The local step projects every element onto its set, independently and in parallel. The global step solves a linear system whose matrix never changes, so it is factored once by Cholesky decomposition. Each pair of steps never increases the objective, which makes the method robust at large time steps, but it converges only linearly.

In plain words

Think of a sheet made of small triangles. Each triangle wants to be a turned copy of its rest shape. First let the sheet fly freely for one frame. Then repeat two moves. In the first move, look at each triangle alone and find the turned copy of its rest shape that is closest to it; this is quick and every triangle can do it at the same time. In the second move, find the positions of all corners that best agree with all these copies at once and with where the free flight wanted them. This is one linear system, and it is the same system in every frame, so you prepare it once and then each solve is cheap. Each round makes the total mismatch smaller or keeps it the same.

The problem

The input is a mesh with lumped vertex masses MM, rest shape, positions xn\mathbf x^n, velocities vn\mathbf v^n, a step Δt\Delta t and a set of elements, each with a weight wtw_t and a constraint set Ct\mathcal C_t. The output is the next state of the backward Euler step in variational form,

xn+1=arg⁡min⁡x 12Δt2(x−y)TM(x−y)+∑twt2 min⁡pt∈Ct∣AtStx−Btpt∣2,y=xn+Δtvn+Δt2g,\mathbf x^{n+1} = \arg\min_{\mathbf x}\ \frac{1}{2\Delta t^2}(\mathbf x - \mathbf y)^T M (\mathbf x - \mathbf y) + \sum_t \frac{w_t}{2}\, \min_{\mathbf p_t \in \mathcal C_t} |A_t S_t \mathbf x - B_t \mathbf p_t|^2, \qquad \mathbf y = \mathbf x^n + \Delta t\mathbf v^n + \Delta t^2 \mathbf g,

the same form that this site uses for XPBD, optimization time integration, vertex block descent, incremental potential contact and affine body dynamics. StS_t selects the vertices of element tt, and AtA_t, BtB_t are constant matrices. For the strain energy used here, AtStxA_t S_t \mathbf x is the deformation gradient FtF_t, BtB_t is the identity and Ct\mathcal C_t is the set of rotations, so the element energy is wt2dist⁡(Ft,SO(2))2\frac{w_t}{2}\operatorname{dist}(F_t, SO(2))^2 with wt=k⋅areatw_t = k \cdot \text{area}_t. This is the energy of as-rigid-as-possible deformation. The page uses 2D triangles, yy up and g=(0,−9.81)\mathbf g = (0, -9.81) m/s²; the paper works with 3D meshes and many constraint types, and the code is a 2D version.

The algorithm

  1. PD-STEP(x, v, Δt, K)
  2. 1(once) L <- M/Δt² + Σ_t w_t S_tᵀ A_tᵀ A_t S_t; factor L = C Cᵀ
  3. 2y <- x + Δt v + Δt² g ▷ pinned vertices stay
  4. 3z <- y
  5. 4repeat K times:
  6. 5for each element t: p_t <- projection of A_t S_t z onto C_t ▷ local, parallel
  7. 6solve L z = M y/Δt² + Σ_t w_t S_tᵀ A_tᵀ B_t p_t with the factor C ▷ global
  8. 7v <- (z - x)/Δt; x <- z

Local step (L5). For the strain energy, the projection of FtF_t onto the rotations is the rotation factor of its polar decomposition. In 2D it is the rotation by θ=atan2⁡(f10−f01,f00+f11)\theta = \operatorname{atan2}(f_{10} - f_{01}, f_{00} + f_{11}), which the shared polar helper computes. It is always a rotation, also for an inverted triangle. Other constraint sets have other projections: an interval of lengths for springs, an interval of areas or volumes, or a plane for a collision.

Global step (L6). With the projections fixed, the objective is a quadratic in x\mathbf x whose Hessian LL is the matrix of L1. LL does not depend on x\mathbf x or on the projections, and in 2D or 3D it is the same for each coordinate, so a step solves two (or three) systems with one factor. Pinned vertices are removed from the unknowns, and their terms move to the right side. The paper uses a sparse Cholesky factor; the code uses a dense one, which is fine for the small meshes of the tests.

Why it descends. Write the objective as g(x)=min⁡ph(x,p)g(\mathbf x) = \min_{\mathbf p} h(\mathbf x, \mathbf p). The local step minimizes hh over p\mathbf p and the global step minimizes it over x\mathbf x, so each step can only lower hh, and g(xk+1)≤h(xk+1,pk)≤h(xk,pk)=g(xk)g(\mathbf x_{k+1}) \le h(\mathbf x_{k+1}, \mathbf p_k) \le h(\mathbf x_k, \mathbf p_k) = g(\mathbf x_k). This is block coordinate descent on the pair (x,p)(\mathbf x, \mathbf p).

Example

One triangle by hand. The rest triangle is (0,0)(0, 0), (1,0)(1, 0), (0,1)(0, 1) with the first two corners pinned. With density 6 the free corner has mass m=1m = 1, and with k=200k = 200 the weight is w=200⋅0.5=100w = 200 \cdot 0.5 = 100. Take Δt=0.1\Delta t = 0.1, no gravity, and the free corner at rest at (0,1.5)(0, 1.5). The deformation gradient is F=diag⁡(1,1.5)F = \operatorname{diag}(1, 1.5), so the local step gives R=IR = I. The global step for the free corner is (m/Δt2+w)x=(m/Δt2)y+w(0,1)(m/\Delta t^2 + w)\mathbf x = (m/\Delta t^2)\mathbf y + w(0, 1), that is 200 x=100 (0,1.5)+100 (0,1)200\,\mathbf x = 100\,(0, 1.5) + 100\,(0, 1), so x=(0,1.25)\mathbf x = (0, 1.25) with the velocity (0,−2.5)(0, -2.5). Now F=diag⁡(1,1.25)F = \operatorname{diag}(1, 1.25) and R=IR = I again, so further iterations change nothing. Backward Euler for the energy w2(s−1)2\frac{w}{2}(s - 1)^2 of the height ss gives 100(s−1.5)+100(s−1)=0100(s - 1.5) + 100(s - 1) = 0, the same s=1.25s = 1.25.

Convergence on a cantilever (measured). A plate of 6×36 \times 3 vertices with spacing 0.1 m and density 1 is pinned at its left column and falls under gravity with Δt=1/30\Delta t = 1/30 s. After 5 steps, one step is solved with 2000 iterations to get the reference value g∗g^*, and the gap g(xK)−g∗g(\mathbf x_K) - g^* after KK iterations is

stiffness kk K=1K = 1 2 5 10 20 50 100 200
10 3.6×10−43.6 \times 10^{-4} 9.6×10−59.6 \times 10^{-5} 3.7×10−63.7 \times 10^{-6} 2.9×10−82.9 \times 10^{-8} 2.1×10−122.1 \times 10^{-12} 0 0 0
100 1.5×10−31.5 \times 10^{-3} 3.7×10−43.7 \times 10^{-4} 1.6×10−51.6 \times 10^{-5} 2.4×10−62.4 \times 10^{-6} 1.5×10−71.5 \times 10^{-7} 3.2×10−113.2 \times 10^{-11} 4×10−174 \times 10^{-17} 2×10−172 \times 10^{-17}
1000 1.5×10−21.5 \times 10^{-2} 4.7×10−34.7 \times 10^{-3} 4.5×10−44.5 \times 10^{-4} 1.2×10−41.2 \times 10^{-4} 4.1×10−54.1 \times 10^{-5} 1.9×10−61.9 \times 10^{-6} 1.2×10−81.2 \times 10^{-8} 4.6×10−134.6 \times 10^{-13}

The gap falls at every iteration, as the descent argument requires. It falls more slowly for the stiffer plate, where the elastic part dominates M/Δt2M/\Delta t^2 in LL. After 2000 iterations the largest entry of the gradient is below 2×10−132 \times 10^{-13} in all three rows.

Correctness

The claims are proved in proofs/correctness.md.

  1. Exact subproblems (proved). The local step gives the best rotation of each element, and the global step gives the unique minimizer for fixed rotations, because LL is symmetric positive definite.
  2. Constant matrix (proved). LL depends only on the masses, Δt\Delta t, the weights and the rest shape, and it is the same for every coordinate.
  3. Monotone descent (proved). Each iteration lowers the objective by at least 12∣xk−xk+1∣L2\frac12|\mathbf x_k - \mathbf x_{k+1}|_L^2. The test checks that the objective never increases over 30 iterations for a soft and a stiff plate.
  4. Limit points are backward Euler steps (proved). The steps go to zero, and every limit point where all best rotations are unique has zero gradient, so it satisfies the backward Euler equation. The test reaches a gradient below 10−1010^{-10} after 300 iterations, and it checks the gradient formula against central differences.
  5. Linear momentum (proved). With no pins and no gravity, every global step keeps ∑mvxv=∑mvyv\sum m_v \mathbf x_v = \sum m_v \mathbf y_v, so a step keeps the linear momentum for any number of iterations.
  6. Rigid motions (proved). The energy is zero on rotated and moved copies of the rest shape, and an unstressed body falls by symplectic Euler, −5.3955-5.3955 m after 10 steps of 0.10.1 s.

The test also checks the Cholesky solver against an LU solve. The rate of convergence is not proved; the table measures it.

Proof: Local and global steps of projective dynamics never increase the backward Euler objective, and their limit points are backward Euler stepsfull

We use the notation of the page, for 2D triangles. The free vertices have positions x\mathbf x, the lumped mass matrix is MM (positive diagonal), and pinned vertices are fixed. Triangle tt has the weight wt>0w_t > 0 and a deformation gradient Ft(x)=∑v∈txvgt,vTF_t(\mathbf x) = \sum_{v \in t} \mathbf x_v \mathbf g_{t,v}^T that is linear in x\mathbf x, with constant vectors gt,v\mathbf g_{t,v} from the rest shape that satisfy ∑v∈tgt,v=0\sum_{v \in t} \mathbf g_{t,v} = 0. Let R=SO(2)\mathcal R = SO(2) and define the surrogate

h(x,R)=12Δt2(x−y)TM(x−y)+∑twt2∣Ft(x)−Rt∣F2,R=(Rt)t∈RT,h(\mathbf x, R) = \frac{1}{2\Delta t^2}(\mathbf x - \mathbf y)^T M (\mathbf x - \mathbf y) + \sum_t \frac{w_t}{2} |F_t(\mathbf x) - R_t|_F^2, \qquad R = (R_t)_t \in \mathcal R^{T},

and the objective g(x)=min⁡Rh(x,R)g(\mathbf x) = \min_{R} h(\mathbf x, R), which is 12Δt2∣x−y∣M2+∑twt2dist⁡(Ft(x),R)2\frac{1}{2\Delta t^2}|\mathbf x - \mathbf y|_M^2 + \sum_t \frac{w_t}{2}\operatorname{dist}(F_t(\mathbf x), \mathcal R)^2. Line L5 sets RtR_t to the rotation factor of FtF_t, and line L6 solves Lx=b(R)L\mathbf x = \mathbf b(R).

The two steps solve their subproblems exactly

Lemma 1 (local step). For fixed x\mathbf x, h(x,⋅)h(\mathbf x, \cdot) is minimized by taking each RtR_t to be the rotation that maximizes tr⁡(RtTFt)\operatorname{tr}(R_t^T F_t). In 2D this is R(θ)R(\theta) with θ=atan2⁡(f10−f01,f00+f11)\theta = \operatorname{atan2}(f_{10} - f_{01}, f_{00} + f_{11}), unique when (f00+f11,f10−f01)≠0(f_{00} + f_{11}, f_{10} - f_{01}) \ne 0.

Proof. The terms are independent, and ∣F−R∣F2=∣F∣F2+∣R∣F2−2tr⁡(RTF)=∣F∣F2+2−2tr⁡(RTF)|F - R|_F^2 = |F|_F^2 + |R|_F^2 - 2\operatorname{tr}(R^T F) = |F|_F^2 + 2 - 2\operatorname{tr}(R^T F) for a rotation. With R=R(θ)R = R(\theta), tr⁡(RTF)=cos⁡θ(f00+f11)+sin⁡θ(f10−f01)\operatorname{tr}(R^T F) = \cos\theta(f_{00} + f_{11}) + \sin\theta(f_{10} - f_{01}), a sinusoid in θ\theta whose maximum is at the stated angle. □\square

Lemma 2 (global step). For fixed RR, h(⋅,R)h(\cdot, R) is a strictly convex quadratic in each coordinate d∈{x,y}d \in \{x, y\} separately, with the Hessian

L=MΔt2+∑twt∑u,v∈t(gt,u⋅gt,v) euevTL = \frac{M}{\Delta t^2} + \sum_t w_t \sum_{u, v \in t} (\mathbf g_{t,u} \cdot \mathbf g_{t,v})\, \mathbf e_u \mathbf e_v^T

restricted to the free vertices. LL is the same for both coordinates, symmetric positive definite and independent of x\mathbf x, RR and y\mathbf y. The unique minimizer solves Lxd=bdL\mathbf x_d = \mathbf b_d with bd=MΔt2yd+∑twt∑v∈t(Rt)d,:gt,v ev−(terms of pinned vertices)\mathbf b_d = \frac{M}{\Delta t^2}\mathbf y_d + \sum_t w_t \sum_{v \in t}(R_t)_{d,:}\mathbf g_{t,v}\,\mathbf e_v - (\text{terms of pinned vertices}).

Proof. Row dd of FtF_t is ∑vxv,dgt,vT\sum_v x_{v,d}\mathbf g_{t,v}^T, so ∣Ft−Rt∣F2=∑d∣∑vxv,dgt,v−(Rt)d,:T∣2|F_t - R_t|_F^2 = \sum_d |\sum_v x_{v,d}\mathbf g_{t,v} - (R_t)_{d,:}^T|^2, and the coordinates do not mix. Expanding the square, the quadratic part in xd\mathbf x_d is 12xdTLxd\frac12\mathbf x_d^T L\mathbf x_d with LL as stated, and the linear part gives bd\mathbf b_d; the pinned vertices enter only through known constants. LL depends only on MM, Δt\Delta t, the wtw_t and the rest shape. The first part is positive definite and the second is a sum of Gram matrices, which are positive semidefinite, so LL is positive definite and the minimizer is unique. □\square

So the code factors L=CCTL = CC^T once (line L1) and every global step costs two triangular solves per coordinate.

Descent and convergence

Theorem 3 (monotone descent). Let xk+1\mathbf x_{k+1} come from xk\mathbf x_k by one local and one global step. Then

g(xk)−g(xk+1)≥12(xk−xk+1)TL(xk−xk+1)≥0,g(\mathbf x_k) - g(\mathbf x_{k+1}) \ge \tfrac12 (\mathbf x_k - \mathbf x_{k+1})^T L (\mathbf x_k - \mathbf x_{k+1}) \ge 0,

with LL applied to each coordinate.

Proof. Let RkR^k be the result of the local step at xk\mathbf x_k. Then g(xk)=h(xk,Rk)g(\mathbf x_k) = h(\mathbf x_k, R^k) by Lemma 1. The function q=h(⋅,Rk)q = h(\cdot, R^k) is quadratic with Hessian LL and minimizer xk+1\mathbf x_{k+1} (Lemma 2), so q(xk)−q(xk+1)=12(xk−xk+1)TL(xk−xk+1)q(\mathbf x_k) - q(\mathbf x_{k+1}) = \frac12(\mathbf x_k - \mathbf x_{k+1})^T L(\mathbf x_k - \mathbf x_{k+1}). Finally g(xk+1)=min⁡Rh(xk+1,R)≤h(xk+1,Rk)=q(xk+1)g(\mathbf x_{k+1}) = \min_R h(\mathbf x_{k+1}, R) \le h(\mathbf x_{k+1}, R^k) = q(\mathbf x_{k+1}). □\square

Lemma 4 (gradient). At a point where every Ft(x)F_t(\mathbf x) has a unique best rotation Rt∗R_t^*, gg is differentiable and ∇g(x)=∇xh(x,R∗)\nabla g(\mathbf x) = \nabla_{\mathbf x} h(\mathbf x, R^*), that is, for a free vertex vv, ∇vg=mvΔt2(xv−yv)+∑t∋vwt(Ft−Rt∗)gt,v\nabla_v g = \frac{m_v}{\Delta t^2}(\mathbf x_v - \mathbf y_v) + \sum_{t \ni v} w_t (F_t - R_t^*)\mathbf g_{t,v}.

Proof. dist⁡(F,R)2=∣F∣F2+2−2max⁡θtr⁡(R(θ)TF)\operatorname{dist}(F, \mathcal R)^2 = |F|_F^2 + 2 - 2\max_\theta \operatorname{tr}(R(\theta)^T F), and max⁡θtr⁡(R(θ)TF)=∣(f00+f11,f10−f01)∣\max_\theta \operatorname{tr}(R(\theta)^T F) = |(f_{00} + f_{11}, f_{10} - f_{01})| is the norm of a linear function of FF, which is differentiable where it is not zero, with derivative R∗R^* (the unit vector of that linear function, mapped back). So ∇F12dist⁡(F,R)2=F−R∗\nabla_F \frac12\operatorname{dist}(F, \mathcal R)^2 = F - R^*, and the chain rule with ∂Ft/∂xv=(⋅) gt,vT\partial F_t / \partial \mathbf x_v = (\cdot)\,\mathbf g_{t,v}^T gives the formula. □\square

Theorem 5 (limit points are backward Euler steps). The sequence xk\mathbf x_k is bounded, g(xk)g(\mathbf x_k) converges, ∣xk+1−xk∣→0|\mathbf x_{k+1} - \mathbf x_k| \to 0, and every limit point xˉ\bar{\mathbf x} at which all best rotations are unique satisfies ∇g(xˉ)=0\nabla g(\bar{\mathbf x}) = 0, the backward Euler equation M(xˉ−y)/Δt2=−∇Ψ(xˉ)M(\bar{\mathbf x} - \mathbf y)/\Delta t^2 = -\nabla\Psi(\bar{\mathbf x}) for Ψ=∑twt2dist⁡(Ft,R)2\Psi = \sum_t \frac{w_t}{2}\operatorname{dist}(F_t, \mathcal R)^2.

Proof. By Theorem 3, g(xk)≤g(x0)g(\mathbf x_k) \le g(\mathbf x_0), and g(x)≥12Δt2∣x−y∣M2g(\mathbf x) \ge \frac{1}{2\Delta t^2}|\mathbf x - \mathbf y|_M^2, so the iterates stay in a bounded set. gg is bounded below by 0 and nonincreasing along the sequence, so it converges, and summing Theorem 3 gives ∑k∣xk−xk+1∣L2≤2g(x0)<∞\sum_k |\mathbf x_k - \mathbf x_{k+1}|_L^2 \le 2g(\mathbf x_0) < \infty, so the steps go to zero. Let xkj→xˉ\mathbf x_{k_j} \to \bar{\mathbf x}. Write the iteration as xk+1=T(xk)=L−1b(R∗(xk))\mathbf x_{k+1} = T(\mathbf x_k) = L^{-1}\mathbf b(R^*(\mathbf x_k)). Where the best rotations are unique, R∗R^* is continuous (Lemma 1: it is the unit vector of a nonzero linear function of FF), so TT is continuous at xˉ\bar{\mathbf x}, and T(xˉ)=lim⁡T(xkj)=lim⁡xkj+1=xˉT(\bar{\mathbf x}) = \lim T(\mathbf x_{k_j}) = \lim \mathbf x_{k_j + 1} = \bar{\mathbf x} because the steps go to zero. A fixed point of TT minimizes h(⋅,R∗(xˉ))h(\cdot, R^*(\bar{\mathbf x})), so ∇xh(xˉ,R∗(xˉ))=0\nabla_{\mathbf x} h(\bar{\mathbf x}, R^*(\bar{\mathbf x})) = 0, which is ∇g(xˉ)=0\nabla g(\bar{\mathbf x}) = 0 by Lemma 4. □\square

The theorem says nothing about the rate. It is linear at best, and it is slow when the triangles are stiff compared with M/Δt2M/\Delta t^2; the page measures this.

Invariances

Lemma 6. Ψ\Psi is zero exactly on the configurations that are rotated and moved copies of the rest shape on each triangle; in particular Ψ(QX+t)=0\Psi(Q\mathbf X + \mathbf t) = 0 for a rotation QQ and a translation t\mathbf t of the whole rest mesh X\mathbf X.

Proof. dist⁡(Ft,R)=0\operatorname{dist}(F_t, \mathcal R) = 0 if and only if FtF_t is a rotation. For x=QX+t\mathbf x = Q\mathbf X + \mathbf t, Ft=Q∑vXvgt,vT+t∑vgt,vT=Q⋅I+0=QF_t = Q\sum_v \mathbf X_v\mathbf g_{t,v}^T + \mathbf t\sum_v\mathbf g_{t,v}^T = Q \cdot I + 0 = Q, since the rest shape has Ft=IF_t = I. □\square

Theorem 7 (linear momentum). With no pinned vertices and no gravity, every global step satisfies ∑vmvxv=∑vmvyv\sum_v m_v \mathbf x_v = \sum_v m_v \mathbf y_v, so the step keeps ∑vmvvv\sum_v m_v \mathbf v_v for any number of iterations.

Proof. Let 1\mathbf 1 be the vector of ones. Since ∑u∈tgt,u=0\sum_{u \in t}\mathbf g_{t,u} = 0, the second part of LL has 1T(⋅)=0\mathbf 1^T(\cdot) = 0, so 1TL=1TM/Δt2\mathbf 1^T L = \mathbf 1^T M/\Delta t^2. Also 1Tbd=1TMyd/Δt2+∑twt(Rt)d,:∑v∈tgt,v=1TMyd/Δt2\mathbf 1^T \mathbf b_d = \mathbf 1^T M\mathbf y_d/\Delta t^2 + \sum_t w_t (R_t)_{d,:}\sum_{v \in t}\mathbf g_{t,v} = \mathbf 1^T M\mathbf y_d/\Delta t^2. Multiplying Lxd=bdL\mathbf x_d = \mathbf b_d by 1T\mathbf 1^T gives 1TMxd=1TMyd\mathbf 1^T M\mathbf x_d = \mathbf 1^T M\mathbf y_d. With y=xn+Δtvn\mathbf y = \mathbf x^n + \Delta t\mathbf v^n and line L7, ∑mvvvn+1=∑mv(xv−xvn)/Δt=∑mvvvn\sum m_v\mathbf v^{n+1}_v = \sum m_v(\mathbf x_v - \mathbf x^n_v)/\Delta t = \sum m_v \mathbf v^n_v. □\square

Lemma 8 (free fall). If the body is at its rest shape up to a rigid motion, has no pins and all vertices have the same velocity u\mathbf u, one step under gravity moves every vertex to yv=xv+Δtu+Δt2g\mathbf y_v = \mathbf x_v + \Delta t\mathbf u + \Delta t^2\mathbf g.

Proof. y\mathbf y is a translated copy of x\mathbf x, so Ψ(y)=0\Psi(\mathbf y) = 0 and g(y)=0g(\mathbf y) = 0, the smallest possible value. The iteration starts at y\mathbf y (line L3), and by Theorem 3 with g≥0g \ge 0 every step satisfies ∣xk−xk+1∣L2≤0|\mathbf x_k - \mathbf x_{k+1}|_L^2 \le 0, so it stays at y\mathbf y. □\square

Cost

Lemma 9. With nn free vertices and TT triangles, the setup costs O(T+n3)O(T + n^3) for the dense factorization of the code, each local step Θ(T)\Theta(T), and each global step Θ(T+n2)\Theta(T + n^2) for the dense triangular solves.

Proof. Assembling LL costs O(1)O(1) per triangle; the dense Cholesky factorization costs Θ(n3)\Theta(n^3). A local step does one 2×22 \times 2 polar decomposition per triangle. A global step assembles b\mathbf b in Θ(T)\Theta(T) plus the pinned terms and does two forward and two backward substitutions with a dense n×nn \times n factor. □\square

With a sparse factorization, as in the paper, the cost of a global step is linear in the number of nonzeros of the factor, which depends on the mesh and on the ordering.

Complexity

The setup assembles LL in O(T)O(T) and factors it once. With a sparse factor that has zz nonzeros, an iteration costs Θ(T)\Theta(T) for the local step, which is parallel over the elements, and Θ(T+z)\Theta(T + z) for the right side and the triangular solves. A step with KK iterations costs O(K(T+z))O(K(T + z)). The factor must be recomputed when Δt\Delta t, a weight or the set of pinned vertices changes. The dense factor of the code costs O(n3)O(n^3) once and O(n2)O(n^2) per solve.

Properties

  • Robust. The objective never increases, so a step cannot blow up, at any Δt\Delta t. With few iterations the answer is a partial minimization, which adds damping; it is stable, not accurate.
  • Linear convergence. The method is a fixed point iteration that converges slowly for stiff materials, as the table shows. It is often stopped after a fixed number of iterations.
  • Restricted energies. Only energies that are squared distances to constraint sets fit the form. General hyperelastic materials such as neo-Hookean need other methods.
  • Constant matrix. Changing contacts, pins or stiffness need a new factorization, or must be handled in the local step.
  • Momentum. Linear momentum is kept for every iteration count without pins and external forces.

Variants and improvements

  • Fast mass-spring. Fast mass-spring is the special case of springs, where the local step projects each spring onto its rest length.
  • Chebyshev acceleration. Wang (2015) accelerated the iterations with a Chebyshev semi-iterative method, which also works for position based solvers.
  • Quasi-Newton. Liu, Bouaziz and Kavan (2017) viewed the global matrix as an approximate Hessian and used it as the starting matrix of a quasi-Newton method, which allows general hyperelastic materials.
  • ADMM. Overby, Brown, Li and Narain (2017) wrote the same split as ADMM, which also allows general materials and hard constraints.
  • Vertex block descent. Vertex block descent minimizes the same objective by Newton steps on single vertices, with no global solve.
  • Shape matching. The local step is the same best rotation as in meshless shape matching and corotational FEM.

When to use it

Use projective dynamics for interactive simulation of cloth, soft bodies and rods with as-rigid-as-possible type energies, when the mesh and the pins do not change often and robustness at large steps matters more than an exact solution. It is a good fit when a sparse Cholesky factor can be reused for many steps.

Do not use it for general nonlinear materials or for very stiff objects where many iterations would be needed; use Newton based optimization time integration then. Contact that changes every step does not fit the constant matrix well.

Pitfalls

  • Few iterations look soft. With a fixed small iteration count, stiff materials look softer and more damped than the material law says.
  • Changing the step size. LL contains M/Δt2M/\Delta t^2, so a new Δt\Delta t needs a new factor.
  • Pins in the matrix. Remove pinned vertices from the unknowns, or add stiff attachment constraints; both change LL and need a new factor when the pins change.
  • Degenerate elements. A triangle with zero rest area has no deformation gradient. A deformation gradient with f00+f11=f10−f01=0f_{00} + f_{11} = f_{10} - f_{01} = 0 has no unique best rotation.
  • Stopping test. Monotone descent does not bound the error after a given number of iterations. Use the gradient norm if accuracy matters.

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
projective_dynamics.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projective-dynamics/. The authors are listed in prov/NBWGAF.jsonl.

"""Projective dynamics (Bouaziz, Martin, Liu, Kavan and Pauly 2014) for 2D triangles.

Each triangle t has the energy (w_t / 2) |F_t - R|^2 with the smallest value
over rotations R, where F_t is the deformation gradient and w_t = k * area_t.
The constraint set is the set of rotations, and the projection of F onto it is
the rotation factor of its polar decomposition (the ARAP strain energy). One
backward Euler step minimizes

    g(x) = 1/(2 dt^2) |x - y|_M^2 + sum_t (w_t / 2) dist(F_t(x), SO(2))^2,

with y = x_n + dt v_n + dt^2 g_grav. The method alternates a local step, which
fixes x and projects each F_t onto SO(2), and a global step, which fixes the
rotations and solves a linear system whose matrix
L = M / dt^2 + sum_t w_t G_t G_t^T does not change. The matrix is the same for
the x and the y coordinates, and it is factored once by Cholesky. Pinned
vertices are removed from the unknowns.

The 2D mesh is a version of the 3D tetrahedral setting of the paper.
"""

import math

from anim import polar

GRAVITY = (0.0, -9.81)


def cholesky(a):
    """Lower triangular C with a = C C^T for a symmetric positive definite matrix."""
    n = len(a)
    c = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = a[j][j] - sum(c[j][k] * c[j][k] for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        c[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            c[i][j] = (a[i][j] - sum(c[i][k] * c[j][k] for k in range(j))) / c[j][j]
    return c


def cholesky_solve(c, b):
    n = len(c)
    z = [0.0] * n
    for i in range(n):
        z[i] = (b[i] - sum(c[i][k] * z[k] for k in range(i))) / c[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (z[i] - sum(c[k][i] * x[k] for k in range(i + 1, n))) / c[i][i]
    return x


class Mesh:
    """Rest positions X, triangles, lumped masses, pinned vertices and per triangle data."""

    def __init__(self, rest, tris, stiffness, density=1.0, pinned=()):
        self.rest = [tuple(p) for p in rest]
        self.tris = [tuple(t) for t in tris]
        self.pinned = set(pinned)
        n = len(rest)
        self.mass = [0.0] * n
        self.grads = []
        self.weights = []
        for a, b, c in self.tris:
            d = [[rest[b][0] - rest[a][0], rest[c][0] - rest[a][0]], [rest[b][1] - rest[a][1], rest[c][1] - rest[a][1]]]
            det = d[0][0] * d[1][1] - d[0][1] * d[1][0]
            area = 0.5 * abs(det)
            inv = [[d[1][1] / det, -d[0][1] / det], [-d[1][0] / det, d[0][0] / det]]
            # F = Ds Dm^-1 = sum_v x_v G[v]^T with the rows G[v] of the 3 by 2 matrix below
            g1, g2 = inv[0], inv[1]
            g0 = [-g1[0] - g2[0], -g1[1] - g2[1]]
            self.grads.append((g0, g1, g2))
            self.weights.append(stiffness * area)
            for v in (a, b, c):
                self.mass[v] += density * area / 3.0
        self.free = [i for i in range(n) if i not in self.pinned]

    def deformation_gradient(self, x, t):
        f = [[0.0, 0.0], [0.0, 0.0]]
        for v, g in zip(self.tris[t], self.grads[t]):
            for d in range(2):
                f[d][0] += x[v][d] * g[0]
                f[d][1] += x[v][d] * g[1]
        return f


def grid(nx, ny, spacing, stiffness, density=1.0, pin_left=True):
    """A rectangle of nx by ny vertices, two triangles per cell, pinned on the left column."""
    rest = [(i * spacing, j * spacing) for j in range(ny) for i in range(nx)]
    tris = []
    for j in range(ny - 1):
        for i in range(nx - 1):
            a, b, c, d = j * nx + i, j * nx + i + 1, (j + 1) * nx + i + 1, (j + 1) * nx + i
            tris += [(a, b, c), (a, c, d)]
    pinned = [j * nx for j in range(ny)] if pin_left else []
    return Mesh(rest, tris, stiffness, density, pinned)


def energy(mesh, x):
    """sum_t (w_t / 2) |F_t - R_t|^2 with R_t the best rotation."""
    e = 0.0
    for t, w in enumerate(mesh.weights):
        f = mesh.deformation_gradient(x, t)
        r, _ = polar(f)
        e += 0.5 * w * sum((f[i][j] - r[i][j]) ** 2 for i in range(2) for j in range(2))
    return e


def objective(mesh, x, y, dt):
    g = energy(mesh, x)
    for i in mesh.free:
        g += mesh.mass[i] / (2.0 * dt * dt) * ((x[i][0] - y[i][0]) ** 2 + (x[i][1] - y[i][1]) ** 2)
    return g


def gradient(mesh, x, y, dt):
    """The gradient of the objective on all vertices (zero rows for pinned ones)."""
    grad = [[0.0, 0.0] for _ in x]
    for i in mesh.free:
        for d in range(2):
            grad[i][d] = mesh.mass[i] / (dt * dt) * (x[i][d] - y[i][d])
    for t, w in enumerate(mesh.weights):
        f = mesh.deformation_gradient(x, t)
        r, _ = polar(f)
        for v, g in zip(mesh.tris[t], mesh.grads[t]):
            if v in mesh.pinned:
                continue
            for d in range(2):
                grad[v][d] += w * ((f[d][0] - r[d][0]) * g[0] + (f[d][1] - r[d][1]) * g[1])
    return grad


class Solver:
    """The constant system matrix on the free vertices, factored once."""

    def __init__(self, mesh, dt):
        self.mesh, self.dt = mesh, dt
        col = {v: k for k, v in enumerate(mesh.free)}
        self.col = col
        nf = len(mesh.free)
        a = [[0.0] * nf for _ in range(nf)]
        for v in mesh.free:
            a[col[v]][col[v]] += mesh.mass[v] / (dt * dt)
        self.coupling = []  # (free row, pinned vertex, value): moved to the right side
        for t, w in enumerate(mesh.weights):
            tri, gs = mesh.tris[t], mesh.grads[t]
            for va, ga in zip(tri, gs):
                for vb, gb in zip(tri, gs):
                    val = w * (ga[0] * gb[0] + ga[1] * gb[1])
                    if va in col and vb in col:
                        a[col[va]][col[vb]] += val
                    elif va in col:
                        self.coupling.append((col[va], vb, val))
        self.matrix = a
        self.factor = cholesky(a)  # @line L1

    def global_step(self, x, y, rotations):
        mesh, dt, col = self.mesh, self.dt, self.col
        out = [tuple(p) for p in x]
        rhs = [[mesh.mass[v] / (dt * dt) * y[v][d] for v in mesh.free] for d in range(2)]
        for t, w in enumerate(mesh.weights):
            r = rotations[t]
            for v, g in zip(mesh.tris[t], mesh.grads[t]):
                if v in col:
                    for d in range(2):
                        rhs[d][col[v]] += w * (r[d][0] * g[0] + r[d][1] * g[1])
        for row, vp, val in self.coupling:
            for d in range(2):
                rhs[d][row] -= val * x[vp][d]
        sol = [cholesky_solve(self.factor, rhs[d]) for d in range(2)]  # @line L6
        for v in mesh.free:
            out[v] = (sol[0][col[v]], sol[1][col[v]])
        return out


def local_step(mesh, x):
    return [polar(mesh.deformation_gradient(x, t))[0] for t in range(len(mesh.tris))]


def pd_step(solver, x, v, iterations, gravity=GRAVITY, history=None):
    """One backward Euler step by projective dynamics. Return (x, v)."""
    mesh, dt = solver.mesh, solver.dt
    y = predict(mesh, x, v, dt, gravity)  # @line L2
    z = list(y)  # @line L3
    for _ in range(iterations):  # @line L4
        rots = local_step(mesh, z)  # @line L5
        z = solver.global_step(z, y, rots)
        if history is not None:
            history.append(objective(mesh, z, y, dt))
    v_new = [((p[0] - q[0]) / dt, (p[1] - q[1]) / dt) for p, q in zip(z, x)]  # @line L7
    return z, v_new


def predict(mesh, 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 mesh.pinned else tuple(p) for i, (p, u) in enumerate(zip(x, v))]
test_projective_dynamics.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projective-dynamics/. The authors are listed in prov/NBWGAF.jsonl.

"""Tests of projective dynamics: the solver parts, monotone descent, convergence and momentum."""

import math
import random

from anim import num_grad, rot2, solve
import projective_dynamics as pd


def test_example_one_triangle():
    mesh = pd.Mesh([(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], [(0, 1, 2)], 200.0, density=6.0, pinned=[0, 1])
    assert abs(mesh.mass[2] - 1.0) < 1e-15 and abs(mesh.weights[0] - 100.0) < 1e-12
    solver = pd.Solver(mesh, 0.1)
    x = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.5)]
    x1, v1 = pd.pd_step(solver, x, [(0.0, 0.0)] * 3, 1, gravity=(0.0, 0.0))
    assert math.dist(x1[2], (0.0, 1.25)) < 1e-14 and math.dist(v1[2], (0.0, -2.5)) < 1e-12
    x2, _ = pd.pd_step(solver, x, [(0.0, 0.0)] * 3, 5, gravity=(0.0, 0.0))
    assert math.dist(x2[2], (0.0, 1.25)) < 1e-14


def test_cholesky_against_lu():
    rng = random.Random(31)
    for n in (1, 3, 8):
        b = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
        a = [[sum(b[i][k] * b[j][k] for k in range(n)) + (n if i == j else 0.0) for j in range(n)] for i in range(n)]
        rhs = [rng.uniform(-1, 1) for _ in range(n)]
        c = pd.cholesky(a)
        assert max(abs(sum(c[i][k] * c[j][k] for k in range(n)) - a[i][j]) for i in range(n) for j in range(n)) < 1e-12
        x1 = pd.cholesky_solve(c, rhs)
        x2 = solve(a, rhs)
        assert max(abs(p - q) for p, q in zip(x1, x2)) < 1e-12


def test_energy_is_zero_exactly_on_rigid_motions():
    rng = random.Random(32)
    mesh = pd.grid(4, 3, 0.1, 50.0, pin_left=False)
    assert energy_close(mesh, mesh.rest, 0.0)
    for _ in range(10):
        r = rot2(rng.uniform(-math.pi, math.pi))
        t = (rng.uniform(-1, 1), rng.uniform(-1, 1))
        x = [(r[0][0] * p[0] + r[0][1] * p[1] + t[0], r[1][0] * p[0] + r[1][1] * p[1] + t[1]) for p in mesh.rest]
        assert energy_close(mesh, x, 0.0)
    stretched = [(1.1 * p[0], p[1]) for p in mesh.rest]
    total_area = 0.3 * 0.2
    assert energy_close(mesh, stretched, 0.5 * 50.0 * total_area * 0.01)


def energy_close(mesh, x, want):
    return abs(pd.energy(mesh, x) - want) < 1e-12


def test_gradient_against_num_grad():
    rng = random.Random(33)
    mesh = pd.grid(3, 3, 0.2, 80.0, density=2.0)
    x = [(p[0] + rng.uniform(-0.03, 0.03), p[1] + rng.uniform(-0.03, 0.03)) if i in mesh.free else p
         for i, p in enumerate(mesh.rest)]
    y = [(p[0] + 0.01, p[1] - 0.02) for p in x]
    dt = 0.05
    grad = pd.gradient(mesh, x, y, dt)
    flat = [c for p in x for c in p]

    def f(z):
        return pd.objective(mesh, [(z[2 * i], z[2 * i + 1]) for i in range(len(x))], y, dt)

    ng = num_grad(f, flat)
    for i in mesh.free:
        for d in range(2):
            assert abs(ng[2 * i + d] - grad[i][d]) < 1e-6 * max(1.0, abs(grad[i][d]))


def test_objective_never_increases():
    for k in (10.0, 1000.0):
        mesh = pd.grid(5, 3, 0.1, k)
        solver = pd.Solver(mesh, 1.0 / 30.0)
        x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
        for _ in range(4):
            hist = []
            y = pd.predict(mesh, x, v, solver.dt)
            start = pd.objective(mesh, y, y, solver.dt)
            x, v = pd.pd_step(solver, x, v, 30, history=hist)
            seq = [start] + hist
            assert all(b <= a + 1e-12 * abs(a) for a, b in zip(seq, seq[1:]))


def test_converges_to_a_backward_euler_step():
    mesh = pd.grid(5, 3, 0.1, 100.0)
    solver = pd.Solver(mesh, 1.0 / 30.0)
    x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
    x, v = pd.pd_step(solver, x, v, 20)
    y = pd.predict(mesh, x, v, solver.dt)
    z, _ = pd.pd_step(solver, x, v, 300)
    grad = pd.gradient(mesh, z, y, solver.dt)
    assert max(abs(c) for g in grad for c in g) < 1e-10
    z5, _ = pd.pd_step(solver, x, v, 5)
    grad5 = pd.gradient(mesh, z5, y, solver.dt)
    assert max(abs(c) for g in grad5 for c in g) > 1e-6


def test_linear_momentum_is_kept_at_every_iteration_count():
    rng = random.Random(34)
    mesh = pd.grid(4, 3, 0.1, 200.0, pin_left=False)
    solver = pd.Solver(mesh, 0.02)
    x = list(mesh.rest)
    v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in x]
    p0 = [sum(m * u[d] for m, u in zip(mesh.mass, v)) for d in range(2)]
    for it in (1, 2, 7):
        for _ in range(10):
            x, v = pd.pd_step(solver, x, v, it, gravity=(0.0, 0.0))
        p1 = [sum(m * u[d] for m, u in zip(mesh.mass, v)) for d in range(2)]
        assert max(abs(a - b) for a, b in zip(p0, p1)) < 1e-12


def test_free_fall_of_an_unstressed_body():
    mesh = pd.grid(3, 2, 0.1, 100.0, pin_left=False)
    solver = pd.Solver(mesh, 0.1)
    x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
    for _ in range(10):
        x, v = pd.pd_step(solver, x, v, 3)
    for p, q in zip(x, mesh.rest):
        assert abs(p[1] - q[1] + 5.3955) < 1e-10 and abs(p[0] - q[0]) < 1e-10

History

Liu, Bargteil, O'Brien and Kavan (2013) showed that the implicit Euler step of a mass-spring system can be solved by alternating spring projections and a solve with a constant matrix. Bouaziz, Martin, Liu, Kavan and Pauly (2014) generalized this to projective dynamics with many constraint types. Wang (2015) added Chebyshev acceleration, and Liu, Bouaziz and Kavan (2017) and Overby, Brown, Li and Narain (2017) extended the method to general materials with quasi-Newton and ADMM views.

References

  1. Sofien Bouaziz, Sebastian Martin, Tiantian Liu, Ladislav Kavan and Mark Pauly, Projective dynamics: fusing constraint projections for fast simulation, ACM Transactions on Graphics 33(4), article 154, 2014 (SIGGRAPH 2014), the whole paper (the variational implicit Euler step, the projective energies, the local and global solver and the constraint types)

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.iteration
  • a full proof of time.setup
  • a full proof of time.step
  • 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