Algorithm Search⌘K

Algorithmadvanced

Invertible finite elements

Also called diagonalized invertible FEM.

Compute stresses in the diagonal space of the SVD of the deformation gradient, with a modified model, so that inverted elements recover their shape.

Time
Θ(n + m) explicit_stepΘ(m) forces_per_step
Space
Θ(n + m) extra
Where
m = the number of elements; n = the number of nodes
Properties
deterministicnot exactiterative
Origin
Geoffrey Irving, Joseph Teran, Ronald Fedkiw, 2004

Invertible finite elements compute the elastic force of each element in a frame where its deformation is diagonal, so that the force stays finite and points back to the rest shape even when the element is flat or turned inside out. Each deformation gradient is written as F=UF^VTF = U\hat F V^T with rotations UU and VV and a diagonal F^\hat F whose smallest entry is negative when the element is inverted. The stress of an isotropic model is diagonal in this frame, P=UP^(F^)VTP = U\hat P(\hat F)V^T, and the model is changed below a compression threshold so that P^\hat P is defined for every F^\hat F. Irving, Teran and Fedkiw (2004) gave the method for tetrahedra, and the same steps work for triangles in 2D.

In plain words

In a simulation with many small triangles or tetrahedra, some elements get crushed flat or pushed through themselves. Many material models have no answer there: their energy goes to infinity, or their force pushes the element further inside out. This method first finds two turns, one before and one after the stretch, that make the stretch of the element a plain scaling along two or three axes. If the element is inside out, it marks this by making the smallest scaling negative. It then asks the material model only about these scalings, and it changes the model where the scaling gets very small, so that the push back stays finite. At last it turns the answer back into the world. So every element gets a sensible force, and a crushed element unfolds again.

The problem

The input is a mesh of triangles (in 2D) or tetrahedra (in 3D) with rest positions XX, current positions xx, and an isotropic hyperelastic model with the Lamé parameters μ\mu and λ\lambda. Each element has the rest edge matrix DmD_m with det⁡Dm>0\det D_m > 0, the current edge matrix DsD_s, F=DsDm−1F = D_s D_m^{-1}, and the rest area V0=det⁡Dm/2V_0 = \det D_m / 2. The output is the elastic force on every node.

The force must be finite and must push toward the rest shape for every xx, including elements with det⁡F≤0\det F \le 0. It must be rotation invariant, and where the element is not too compressed it must agree with the chosen model. A model such as the neo-Hookean model has the energy term −μlog⁡J-\mu\log J with J=det⁡FJ = \det F, which is undefined for J≤0J \le 0. The St. Venant-Kirchhoff model is defined there, but its force can keep an inverted element inverted.

This page gives the method in 2D. It uses two diagonal models: the corotated model P^i=2μ(σi−1)+λ(σ1+σ2−2)\hat P_i = 2\mu(\sigma_i - 1) + \lambda(\sigma_1 + \sigma_2 - 2), which the paper calls the rotated linear model, and the neo-Hookean model P^i=μσi−μ/σi+λlog⁡(σ1σ2)/σi\hat P_i = \mu\sigma_i - \mu/\sigma_i + \lambda\log(\sigma_1\sigma_2)/\sigma_i.

The algorithm

  1. INVERTIBLE-FORCES(x, c) ▷ D_m^(-1) and B_m = -V_0 D_m^(-T) precomputed per element, c > 0
  2. 1f ← 0 on every node
  3. 2for each element e with nodes a_0, a_1, a_2 do
  4. 3F ← D_s D_m^(-1)
  5. 4(U, σ, V) ← signed SVD of F with det U = det V = +1, σ_1 ≥ |σ_2|
  6. 5σ̃_i ← max(σ_i, c) for each i
  7. 6P̂ ← P̂(σ̃) + J(σ̃)(σ - σ̃) ▷ J is the Jacobian of P̂; the identity when σ̃ = σ
  8. 7P ← U diag(P̂) V^T
  9. 8G ← P B_m ▷ the forces on a_1 and a_2 as columns
  10. 9f_(a_k) ← f_(a_k) + G_k for k = 1, 2, and f_(a_0) ← f_(a_0) - G_1 - G_2
  11. return f

Line L4 is the key step. In 2D it has a closed form: with e=(F00+F11)/2e = (F_{00} + F_{11})/2, g=(F00−F11)/2g = (F_{00} - F_{11})/2, h=(F10+F01)/2h = (F_{10} + F_{01})/2 and k=(F10−F01)/2k = (F_{10} - F_{01})/2, set q=e2+k2q = \sqrt{e^2 + k^2}, r=g2+h2r = \sqrt{g^2 + h^2}, σ1=q+r\sigma_1 = q + r and σ2=q−r\sigma_2 = q - r. Then U=rot⁡(φ)U = \operatorname{rot}(\varphi) and V=rot⁡(−θ)V = \operatorname{rot}(-\theta) with φ+θ=atan2⁡(k,e)\varphi + \theta = \operatorname{atan2}(k, e) and φ−θ=atan2⁡(h,g)\varphi - \theta = \operatorname{atan2}(h, g). Since det⁡F=q2−r2\det F = q^2 - r^2, σ2\sigma_2 is negative exactly when the element is inverted. In 3D, Irving et al. take an SVD from the eigenvectors of FTFF^T F and then fix the signs: if det⁡V=−1\det V = -1 they negate a column of VV, and if det⁡U=−1\det U = -1 they negate the smallest entry of F^\hat F and its column of UU.

Lines L5 and L6 change the model below the threshold cc: they replace the stress by its first order Taylor expansion about the clamped point. The paper describes this choice as linearizing the model at a compression limit, or clamping the stress, and gives no value of cc; the value is a tuning choice. For the corotated model the stress is affine, so lines L5 and L6 change nothing. Line L8 is the force formula G=PBmG = P B_m of Section 4 of the paper. Any time integrator can use these forces; the test code uses symplectic Euler with velocity damping.

Example

