Algorithm Search⌘K

Definitioncore

Deformation gradient

Also called deformation gradient tensor.

The Jacobian F of the map from rest to deformed positions, constant on a linear triangle or tetrahedron, from which strain and stress are computed.

The deformation gradient FF is the Jacobian of the map that takes each point of a body in its rest shape to its point in the deformed shape. It describes how a small neighborhood of the point is stretched, sheared and turned. In a mesh of linear triangles or tetrahedra the map is affine on each element, so FF is one constant matrix per element, F=DsDm−1F = D_sD_m^{-1}, computed from the edge vectors. All strain measures and all stresses of the elastic models on the neighboring pages start from FF.

Definition

Let a body occupy the rest region Ω⊂Rd\Omega \subset \mathbb R^d with d=2d = 2 or 3, and let the deformation φ:Ω→Rd\varphi: \Omega \to \mathbb R^d map each rest point XX to its current point x=φ(X)x = \varphi(X). The deformation gradient is

F(X)=∂φ∂X(X),Fij=∂φi∂Xj.F(X) = \frac{\partial\varphi}{\partial X}(X), \qquad F_{ij} = \frac{\partial\varphi_i}{\partial X_j}.

A small rest vector dXdX at XX is mapped to dx=F dXdx = F\,dX at first order. The derived quantities are:

  • J=det⁡FJ = \det F, the ratio of the current to the rest volume (in 2D, area) near XX. J>0J > 0 for a deformation that keeps the orientation, J=0J = 0 for a flat element and J<0J < 0 for an inverted one.
  • The right Cauchy-Green tensor C=FTFC = F^TF, with ∣dx∣2=dXTC dX|dx|^2 = dX^TC\,dX.
  • The Green strain E=12(FTF−I)E = \frac12(F^TF - I), with ∣dx∣2−∣dX∣2=2 dXTE dX|dx|^2 - |dX|^2 = 2\,dX^TE\,dX. With the displacement gradient H=F−IH = F - I, E=12(H+HT)+12HTHE = \frac12(H + H^T) + \frac12H^TH; the first term alone is the linear (small) strain.
  • The polar decomposition F=RSF = RS with a rotation RR and a symmetric SS, which is positive definite when J>0J > 0. RR is the part of the deformation that only turns the neighborhood.

Linear elements. For a simplex with rest vertices X0,…,XdX_0, \dots, X_d and current vertices x0,…,xdx_0, \dots, x_d, define the edge matrices

Dm=[X1−X0,…,Xd−X0],Ds=[x1−x0,…,xd−x0].D_m = [X_1 - X_0, \dots, X_d - X_0], \qquad D_s = [x_1 - x_0, \dots, x_d - x_0].

If det⁡Dm≠0\det D_m \ne 0, the only affine map with φ(Xk)=xk\varphi(X_k) = x_k has the gradient F=DsDm−1F = D_sD_m^{-1}, constant on the element. Dm−1D_m^{-1} depends only on the rest shape, so a simulator computes it once per element.

Properties. These are proved properties, shown in the proof.

  • FF reproduces every affine map exactly and does not depend on the numbering of the vertices.
  • J=det⁡Ds/det⁡DmJ = \det D_s/\det D_m, the ratio of the signed measures.
  • The gradient of a composition is the product: F2∘1=F2F1F_{2 \circ 1} = F_2F_1.
  • E(QF)=E(F)E(QF) = E(F) for every rotation QQ, and E=0E = 0 exactly when FF is orthogonal. A reflection, det⁡F=−1\det F = -1, also has E=0E = 0: the Green strain does not see inversion.
  • For a smooth φ\varphi and a simplex of size hh at X0X_0, F−∇φ(X0)=O(h)F - \nabla\varphi(X_0) = O(h).
  • In 2D, R=rot⁡(θ)R = \operatorname{rot}(\theta) with θ=atan2⁡(F10−F01,F00+F11)\theta = \operatorname{atan2}(F_{10} - F_{01}, F_{00} + F_{11}), the rotation that maximizes tr⁡(RTF)\operatorname{tr}(R^TF).

