Algorithm Search⌘K

Algorithmadvanced

Discrete elastic rods

Also called DER.

Simulate hair and cables as a polyline with a bending energy from discrete curvature and a twist energy measured against a parallel transported frame.

Time
Θ(n) forces_per_step
Space
Θ(n) extra
Where
n = the number of edges of the rod
Properties
deterministicnot exactiterative
Origin
Miklós Bergou, Max Wardetzky, Stephen Robinson, Basile Audoly, Eitan Grinspun, 2008

Discrete elastic rods model a thin elastic rod, such as a hair, a cable or a thread, as a polyline with a twist angle on each edge. The bending energy at each interior vertex uses the curvature binormal

κbi=2 ei−1×ei∣ei−1∣∣ei∣+ei−1⋅ei,\kappa b_i = \frac{2\, e^{i-1} \times e^i}{|e^{i-1}||e^i| + e^{i-1} \cdot e^i},

and the twist is measured against the Bishop frame, the frame of the first edge carried along the rod by parallel transport. When the centerline moves, the Bishop frame at the far end turns by the holonomy, so bending and twisting are coupled. Bergou, Wardetzky, Robinson, Audoly and Grinspun (2008) gave the method, with the exact gradient of this coupling.

In plain words

A hair or a cable is long and thin, so it is drawn as a chain of short straight pieces. It resists bending at each joint, and it resists twisting along its length. Bending is easy to measure: look at the angle between the two pieces at a joint. Twisting is harder, because a chain has no natural "up" direction. The method makes one by sliding a marker along the chain without spinning it. The twist is how far the real end of the cable has turned compared with that marker. A strange fact follows: if you bend the chain into a loop in space, the marker comes back turned. So bending the cable changes its twist, and a twisted cable wants to bend. The method computes this effect exactly, at low cost.

The problem

The input is a rod with the vertices x0,…,xnx_0, \dots, x_n, the edges ej=xj+1−xje^j = x_{j+1} - x_j, and the rest edges eˉj\bar e^j. This page treats an isotropic rod that is straight at rest, with the bending stiffness α\alpha (EI, in N m²), the twisting stiffness β\beta (GJ, in N m²), and a stretching penalty ksk_s in N. The rod is clamped at both ends: the first two and the last two vertices are fixed, the material director u0u^0 of edge 0 is given, and the material director dendd_{end} of the last edge is given. The output is the force on every vertex and a time step.

The energy is

E=∑jks2∣eˉj∣(∣ej∣∣eˉj∣−1)2+∑iα∣κbi∣2lˉi+β Δθ2Lˉ,E = \sum_j \tfrac{k_s}{2}|\bar e^j|\Bigl(\tfrac{|e^j|}{|\bar e^j|} - 1\Bigr)^2 + \sum_i \frac{\alpha|\kappa b_i|^2}{\bar l_i} + \frac{\beta\,\Delta\theta^2}{\bar L},

with lˉi=∣eˉi−1∣+∣eˉi∣\bar l_i = |\bar e^{i-1}| + |\bar e^i| and Lˉ=∑ilˉi\bar L = \sum_i \bar l_i. The last term is the quasistatic twist: the material frames of the interior edges are at their minimum, so the total twist Δθ\Delta\theta spreads along the rod in proportion to lˉi\bar l_i. Δθ\Delta\theta is the angle about the last tangent from the Bishop director un−1u^{n-1} to dendd_{end}. The paper writes the bending term with natural curvatures and material curvatures for rods that are curved or not round at rest; constant factors in α\alpha differ between conventions. With the lˉi\bar l_i above, α\alpha equals the EI of a beam (see Properties).

The algorithm

  1. DER-STEP(x, v, Δθ_prev, Δt) ▷ u^0, d_end, l̄_i, L̄ fixed; ends clamped
  2. 1e^j ← x_(j+1) - x_j for each edge j
  3. 2κb_i ← 2 e^(i-1) × e^i / (|e^(i-1)||e^i| + e^(i-1)·e^i) for each interior vertex i
  4. 3u^j ← P(t^(j-1) → t^j) u^(j-1) for j = 1, ..., n-1 ▷ parallel transport
  5. 4Δθ ← signed angle from u^(n-1) to d_end about t^(n-1), nearest to Δθ_prev
  6. 5f ← -∇E_stretch
  7. 6f_k ← f_k - (2α / l̄_i) (∂κb_i/∂x_k)^T κb_i for k = i-1, i, i+1, each interior i
  8. 7f_k ← f_k + (2βΔθ / L̄) ∇_k ψ_i for k = i-1, i, i+1, each interior i
  9. 8v ← v + Δt M^(-1) f, x ← x + Δt v on the free vertices
  10. return x, v, Δθ

Line L3 uses the minimal rotation P(t1→t2)=cI+[b]+bbT/(1+c)P(t_1 \to t_2) = cI + [b] + bb^T/(1 + c), with c=t1⋅t2c = t_1 \cdot t_2, b=t1×t2b = t_1 \times t_2 and [b]y=b×y[b]y = b \times y. Line L4 counts full turns by taking the angle nearest to the value of the previous step. Line L6 uses the Jacobians of κb\kappa b with respect to the two edges a=ei−1a = e^{i-1} and b=eib = e^i,

∂κb∂a=−2[b]−κb (∣b∣ a/∣a∣+b)TD,∂κb∂b=2[a]−κb (∣a∣ b/∣b∣+a)TD,D=∣a∣∣b∣+a⋅b.\frac{\partial\kappa b}{\partial a} = \frac{-2[b] - \kappa b\,(|b|\,a/|a| + b)^T}{D}, \qquad \frac{\partial\kappa b}{\partial b} = \frac{2[a] - \kappa b\,(|a|\,b/|b| + a)^T}{D}, \qquad D = |a||b| + a \cdot b.

Line L7 is the twist force through the holonomy: ∇i−1ψi=κbi/(2∣ei−1∣)\nabla_{i-1}\psi_i = \kappa b_i/(2|e^{i-1}|), ∇i+1ψi=−κbi/(2∣ei∣)\nabla_{i+1}\psi_i = -\kappa b_i/(2|e^i|) and ∇iψi=−(∇i−1ψi+∇i+1ψi)\nabla_i\psi_i = -(\nabla_{i-1}\psi_i + \nabla_{i+1}\psi_i). Line L8 is a symplectic Euler step with lumped masses; the paper also enforces the edge lengths with a projection, and the stretching penalty of line L5 stands in for it here.

