Modelcore
Neo-Hookean model
Also called neo-Hookean material, compressible neo-Hookean model.
A hyperelastic model with an energy in tr(F^T F) and log J. Its energy and its restoring force grow without bound as J goes to 0, and it is undefined for J ≤ 0.
The neo-Hookean model is a hyperelastic model for rubber-like materials that adds a logarithmic term in the volume ratio . This page uses the compressible form of Bonet and Wood, which is common in graphics:
with ; in 2D, becomes . The energy is zero for every rotation, and its linear limit has exactly the Lamé parameters and . As an element is squeezed toward zero volume, the energy and the restoring force grow without bound. The price is that and are undefined for , so a flat or inverted element stops the simulation unless a solver keeps or the model is changed.
The machine
State and parameters. The input is a deformation gradient with and the Lamé parameters and , from Young's modulus and Poisson's ratio by and . For and , and .
The three terms. penalizes the change of the squared lengths, but it is not zero only for rotations: a uniform shrink lowers below 3. cancels the stress that the first term has at rest, so . penalizes the change of volume, and is the same for and .
Forces of a linear element. With and the rest volume , the forces on the vertices 1 to are the columns of , and vertex 0 gets minus their sum. A simulator computes once per element and step, which needs .
What it counts
is the energy per unit rest volume. It depends on only through and , so it counts the change of lengths and of volume, and nothing for rotations and translations. Unlike the St. Venant-Kirchhoff model, it counts a mirror image as an infinite cost: there is no path of with to it, and has no value there.
Example. The bar , which cannot change its width, with and . Here and .
| StVK | ||||
|---|---|---|---|---|
| 1.5 | 0.131860 | 0.476461 | 0.233922 | 1.262019 |
| 1.2 | 0.024081 | 0.228680 | 0.105186 | 0.355385 |
| 1.0 | 0 | 0 | 0 | 0 |
| 0.8 | 0.030957 | |||
| 0.577350 | 0.170106 | |||
| 0.3 | 0.706206 | |||
| 0.1 | 2.224619 | |||
| 0.01 | 7.696506 |
Both models agree at first order near . Under compression the neo-Hookean stress grows without bound, while the St. Venant-Kirchhoff stress has its largest size at and then falls. The energy grows only like , slowly; the stress, like , is what stops the element.
Relation to other models
- St. Venant-Kirchhoff model. Same linear limit, a polynomial energy, defined for every , but weak and then reversed under strong compression.
- Stable neo-Hookean model. Smith, de Goes and Kim replace the log terms by a quadratic in and a term, so the energy is finite and smooth for every , also for .
- Invertible finite elements. Irving, Teran and Fedkiw write the model in the singular values of and extend it past a small threshold of the smallest singular value, so that inverted elements get a force back toward .
- Incompressible neo-Hookean. For rubber, is a constraint, and on that set. The compressible form above replaces the constraint by the term, and many other compressible forms exist; they differ far from rest.
- Barrier based solvers. Optimization time integration and incremental potential contact use line searches that keep every , and then the barrier of this model is an advantage.
Known results in the model
- Exact gradient for (proved). , and the element forces are minus the gradient of the element energy. See the proof, Steps 1 and 2.
- Objective and isotropic (proved). for every rotation , , and is symmetric. Proof, Step 3.
- Rest state (proved). and for every rotation. Without the term , the form has , so its rest shape is not in equilibrium. Proof, Step 4.
- Linear limit (proved). , with no remap of and . Proof, Step 5.
- Barrier (proved). as , and in the bar the compressive stress grows monotonically and without bound. So no finite value at continues , and the model is undefined for . Proof, Step 6.
- Convexity of the volume term (proved). is convex in only for , so a Newton solver must project the element stiffness to be positive semidefinite in general; the projection is a heuristic. Proof, Step 7.
- Failure with inverted elements (heuristic). An explicit step or an unguarded Newton step can move a vertex past the opposite face, and then the simulation stops; in practice large time steps and collisions cause this. The fixes are a guarded line search, the inversion handling of invertible finite elements, or the stable neo-Hookean energy.
Proof: The neo-Hookean stress is the gradient of its energy for J > 0, is objective and isotropic, has the Lamé parameters as its linear limit, and has a barrier at J = 0full
The code works in with or 3. For a matrix with it computes ,
and it raises an error for . is the Frobenius inner product, and all claims are about exact arithmetic.
Step 1: for
. By Jacobi's formula, , so . So .
Step 2: the element forces
As for every energy density of , with and , . So the gradient for vertex is column of , the gradient for vertex 0 is minus their sum, and the code returns minus these vectors.
Step 3: objectivity, isotropy and no torque
For a rotation , and , so . , so . is symmetric, so the element forces have no net torque.
Step 4: the rest state and rotations
For a rotation , , and , so and . This includes . Without the term , the energy in 3D has the stress , which is at : the rest shape is not in equilibrium. The term has the gradient , which is at rest and cancels it.
Step 5: the linear limit
Let . Then and , so
So and are the Lamé parameters of the linear limit, with no remap.
Step 6: the bar and the barrier
Let with , so and . Then , and .
- For , both terms of are negative, so the stress always pushes back toward , and falls as grows to 1.
- for , so the size of the compressive stress grows as falls; it has no largest value, unlike the St. Venant-Kirchhoff model.
- and as .
For a general , , which tends to as , so no finite value at continues , and has no real value for . This is why the code rejects .
Step 7: where the volume term is convex
, which is positive for and negative for . So the term is convex in only up to , and a Newton solver can meet an indefinite stiffness under strong expansion as well as under compression.
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
neo_hookean_model.py 81 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/neo-hookean-model/. The authors are listed in prov/DY1W7J.jsonl.
"""The compressible neo-Hookean model in the form of Bonet and Wood, in 2D or 3D.
J = det F, I1 = tr(F^T F)
Psi(F) = (mu / 2) (I1 - d) - mu log J + (lambda / 2) (log J)^2
P(F) = mu (F - F^(-T)) + lambda log(J) F^(-T)
Psi and P are defined only for J > 0; for J <= 0 the functions raise
ValueError. The forces of a linear element with rest volume V0 are the
columns of -V0 P D_m^(-T) on the vertices 1 to d, and vertex 0 gets minus
their sum.
"""
import math
from anim import det, inv, mul, transpose
def lame(young, poisson):
"""Return (mu, lambda) from 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 _volume_ratio(f):
j = det(f)
if j <= 0.0:
raise ValueError("the neo-Hookean energy is undefined for det F <= 0")
return j
def energy_density(f, mu, lam):
j = _volume_ratio(f)
d = len(f)
i1 = sum(v * v for row in f for v in row)
lj = math.log(j)
return 0.5 * mu * (i1 - d) - mu * lj + 0.5 * lam * lj * lj
def pk1(f, mu, lam):
j = _volume_ratio(f)
d = len(f)
fit = transpose(inv(f))
lj = math.log(j)
return [[mu * (f[i][k] - fit[i][k]) + lam * lj * fit[i][k] for k in range(d)] for i in range(d)]
def edge_matrix(points):
d = len(points) - 1
return [[points[k + 1][i] - points[0][i] for k in range(d)] for i in range(d)]
def element_forces(rest, cur, mu, lam):
"""The forces on the d + 1 vertices of a linear triangle or tetrahedron."""
dm = edge_matrix(rest)
d = len(dm)
v0 = det(dm) / (2.0 if d == 2 else 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(d)) for k in range(d)]
first = tuple(-sum(c[i] for c in cols) for i in range(d))
return [first] + cols
def element_energy(rest, cur, mu, lam):
dm = edge_matrix(rest)
f = mul(edge_matrix(cur), inv(dm))
return det(dm) / (2.0 if len(dm) == 2 else 6.0) * energy_density(f, mu, lam)
def bar_energy(s, mu, lam):
"""Psi for F = diag(s, 1, 1) with s > 0."""
return 0.5 * mu * (s * s - 1.0) - mu * math.log(s) + 0.5 * lam * math.log(s) ** 2
def bar_stress(s, mu, lam):
"""P_xx for F = diag(s, 1, 1) with s > 0: mu (s - 1/s) + lambda log(s) / s."""
return mu * (s - 1.0 / s) + lam * math.log(s) / s
test_neo_hookean_model.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/neo-hookean-model/. The authors are listed in prov/DY1W7J.jsonl.
"""Tests of the compressible neo-Hookean model.
The stress is checked against the central difference gradient of the
energy density, the element forces against the gradient of the element
energy, and the model against rotations of the deformed and the rest shape.
The linear limit gives the Lame parameters with no remap. The energy and
the restoring stress grow without bound as J goes to 0, and F with J <= 0
is rejected.
"""
import math
import random
import pytest
from anim import det, mul, num_grad, q_normalize, q_to_mat3, transpose
from neo_hookean_model import (
bar_energy,
bar_stress,
element_energy,
element_forces,
energy_density,
lame,
pk1,
)
MU, LAM = lame(1.0, 0.3)
def rand_mat(rng, d, amount=0.5):
while True:
m = [[(1.0 if i == j else 0.0) + rng.uniform(-amount, amount) for j in range(d)] for i in range(d)]
if det(m) > 0.1:
return m
def rotation(rng, d):
if d == 2:
t = rng.uniform(-math.pi, math.pi)
return [[math.cos(t), -math.sin(t)], [math.sin(t), math.cos(t)]]
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, d):
return [list(x[i * d:(i + 1) * d]) for i in range(d)]
def maxdiff(a, b):
return max(abs(x - y) for x, y in zip(flat(a), flat(b)))
def test_lame_check_values():
assert abs(MU - 0.384615) < 1e-6
assert abs(LAM - 0.576923) < 1e-6
def test_pk1_is_energy_gradient():
rng = random.Random(1)
for d in (2, 3):
for _ in range(20):
f = rand_mat(rng, d)
g = num_grad(lambda x: energy_density(unflat(x, d), MU, LAM), flat(f))
assert maxdiff(pk1(f, MU, LAM), unflat(g, d)) < 1e-6
def test_element_forces_are_minus_energy_gradient():
rng = random.Random(2)
for d in (2, 3):
rest = [tuple(1.0 if i == k - 1 else 0.0 for i in range(d)) for k in range(d + 1)]
for _ in range(10):
cur = [tuple(c + rng.uniform(-0.15, 0.15) for c in p) for p in rest]
def w(x):
pts = [tuple(x[k * d:(k + 1) * d]) for k in range(d + 1)]
return element_energy(rest, pts, 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::d])) for i in range(d)) < 1e-12
def test_objective_and_isotropic():
rng = random.Random(3)
for d in (2, 3):
for _ in range(20):
f = rand_mat(rng, d)
q = rotation(rng, d)
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_state_and_rotations():
rng = random.Random(4)
for d in (2, 3):
eye = [[1.0 if i == j else 0.0 for j in range(d)] for i in range(d)]
assert energy_density(eye, MU, LAM) == 0.0
assert maxdiff(pk1(eye, MU, LAM), [[0.0] * d for _ in range(d)]) == 0.0
q = rotation(rng, d)
assert abs(energy_density(q, MU, LAM)) < 1e-12
assert maxdiff(pk1(q, MU, LAM), [[0.0] * d for _ in range(d)]) < 1e-12
def test_linear_limit_has_lame_parameters():
rng = random.Random(5)
h = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
tr = h[0][0] + h[1][1] + h[2][2]
lin = [[MU * (h[i][j] + h[j][i]) + (LAM * 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
def test_bar_formulas():
for s in (0.05, 0.3, 0.8, 1.0, 1.4, 3.0):
f = [[s, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
assert abs(energy_density(f, MU, LAM) - bar_energy(s, MU, LAM)) < 1e-12
p = pk1(f, MU, LAM)
assert abs(p[0][0] - bar_stress(s, MU, LAM)) < 1e-12
assert abs(p[1][1] - LAM * math.log(s)) < 1e-12
def test_barrier_under_compression():
prev_e, prev_p = 0.0, 0.0
for k in range(1, 60):
s = 0.8 ** k
e = bar_energy(s, MU, LAM)
p = bar_stress(s, MU, LAM)
assert e > prev_e
assert p < prev_p < 0.0 or (k == 1 and p < 0.0)
prev_e, prev_p = e, p
assert prev_e > 50.0
assert prev_p < -1e5
assert bar_energy(1e-100, MU, LAM) > 1.5e4
def test_rejects_flat_and_inverted():
for f in ([[1.0, 0.0], [0.0, 0.0]], [[-1.0, 0.0], [0.0, 1.0]], [[1, 0, 0], [0, 1, 0], [0, 0, -0.5]]):
with pytest.raises(ValueError):
energy_density(f, MU, LAM)
with pytest.raises(ValueError):
pk1(f, MU, LAM)
def test_form_without_log_term_is_not_at_rest():
def psi(x):
f = unflat(x, 3)
return 0.5 * MU * (sum(v * v for v in x) - 3.0) + 0.5 * LAM * (det(f) - 1.0) ** 2
g = num_grad(psi, [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0])
expected = [MU, 0.0, 0.0, 0.0, MU, 0.0, 0.0, 0.0, MU]
assert max(abs(a - b) for a, b in zip(g, expected)) < 1e-8
def test_volume_term_convex_only_up_to_e():
for j in (0.2, 1.0, 2.0, math.e - 0.01, math.e + 0.01, 5.0):
h = 1e-4
g = lambda x: math.log(x) ** 2
second = (g(j + h) - 2 * g(j) + g(j - h)) / (h * h)
assert abs(second - 2.0 * (1.0 - math.log(j)) / (j * j)) < 1e-4
assert (second > 0.0) == (j < math.e)
References
- Javier Bonet and Richard D. Wood, Nonlinear Continuum Mechanics for Finite Element Analysis, second edition, Cambridge University Press, 2008, the chapter on hyperelasticity, the compressible neo-Hookean material (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 neo-Hookean energy and its first Piola-Kirchhoff stress among the isotropic models (general locator)
- Breannan Smith, Fernando de Goes and Theodore Kim, Stable neo-Hookean flesh simulation, ACM Transactions on Graphics 37(2), article 12, 2018, the discussion of earlier neo-Hookean energies, their rest state and their behavior for J ≤ 0 (general locator)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 DY1W7J Edit this page History Report an error Markdown