Examples and non-examples

Take the rest triangle (0,0)(0, 0), (2,0)(2, 0), (0,1)(0, 1), so Dm=diag⁡(2,1)D_m = \operatorname{diag}(2, 1) and Dm−1=diag⁡(0.5,1)D_m^{-1} = \operatorname{diag}(0.5, 1).

Current vertices FF JJ EE RR
(0,0)(0, 0), (3,0)(3, 0), (0,1)(0, 1) (1.5001)\begin{pmatrix}1.5 & 0\\0 & 1\end{pmatrix} 1.5 (0.625000)\begin{pmatrix}0.625 & 0\\0 & 0\end{pmatrix} II
(1,1)(1, 1), (3,1)(3, 1), (1.5,2)(1.5, 2) (10.501)\begin{pmatrix}1 & 0.5\\0 & 1\end{pmatrix} 1 (00.250.250.125)\begin{pmatrix}0 & 0.25\\0.25 & 0.125\end{pmatrix} rot⁡(−0.244979)\operatorname{rot}(-0.244979)
(0,0)(0, 0), (0,2)(0, 2), (−1,0)(-1, 0) (0−110)\begin{pmatrix}0 & -1\\1 & 0\end{pmatrix} 1 0 rot⁡(π/2)\operatorname{rot}(\pi/2)
(0,0)(0, 0), (2,0)(2, 0), (1,0)(1, 0) (1100)\begin{pmatrix}1 & 1\\0 & 0\end{pmatrix} 0 (00.50.50)\begin{pmatrix}0 & 0.5\\0.5 & 0\end{pmatrix} rot⁡(−π/4)\operatorname{rot}(-\pi/4)
(0,0)(0, 0), (2,0)(2, 0), (0.5,−1)(0.5, -1) (10.50−1)\begin{pmatrix}1 & 0.5\\0 & -1\end{pmatrix} −1-1 (00.250.250.125)\begin{pmatrix}0 & 0.25\\0.25 & 0.125\end{pmatrix} rot⁡(−π/2)\operatorname{rot}(-\pi/2)
  • The first row is a stretch by 1.5 along xx: E00=(1.52−1)/2=0.625E_{00} = (1.5^2 - 1)/2 = 0.625, while the linear strain would be 0.5.
  • The second row is a translation by (1,1)(1, 1) and a shear. The translation does not appear in FF, and the shear has J=1J = 1, so the area does not change.
  • The third row is a rotation by 90 degrees. FF is far from II, but E=0E = 0, so a model built on EE gives no force. The linear strain 12(H+HT)=−I\frac12(H + H^T) = -I is not zero; this is why linear elasticity fails under rotation.
  • The fourth row is flat, J=0J = 0, so FF has no inverse.
  • The fifth row is inverted, J=−1J = -1, but its EE equals the EE of the shear in the second row. So EE alone cannot tell an inverted element from a valid one; the sign of JJ can. Its SS has one negative eigenvalue.

A non-example: the matrix DsD_s alone is not the deformation gradient, because it also depends on the size and the shape of the rest element. Another non-example: on a quadratic element the map is not affine, so FF changes inside the element, and one matrix per element is only an approximation.

Proof: The deformation gradient of a linear element is the gradient of its affine map, with the stated properties of J, the Green strain and the polar factorfull

Let a simplex in Rd\mathbb R^d (d=2d = 2 or 3) have the rest vertices X0,…,XdX_0, \dots, X_d with det⁡Dm≠0\det D_m \ne 0, where Dm=[X1−X0,…,Xd−X0]D_m = [X_1 - X_0, \dots, X_d - X_0], and the current vertices x0,…,xdx_0, \dots, x_d with Ds=[x1−x0,…,xd−x0]D_s = [x_1 - x_0, \dots, x_d - x_0]. The code computes F=DsDm−1F = D_sD_m^{-1}.