Example

Take five vertices (0,0,0)(0, 0, 0), (1,0,0)(1, 0, 0), (1,1,0)(1, 1, 0), (1,1,1)(1, 1, 1) and (2,1,1)(2, 1, 1) in m, a straight rest shape with unit edges, α=β=1\alpha = \beta = 1 N m², and u0=dend=(0,0,1)u^0 = d_{end} = (0, 0, 1). The rod turns by 90 degrees at each of the three interior vertices, and its last edge is parallel to its first. So lˉi=2\bar l_i = 2 m and Lˉ=6\bar L = 6 m.

| Edge or vertex | Tangent tjt^j | Bishop director uju^j | κbi\kappa b_i at the vertex after the edge | ∣κbi∣|\kappa b_i| | |---|---|---|---|---| | edge 0 | (1,0,0)(1, 0, 0) | (0,0,1)(0, 0, 1) | (0,0,2)(0, 0, 2) | 2 | | edge 1 | (0,1,0)(0, 1, 0) | (0,0,1)(0, 0, 1) | (2,0,0)(2, 0, 0) | 2 | | edge 2 | (0,0,1)(0, 0, 1) | (0,−1,0)(0, -1, 0) | (0,2,0)(0, 2, 0) | 2 | | edge 3 | (1,0,0)(1, 0, 0) | (0,−1,0)(0, -1, 0) | none | none |

Each turn of 90 degrees gives ∣κb∣=2tan⁡45°=2|\kappa b| = 2\tan 45° = 2, so the bending energy is 3⋅4/2=63 \cdot 4/2 = 6 J. The last edge points the same way as the first, but the Bishop director came back turned by 90 degrees: it is (0,−1,0)(0, -1, 0), not (0,0,1)(0, 0, 1). This turn is the holonomy of the path. So the clamp dend=(0,0,1)d_{end} = (0, 0, 1) is twisted by Δθ=−π/2\Delta\theta = -\pi/2 relative to the Bishop frame, and the twist energy is (π/2)2/6=0.411234(\pi/2)^2/6 = 0.411234 J, although the two clamps point the same way. A planar rod never shows this effect: the director that starts normal to the plane stays normal to it.

Correctness

The proof shows that lines L5 to L7 return the exact negative gradient of EE. These are proved properties.

  • ∣κbi∣=2tan⁡(φi/2)|\kappa b_i| = 2\tan(\varphi_i/2) for the turning angle φi\varphi_i, and κbi\kappa b_i is perpendicular to both edges.
  • Line L3 is the rotation about tj−1×tjt^{j-1} \times t^j that takes tj−1t^{j-1} to tjt^j.
  • The key step. Write the transport as the product of two reflections, P=HmHt1P = H_m H_{t_1} with the bisector mm of t1t_1 and t2t_2. Then the rate at which a variation turns the transported frame about the tangent is −12κb⋅(δt1+δt2)-\frac12\kappa b \cdot (\delta t_1 + \delta t_2) at each vertex. Summed along the rod this is the holonomy, and it gives the formulas of line L7.
  • The quasistatic twist energy βΔθ2/Lˉ\beta\Delta\theta^2/\bar L is the minimum of ∑iβ(θi−θi−1)2/lˉi\sum_i \beta(\theta^i - \theta^{i-1})^2/\bar l_i over the interior angles, by the Cauchy-Schwarz inequality.
  • The energy does not change under rigid motions, so the net force and the net torque of a free rod are zero, and a straight rod has no force for any twist.

The twist term needs the first and the last edges to be fixed; the proof uses this to keep u0u^0 and dendd_{end} fixed.

Proof: The forces of the discrete elastic rod are the exact negative gradient of its energy, including the twist term through the holonomyfull

We use the notation of the page. The rod has the vertices x0,…,xnx_0, \dots, x_n and the edges ej=xj+1−xje^j = x_{j+1} - x_j with unit tangents tjt^j. At an interior vertex ii the edges a=ei−1a = e^{i-1} and b=eib = e^i meet, and we assume a⋅b>−∣a∣∣b∣a \cdot b > -|a||b|, so the rod does not fold back. [w][w] is the skew matrix with [w]y=w×y[w]y = w \times y. The energy is E=Es+Eb+EtE = E_s + E_b + E_t with

Es=∑jks2∣eˉj∣(∣ej∣∣eˉj∣−1)2,Eb=∑iα∣κbi∣2lˉi,Et=β Δθ2Lˉ.E_s = \sum_j \tfrac{k_s}{2}|\bar e^j|\Bigl(\tfrac{|e^j|}{|\bar e^j|} - 1\Bigr)^2, \qquad E_b = \sum_i \frac{\alpha|\kappa b_i|^2}{\bar l_i}, \qquad E_t = \frac{\beta\,\Delta\theta^2}{\bar L}.

Step 1: the curvature binormal

κb=2 a×b/(∣a∣∣b∣+a⋅b)\kappa b = 2\,a \times b / (|a||b| + a \cdot b). It is perpendicular to aa and bb. With the turning angle φ\varphi between aa and bb, ∣a×b∣=∣a∣∣b∣sin⁡φ|a \times b| = |a||b|\sin\varphi and a⋅b=∣a∣∣b∣cos⁡φa \cdot b = |a||b|\cos\varphi, so ∣κb∣=2sin⁡φ/(1+cos⁡φ)=2tan⁡(φ/2)|\kappa b| = 2\sin\varphi / (1 + \cos\varphi) = 2\tan(\varphi/2). □\square

Step 2: lines L5 and L6 give −∇(Es+Eb)-\nabla(E_s + E_b)

For one edge, ∂Es/∂e=ks(∣e∣/∣eˉ∣−1) e/∣e∣=g\partial E_s / \partial e = k_s(|e|/|\bar e| - 1)\,e/|e| = g, and e=xj+1−xje = x_{j+1} - x_j, so the force is +g+g on xjx_j and −g-g on xj+1x_{j+1}, as in line L5.

Write κb=N/D\kappa b = N / D with N=2 a×bN = 2\,a \times b and D=∣a∣∣b∣+a⋅bD = |a||b| + a \cdot b. Then dN=2 da×b+2 a×db=−2[b] da+2[a] dbdN = 2\,da \times b + 2\,a \times db = -2[b]\,da + 2[a]\,db and dD=(∣b∣ a/∣a∣+b)⋅da+(∣a∣ b/∣b∣+a)⋅dbdD = (|b|\,a/|a| + b) \cdot da + (|a|\,b/|b| + a) \cdot db. By the quotient rule,

