Algorithm Search⌘K

Algorithmcore

Corotational finite elements

Also called corotated linear elasticity, stiffness warping.

Extract the rotation of each element by polar decomposition and apply linear elasticity in the rotated frame, which removes the ghost forces of linear FEM under rotation.

Time
Θ(m) forces_per_stepO(m + k (n + m)) implicit_step_with_cg
Space
Θ(n + m) extra
Where
k = the number of CG iterations per step; m = the number of elements; n = the number of nodes
Properties
deterministicnot exactiterative
Origin
Matthias Müller, Julie Dorsey, Leonard McMillan, Robert Jagnow, Barbara Cutler, 2002

Corotational finite elements simulate an elastic solid with the cheap linear stiffness matrix of each element, but measured in a frame that turns with the element. For each element the method finds the rotation RR of the deformation gradient F=RSF = R S, turns the nodes back by RTR^T, applies the linear force there, and turns the force forward by RR:

fe=−R Ke (RTxe−Xe).f_e = -R\, K_e\, (R^T x_e - X_e).

Plain linear elasticity sees a rotation as a strain and makes the body grow when it turns. The corotational force is zero for every rigid motion, and it is the exact negative gradient of the corotated energy μ∣F−R∣F2+λ2tr⁡(RTF−I)2\mu|F - R|_F^2 + \frac{\lambda}{2}\operatorname{tr}(R^T F - I)^2. The method is a standard way to simulate large rotations with small strains in games and interactive tools.

In plain words

Linear elasticity is simple and fast, because the force is a fixed matrix times the displacement. But it measures the displacement in a fixed frame. When a body turns, its points move a long way, so linear elasticity sees a large strain and pushes the body out of shape. The corotational method fixes this for each element. It finds how much the element has turned. It turns the element back, computes the linear force in the rest frame, and turns that force forward again. The turning no longer counts as strain, so only the real change of shape makes a force. The stiffness matrix of each element is computed once. At each step the method only needs the rotations.

The problem

The input is a mesh of linear elements: triangles in 2D or tetrahedra in 3D, with the rest positions XX of the nn nodes and the mm elements. The material has the Lamé parameters μ\mu and λ\lambda, from Young's modulus EE and Poisson's ratio ν\nu by μ=E/(2(1+ν))\mu = E / (2(1 + \nu)) and λ=Eν/((1+ν)(1−2ν))\lambda = E\nu / ((1 + \nu)(1 - 2\nu)). These are the 3D formulas, and in 2D they give the plane strain values; this page uses them in both cases. The state is the node positions xx and velocities vv, and the lumped node masses MM come from the rest areas (see mass lumping).

The output is the elastic force on every node and a time step. The force must be zero for every rigid motion x=QX+tx = QX + t with a rotation QQ, so that a turning body keeps its shape. For small strains it must agree with linear elasticity.

Each element has the edge matrix DmD_m with the rest edge vectors as columns, and DsD_s with the current ones, so F=DsDm−1F = D_s D_m^{-1} and the rest area or volume is V0=∣det⁡Dm∣/2V_0 = |\det D_m| / 2 in 2D and /6/ 6 in 3D. Its linear stiffness matrix KeK_e gives the force −Ke(xe−Xe)-K_e(x_e - X_e) of the energy V0(μ∣ε∣F2+λ2(tr⁡ε)2)V_0(\mu|\varepsilon|_F^2 + \frac{\lambda}{2}(\operatorname{tr}\varepsilon)^2) with the small strain ε=12(F+FT)−I\varepsilon = \frac12(F + F^T) - I. It is computed once, before the simulation.

The algorithm

  1. COROTATIONAL-STEP(x, v, Δt, f_ext) ▷ K_e, D_m^(-1), X_e precomputed per element
  2. 1f ← 0 on every node
  3. 2for each element e with nodes a_0, ..., a_d do
  4. 3D_s ← [x_(a_1) - x_(a_0), ..., x_(a_d) - x_(a_0)]
  5. 4F ← D_s D_m^(-1)
  6. 5R ← the rotation factor of the polar decomposition F = R S
  7. 6y_a ← R^T x_a for each node a of e ▷ turn the element back
  8. 7g ← -K_e (y - X_e) ▷ the linear force in the rest frame
  9. 8f_a ← f_a + R g_a for each node a of e ▷ turn the force forward
  10. 9K_w ← Σ_e R_e K_e R_e^T, assembled ▷ the warped stiffness
  11. 10solve (M + Δt² K_w) v' = M v + Δt (f + f_ext)
  12. 11x' ← x + Δt v'
  13. return x', v'

Lines L1 to L8 compute the forces. Line L5 uses the polar decomposition with det⁡R=+1\det R = +1; in 2D it has the closed form R=rot⁡(θ)R = \operatorname{rot}(\theta) with θ=atan2⁡(F10−F01,F00+F11)\theta = \operatorname{atan2}(F_{10} - F_{01}, F_{00} + F_{11}). Lines L6 to L8 apply the precomputed linear stiffness in the frame of the element. Lines L9 to L11 are one linearized backward Euler step, as in Müller et al. (2002): the force at the end of the step is approximated by f−Δt Kwv′f - \Delta t\, K_w v'. Fixed nodes get v′=0v' = 0 by replacing their rows of the system. The explicit variant replaces lines L9 to L11 by a symplectic Euler step, v′=v+ΔtM−1(f+fext)v' = v + \Delta t M^{-1}(f + f_{ext}) and then x′=x+Δtv′x' = x + \Delta t v'.

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 μ=0.384615\mu = 0.384615 N/m and λ=0.576923\lambda = 0.576923 N/m, and V0=0.5V_0 = 0.5 m². Node 0 stays at the origin.