Step 1: FF is the gradient of the unique affine map

An affine map φ(X)=AX+t\varphi(X) = AX + t with φ(Xk)=xk\varphi(X_k) = x_k for all kk must satisfy A(Xk−X0)=xk−x0A(X_k - X_0) = x_k - x_0 for k=1,…,dk = 1, \dots, d, that is ADm=DsAD_m = D_s. Since DmD_m is invertible, A=DsDm−1=FA = D_sD_m^{-1} = F is the only solution, and t=x0−FX0t = x_0 - FX_0. So FF is the gradient of the linear interpolant of the vertex positions, and if x=AX+tx = AX + t for some affine map, then F=AF = A exactly. The interpolant does not depend on how the vertices are numbered, so neither does FF. □\square

Step 2: J=det⁡FJ = \det F is the ratio of the signed measures

The signed measure of a simplex is det⁡D/d!\det D/d!. By Step 1, det⁡Ds=det⁡(FDm)=det⁡Fdet⁡Dm\det D_s = \det(FD_m) = \det F\det D_m, so J=det⁡Ds/det⁡DmJ = \det D_s/\det D_m, the ratio of the current to the rest measure with sign. J<0J < 0 exactly when the orientation of the simplex is reversed, which is an inverted element, and J=0J = 0 exactly when it is flat. □\square

Step 3: composition

Let φ1\varphi_1 map the rest simplex to a middle simplex yy and φ2\varphi_2 map yy to xx, both affine with the gradients F1F_1 and F2F_2. Then φ2∘φ1\varphi_2 \circ \varphi_1 is affine with the gradient F2F1F_2F_1 and maps XkX_k to xkx_k, so by Step 1 the deformation gradient from XX to xx is F2F1F_2F_1. □\square

Step 4: the Green strain

E=(FTF−I)/2E = (F^TF - I)/2. For a rotation QQ, (QF)T(QF)=FTQTQF=FTF(QF)^T(QF) = F^TQ^TQF = F^TF, so E(QF)=E(F)E(QF) = E(F): a rotation after the deformation does not change the strain. E=0E = 0 exactly when FTF=IF^TF = I, that is when FF is orthogonal. An orthogonal FF is a rotation if det⁡F=1\det F = 1 and a reflection if det⁡F=−1\det F = -1, so EE is zero for every rigid motion, and also for a mirror image, which EE cannot tell apart from the rest shape. With F=I+HF = I + H, FTF=I+H+HT+HTHF^TF = I + H + H^T + H^TH, so

E=12(H+HT)+12HTH,E = \tfrac12(H + H^T) + \tfrac12H^TH,

and for HH replaced by εH\varepsilon H the difference between EE and the linear strain 12ε(H+HT)\frac12\varepsilon(H + H^T) is 12ε2HTH\frac12\varepsilon^2H^TH, which falls by a factor of 4 when ε\varepsilon is halved. □\square

Step 5: small elements of a smooth map

Let φ\varphi be twice continuously differentiable, and let the rest simplex have the vertices X0X_0 and Xk=X0+hukX_k = X_0 + hu_k with fixed uku_k and det⁡[u1,…,ud]≠0\det[u_1, \dots, u_d] \ne 0. By Taylor's theorem, φ(Xk)−φ(X0)=h∇φ(X0)uk+h22rk\varphi(X_k) - \varphi(X_0) = h\nabla\varphi(X_0)u_k + \frac{h^2}{2}r_k with rkr_k bounded independently of hh. So Ds=h∇φ(X0)U+h22[r1,…,rd]D_s = h\nabla\varphi(X_0)U + \frac{h^2}{2}[r_1, \dots, r_d] with U=[u1,…,ud]U = [u_1, \dots, u_d], Dm=hUD_m = hU, and