Ga=∂κb∂a=−2[b]−κb (∣b∣ a/∣a∣+b)TD,Gb=∂κb∂b=2[a]−κb (∣a∣ b/∣b∣+a)TD.G_a = \frac{\partial\kappa b}{\partial a} = \frac{-2[b] - \kappa b\,(|b|\,a/|a| + b)^T}{D}, \qquad G_b = \frac{\partial\kappa b}{\partial b} = \frac{2[a] - \kappa b\,(|a|\,b/|b| + a)^T}{D}.

Since a=xi−xi−1a = x_i - x_{i-1} and b=xi+1−xib = x_{i+1} - x_i, ∂κb/∂xi−1=−Ga\partial\kappa b/\partial x_{i-1} = -G_a, ∂κb/∂xi=Ga−Gb\partial\kappa b/\partial x_i = G_a - G_b and ∂κb/∂xi+1=Gb\partial\kappa b/\partial x_{i+1} = G_b. The term α∣κb∣2/lˉ\alpha|\kappa b|^2/\bar l has ∂/∂κb=(2α/lˉ)κb\partial/\partial\kappa b = (2\alpha/\bar l)\kappa b, so its gradient for vertex kk is (2α/lˉ)(∂κb/∂xk)Tκb(2\alpha/\bar l)(\partial\kappa b/\partial x_k)^T\kappa b. Line L6 adds minus this to the three vertices. □\square

Step 3: parallel transport is the rotation of line L3

For unit t1t_1, t2t_2 with c=t1⋅t2>−1c = t_1 \cdot t_2 > -1 and b=t1×t2=sin⁡φ kb = t_1 \times t_2 = \sin\varphi\, k for a unit axis kk, Rodrigues' formula gives the rotation about kk by φ\varphi as I+sin⁡φ[k]+(1−c)[k]2I + \sin\varphi[k] + (1 - c)[k]^2. With [k]2=kkT−I[k]^2 = kk^T - I and (1−c)/sin⁡2φ=1/(1+c)(1 - c)/\sin^2\varphi = 1/(1 + c) this is P=cI+[b]+bbT/(1+c)P = cI + [b] + bb^T/(1 + c), the formula of the code. It maps t1t_1 to t2t_2 and fixes bb. PP is also the product HmHt1H_m H_{t_1} of the reflections Hn=I−2nnTH_n = I - 2nn^T with m=(t1+t2)/∣t1+t2∣m = (t_1 + t_2)/|t_1 + t_2|: Ht1H_{t_1} maps t1t_1 to −t1-t_1, HmH_m maps −t1-t_1 to t2t_2, both fix bb, and the product of two reflections is the rotation about the line where their planes meet, by twice the angle between them, which is φ\varphi. □\square

Step 4: the variation of the twist (the holonomy)

Let the vertices move smoothly, with the first and the last edges fixed, and write δ\delta for the derivative. Let uju^j be the Bishop director of edge jj and vj=tj×ujv^j = t^j \times u^j, and let Ψj=δuj⋅vj\Psi_j = \delta u^j \cdot v^j, the rate at which uju^j turns about tjt^j. Since edge 0 is fixed, u0u^0 is fixed and Ψ0=0\Psi_0 = 0.

From uj=Pjuj−1u^j = P_j u^{j-1} and vj=Pjvj−1v^j = P_j v^{j-1} (a rotation keeps the cross product),

Ψj=(δPj uj−1)⋅(Pjvj−1)+(Pj δuj−1)⋅(Pjvj−1)=vj−1⋅(PjTδPj) uj−1+Ψj−1.\Psi_j = (\delta P_j\, u^{j-1}) \cdot (P_j v^{j-1}) + (P_j\,\delta u^{j-1}) \cdot (P_j v^{j-1}) = v^{j-1} \cdot (P_j^T \delta P_j)\, u^{j-1} + \Psi_{j-1}.

PjTδPjP_j^T\delta P_j is skew, say [ωj][\omega_j], and v⋅(ω×u)=ω⋅(u×v)=ω⋅tj−1v \cdot (\omega \times u) = \omega \cdot (u \times v) = \omega \cdot t^{j-1}, so Ψj−Ψj−1=tj−1⋅ωj\Psi_j - \Psi_{j-1} = t^{j-1} \cdot \omega_j.

Now compute t1⋅ωt_1 \cdot \omega for P=HmHt1P = H_m H_{t_1} (Step 3, with t1=tj−1t_1 = t^{j-1} and t2=tjt_2 = t^j). For a unit nn, δHn=−2(δn nT+n δnT)\delta H_n = -2(\delta n\, n^T + n\,\delta n^T) and HnδHn=2(n δnT−δn nT)=2[δn×n]H_n \delta H_n = 2(n\,\delta n^T - \delta n\, n^T) = 2[\delta n \times n]. So PTδP=Ht1(HmδHm)Ht1+Ht1δHt1=2Ht1[δm×m]Ht1+2[δt1×t1]P^T\delta P = H_{t_1}(H_m \delta H_m)H_{t_1} + H_{t_1}\delta H_{t_1} = 2H_{t_1}[\delta m \times m]H_{t_1} + 2[\delta t_1 \times t_1]. For a reflection HH, H[w]H=−[Hw]H[w]H = -[Hw], so ω=−2Ht1(δm×m)+2 δt1×t1\omega = -2H_{t_1}(\delta m \times m) + 2\,\delta t_1 \times t_1, and

t1⋅ω=−2 (Ht1t1)⋅(δm×m)=2 t1⋅(δm×m)=2 δm⋅(m×t1).t_1 \cdot \omega = -2\,(H_{t_1}t_1) \cdot (\delta m \times m) = 2\,t_1 \cdot (\delta m \times m) = 2\,\delta m \cdot (m \times t_1).

