Algorithmadvanced
Invertible finite elements
Also called diagonalized invertible FEM.
Compute stresses in the diagonal space of the SVD of the deformation gradient, with a modified model, so that inverted elements recover their shape.
- Time
- Θ(n + m) explicit_stepΘ(m) forces_per_step
- Space
- Θ(n + m) extra
- Where
- m = the number of elements; n = the number of nodes
- Model
- Real RAM
- Properties
- deterministicnot exactiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Geoffrey Irving, Joseph Teran, Ronald Fedkiw, 2004
Invertible finite elements compute the elastic force of each element in a frame where its deformation is diagonal, so that the force stays finite and points back to the rest shape even when the element is flat or turned inside out. Each deformation gradient is written as with rotations and and a diagonal whose smallest entry is negative when the element is inverted. The stress of an isotropic model is diagonal in this frame, , and the model is changed below a compression threshold so that is defined for every . Irving, Teran and Fedkiw (2004) gave the method for tetrahedra, and the same steps work for triangles in 2D.
In plain words
In a simulation with many small triangles or tetrahedra, some elements get crushed flat or pushed through themselves. Many material models have no answer there: their energy goes to infinity, or their force pushes the element further inside out. This method first finds two turns, one before and one after the stretch, that make the stretch of the element a plain scaling along two or three axes. If the element is inside out, it marks this by making the smallest scaling negative. It then asks the material model only about these scalings, and it changes the model where the scaling gets very small, so that the push back stays finite. At last it turns the answer back into the world. So every element gets a sensible force, and a crushed element unfolds again.
The problem
The input is a mesh of triangles (in 2D) or tetrahedra (in 3D) with rest positions , current positions , and an isotropic hyperelastic model with the Lamé parameters and . Each element has the rest edge matrix with , the current edge matrix , , and the rest area . The output is the elastic force on every node.
The force must be finite and must push toward the rest shape for every , including elements with . It must be rotation invariant, and where the element is not too compressed it must agree with the chosen model. A model such as the neo-Hookean model has the energy term with , which is undefined for . The St. Venant-Kirchhoff model is defined there, but its force can keep an inverted element inverted.
This page gives the method in 2D. It uses two diagonal models: the corotated model , which the paper calls the rotated linear model, and the neo-Hookean model .
The algorithm
INVERTIBLE-FORCES(x, c) ▷ D_m^(-1) and B_m = -V_0 D_m^(-T) precomputed per element, c > 0- 1
f ← 0 on every node - 2
for each element e with nodes a_0, a_1, a_2 do - 3
F ← D_s D_m^(-1) - 4
(U, σ, V) ← signed SVD of F with det U = det V = +1, σ_1 ≥ |σ_2| - 5
σ̃_i ← max(σ_i, c) for each i - 6
P̂ ← P̂(σ̃) + J(σ̃)(σ - σ̃) ▷ J is the Jacobian of P̂; the identity when σ̃ = σ - 7
P ← U diag(P̂) V^T - 8
G ← P B_m ▷ the forces on a_1 and a_2 as columns - 9
f_(a_k) ← f_(a_k) + G_k for k = 1, 2, and f_(a_0) ← f_(a_0) - G_1 - G_2 return f
Line L4 is the key step. In 2D it has a closed form: with , , and , set , , and . Then and with and . Since , is negative exactly when the element is inverted. In 3D, Irving et al. take an SVD from the eigenvectors of and then fix the signs: if they negate a column of , and if they negate the smallest entry of and its column of .
Lines L5 and L6 change the model below the threshold : they replace the stress by its first order Taylor expansion about the clamped point. The paper describes this choice as linearizing the model at a compression limit, or clamping the stress, and gives no value of ; the value is a tuning choice. For the corotated model the stress is affine, so lines L5 and L6 change nothing. Line L8 is the force formula of Section 4 of the paper. Any time integrator can use these forces; the test code uses symplectic Euler with velocity damping.
Example
Take one triangle with the rest nodes , and in m, Pa and , so N/m and N/m, and . The table uses the six-place values N/m and N/m, as the tests do, so its last digits can differ from the exact values by a few units (the extended neo-Hookean at is with the exact and ). Nodes 0 and 1 stay in place, and node 2 moves down.
| Node 2 at | plain neo-Hookean | extended neo-Hookean | force on node 2, extended neo-Hookean (N) | force on node 2, corotated (N) | ||
|---|---|---|---|---|---|---|
| 1 | 0 | 0 | ||||
| 0.5 | ||||||
| 0.1 | ||||||
| 0 | undefined | |||||
| undefined | ||||||
| undefined |
Above the threshold the extended and the plain stresses agree. Below it the plain neo-Hookean stress grows without bound and is undefined at and past the flat state, while the extended stress continues along a straight line. In every row the force on node 2 points up, so it unfolds the triangle, also when the triangle is flat or inverted. In the last row is not diagonal, and the signed SVD finds the rotations; the negative entry is still the one of smallest magnitude. That force also has a part along , because the diagonal frame is turned; the damped run of the test code still brings node 2 back to .
Correctness
The proof shows these facts, each a proved property.
- Line L4 gives with rotations , , , and exactly when .
- When , the stress of line L7 does not depend on which such SVD is used, so it is a function of . It is rotation equivariant: for rotations and , and it is zero at every rotation.
- The extension of lines L5 and L6 is finite for every and has continuous first derivatives at .
- For the corotated model, the force is the exact negative gradient of with and , for inverted elements too. In 2D this energy is , smooth wherever .
- For the neo-Hookean model, the force is the exact negative gradient of the neo-Hookean energy while all . Below the extended force is not the gradient of any energy.
- The net force and the net torque of each element are zero for every diagonal , because is symmetric.
The key step is the sign rule of line L4: the rotations and carry no reflection, so the inversion shows up as a negative , where the diagonal model can see it and push against it.
Proof: The signed SVD is valid, the diagonal stress is well defined and rotation equivariant, and the forces are the negative gradient of the energy where the model is not extendedfull
We use the notation of the page, in 2D. is the rotation by the angle , and . For matrices, . An element has the rest edge matrix with , , and .
Step 1: line L4 gives a signed SVD
Write and set , , and . Then
with , , and . Put , , and . Since and ,
So with , and , and . As , . Also , so exactly when , and then is the entry of smallest magnitude.
Step 2: the stress of lines L5 to L7 does not depend on the choice of the SVD when
Let be any factorization with rotations , and , . By the identity of Step 1 it equals with and . A matrix of the form plus one of the form fixes both parts, because the two sets of matrices are complementary subspaces of the 2 by 2 matrices. So and , that is .
Now let , and let be a map of to a diagonal matrix that is symmetric in its two arguments. If , then and modulo , so and with . So and with the same sign , and . If , then , for one number by the symmetry, and . So is a function of alone on the set .
The set is the set of the matrices with a rotation , where . There is not fixed by , and the stress of the models below is not well defined. It is a set of measure zero, which this proof leaves out.
Step 3: rest, rotation equivariance and isotropy
At a rotation we have and , so , and both models give : no stress. For rotations and , has the signed SVD , and by Step 2. By Step 2, . This holds for every with , inverted or not.
Step 4: the extension below is , and it is finite for every
Line L5 sets with , and line L6 sets , where is the Jacobian of . The model is only evaluated at , so is finite for every , including . Where both , and .
Let and . Then is constant, so . For , , and . As the value tends to and both derivatives tend to and , the derivatives of from the other side. The same holds when both entries are below . So and its first derivatives are continuous, given that is on , as the neo-Hookean is. For the corotated model, is affine in , so for every .
Step 5: the two models agree with their usual stresses
Neo-Hookean. For the usual stress is with . With , , so . The diagonal entries are , the of the page. So where both , line L7 gives the usual neo-Hookean stress.
Corotated. Let , a rotation, and , symmetric, so . For this is the polar decomposition. Then and , so the energy is . In 2D, and , so
a smooth function of on the whole set , which contains inverted and flat elements. From , , and . So
This gradient is , which is what line L7 gives with the corotated .
Step 6: lines L8 and L9 give the negative gradient of the energy
Let at . Moving node by changes by , so and . So the gradient for node is column of , and line L8 sets , the negative gradient. Moving node 0 by is the same as moving the other nodes by and then translating, which does not change , so its force is minus the sum of the others, as in line L9. Summing over the elements, lines L1 to L9 return for .
With Step 5 this holds for the corotated model at every configuration with in each element, inverted or not, and for the neo-Hookean model when both in each element. Below the extended neo-Hookean stress is not the gradient of any function of : , but for , , and the two differ. So in that region the force is a finite, and rotation equivariant force, but not a conservative one.
Step 7: zero net force and zero net torque
In each element the forces of line L9 sum to 0 by construction. The torque of the element is the skew part of . With and , , which is symmetric because and are diagonal. So the torque is 0 for every diagonal , including the extension below .
Complexity
Each element costs a constant amount of work: a closed form SVD in 2D (in 3D, a 3 by 3 symmetric eigenproblem) and a few small matrix products. So the forces cost for elements, and an explicit step costs for nodes. Memory is : , and per element and the state per node. An implicit step also needs the stiffness, which in the diagonal frame splits into small blocks; see the variants.
Properties
- Defined everywhere but a thin set. The force is finite for every configuration, and it is a function of wherever . This is proved.
- Rotation invariant and isotropic. Rotating the world or the rest shape rotates the stress, and a rigid motion gives no force. This is proved.
- Same as the model where it matters. For the stress is the stress of the chosen model. This is proved.
- Not conservative below . The extended neo-Hookean force is not the gradient of an energy in the extended region, so an energy based integrator or a line search on the energy does not apply there. This is proved.
- Recovery. In the diagonal models of this page an inverted element is pushed back. That a mesh recovers from a given crushed state is a measurement: in the test code a triangle with node 2 at , a flat triangle, and a 2 by 2 grid with three inverted triangles all return to rest under damped symplectic Euler.
- A modelling choice. The change of the model below is a heuristic. It is not a law of physics, and Irving et al. note that most models lose accuracy long before inversion.
Variants and improvements
- Other diagonal models. Any isotropic model in terms of the singular values can be used, for example a model with a cubic spline between threshold values, which the paper uses for a volumetric Buddha model, or the corotated model, which needs no change at all.
- Definite stiffness. Teran, Sifakis, Irving and Fedkiw (2005) used the diagonal frame to split the stiffness of each element into small blocks and to make each block positive definite. This gives a robust implicit and quasistatic solver.
- Inversion-safe energies. The stable neo-Hookean model of Smith, de Goes and Kim (2018) is defined for inverted elements without any threshold, so its force stays the gradient of an energy.
- Anisotropy. For an anisotropic model is not diagonal. Section 6.1 of the paper rotates the anisotropic terms into the diagonal frame.
- Other discretizations. Projective dynamics projects each element onto rotations, and the material point method often applies a signed SVD to the deformation gradient of each particle.
When to use it
Use invertible elements whenever a mesh can be crushed: collisions with thin objects, coarse meshes of soft tissue, or large time steps. Use it with the corotated model if speed matters more than the response at large strain, and with an extended neo-Hookean or a similar model for rubbery materials. If an implicit solver needs a smooth energy everywhere, use the stable neo-Hookean model instead of a model with a threshold. For cloth and shells in 3D the triangles cannot invert, and the plain finite element method is enough.
Pitfalls
- Unsigned SVD. A standard SVD returns and lets or be a reflection. With line L4 written that way, an inverted element looks like an uninverted one, and the force keeps it inverted. Both and must be rotations.
- The wrong entry negated. In line L4 the negative entry must be the one of smallest magnitude. Negating another entry gives a valid factorization, but it asks for the long way back and gives large forces.
- Evaluating the model at . Without lines L5 and L6, the neo-Hookean takes of a negative number. A threshold of does not help, because the stress is infinite there.
- A threshold that is too small. For a small the slope of line L6 is very large, so the extended force is very stiff and an explicit step needs a much smaller .
- Treating the extended force as conservative. Below the force of line L6 is not the gradient of an energy. A Newton solver that checks the energy, or an energy diagnostic, gives wrong results there.
- Using as the polar rotation of an inverted element. For , is a rotation but is not positive definite, so it is not the polar decomposition of line L5 in corotational finite elements. The corotated force is correct with it; formulas that assume a positive are not.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
invertible_finite_elements.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/invertible-finite-elements/. The authors are listed in prov/8XGGPB.jsonl.
"""Invertible finite elements (Irving, Teran and Fedkiw 2004) on 2D triangles.
For each element, F = D_s D_m^(-1) is written as F = U F_hat V^T with
rotations U and V (det U = det V = +1) and F_hat = diag(s1, s2), where
s1 >= |s2| and s2 < 0 exactly when det F < 0. So an inverted element has one
negative entry, the one of smallest magnitude.
The stress of an isotropic model is diagonal in this frame:
P = U P_hat(F_hat) V^T. The force on the nodes 1 and 2 is G = P B_m with
B_m = -V0 D_m^(-T), and node 0 gets minus the sum.
Two diagonal models are given:
- corotated: P_hat_i = 2 mu (s_i - 1) + lambda sum_j (s_j - 1), the gradient
of mu sum (s_i - 1)^2 + (lambda / 2) (sum (s_i - 1))^2. It is defined for
every F, inverted or not.
- neo-Hookean: P_hat_i = mu s_i - mu / s_i + lambda log(s1 s2) / s_i, the
gradient of (mu / 2)(s1^2 + s2^2 - 2) - mu log J + (lambda / 2) (log J)^2.
It is undefined for s_i <= 0. Below the threshold c > 0 the stress is
replaced by its first order Taylor expansion about the clamped point
max(s_i, c), which is continuous with a continuous first derivative at
s_i = c. The threshold is a tuning value; the paper gives none.
Units: SI in 2D; mu and lambda in N/m, masses in kg.
"""
import math
from anim import det, inv, mul, rot2, transpose
def signed_svd2(f):
"""Return (U, (s1, s2), V) with F = U diag(s1, s2) V^T and det U = det V = +1.
s1 >= |s2| >= 0 when det F >= 0, and s2 < 0 when det F < 0. Closed form:
F = rot(phi) diag(s1, s2) rot(theta), so U = rot(phi) and V = rot(-theta).
"""
a, b, c, d = f[0][0], f[0][1], f[1][0], f[1][1]
e, g = 0.5 * (a + d), 0.5 * (a - d)
h, k = 0.5 * (c + b), 0.5 * (c - b)
q, r = math.hypot(e, k), math.hypot(g, h)
a1, a2 = math.atan2(h, g), math.atan2(k, e)
theta, phi = 0.5 * (a2 - a1), 0.5 * (a2 + a1)
return rot2(phi), (q + r, q - r), rot2(-theta)
def corotated_diag(s, mu, lam):
"""Diagonal stress and its 2 by 2 Jacobian for the corotated model."""
t = (s[0] - 1.0) + (s[1] - 1.0)
p = [2.0 * mu * (s[i] - 1.0) + lam * t for i in range(2)]
jac = [[2.0 * mu + lam, lam], [lam, 2.0 * mu + lam]]
return p, jac
def neo_hookean_diag(s, mu, lam):
"""Diagonal stress and its Jacobian for the neo-Hookean model (s1, s2 > 0)."""
lj = math.log(s[0] * s[1])
p = [mu * s[i] - mu / s[i] + lam * lj / s[i] for i in range(2)]
jac = [[0.0, 0.0], [0.0, 0.0]]
for i in range(2):
jac[i][i] = mu + (mu + lam * (1.0 - lj)) / (s[i] * s[i])
jac[0][1] = jac[1][0] = lam / (s[0] * s[1])
return p, jac
def diag_energy(s, mu, lam, model):
"""The energy density in terms of the signed singular values (no extrapolation)."""
if model == "corotated":
t = (s[0] - 1.0) + (s[1] - 1.0)
return mu * ((s[0] - 1.0) ** 2 + (s[1] - 1.0) ** 2) + 0.5 * lam * t * t
lj = math.log(s[0] * s[1])
return 0.5 * mu * (s[0] ** 2 + s[1] ** 2 - 2.0) - mu * lj + 0.5 * lam * lj * lj
def diagonal_stress(s, mu, lam, model, c):
"""P_hat at the signed singular values s, linearized below the threshold c."""
st = [max(s[0], c), max(s[1], c)] # @line L5
if model == "corotated":
p, jac = corotated_diag(st, mu, lam)
else:
p, jac = neo_hookean_diag(st, mu, lam)
return [p[i] + sum(jac[i][j] * (s[j] - st[j]) for j in range(2)) for i in range(2)] # @line L6
class Mesh:
"""2D triangle mesh with rest data and lumped masses (density in kg/m^2)."""
def __init__(self, rest, tris, mu, lam, density=1.0):
self.rest = [tuple(map(float, p)) for p in rest]
self.tris = [tuple(t) for t in tris]
self.mu, self.lam = mu, lam
self.dm_inv, self.bm, self.v0 = [], [], []
self.mass = [0.0] * len(rest)
for t in self.tris:
dm = edge_matrix(self.rest, t)
if det(dm) <= 0.0:
raise ValueError("each triangle needs a positive rest orientation")
di = inv(dm)
v0 = 0.5 * det(dm)
self.dm_inv.append(di)
self.v0.append(v0)
self.bm.append([[-v0 * x for x in row] for row in transpose(di)])
for a in t:
self.mass[a] += density * v0 / 3.0
def edge_matrix(p, t):
a, b, c = p[t[0]], p[t[1]], p[t[2]]
return [[b[0] - a[0], c[0] - a[0]], [b[1] - a[1], c[1] - a[1]]]
def invertible_forces(mesh, x, model="neo-hookean", c=0.3):
"""Return the elastic forces on all nodes, valid for inverted elements too.
Cost O(m) for m elements: one closed form 2 by 2 SVD per element.
"""
f = [[0.0, 0.0] for _ in x] # @line L1
for e, t in enumerate(mesh.tris): # @line L2
fmat = mul(edge_matrix(x, t), mesh.dm_inv[e]) # @line L3
u, s, v = signed_svd2(fmat) # @line L4
ph = diagonal_stress(s, mesh.mu, mesh.lam, model, c)
p = mul(mul(u, [[ph[0], 0.0], [0.0, ph[1]]]), transpose(v)) # @line L7
g = mul(p, mesh.bm[e]) # @line L8
for k in range(2): # @line L9
f[t[k + 1]][0] += g[0][k]
f[t[k + 1]][1] += g[1][k]
f[t[0]][0] -= g[0][k]
f[t[0]][1] -= g[1][k]
return [tuple(q) for q in f]
def total_energy(mesh, x, model):
"""Sum of V0 Psi(F) over the elements, from the signed singular values."""
tot = 0.0
for e, t in enumerate(mesh.tris):
_, s, _ = signed_svd2(mul(edge_matrix(x, t), mesh.dm_inv[e]))
tot += mesh.v0[e] * diag_energy(s, mesh.mu, mesh.lam, model)
return tot
def direct_neo_hookean_stress(f, mu, lam):
"""P = mu (F - F^(-T)) + lambda log(J) F^(-T), the usual form for det F > 0."""
fit = transpose(inv(f))
lj = math.log(det(f))
return [[mu * (f[i][j] - fit[i][j]) + lam * lj * fit[i][j] for j in range(2)] for i in range(2)]
def step(mesh, x, v, dt, model="neo-hookean", c=0.3, fixed=(), damping=0.0):
"""One symplectic Euler step with the velocity damping v <- (1 - damping dt) v.
The damping is a tuning value, not part of the method. Cost O(n + m).
"""
f = invertible_forces(mesh, x, model, c)
fixed = set(fixed)
xn, vn = [], []
for i in range(len(x)):
if i in fixed:
xn.append(x[i])
vn.append((0.0, 0.0))
continue
w = tuple((1.0 - damping * dt) * (v[i][k] + dt * f[i][k] / mesh.mass[i]) for k in range(2))
vn.append(w)
xn.append((x[i][0] + dt * w[0], x[i][1] + dt * w[1]))
return xn, vn
def signed_area(x, t):
return 0.5 * det(edge_matrix(x, t))
test_invertible_finite_elements.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/invertible-finite-elements/. The authors are listed in prov/8XGGPB.jsonl.
"""Tests of invertible finite elements on small 2D triangle meshes.
The signed SVD rebuilds F with rotations U and V and puts the negative entry
on the smallest singular value. The diagonal stress agrees with the usual
neo-Hookean stress for det F > 0, the forces are the negative gradient of
the energy (for inverted elements too with the corotated model), the stress
is rotation equivariant and C1 at the threshold, and inverted and flat
elements recover their rest shape.
"""
import math
import random
import pytest
import anim
from invertible_finite_elements import (Mesh, diagonal_stress, direct_neo_hookean_stress,
invertible_forces, neo_hookean_diag, signed_area, signed_svd2,
step, total_energy)
MU, LAM = 0.384615, 0.576923
def rand_f(rng, spread=1.5):
return [[rng.uniform(-spread, spread) for _ in range(2)] for _ in range(2)]
def close(a, b, tol):
return all(abs(a[i][j] - b[i][j]) <= tol for i in range(2) for j in range(2))
def stress(f, model, c=0.3):
u, s, v = signed_svd2(f)
ph = diagonal_stress(s, MU, LAM, model, c)
return anim.mul(anim.mul(u, [[ph[0], 0.0], [0.0, ph[1]]]), anim.transpose(v))
def test_signed_svd():
rng = random.Random(1)
for _ in range(2000):
f = rand_f(rng)
u, s, v = signed_svd2(f)
g = anim.mul(anim.mul(u, [[s[0], 0.0], [0.0, s[1]]]), anim.transpose(v))
assert close(f, g, 1e-12)
assert abs(anim.det(u) - 1.0) < 1e-12 and abs(anim.det(v) - 1.0) < 1e-12
assert s[0] >= abs(s[1]) - 1e-12
assert (s[1] < 0.0) == (anim.det(f) < 0.0)
def test_diagonal_stress_matches_direct_neo_hookean():
rng = random.Random(2)
for _ in range(300):
r = anim.rot2(rng.uniform(-3, 3))
q = anim.rot2(rng.uniform(-3, 3))
f = anim.mul(anim.mul(r, [[rng.uniform(0.5, 2.0), 0.0], [0.0, rng.uniform(0.5, 2.0)]]), q)
assert close(stress(f, "neo-hookean"), direct_neo_hookean_stress(f, MU, LAM), 1e-10)
def test_plain_neo_hookean_fails_when_inverted():
with pytest.raises(ValueError):
direct_neo_hookean_stress([[1.0, 0.0], [0.0, -0.5]], MU, LAM)
def flat(x):
return [c for p in x for c in p]
def unflat(z):
return [(z[2 * i], z[2 * i + 1]) for i in range(len(z) // 2)]
def check_gradient(mesh, x, model):
f = invertible_forces(mesh, x, model, c=-1e9 if model == "corotated" else 0.3)
g = anim.num_grad(lambda z: total_energy(mesh, unflat(z), model), flat(x))
scale = max(abs(c) for c in g)
for a, b in zip(flat(f), g):
assert abs(a + b) <= 1e-6 * scale + 1e-9
def test_force_is_minus_gradient_corotated_with_inversion():
rng = random.Random(3)
mesh = Mesh([(0, 0), (1, 0), (0, 1), (1, 1)], [(0, 1, 3), (0, 3, 2)], MU, LAM)
inverted = 0
for _ in range(30):
x = [(p[0] + rng.uniform(-0.8, 0.8), p[1] + rng.uniform(-0.8, 0.8)) for p in mesh.rest]
inverted += any(signed_area(x, t) < 0 for t in mesh.tris)
check_gradient(mesh, x, "corotated")
assert inverted > 5
def test_force_is_minus_gradient_neo_hookean():
rng = random.Random(4)
mesh = Mesh([(0, 0), (1, 0), (0, 1), (1, 1)], [(0, 1, 3), (0, 3, 2)], MU, LAM)
done = 0
while done < 20:
x = [(p[0] + rng.uniform(-0.2, 0.2), p[1] + rng.uniform(-0.2, 0.2)) for p in mesh.rest]
sv = [signed_svd2(anim.mul([[x[t[1]][0] - x[t[0]][0], x[t[2]][0] - x[t[0]][0]],
[x[t[1]][1] - x[t[0]][1], x[t[2]][1] - x[t[0]][1]]], mesh.dm_inv[e]))[1]
for e, t in enumerate(mesh.tris)]
if min(min(s) for s in sv) < 0.35:
continue
check_gradient(mesh, x, "neo-hookean")
done += 1
def test_rotation_equivariance_including_inverted():
rng = random.Random(5)
for _ in range(300):
f = rand_f(rng)
r = anim.rot2(rng.uniform(-3, 3))
q = anim.rot2(rng.uniform(-3, 3))
for model in ("neo-hookean", "corotated"):
p = stress(f, model)
assert close(stress(anim.mul(r, f), model), anim.mul(r, p), 1e-9 * (1 + max(map(abs, flat(p)))))
assert close(stress(anim.mul(f, q), model), anim.mul(p, q), 1e-9 * (1 + max(map(abs, flat(p)))))
def test_zero_stress_at_rest_and_rotation():
for theta in (0.0, 1.0, 3.0):
for model in ("neo-hookean", "corotated"):
assert close(stress(anim.rot2(theta), model), [[0, 0], [0, 0]], 1e-12)
def test_extrapolation_is_c1_at_threshold():
c, h = 0.3, 1e-7
for s1 in (0.5, 1.0, 2.0):
below = diagonal_stress((s1, c - h), MU, LAM, "neo-hookean", c)
above = diagonal_stress((s1, c + h), MU, LAM, "neo-hookean", c)
assert max(abs(a - b) for a, b in zip(below, above)) < 1e-5
_, jac = neo_hookean_diag((s1, c), MU, LAM)
d_below = [(diagonal_stress((s1, c - h), MU, LAM, "neo-hookean", c)[i]
- diagonal_stress((s1, c - 2 * h), MU, LAM, "neo-hookean", c)[i]) / h for i in range(2)]
assert abs(d_below[1] - jac[1][1]) < 1e-4 * abs(jac[1][1])
assert abs(d_below[0] - jac[0][1]) < 1e-4 * max(1.0, abs(jac[0][1]))
def run_recovery(mesh, x, model, fixed, steps=3000, dt=0.01):
v = [(0.0, 0.0)] * len(x)
for _ in range(steps):
x, v = step(mesh, x, v, dt, model=model, c=0.3, fixed=fixed, damping=2.0)
return x
@pytest.mark.parametrize("model", ["neo-hookean", "corotated"])
def test_inverted_triangle_recovers(model):
mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
x = [(0.0, 0.0), (1.0, 0.0), (0.3, -0.5)]
assert signed_area(x, mesh.tris[0]) < 0
x = run_recovery(mesh, x, model, fixed=[0, 1])
assert abs(x[2][0]) < 1e-3 and abs(x[2][1] - 1.0) < 1e-3
@pytest.mark.parametrize("model", ["neo-hookean", "corotated"])
def test_flat_triangle_recovers(model):
mesh = Mesh([(0, 0), (1, 0), (0, 1)], [(0, 1, 2)], MU, LAM)
x = [(0.0, 0.0), (1.0, 0.0), (0.5, 0.0)]
f = invertible_forces(mesh, x, model)
assert all(math.isfinite(c) for p in f for c in p)
assert f[2][1] > 0.0
x = run_recovery(mesh, x, model, fixed=[0, 1])
assert abs(x[2][0]) < 1e-3 and abs(x[2][1] - 1.0) < 1e-3
def test_crushed_mesh_recovers():
rest = [(i * 0.5, j * 0.5) for j in range(3) for i in range(3)]
tris = []
for j in range(2):
for i in range(2):
a = 3 * j + i
tris += [(a, a + 1, a + 4), (a, a + 4, a + 3)]
mesh = Mesh(rest, tris, MU, LAM)
x = list(rest)
x[4] = (1.2, 0.1)
x[7] = (0.5, -0.3)
assert sum(signed_area(x, t) < 0 for t in tris) >= 3
fixed = [0, 1, 2, 3, 5, 6, 8]
x = run_recovery(mesh, x, "neo-hookean", fixed, steps=3000, dt=0.005)
for i in (4, 7):
assert math.dist(x[i], rest[i]) < 1e-3
assert all(signed_area(x, t) > 0 for t in tris)
History
Before 2004, simulations in graphics used springs or an extra volume term to resist inversion, or turned to a linear model in a rotated frame, which works for inverted elements but limits the material. Irving, Teran and Fedkiw (2004) diagonalized with rotations, put the sign of the inversion on the smallest entry, and extended the constitutive models past the flat state with or continuity. Teran, Sifakis, Irving and Fedkiw (2005) used the same frame to build a positive definite stiffness for implicit and quasistatic solves. Sifakis and Barbič (2012) explain the corotated model and the stress from the singular values in their course notes, and Smith, de Goes and Kim (2018) designed an energy that needs no threshold.
References
- Geoffrey Irving, Joseph Teran and Ronald Fedkiw, Invertible finite elements for robust simulation of large deformation, ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2004), 131-140, Section 4 (force G = P B_m), Section 5 (diagonalization, Eq. 1, the sign rule for inverted elements), Section 6 and Figure 3 (the modified neo-Hookean and the rotated linear models)
- Joseph Teran, Eftychios Sifakis, Geoffrey Irving and Ronald Fedkiw, Robust quasistatic finite elements and flesh simulation, ACM SIGGRAPH/Eurographics Symposium on Computer Animation (SCA 2005), the definiteness fix of the stiffness in the diagonal frame for implicit and quasistatic solves (general locator)
- Eftychios Sifakis and Jernej Barbič, FEM simulation of 3D deformable solids, a practitioner's guide to theory, discretization and model reduction, SIGGRAPH 2012 Courses, article 20, the isotropic stress from the singular values and the corotated model (general locator)
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 8XGGPB Edit this page History Report an error Markdown