State FF RR Linear force on node 1 (N) Corotational force on node 1 (N)
rest II II (0,0)(0, 0) (0,0)(0, 0)
turned by 90 degrees rot⁡(π/2)\operatorname{rot}(\pi/2) rot⁡(π/2)\operatorname{rot}(\pi/2) (0.961538,0)(0.961538, 0) (0,0)(0, 0)
stretched by 1.2 along xx, then turned by 90 degrees rot⁡(π/2)diag⁡(1.2,1)\operatorname{rot}(\pi/2)\operatorname{diag}(1.2, 1) rot⁡(π/2)\operatorname{rot}(\pi/2) (0.961538,−0.038462)(0.961538, -0.038462) (0,−0.134615)(0, -0.134615)

In the turned state, node 1 is at (0,1)(0, 1). Linear elasticity sees the strain ε=−I\varepsilon = -I and pushes node 1 sideways with 0.96 N, so the triangle grows. The corotational force is zero. In the stretched state, node 1 is at (0,1.2)(0, 1.2), and the corotational force (0,−0.134615)(0, -0.134615) pulls it back toward node 0 along the stretched edge. It is the linear force of the unturned stretch, −V0Plin(diag⁡(1.2,1))-V_0 P_{lin}(\operatorname{diag}(1.2, 1)) in its first column, turned by 90 degrees. The element energy is V0(μ⋅0.04+λ2⋅0.04)=0.013462V_0(\mu \cdot 0.04 + \frac{\lambda}{2} \cdot 0.04) = 0.013462 J.

Correctness

The statement: for det⁡F>0\det F > 0, lines L2 to L8 return f=−∇Ecr(x)f = -\nabla E_{cr}(x), the negative gradient of Ecr=∑eV0Ψcr(Fe)E_{cr} = \sum_e V_0 \Psi_{cr}(F_e) with

Ψcr(F)=μ∣F−R∣F2+λ2tr⁡(RTF−I)2,Pcr=∂Ψcr∂F=2μ(F−R)+λtr⁡(RTF−I) R.\Psi_{cr}(F) = \mu|F - R|_F^2 + \tfrac{\lambda}{2}\operatorname{tr}(R^T F - I)^2, \qquad P_{cr} = \frac{\partial \Psi_{cr}}{\partial F} = 2\mu(F - R) + \lambda\operatorname{tr}(R^T F - I)\, R.

The key step: turning the element back gives the deformation gradient RTF=SR^T F = S, which is symmetric, so the linear stress there is 2μ(S−I)+λtr⁡(S−I)I2\mu(S - I) + \lambda\operatorname{tr}(S - I) I, and turning it forward gives PcrP_{cr}. The derivative of RR drops out of ∂Ψcr/∂F\partial\Psi_{cr}/\partial F, because tr⁡(dRTF)=−tr⁡(WS)=0\operatorname{tr}(dR^T F) = -\operatorname{tr}(WS) = 0 for the skew matrix W=RTdRW = R^T dR. So the force is exact, it is zero for rigid motions, and the net force and torque of each element are zero.

The stiffness KwK_w of line L9 leaves out the derivative of RR. It equals the true Hessian of EcrE_{cr} at a turned rest shape, but not at a stretched and turned shape; in 2D the missing part of the stress change is (μ+λ)tr⁡(S−I) dR(\mu + \lambda)\operatorname{tr}(S - I)\, dR. So line L10 is an approximate Newton step, not the exact linearization of backward Euler. The proof gives every step.

Proof: The corotational force is the exact gradient of the corotated energy, and the warped stiffness is exact only at a rotated rest shapefull

We use the notation of the page. An element has d+1d + 1 nodes in dd dimensions (d=2d = 2 for triangles, d=3d = 3 for tetrahedra). DmD_m and DsD_s hold the rest and current edge vectors as columns, F=DsDm−1F = D_s D_m^{-1}, and V0V_0 is the rest area or volume. For matrices, A:B=tr⁡(ATB)A : B = \operatorname{tr}(A^T B) and ∣A∣F2=A:A|A|_F^2 = A : A. We assume det⁡F>0\det F > 0. Then FF has a unique polar decomposition F=RSF = R S with R∈SO(d)R \in SO(d) and SS symmetric positive definite, and RR and SS are smooth functions of FF.

The linear energy density is Ψlin(F)=μ∣ε∣F2+λ2(tr⁡ε)2\Psi_{lin}(F) = \mu|\varepsilon|_F^2 + \frac{\lambda}{2}(\operatorname{tr}\varepsilon)^2 with ε=12(F+FT)−I\varepsilon = \frac12(F + F^T) - I. Its stress is Plin(F)=2με+λ(tr⁡ε)IP_{lin}(F) = 2\mu\varepsilon + \lambda(\operatorname{tr}\varepsilon) I. The corotated energy density is Ψ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, where S=RTFS = R^T F.

Step 1: the linear force of an element is −Ke(y−X)-K_e (y - X)

The linear element force at the node positions yy is flin(y)=−V0Plin(F(y))Dm−Tf_{lin}(y) = -V_0 P_{lin}(F(y)) D_m^{-T} for the nodes 1,…,d1, \dots, d, and minus their sum for node 0. F(y)F(y) is affine in yy with F(X)=IF(X) = I, and PlinP_{lin} is affine in FF with Plin(I)=0P_{lin}(I) = 0. So flinf_{lin} is a linear function of the displacement y−Xy - X. A linear map is fixed by its values on the unit vectors. Line L7 uses the matrix KeK_e whose column kk is −flin(X+ek)-f_{lin}(X + e_k), so flin(y)=−Ke(y−X)f_{lin}(y) = -K_e (y - X) for every yy. □\square

