Algorithmadvanced
Projective dynamics
Also called projective implicit dynamics.
Solve implicit Euler by alternating local projections of elements onto constraint sets and a global linear solve with a constant prefactored matrix.
- Time
- Θ(T + z) iterationO(n^3) setupO(K (T + z)) step
- Space
- O(n + T + z) step
- Where
- K = the number of local and global iterations per step; T = the number of elements; n = the number of free vertices; z = the number of nonzeros of the Cholesky factor
- Model
- Real RAM
- Properties
- constant system matrixdeterministicnot exactlinear momentum conservingmonotone objective
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Sofien Bouaziz, Sebastian Martin, Tiantian Liu, Ladislav Kavan, Mark Pauly, 2014
Projective dynamics (PD) takes a backward Euler step of a deformable body by minimizing the inertia term plus a sum of energies of a special form: the squared distance of each element from a constraint set, such as the set of rotations. Bouaziz, Martin, Liu, Kavan and Pauly (2014) solve this minimization by alternating two steps. The local step projects every element onto its set, independently and in parallel. The global step solves a linear system whose matrix never changes, so it is factored once by Cholesky decomposition. Each pair of steps never increases the objective, which makes the method robust at large time steps, but it converges only linearly.
In plain words
Think of a sheet made of small triangles. Each triangle wants to be a turned copy of its rest shape. First let the sheet fly freely for one frame. Then repeat two moves. In the first move, look at each triangle alone and find the turned copy of its rest shape that is closest to it; this is quick and every triangle can do it at the same time. In the second move, find the positions of all corners that best agree with all these copies at once and with where the free flight wanted them. This is one linear system, and it is the same system in every frame, so you prepare it once and then each solve is cheap. Each round makes the total mismatch smaller or keeps it the same.
The problem
The input is a mesh with lumped vertex masses , rest shape, positions , velocities , a step and a set of elements, each with a weight and a constraint set . The output is the next state of the backward Euler step in variational form,
the same form that this site uses for XPBD, optimization time integration, vertex block descent, incremental potential contact and affine body dynamics. selects the vertices of element , and , are constant matrices. For the strain energy used here, is the deformation gradient , is the identity and is the set of rotations, so the element energy is with . This is the energy of as-rigid-as-possible deformation. The page uses 2D triangles, up and m/s²; the paper works with 3D meshes and many constraint types, and the code is a 2D version.
The algorithm
PD-STEP(x, v, Δt, K)- 1
(once) L <- M/Δt² + Σ_t w_t S_tᵀ A_tᵀ A_t S_t; factor L = C Cᵀ - 2
y <- x + Δt v + Δt² g ▷ pinned vertices stay - 3
z <- y - 4
repeat K times: - 5
for each element t: p_t <- projection of A_t S_t z onto C_t ▷ local, parallel - 6
solve L z = M y/Δt² + Σ_t w_t S_tᵀ A_tᵀ B_t p_t with the factor C ▷ global - 7
v <- (z - x)/Δt; x <- z
Local step (L5). For the strain energy, the projection of onto the rotations is the rotation factor of its polar decomposition. In 2D it is the rotation by , which the shared polar helper computes. It is always a rotation, also for an inverted triangle. Other constraint sets have other projections: an interval of lengths for springs, an interval of areas or volumes, or a plane for a collision.
Global step (L6). With the projections fixed, the objective is a quadratic in whose Hessian is the matrix of L1. does not depend on or on the projections, and in 2D or 3D it is the same for each coordinate, so a step solves two (or three) systems with one factor. Pinned vertices are removed from the unknowns, and their terms move to the right side. The paper uses a sparse Cholesky factor; the code uses a dense one, which is fine for the small meshes of the tests.
Why it descends. Write the objective as . The local step minimizes over and the global step minimizes it over , so each step can only lower , and . This is block coordinate descent on the pair .
Example
One triangle by hand. The rest triangle is , , with the first two corners pinned. With density 6 the free corner has mass , and with the weight is . Take , no gravity, and the free corner at rest at . The deformation gradient is , so the local step gives . The global step for the free corner is , that is , so with the velocity . Now and again, so further iterations change nothing. Backward Euler for the energy of the height gives , the same .
Convergence on a cantilever (measured). A plate of vertices with spacing 0.1 m and density 1 is pinned at its left column and falls under gravity with s. After 5 steps, one step is solved with 2000 iterations to get the reference value , and the gap after iterations is
| stiffness | 2 | 5 | 10 | 20 | 50 | 100 | 200 | |
|---|---|---|---|---|---|---|---|---|
| 10 | 0 | 0 | 0 | |||||
| 100 | ||||||||
| 1000 |
The gap falls at every iteration, as the descent argument requires. It falls more slowly for the stiffer plate, where the elastic part dominates in . After 2000 iterations the largest entry of the gradient is below in all three rows.
Correctness
The claims are proved in proofs/correctness.md.
- Exact subproblems (proved). The local step gives the best rotation of each element, and the global step gives the unique minimizer for fixed rotations, because is symmetric positive definite.
- Constant matrix (proved). depends only on the masses, , the weights and the rest shape, and it is the same for every coordinate.
- Monotone descent (proved). Each iteration lowers the objective by at least . The test checks that the objective never increases over 30 iterations for a soft and a stiff plate.
- Limit points are backward Euler steps (proved). The steps go to zero, and every limit point where all best rotations are unique has zero gradient, so it satisfies the backward Euler equation. The test reaches a gradient below after 300 iterations, and it checks the gradient formula against central differences.
- Linear momentum (proved). With no pins and no gravity, every global step keeps , so a step keeps the linear momentum for any number of iterations.
- Rigid motions (proved). The energy is zero on rotated and moved copies of the rest shape, and an unstressed body falls by symplectic Euler, m after 10 steps of s.
The test also checks the Cholesky solver against an LU solve. The rate of convergence is not proved; the table measures it.
Proof: Local and global steps of projective dynamics never increase the backward Euler objective, and their limit points are backward Euler stepsfull
We use the notation of the page, for 2D triangles. The free vertices have positions , the lumped mass matrix is (positive diagonal), and pinned vertices are fixed. Triangle has the weight and a deformation gradient that is linear in , with constant vectors from the rest shape that satisfy . Let and define the surrogate
and the objective , which is . Line L5 sets to the rotation factor of , and line L6 solves .
The two steps solve their subproblems exactly
Lemma 1 (local step). For fixed , is minimized by taking each to be the rotation that maximizes . In 2D this is with , unique when .
Proof. The terms are independent, and for a rotation. With , , a sinusoid in whose maximum is at the stated angle.
Lemma 2 (global step). For fixed , is a strictly convex quadratic in each coordinate separately, with the Hessian
restricted to the free vertices. is the same for both coordinates, symmetric positive definite and independent of , and . The unique minimizer solves with .
Proof. Row of is , so , and the coordinates do not mix. Expanding the square, the quadratic part in is with as stated, and the linear part gives ; the pinned vertices enter only through known constants. depends only on , , the and the rest shape. The first part is positive definite and the second is a sum of Gram matrices, which are positive semidefinite, so is positive definite and the minimizer is unique.
So the code factors once (line L1) and every global step costs two triangular solves per coordinate.
Descent and convergence
Theorem 3 (monotone descent). Let come from by one local and one global step. Then
with applied to each coordinate.
Proof. Let be the result of the local step at . Then by Lemma 1. The function is quadratic with Hessian and minimizer (Lemma 2), so . Finally .
Lemma 4 (gradient). At a point where every has a unique best rotation , is differentiable and , that is, for a free vertex , .
Proof. , and is the norm of a linear function of , which is differentiable where it is not zero, with derivative (the unit vector of that linear function, mapped back). So , and the chain rule with gives the formula.
Theorem 5 (limit points are backward Euler steps). The sequence is bounded, converges, , and every limit point at which all best rotations are unique satisfies , the backward Euler equation for .
Proof. By Theorem 3, , and , so the iterates stay in a bounded set. is bounded below by 0 and nonincreasing along the sequence, so it converges, and summing Theorem 3 gives , so the steps go to zero. Let . Write the iteration as . Where the best rotations are unique, is continuous (Lemma 1: it is the unit vector of a nonzero linear function of ), so is continuous at , and because the steps go to zero. A fixed point of minimizes , so , which is by Lemma 4.
The theorem says nothing about the rate. It is linear at best, and it is slow when the triangles are stiff compared with ; the page measures this.
Invariances
Lemma 6. is zero exactly on the configurations that are rotated and moved copies of the rest shape on each triangle; in particular for a rotation and a translation of the whole rest mesh .
Proof. if and only if is a rotation. For , , since the rest shape has .
Theorem 7 (linear momentum). With no pinned vertices and no gravity, every global step satisfies , so the step keeps for any number of iterations.
Proof. Let be the vector of ones. Since , the second part of has , so . Also . Multiplying by gives . With and line L7, .
Lemma 8 (free fall). If the body is at its rest shape up to a rigid motion, has no pins and all vertices have the same velocity , one step under gravity moves every vertex to .
Proof. is a translated copy of , so and , the smallest possible value. The iteration starts at (line L3), and by Theorem 3 with every step satisfies , so it stays at .
Cost
Lemma 9. With free vertices and triangles, the setup costs for the dense factorization of the code, each local step , and each global step for the dense triangular solves.
Proof. Assembling costs per triangle; the dense Cholesky factorization costs . A local step does one polar decomposition per triangle. A global step assembles in plus the pinned terms and does two forward and two backward substitutions with a dense factor.
With a sparse factorization, as in the paper, the cost of a global step is linear in the number of nonzeros of the factor, which depends on the mesh and on the ordering.
Complexity
The setup assembles in and factors it once. With a sparse factor that has nonzeros, an iteration costs for the local step, which is parallel over the elements, and for the right side and the triangular solves. A step with iterations costs . The factor must be recomputed when , a weight or the set of pinned vertices changes. The dense factor of the code costs once and per solve.
Properties
- Robust. The objective never increases, so a step cannot blow up, at any . With few iterations the answer is a partial minimization, which adds damping; it is stable, not accurate.
- Linear convergence. The method is a fixed point iteration that converges slowly for stiff materials, as the table shows. It is often stopped after a fixed number of iterations.
- Restricted energies. Only energies that are squared distances to constraint sets fit the form. General hyperelastic materials such as neo-Hookean need other methods.
- Constant matrix. Changing contacts, pins or stiffness need a new factorization, or must be handled in the local step.
- Momentum. Linear momentum is kept for every iteration count without pins and external forces.
Variants and improvements
- Fast mass-spring. Fast mass-spring is the special case of springs, where the local step projects each spring onto its rest length.
- Chebyshev acceleration. Wang (2015) accelerated the iterations with a Chebyshev semi-iterative method, which also works for position based solvers.
- Quasi-Newton. Liu, Bouaziz and Kavan (2017) viewed the global matrix as an approximate Hessian and used it as the starting matrix of a quasi-Newton method, which allows general hyperelastic materials.
- ADMM. Overby, Brown, Li and Narain (2017) wrote the same split as ADMM, which also allows general materials and hard constraints.
- Vertex block descent. Vertex block descent minimizes the same objective by Newton steps on single vertices, with no global solve.
- Shape matching. The local step is the same best rotation as in meshless shape matching and corotational FEM.
When to use it
Use projective dynamics for interactive simulation of cloth, soft bodies and rods with as-rigid-as-possible type energies, when the mesh and the pins do not change often and robustness at large steps matters more than an exact solution. It is a good fit when a sparse Cholesky factor can be reused for many steps.
Do not use it for general nonlinear materials or for very stiff objects where many iterations would be needed; use Newton based optimization time integration then. Contact that changes every step does not fit the constant matrix well.
Pitfalls
- Few iterations look soft. With a fixed small iteration count, stiff materials look softer and more damped than the material law says.
- Changing the step size. contains , so a new needs a new factor.
- Pins in the matrix. Remove pinned vertices from the unknowns, or add stiff attachment constraints; both change and need a new factor when the pins change.
- Degenerate elements. A triangle with zero rest area has no deformation gradient. A deformation gradient with has no unique best rotation.
- Stopping test. Monotone descent does not bound the error after a given number of iterations. Use the gradient norm if accuracy matters.
Implementations
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
projective_dynamics.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projective-dynamics/. The authors are listed in prov/NBWGAF.jsonl.
"""Projective dynamics (Bouaziz, Martin, Liu, Kavan and Pauly 2014) for 2D triangles.
Each triangle t has the energy (w_t / 2) |F_t - R|^2 with the smallest value
over rotations R, where F_t is the deformation gradient and w_t = k * area_t.
The constraint set is the set of rotations, and the projection of F onto it is
the rotation factor of its polar decomposition (the ARAP strain energy). One
backward Euler step minimizes
g(x) = 1/(2 dt^2) |x - y|_M^2 + sum_t (w_t / 2) dist(F_t(x), SO(2))^2,
with y = x_n + dt v_n + dt^2 g_grav. The method alternates a local step, which
fixes x and projects each F_t onto SO(2), and a global step, which fixes the
rotations and solves a linear system whose matrix
L = M / dt^2 + sum_t w_t G_t G_t^T does not change. The matrix is the same for
the x and the y coordinates, and it is factored once by Cholesky. Pinned
vertices are removed from the unknowns.
The 2D mesh is a version of the 3D tetrahedral setting of the paper.
"""
import math
from anim import polar
GRAVITY = (0.0, -9.81)
def cholesky(a):
"""Lower triangular C with a = C C^T for a symmetric positive definite matrix."""
n = len(a)
c = [[0.0] * n for _ in range(n)]
for j in range(n):
s = a[j][j] - sum(c[j][k] * c[j][k] for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
c[j][j] = math.sqrt(s)
for i in range(j + 1, n):
c[i][j] = (a[i][j] - sum(c[i][k] * c[j][k] for k in range(j))) / c[j][j]
return c
def cholesky_solve(c, b):
n = len(c)
z = [0.0] * n
for i in range(n):
z[i] = (b[i] - sum(c[i][k] * z[k] for k in range(i))) / c[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (z[i] - sum(c[k][i] * x[k] for k in range(i + 1, n))) / c[i][i]
return x
class Mesh:
"""Rest positions X, triangles, lumped masses, pinned vertices and per triangle data."""
def __init__(self, rest, tris, stiffness, density=1.0, pinned=()):
self.rest = [tuple(p) for p in rest]
self.tris = [tuple(t) for t in tris]
self.pinned = set(pinned)
n = len(rest)
self.mass = [0.0] * n
self.grads = []
self.weights = []
for a, b, c in self.tris:
d = [[rest[b][0] - rest[a][0], rest[c][0] - rest[a][0]], [rest[b][1] - rest[a][1], rest[c][1] - rest[a][1]]]
det = d[0][0] * d[1][1] - d[0][1] * d[1][0]
area = 0.5 * abs(det)
inv = [[d[1][1] / det, -d[0][1] / det], [-d[1][0] / det, d[0][0] / det]]
# F = Ds Dm^-1 = sum_v x_v G[v]^T with the rows G[v] of the 3 by 2 matrix below
g1, g2 = inv[0], inv[1]
g0 = [-g1[0] - g2[0], -g1[1] - g2[1]]
self.grads.append((g0, g1, g2))
self.weights.append(stiffness * area)
for v in (a, b, c):
self.mass[v] += density * area / 3.0
self.free = [i for i in range(n) if i not in self.pinned]
def deformation_gradient(self, x, t):
f = [[0.0, 0.0], [0.0, 0.0]]
for v, g in zip(self.tris[t], self.grads[t]):
for d in range(2):
f[d][0] += x[v][d] * g[0]
f[d][1] += x[v][d] * g[1]
return f
def grid(nx, ny, spacing, stiffness, density=1.0, pin_left=True):
"""A rectangle of nx by ny vertices, two triangles per cell, pinned on the left column."""
rest = [(i * spacing, j * spacing) for j in range(ny) for i in range(nx)]
tris = []
for j in range(ny - 1):
for i in range(nx - 1):
a, b, c, d = j * nx + i, j * nx + i + 1, (j + 1) * nx + i + 1, (j + 1) * nx + i
tris += [(a, b, c), (a, c, d)]
pinned = [j * nx for j in range(ny)] if pin_left else []
return Mesh(rest, tris, stiffness, density, pinned)
def energy(mesh, x):
"""sum_t (w_t / 2) |F_t - R_t|^2 with R_t the best rotation."""
e = 0.0
for t, w in enumerate(mesh.weights):
f = mesh.deformation_gradient(x, t)
r, _ = polar(f)
e += 0.5 * w * sum((f[i][j] - r[i][j]) ** 2 for i in range(2) for j in range(2))
return e
def objective(mesh, x, y, dt):
g = energy(mesh, x)
for i in mesh.free:
g += mesh.mass[i] / (2.0 * dt * dt) * ((x[i][0] - y[i][0]) ** 2 + (x[i][1] - y[i][1]) ** 2)
return g
def gradient(mesh, x, y, dt):
"""The gradient of the objective on all vertices (zero rows for pinned ones)."""
grad = [[0.0, 0.0] for _ in x]
for i in mesh.free:
for d in range(2):
grad[i][d] = mesh.mass[i] / (dt * dt) * (x[i][d] - y[i][d])
for t, w in enumerate(mesh.weights):
f = mesh.deformation_gradient(x, t)
r, _ = polar(f)
for v, g in zip(mesh.tris[t], mesh.grads[t]):
if v in mesh.pinned:
continue
for d in range(2):
grad[v][d] += w * ((f[d][0] - r[d][0]) * g[0] + (f[d][1] - r[d][1]) * g[1])
return grad
class Solver:
"""The constant system matrix on the free vertices, factored once."""
def __init__(self, mesh, dt):
self.mesh, self.dt = mesh, dt
col = {v: k for k, v in enumerate(mesh.free)}
self.col = col
nf = len(mesh.free)
a = [[0.0] * nf for _ in range(nf)]
for v in mesh.free:
a[col[v]][col[v]] += mesh.mass[v] / (dt * dt)
self.coupling = [] # (free row, pinned vertex, value): moved to the right side
for t, w in enumerate(mesh.weights):
tri, gs = mesh.tris[t], mesh.grads[t]
for va, ga in zip(tri, gs):
for vb, gb in zip(tri, gs):
val = w * (ga[0] * gb[0] + ga[1] * gb[1])
if va in col and vb in col:
a[col[va]][col[vb]] += val
elif va in col:
self.coupling.append((col[va], vb, val))
self.matrix = a
self.factor = cholesky(a) # @line L1
def global_step(self, x, y, rotations):
mesh, dt, col = self.mesh, self.dt, self.col
out = [tuple(p) for p in x]
rhs = [[mesh.mass[v] / (dt * dt) * y[v][d] for v in mesh.free] for d in range(2)]
for t, w in enumerate(mesh.weights):
r = rotations[t]
for v, g in zip(mesh.tris[t], mesh.grads[t]):
if v in col:
for d in range(2):
rhs[d][col[v]] += w * (r[d][0] * g[0] + r[d][1] * g[1])
for row, vp, val in self.coupling:
for d in range(2):
rhs[d][row] -= val * x[vp][d]
sol = [cholesky_solve(self.factor, rhs[d]) for d in range(2)] # @line L6
for v in mesh.free:
out[v] = (sol[0][col[v]], sol[1][col[v]])
return out
def local_step(mesh, x):
return [polar(mesh.deformation_gradient(x, t))[0] for t in range(len(mesh.tris))]
def pd_step(solver, x, v, iterations, gravity=GRAVITY, history=None):
"""One backward Euler step by projective dynamics. Return (x, v)."""
mesh, dt = solver.mesh, solver.dt
y = predict(mesh, x, v, dt, gravity) # @line L2
z = list(y) # @line L3
for _ in range(iterations): # @line L4
rots = local_step(mesh, z) # @line L5
z = solver.global_step(z, y, rots)
if history is not None:
history.append(objective(mesh, z, y, dt))
v_new = [((p[0] - q[0]) / dt, (p[1] - q[1]) / dt) for p, q in zip(z, x)] # @line L7
return z, v_new
def predict(mesh, x, v, dt, gravity=GRAVITY):
return [(p[0] + dt * u[0] + dt * dt * gravity[0], p[1] + dt * u[1] + dt * dt * gravity[1])
if i not in mesh.pinned else tuple(p) for i, (p, u) in enumerate(zip(x, v))]
test_projective_dynamics.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/projective-dynamics/. The authors are listed in prov/NBWGAF.jsonl.
"""Tests of projective dynamics: the solver parts, monotone descent, convergence and momentum."""
import math
import random
from anim import num_grad, rot2, solve
import projective_dynamics as pd
def test_example_one_triangle():
mesh = pd.Mesh([(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], [(0, 1, 2)], 200.0, density=6.0, pinned=[0, 1])
assert abs(mesh.mass[2] - 1.0) < 1e-15 and abs(mesh.weights[0] - 100.0) < 1e-12
solver = pd.Solver(mesh, 0.1)
x = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.5)]
x1, v1 = pd.pd_step(solver, x, [(0.0, 0.0)] * 3, 1, gravity=(0.0, 0.0))
assert math.dist(x1[2], (0.0, 1.25)) < 1e-14 and math.dist(v1[2], (0.0, -2.5)) < 1e-12
x2, _ = pd.pd_step(solver, x, [(0.0, 0.0)] * 3, 5, gravity=(0.0, 0.0))
assert math.dist(x2[2], (0.0, 1.25)) < 1e-14
def test_cholesky_against_lu():
rng = random.Random(31)
for n in (1, 3, 8):
b = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
a = [[sum(b[i][k] * b[j][k] for k in range(n)) + (n if i == j else 0.0) for j in range(n)] for i in range(n)]
rhs = [rng.uniform(-1, 1) for _ in range(n)]
c = pd.cholesky(a)
assert max(abs(sum(c[i][k] * c[j][k] for k in range(n)) - a[i][j]) for i in range(n) for j in range(n)) < 1e-12
x1 = pd.cholesky_solve(c, rhs)
x2 = solve(a, rhs)
assert max(abs(p - q) for p, q in zip(x1, x2)) < 1e-12
def test_energy_is_zero_exactly_on_rigid_motions():
rng = random.Random(32)
mesh = pd.grid(4, 3, 0.1, 50.0, pin_left=False)
assert energy_close(mesh, mesh.rest, 0.0)
for _ in range(10):
r = rot2(rng.uniform(-math.pi, math.pi))
t = (rng.uniform(-1, 1), rng.uniform(-1, 1))
x = [(r[0][0] * p[0] + r[0][1] * p[1] + t[0], r[1][0] * p[0] + r[1][1] * p[1] + t[1]) for p in mesh.rest]
assert energy_close(mesh, x, 0.0)
stretched = [(1.1 * p[0], p[1]) for p in mesh.rest]
total_area = 0.3 * 0.2
assert energy_close(mesh, stretched, 0.5 * 50.0 * total_area * 0.01)
def energy_close(mesh, x, want):
return abs(pd.energy(mesh, x) - want) < 1e-12
def test_gradient_against_num_grad():
rng = random.Random(33)
mesh = pd.grid(3, 3, 0.2, 80.0, density=2.0)
x = [(p[0] + rng.uniform(-0.03, 0.03), p[1] + rng.uniform(-0.03, 0.03)) if i in mesh.free else p
for i, p in enumerate(mesh.rest)]
y = [(p[0] + 0.01, p[1] - 0.02) for p in x]
dt = 0.05
grad = pd.gradient(mesh, x, y, dt)
flat = [c for p in x for c in p]
def f(z):
return pd.objective(mesh, [(z[2 * i], z[2 * i + 1]) for i in range(len(x))], y, dt)
ng = num_grad(f, flat)
for i in mesh.free:
for d in range(2):
assert abs(ng[2 * i + d] - grad[i][d]) < 1e-6 * max(1.0, abs(grad[i][d]))
def test_objective_never_increases():
for k in (10.0, 1000.0):
mesh = pd.grid(5, 3, 0.1, k)
solver = pd.Solver(mesh, 1.0 / 30.0)
x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
for _ in range(4):
hist = []
y = pd.predict(mesh, x, v, solver.dt)
start = pd.objective(mesh, y, y, solver.dt)
x, v = pd.pd_step(solver, x, v, 30, history=hist)
seq = [start] + hist
assert all(b <= a + 1e-12 * abs(a) for a, b in zip(seq, seq[1:]))
def test_converges_to_a_backward_euler_step():
mesh = pd.grid(5, 3, 0.1, 100.0)
solver = pd.Solver(mesh, 1.0 / 30.0)
x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
x, v = pd.pd_step(solver, x, v, 20)
y = pd.predict(mesh, x, v, solver.dt)
z, _ = pd.pd_step(solver, x, v, 300)
grad = pd.gradient(mesh, z, y, solver.dt)
assert max(abs(c) for g in grad for c in g) < 1e-10
z5, _ = pd.pd_step(solver, x, v, 5)
grad5 = pd.gradient(mesh, z5, y, solver.dt)
assert max(abs(c) for g in grad5 for c in g) > 1e-6
def test_linear_momentum_is_kept_at_every_iteration_count():
rng = random.Random(34)
mesh = pd.grid(4, 3, 0.1, 200.0, pin_left=False)
solver = pd.Solver(mesh, 0.02)
x = list(mesh.rest)
v = [(rng.uniform(-1, 1), rng.uniform(-1, 1)) for _ in x]
p0 = [sum(m * u[d] for m, u in zip(mesh.mass, v)) for d in range(2)]
for it in (1, 2, 7):
for _ in range(10):
x, v = pd.pd_step(solver, x, v, it, gravity=(0.0, 0.0))
p1 = [sum(m * u[d] for m, u in zip(mesh.mass, v)) for d in range(2)]
assert max(abs(a - b) for a, b in zip(p0, p1)) < 1e-12
def test_free_fall_of_an_unstressed_body():
mesh = pd.grid(3, 2, 0.1, 100.0, pin_left=False)
solver = pd.Solver(mesh, 0.1)
x, v = list(mesh.rest), [(0.0, 0.0)] * len(mesh.rest)
for _ in range(10):
x, v = pd.pd_step(solver, x, v, 3)
for p, q in zip(x, mesh.rest):
assert abs(p[1] - q[1] + 5.3955) < 1e-10 and abs(p[0] - q[0]) < 1e-10
History
Liu, Bargteil, O'Brien and Kavan (2013) showed that the implicit Euler step of a mass-spring system can be solved by alternating spring projections and a solve with a constant matrix. Bouaziz, Martin, Liu, Kavan and Pauly (2014) generalized this to projective dynamics with many constraint types. Wang (2015) added Chebyshev acceleration, and Liu, Bouaziz and Kavan (2017) and Overby, Brown, Li and Narain (2017) extended the method to general materials with quasi-Newton and ADMM views.
References
- Sofien Bouaziz, Sebastian Martin, Tiantian Liu, Ladislav Kavan and Mark Pauly, Projective dynamics: fusing constraint projections for fast simulation, ACM Transactions on Graphics 33(4), article 154, 2014 (SIGGRAPH 2014), the whole paper (the variational implicit Euler step, the projective energies, the local and global solver and the constraint types)
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 | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NBWGAF Edit this page History Report an error Markdown