With s=∣t1+t2∣=2+2cs = |t_1 + t_2| = \sqrt{2 + 2c}, m×t1=(t2×t1)/sm \times t_1 = (t_2 \times t_1)/s, and δm=(I−mmT)(δt1+δt2)/s\delta m = (I - mm^T)(\delta t_1 + \delta t_2)/s, where the projection drops out because m×t1⊥mm \times t_1 \perp m. So t1⋅ω=(δt1+δt2)⋅(t2×t1)/(1+c)=−12κb⋅(δt1+δt2)t_1 \cdot \omega = (\delta t_1 + \delta t_2) \cdot (t_2 \times t_1)/(1 + c) = -\tfrac12\kappa b \cdot (\delta t_1 + \delta t_2), because κb=2 t1×t2/(1+c)\kappa b = 2\,t_1 \times t_2/(1 + c) for unit tangents. Summing from Ψ0=0\Psi_0 = 0,

Ψn−1=−12∑iκbi⋅(δti−1+δti).\Psi_{n-1} = -\tfrac12\sum_i \kappa b_i \cdot (\delta t^{i-1} + \delta t^i).

The last edge and dendd_{end} are fixed, and un−1u^{n-1}, vn−1v^{n-1} turn together about tn−1t^{n-1} at the rate Ψn−1\Psi_{n-1}. Line L4 measures Δθ\Delta\theta with dend=cos⁡Δθ un−1+sin⁡Δθ vn−1d_{end} = \cos\Delta\theta\, u^{n-1} + \sin\Delta\theta\, v^{n-1}, so δΔθ=−Ψn−1\delta\Delta\theta = -\Psi_{n-1}. The unwrapping to the value nearest the previous one adds a constant multiple of 2π2\pi, which does not change the derivative.

Finally, δt=(I−ttT) δe/∣e∣\delta t = (I - tt^T)\,\delta e/|e| and κbi⊥ti−1,ti\kappa b_i \perp t^{i-1}, t^i, so κbi⋅δti−1=κbi⋅(δxi−δxi−1)/∣ei−1∣\kappa b_i \cdot \delta t^{i-1} = \kappa b_i \cdot (\delta x_i - \delta x_{i-1})/|e^{i-1}| and κbi⋅δti=κbi⋅(δxi+1−δxi)/∣ei∣\kappa b_i \cdot \delta t^i = \kappa b_i \cdot (\delta x_{i+1} - \delta x_i)/|e^i|. With hi−=κbi/(2∣ei−1∣)h^-_i = \kappa b_i/(2|e^{i-1}|) and hi+=−κbi/(2∣ei∣)h^+_i = -\kappa b_i/(2|e^i|), the interior vertex ii contributes −hi−-h^-_i to ∂Δθ/∂xi−1\partial\Delta\theta/\partial x_{i-1}, −hi+-h^+_i to ∂Δθ/∂xi+1\partial\Delta\theta/\partial x_{i+1} and hi−+hi+h^-_i + h^+_i to ∂Δθ/∂xi\partial\Delta\theta/\partial x_i, and ∂Δθ/∂x\partial\Delta\theta/\partial x is the sum of these contributions over all interior vertices. □\square

Step 5: line L7 gives −∇Et-\nabla E_t

∂Et/∂x=(2βΔθ/Lˉ) ∂Δθ/∂x\partial E_t/\partial x = (2\beta\Delta\theta/\bar L)\,\partial\Delta\theta/\partial x. By Step 4 the force −∂Et/∂x-\partial E_t/\partial x adds c hi−c\,h^-_i to xi−1x_{i-1}, c hi+c\,h^+_i to xi+1x_{i+1} and −c(hi−+hi+)-c(h^-_i + h^+_i) to xix_i, with c=2βΔθ/Lˉc = 2\beta\Delta\theta/\bar L, which is line L7. The term holds for every motion of the vertices that are not in the two end edges, which is the setting of a rod clamped at both ends. With Steps 2 and 5, lines L5 to L7 return −∇E-\nabla E. □\square

Step 6: the quasistatic twist energy

With the material angles θ0,…,θn−1\theta^0, \dots, \theta^{n-1} of the edges measured from the Bishop frame and the end angles fixed by the clamps, the discrete twist energy is ∑iβmi2/lˉi\sum_i \beta m_i^2/\bar l_i with mi=θi−θi−1m_i = \theta^i - \theta^{i-1} and ∑imi=Δθ\sum_i m_i = \Delta\theta. By the Cauchy-Schwarz inequality, Δθ2=(∑imi)2≤(∑imi2/lˉi)(∑ilˉi)\Delta\theta^2 = (\sum_i m_i)^2 \le (\sum_i m_i^2/\bar l_i)(\sum_i \bar l_i), with equality exactly when mim_i is proportional to lˉi\bar l_i. So the minimum over the interior angles is βΔθ2/Lˉ\beta\Delta\theta^2/\bar L, the term EtE_t. It depends on the centerline only through Δθ\Delta\theta, so Step 5 gives the gradient of the minimized energy. □\square

Step 7: rigid motions, net force and torque

All the terms use only lengths, dot products and cross products of edges, and Δθ\Delta\theta is an angle between vectors that move with the rod. Under x↦Qx+tx \mapsto Qx + t with a rotation QQ, applied also to u0u^0 and dendd_{end}, the transports satisfy P(Qt1,Qt2)=QP(t1,t2)QTP(Qt_1, Qt_2) = QP(t_1, t_2)Q^T, so the Bishop frame and Δθ\Delta\theta are unchanged, and so is EE. EE does not change under a translation of all vertices, so its gradients sum to zero; it does not change under a small rotation δxk=w×xk\delta x_k = w \times x_k, so ∑kxk×∇kE=0\sum_k x_k \times \nabla_k E = 0. For a free rod (the terms of lines L5 and L6) the net force and the net torque are therefore zero. A straight rod has κbi=0\kappa b_i = 0 at every vertex, so lines L6 and L7 add nothing and a straight rod at its rest lengths feels no force, for every twist. ■\blacksquare

Complexity

Each line touches each edge or vertex a constant number of times, so one step costs Θ(n)\Theta(n) time. Line L4 needs the whole transport of line L3, which is also Θ(n)\Theta(n). Memory is Θ(n)\Theta(n) for the positions, the velocities, the rest lengths and the frames. An implicit step needs the Hessian, which is banded with a constant band width, so a direct banded solve also costs Θ(n)\Theta(n) per Newton iteration. An explicit step is cheap but its stable time step shrinks with the edge length: for bending, the highest frequency grows like 1/h21/h^2 for edge length hh.

