Algorithm Search⌘K

Modelcore

St. Venant-Kirchhoff model

Also called StVK material, Saint Venant-Kirchhoff material.

A hyperelastic model with an energy quadratic in the Green strain. Rotations give no stress, but its resistance to strong compression weakens and then reverses.

The St. Venant-Kirchhoff (StVK) model is the simplest hyperelastic model that is correct under rotation. It takes the energy of linear elasticity and puts the Green strain E=12(FTF−I)E = \frac12(F^TF - I) in the place of the small strain:

Ψ(F)=μ∣E∣F2+λ2(tr⁡E)2,S=2μE+λtr⁡(E)I,P=FS.\Psi(F) = \mu\lvert E\rvert_F^2 + \frac\lambda2(\operatorname{tr}E)^2, \qquad S = 2\mu E + \lambda\operatorname{tr}(E)I, \qquad P = FS.

Because EE is zero for every rotation, a turned body has no stress, which fixes the main defect of linear elasticity. The energy is a polynomial of degree 4 in FF, so the forces are cubic in the vertex positions, and this makes the model popular for modal reduction and brittle fracture. Its weakness is strong compression: the restoring force has a largest value, falls to zero when an element is flat, and then pushes the element toward its mirror image.

The machine

State and parameters. The input is a deformation gradient FF, a d×dd \times d matrix with d=2d = 2 or 3, and the two Lamé parameters μ>0\mu > 0 and λ≥0\lambda \ge 0. They come from Young's modulus EYE_Y and Poisson's ratio ν\nu by μ=EY/(2(1+ν))\mu = E_Y/(2(1 + \nu)) and λ=EYν/((1+ν)(1−2ν))\lambda = E_Y\nu/((1 + \nu)(1 - 2\nu)); for EY=1E_Y = 1 and ν=0.3\nu = 0.3, μ=0.384615\mu = 0.384615 and λ=0.576923\lambda = 0.576923.

Energy and stress. The formulas above give the energy per unit rest volume Ψ\Psi, the symmetric second Piola-Kirchhoff stress SS, and the first Piola-Kirchhoff stress P=∂Ψ/∂FP = \partial\Psi/\partial F, the force per unit rest area. P=FSP = FS is the exact derivative for every FF, also for flat and inverted elements; the model never divides by det⁡F\det F.

Forces of a linear element. With the rest edge matrix DmD_m, the rest volume V0V_0 and F=DsDm−1F = D_sD_m^{-1}, the forces on the vertices 1 to dd are the columns of −V0PDm−T-V_0PD_m^{-T}, and vertex 0 gets minus their sum. These are the exact gradient of −V0Ψ(F)-V_0\Psi(F). Each component of FF is linear in the vertex positions, EE is quadratic and PP is cubic, so the forces of a whole mesh are a cubic polynomial in the positions.

The bar. For a bar that is stretched along xx and cannot change its width, F=diag⁡(s,1,1)F = \operatorname{diag}(s, 1, 1), and

Ψ=(μ+λ2)(s2−1)24,Pxx=2μ+λ2(s3−s).\Psi = \Bigl(\mu + \frac\lambda2\Bigr)\frac{(s^2 - 1)^2}4, \qquad P_{xx} = \frac{2\mu + \lambda}2(s^3 - s).

What it counts

Ψ\Psi is the energy that a unit of rest volume stores; its integral over the rest shape is the elastic energy of the body. The model counts only the change of lengths and angles, through C=FTFC = F^TF, so it counts nothing for rotations and translations. It also counts nothing for reflections: Ψ(diag⁡(−1,1,1))=0\Psi(\operatorname{diag}(-1, 1, 1)) = 0, so a mirror image of an element has the same zero energy as its rest shape.

Example. The bar with EY=1E_Y = 1 and ν=0.3\nu = 0.3, so μ+λ/2=0.673077\mu + \lambda/2 = 0.673077 and 2μ+λ=1.3461542\mu + \lambda = 1.346154. The last column is the stress (2μ+λ)(s−1)(2\mu + \lambda)(s - 1) of linear elasticity for the same bar.