F−∇φ(X0)=h2[r1,…,rd]U−1.F - \nabla\varphi(X_0) = \tfrac h2[r_1, \dots, r_d]U^{-1}.

The error is O(h)O(h), and [r1,…,rd]→∇2φ(X0)[uk,uk][r_1, \dots, r_d] \to \nabla^2\varphi(X_0)[u_k, u_k] column by column as h→0h \to 0, so the error divided by hh has a limit and the error halves when hh halves, unless that limit is zero. □\square

Step 6: the polar factor in 2D

For a rotation R(θ)R(\theta) with c=cos⁡θc = \cos\theta and s=sin⁡θs = \sin\theta, tr⁡(RTF)=c(F00+F11)+s(F10−F01)\operatorname{tr}(R^TF) = c(F_{00} + F_{11}) + s(F_{10} - F_{01}). With ρ=(F00+F11)2+(F10−F01)2\rho = \sqrt{(F_{00} + F_{11})^2 + (F_{10} - F_{01})^2} this is ρcos⁡(θ−θ∗)\rho\cos(\theta - \theta^*) with θ∗=atan2⁡(F10−F01,F00+F11)\theta^* = \operatorname{atan2}(F_{10} - F_{01}, F_{00} + F_{11}), which is largest at θ=θ∗\theta = \theta^*, the angle of the code. For this angle, the off-diagonal entries of S=RTFS = R^TF are cF01+sF11cF_{01} + sF_{11} and −sF00+cF10-sF_{00} + cF_{10}, and their difference c(F01−F10)+s(F00+F11)c(F_{01} - F_{10}) + s(F_{00} + F_{11}) is ρ(−sin⁡θ∗cos⁡θ∗+cos⁡θ∗sin⁡θ∗)=0\rho(-\sin\theta^*\cos\theta^* + \cos\theta^*\sin\theta^*) = 0, so SS is symmetric and F=RSF = RS. tr⁡S=ρ≥0\operatorname{tr}S = \rho \ge 0 and det⁡S=det⁡F\det S = \det F, so if det⁡F>0\det F > 0 both eigenvalues of SS are positive and SS is the positive definite polar factor. Then FTF=STRTRS=S2F^TF = S^TR^TRS = S^2, so E(F)=E(S)E(F) = E(S), which is also true in 3D for the factors of anim.polar. ■\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
deformation_gradient.py 52 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deformation-gradient/. The authors are listed in prov/1C1F35.jsonl.
"""The deformation gradient of a linear triangle (2D) or tetrahedron (3D).

For rest vertices X_0, ..., X_d and current vertices x_0, ..., x_d, the edge
matrices are D_m = [X_1 - X_0, ..., X_d - X_0] and D_s = [x_1 - x_0, ...],
and F = D_s D_m^(-1). The quantities derived from F are J = det F, the right
Cauchy-Green tensor C = F^T F, the Green strain E = (C - I) / 2 and the
polar decomposition F = R S, which comes from anim.polar.

Matrices are lists of rows, and vectors are tuples or lists.
"""

import math

from anim import det, inv, mul, polar, transpose


def edge_matrix(points):
    """D = [p_1 - p_0, ..., p_d - p_0] as a d by d matrix (the edges are columns)."""
    d = len(points) - 1
    return [[points[k + 1][i] - points[0][i] for k in range(d)] for i in range(d)]


def deformation_gradient(rest, cur):
    """F = D_s D_m^(-1) for one simplex with rest vertices rest and current vertices cur."""
    dm = edge_matrix(rest)
    if det(dm) == 0.0:
        raise ValueError("the rest simplex is degenerate")
    return mul(edge_matrix(cur), inv(dm))


def right_cauchy_green(f):
    """C = F^T F."""
    return mul(transpose(f), f)