Properties

  • Frame invariant. A rigid motion of the rod and of both clamps does not change the energy or the twist. This is proved.
  • Exact forces. The forces are the exact gradient, including the coupling of twist and bending through the holonomy. This is proved.
  • No holonomy in a plane. For a planar rod, Δθ\Delta\theta depends only on the clamps. This is proved (a planar rod transports the plane normal to itself).
  • Bending stiffness. For a small turn φ\varphi at a vertex between edges of length hh, ∣κb∣2≈φ2|\kappa b|^2 \approx \varphi^2 and the discrete energy is αφ2/(2h)\alpha\varphi^2/(2h), the energy 12EIκ2h\frac12 EI\kappa^2 h of a beam with κ=φ/h\kappa = \varphi/h, so α=EI\alpha = EI. This is a proved limit.
  • First order convergence of a cantilever. A rod of length 0.9 m, clamped at one end, with α=1\alpha = 1 N m² under a load of 0.1 N/m, has the tip deflection 0.0082 m by Euler-Bernoulli beam theory. The rod settles at 0.0118 m with 5 free edges and at 0.0099 m with 10, so the error falls by about half when hh halves. This is a measurement on the test code.
  • Not a law. The rod model is the Kirchhoff model of an inextensible, unshearable rod. The penalty ksk_s of this page and the damping are tuning.

Variants and improvements

  • Natural curvature and anisotropy. Bergou et al. (2008) store the material curvatures (κb⋅m2,−κb⋅m1)(\kappa b \cdot m_2, -\kappa b \cdot m_1) in the material frame and compare them with their rest values, which gives curly hair and ribbons. The twist angles of the edges are then degrees of freedom, solved quasistatically or in time.
  • Time parallel reference frame. Bergou et al. (2010) carry the reference frame of each edge forward in time by parallel transport from its previous direction, not along the rod in space. This keeps each update local and avoids the Θ(n)\Theta(n) dependence of the twist on the far end.
  • Inextensibility. The paper projects the vertex positions onto constant edge lengths after each step. Position based dynamics uses a similar projection.
  • Cosserat rods. A Cosserat rod also allows stretching and shearing, with an independent frame at each point.
  • Frames. The Bishop frame is a rotation minimizing frame, and the double reflection method computes a similar frame on sampled curves. The Frenet frame is undefined where the curve is straight, so it is not used.

When to use it

Use discrete elastic rods for hair, fur, cables, ropes, knots and threads, where twist matters and the rod is thin enough that it does not shear. For many hairs, use the reduced cost variants with the time parallel reference frame and an implicit solver. If twist does not matter, a chain of springs with bending springs, as in a mass spring system, is simpler. For thick or soft rods that stretch and shear, use a Cosserat rod model.

Pitfalls

  • Using the turning angle as the curvature. Line L2 uses 2tan⁡(φ/2)2\tan(\varphi/2), not φ\varphi. Mixing the two changes the energy at large turns and breaks the gradient of line L6.
  • Dropping the holonomy. With line L7 missing, the twist of a clamped rod never makes it bend, and a twisted cable never forms loops. The forces are then not the gradient of the energy.
  • Wrapping the twist. The angle of line L4 is only known modulo 2π2\pi. Taking it in (−π,π](-\pi, \pi] at each step loses full turns; keep the value nearest to the previous one.
  • Transport between opposite tangents. Line L3 divides by 1+tj−1⋅tj1 + t^{j-1} \cdot t^j, which is zero when the rod folds back on itself. Keep the time step small enough that no vertex turns by close to 180 degrees.
  • Moving the clamped edges. The twist force of line L7 assumes that the first and the last edges are fixed. If an end is free, the quasistatic twist is zero and line L7 must be left out.
  • Too large a time step. Line L8 is explicit, and bending is stiff on short edges. Halving the edge length needs about a quarter of the time step.

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
discrete_elastic_rods.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-elastic-rods/. The authors are listed in prov/56ZBR0.jsonl.
"""Discrete elastic rods (Bergou et al. 2008), isotropic and straight at rest.

The rod is a polyline x_0, ..., x_n in 3D with edges e^j = x_(j+1) - x_j.
At an interior vertex i the curvature binormal is

    kb_i = 2 e^(i-1) x e^i / (|e^(i-1)| |e^i| + e^(i-1) . e^i),

with |kb_i| = 2 tan(phi_i / 2) for the turning angle phi_i. The energy is

    E = sum_j (k_s / 2) |e_bar^j| (|e^j| / |e_bar^j| - 1)^2       stretching (a penalty)
      + sum_i alpha |kb_i|^2 / l_bar_i                             bending
      + beta (delta_theta)^2 / L_bar                              twisting

with l_bar_i = |e_bar^(i-1)| + |e_bar^i|, L_bar = sum_i l_bar_i, and e_bar the
rest edges. The twist term is the quasistatic twist of Bergou et al.: the
material frame of the interior edges is at its energy minimum, so the twist
spreads in proportion to l_bar_i. delta_theta is the angle about the last
tangent from the Bishop frame (the frame of edge 0 carried along the curve by
parallel transport) to the clamped material director d_end. It changes when
the centerline moves because of the holonomy of parallel transport.

With this l_bar the bending stiffness alpha equals EI of a beam, and beta is
the twisting stiffness GJ. Units: SI; alpha and beta in N m^2, k_s in N.
"""

import math

from anim import add, cross, dot, norm, scale, sub


def curvature_binormal(a, b):
    """kb = 2 a x b / (|a| |b| + a . b) for consecutive edges a and b."""
    den = norm(a) * norm(b) + dot(a, b)
    if den <= 0.0:
        raise ValueError("the rod folds back on itself")
    return scale(cross(a, b), 2.0 / den)


def _skew(v):
    return [[0.0, -v[2], v[1]], [v[2], 0.0, -v[0]], [-v[1], v[0], 0.0]]


def grad_kb(a, b):
    """Return (Ga, Gb), the 3 by 3 Jacobians of kb with respect to a and b."""
    na, nb = norm(a), norm(b)
    den = na * nb + dot(a, b)
    kb = scale(cross(a, b), 2.0 / den)
    da = add(scale(a, nb / na), b)
    db = add(scale(b, na / nb), a)
    sa, sb = _skew(a), _skew(b)
    ga = [[(-2.0 * sb[r][c] - kb[r] * da[c]) / den for c in range(3)] for r in range(3)]
    gb = [[(2.0 * sa[r][c] - kb[r] * db[c]) / den for c in range(3)] for r in range(3)]
    return ga, gb