ss Ψ\Psi PxxP_{xx} PyyP_{yy} linear PxxP_{xx}
1.5 0.262921 1.262019 0.360577 0.673077
1.2 0.032577 0.355385 0.126923 0.269231
1.0 0 0 0 0
0.8 0.021808 −0.193846-0.193846 −0.103846-0.103846 −0.269231-0.269231
0.577350 0.074786 −0.259067-0.259067 −0.192308-0.192308 −0.568952-0.568952
0.3 0.139344 −0.183750-0.183750 −0.262500-0.262500 −0.942308-0.942308
0 0.168269 0 −0.288462-0.288462 −1.346154-1.346154
−0.5-0.5 0.094651 0.252404 −0.216346-0.216346 −2.019231-2.019231
−1.0-1.0 0 0 0 −2.692308-2.692308

Under tension StVK is stiffer than linear elasticity. Under compression the stress has its largest size, 0.259067, at s=1/3=0.577350s = 1/\sqrt3 = 0.577350, falls to zero at s=0s = 0, and changes sign for −1<s<0-1 < s < 0. In that range the force pushes the bar toward s=−1s = -1, the mirror image, which has zero energy. The energy at the flat state s=0s = 0 is only 0.168269, so a moderate load can push an element through it.

Relation to other models

  • Linear elasticity. StVK has the same energy with EE in the place of the small strain 12(H+HT)\frac12(H + H^T), H=F−IH = F - I. The two agree at first order near rest, but linear elasticity gives a stress for a pure rotation and StVK does not.
  • Corotational FEM. It also removes rotations, but by the polar factor RR of each element, and then applies linear elasticity to RTFR^TF. Its forces are not polynomial, and for the bar with 0<s<10 < s < 1 its stress is the linear one, with no reversal.
  • Neo-Hookean model. It adds a log⁡J\log J term, so the energy grows without bound as an element becomes flat. It is a better model of rubber under large compression, but it is undefined for J≤0J \le 0.
  • Stable neo-Hookean model. It keeps a finite energy at J≤0J \le 0 and a force that pushes toward J>0J > 0.
  • Invertible finite elements. They take any isotropic model, StVK included, and change the energy for inverted elements, so that the force pushes them back.
  • Modal reduction and brittle fracture. Barbič and James use the cubic StVK forces to precompute the reduced forces, and O'Brien and Hodgins use the Green strain with a linear stress, which is StVK.

Known results in the model

  • Exact gradient (proved). P=FSP = FS is ∂Ψ/∂F\partial\Psi/\partial F for every FF, and the element forces are minus the gradient of the element energy. See the proof, Steps 1 and 2.
  • Objective and isotropic (proved). Ψ(QF)=Ψ(FQ)=Ψ(F)\Psi(QF) = \Psi(FQ) = \Psi(F) for every rotation QQ, and PFTPF^T is symmetric. Proof, Step 3.
  • Rest states (proved). P=0P = 0 and Ψ=0\Psi = 0 exactly when FTF=IF^TF = I, which includes every rotation and every reflection. Proof, Step 4.
  • Linear limit (proved). P(I+εH)=ε(2μsym⁡H+λtr⁡(H)I)+O(ε2)P(I + \varepsilon H) = \varepsilon(2\mu\operatorname{sym}H + \lambda\operatorname{tr}(H)I) + O(\varepsilon^2), so μ\mu and λ\lambda are the Lamé parameters without a remap. Proof, Step 5.
  • Weak compression (proved). In the bar the compressive stress has its largest size (2μ+λ)/(33)(2\mu + \lambda)/(3\sqrt3) at s=1/3s = 1/\sqrt3, is zero at s=0s = 0, and for −1<s<0-1 < s < 0 pushes toward the mirror image. Proof, Step 6.
  • Not convex (proved). d2Ψ/ds2<0d^2\Psi/ds^2 < 0 for ∣s∣<1/3\lvert s\rvert < 1/\sqrt3 in the bar, so Ψ\Psi is not convex in FF, and Newton steps need a fix of the stiffness, such as projecting it to be positive semidefinite. The fix is a heuristic.
  • Use in practice (heuristic). StVK works well when the strains stay moderate, such as stiff objects, cloth in its plane and reduced models. When elements can be strongly compressed, simulators use a model with a barrier or an inversion fix instead.