def green_strain(f):
    """E = (F^T F - I) / 2."""
    c = right_cauchy_green(f)
    return [[0.5 * (c[i][j] - (1.0 if i == j else 0.0)) for j in range(len(f))] for i in range(len(f))]


def simplex_measure(points):
    """The signed area (2D) or volume (3D) of a simplex: det D / d!."""
    d = len(points) - 1
    return det(edge_matrix(points)) / math.factorial(d)


def polar_decomposition(f):
    """F = R S with det R = +1 and S symmetric; S is positive definite when det F > 0."""
    return polar(f)
test_deformation_gradient.py 158 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deformation-gradient/. The authors are listed in prov/1C1F35.jsonl.
"""Tests of the deformation gradient of linear triangles and tetrahedra.

F reproduces every affine map, does not depend on the order of the
vertices, has det F equal to the ratio of the measures, composes by the
product rule, and approaches the Jacobian of a smooth map at first order.
The Green strain is zero exactly for rigid motions and is the symmetric
gradient at first order. The 2D polar factor is checked against a scan of
all rotations.
"""

import itertools
import math
import random

from anim import det, mul, q_normalize, q_to_mat3, transpose
from deformation_gradient import deformation_gradient, green_strain, polar_decomposition, simplex_measure


def close(a, b, tol):
    return all(abs(a[i][j] - b[i][j]) <= tol for i in range(len(a)) for j in range(len(a[0])))


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


def rand_simplex(rng, d):
    while True:
        pts = [tuple(rng.uniform(-1, 1) for _ in range(d)) for _ in range(d + 1)]
        if abs(simplex_measure(pts)) > 0.05:
            return pts


def apply(a, t, p):
    return tuple(sum(a[i][k] * p[k] for k in range(len(p))) + t[i] for i in range(len(p)))


def rotation(rng, d):
    if d == 2:
        th = rng.uniform(-math.pi, math.pi)
        return [[math.cos(th), -math.sin(th)], [math.sin(th), math.cos(th)]]
    return q_to_mat3(q_normalize([rng.gauss(0, 1) for _ in range(4)]))


def test_affine_maps_are_reproduced_exactly():
    rng = random.Random(1)
    for d in (2, 3):
        for _ in range(200):
            a, t = rand_mat(rng, d), [rng.uniform(-3, 3) for _ in range(d)]
            rest = rand_simplex(rng, d)
            f = deformation_gradient(rest, [apply(a, t, p) for p in rest])
            assert close(f, a, 1e-9)


def test_vertex_order_does_not_matter():
    rng = random.Random(2)
    for d in (2, 3):
        rest = rand_simplex(rng, d)
        cur = [tuple(c + rng.uniform(-0.3, 0.3) for c in p) for p in rest]
        f0 = deformation_gradient(rest, cur)
        for perm in itertools.permutations(range(d + 1)):
            f = deformation_gradient([rest[i] for i in perm], [cur[i] for i in perm])
            assert close(f, f0, 1e-9)


def test_det_is_the_ratio_of_measures():
    rng = random.Random(3)
    for d in (2, 3):
        for _ in range(200):
            rest = rand_simplex(rng, d)
            cur = [tuple(c + rng.uniform(-0.6, 0.6) for c in p) for p in rest]
            j = det(deformation_gradient(rest, cur))
            assert abs(j - simplex_measure(cur) / simplex_measure(rest)) < 1e-9 * (1 + abs(j))


def test_inversion_flips_the_sign_of_j():
    rest = [(0, 0), (1, 0), (0, 1)]
    for y, sign in ((0.5, 1), (1e-9, 1), (-1e-9, -1), (-0.5, -1)):
        assert math.copysign(1, det(deformation_gradient(rest, [(0, 0), (1, 0), (0.2, y)]))) == sign


