Techniqueadvanced
Modal deformable models
Also called modal analysis for animation, reduced deformable models.
Simulate a deformable body in a basis of its r lowest vibration modes. Each mode is an independent oscillator, so a step costs O(r), plus O(nr) when the full shape is rebuilt.
A modal deformable model describes the shape of an elastic body by a few numbers, the amplitudes of its lowest vibration modes, instead of the positions of all mesh nodes. For a mesh with degrees of freedom, the finite element method gives the stiffness matrix at rest and the mass matrix . The modes are the solutions of the generalized eigenvalue problem , scaled so that . With the modes of smallest as the columns of , the shape is , and the equation becomes oscillators with , which do not interact. Pentland and Williams (1989) used this for animation; Barbič and James (2005) extended the basis and the forces so that the reduced model has large deformations.
In plain words
A plate or a beam vibrates in a few typical patterns. The slowest pattern is a long, soft bend. Faster patterns have more waves and are stiffer.
Most of the visible motion of an elastic body is made of the slowest patterns. So we compute these patterns once, before the animation. Then each frame only has to say how much of each pattern is present.
Each pattern moves like its own spring with its own weight, and it does not push the other patterns. So one frame is a few small updates, one per pattern, however fine the mesh is. To draw the body, we add up the patterns.
The price is that the patterns come from small motions near rest. They do not know that a large rotation should not stretch the body.
When it applies
- Small deformations near one rest shape. The modes come from the linear system at rest, so the method is exact for that linear system and has errors when the material leaves the linear range.
- Forces that are known or cheap to project. The external force enters as ; a force at a few nodes costs per node.
- Many frames for one mesh. The eigenproblem is solved once before the animation, which pays off when the same body moves for many steps.
- Low modes carry the motion. A load that excites mostly high modes, for example an impact at one node, needs many modes.
The template
MODAL-REDUCTION(mesh, fixed, r, f, h, steps)- 1
assemble the linear stiffness K at rest and the lumped mass M, and remove the fixed degrees of freedom - 2
solve the generalized eigenproblem K φ = λ M φ and scale each φ so that φᵀ M φ = 1 - 3
keep the r modes with the smallest λ, as the columns of U, and set ω_i² = λ_i - 4
project the external force: g = Uᵀ f - 5
each step, advance each mode as its own oscillator: v_i ← v_i + h (g_i - ω_i² q_i), q_i ← q_i + h v_i - 6
rebuild the shape when it is needed: u = U q
The code uses mass lumping, so is diagonal, and it solves L2 with the Jacobi eigenvalue algorithm on . L5 is the symplectic Euler method on each mode.
Diagonal form (proved). With all modes, and , so . See the proof, Steps 2 and 3.
Same steps as the full system (proved). With all modes, the steps of L5 and L6 give the same shapes as symplectic Euler on , from the initial values and . Proof, Step 4.
Truncation keeps its modes (proved). The modes do not interact, so with modes the code computes exactly the first modal coordinates of the full solution, and the error is the part of the full solution in the dropped modes. For a static load the error in the -norm does not increase with . Proof, Step 5.
Cost (proved). L1 to L3 run once; the code solves the dense eigenproblem in per Jacobi sweep. A step of L5 costs , and L6 costs for each frame that is drawn.
Classic examples
A cantilever plate. A grid of nodes on , two triangles per cell, , , density 1, and the left edge fixed, has 24 free degrees of freedom. The code gives these lowest eigenvalues; the largest of all 24 is .
| mode | ||
|---|---|---|
| 1 | 0.082265 | 0.286818 |
| 2 | 0.696038 | 0.834289 |
| 3 | 0.858783 | 0.926705 |
| 4 | 3.051315 | 1.746801 |
| 5 | 4.596023 | 2.143834 |
| 6 | 5.163225 | 2.272273 |
For the weight in the direction, the static shape has the largest deflection 0.162985. The relative error in the -norm of the static shape with modes is a measurement on this mesh:
| 1 | 2 | 3 | 6 | 12 | 24 | |
|---|---|---|---|---|---|---|
| relative error | 0.056257 | 0.054433 | 0.006409 | 0.000545 | 0.000138 | 0 |
Mode 2 adds little because the load does not excite it much: , against and .
A free body. The same grid with no fixed node has three eigenvalues 0, for the two translations and the linearized rotation (proved, Step 6). The fourth is .
A large rotation. The rotation mode with amplitude has zero linear energy, but it is not a rotation: it multiplies the area by , and its St. Venant-Kirchhoff energy is (proved, Step 7). For the free grid, , and gives the area 2.5 and the energy 0.060096. This is the main error of linear modes for large motion.
Variations
- Modal derivatives. Barbič and James (2005) add to the linear modes their derivatives, the second-order change of the static shape when two modes are present together. With a St. Venant-Kirchhoff material, the reduced internal force is a cubic polynomial in , and they evaluate it in a cost that does not depend on . This page states that result from the paper and does not check it.
- Damping. With Rayleigh damping , is diagonal too, and mode gets the damping (proved by the same argument as Step 3).
- Rotation of the frame. A reduced body can move with a rigid frame and use the modes only for the deformation relative to the frame. This removes the error of the large-rotation example for the rigid part of the motion (heuristic: the error comes back when the deformation itself rotates parts of the body).
- Other bases. A basis from principal component analysis of example shapes, or from a Rayleigh-Ritz projection with other vectors, uses the same steps L4 to L6 with a reduced that is not diagonal. See also model order reduction.
- Iterative eigensolvers. For a large mesh, only the lowest pairs are needed, and Lanczos or subspace iteration find them without a dense solve.
Pitfalls
- Zero modes. A free body has rigid modes with . Integrate them as free motion, and do not divide by for a static solve.
- Mass scaling. The modes must be -orthonormal, not orthonormal in the usual sense. With unit vectors, is not and the modes interact through the mass.
- Initial values. The modal coordinates of a full shape are , not . Only for is the shape rebuilt exactly.
- Time step. Symplectic Euler on one mode is stable only for . Truncation removes the stiff high modes, so the reduced model can use a larger step than the full one. For the cantilever plate, the full model needs , while 6 modes allow .
- Large rotations. Linear modes stretch the body when it rotates. A rigid frame, modal derivatives or a corotational step is needed for large motion.
- Load shapes. A load at one node excites high modes. A few low modes give a shape that is too smooth near the load.
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
modal_reduction.py 217 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modal-reduction/. The authors are listed in prov/CSEPNJ.jsonl.
"""Linear modal reduction of a 2D triangle mesh.
The rest stiffness K of linear elasticity and the lumped mass M are
assembled, the generalized eigenproblem K phi = lambda M phi is solved by
the cyclic Jacobi method on M^(-1/2) K M^(-1/2), and the r modes with the
smallest eigenvalues form the basis U, with U^T M U = I and
U^T K U = diag(omega^2). The reduced coordinates q follow r independent
oscillators q'' = -omega^2 q + U^T f, advanced by symplectic Euler, and the
shape is u = U q.
Displacements are flat lists (u_x0, u_y0, u_x1, u_y1, ...).
"""
import math
from anim import det, inv, mul, transpose
def lame(young, poisson):
mu = young / (2.0 * (1.0 + poisson))
lam = young * poisson / ((1.0 + poisson) * (1.0 - 2.0 * poisson))
return mu, lam
def grid_mesh(nx, ny, width, height):
"""Nodes of an nx by ny grid on [0, width] x [0, height], two triangles per cell, all counterclockwise."""
nodes = [(width * i / (nx - 1), height * j / (ny - 1)) for j in range(ny) for i in range(nx)]
tris = []
for j in range(ny - 1):
for i in range(nx - 1):
a = j * nx + i
b, c, d = a + 1, a + nx, a + nx + 1
tris.append((a, b, d))
tris.append((a, d, c))
return nodes, tris
def _edge(p, t):
return [[p[t[1]][0] - p[t[0]][0], p[t[2]][0] - p[t[0]][0]], [p[t[1]][1] - p[t[0]][1], p[t[2]][1] - p[t[0]][1]]]
def element_linear_forces(dm, area, du, mu, lam):
"""Forces of linear elasticity on the 3 vertices for the vertex displacements du (6 numbers)."""
dm_inv = inv(dm)
ds = [[du[2] - du[0], du[4] - du[0]], [du[3] - du[1], du[5] - du[1]]]
h = mul(ds, dm_inv)
tr = h[0][0] + h[1][1]
p = [[mu * (h[i][j] + h[j][i]) + (lam * tr if i == j else 0.0) for j in range(2)] for i in range(2)]
g = mul(p, transpose(dm_inv))
f1 = (-area * g[0][0], -area * g[1][0])
f2 = (-area * g[0][1], -area * g[1][1])
return [-f1[0] - f2[0], -f1[1] - f2[1], f1[0], f1[1], f2[0], f2[1]]
def stiffness_matrix(nodes, tris, mu, lam):
n = 2 * len(nodes)
k = [[0.0] * n for _ in range(n)]
for t in tris:
dm = _edge(nodes, t)
area = det(dm) / 2.0
dofs = [2 * t[0], 2 * t[0] + 1, 2 * t[1], 2 * t[1] + 1, 2 * t[2], 2 * t[2] + 1]
for b in range(6):
unit = [1.0 if c == b else 0.0 for c in range(6)]
col = element_linear_forces(dm, area, unit, mu, lam)
for a in range(6):
k[dofs[a]][dofs[b]] -= col[a]
return k
def lumped_mass(nodes, tris, rho):
m = [0.0] * (2 * len(nodes))
for t in tris:
share = rho * det(_edge(nodes, t)) / 6.0
for v in t:
m[2 * v] += share
m[2 * v + 1] += share
return m
def restrict(k, m, free):
"""Keep only the degrees of freedom in the list free."""
return [[k[i][j] for j in free] for i in free], [m[i] for i in free]
def jacobi_eigen(a, tol=1e-13, max_sweeps=60):
"""Eigenvalues and eigenvectors of a symmetric matrix by cyclic Jacobi rotations.
Return (values, vectors) with vectors[k] the unit eigenvector of values[k].
"""
n = len(a)
a = [list(map(float, row)) for row in a]
v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
scale = math.sqrt(sum(x * x for row in a for x in row)) or 1.0
for _ in range(max_sweeps):
off = math.sqrt(sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j))
if off <= tol * scale:
break
for p in range(n - 1):
for q in range(p + 1, n):
apq = a[p][q]
if abs(apq) <= 1e-300:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * apq)
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
s = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - s * akq
a[k][q] = s * akp + c * akq
rp, rq = a[p], a[q]
for k in range(n):
apk, aqk = rp[k], rq[k]
rp[k] = c * apk - s * aqk
rq[k] = s * apk + c * aqk
for k in range(n):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - s * vkq
v[k][q] = s * vkp + c * vkq
values = [a[i][i] for i in range(n)]
vectors = [[v[k][i] for k in range(n)] for i in range(n)]
return values, vectors
def generalized_eigen(k, m):
"""Solve K phi = lambda M phi for a diagonal M > 0; return the pairs sorted by lambda, with phi^T M phi = 1."""
n = len(k)
s = [1.0 / math.sqrt(x) for x in m]
a = [[s[i] * k[i][j] * s[j] for j in range(n)] for i in range(n)]
values, vectors = jacobi_eigen(a)
pairs = sorted(zip(values, vectors), key=lambda pv: pv[0])
lams = [p[0] for p in pairs]
phis = [[s[i] * p[1][i] for i in range(n)] for p in pairs]
return lams, phis
def modal_basis(k, m, r):
"""The r modes with the smallest eigenvalues: (omega^2 list, U as a list of r mode vectors)."""
lams, phis = generalized_eigen(k, m) # @line L2
return lams[:r], phis[:r] # @line L3
def project(modes, f):
return [sum(a * b for a, b in zip(phi, f)) for phi in modes]
def reconstruct(modes, q):
n = len(modes[0])
return [sum(q[i] * modes[i][j] for i in range(len(modes))) for j in range(n)]
def simulate_modal(modes, omega2, force, h, steps, q0=None, v0=None):
"""Advance q'' = -omega^2 q + U^T f by symplectic Euler; return the list of shapes u = U q."""
r = len(modes)
q = list(q0) if q0 else [0.0] * r
v = list(v0) if v0 else [0.0] * r
g = project(modes, force) # @line L4
shapes = []
for _ in range(steps):
for i in range(r):
v[i] += h * (g[i] - omega2[i] * q[i]) # @line L5
q[i] += h * v[i]
shapes.append(reconstruct(modes, q)) # @line L6
return shapes, q
def simulate_full(k, m, force, h, steps, u0=None, v0=None):
"""The reference: M u'' = -K u + f with the same symplectic Euler step on all degrees of freedom."""
n = len(k)
u = list(u0) if u0 else [0.0] * n
v = list(v0) if v0 else [0.0] * n
shapes = []
for _ in range(steps):
ku = [sum(k[i][j] * u[j] for j in range(n)) for i in range(n)]
for i in range(n):
v[i] += h * (force[i] - ku[i]) / m[i]
for i in range(n):
u[i] += h * v[i]
shapes.append(list(u))
return shapes
def setup(nx, ny, width, height, young, poisson, rho, fix_left):
"""Assemble and restrict a grid; return (nodes, tris, K, M, free dofs)."""
nodes, tris = grid_mesh(nx, ny, width, height)
mu, lam = lame(young, poisson)
k = stiffness_matrix(nodes, tris, mu, lam) # @line L1
m = lumped_mass(nodes, tris, rho)
free = [d for d in range(2 * len(nodes)) if not (fix_left and nodes[d // 2][0] == 0.0)]
kr, mr = restrict(k, m, free)
return nodes, tris, kr, mr, free
def stvk_energy(nodes, tris, u, mu, lam):
"""St. Venant-Kirchhoff energy of the displaced mesh, to measure the error of linear modes at large amplitude."""
total = 0.0
for t in tris:
dm = _edge(nodes, t)
cur = [(nodes[v][0] + u[2 * v], nodes[v][1] + u[2 * v + 1]) for v in t]
ds = [[cur[1][0] - cur[0][0], cur[2][0] - cur[0][0]], [cur[1][1] - cur[0][1], cur[2][1] - cur[0][1]]]
f = mul(ds, inv(dm))
c = mul(transpose(f), f)
e = [[0.5 * (c[i][j] - (1.0 if i == j else 0.0)) for j in range(2)] for i in range(2)]
tr = e[0][0] + e[1][1]
psi = mu * sum(x * x for row in e for x in row) + 0.5 * lam * tr * tr
total += det(dm) / 2.0 * psi
return total
def mesh_area(nodes, tris, u):
total = 0.0
for t in tris:
p = [(nodes[v][0] + u[2 * v], nodes[v][1] + u[2 * v + 1]) for v in t]
total += 0.5 * ((p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[1][1] - p[0][1]) * (p[2][0] - p[0][0]))
return total
test_modal_reduction.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/modal-reduction/. The authors are listed in prov/CSEPNJ.jsonl.
"""Tests of linear modal reduction on a small grid mesh.
The stiffness is checked against the gradient of the linear energy, the
eigenpairs against the residual, M-orthonormality and the trace identities,
and the modal simulation against the full simulation of the same linear
system. A free body has exactly the three rigid modes. A large rotation
mode changes the area and the St. Venant-Kirchhoff energy, which the linear
modes do not see.
"""
import math
import random
from anim import num_grad
from modal_reduction import (
generalized_eigen,
jacobi_eigen,
lame,
mesh_area,
modal_basis,
project,
reconstruct,
setup,
simulate_full,
simulate_modal,
stvk_energy,
)
MU, LAM = lame(1.0, 0.3)
def matvec(a, x):
return [sum(r[j] * x[j] for j in range(len(x))) for r in a]
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def test_lame_values():
assert abs(MU - 0.384615) < 1e-6
assert abs(LAM - 0.576923) < 1e-6
def test_stiffness_is_hessian_of_linear_energy():
nodes, tris, k, m, free = setup(4, 3, 1.5, 1.0, 1.0, 0.3, 1.0, False)
n = len(k)
assert all(abs(k[i][j] - k[j][i]) < 1e-12 for i in range(n) for j in range(n))
rng = random.Random(1)
u = [rng.uniform(-1, 1) for _ in range(n)]
def energy(x):
return 0.5 * dot(x, matvec(k, x))
# the quadratic energy 1/2 u^T K u equals the linear elastic energy of the mesh
def lin_energy(x):
total = 0.0
for t in tris:
p = [nodes[v] for v in t]
dm = [[p[1][0] - p[0][0], p[2][0] - p[0][0]], [p[1][1] - p[0][1], p[2][1] - p[0][1]]]
a = (dm[0][0] * dm[1][1] - dm[0][1] * dm[1][0]) / 2.0
ia = [[dm[1][1] / (2 * a), -dm[0][1] / (2 * a)], [-dm[1][0] / (2 * a), dm[0][0] / (2 * a)]]
ds = [[x[2 * t[1]] - x[2 * t[0]], x[2 * t[2]] - x[2 * t[0]]], [x[2 * t[1] + 1] - x[2 * t[0] + 1], x[2 * t[2] + 1] - x[2 * t[0] + 1]]]
h = [[sum(ds[i][c] * ia[c][j] for c in range(2)) for j in range(2)] for i in range(2)]
e = [[0.5 * (h[i][j] + h[j][i]) for j in range(2)] for i in range(2)]
tr = e[0][0] + e[1][1]
total += a * (MU * sum(v * v for row in e for v in row) + 0.5 * LAM * tr * tr)
return total
assert abs(energy(u) - lin_energy(u)) < 1e-12
g = num_grad(lin_energy, u)
assert max(abs(a - b) for a, b in zip(g, matvec(k, u))) < 1e-6
def test_jacobi_against_trace_and_residual():
rng = random.Random(2)
n = 7
b = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
a = [[b[i][j] + b[j][i] for j in range(n)] for i in range(n)]
vals, vecs = jacobi_eigen(a)
assert abs(sum(vals) - sum(a[i][i] for i in range(n))) < 1e-12
assert abs(sum(v * v for v in vals) - sum(x * x for row in a for x in row)) < 1e-10
for lam, v in zip(vals, vecs):
av = matvec(a, v)
assert max(abs(av[i] - lam * v[i]) for i in range(n)) < 1e-10
assert abs(dot(v, v) - 1.0) < 1e-12
def test_generalized_eigenpairs():
for fix in (False, True):
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, fix)
n = len(k)
lams, phis = generalized_eigen(k, m)
assert lams == sorted(lams)
for lam, phi in zip(lams, phis):
kp = matvec(k, phi)
assert max(abs(kp[i] - lam * m[i] * phi[i]) for i in range(n)) < 1e-9
for a in range(n):
for b in range(a, n):
mab = sum(phis[a][i] * m[i] * phis[b][i] for i in range(n))
assert abs(mab - (1.0 if a == b else 0.0)) < 1e-10
minv_k = [[k[i][j] / m[i] for j in range(n)] for i in range(n)]
tr1 = sum(minv_k[i][i] for i in range(n))
tr2 = sum(minv_k[i][j] * minv_k[j][i] for i in range(n) for j in range(n))
assert abs(sum(lams) - tr1) < 1e-9 * tr1
assert abs(sum(x * x for x in lams) - tr2) < 1e-9 * tr2
def test_free_body_has_three_rigid_modes():
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, False)
lams, phis = generalized_eigen(k, m)
assert all(abs(x) < 1e-10 for x in lams[:3])
assert lams[3] > 1.0
# the zero modes span the translations and the linearized rotation (-y, x)
rigid = [[1.0, 0.0] * len(nodes), [0.0, 1.0] * len(nodes), [c for p in nodes for c in (-p[1], p[0])]]
for w in rigid:
coef = [sum(phi[i] * m[i] * w[i] for i in range(len(w))) for phi in phis[:3]]
back = reconstruct(phis[:3], coef)
assert max(abs(a - b) for a, b in zip(back, w)) < 1e-9
_, _, kf, mf, _ = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, True)
assert min(generalized_eigen(kf, mf)[0]) > 0.05
def test_full_basis_matches_full_simulation():
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, True)
n = len(k)
rng = random.Random(3)
f = [rng.uniform(-0.1, 0.1) for _ in range(n)]
u0 = [rng.uniform(-0.05, 0.05) for _ in range(n)]
v0 = [rng.uniform(-0.05, 0.05) for _ in range(n)]
om2, modes = modal_basis(k, m, n)
mu0 = [m[i] * u0[i] for i in range(n)]
mv0 = [m[i] * v0[i] for i in range(n)]
h, steps = 0.05, 200
shapes, _ = simulate_modal(modes, om2, f, h, steps, project(modes, mu0), project(modes, mv0))
full = simulate_full(k, m, f, h, steps, u0, v0)
assert max(abs(a - b) for s, t in zip(shapes, full) for a, b in zip(s, t)) < 1e-9
assert max(abs(x) for x in full[-1]) > 1e-2
def test_truncated_basis_keeps_its_modes_exactly():
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, True)
n = len(k)
om2, modes = modal_basis(k, m, n)
rng = random.Random(4)
f = [rng.uniform(-0.1, 0.1) for _ in range(n)]
h, steps, r = 0.05, 120, 6
full = simulate_full(k, m, f, h, steps)
shapes, q = simulate_modal(modes[:r], om2[:r], f, h, steps)
q_full = project(modes[:r], [m[i] * full[-1][i] for i in range(n)])
assert max(abs(a - b) for a, b in zip(q, q_full)) < 1e-9
# the error is the part of the full shape in the dropped modes
q_rest = project(modes[r:], [m[i] * full[-1][i] for i in range(n)])
rest = reconstruct(modes[r:], q_rest)
err = [a - b for a, b in zip(full[-1], shapes[-1])]
assert max(abs(a - b) for a, b in zip(err, rest)) < 1e-9
assert max(abs(x) for x in err) > 1e-6
def test_static_load_converges_with_more_modes():
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, True)
n = len(k)
om2, modes = modal_basis(k, m, n)
f = [0.0 if i % 2 == 0 else -0.01 * m[i] for i in range(n)]
g = project(modes, f)
exact = reconstruct(modes, [g[i] / om2[i] for i in range(n)])
ku = matvec(k, exact)
assert max(abs(a - b) for a, b in zip(ku, f)) < 1e-12
errs = []
for r in (1, 3, 6, 12, n):
approx = reconstruct(modes[:r], [g[i] / om2[i] for i in range(r)])
errs.append(math.sqrt(sum(m[i] * (approx[i] - exact[i]) ** 2 for i in range(n))))
assert all(errs[i + 1] <= errs[i] + 1e-15 for i in range(len(errs) - 1))
assert errs[-1] < 1e-12 and errs[0] > 0.0
def test_large_rotation_mode_is_not_rigid():
nodes, tris, k, m, free = setup(5, 3, 2.0, 1.0, 1.0, 0.3, 1.0, False)
area = 2.0
rot = [c for p in nodes for c in (-p[1], p[0])]
for theta in (0.1, 0.5, 1.0):
u = [theta * x for x in rot]
assert abs(0.5 * dot(u, matvec(k, u))) < 1e-10
assert abs(mesh_area(nodes, tris, u) - area * (1.0 + theta * theta)) < 1e-12
e = stvk_energy(nodes, tris, u, MU, LAM)
assert abs(e - area * (MU + LAM) * theta ** 4 / 2.0) < 1e-12
Exercises
- Show that a square matrix with satisfies .
- With Rayleigh damping , write the damped modal equation of mode and its critical damping.
- Show that for a static load the -norm error with modes is .
- Show that symplectic Euler on is stable for and unstable for .
- For the field , compute the deformation gradient, its determinant and the Green strain, and find the St. Venant-Kirchhoff energy per unit area.
- Two triangles share an edge. Show that if the linear energy of a displacement is zero, then the displacement is one rigid motion on both triangles.
Proof: The modal basis diagonalizes the linear system, the modal steps equal the full steps, and a truncated basis keeps its modes exactlyfull
The code works on a triangle mesh in the plane with linear elasticity, Lamé parameters and , and a lumped mass matrix with every . is the stiffness matrix after the fixed degrees of freedom are removed. All claims are about exact arithmetic, except Step 2, which also bounds the error of the eigensolver.
Step 1: is the Hessian of the linear energy
For one triangle with rest edge matrix and area , the code forms from the vertex displacements, , and the forces as the columns of , with vertex 0 getting minus their sum. is the gradient of , so these forces are , by the same chain rule as for every energy density of . The forces are linear in , so the column of the element force for a unit displacement is , and the code stores column by column. The sum over triangles gives with , so is symmetric. for and , so is positive semidefinite, and removing degrees of freedom takes a principal submatrix, which keeps both properties.
Step 2: the generalized eigenpairs
Let and , which is symmetric. Each Jacobi rotation replaces by and by , so after the loop is orthogonal and . Let be the diagonal of and the Frobenius norm of its off-diagonal part, which the stop test bounds. Then , whose norm is , so each column of satisfies . For , , so the pairs solve up to this residual, and exactly when . , so the are -orthonormal exactly, up to rounding, whatever is. The cyclic Jacobi method makes go to zero (a known result), and the stop test checks it. By Step 1, every eigenvalue is at least 0.
Step 3: the full basis diagonalizes the system
Let be the square matrix with columns and . By Step 2, and , so . is invertible with , so . For , the equation becomes : oscillators that do not interact.
Step 4: the modal steps equal the full steps
The full code does , then . Let and , with and , so that and . By Step 3, with . So the full velocity step is times the modal step , and the position step is times . By induction on the number of steps, the full shape is after every step, which is what L6 returns.
Step 5: a truncated basis keeps its modes exactly
The modal updates of Step 4 for mode use only , and . So the code with the first modes computes the same as the full basis, and these are of the full solution . The error is , the part of in the dropped modes. For a static load, for , so the error in the norm is , which does not increase with and is zero for .
Step 6: the zero modes are the rigid motions
for and exactly when , so exactly when on each triangle is with the rotation by a right angle. If two triangles share an edge with the distinct end points , , two such fields that agree at both points have , so and then . The grid is connected through edges, so the null space of the full is the 3-dimensional space of the two translations and the field , and a free body has exactly 3 zero eigenvalues. If two distinct nodes are fixed, a field that is zero at both is zero, so is positive definite and every .
Step 7: the rotation mode at finite amplitude
The field gives on every triangle. , so each triangle, and the mesh, has its area times . , so the Green strain is , and the St. Venant-Kirchhoff energy density is . So a mesh of area has the energy , while the linear energy is 0 by Step 6.
References
- Alex Pentland and John Williams, Good vibrations, modal dynamics for graphics and animation, SIGGRAPH 1989, Computer Graphics 23(3), the use of a few vibration modes of a finite element model as the degrees of freedom of an animated object (general locator)
- Jernej Barbič and Doug L. James, Real-time subspace integration for St. Venant-Kirchhoff deformable models, ACM Transactions on Graphics 24(3), 2005, 982 to 990, the basis of linear modes and modal derivatives, and the reduced internal forces that are cubic polynomials of the reduced coordinates (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, the part on model reduction (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 | W2 basic |
|
Tag CSEPNJ Edit this page History Report an error Markdown