Proof: The St. Venant-Kirchhoff stress is the gradient of its energy, is objective and isotropic, has the linear limit, and weakens and reverses under strong compressionfull

The code works in Rd\mathbb R^d with d=2d = 2 or 3. For a matrix FF it computes E=12(FTF−I)E = \frac12(F^TF - I), Ψ(F)=μ∣E∣F2+λ2(tr⁡E)2\Psi(F) = \mu\lvert E\rvert_F^2 + \frac\lambda2(\operatorname{tr}E)^2, S=2μE+λtr⁡(E)IS = 2\mu E + \lambda\operatorname{tr}(E)I and P=FSP = FS. A:B=tr⁡(ATB)A : B = \operatorname{tr}(A^TB) is the Frobenius inner product. All claims are about exact arithmetic.

Step 1: P=∂Ψ/∂FP = \partial\Psi/\partial F

For a change dFdF, dE=12(dFTF+FTdF)dE = \frac12(dF^TF + F^TdF), the symmetric part of FTdFF^TdF. Then dΨ=2μE:dE+λtr⁡(E)tr⁡(dE)=S:dEd\Psi = 2\mu E : dE + \lambda\operatorname{tr}(E)\operatorname{tr}(dE) = S : dE. SS is symmetric, and a symmetric matrix has a zero inner product with every antisymmetric one, so S:dE=S:FTdF=FS:dFS : dE = S : F^TdF = FS : dF. So dΨ=P:dFd\Psi = P : dF with P=FSP = FS. No step uses det⁡F>0\det F > 0, so this holds for every FF, also for flat and inverted ones. □\square

Step 2: the element forces are minus the gradient of the element energy

For a linear element with the rest edge matrix DmD_m, the rest measure V0=det⁡Dm/d!V_0 = \det D_m/d! and the current edge matrix DsD_s, the code uses F=DsDm−1F = D_sD_m^{-1} and W=V0Ψ(F)W = V_0\Psi(F). By Step 1, dW=V0P:dDsDm−1=V0PDm−T:dDsdW = V_0P : dD_sD_m^{-1} = V_0PD_m^{-T} : dD_s. Column kk of DsD_s is xk−x0x_k - x_0, so ∂W/∂xk\partial W/\partial x_k is column kk of V0PDm−TV_0PD_m^{-T} for k=1,…,dk = 1, \dots, d, and ∂W/∂x0\partial W/\partial x_0 is minus their sum. The code returns minus these vectors, so the forces are −∂W/∂x-\partial W/\partial x and they sum to zero. □\square

Step 3: objectivity, isotropy and no torque

For a rotation QQ, (QF)T(QF)=FTF(QF)^T(QF) = F^TF, so E(QF)=E(F)E(QF) = E(F) and Ψ(QF)=Ψ(F)\Psi(QF) = \Psi(F); also S(QF)=S(F)S(QF) = S(F) and P(QF)=QFS=QP(F)P(QF) = QFS = QP(F). For the rest side, (FQ)T(FQ)=QTFTFQ(FQ)^T(FQ) = Q^TF^TFQ, so E(FQ)=QTE(F)QE(FQ) = Q^TE(F)Q, which has the same Frobenius norm and the same trace; so Ψ(FQ)=Ψ(F)\Psi(FQ) = \Psi(F). PFT=FSFTPF^T = FSF^T is symmetric because SS is, so the forces of an element have no net torque. □\square

Step 4: the rest state, rigid motions and mirror images