Step 2: lines L5 to L8 compute −V0PcrDm−T-V_0 P_{cr} D_m^{-T}

Line L6 sets ya=RTxay_a = R^T x_a. The edge matrix of yy is RTDsR^T D_s, so F(y)=RTF=SF(y) = R^T F = S. SS is symmetric, so ε(S)=S−I\varepsilon(S) = S - I and Plin(S)=2μ(S−I)+λtr⁡(S−I)IP_{lin}(S) = 2\mu(S - I) + \lambda\operatorname{tr}(S - I) I. By Step 1, line L7 gives g=flin(y)=−V0Plin(S)Dm−Tg = f_{lin}(y) = -V_0 P_{lin}(S) D_m^{-T} on the nodes 1,…,d1, \dots, d, and minus their sum on node 0. Line L8 multiplies each nodal vector by RR, which commutes with the sum, so the force on the nodes 1,…,d1, \dots, d is −V0RPlin(S)Dm−T-V_0 R P_{lin}(S) D_m^{-T}. Now RPlin(S)=2μ(RS−R)+λtr⁡(S−I)R=2μ(F−R)+λtr⁡(S−I)RR P_{lin}(S) = 2\mu(RS - R) + \lambda\operatorname{tr}(S - I) R = 2\mu(F - R) + \lambda\operatorname{tr}(S - I) R. Call this matrix PcrP_{cr}. □\square

Step 3: Pcr=∂Ψcr/∂FP_{cr} = \partial\Psi_{cr} / \partial F

Expand ∣F−R∣F2=∣F∣F2−2tr⁡(RTF)+d|F - R|_F^2 = |F|_F^2 - 2\operatorname{tr}(R^T F) + d, because RTR=IR^T R = I. So Ψcr=μ(∣F∣F2−2tr⁡S+d)+λ2(tr⁡S−d)2\Psi_{cr} = \mu(|F|_F^2 - 2\operatorname{tr} S + d) + \frac{\lambda}{2}(\operatorname{tr} S - d)^2, and it is enough to show d(tr⁡S)=R:dFd(\operatorname{tr} S) = R : dF.

Differentiate tr⁡S=tr⁡(RTF)\operatorname{tr} S = \operatorname{tr}(R^T F): d(tr⁡S)=tr⁡(dRTF)+tr⁡(RTdF)d(\operatorname{tr} S) = \operatorname{tr}(dR^T F) + \operatorname{tr}(R^T dF). R(t)R(t) stays in SO(d)SO(d), so dR=RWdR = R W with WW skew symmetric. Then tr⁡(dRTF)=tr⁡(WTRTRS)=−tr⁡(WS)=0\operatorname{tr}(dR^T F) = \operatorname{tr}(W^T R^T R S) = -\operatorname{tr}(W S) = 0, because the trace of a product of a skew symmetric and a symmetric matrix is 0. So d(tr⁡S)=R:dFd(\operatorname{tr} S) = R : dF, and

dΨcr=2μF:dF−2μR:dF+λtr⁡(S−I) R:dF=Pcr:dF.□d\Psi_{cr} = 2\mu F : dF - 2\mu R : dF + \lambda\operatorname{tr}(S - I)\, R : dF = P_{cr} : dF. \qquad \square

Step 4: the force is the negative gradient of the energy

The element energy is V0Ψcr(F)V_0\Psi_{cr}(F), and F=DsDm−1F = D_s D_m^{-1} with DsD_s linear in the nodes. 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Ψcr)=V0Pcr:δeaTDm−1=δT(V0PcrDm−T)ead(V_0\Psi_{cr}) = V_0 P_{cr} : \delta e_a^T D_m^{-1} = \delta^T (V_0 P_{cr} D_m^{-T}) e_a. So the gradient for node aa is column aa of V0PcrDm−TV_0 P_{cr} D_m^{-T}. Moving node 0 by δ\delta is the same as moving all the other nodes by −δ-\delta and then translating the element, which does not change FF, so its gradient is minus the sum of the others. With Step 2, the force of lines L2 to L8 on every node is minus the gradient of V0ΨcrV_0\Psi_{cr}. Summing over elements, the loop of lines L2 to L8 gives −∇Ecr-\nabla E_{cr} for Ecr=∑eV0Ψcr(Fe)E_{cr} = \sum_e V_0\Psi_{cr}(F_e). □\square

Step 5: rest, rigid motions, net force and torque

If x=QX+tx = Q X + t with Q∈SO(d)Q \in SO(d), then Ds=QDmD_s = Q D_m and F=QF = Q, so R=QR = Q, S=IS = I and Pcr=0P_{cr} = 0: no force. For any rotation QQ, QF=(QR)SQF = (QR) S is the polar decomposition of QFQF, so Ψcr(QF)=Ψcr(F)\Psi_{cr}(QF) = \Psi_{cr}(F). In each element the nodal forces sum to 0 by construction, so the total force is 0. The torque of one element is the skew part of ∑a(xa−x0)faT\sum_a (x_a - x_0) f_a^T, and this sum is −V0DsDm−1PcrT=−V0FPcrT-V_0 D_s D_m^{-1} P_{cr}^T = -V_0 F P_{cr}^T. Here FPcrT=2μ(FFT−FRT)+λtr⁡(S−I)FRTF P_{cr}^T = 2\mu(F F^T - F R^T) + \lambda\operatorname{tr}(S - I) F R^T and FRT=RSRTF R^T = R S R^T, so it is symmetric and the torque is 0. □\square