def test_composition_is_the_product():
    rng = random.Random(4)
    for d in (2, 3):
        a, b = rand_mat(rng, d, 0.5), rand_mat(rng, d, 0.5)
        rest = rand_simplex(rng, d)
        mid = [apply(a, [0.0] * d, p) for p in rest]
        end = [apply(b, [1.0] * d, p) for p in mid]
        f = deformation_gradient(rest, end)
        assert close(f, mul(deformation_gradient(mid, end), deformation_gradient(rest, mid)), 1e-9)


def test_green_strain_is_zero_exactly_for_rigid_motions():
    rng = random.Random(5)
    for d in (2, 3):
        for _ in range(100):
            q = rotation(rng, d)
            f = rand_mat(rng, d, 0.4)
            assert close(green_strain(q), [[0.0] * d for _ in range(d)], 1e-12)
            assert close(green_strain(mul(q, f)), green_strain(f), 1e-12)
            e = green_strain(f)
            if max(abs(v) for r in e for v in r) > 1e-3:
                assert not close(e, [[0.0] * d for _ in range(d)], 1e-6)


def test_green_strain_is_the_symmetric_gradient_at_first_order():
    rng = random.Random(6)
    h = [[rng.uniform(-1, 1) for _ in range(3)] for _ 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)]
        e = green_strain(f)
        errs.append(max(abs(e[i][j] - 0.5 * eps * (h[i][j] + h[j][i])) for i in range(3) for j in range(3)))
    assert 3.5 < errs[0] / errs[1] < 4.5


def test_small_elements_approach_the_jacobian():
    def phi(p):
        x, y = p
        return (x + 0.3 * math.sin(y) + 0.2 * x * x, y + 0.1 * x * y)

    x0 = (0.4, 0.7)
    jac = [[1 + 0.4 * x0[0], 0.3 * math.cos(x0[1])], [0.1 * x0[1], 1 + 0.1 * x0[0]]]
    errs = []
    for hstep in (0.02, 0.01, 0.005):
        rest = [x0, (x0[0] + hstep, x0[1]), (x0[0], x0[1] + hstep)]
        f = deformation_gradient(rest, [phi(p) for p in rest])
        errs.append(max(abs(f[i][j] - jac[i][j]) for i in range(2) for j in range(2)))
    assert 1.8 < errs[0] / errs[1] < 2.2 and 1.8 < errs[1] / errs[2] < 2.2


def test_polar_decomposition_in_3d():
    rng = random.Random(8)
    for _ in range(50):
        f = rand_mat(rng, 3, 0.6)
        if abs(det(f)) < 0.05:
            continue
        r, s = polar_decomposition(f)
        assert close(mul(transpose(r), r), [[1, 0, 0], [0, 1, 0], [0, 0, 1]], 1e-10) and det(r) > 0
        assert close(mul(r, s), f, 1e-10) and close(s, transpose(s), 1e-12)
        assert close(green_strain(f), green_strain(s), 1e-10)


def test_polar_decomposition_in_2d():
    rng = random.Random(7)
    for _ in range(300):
        f = rand_mat(rng, 2, 1.5)
        r, s = polar_decomposition(f)
        assert close(mul(transpose(r), r), [[1, 0], [0, 1]], 1e-12) and det(r) > 0
        assert close(mul(r, s), f, 1e-12) and s[0][1] == s[1][0]
        if det(f) > 0:
            assert s[0][0] > 0 and det(s) > 0
        tr = r[0][0] * f[0][0] + r[1][0] * f[1][0] + r[0][1] * f[0][1] + r[1][1] * f[1][1]
        for k in range(360):
            c, sn = math.cos(k * math.pi / 180), math.sin(k * math.pi / 180)
            assert c * (f[0][0] + f[1][1]) + sn * (f[1][0] - f[0][1]) <= tr + 1e-12

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 deformation map and its gradient, and F = D_s D_m^(-1) for a linear tetrahedron (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 kinematics, with the deformation gradient, the volume change J, the polar decomposition and the Green strain (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/1C1F35/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/1C1F35/text.yaml