If FTF=IF^TF = I, then E=0E = 0, S=0S = 0, P=0P = 0 and Ψ=0\Psi = 0. This includes F=IF = I, every rotation, and every reflection such as diag⁡(−1,1,1)\operatorname{diag}(-1, 1, 1). So a mirror image of the rest shape has zero energy and zero stress: it is a second rest state. □\square

Step 5: the linear limit

Let F=I+εHF = I + \varepsilon H. Then E=εsym⁡H+ε22HTHE = \varepsilon\operatorname{sym}H + \frac{\varepsilon^2}2H^TH with sym⁡H=12(H+HT)\operatorname{sym}H = \frac12(H + H^T), so S=ε(2μsym⁡H+λtr⁡(H)I)+O(ε2)S = \varepsilon(2\mu\operatorname{sym}H + \lambda\operatorname{tr}(H)I) + O(\varepsilon^2) and

P=(I+εH)S=ε(2μsym⁡H+λtr⁡(H)I)+O(ε2).P = (I + \varepsilon H)S = \varepsilon\bigl(2\mu\operatorname{sym}H + \lambda\operatorname{tr}(H)I\bigr) + O(\varepsilon^2).

So P(I+εH)/εP(I + \varepsilon H)/\varepsilon differs from the linear stress by O(ε)O(\varepsilon), and μ\mu and λ\lambda are the Lamé parameters of the linear limit. □\square

Step 6: the bar under compression

Let F=diag⁡(s,1,1)F = \operatorname{diag}(s, 1, 1). Then E=diag⁡(s2−12,0,0)E = \operatorname{diag}(\frac{s^2 - 1}2, 0, 0), so ∣E∣F2=(tr⁡E)2=(s2−1)24\lvert E\rvert_F^2 = (\operatorname{tr}E)^2 = \frac{(s^2 - 1)^2}4 and

Ψ=(μ+λ2)(s2−1)24.\Psi = \Bigl(\mu + \frac\lambda2\Bigr)\frac{(s^2 - 1)^2}4.

Sxx=(2μ+λ)s2−12S_{xx} = (2\mu + \lambda)\frac{s^2 - 1}2 and Syy=Szz=λs2−12S_{yy} = S_{zz} = \lambda\frac{s^2 - 1}2, so Pxx=sSxx=c(s3−s)P_{xx} = sS_{xx} = c(s^3 - s) with c=μ+λ2>0c = \mu + \frac\lambda2 > 0, and Pyy=Pzz=SyyP_{yy} = P_{zz} = S_{yy}. This PxxP_{xx} is also dΨ/dsd\Psi/ds.

  • For 0<s<10 < s < 1, s3−s<0s^3 - s < 0, so Pxx<0P_{xx} < 0: the stress pushes the bar back toward s=1s = 1.
  • dPxx/ds=c(3s2−1)dP_{xx}/ds = c(3s^2 - 1) is zero on (0,1)(0, 1) only at s=1/3s = 1/\sqrt3, negative before it and positive after it. So the size of the compressive stress grows as ss falls from 1 to 1/31/\sqrt3, has its largest value 2c/(33)2c/(3\sqrt3) there, and then falls to zero at s=0s = 0.
  • For −1<s<0-1 < s < 0, s3−s=s(s2−1)>0s^3 - s = s(s^2 - 1) > 0, so Pxx>0P_{xx} > 0. The force −dW/ds-dW/ds is negative, so it pushes ss toward −1-1, the mirror image of Step 4, and not back toward s=1s = 1.
  • d2Ψ/ds2=c(3s2−1)<0d^2\Psi/ds^2 = c(3s^2 - 1) < 0 for ∣s∣<1/3\lvert s\rvert < 1/\sqrt3, so Ψ\Psi is not convex along this line, and so not convex in FF. ■\blacksquare

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.