def parallel_transport(t1, t2, v):
    """Rotate v by the smallest rotation that takes the unit vector t1 to t2."""
    c = dot(t1, t2)
    if c <= -1.0 + 1e-12:
        raise ValueError("parallel transport is undefined between opposite tangents")
    b = cross(t1, t2)
    return add(add(scale(v, c), cross(b, v)), scale(b, dot(b, v) / (1.0 + c)))


def _unit(v):
    n = norm(v)
    return (v[0] / n, v[1] / n, v[2] / n)


def bishop_frames(x, u0):
    """The first director u^j of each edge, by parallel transport of u0 from edge 0."""
    t = [_unit(sub(x[j + 1], x[j])) for j in range(len(x) - 1)]
    u = [tuple(u0)]
    for j in range(1, len(t)):
        u.append(parallel_transport(t[j - 1], t[j], u[-1]))
    return u, t


def twist_angle(x, u0, d_end, near=0.0):
    """delta_theta: the angle about the last tangent from u^(n-1) to d_end.

    The angle is defined modulo 2 pi; the value nearest to near is returned,
    so a caller that follows the motion in small steps can count full turns.
    """
    u, t = bishop_frames(x, u0)  # @line L3
    un, tn = u[-1], t[-1]
    ang = math.atan2(dot(cross(un, d_end), tn), dot(un, d_end))  # @line L4
    return ang + 2.0 * math.pi * round((near - ang) / (2.0 * math.pi))


class Rod:
    """Rest data of a rod that is straight at rest."""

    def __init__(self, rest, alpha, beta, ks, density=1.0):
        self.rest = [tuple(map(float, p)) for p in rest]
        n = len(rest) - 1
        if n < 2:
            raise ValueError("a rod needs at least two edges")
        self.rest_len = [norm(sub(rest[j + 1], rest[j])) for j in range(n)]
        for i in range(1, n):
            if norm(curvature_binormal(sub(rest[i], rest[i - 1]), sub(rest[i + 1], rest[i]))) > 1e-9:
                raise ValueError("this implementation supports rods that are straight at rest")
        self.lbar = [0.0] + [self.rest_len[i - 1] + self.rest_len[i] for i in range(1, n)]
        self.Lbar = sum(self.lbar)
        self.alpha, self.beta, self.ks = alpha, beta, ks
        self.mass = [0.0] * (n + 1)
        for j in range(n):
            self.mass[j] += 0.5 * density * self.rest_len[j]
            self.mass[j + 1] += 0.5 * density * self.rest_len[j]


def energy(rod, x, u0=None, d_end=None, near=0.0):
    """Total elastic energy; the twist term is used only when u0 and d_end are given."""
    n = len(x) - 1
    e = [sub(x[j + 1], x[j]) for j in range(n)]
    tot = 0.0
    for j in range(n):
        s = norm(e[j]) / rod.rest_len[j] - 1.0
        tot += 0.5 * rod.ks * rod.rest_len[j] * s * s
    for i in range(1, n):
        kb = curvature_binormal(e[i - 1], e[i])
        tot += rod.alpha * dot(kb, kb) / rod.lbar[i]
    if d_end is not None:
        th = twist_angle(x, u0, d_end, near)
        tot += rod.beta * th * th / rod.Lbar
    return tot


def forces(rod, x, twist=0.0):
    """Return -dE/dx for the rod, with delta_theta = twist held by clamped ends.

    The twist term uses the holonomy gradient, which needs the first and the
    last edge to be fixed; pass twist = 0.0 for a rod with a free end.
    Cost Theta(n).
    """
    n = len(x) - 1
    f = [[0.0, 0.0, 0.0] for _ in x]
    e = [sub(x[j + 1], x[j]) for j in range(n)]  # @line L1
    for j in range(n):  # @line L5
        le = norm(e[j])
        g = scale(e[j], rod.ks * (le / rod.rest_len[j] - 1.0) / le)
        for k in range(3):
            f[j][k] += g[k]
            f[j + 1][k] -= g[k]
    c_twist = 2.0 * rod.beta * twist / rod.Lbar
    for i in range(1, n):
        kb = curvature_binormal(e[i - 1], e[i])  # @line L2
        ga, gb = grad_kb(e[i - 1], e[i])
        c = 2.0 * rod.alpha / rod.lbar[i]
        # dkb/dx_(i-1) = -Ga, dkb/dx_i = Ga - Gb, dkb/dx_(i+1) = Gb
        wa = [c * sum(ga[r][k] * kb[r] for r in range(3)) for k in range(3)]  # @line L6
        wb = [c * sum(gb[r][k] * kb[r] for r in range(3)) for k in range(3)]
        h_prev = scale(kb, 1.0 / (2.0 * norm(e[i - 1])))  # @line L7
        h_next = scale(kb, -1.0 / (2.0 * norm(e[i])))
        for k in range(3):
            f[i - 1][k] += wa[k]
            f[i][k] -= wa[k] - wb[k]
            f[i + 1][k] -= wb[k]
            # d(delta_theta)/dx = -d(holonomy)/dx, so the force is +c_twist d(holonomy)/dx
            f[i - 1][k] += c_twist * h_prev[k]
            f[i + 1][k] += c_twist * h_next[k]
            f[i][k] -= c_twist * (h_prev[k] + h_next[k])
    return [tuple(p) for p in f]


def step(rod, x, v, dt, fixed=(), gravity=(0.0, 0.0, 0.0), damping=0.0, u0=None, d_end=None, twist=0.0):
    """One symplectic Euler step; return (x, v, twist).

    If u0 and d_end are given, the first and last edges must be in fixed.
    The twist of the current centerline is measured first, unwrapped near the
    value passed in, and returned for the next call. The velocity damping
    v <- (1 - damping dt) v is a tuning value, not part of the method.
    """
    if d_end is not None:
        twist = twist_angle(x, u0, d_end, near=twist)
    f = forces(rod, x, twist if d_end is not None else 0.0)
    fixed = set(fixed)
    xn, vn = [], []
    for i in range(len(x)):  # @line L8
        if i in fixed:
            xn.append(x[i])
            vn.append((0.0, 0.0, 0.0))
            continue
        w = tuple((1.0 - damping * dt) * (v[i][k] + dt * (f[i][k] / rod.mass[i] + gravity[k])) for k in range(3))
        vn.append(w)
        xn.append(add(x[i], scale(w, dt)))
    return xn, vn, twist
