Modelresearch
Stable neo-Hookean flesh
Also called stable neo-Hookean model.
A neo-Hookean energy that is smooth and finite for flat and inverted elements, is at rest at F = I, and has a closed-form eigensystem of its Hessian.
The stable neo-Hookean model of Smith, de Goes and Kim (2018) is a neo-Hookean energy written so that it has a finite value and a smooth gradient for every deformation gradient, including flat and inverted elements. In 3D, with and ,
The volume term is a quadratic in , not in , so it needs no ; the cofactor matrix is the derivative of for every . The shift and the small log term put the rest state at . Because the terms change the linear limit, the model parameters come from the target Lamé parameters , by a remap, and .
The machine
Parameters. From Young's modulus and Poisson's ratio , compute the Lamé parameters and , then the model parameters , by the remap, then from and . For and : , , , and . Without the remap, the linear limit has the shear modulus and the Poisson's ratio , which is 0.269231 instead of 0.3 for these values.
Energy and stress. The formulas above, for every real matrix . Column of is the cross product of the other two columns of in cyclic order, so the cost is a few multiplications and no division except , with .
Forces of a linear element. With and the rest volume , the forces on the vertices 1 to 3 are the columns of , and vertex 0 gets minus their sum. Only the rest matrix is inverted, so the forces are defined for a flat or inverted current tetrahedron.
The terms. is the stretch term of the neo-Hookean model. is the volume term, a smooth function of everywhere. is a small term whose argument is never below 1. At rest, , and makes this zero; the paper writes it as , the same number.
What it counts
is the energy per unit rest volume, up to a constant: is not zero, and only differences matter. It counts stretch through and the change of volume through , and nothing for rotations. It gives an inverted element a finite energy and a force back toward , so the simulation keeps going after an inversion.
Example. The bar with and , so . The table gives , , the linear stress and the neo-Hookean stress with , , which has no value for .
| linear | neo-Hookean | |||
|---|---|---|---|---|
| 1.5 | 0.170658 | 0.686813 | 0.673077 | 0.476461 |
| 1.2 | 0.027087 | 0.271656 | 0.269231 | 0.228680 |
| 1.0 | 0 | 0 | 0 | 0 |
| 0.8 | 0.026746 | |||
| 0.577350 | 0.118522 | |||
| 0.3 | 0.321955 | |||
| 0 | 0.650688 | none | ||
| 1.447472 | none | |||
| 2.564103 | none |
The stress stays close to the linear one in this range and keeps its sign for every , so a flat or inverted bar is pushed back. There is no barrier: the energy of the flat state is finite, so a strong load can still invert an element, and the model then recovers it instead of failing.
Relation to other models
- Neo-Hookean model. It has a barrier, as , and no value for . The stable form gives up the barrier to get an energy that is defined everywhere.
- Invertible finite elements. Irving, Teran and Fedkiw change an existing energy past a threshold on the singular values of . The stable form needs no singular value decomposition and no threshold, because the energy itself is smooth through .
- St. Venant-Kirchhoff model. It is also defined for every , but its bar force reverses for and pushes toward the mirror image; the stable form pushes toward on the whole line.
- Corotational FEM. The corotated energy is defined for inverted elements only with a choice of the sign of ; the stable form needs no polar decomposition.
- Remap for other energies. Smith et al. note that the same linearization method can set the parameters of the other energies that they compare.
Known results in the model
- Exact gradient for every (proved). with , also at and ; the element forces are minus the gradient of the element energy for flat and inverted tetrahedra. See the proof, Steps 1 and 2.
- Objective and isotropic (proved). , and is symmetric. Proof, Step 3.
- Rest state needs the right (proved). exactly for . With , , and with , the value without the log term, . Proof, Step 4.
- Remap (proved). The linear limit has the shear modulus and the first Lamé parameter , so , reproduce the target , . Proof, Step 5.
- Bar recovers from any compression (proved). On the line , is strictly increasing in and zero only at , so the force points to rest for every flat or inverted state on that line. Proof, Step 6.
- Collapsed point (proved). , so an element collapsed to a point has no elastic force; is a saddle of , and nearby the force moves toward . Proof, Step 7.
- Hessian eigensystem (stated in the paper). Smith et al. give the eigenvalues and eigenvectors of the energy Hessian in closed form, so a Newton solver can clamp the negative eigenvalues per element without a numerical eigensolver. This page does not check that result.
- Choice of model (heuristic). The name of the paper refers to flesh. Whether this energy fits a given material is a measurement for that material.
Proof: The stable neo-Hookean stress is the gradient of its energy for every F, the rest state needs the stated alpha, and the remap gives the target Lamé parametersfull
The code works in . For every matrix it computes , ,
with unless the caller gives another , and the cofactor matrix , whose column is the cross product of the other two columns of in cyclic order. , and all claims are about exact arithmetic with and .
Step 1: for every
is a polynomial in the entries of , and its expansion along row gives , for every , singular or not. When , . and , so the log term is smooth for all . So . and are finite and smooth on all of , including and .
Step 2: the element forces
With and , , as for every energy density of . So the code, which returns minus column of for vertex and minus their negated sum for vertex 0, returns . Only is inverted, so this holds when the current tetrahedron is flat or inverted.
Step 3: objectivity, isotropy and no torque
For a rotation , and do not change when becomes or , so neither does . , because and , so . with , and , so is symmetric.
Step 4: the rest state needs the right
At , , and , so . This is zero exactly when , which is the same number as . With , ; with , the value without the log term, . For a rotation , by Step 3, so every rotation is at rest too. is not zero; only differences of matter.
Step 5: the linear limit and the remap
Let and . Then , so ; with ; and . Collecting the terms of order :
with and . So the model parameters and give the target Lamé parameters and . The Poisson's ratio of the limit is .
Step 6: the bar, flat and inverted states
Let for any real . Then , , and with . , so is strictly increasing in , and by Step 4 it is zero at . So for every and for every : for a compressed, flat or inverted bar the force pushes toward , and is the only rest state on this line. At the energy is finite, and .
Step 7: the collapsed state
At , and the first term of is zero, so : a tetrahedron collapsed to a point feels no elastic force. For , and , so the terms of order cancel and
So is a saddle: the energy falls for and rises for . On the line the force moves toward the sign of , which is the side where .
Code
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
stable_neo_hookean.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-neo-hookean/. The authors are listed in prov/F0PH35.jsonl.
"""The stable neo-Hookean energy of Smith, de Goes and Kim (2018), in 3D.
I_C = tr(F^T F), J = det F
Psi(F) = (mu / 2) (I_C - 3) + (lambda / 2) (J - alpha)^2 - (mu / 2) log(I_C + 1)
alpha = 1 + 3 mu / (4 lambda) (= 1 + mu / lambda - mu / (4 lambda))
P(F) = mu (1 - 1 / (I_C + 1)) F + lambda (J - alpha) cof(F)
cof(F) is the cofactor matrix, with dJ/dF = cof(F) for every F, so Psi and P
are defined and smooth for all F, also for J <= 0. The model parameters
(mu, lambda) come from the Lame parameters (mu0, lambda0) of the linear limit
by mu = 4 mu0 / 3 and lambda = lambda0 + 5 mu0 / 6.
"""
import math
from anim import det, inv, mul, transpose
def lame(young, poisson):
"""Return the Lame parameters (mu0, lambda0) of Young's modulus and Poisson's ratio."""
mu = young / (2.0 * (1.0 + poisson))
lam = young * poisson / ((1.0 + poisson) * (1.0 - 2.0 * poisson))
return mu, lam
def remap(mu0, lam0):
"""Return the model parameters (mu, lambda) whose linear limit has the Lame parameters mu0, lambda0."""
return 4.0 * mu0 / 3.0, lam0 + 5.0 * mu0 / 6.0
def rest_alpha(mu, lam):
return 1.0 + 0.75 * mu / lam
def cofactor(f):
"""The cofactor matrix of a 3 by 3 matrix: column k is the cross product of the other two columns."""
c = [[0.0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
i1, i2 = (i + 1) % 3, (i + 2) % 3
j1, j2 = (j + 1) % 3, (j + 2) % 3
c[i][j] = f[i1][j1] * f[i2][j2] - f[i1][j2] * f[i2][j1]
return c
def energy_density(f, mu, lam, alpha=None):
if alpha is None:
alpha = rest_alpha(mu, lam)
ic = sum(v * v for row in f for v in row)
j = det(f)
return 0.5 * mu * (ic - 3.0) + 0.5 * lam * (j - alpha) ** 2 - 0.5 * mu * math.log(ic + 1.0)
def pk1(f, mu, lam, alpha=None):
if alpha is None:
alpha = rest_alpha(mu, lam)
ic = sum(v * v for row in f for v in row)
j = det(f)
a = mu * (1.0 - 1.0 / (ic + 1.0))
b = lam * (j - alpha)
cof = cofactor(f)
return [[a * f[i][k] + b * cof[i][k] for k in range(3)] for i in range(3)]
def edge_matrix(points):
return [[points[k + 1][i] - points[0][i] for k in range(3)] for i in range(3)]
def element_forces(rest, cur, mu, lam):
"""The forces on the 4 vertices of a linear tetrahedron; valid also when it is flat or inverted."""
dm = edge_matrix(rest)
v0 = det(dm) / 6.0
dm_inv = inv(dm)
f = mul(edge_matrix(cur), dm_inv)
h = mul(pk1(f, mu, lam), transpose(dm_inv))
cols = [tuple(-v0 * h[i][k] for i in range(3)) for k in range(3)]
first = tuple(-sum(c[i] for c in cols) for i in range(3))
return [first] + cols
def element_energy(rest, cur, mu, lam):
dm = edge_matrix(rest)
f = mul(edge_matrix(cur), inv(dm))
return det(dm) / 6.0 * energy_density(f, mu, lam)
def bar_stress(s, mu, lam):
"""P_xx = dPsi/ds for F = diag(s, 1, 1): mu s (s^2 + 2) / (s^2 + 3) + lambda (s - alpha)."""
return mu * s * (s * s + 2.0) / (s * s + 3.0) + lam * (s - rest_alpha(mu, lam))
def effective_poisson(mu, lam):
"""The Poisson's ratio of the linear limit: (lambda - 5 mu / 8) / (2 (lambda + mu / 8))."""
return (lam - 0.625 * mu) / (2.0 * (lam + 0.125 * mu))
test_stable_neo_hookean.py 181 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/stable-neo-hookean/. The authors are listed in prov/F0PH35.jsonl.
"""Tests of the stable neo-Hookean energy.
The stress is checked against the central difference gradient of the
energy for valid, flat and inverted F, and the element forces against the
gradient of the element energy for inverted tetrahedra. The model is
checked against rotations, the rest state needs the right alpha, and the
remapped parameters give the target Lame parameters in the linear limit.
The bar force pushes every compressed or inverted state toward J = 1.
"""
import math
import random
from anim import det, inv, mul, num_grad, q_normalize, q_to_mat3, transpose
from stable_neo_hookean import (
bar_stress,
cofactor,
effective_poisson,
element_energy,
element_forces,
energy_density,
lame,
pk1,
remap,
rest_alpha,
)
MU0, LAM0 = lame(1.0, 0.3)
MU, LAM = remap(MU0, LAM0)
EYE = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
def rand_mat(rng, amount=0.8):
return [[(1.0 if i == j else 0.0) + rng.uniform(-amount, amount) for j in range(3)] for i in range(3)]
def rotation(rng):
return q_to_mat3(q_normalize(tuple(rng.gauss(0.0, 1.0) for _ in range(4))))
def flat(m):
return [v for row in m for v in row]
def unflat(x):
return [list(x[i * 3:(i + 1) * 3]) for i in range(3)]
def maxdiff(a, b):
return max(abs(x - y) for x, y in zip(flat(a), flat(b)))
def test_lame_and_remap_values():
assert abs(MU0 - 0.384615) < 1e-6
assert abs(LAM0 - 0.576923) < 1e-6
assert abs(MU - 0.512821) < 1e-6
assert abs(LAM - 0.897436) < 1e-6
assert abs(rest_alpha(MU, LAM) - (1.0 + MU / LAM - MU / (4.0 * LAM))) < 1e-15
def test_cofactor_is_det_times_inverse_transpose():
rng = random.Random(1)
for _ in range(20):
f = rand_mat(rng)
j = det(f)
fit = transpose(inv(f))
assert maxdiff(cofactor(f), [[j * v for v in row] for row in fit]) < 1e-12
def test_pk1_is_energy_gradient_also_when_inverted():
rng = random.Random(2)
signs = {True: 0, False: 0}
for trial in range(40):
f = rand_mat(rng)
if trial % 2:
f[0] = [-v for v in f[0]]
if trial == 7:
f[2] = [f[0][k] + f[1][k] for k in range(3)]
signs[det(f) > 0] += 1
g = num_grad(lambda x: energy_density(unflat(x), MU, LAM), flat(f))
assert maxdiff(pk1(f, MU, LAM), unflat(g)) < 1e-6
assert signs[True] > 5 and signs[False] > 5
def test_element_forces_for_inverted_tetrahedra():
rng = random.Random(3)
rest = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0)]
for k in range(10):
cur = [tuple(c + rng.uniform(-0.2, 0.2) for c in p) for p in rest]
if k % 2:
cur[3] = (cur[3][0], cur[3][1], -cur[3][2])
def w(x):
return element_energy(rest, [tuple(x[i * 3:(i + 1) * 3]) for i in range(4)], MU, LAM)
g = num_grad(w, [c for p in cur for c in p])
forces = [c for p in element_forces(rest, cur, MU, LAM) for c in p]
assert max(abs(a + b) for a, b in zip(forces, g)) < 1e-6
assert max(abs(sum(forces[i::3])) for i in range(3)) < 1e-12
def test_objective_and_isotropic():
rng = random.Random(4)
for _ in range(20):
f = rand_mat(rng)
q = rotation(rng)
psi = energy_density(f, MU, LAM)
assert abs(energy_density(mul(q, f), MU, LAM) - psi) < 1e-12
assert abs(energy_density(mul(f, q), MU, LAM) - psi) < 1e-12
assert maxdiff(pk1(mul(q, f), MU, LAM), mul(q, pk1(f, MU, LAM))) < 1e-12
pft = mul(pk1(f, MU, LAM), transpose(f))
assert maxdiff(pft, transpose(pft)) < 1e-12
def test_rest_needs_the_right_alpha():
assert maxdiff(pk1(EYE, MU, LAM), [[0.0] * 3 for _ in range(3)]) < 1e-15
p_one = pk1(EYE, MU, LAM, alpha=1.0)
assert maxdiff(p_one, [[0.75 * MU if i == j else 0.0 for j in range(3)] for i in range(3)]) < 1e-15
p_nolog = 1.0 + MU / LAM
p = pk1(EYE, MU, LAM, alpha=p_nolog)
assert maxdiff(p, [[-0.25 * MU if i == j else 0.0 for j in range(3)] for i in range(3)]) < 1e-15
rng = random.Random(5)
for _ in range(5):
q = rotation(rng)
assert maxdiff(pk1(q, MU, LAM), [[0.0] * 3 for _ in range(3)]) < 1e-12
def test_remap_gives_target_linear_limit():
rng = random.Random(6)
h = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
tr = h[0][0] + h[1][1] + h[2][2]
lin = [[MU0 * (h[i][j] + h[j][i]) + (LAM0 * tr if i == j else 0.0) for j in range(3)] for i in range(3)]
errs = []
for eps in (1e-2, 5e-3):
f = [[(1.0 if i == j else 0.0) + eps * h[i][j] for j in range(3)] for i in range(3)]
p = pk1(f, MU, LAM)
errs.append(max(abs(p[i][j] / eps - lin[i][j]) for i in range(3) for j in range(3)))
assert errs[0] < 0.1
assert 1.8 < errs[0] / errs[1] < 2.2
assert abs(effective_poisson(MU, LAM) - 0.3) < 1e-12
assert abs(effective_poisson(MU0, LAM0) - 0.269231) < 1e-6
def test_bar_force_points_to_rest():
for k in range(-300, 301):
s = k / 100.0
f = [[s, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
p = pk1(f, MU, LAM)[0][0]
assert abs(p - bar_stress(s, MU, LAM)) < 1e-12
if s < 1.0:
assert p < 0.0
elif s > 1.0:
assert p > 0.0
else:
assert abs(p) < 1e-15
def test_finite_energy_at_flat_and_inverted_states():
assert math.isfinite(energy_density([[0.0] * 3 for _ in range(3)], MU, LAM))
flat_f = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 0.0]]
inv_f = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]]
e_flat = energy_density(flat_f, MU, LAM)
e_inv = energy_density(inv_f, MU, LAM)
assert 0.0 < e_flat < e_inv
p = pk1(flat_f, MU, LAM)
assert p[2][2] < 0.0
def test_collapsed_point_is_a_saddle():
zero = [[0.0] * 3 for _ in range(3)]
assert maxdiff(pk1(zero, MU, LAM), zero) == 0.0
e0 = energy_density(zero, MU, LAM)
rng = random.Random(7)
for _ in range(10):
g = rand_mat(rng)
eps = 1e-2
diff = energy_density([[eps * v for v in row] for row in g], MU, LAM) - e0
cubic = -LAM * rest_alpha(MU, LAM) * eps ** 3 * det(g)
assert abs(diff - cubic) < 0.05 * abs(cubic) + 1e-8
References
- Breannan Smith, Fernando de Goes and Theodore Kim, Stable neo-Hookean flesh simulation, ACM Transactions on Graphics 37(2), article 12, 2018, Section 3.3 (the energy with the log term and the rest value of alpha), Section 3.4 (the Lamé reparameterization) and Eq. 16 (the Poisson's ratio of the linear limit)
- Geoffrey Irving, Joseph Teran and Ronald Fedkiw, Invertible finite elements for robust simulation of large deformation, Symposium on Computer Animation 2004, 131 to 140, the earlier approach, which extends an energy past a threshold on the singular values of F (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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag F0PH35 Edit this page History Report an error Markdown