anim.pyI0RawGitHub
# 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
st_venant_kirchhoff_model.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/st-venant-kirchhoff-model/. The authors are listed in prov/H0C71P.jsonl.
"""The St. Venant-Kirchhoff (StVK) hyperelastic model in 2D or 3D.

    E = (F^T F - I) / 2                       the Green strain
    Psi(F) = mu |E|_F^2 + (lambda / 2) tr(E)^2
    S = 2 mu E + lambda tr(E) I               the second Piola-Kirchhoff stress
    P = F S                                   the first Piola-Kirchhoff stress

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.

For the deformation F = diag(s, 1, 1) (a bar that cannot shrink sideways),
Psi = (mu + lambda / 2) (s^2 - 1)^2 / 4 and P_xx = (2 mu + lambda) (s^3 - s) / 2.
"""

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 green_strain(f):
    c = mul(transpose(f), f)
    d = len(f)
    return [[0.5 * (c[i][j] - (1.0 if i == j else 0.0)) for j in range(d)] for i in range(d)]


def energy_density(f, mu, lam):
    e = green_strain(f)
    tr = sum(e[i][i] for i in range(len(f)))
    return mu * sum(v * v for row in e for v in row) + 0.5 * lam * tr * tr


def pk2(f, mu, lam):
    e = green_strain(f)
    d = len(f)
    tr = sum(e[i][i] for i in range(d))
    return [[2.0 * mu * e[i][j] + (lam * tr if i == j else 0.0) for j in range(d)] for i in range(d)]


def pk1(f, mu, lam):
    return mul(f, pk2(f, mu, lam))


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)
    fact = 2.0 if d == 2 else 6.0
    v0 = det(dm) / fact
    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)
    fact = 2.0 if len(dm) == 2 else 6.0
    f = mul(edge_matrix(cur), inv(dm))
    return det(dm) / fact * energy_density(f, mu, lam)


def bar_stress(s, mu, lam):
    """P_xx for F = diag(s, 1, 1): (2 mu + lambda) (s^3 - s) / 2."""
    return 0.5 * (2.0 * mu + lam) * (s ** 3 - s)


def linearized_stress(h, mu, lam):
    """The small strain stress 2 mu sym(H) + lambda tr(H) I, the limit of P(I + H) at first order."""
    d = len(h)
    tr = sum(h[i][i] for i in range(d))
    return [[mu * (h[i][j] + h[j][i]) + (lam * tr if i == j else 0.0) for j in range(d)] for i in range(d)]
test_st_venant_kirchhoff_model.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/st-venant-kirchhoff-model/. The authors are listed in prov/H0C71P.jsonl.
"""Tests of the St. Venant-Kirchhoff model.

The stress is checked against the central difference gradient of the
energy density (also for inverted F), the element forces against the
gradient of the element energy, and the model against rotations of the
deformed and the rest shape. The bar formulas give the largest compressive
force at s = 1/sqrt(3), zero force at s = 0, and a force toward the
inverted state for -1 < s < 0.
"""

import math
import random

from anim import det, mul, num_grad, q_normalize, q_to_mat3, transpose
from st_venant_kirchhoff_model import (
    bar_stress,
    element_energy,
    element_forces,
    energy_density,
    lame,
    linearized_stress,
    pk1,
    pk2,
)

MU, LAM = lame(1.0, 0.3)