Take one triangle with the rest nodes (0,0)(0, 0), (1,0)(1, 0) and (0,1)(0, 1) in m, E=1E = 1 Pa and ν=0.3\nu = 0.3, so μ=5/13\mu = 5/13 N/m and λ=15/26\lambda = 15/26 N/m, and c=0.3c = 0.3. The table uses the six-place values μ=0.384615\mu = 0.384615 N/m and λ=0.576923\lambda = 0.576923 N/m, as the tests do, so its last digits can differ from the exact values by a few units (the extended neo-Hookean P^2\hat P_2 at (0,0)(0, 0) is −9.117844-9.117844 with the exact μ\mu and λ\lambda). Nodes 0 and 1 stay in place, and node 2 moves down.

Node 2 at det⁡F\det F (σ1,σ2)(\sigma_1, \sigma_2) plain neo-Hookean P^2\hat P_2 extended neo-Hookean P^2\hat P_2 force on node 2, extended neo-Hookean (N) force on node 2, corotated (N)
(0,1)(0, 1) 1 (1,1)(1, 1) 0 0 (0,0)(0, 0) (0,0)(0, 0)
(0,0.5)(0, 0.5) 0.5 (1,0.5)(1, 0.5) −1.376708-1.376708 −1.376708-1.376708 (0,0.688354)(0, 0.688354) (0,0.336538)(0, 0.336538)
(0,0.1)(0, 0.1) 0.1 (1,0.1)(1, 0.1) −17.091831-17.091831 −7.239226-7.239226 (0,3.619613)(0, 3.619613) (0,0.605769)(0, 0.605769)
(0,0)(0, 0) 0 (1,0)(1, 0) undefined −9.117841-9.117841 (0,4.558920)(0, 4.558920) (0,0.673076)(0, 0.673076)
(0,−0.5)(0, -0.5) −0.5-0.5 (1,−0.5)(1, -0.5) undefined −18.510913-18.510913 (0,9.255456)(0, 9.255456) (0,1.009615)(0, 1.009615)
(0.3,−0.5)(0.3, -0.5) −0.5-0.5 (1.056401,−0.473305)(1.056401, -0.473305) undefined −17.631926-17.631926 (1.757483,8.040864)(1.757483, 8.040864) (0.292784,0.872589)(0.292784, 0.872589)

Above the threshold the extended and the plain stresses agree. Below it the plain neo-Hookean stress grows without bound and is undefined at and past the flat state, while the extended stress continues along a straight line. In every row the force on node 2 points up, so it unfolds the triangle, also when the triangle is flat or inverted. In the last row FF is not diagonal, and the signed SVD finds the rotations; the negative entry is still the one of smallest magnitude. That force also has a part along +x+x, because the diagonal frame is turned; the damped run of the test code still brings node 2 back to (0,1)(0, 1).

Correctness