Step 6: the warped stiffness

The warped stiffness RKeRTR K_e R^T of line L9 maps a change dxdx to the force change −V0 dPw Dm−T-V_0\, dP_w\, D_m^{-T} with dPw=R (2μsym⁡(RTdF)+λtr⁡(RTdF)I)dP_w = R\,(2\mu\operatorname{sym}(R^T dF) + \lambda\operatorname{tr}(R^T dF) I), by Step 1 applied to RTdxR^T dx. The exact change is dPcr=2μ(dF−dR)+λ(R:dF)R+λtr⁡(S−I) dRdP_{cr} = 2\mu(dF - dR) + \lambda (R : dF) R + \lambda\operatorname{tr}(S - I)\, dR. Write dR=RWdR = RW and dF=dR S+R dSdF = dR\, S + R\, dS with dSdS symmetric. Then 2Rsym⁡(RTdF)=dF+R dFTR=R(WS+dS)+R(−SW+dS)2 R\operatorname{sym}(R^T dF) = dF + R\, dF^T R = R(WS + dS) + R(-SW + dS), and tr⁡(RTdF)=R:dF\operatorname{tr}(R^T dF) = R : dF. Subtracting,

dPcr−dPw=R (μ (W(S−I)+(S−I)W)+λtr⁡(S−I) W).dP_{cr} - dP_w = R\,\bigl(\mu\,(W(S - I) + (S - I)W) + \lambda\operatorname{tr}(S - I)\, W\bigr).

At a rotated rest shape S=IS = I, so the difference is 0 and the warped stiffness is the exact Hessian there. In 2D every skew WW is ωJ\omega J with J=(0−110)J = \bigl(\begin{smallmatrix}0 & -1\\ 1 & 0\end{smallmatrix}\bigr), and JE+EJ=(tr⁡E)JJE + EJ = (\operatorname{tr}E) J for a symmetric EE, so the difference is (μ+λ)tr⁡(S−I) dR(\mu + \lambda)\operatorname{tr}(S - I)\, dR. It is not 0 when the element is stretched with tr⁡(S−I)≠0\operatorname{tr}(S - I) \ne 0 and the change dxdx turns the element. So the stiffness of lines L9 and L10 is exact at rest and only approximate elsewhere. ■\blacksquare

Complexity

The force loop does a constant amount of work per element: one small polar decomposition (closed form in 2D, a few Newton iterations in 3D) and one product with a 3(d+1)3(d + 1) by 3(d+1)3(d + 1) matrix, at most 12 by 12. So the forces cost Θ(m)\Theta(m) per step. Assembling KwK_w costs Θ(m)\Theta(m) and gives a sparse matrix with O(n+m)O(n + m) nonzeros. Solving line L10 with kk iterations of the conjugate gradient method costs O(k(n+m))O(k(n + m)); the matrix M+Δt2KwM + \Delta t^2 K_w is symmetric positive definite when KwK_w is positive semidefinite, which holds because each KeK_e is. The value of kk for a given tolerance is a measurement, and it grows with the stiffness and the mesh size. The test code uses a dense Gaussian elimination, O(n3)O(n^3), which is fine for its small meshes. Memory is Θ(n+m)\Theta(n + m): the precomputed KeK_e, Dm−1D_m^{-1} and V0V_0 per element, and the state per node.

Properties

  • Rotation invariant. Ψcr(QF)=Ψcr(F)\Psi_{cr}(QF) = \Psi_{cr}(F) for every rotation QQ, and the force is zero for every rigid motion. This is proved.
  • Exact force. The force is the gradient of an energy, so with no damping and an energy conserving integrator the total energy is a conserved quantity of the semi-discrete system. This is proved.
  • Momentum. The net force and the net torque of the internal forces are zero. Under symplectic Euler with no external force, the total momentum and angular momentum stay constant up to rounding. This is proved.
  • Linear for small strain. Near the rest shape Ψcr\Psi_{cr} agrees with linear elasticity to second order.
  • Inexact stiffness. KwK_w omits the derivative of RR, so the implicit step is not an exact Newton step. It is symmetric and positive semidefinite, which keeps the linear solve simple.
  • Not invertible. At det⁡F=0\det F = 0 the polar decomposition is not unique, and for det⁡F<0\det F < 0 the rotation with det⁡R=+1\det R = +1 does not give a symmetric positive SS. The element can stay inverted.
  • Model, not law. The corotated energy is a constitutive model chosen for speed. It is not a law of physics, and for large strains it differs from the St. Venant-Kirchhoff model and the neo-Hookean model.

Variants and improvements

  • Per vertex rotations. Müller et al. (2002) took a rotation per vertex from the rotation of the vertex neighbourhood and warped the global stiffness matrix with it. This is the original stiffness warping. Neighbouring vertices use different rotations, so in general the internal forces are not the gradient of one energy, and their sum and their torque need not be zero.
  • Per element rotations. Müller and Gross (2004) used one rotation per element, which is the method of this page. They also added plasticity and a simple fracture rule from the principal stresses.
  • Exact Hessian. The derivative of RR has a closed form, and adding it gives the true Hessian of Ψcr\Psi_{cr}, as in Sifakis and Barbič (2012). The true Hessian can be indefinite, so it is usually projected to be positive definite before the solve.
  • Invertible elements. The invertible finite elements of Irving, Teran and Fedkiw (2004) work in the diagonal frame of the singular value decomposition with det⁡U=det⁡V=+1\det U = \det V = +1. With the linear stress in that frame they extend the corotated model to inverted elements.
  • Shape matching and ARAP. Meshless shape matching takes one rotation for a cluster of particles, and as-rigid-as-possible deformation minimizes ∑∣F−R∣F2\sum |F - R|_F^2 over meshes. Both use the same idea of a best fit rotation.