def rand_mat(rng, d, amount=0.6):
    return [[(1.0 if i == j else 0.0) + rng.uniform(-amount, amount) for j in range(d)] for i in range(d)]


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)]]
    q = q_normalize(tuple(rng.gauss(0.0, 1.0) for _ in range(4)))
    return q_to_mat3(q)


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 trial in range(20):
            f = rand_mat(rng, d)
            if trial % 4 == 0:
                f[0] = [-v for v in f[0]]
            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):
        for _ in range(10):
            rest = [tuple(rng.uniform(-1, 1) for _ in range(d)) for _ in range(d + 1)]
            if d == 2:
                m = (rest[1][0] - rest[0][0]) * (rest[2][1] - rest[0][1]) - (rest[1][1] - rest[0][1]) * (rest[2][0] - rest[0][0])
            else:
                m = det([[rest[k + 1][i] - rest[0][i] for k in range(3)] for i in range(3)])
            if abs(m) < 0.05:
                continue
            if m < 0:
                rest[1], rest[2] = rest[2], rest[1]
            cur = [tuple(c + rng.uniform(-0.4, 0.4) 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


def test_rest_state_and_rotations_have_no_stress():
    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 maxdiff(pk1(eye, MU, LAM), [[0.0] * d for _ in range(d)]) == 0.0
        q = rotation(rng, d)
        assert energy_density(q, MU, LAM) < 1e-24
        assert maxdiff(pk1(q, MU, LAM), [[0.0] * d for _ in range(d)]) < 1e-12


def test_pk2_symmetric_and_torque_free():
    rng = random.Random(5)
    for d in (2, 3):
        for _ in range(20):
            f = rand_mat(rng, d)
            s = pk2(f, MU, LAM)
            assert maxdiff(s, transpose(s)) < 1e-14
            pft = mul(pk1(f, MU, LAM), transpose(f))
            assert maxdiff(pft, transpose(pft)) < 1e-12


def test_linear_limit():
    rng = random.Random(6)
    h = [[rng.uniform(-1, 1) for _ in range(3)] for _ in range(3)]
    lin = linearized_stress(h, MU, LAM)
    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 (-1.5, -0.7, -0.2, 0.0, 0.3, 0.9, 1.0, 1.4):
        f = [[s, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
        psi = (MU + 0.5 * LAM) * (s * s - 1.0) ** 2 / 4.0
        assert abs(energy_density(f, MU, LAM) - psi) < 1e-14
        p = pk1(f, MU, LAM)
        assert abs(p[0][0] - bar_stress(s, MU, LAM)) < 1e-14
        assert abs(p[1][1] - LAM * (s * s - 1.0) / 2.0) < 1e-14


def test_compression_force_peaks_then_reverses():
    n = 20000
    best_s, best_p = None, 0.0
    for k in range(1, n):
        s = k / n
        p = bar_stress(s, MU, LAM)
        assert p < 0.0
        if p < best_p:
            best_s, best_p = s, p
    assert abs(best_s - 1.0 / math.sqrt(3.0)) < 1e-4
    assert bar_stress(0.0, MU, LAM) == 0.0
    for k in range(1, 100):
        s = -k / 100.0
        assert bar_stress(s, MU, LAM) > 0.0
    inverted = [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    assert energy_density(inverted, MU, LAM) == 0.0
    assert maxdiff(pk1(inverted, MU, LAM), [[0.0] * 3 for _ in range(3)]) == 0.0


def test_bar_energy_not_convex_near_flat():
    c = MU + 0.5 * LAM
    for s in (-0.5, 0.0, 0.5):
        h = 1e-4
        second = (bar_stress(s + h, MU, LAM) - bar_stress(s - h, MU, LAM)) / (2 * h)
        assert abs(second - c * (3 * s * s - 1.0)) < 1e-6
        assert second < 0.0

References

  1. 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 St. Venant-Kirchhoff energy and its first Piola-Kirchhoff stress, and its behavior under compression (general locator)
  2. Javier Bonet and Richard D. Wood, Nonlinear Continuum Mechanics for Finite Element Analysis, second edition, Cambridge University Press, 2008, the chapter on hyperelasticity, with the Green strain and the second Piola-Kirchhoff stress (general locator)
  3. Jernej Barbič and Doug L. James, Real-time subspace integration for St. Venant-Kirchhoff deformable models, ACM Transactions on Graphics 24(3), SIGGRAPH 2005, 982 to 990, the StVK internal forces as cubic polynomials of the reduced coordinates (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.

LadderLevelWhat the next level needs
Human proofH2 full proof
  • correctness: no review record reviews/H0C71P/proof-correctness.yaml
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/H0C71P/text.yaml