test_discrete_elastic_rods.py 235 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/discrete-elastic-rods/. The authors are listed in prov/56ZBR0.jsonl.
"""Tests of discrete elastic rods (isotropic, straight at rest).

The forces are compared with central differences of the energy, for the
bending and stretching terms on free rods and for the twist term through
the holonomy on rods with clamped ends. Further tests: the length of the
curvature binormal, a planar rod has no holonomy, rigid motions keep the
energy, the quasistatic twist is the minimum over the interior angles, and
a cantilever approaches beam theory as the rod is refined.
"""

import math
import random

import anim
from discrete_elastic_rods import (Rod, bishop_frames, curvature_binormal, energy, forces, parallel_transport,
                                   step, twist_angle)


def straight(n, h=0.2):
    return [(h * i, 0.0, 0.0) for i in range(n + 1)]


def jitter(rng, pts, amount, keep=()):
    out = []
    for i, p in enumerate(pts):
        if i in keep:
            out.append(p)
        else:
            out.append(tuple(c + rng.uniform(-amount, amount) for c in p))
    return out


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


def unflat(z):
    return [tuple(z[3 * i:3 * i + 3]) for i in range(len(z) // 3)]


def test_curvature_binormal_length_and_direction():
    rng = random.Random(1)
    for _ in range(200):
        a = tuple(rng.uniform(-1, 1) for _ in range(3))
        b = tuple(rng.uniform(-1, 1) for _ in range(3))
        phi = math.acos(max(-1.0, min(1.0, anim.dot(a, b) / (anim.norm(a) * anim.norm(b)))))
        if phi > 3.0:
            continue
        kb = curvature_binormal(a, b)
        assert abs(anim.norm(kb) - 2.0 * math.tan(phi / 2.0)) < 1e-9 * (1 + anim.norm(kb))
        assert abs(anim.dot(kb, a)) < 1e-9 and abs(anim.dot(kb, b)) < 1e-9
    assert anim.norm(curvature_binormal((1, 0, 0), (2, 0, 0))) == 0.0


def test_parallel_transport_is_a_rotation_taking_t1_to_t2():
    rng = random.Random(2)
    for _ in range(200):
        t1 = anim.normalize(tuple(rng.uniform(-1, 1) for _ in range(3)))
        t2 = anim.normalize(tuple(rng.uniform(-1, 1) for _ in range(3)))
        if anim.dot(t1, t2) < -0.9:
            continue
        assert anim.norm(anim.sub(parallel_transport(t1, t2, t1), t2)) < 1e-12
        b = anim.cross(t1, t2)
        v = tuple(rng.uniform(-1, 1) for _ in range(3))
        w = parallel_transport(t1, t2, v)
        assert abs(anim.norm(w) - anim.norm(v)) < 1e-12
        if anim.norm(b) > 1e-6:
            assert abs(anim.dot(w, b) - anim.dot(v, b)) < 1e-12


def test_bend_and_stretch_force_is_minus_gradient():
    rng = random.Random(3)
    rod = Rod(straight(6), alpha=1.3, beta=0.7, ks=40.0)
    for _ in range(10):
        x = jitter(rng, rod.rest, 0.08)
        f = forces(rod, x, twist=0.0)
        g = anim.num_grad(lambda z: energy(rod, unflat(z)), flat(x))
        s = max(map(abs, g))
        for a, b in zip(flat(f), g):
            assert abs(a + b) <= 1e-6 * s


def test_twist_force_through_holonomy_is_minus_gradient():
    rng = random.Random(4)
    n = 7
    rod = Rod(straight(n), alpha=0.0, beta=0.9, ks=0.0)
    u0 = (0.0, 1.0, 0.0)
    clamped = {0, 1, n - 1, n}
    for k in range(10):
        x = jitter(rng, rod.rest, 0.1, keep=clamped)
        d_end = (0.0, math.cos(0.5 * k), math.sin(0.5 * k))
        tw = twist_angle(x, u0, d_end)
        f = forces(rod, x, twist=tw)
        free = [i for i in range(n + 1) if i not in clamped]

        def e_free(z):
            y = list(x)
            for j, i in enumerate(free):
                y[i] = tuple(z[3 * j:3 * j + 3])
            return energy(rod, y, u0, d_end, near=tw)

        g = anim.num_grad(e_free, [c for i in free for c in x[i]])
        got = [c for i in free for c in f[i]]
        s = max(map(abs, g))
        assert s > 1e-3
        for a, b in zip(got, g):
            assert abs(a + b) <= 1e-6 * s


def test_full_force_with_clamped_twist_is_minus_gradient():
    rng = random.Random(5)
    n = 6
    rod = Rod(straight(n), alpha=0.8, beta=1.1, ks=30.0)
    u0 = (0.0, 0.0, 1.0)
    clamped = {0, 1, n - 1, n}
    x = jitter(rng, rod.rest, 0.07, keep=clamped)
    d_end = (0.0, -math.sin(2.0), math.cos(2.0))
    tw = twist_angle(x, u0, d_end, near=2.0 + 2 * math.pi)
    assert tw > 2 * math.pi
    f = forces(rod, x, twist=tw)
    free = [i for i in range(n + 1) if i not in clamped]

    def e_free(z):
        y = list(x)
        for j, i in enumerate(free):
            y[i] = tuple(z[3 * j:3 * j + 3])
        return energy(rod, y, u0, d_end, near=tw)

    g = anim.num_grad(e_free, [c for i in free for c in x[i]])
    s = max(map(abs, g))
    for a, b in zip([c for i in free for c in f[i]], g):
        assert abs(a + b) <= 1e-6 * s


def test_planar_rod_has_no_holonomy():
    rng = random.Random(6)
    for _ in range(20):
        x = [(0.2 * i + rng.uniform(-0.05, 0.05), rng.uniform(-0.1, 0.1), 0.0) for i in range(8)]
        u, _ = bishop_frames(x, (0.0, 0.0, 1.0))
        for v in u:
            assert anim.norm(anim.sub(v, (0.0, 0.0, 1.0))) < 1e-12
        assert abs(twist_angle(x, (0.0, 0.0, 1.0), (0.0, 0.0, 1.0))) < 1e-12


def test_rigid_motion_keeps_energy_and_rotates_forces():
    rng = random.Random(7)
    n = 6
    rod = Rod(straight(n), alpha=1.0, beta=1.0, ks=20.0)
    u0 = (0.0, 1.0, 0.0)
    clamped = {0, 1, n - 1, n}
    x = jitter(rng, rod.rest, 0.1, keep=clamped)
    d_end = (0.0, math.cos(0.8), math.sin(0.8))
    tw = twist_angle(x, u0, d_end)
    q = anim.q_to_mat3(anim.q_from_axis_angle((0.3, -1.0, 0.5), 1.1))
    t = (0.4, -2.0, 1.0)
    y = [anim.add(anim.matvec(q, p), t) for p in x]
    tw2 = twist_angle(y, anim.matvec(q, u0), anim.matvec(q, d_end), near=tw)
    assert abs(tw2 - tw) < 1e-12
    assert abs(energy(rod, x, u0, d_end) - energy(rod, y, anim.matvec(q, u0), anim.matvec(q, d_end))) < 1e-12
    fx, fy = forces(rod, x, tw), forces(rod, y, tw2)
    for a, b in zip(fx, fy):
        assert anim.norm(anim.sub(anim.matvec(q, a), b)) < 1e-10


def test_straight_rod_has_no_force_even_when_twisted():
    rod = Rod(straight(5), alpha=1.0, beta=1.0, ks=10.0)
    for tw in (0.0, 1.0, 7.0):
        f = forces(rod, rod.rest, twist=tw)
        assert max(abs(c) for p in f for c in p) < 1e-14
    assert abs(energy(rod, rod.rest, (0, 1, 0), (0, 0, 1)) - rod.beta * (math.pi / 2) ** 2 / rod.Lbar) < 1e-12


def test_free_rod_net_force_and_torque_are_zero():
    rng = random.Random(8)
    rod = Rod(straight(7), alpha=1.0, beta=1.0, ks=25.0)
    x = jitter(rng, rod.rest, 0.1)
    f = forces(rod, x)
    net = [sum(p[k] for p in f) for k in range(3)]
    torque = [0.0, 0.0, 0.0]
    for p, fp in zip(x, f):
        torque = list(anim.add(torque, anim.cross(p, fp)))
    assert max(map(abs, net)) < 1e-10 and max(map(abs, torque)) < 1e-10


def test_quasistatic_twist_is_the_minimum_over_interior_angles():
    rng = random.Random(9)
    lbar = [rng.uniform(0.2, 0.6) for _ in range(6)]
    beta, total = 0.7, 2.3

    def e(theta):
        return sum(beta * (theta[i + 1] - theta[i]) ** 2 / lbar[i] for i in range(len(lbar)))

    theta = [0.0] + [rng.uniform(-3, 3) for _ in range(len(lbar) - 1)] + [total]
    for _ in range(2000):
        for i in range(1, len(theta) - 1):
            a, b = lbar[i - 1], lbar[i]
            theta[i] = (theta[i - 1] / a + theta[i + 1] / b) / (1.0 / a + 1.0 / b)
    assert abs(e(theta) - beta * total ** 2 / sum(lbar)) < 1e-10


def test_twisted_clamped_rod_settles_straight():
    rng = random.Random(10)
    n = 6
    rod = Rod(straight(n), alpha=1.0, beta=1.0, ks=50.0)
    clamped = [0, 1, n - 1, n]
    x = jitter(rng, rod.rest, 0.05, keep=set(clamped))
    v = [(0.0, 0.0, 0.0)] * (n + 1)
    u0, d_end = (0.0, 1.0, 0.0), (0.0, math.cos(1.0), math.sin(1.0))
    tw = twist_angle(x, u0, d_end, near=1.0)
    e0 = energy(rod, x, u0, d_end, near=tw)
    for _ in range(3000):
        x, v, tw = step(rod, x, v, 0.002, fixed=clamped, damping=5.0, u0=u0, d_end=d_end, twist=tw)
    assert max(abs(c) for i in range(n + 1) for c in anim.sub(x[i], rod.rest[i])) < 1e-4
    assert abs(tw - 1.0) < 1e-6
    assert energy(rod, x, u0, d_end, near=tw) < e0


def cantilever_tip(n, dt, steps):
    h = 0.9 / (n - 1)
    rod = Rod([(h * (i - 1), 0.0, 0.0) for i in range(n + 1)], alpha=1.0, beta=1.0, ks=200.0)
    x, v = list(rod.rest), [(0.0, 0.0, 0.0)] * (n + 1)
    for _ in range(steps):
        x, v, _ = step(rod, x, v, dt, fixed=[0, 1], gravity=(0.0, -0.1, 0.0), damping=3.0)
    return x[-1][1]


def test_cantilever_converges_to_beam_theory():
    beam = -0.1 * 0.9 ** 4 / 8.0
    coarse = cantilever_tip(6, 0.004, 2500) - beam
    fine = cantilever_tip(11, 0.002, 3500) - beam
    assert coarse < 0.0 and fine < 0.0
    assert abs(fine) < 0.25 * abs(beam)
    assert 1.5 < coarse / fine < 2.6

History

Kirchhoff's rod theory of the 19th century describes an inextensible rod by its bending and twisting, and Cosserat rods (1909) add stretching and shearing. In graphics, hair was long simulated with chains of springs or of rigid links. Bergou, Wardetzky, Robinson, Audoly and Grinspun (2008) built a discrete rod from discrete differential geometry: the curvature binormal, the Bishop frame and its holonomy, with forces that are exact gradients. Bergou, Audoly, Vouga, Wardetzky and Grinspun (2010) changed the reference frame to one carried in time and added viscous threads.

References

  1. Miklós Bergou, Max Wardetzky, Stephen Robinson, Basile Audoly and Eitan Grinspun, Discrete elastic rods, ACM Transactions on Graphics 27(3), article 63 (SIGGRAPH 2008), the curvature binormal, the Bishop frame, the quasistatic twist and the gradient of the holonomy (general locator)
  2. Miklós Bergou, Basile Audoly, Etienne Vouga, Max Wardetzky and Eitan Grinspun, Discrete viscous threads, ACM Transactions on Graphics 29(4) (SIGGRAPH 2010), the reference frame carried by parallel transport in time (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.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
  • at least three sources
  • a scene preset for the example