When to use it

Use corotational elements when the body turns a lot but each element stretches by a few percent, for example soft props, muscles under small strain and interactive tools. It costs about as much as linear FEM, with one polar decomposition per element. For large strains or strong compression, use a nonlinear model such as the stable neo-Hookean model. If elements can invert, use invertible finite elements. For a cheaper and less accurate model, use position based dynamics or projective dynamics.

Pitfalls

  • Rotation from the wrong factor. Line L5 must use the polar rotation. A QR factor of FF depends on the order of the edges, so the result changes with the node numbering of the element.
  • A reflection in place of a rotation. The orthogonal polar factor of an inverted element has det⁡=−1\det = -1. Line L5 must return det⁡R=+1\det R = +1; a reflection flips the element frame and gives wrong forces.
  • Rotating only the displacement. The force is −RKe(RTx−X)-R K_e(R^T x - X). Writing −RKeRT(x−X)-R K_e R^T (x - X) in line L7 is not the same, because RTX≠XR^T X \ne X, and it brings back ghost forces under rotation.
  • Treating KwK_w as exact. The stiffness of line L9 is exact only at the rest shape. A Newton solver that relies on it can converge slowly at large strains; add a line search or the exact Hessian.
  • Stable is not accurate. The implicit step is stable for large Δt\Delta t, but it damps the motion: on a harmonic oscillator, backward Euler multiplies the energy by 1/(1+(ωΔt)2)1 / (1 + (\omega\Delta t)^2) per step. Large steps make the body look too soft and too damped.
  • Locking. Linear triangles and tetrahedra are too stiff in bending on coarse meshes. A cantilever of 1 m by 0.25 m made of 8 triangles, with E=1000E = 1000 Pa, ν=0.3\nu = 0.3 and 1 kg/m² under gravity, settles at a tip deflection of 0.059 m, about a quarter of the 0.235 m of Euler-Bernoulli beam theory (a measurement on this toy). See finite element locking.

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
corotational_fem.py 268 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/corotational-fem/. The authors are listed in prov/NYXCZF.jsonl.
"""Corotational linear finite elements on 2D triangles.

Each element has the rest positions X_a of its three nodes, the matrix D_m of
rest edge vectors, the rest area V0 = |det D_m| / 2 and the 6 by 6 stiffness
matrix K_e of linear elasticity,

    Psi_lin(F) = mu |eps|_F^2 + (lambda / 2) tr(eps)^2,  eps = (F + F^T) / 2 - I.

The corotational force rotates the element back to the rest frame, applies
the linear force there and rotates the result forward:

    f_e = -R K_e (R^T x_e - X_e),

with R the rotation factor of the polar decomposition F = R S. This force is
the exact negative gradient of the corotated energy

    Psi_cr(F) = mu |F - R|_F^2 + (lambda / 2) tr(R^T F - I)^2,

whose first Piola-Kirchhoff stress is P = 2 mu (F - R) + lambda tr(R^T F - I) R.
The warped stiffness R K_e R^T leaves out the derivative of R, so it is not
the exact Hessian of Psi_cr away from the rest shape.

Units: SI in 2D (positions in m, mu and lambda in N/m, masses in kg).
The Lame parameters are the 3D (plane strain) values of lame().
"""

import math

from anim import det, inv, mul, polar, solve, transpose


def lame(young, poisson):
    """Return (mu, lambda) from Young's modulus and Poisson's ratio (3D formula)."""
    mu = young / (2.0 * (1.0 + poisson))
    lam = young * poisson / ((1.0 + poisson) * (1.0 - 2.0 * poisson))
    return mu, lam


def edge_matrix(p, tri):
    """Return the 2 by 2 matrix [p1 - p0, p2 - p0] (edge vectors as columns)."""
    a, b, c = (p[i] for i in tri)
    return [[b[0] - a[0], c[0] - a[0]], [b[1] - a[1], c[1] - a[1]]]


def linear_stress(f, mu, lam):
    """First Piola-Kirchhoff stress of linear elasticity at F."""
    e00 = f[0][0] - 1.0
    e11 = f[1][1] - 1.0
    e01 = 0.5 * (f[0][1] + f[1][0])
    tr = e00 + e11
    return [[2.0 * mu * e00 + lam * tr, 2.0 * mu * e01], [2.0 * mu * e01, 2.0 * mu * e11 + lam * tr]]


def element_force_from_stress(p_stress, dm_inv_t, v0):
    """Return the forces on the 3 nodes, -V0 P D_m^(-T) and minus the sum for node 0."""
    h = mul(p_stress, dm_inv_t)
    f1 = (-v0 * h[0][0], -v0 * h[1][0])
    f2 = (-v0 * h[0][1], -v0 * h[1][1])
    f0 = (-f1[0] - f2[0], -f1[1] - f2[1])
    return [f0, f1, f2]