The proof shows these facts, each a proved property.

  • Line L4 gives F=UF^VTF = U\hat F V^T with rotations UU, VV, σ1≥∣σ2∣\sigma_1 \ge |\sigma_2|, and σ2<0\sigma_2 < 0 exactly when det⁡F<0\det F < 0.
  • When σ1+σ2≠0\sigma_1 + \sigma_2 \ne 0, the stress of line L7 does not depend on which such SVD is used, so it is a function of FF. It is rotation equivariant: P(QFQ′)=QP(F)Q′P(QFQ') = Q P(F) Q' for rotations QQ and Q′Q', and it is zero at every rotation.
  • The extension of lines L5 and L6 is finite for every FF and has continuous first derivatives at σi=c\sigma_i = c.
  • For the corotated model, the force is the exact negative gradient of ∑eV0(μ∣F−R∣F2+λ2tr⁡(S−I)2)\sum_e V_0(\mu|F - R|_F^2 + \frac{\lambda}{2}\operatorname{tr}(S - I)^2) with R=UVTR = UV^T and S=VF^VTS = V\hat F V^T, for inverted elements too. In 2D this energy is μ(∣F∣F2−4q+2)+2λ(q−1)2\mu(|F|_F^2 - 4q + 2) + 2\lambda(q - 1)^2, smooth wherever q>0q > 0.
  • For the neo-Hookean model, the force is the exact negative gradient of the neo-Hookean energy while all σi≥c\sigma_i \ge c. Below cc the extended force is not the gradient of any energy.
  • The net force and the net torque of each element are zero for every diagonal P^\hat P, because FPT=UF^P^UTF P^T = U\hat F\hat P U^T is symmetric.

The key step is the sign rule of line L4: the rotations UU and VV carry no reflection, so the inversion shows up as a negative σ2\sigma_2, where the diagonal model can see it and push against it.

Proof: The signed SVD is valid, the diagonal stress is well defined and rotation equivariant, and the forces are the negative gradient of the energy where the model is not extendedfull

We use the notation of the page, in 2D. rot⁡(t)\operatorname{rot}(t) is the rotation by the angle tt, and Z=diag⁡(1,−1)Z = \operatorname{diag}(1, -1). For matrices, A:B=tr⁡(ATB)A : B = \operatorname{tr}(A^T B). An element has the rest edge matrix DmD_m with det⁡Dm>0\det D_m > 0, F=DsDm−1F = D_s D_m^{-1}, V0=det⁡Dm/2V_0 = \det D_m / 2 and Bm=−V0Dm−TB_m = -V_0 D_m^{-T}.

Step 1: line L4 gives a signed SVD

Write F=(abcd)F = \begin{pmatrix} a & b \\ c & d \end{pmatrix} and set e=(a+d)/2e = (a + d)/2, g=(a−d)/2g = (a - d)/2, h=(c+b)/2h = (c + b)/2 and k=(c−b)/2k = (c - b)/2. Then

F=(e−kke)+(ghh−g)=qrot⁡(a2)+rrot⁡(a1)Z,F = \begin{pmatrix} e & -k \\ k & e \end{pmatrix} + \begin{pmatrix} g & h \\ h & -g \end{pmatrix} = q\operatorname{rot}(a_2) + r\operatorname{rot}(a_1) Z,

with q=e2+k2q = \sqrt{e^2 + k^2}, a2=atan2⁡(k,e)a_2 = \operatorname{atan2}(k, e), r=g2+h2r = \sqrt{g^2 + h^2} and a1=atan2⁡(h,g)a_1 = \operatorname{atan2}(h, g). Put φ=(a2+a1)/2\varphi = (a_2 + a_1)/2, θ=(a2−a1)/2\theta = (a_2 - a_1)/2, σ1=q+r\sigma_1 = q + r and σ2=q−r\sigma_2 = q - r. Since diag⁡(σ1,σ2)=qI+rZ\operatorname{diag}(\sigma_1, \sigma_2) = qI + rZ and Zrot⁡(θ)=rot⁡(−θ)ZZ\operatorname{rot}(\theta) = \operatorname{rot}(-\theta) Z,

rot⁡(φ)diag⁡(σ1,σ2)rot⁡(θ)=qrot⁡(φ+θ)+rrot⁡(φ−θ)Z=F.\operatorname{rot}(\varphi)\operatorname{diag}(\sigma_1, \sigma_2)\operatorname{rot}(\theta) = q\operatorname{rot}(\varphi + \theta) + r\operatorname{rot}(\varphi - \theta) Z = F.

So F=UF^VTF = U\hat F V^T with U=rot⁡(φ)U = \operatorname{rot}(\varphi), V=rot⁡(−θ)V = \operatorname{rot}(-\theta) and F^=diag⁡(σ1,σ2)\hat F = \operatorname{diag}(\sigma_1, \sigma_2), and det⁡U=det⁡V=+1\det U = \det V = +1. As q,r≥0q, r \ge 0, σ1≥∣σ2∣\sigma_1 \ge |\sigma_2|. Also det⁡F=σ1σ2=q2−r2\det F = \sigma_1\sigma_2 = q^2 - r^2, so σ2<0\sigma_2 < 0 exactly when det⁡F<0\det F < 0, and then σ2\sigma_2 is the entry of smallest magnitude. □\square

Step 2: the stress of lines L5 to L7 does not depend on the choice of the SVD when q>0q > 0

Let F=U′F^′V′TF = U'\hat F' V'^T be any factorization with rotations U′=rot⁡(φ′)U' = \operatorname{rot}(\varphi'), V′=rot⁡(−θ′)V' = \operatorname{rot}(-\theta') and F^′=diag⁡(σ1′,σ2′)\hat F' = \operatorname{diag}(\sigma_1', \sigma_2'), σ1′≥∣σ2′∣\sigma_1' \ge |\sigma_2'|. By the identity of Step 1 it equals q′rot⁡(φ′+θ′)+r′rot⁡(φ′−θ′)Zq'\operatorname{rot}(\varphi' + \theta') + r'\operatorname{rot}(\varphi' - \theta') Z with q′=(σ1′+σ2′)/2≥0q' = (\sigma_1' + \sigma_2')/2 \ge 0 and r′=(σ1′−σ2′)/2≥0r' = (\sigma_1' - \sigma_2')/2 \ge 0. A matrix of the form (e−kke)\left(\begin{smallmatrix} e & -k \\ k & e \end{smallmatrix}\right) plus one of the form (ghh−g)\left(\begin{smallmatrix} g & h \\ h & -g \end{smallmatrix}\right) fixes both parts, because the two sets of matrices are complementary subspaces of the 2 by 2 matrices. So q′=qq' = q and r′=rr' = r, that is F^′=F^\hat F' = \hat F.

Now let q>0q > 0, and let P^\hat P be a map of (σ1,σ2)(\sigma_1, \sigma_2) to a diagonal matrix that is symmetric in its two arguments. If r>0r > 0, then φ′+θ′=a2\varphi' + \theta' = a_2 and φ′−θ′=a1\varphi' - \theta' = a_1 modulo 2π2\pi, so φ′=φ+πj\varphi' = \varphi + \pi j and θ′=θ+πl\theta' = \theta + \pi l with j≡l(mod2)j \equiv l \pmod 2. So U′=sUU' = sU and V′=sVV' = sV with the same sign s=±1s = \pm 1, and U′P^V′T=UP^VTU'\hat P V'^T = U\hat P V^T. If r=0r = 0, then F^=qI\hat F = qI, P^=pI\hat P = pI for one number pp by the symmetry, and U′P^V′T=p U′V′T=prot⁡(a2)=UP^VTU'\hat P V'^T = p\,U'V'^T = p\operatorname{rot}(a_2) = U\hat P V^T. So P=UP^(F^)VTP = U\hat P(\hat F)V^T is a function of FF alone on the set q>0q > 0. □\square

The set q=0q = 0 is the set of the matrices rR′ZrR'Z with a rotation R′R', where σ1=−σ2\sigma_1 = -\sigma_2. There UVTU V^T is not fixed by FF, and the stress of the models below is not well defined. It is a set of measure zero, which this proof leaves out.

Step 3: rest, rotation equivariance and isotropy

At a rotation F=QF = Q we have e2+k2=1e^2 + k^2 = 1 and g=h=0g = h = 0, so F^=I\hat F = I, and both models give P^(I)=0\hat P(I) = 0: no stress. For rotations QQ and Q′Q', QFQ′Q F Q' has the signed SVD (QU)F^(Q′TV)T(QU)\hat F (Q'^T V)^T, and q(QFQ′)=q(F)q(QFQ') = q(F) by Step 2. By Step 2, P(QFQ′)=QUP^VTQ′=QP(F)Q′P(QFQ') = Q U\hat P V^T Q' = Q P(F) Q'. This holds for every FF with q>0q > 0, inverted or not. □\square

Step 4: the extension below cc is C1C^1, and it is finite for every FF

Line L5 sets σ~i=max⁡(σi,c)\tilde\sigma_i = \max(\sigma_i, c) with c>0c > 0, and line L6 sets P^ext(σ)=P^(σ~)+J(σ~)(σ−σ~)\hat P^{ext}(\sigma) = \hat P(\tilde\sigma) + J(\tilde\sigma)(\sigma - \tilde\sigma), where JJ is the Jacobian of P^\hat P. The model is only evaluated at σ~i≥c>0\tilde\sigma_i \ge c > 0, so P^ext\hat P^{ext} is finite for every σ\sigma, including σ2≤0\sigma_2 \le 0. Where both σi≥c\sigma_i \ge c, σ~=σ\tilde\sigma = \sigma and P^ext=P^\hat P^{ext} = \hat P.

Let σi<c\sigma_i < c and σj≥c\sigma_j \ge c. Then σ~i=c\tilde\sigma_i = c is constant, so ∂P^ext/∂σi=J(σ~)ei\partial\hat P^{ext}/\partial\sigma_i = J(\tilde\sigma) e_i. For jj, σ~j=σj\tilde\sigma_j = \sigma_j, and ∂P^ext/∂σj=J(σ~)ej+(∂J/∂σj)(σ~)(σ−σ~)\partial\hat P^{ext}/\partial\sigma_j = J(\tilde\sigma) e_j + (\partial J/\partial\sigma_j)(\tilde\sigma)(\sigma - \tilde\sigma). As σi→c\sigma_i \to c the value tends to P^(σ)\hat P(\sigma) and both derivatives tend to J(σ)eiJ(\sigma)e_i and J(σ)ejJ(\sigma)e_j, the derivatives of P^\hat P from the other side. The same holds when both entries are below cc. So P^ext\hat P^{ext} and its first derivatives are continuous, given that P^\hat P is C2C^2 on σ1,σ2>0\sigma_1, \sigma_2 > 0, as the neo-Hookean P^\hat P is. For the corotated model, P^\hat P is affine in σ\sigma, so P^ext=P^\hat P^{ext} = \hat P for every cc. □\square

Step 5: the two models agree with their usual stresses

Neo-Hookean. For det⁡F>0\det F > 0 the usual stress is P=μ(F−F−T)+λlog⁡J F−TP = \mu(F - F^{-T}) + \lambda\log J\, F^{-T} with J=det⁡F=σ1σ2J = \det F = \sigma_1\sigma_2. With F=UF^VTF = U\hat F V^T, F−T=UF^−1VTF^{-T} = U\hat F^{-1}V^T, so P=U(μ(F^−F^−1)+λlog⁡J F^−1)VTP = U\bigl(\mu(\hat F - \hat F^{-1}) + \lambda\log J\,\hat F^{-1}\bigr)V^T. The diagonal entries are μσi−μ/σi+λlog⁡J/σi\mu\sigma_i - \mu/\sigma_i + \lambda\log J/\sigma_i, the P^\hat P of the page. So where both σi≥c\sigma_i \ge c, line L7 gives the usual neo-Hookean stress.

Corotated. Let R=UVTR = UV^T, a rotation, and S=VF^VTS = V\hat F V^T, symmetric, so F=RSF = RS. For det⁡F>0\det F > 0 this is the polar decomposition. Then ∣F−R∣F2=∣F^−I∣F2|F - R|_F^2 = |\hat F - I|_F^2 and tr⁡(S−I)=σ1+σ2−2\operatorname{tr}(S - I) = \sigma_1 + \sigma_2 - 2, so the energy Ψcr(F)=μ∣F−R∣F2+λ2tr⁡(S−I)2\Psi_{cr}(F) = \mu|F - R|_F^2 + \frac{\lambda}{2}\operatorname{tr}(S - I)^2 is Ψ^(σ)=μ∑i(σi−1)2+λ2(σ1+σ2−2)2\hat\Psi(\sigma) = \mu\sum_i(\sigma_i - 1)^2 + \frac{\lambda}{2}(\sigma_1 + \sigma_2 - 2)^2. In 2D, σ1+σ2=2q\sigma_1 + \sigma_2 = 2q and R=rot⁡(a2)R = \operatorname{rot}(a_2), so

Ψcr(F)=μ(∣F∣F2−4q+2)+2λ(q−1)2,\Psi_{cr}(F) = \mu\bigl(|F|_F^2 - 4q + 2\bigr) + 2\lambda(q - 1)^2,

a smooth function of FF on the whole set q>0q > 0, which contains inverted and flat elements. From q2=e2+k2q^2 = e^2 + k^2, dq=cos⁡a2 de+sin⁡a2 dkdq = \cos a_2\, de + \sin a_2\, dk, and R:dF=cos⁡a2(da+dd)+sin⁡a2(dc−db)=2 dqR : dF = \cos a_2 (da + dd) + \sin a_2 (dc - db) = 2\,dq. So

dΨcr=2μF:dF−2μR:dF+λ(2q−2) R:dF=(2μ(F−R)+λtr⁡(S−I)R):dF.d\Psi_{cr} = 2\mu F : dF - 2\mu R : dF + \lambda(2q - 2)\, R : dF = \bigl(2\mu(F - R) + \lambda\operatorname{tr}(S - I) R\bigr) : dF.

This gradient is U(2μ(F^−I)+λtr⁡(F^−I)I)VTU\bigl(2\mu(\hat F - I) + \lambda\operatorname{tr}(\hat F - I) I\bigr)V^T, which is what line L7 gives with the corotated P^\hat P. □\square

Step 6: lines L8 and L9 give the negative gradient of the energy

Let P=∂Ψ/∂FP = \partial\Psi/\partial F at FF. Moving node a≥1a \ge 1 by δ\delta changes DsD_s by δeaT\delta e_a^T, so dF=δeaTDm−1dF = \delta e_a^T D_m^{-1} and d(V0Ψ)=V0P:δeaTDm−1=δT(V0PDm−T)ead(V_0\Psi) = V_0 P : \delta e_a^T D_m^{-1} = \delta^T(V_0 P D_m^{-T}) e_a. So the gradient for node aa is column aa of V0PDm−T=−PBmV_0 P D_m^{-T} = -P B_m, and line L8 sets G=PBmG = P B_m, the negative gradient. Moving node 0 by δ\delta is the same as moving the other nodes by −δ-\delta and then translating, which does not change FF, so its force is minus the sum of the others, as in line L9. Summing over the elements, lines L1 to L9 return −∇E-\nabla E for E=∑eV0Ψ(Fe)E = \sum_e V_0\Psi(F_e).

With Step 5 this holds for the corotated model at every configuration with q>0q > 0 in each element, inverted or not, and for the neo-Hookean model when both σi≥c\sigma_i \ge c in each element. Below cc the extended neo-Hookean stress is not the gradient of any function of σ\sigma: ∂P^1ext/∂σ2=λ/(σ1c)\partial\hat P^{ext}_1/\partial\sigma_2 = \lambda/(\sigma_1 c), but for σ2<c≤σ1\sigma_2 < c \le \sigma_1, ∂P^2ext/∂σ1=λ/(σ1c)−λ(σ2−c)/(σ1c2)\partial\hat P^{ext}_2/\partial\sigma_1 = \lambda/(\sigma_1 c) - \lambda(\sigma_2 - c)/(\sigma_1 c^2), and the two differ. So in that region the force is a finite, C1C^1 and rotation equivariant force, but not a conservative one. □\square

Step 7: zero net force and zero net torque

In each element the forces of line L9 sum to 0 by construction. The torque of the element is the skew part of ∑a≥1(xa−x0)faT=DsGT=DsBmTPT=−V0DsDm−1PT=−V0FPT\sum_{a \ge 1} (x_a - x_0) f_a^T = D_s G^T = D_s B_m^T P^T = -V_0 D_s D_m^{-1} P^T = -V_0 F P^T. With F=UF^VTF = U\hat F V^T and P=UP^VTP = U\hat P V^T, FPT=UF^P^UTF P^T = U\hat F\hat P U^T, which is symmetric because F^\hat F and P^\hat P are diagonal. So the torque is 0 for every diagonal P^\hat P, including the extension below cc. ■\blacksquare

Complexity

Each element costs a constant amount of work: a closed form SVD in 2D (in 3D, a 3 by 3 symmetric eigenproblem) and a few small matrix products. So the forces cost Θ(m)\Theta(m) for mm elements, and an explicit step costs Θ(n+m)\Theta(n + m) for nn nodes. Memory is Θ(n+m)\Theta(n + m): Dm−1D_m^{-1}, BmB_m and V0V_0 per element and the state per node. An implicit step also needs the stiffness, which in the diagonal frame splits into small blocks; see the variants.

Properties

  • Defined everywhere but a thin set. The force is finite for every configuration, and it is a function of FF wherever σ1+σ2≠0\sigma_1 + \sigma_2 \ne 0. This is proved.
  • Rotation invariant and isotropic. Rotating the world or the rest shape rotates the stress, and a rigid motion gives no force. This is proved.
  • Same as the model where it matters. For σi≥c\sigma_i \ge c the stress is the stress of the chosen model. This is proved.
  • Not conservative below cc. The extended neo-Hookean force is not the gradient of an energy in the extended region, so an energy based integrator or a line search on the energy does not apply there. This is proved.
  • Recovery. In the diagonal models of this page an inverted element is pushed back. That a mesh recovers from a given crushed state is a measurement: in the test code a triangle with node 2 at (0.3,−0.5)(0.3, -0.5), a flat triangle, and a 2 by 2 grid with three inverted triangles all return to rest under damped symplectic Euler.
  • A modelling choice. The change of the model below cc is a heuristic. It is not a law of physics, and Irving et al. note that most models lose accuracy long before inversion.

Variants and improvements

  • Other diagonal models. Any isotropic model in terms of the singular values can be used, for example a model with a cubic spline between threshold values, which the paper uses for a volumetric Buddha model, or the corotated model, which needs no change at all.
  • Definite stiffness. Teran, Sifakis, Irving and Fedkiw (2005) used the diagonal frame to split the stiffness of each element into small blocks and to make each block positive definite. This gives a robust implicit and quasistatic solver.
  • Inversion-safe energies. The stable neo-Hookean model of Smith, de Goes and Kim (2018) is defined for inverted elements without any threshold, so its force stays the gradient of an energy.
  • Anisotropy. For an anisotropic model P^\hat P is not diagonal. Section 6.1 of the paper rotates the anisotropic terms into the diagonal frame.
  • Other discretizations. Projective dynamics projects each element onto rotations, and the material point method often applies a signed SVD to the deformation gradient of each particle.

When to use it

Use invertible elements whenever a mesh can be crushed: collisions with thin objects, coarse meshes of soft tissue, or large time steps. Use it with the corotated model if speed matters more than the response at large strain, and with an extended neo-Hookean or a similar model for rubbery materials. If an implicit solver needs a smooth energy everywhere, use the stable neo-Hookean model instead of a model with a threshold. For cloth and shells in 3D the triangles cannot invert, and the plain finite element method is enough.

Pitfalls

  • Unsigned SVD. A standard SVD returns σi≥0\sigma_i \ge 0 and lets UU or VV be a reflection. With line L4 written that way, an inverted element looks like an uninverted one, and the force keeps it inverted. Both UU and VV must be rotations.
  • The wrong entry negated. In line L4 the negative entry must be the one of smallest magnitude. Negating another entry gives a valid factorization, but it asks for the long way back and gives large forces.
  • Evaluating the model at σ≤0\sigma \le 0. Without lines L5 and L6, the neo-Hookean P^\hat P takes log⁡\log of a negative number. A threshold of c=0c = 0 does not help, because the stress is infinite there.
  • A threshold that is too small. For a small cc the slope J(σ~)J(\tilde\sigma) of line L6 is very large, so the extended force is very stiff and an explicit step needs a much smaller Δt\Delta t.
  • Treating the extended force as conservative. Below cc the force of line L6 is not the gradient of an energy. A Newton solver that checks the energy, or an energy diagnostic, gives wrong results there.
  • Using UVTU V^T as the polar rotation of an inverted element. For det⁡F<0\det F < 0, R=UVTR = UV^T is a rotation but S=VF^VTS = V\hat F V^T is not positive definite, so it is not the polar decomposition of line L5 in corotational finite elements. The corotated force is correct with it; formulas that assume a positive SS are not.

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
invertible_finite_elements.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/invertible-finite-elements/. The authors are listed in prov/8XGGPB.jsonl.
"""Invertible finite elements (Irving, Teran and Fedkiw 2004) on 2D triangles.

For each element, F = D_s D_m^(-1) is written as F = U F_hat V^T with
rotations U and V (det U = det V = +1) and F_hat = diag(s1, s2), where
s1 >= |s2| and s2 < 0 exactly when det F < 0. So an inverted element has one
negative entry, the one of smallest magnitude.

The stress of an isotropic model is diagonal in this frame:
P = U P_hat(F_hat) V^T. The force on the nodes 1 and 2 is G = P B_m with
B_m = -V0 D_m^(-T), and node 0 gets minus the sum.

Two diagonal models are given:
- corotated: P_hat_i = 2 mu (s_i - 1) + lambda sum_j (s_j - 1), the gradient
  of mu sum (s_i - 1)^2 + (lambda / 2) (sum (s_i - 1))^2. It is defined for
  every F, inverted or not.
- neo-Hookean: P_hat_i = mu s_i - mu / s_i + lambda log(s1 s2) / s_i, the
  gradient of (mu / 2)(s1^2 + s2^2 - 2) - mu log J + (lambda / 2) (log J)^2.
  It is undefined for s_i <= 0. Below the threshold c > 0 the stress is
  replaced by its first order Taylor expansion about the clamped point
  max(s_i, c), which is continuous with a continuous first derivative at
  s_i = c. The threshold is a tuning value; the paper gives none.

Units: SI in 2D; mu and lambda in N/m, masses in kg.
"""

import math

from anim import det, inv, mul, rot2, transpose


def signed_svd2(f):
    """Return (U, (s1, s2), V) with F = U diag(s1, s2) V^T and det U = det V = +1.

    s1 >= |s2| >= 0 when det F >= 0, and s2 < 0 when det F < 0. Closed form:
    F = rot(phi) diag(s1, s2) rot(theta), so U = rot(phi) and V = rot(-theta).
    """
    a, b, c, d = f[0][0], f[0][1], f[1][0], f[1][1]
    e, g = 0.5 * (a + d), 0.5 * (a - d)
    h, k = 0.5 * (c + b), 0.5 * (c - b)
    q, r = math.hypot(e, k), math.hypot(g, h)
    a1, a2 = math.atan2(h, g), math.atan2(k, e)
    theta, phi = 0.5 * (a2 - a1), 0.5 * (a2 + a1)
    return rot2(phi), (q + r, q - r), rot2(-theta)


def corotated_diag(s, mu, lam):
    """Diagonal stress and its 2 by 2 Jacobian for the corotated model."""
    t = (s[0] - 1.0) + (s[1] - 1.0)
    p = [2.0 * mu * (s[i] - 1.0) + lam * t for i in range(2)]
    jac = [[2.0 * mu + lam, lam], [lam, 2.0 * mu + lam]]
    return p, jac


def neo_hookean_diag(s, mu, lam):
    """Diagonal stress and its Jacobian for the neo-Hookean model (s1, s2 > 0)."""
    lj = math.log(s[0] * s[1])
    p = [mu * s[i] - mu / s[i] + lam * lj / s[i] for i in range(2)]
    jac = [[0.0, 0.0], [0.0, 0.0]]
    for i in range(2):
        jac[i][i] = mu + (mu + lam * (1.0 - lj)) / (s[i] * s[i])
    jac[0][1] = jac[1][0] = lam / (s[0] * s[1])
    return p, jac


def diag_energy(s, mu, lam, model):
    """The energy density in terms of the signed singular values (no extrapolation)."""
    if model == "corotated":
        t = (s[0] - 1.0) + (s[1] - 1.0)
        return mu * ((s[0] - 1.0) ** 2 + (s[1] - 1.0) ** 2) + 0.5 * lam * t * t
    lj = math.log(s[0] * s[1])
    return 0.5 * mu * (s[0] ** 2 + s[1] ** 2 - 2.0) - mu * lj + 0.5 * lam * lj * lj


def diagonal_stress(s, mu, lam, model, c):
    """P_hat at the signed singular values s, linearized below the threshold c."""
    st = [max(s[0], c), max(s[1], c)]  # @line L5
    if model == "corotated":
        p, jac = corotated_diag(st, mu, lam)
    else:
        p, jac = neo_hookean_diag(st, mu, lam)
    return [p[i] + sum(jac[i][j] * (s[j] - st[j]) for j in range(2)) for i in range(2)]  # @line L6


class Mesh:
    """2D triangle mesh with rest data and lumped masses (density in kg/m^2)."""

    def __init__(self, rest, tris, mu, lam, density=1.0):
        self.rest = [tuple(map(float, p)) for p in rest]
        self.tris = [tuple(t) for t in tris]
        self.mu, self.lam = mu, lam
        self.dm_inv, self.bm, self.v0 = [], [], []
        self.mass = [0.0] * len(rest)
        for t in self.tris:
            dm = edge_matrix(self.rest, t)
            if det(dm) <= 0.0:
                raise ValueError("each triangle needs a positive rest orientation")
            di = inv(dm)
            v0 = 0.5 * det(dm)
            self.dm_inv.append(di)
            self.v0.append(v0)
            self.bm.append([[-v0 * x for x in row] for row in transpose(di)])
            for a in t:
                self.mass[a] += density * v0 / 3.0


def edge_matrix(p, t):
    a, b, c = p[t[0]], p[t[1]], p[t[2]]
    return [[b[0] - a[0], c[0] - a[0]], [b[1] - a[1], c[1] - a[1]]]


def invertible_forces(mesh, x, model="neo-hookean", c=0.3):
    """Return the elastic forces on all nodes, valid for inverted elements too.

    Cost O(m) for m elements: one closed form 2 by 2 SVD per element.
    """
    f = [[0.0, 0.0] for _ in x]  # @line L1
    for e, t in enumerate(mesh.tris):  # @line L2
        fmat = mul(edge_matrix(x, t), mesh.dm_inv[e])  # @line L3
        u, s, v = signed_svd2(fmat)  # @line L4
        ph = diagonal_stress(s, mesh.mu, mesh.lam, model, c)
        p = mul(mul(u, [[ph[0], 0.0], [0.0, ph[1]]]), transpose(v))  # @line L7
        g = mul(p, mesh.bm[e])  # @line L8
        for k in range(2):  # @line L9
            f[t[k + 1]][0] += g[0][k]
            f[t[k + 1]][1] += g[1][k]
            f[t[0]][0] -= g[0][k]
            f[t[0]][1] -= g[1][k]
    return [tuple(q) for q in f]


def total_energy(mesh, x, model):
    """Sum of V0 Psi(F) over the elements, from the signed singular values."""
    tot = 0.0
    for e, t in enumerate(mesh.tris):
        _, s, _ = signed_svd2(mul(edge_matrix(x, t), mesh.dm_inv[e]))
        tot += mesh.v0[e] * diag_energy(s, mesh.mu, mesh.lam, model)
    return tot


def direct_neo_hookean_stress(f, mu, lam):
    """P = mu (F - F^(-T)) + lambda log(J) F^(-T), the usual form for det F > 0."""
    fit = transpose(inv(f))
    lj = math.log(det(f))
    return [[mu * (f[i][j] - fit[i][j]) + lam * lj * fit[i][j] for j in range(2)] for i in range(2)]


def step(mesh, x, v, dt, model="neo-hookean", c=0.3, fixed=(), damping=0.0):
    """One symplectic Euler step with the velocity damping v <- (1 - damping dt) v.

    The damping is a tuning value, not part of the method. Cost O(n + m).
    """
    f = invertible_forces(mesh, x, model, c)
    fixed = set(fixed)
    xn, vn = [], []
    for i in range(len(x)):
        if i in fixed:
            xn.append(x[i])
            vn.append((0.0, 0.0))
            continue
        w = tuple((1.0 - damping * dt) * (v[i][k] + dt * f[i][k] / mesh.mass[i]) for k in range(2))
        vn.append(w)
        xn.append((x[i][0] + dt * w[0], x[i][1] + dt * w[1]))
    return xn, vn


def signed_area(x, t):
    return 0.5 * det(edge_matrix(x, t))
test_invertible_finite_elements.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/invertible-finite-elements/. The authors are listed in prov/8XGGPB.jsonl.
"""Tests of invertible finite elements on small 2D triangle meshes.

The signed SVD rebuilds F with rotations U and V and puts the negative entry
on the smallest singular value. The diagonal stress agrees with the usual
neo-Hookean stress for det F > 0, the forces are the negative gradient of
the energy (for inverted elements too with the corotated model), the stress
is rotation equivariant and C1 at the threshold, and inverted and flat
elements recover their rest shape.
"""

import math
import random

import pytest

import anim
from invertible_finite_elements import (Mesh, diagonal_stress, direct_neo_hookean_stress,
                                        invertible_forces, neo_hookean_diag, signed_area, signed_svd2,
                                        step, total_energy)

MU, LAM = 0.384615, 0.576923


def rand_f(rng, spread=1.5):
    return [[rng.uniform(-spread, spread) for _ in range(2)] for _ in range(2)]


def close(a, b, tol):
    return all(abs(a[i][j] - b[i][j]) <= tol for i in range(2) for j in range(2))


def stress(f, model, c=0.3):
    u, s, v = signed_svd2(f)
    ph = diagonal_stress(s, MU, LAM, model, c)
    return anim.mul(anim.mul(u, [[ph[0], 0.0], [0.0, ph[1]]]), anim.transpose(v))


def test_signed_svd():
    rng = random.Random(1)
    for _ in range(2000):
        f = rand_f(rng)
        u, s, v = signed_svd2(f)
        g = anim.mul(anim.mul(u, [[s[0], 0.0], [0.0, s[1]]]), anim.transpose(v))
        assert close(f, g, 1e-12)
        assert abs(anim.det(u) - 1.0) < 1e-12 and abs(anim.det(v) - 1.0) < 1e-12
        assert s[0] >= abs(s[1]) - 1e-12
        assert (s[1] < 0.0) == (anim.det(f) < 0.0)


def test_diagonal_stress_matches_direct_neo_hookean():
    rng = random.Random(2)
    for _ in range(300):
        r = anim.rot2(rng.uniform(-3, 3))
        q = anim.rot2(rng.uniform(-3, 3))
        f = anim.mul(anim.mul(r, [[rng.uniform(0.5, 2.0), 0.0], [0.0, rng.uniform(0.5, 2.0)]]), q)
        assert close(stress(f, "neo-hookean"), direct_neo_hookean_stress(f, MU, LAM), 1e-10)


def test_plain_neo_hookean_fails_when_inverted():
    with pytest.raises(ValueError):
        direct_neo_hookean_stress([[1.0, 0.0], [0.0, -0.5]], MU, LAM)


def flat(x):
    return [c for p in x for c in p]


def unflat(z):
    return [(z[2 * i], z[2 * i + 1]) for i in range(len(z) // 2)]


def check_gradient(mesh, x, model):
    f = invertible_forces(mesh, x, model, c=-1e9 if model == "corotated" else 0.3)
    g = anim.num_grad(lambda z: total_energy(mesh, unflat(z), model), flat(x))
    scale = max(abs(c) for c in g)
    for a, b in zip(flat(f), g):
        assert abs(a + b) <= 1e-6 * scale + 1e-9


def test_force_is_minus_gradient_corotated_with_inversion():
    rng = random.Random(3)
    mesh = Mesh([(0, 0), (1, 0), (0, 1), (1, 1)], [(0, 1, 3), (0, 3, 2)], MU, LAM)
    inverted = 0
    for _ in range(30):
        x = [(p[0] + rng.uniform(-0.8, 0.8), p[1] + rng.uniform(-0.8, 0.8)) for p in mesh.rest]
        inverted += any(signed_area(x, t) < 0 for t in mesh.tris)
        check_gradient(mesh, x, "corotated")
    assert inverted > 5


def test_force_is_minus_gradient_neo_hookean():
    rng = random.Random(4)
    mesh = Mesh([(0, 0), (1, 0), (0, 1), (1, 1)], [(0, 1, 3), (0, 3, 2)], MU, LAM)
    done = 0
    while done < 20:
        x = [(p[0] + rng.uniform(-0.2, 0.2), p[1] + rng.uniform(-0.2, 0.2)) for p in mesh.rest]
        sv = [signed_svd2(anim.mul([[x[t[1]][0] - x[t[0]][0], x[t[2]][0] - x[t[0]][0]],
                                    [x[t[1]][1] - x[t[0]][1], x[t[2]][1] - x[t[0]][1]]], mesh.dm_inv[e]))[1]
              for e, t in enumerate(mesh.tris)]
        if min(min(s) for s in sv) < 0.35:
            continue
        check_gradient(mesh, x, "neo-hookean")
        done += 1


def test_rotation_equivariance_including_inverted():
    rng = random.Random(5)
    for _ in range(300):
        f = rand_f(rng)
        r = anim.rot2(rng.uniform(-3, 3))
        q = anim.rot2(rng.uniform(-3, 3))
        for model in ("neo-hookean", "corotated"):
            p = stress(f, model)
            assert close(stress(anim.mul(r, f), model), anim.mul(r, p), 1e-9 * (1 + max(map(abs, flat(p)))))
            assert close(stress(anim.mul(f, q), model), anim.mul(p, q), 1e-9 * (1 + max(map(abs, flat(p)))))


def test_zero_stress_at_rest_and_rotation():
    for theta in (0.0, 1.0, 3.0):
        for model in ("neo-hookean", "corotated"):
            assert close(stress(anim.rot2(theta), model), [[0, 0], [0, 0]], 1e-12)


def test_extrapolation_is_c1_at_threshold():
    c, h = 0.3, 1e-7
    for s1 in (0.5, 1.0, 2.0):
        below = diagonal_stress((s1, c - h), MU, LAM, "neo-hookean", c)
        above = diagonal_stress((s1, c + h), MU, LAM, "neo-hookean", c)
        assert max(abs(a - b) for a, b in zip(below, above)) < 1e-5
        _, jac = neo_hookean_diag((s1, c), MU, LAM)
        d_below = [(diagonal_stress((s1, c - h), MU, LAM, "neo-hookean", c)[i]
                    - diagonal_stress((s1, c - 2 * h), MU, LAM, "neo-hookean", c)[i]) / h for i in range(2)]
        assert abs(d_below[1] - jac[1][1]) < 1e-4 * abs(jac[1][1])
        assert abs(d_below[0] - jac[0][1]) < 1e-4 * max(1.0, abs(jac[0][1]))


def run_recovery(mesh, x, model, fixed, steps=3000, dt=0.01):
    v = [(0.0, 0.0)] * len(x)
    for _ in range(steps):
        x, v = step(mesh, x, v, dt, model=model, c=0.3, fixed=fixed, damping=2.0)
    return x


@pytest.mark.parametrize("model", ["neo-hookean", "corotated"])
def test_inverted_triangle_recovers(model):
    mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
    x = [(0.0, 0.0), (1.0, 0.0), (0.3, -0.5)]
    assert signed_area(x, mesh.tris[0]) < 0
    x = run_recovery(mesh, x, model, fixed=[0, 1])
    assert abs(x[2][0]) < 1e-3 and abs(x[2][1] - 1.0) < 1e-3


@pytest.mark.parametrize("model", ["neo-hookean", "corotated"])
def test_flat_triangle_recovers(model):
    mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
    x = [(0.0, 0.0), (1.0, 0.0), (0.5, 0.0)]
    f = invertible_forces(mesh, x, model)
    assert all(math.isfinite(c) for p in f for c in p)
    assert f[2][1] > 0.0
    x = run_recovery(mesh, x, model, fixed=[0, 1])
    assert abs(x[2][0]) < 1e-3 and abs(x[2][1] - 1.0) < 1e-3


def test_crushed_mesh_recovers():
    rest = [(i * 0.5, j * 0.5) for j in range(3) for i in range(3)]
    tris = []
    for j in range(2):
        for i in range(2):
            a = 3 * j + i
            tris += [(a, a + 1, a + 4), (a, a + 4, a + 3)]
    mesh = Mesh(rest, tris, MU, LAM)
    x = list(rest)
    x[4] = (1.2, 0.1)
    x[7] = (0.5, -0.3)
    assert sum(signed_area(x, t) < 0 for t in tris) >= 3
    fixed = [0, 1, 2, 3, 5, 6, 8]
    x = run_recovery(mesh, x, "neo-hookean", fixed, steps=3000, dt=0.005)
    for i in (4, 7):
        assert math.dist(x[i], rest[i]) < 1e-3
    assert all(signed_area(x, t) > 0 for t in tris)

History

Before 2004, simulations in graphics used springs or an extra volume term to resist inversion, or turned to a linear model in a rotated frame, which works for inverted elements but limits the material. Irving, Teran and Fedkiw (2004) diagonalized FF with rotations, put the sign of the inversion on the smallest entry, and extended the constitutive models past the flat state with C0C^0 or C1C^1 continuity. Teran, Sifakis, Irving and Fedkiw (2005) used the same frame to build a positive definite stiffness for implicit and quasistatic solves. Sifakis and Barbič (2012) explain the corotated model and the stress from the singular values in their course notes, and Smith, de Goes and Kim (2018) designed an energy that needs no threshold.

References

  1. Geoffrey Irving, Joseph Teran and Ronald Fedkiw, Invertible finite elements for robust simulation of large deformation, ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2004), 131-140, Section 4 (force G = P B_m), Section 5 (diagonalization, Eq. 1, the sign rule for inverted elements), Section 6 and Figure 3 (the modified neo-Hookean and the rotated linear models)
  2. Joseph Teran, Eftychios Sifakis, Geoffrey Irving and Ronald Fedkiw, Robust quasistatic finite elements and flesh simulation, ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2005), the definiteness fix of the stiffness in the diagonal frame for implicit and quasistatic solves (general locator)
  3. Eftychios Sifakis and Jernej Barbič, FEM simulation of 3D deformable solids, a practitioner's guide to theory, discretization and model reduction, SIGGRAPH 2012 Courses, article 20, the isotropic stress from the singular values and the corotated model (general locator)

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.explicit_step
  • a full proof of time.forces_per_step
  • a full proof of space.extra
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
  • a scene preset for the example