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
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- 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
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 , the edges , and the rest edges . This page treats an isotropic rod that is straight at rest, with the bending stiffness (EI, in N m²), the twisting stiffness (GJ, in N m²), and a stretching penalty in N. The rod is clamped at both ends: the first two and the last two vertices are fixed, the material director of edge 0 is given, and the material director of the last edge is given. The output is the force on every vertex and a time step.
The energy is
with and . The last term is the quasistatic twist: the material frames of the interior edges are at their minimum, so the total twist spreads along the rod in proportion to . is the angle about the last tangent from the Bishop director to . 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 differ between conventions. With the above, equals the EI of a beam (see Properties).
The algorithm
DER-STEP(x, v, Δθ_prev, Δt) ▷ u^0, d_end, l̄_i, L̄ fixed; ends clamped- 1
e^j ← x_(j+1) - x_j for each edge j - 2
κb_i ← 2 e^(i-1) × e^i / (|e^(i-1)||e^i| + e^(i-1)·e^i) for each interior vertex i - 3
u^j ← P(t^(j-1) → t^j) u^(j-1) for j = 1, ..., n-1 ▷ parallel transport - 4
Δθ ← signed angle from u^(n-1) to d_end about t^(n-1), nearest to Δθ_prev - 5
f ← -∇E_stretch - 6
f_k ← f_k - (2α / l̄_i) (∂κb_i/∂x_k)^T κb_i for k = i-1, i, i+1, each interior i - 7
f_k ← f_k + (2βΔθ / L̄) ∇_k ψ_i for k = i-1, i, i+1, each interior i - 8
v ← v + Δt M^(-1) f, x ← x + Δt v on the free vertices return x, v, Δθ
Line L3 uses the minimal rotation , with , and . Line L4 counts full turns by taking the angle nearest to the value of the previous step. Line L6 uses the Jacobians of with respect to the two edges and ,
Line L7 is the twist force through the holonomy: , and . 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 , , , and in m, a straight rest shape with unit edges, N m², and . The rod turns by 90 degrees at each of the three interior vertices, and its last edge is parallel to its first. So m and m.
| Edge or vertex | Tangent | Bishop director | at the vertex after the edge | | |---|---|---|---|---| | edge 0 | | | | 2 | | edge 1 | | | | 2 | | edge 2 | | | | 2 | | edge 3 | | | none | none |
Each turn of 90 degrees gives , so the bending energy is J. The last edge points the same way as the first, but the Bishop director came back turned by 90 degrees: it is , not . This turn is the holonomy of the path. So the clamp is twisted by relative to the Bishop frame, and the twist energy is 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 . These are proved properties.
- for the turning angle , and is perpendicular to both edges.
- Line L3 is the rotation about that takes to .
- The key step. Write the transport as the product of two reflections, with the bisector of and . Then the rate at which a variation turns the transported frame about the tangent is at each vertex. Summed along the rod this is the holonomy, and it gives the formulas of line L7.
- The quasistatic twist energy is the minimum of 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 and 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 and the edges with unit tangents . At an interior vertex the edges and meet, and we assume , so the rod does not fold back. is the skew matrix with . The energy is with
Step 1: the curvature binormal
. It is perpendicular to and . With the turning angle between and , and , so .
Step 2: lines L5 and L6 give
For one edge, , and , so the force is on and on , as in line L5.
Write with and . Then and . By the quotient rule,
Since and , , and . The term has , so its gradient for vertex is . Line L6 adds minus this to the three vertices.
Step 3: parallel transport is the rotation of line L3
For unit , with and for a unit axis , Rodrigues' formula gives the rotation about by as . With and this is , the formula of the code. It maps to and fixes . is also the product of the reflections with : maps to , maps to , both fix , and the product of two reflections is the rotation about the line where their planes meet, by twice the angle between them, which is .
Step 4: the variation of the twist (the holonomy)
Let the vertices move smoothly, with the first and the last edges fixed, and write for the derivative. Let be the Bishop director of edge and , and let , the rate at which turns about . Since edge 0 is fixed, is fixed and .
From and (a rotation keeps the cross product),
is skew, say , and , so .
Now compute for (Step 3, with and ). For a unit , and . So . For a reflection , , so , and
With , , and , where the projection drops out because . So , because for unit tangents. Summing from ,
The last edge and are fixed, and , turn together about at the rate . Line L4 measures with , so . The unwrapping to the value nearest the previous one adds a constant multiple of , which does not change the derivative.
Finally, and , so and . With and , the interior vertex contributes to , to and to , and is the sum of these contributions over all interior vertices.
Step 5: line L7 gives
. By Step 4 the force adds to , to and to , with , 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 .
Step 6: the quasistatic twist energy
With the material angles of the edges measured from the Bishop frame and the end angles fixed by the clamps, the discrete twist energy is with and . By the Cauchy-Schwarz inequality, , with equality exactly when is proportional to . So the minimum over the interior angles is , the term . It depends on the centerline only through , so Step 5 gives the gradient of the minimized energy.
Step 7: rigid motions, net force and torque
All the terms use only lengths, dot products and cross products of edges, and is an angle between vectors that move with the rod. Under with a rotation , applied also to and , the transports satisfy , so the Bishop frame and are unchanged, and so is . does not change under a translation of all vertices, so its gradients sum to zero; it does not change under a small rotation , so . 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 at every vertex, so lines L6 and L7 add nothing and a straight rod at its rest lengths feels no force, for every twist.
Complexity
Each line touches each edge or vertex a constant number of times, so one step costs time. Line L4 needs the whole transport of line L3, which is also . Memory is 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 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 for edge length .
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, depends only on the clamps. This is proved (a planar rod transports the plane normal to itself).
- Bending stiffness. For a small turn at a vertex between edges of length , and the discrete energy is , the energy of a beam with , so . This is a proved limit.
- First order convergence of a cantilever. A rod of length 0.9 m, clamped at one end, with 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 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 of this page and the damping are tuning.
Variants and improvements
- Natural curvature and anisotropy. Bergou et al. (2008) store the material curvatures 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 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 , not . 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 . Taking it in at each step loses full turns; keep the value nearest to the previous one.
- Transport between opposite tangents. Line L3 divides by , 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.
# 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 56ZBR0 Edit this page History Report an error Markdown