class Mesh:
    """A 2D triangle mesh with its rest data, per element stiffness and lumped masses.

    rest: list of (x, y) rest positions in m; tris: list of index triples with
    positive rest orientation; density in kg/m^2. Cost of the build: O(n + m)
    for n nodes and m elements.
    """

    def __init__(self, rest, tris, mu, lam, density=1.0):
        self.rest = [tuple(map(float, r)) for r in rest]
        self.tris = [tuple(t) for t in tris]
        self.mu = mu
        self.lam = lam
        self.dm_inv = []
        self.dm_inv_t = []
        self.v0 = []
        self.ke = []
        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)
            self.dm_inv.append(di)
            self.dm_inv_t.append(transpose(di))
            v0 = 0.5 * abs(det(dm))
            self.v0.append(v0)
            for a in t:
                self.mass[a] += density * v0 / 3.0
            self.ke.append(self._stiffness(len(self.v0) - 1))

    def deformation_gradient(self, x, e):
        """F = D_s D_m^(-1) of element e at the positions x."""
        return mul(edge_matrix(x, self.tris[e]), self.dm_inv[e])

    def linear_element_force(self, x, e):
        """Forces of linear elasticity on the nodes of element e (a linear map of x - X)."""
        f = self.deformation_gradient(x, e)
        return element_force_from_stress(linear_stress(f, self.mu, self.lam), self.dm_inv_t[e], self.v0[e])

    def _stiffness(self, e):
        """The 6 by 6 matrix K_e with f_lin = -K_e (x_e - X_e), one column per unit displacement."""
        t = self.tris[e]
        k = [[0.0] * 6 for _ in range(6)]
        for col in range(6):
            x = list(self.rest)
            a, comp = t[col // 2], col % 2
            moved = list(x[a])
            moved[comp] += 1.0
            x[a] = tuple(moved)
            fe = self.linear_element_force(x, e)
            for row in range(6):
                k[row][col] = -fe[row // 2][row % 2]
        return k


def corotational_forces(mesh, x):
    """Return the corotational elastic forces on all nodes at the positions x.

    Cost O(m) for m elements: one 2 by 2 polar decomposition and one 6 by 6
    product per element.
    """
    n = len(x)
    f = [[0.0, 0.0] for _ in range(n)]  # @line L1
    rots = []
    for e, t in enumerate(mesh.tris):  # @line L2
        ds = edge_matrix(x, t)  # @line L3
        fmat = mul(ds, mesh.dm_inv[e])  # @line L4
        r, _ = polar(fmat)  # @line L5
        rots.append(r)
        y = []
        for k, a in enumerate(t):  # @line L6
            ya = (r[0][0] * x[a][0] + r[1][0] * x[a][1], r[0][1] * x[a][0] + r[1][1] * x[a][1])
            ra = mesh.rest[a]
            y.extend((ya[0] - ra[0], ya[1] - ra[1]))
        ke = mesh.ke[e]
        g = [-sum(ke[i][j] * y[j] for j in range(6)) for i in range(6)]  # @line L7
        for k, a in enumerate(t):  # @line L8
            gx, gy = g[2 * k], g[2 * k + 1]
            f[a][0] += r[0][0] * gx + r[0][1] * gy
            f[a][1] += r[1][0] * gx + r[1][1] * gy
    return [tuple(v) for v in f], rots


def warped_stiffness(mesh, rots):
    """Assemble the 2n by 2n matrix K_w = sum over elements of R K_e R^T. Cost O(m + n^2)."""
    n = len(mesh.rest)
    kw = [[0.0] * (2 * n) for _ in range(2 * n)]
    for e, t in enumerate(mesh.tris):
        r = rots[e]
        ke = mesh.ke[e]
        for i in range(3):
            for j in range(3):
                blk = [[ke[2 * i + p][2 * j + q] for q in range(2)] for p in range(2)]
                w = mul(mul(r, blk), transpose(r))
                for p in range(2):
                    for q in range(2):
                        kw[2 * t[i] + p][2 * t[j] + q] += w[p][q]
    return kw


def step_implicit(mesh, x, v, dt, f_ext=None, fixed=()):
    """One linearized backward Euler step with the warped stiffness.

    Solves (M + dt^2 K_w) v' = M v + dt (f(x) + f_ext), then x' = x + dt v'.
    Nodes in fixed keep v' = 0. Cost: O(m) for the forces plus one dense solve
    of size 2n, O(n^3) here (a sparse solver or CG is used in practice).
    """
    n = len(x)
    f, rots = corotational_forces(mesh, x)
    kw = warped_stiffness(mesh, rots)  # @line L9
    fixed = set(fixed)
    a = [[dt * dt * kw[i][j] for j in range(2 * n)] for i in range(2 * n)]
    b = [0.0] * (2 * n)
    for i in range(n):
        for c in range(2):
            row = 2 * i + c
            a[row][row] += mesh.mass[i]
            fe = f_ext[i][c] if f_ext is not None else 0.0
            b[row] = mesh.mass[i] * v[i][c] + dt * (f[i][c] + fe)
    for i in fixed:
        for c in range(2):
            row = 2 * i + c
            a[row] = [0.0] * (2 * n)
            a[row][row] = 1.0
            b[row] = 0.0
            for k in range(2 * n):
                if k != row:
                    a[k][row] = 0.0
    vn = solve(a, b)  # @line L10
    v_new = [(vn[2 * i], vn[2 * i + 1]) for i in range(n)]
    x_new = [(x[i][0] + dt * v_new[i][0], x[i][1] + dt * v_new[i][1]) for i in range(n)]  # @line L11
    return x_new, v_new


def step_explicit(mesh, x, v, dt, f_ext=None, fixed=()):
    """One symplectic Euler step: v' = v + dt M^(-1) f(x), then x' = x + dt v'.

    Stable for a linear spring only if omega dt < 2. Cost O(n + m).
    """
    f, _ = corotational_forces(mesh, x)
    fixed = set(fixed)
    v_new, x_new = [], []
    for i in range(len(x)):
        if i in fixed:
            v_new.append((0.0, 0.0))
            x_new.append(x[i])
            continue
        fe = f_ext[i] if f_ext is not None else (0.0, 0.0)
        vi = tuple(v[i][c] + dt * (f[i][c] + fe[c]) / mesh.mass[i] for c in range(2))
        v_new.append(vi)
        x_new.append((x[i][0] + dt * vi[0], x[i][1] + dt * vi[1]))
    return x_new, v_new


# ---------------------------------------------------------------- reference quantities


def corotated_energy_density(f, mu, lam):
    """Psi_cr(F) = mu |F - R|_F^2 + (lambda / 2) tr(R^T F - I)^2 with R from polar(F)."""
    r, s = polar(f)
    d = sum((f[i][j] - r[i][j]) ** 2 for i in range(2) for j in range(2))
    tr = s[0][0] + s[1][1] - 2.0
    return mu * d + 0.5 * lam * tr * tr


def corotated_energy(mesh, x):
    """Total corotated energy, the sum of V0 Psi_cr(F) over the elements."""
    return sum(mesh.v0[e] * corotated_energy_density(mesh.deformation_gradient(x, e), mesh.mu, mesh.lam)
               for e in range(len(mesh.tris)))


def linear_forces(mesh, x):
    """Forces of plain linear FEM, -K (x - X), for comparison."""
    f = [[0.0, 0.0] for _ in x]
    for e, t in enumerate(mesh.tris):
        fe = mesh.linear_element_force(x, e)
        for k, a in enumerate(t):
            f[a][0] += fe[k][0]
            f[a][1] += fe[k][1]
    return [tuple(v) for v in f]


def grid_mesh(nx, ny, width, height):
    """A rectangle split into nx by ny squares, each cut into two triangles."""
    rest = [(width * i / nx, height * j / ny) for j in range(ny + 1) for i in range(nx + 1)]
    tris = []
    for j in range(ny):
        for i in range(nx):
            a = j * (nx + 1) + i
            b, c, d = a + 1, a + nx + 1, a + nx + 2
            tris.append((a, b, d))
            tris.append((a, d, c))
    return rest, tris


def rotate_points(points, theta, center=(0.0, 0.0), shift=(0.0, 0.0)):
    """Rotate points by theta about center, then translate by shift."""
    c, s = math.cos(theta), math.sin(theta)
    out = []
    for p in points:
        dx, dy = p[0] - center[0], p[1] - center[1]
        out.append((center[0] + c * dx - s * dy + shift[0], center[1] + s * dx + c * dy + shift[1]))
    return out
test_corotational_fem.py 168 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/corotational-fem/. The authors are listed in prov/NYXCZF.jsonl.
"""Tests of corotational FEM on small 2D triangle meshes.

The force is checked against central differences of the corotated energy,
it vanishes at the rest shape and after a rigid motion, it has zero net force
and zero net torque, and the warped stiffness equals the true Hessian only at
a rotated rest shape. Plain linear FEM gives ghost forces under rotation.
A free spinning body keeps its momentum and angular momentum under
symplectic Euler, and a cantilever under gravity settles to an equilibrium
with the implicit step.
"""

import math
import random

import anim
from corotational_fem import (Mesh, corotated_energy, corotated_energy_density, corotational_forces,
                              grid_mesh, lame, linear_forces, rotate_points, step_explicit, step_implicit,
                              warped_stiffness)

MU, LAM = lame(1000.0, 0.3)


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 perturbed(rest, rng, amount):
    return [(p[0] + rng.uniform(-amount, amount), p[1] + rng.uniform(-amount, amount)) for p in rest]


def small_mesh():
    rest, tris = grid_mesh(2, 1, 1.0, 0.5)
    return Mesh(rest, tris, MU, LAM)


def test_lame_check_values():
    mu, lam = lame(1.0, 0.3)
    assert abs(mu - 0.384615) < 1e-6
    assert abs(lam - 0.576923) < 1e-6


def test_force_is_minus_gradient_of_corotated_energy():
    rng = random.Random(11)
    mesh = small_mesh()
    for _ in range(5):
        x = rotate_points(perturbed(mesh.rest, rng, 0.15), rng.uniform(-3.0, 3.0))
        f, _ = corotational_forces(mesh, x)
        g = anim.num_grad(lambda z: corotated_energy(mesh, unflat(z)), 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_zero_force_at_rest_and_after_rigid_motion():
    mesh = small_mesh()
    for theta in (0.0, 0.7, 2.5, -3.0):
        x = rotate_points(mesh.rest, theta, center=(0.3, 0.1), shift=(2.0, -1.0))
        f, _ = corotational_forces(mesh, x)
        assert max(abs(c) for c in flat(f)) < 1e-10


def test_linear_fem_has_ghost_forces_under_rotation():
    mesh = small_mesh()
    x = rotate_points(mesh.rest, 1.0)
    fl = linear_forces(mesh, x)
    assert max(abs(c) for c in flat(fl)) > 10.0


def test_energy_is_frame_indifferent():
    rng = random.Random(5)
    for _ in range(20):
        f = [[1.0 + rng.uniform(-0.4, 0.4), rng.uniform(-0.4, 0.4)], [rng.uniform(-0.4, 0.4), 1.0 + rng.uniform(-0.4, 0.4)]]
        r = anim.rot2(rng.uniform(-math.pi, math.pi))
        a = corotated_energy_density(f, MU, LAM)
        b = corotated_energy_density(anim.mul(r, f), MU, LAM)
        assert abs(a - b) <= 1e-12 * max(1.0, a)


def test_zero_net_force_and_torque():
    rng = random.Random(3)
    mesh = small_mesh()
    x = perturbed(mesh.rest, rng, 0.2)
    f, _ = corotational_forces(mesh, x)
    scale = max(abs(c) for c in flat(f))
    assert abs(sum(p[0] for p in f)) < 1e-12 * scale * len(f)
    assert abs(sum(p[1] for p in f)) < 1e-12 * scale * len(f)
    torque = sum(anim.cross2(x[i], f[i]) for i in range(len(f)))
    assert abs(torque) < 1e-11 * scale * len(f)


def numeric_hessian(mesh, x, h=1e-6):
    z = flat(x)
    cols = []
    for k in range(len(z)):
        zp, zm = list(z), list(z)
        zp[k] += h
        zm[k] -= h
        fp, _ = corotational_forces(mesh, unflat(zp))
        fm, _ = corotational_forces(mesh, unflat(zm))
        cols.append([-(a - b) / (2 * h) for a, b in zip(flat(fp), flat(fm))])
    return [list(r) for r in zip(*cols)]


def test_warped_stiffness_exact_only_at_rotated_rest():
    mesh = small_mesh()
    x = rotate_points(mesh.rest, 0.9)
    _, rots = corotational_forces(mesh, x)
    kw = warped_stiffness(mesh, rots)
    kn = numeric_hessian(mesh, x)
    scale = max(abs(c) for row in kn for c in row)
    assert max(abs(kw[i][j] - kn[i][j]) for i in range(len(kw)) for j in range(len(kw))) < 1e-6 * scale
    stretched = [(1.3 * p[0], 0.8 * p[1]) for p in mesh.rest]
    x = rotate_points(stretched, 0.9)
    _, rots = corotational_forces(mesh, x)
    kw = warped_stiffness(mesh, rots)
    kn = numeric_hessian(mesh, x)
    assert max(abs(kw[i][j] - kn[i][j]) for i in range(len(kw)) for j in range(len(kw))) > 1e-2 * scale


def test_spinning_body_keeps_momentum_and_shape():
    mesh = small_mesh()
    x = list(mesh.rest)
    cx = sum(p[0] for p in x) / len(x)
    cy = sum(p[1] for p in x) / len(x)
    omega = 3.0
    v = [(-omega * (p[1] - cy), omega * (p[0] - cx)) for p in x]
    dt = 1e-3

    def momenta(x, v):
        px = sum(m * w[0] for m, w in zip(mesh.mass, v))
        py = sum(m * w[1] for m, w in zip(mesh.mass, v))
        lz = sum(m * anim.cross2(p, w) for m, p, w in zip(mesh.mass, x, v))
        return px, py, lz

    p0 = momenta(x, v)
    for _ in range(1000):
        x, v = step_explicit(mesh, x, v, dt)
    p1 = momenta(x, v)
    assert abs(p1[0] - p0[0]) < 1e-10 and abs(p1[1] - p0[1]) < 1e-10
    assert abs(p1[2] - p0[2]) < 1e-10 * abs(p0[2])
    area = sum(0.5 * anim.det([[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]]]) for t in mesh.tris)
    assert abs(area - 0.5) < 0.01


def test_cantilever_settles_with_implicit_step():
    rest, tris = grid_mesh(4, 1, 1.0, 0.25)
    mesh = Mesh(rest, tris, MU, LAM)
    fixed = [i for i, p in enumerate(rest) if p[0] == 0.0]
    g = [(0.0, -9.81 * m) for m in mesh.mass]
    x, v = list(rest), [(0.0, 0.0)] * len(rest)
    for _ in range(150):
        x, v = step_implicit(mesh, x, v, 0.05, f_ext=g, fixed=fixed)
    f, _ = corotational_forces(mesh, x)
    free = [i for i in range(len(x)) if i not in fixed]
    resid = max(abs(f[i][c] + g[i][c]) for i in free for c in range(2))
    gmax = max(abs(g[i][1]) for i in free)
    assert resid < 1e-3 * gmax
    tip = min(x[i][1] for i in free)
    assert -0.6 < tip < -0.05
    for i in fixed:
        assert x[i] == rest[i]

History

The idea of a frame that turns with each element comes from structural mechanics, where corotational formulations of beams and shells are old. In computer graphics, Müller, Dorsey, McMillan, Jagnow and Cutler (2002) brought it in as stiffness warping, with a rotation per vertex, linear stiffness and an implicit step, for real time deformation. Müller and Gross (2004) changed to a rotation per element and added plasticity and fracture. Irving, Teran and Fedkiw (2004) extended the corotated model to inverted elements, and Sifakis and Barbič (2012) wrote it as the energy μ∣F−R∣F2+λ2tr⁡(RTF−I)2\mu|F - R|_F^2 + \frac{\lambda}{2}\operatorname{tr}(R^T F - I)^2 with its exact gradient.

References

  1. Matthias Müller, Julie Dorsey, Leonard McMillan, Robert Jagnow and Barbara Cutler, Stable real-time deformations, ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2002), 49-54, the whole paper (stiffness warping with a rotation per vertex and an implicit step)
  2. Matthias Müller and Markus Gross, Interactive virtual materials, Proceedings of Graphics Interface 2004, 239-246, the corotational formulation with a rotation per element, plus plasticity and fracture (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 corotated linear material and its stress (general locator)

Where this leads

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.forces_per_step
  • a full proof of time.implicit_step_with_cg
  • 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