Algorithmadvanced
As-rigid-as-possible shape interpolation
Also called ARAP shape interpolation.
Morph between two compatible triangulations by interpolating the rotation and stretch of each triangle separately and solving for a consistent mesh.
- Time
- O(n^3 + m) buildO(n^2 + m) query
- Space
- Θ(n^2) extra
- Where
- m = the number of triangles; n = the number of vertices
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
As-rigid-as-possible shape interpolation morphs one 2D shape into another when both are triangulated with the same triangles. For each triangle it takes the affine map from the source triangle to the target triangle, splits it into a rotation and a stretch, and interpolates the angle of the rotation and the entries of the stretch separately. The interpolated triangles do not fit together, so the vertices at each time are the least squares fit to them. Marc Alexa, Daniel Cohen-Or and David Levin (2000) introduced the method. It avoids the shrinking and the kinks of linear interpolation of the vertices, because a triangle that only turns keeps its shape and area at every time.
In plain words
Picture a cartoon arm drawn as a mesh of small triangles, first held down and then raised. If every corner moves in a straight line to its new place, the arm shrinks in the middle of the move, as if it were made of rubber. This method looks at each small triangle instead. It asks how much the triangle turns and how much it is stretched, and makes it turn and stretch a little at a time. Those little triangles no longer fit together, like tiles cut a bit wrong. So the method finds the mesh that comes closest to all of them at once. That mesh turns the arm as a whole, and the arm keeps its size.
The problem
The input is a source shape and a target shape of points in the plane, a list of triangles on the vertex indices that triangulates both shapes, and a time . The two triangulations must be compatible: the same triangles, with the same orientation, in both shapes. The output is the shape , with and . The shapes in between should keep each triangle as close to a rotated and gradually stretched copy of itself as possible.
For a triangle , is the 2 by 2 matrix with and , the linear part of the affine map of the triangle. In the same way, is the linear part of the map from the source triangle to the triangle of ; it is linear in .
The algorithm
is the rotation by . The polar decomposition of a 2 by 2 matrix with is with symmetric positive definite; in 2D it has the closed form and .
ARAP-INTERPOLATION(P, Q, triangles) ▷ build, once- 1
for each triangle f do - 2
A_f ← the linear part of the map from triangle f of P to triangle f of Q - 3
(R(γ_f), S_f) ← polar(A_f) - 4
walk over neighbouring triangles: γ_g ← γ_g + 2πk with |γ_g - γ_f| ≤ π - 5
H ← the matrix of Σ_f |B_f(V)|²_F, without vertex 1 ▷ does not depend on t AT(t) ▷ query, for each frame- 6
A_f(t) ← R(t γ_f) ((1 - t) I + t S_f) for each triangle f - 7
v_1(t) ← (1 - t) p_1 + t q_1 - 8
for each coordinate x and y: solve H z = b(t) for the free vertices - 9
return V(t)
Lines L1 to L3 compute the matrices and their polar decompositions. Line L4 makes the angles consistent, as Baxter, Barla and Anjyo (2008) propose: the polar decomposition gives angles in , and two neighbouring triangles that both turn by about 180 degrees could get the angles and and turn in opposite directions. Line L5 builds the normal equations of the energy
which Alexa et al. minimize at each time. Each entry of depends only on the coordinates or only on the coordinates of , so the energy splits into an part and a part with the same matrix . Fixing removes the free translation, and is then positive definite for a connected triangulation. Only the right side of line L8 depends on , so is factored once and each frame costs two solves.
Example
One triangle. Let and . Line L2 gives , and line L3 gives and : the triangle is stretched by 2 along and turned by 90 degrees. At , line L6 gives . With one triangle the fit is exact, so , with the area . Linear interpolation of the vertices gives , with the area , less than both the source area and the target area . The area of the interpolated triangle is , which grows steadily from to .
A turn by almost 180 degrees. Let be a 3 by 3 grid of vertices with 8 triangles, turned by radians. Every is , so the interpolation turns the grid rigidly, and is the grid turned by radians, with the full area. Linear interpolation of the vertices maps the grid by , whose determinant is , so the grid at has only 0.5 percent of its area.
Consistent angles. On a strip of four triangles with the angles from line L3, line L4 adds to the second and the fourth, which gives . All four triangles then turn the same way.
Correctness
The matrix path of line L6 starts at and ends at . At , the source shape has for every triangle, so it has the energy 0, and with it is the only minimizer; so . At , the target shape has the energy 0 in the same way, so .
If the target is a rigid motion of the source by the angle , every is , every is , and the path is . The shape turned by about and moved to fits every triangle exactly, so the morph is rigid.
If , then is positive definite, so is positive definite and for all : each target triangle keeps its orientation. The least squares fit of line L8 can still flip a triangle, because it only approximates the targets. The proof gives the details, including why is positive definite for a connected triangulation.
Proof: As-rigid-as-possible shape interpolation has a unique solution that starts at the source, ends at the target and keeps rigid motions rigidfull
We use the notation of the page. The triangulation has the vertices and the triangles , each with a nondegenerate source triangle. For a triangle , let be the 2 by 2 matrix with the columns and , and . Then and .
The matrix path
Lemma 1. For a 2 by 2 matrix with and not both zero, let and . Then is symmetric and . If , is positive definite.
Proof. With and , the off-diagonal entries of are and . Their difference is , which is 0 because is parallel to . So is symmetric, and since is orthogonal. The trace of is and . A symmetric 2 by 2 matrix with a positive trace and a positive determinant has two positive eigenvalues.
The implementation uses this closed form (the function polar of the helper file for 2 by 2 matrices) and then sets the off-diagonal entries of to their mean, which changes them only by roundoff.
Lemma 2. , , and if then for all . Adding to changes for but not .
Proof. and by Lemma 1. By Lemma 1, is positive definite, so is positive definite as a convex combination of positive definite matrices, and . , but , which differs for not an integer.
Lemma 3. After line L4, the angles of two triangles and are within of each other whenever was first reached from in the walk.
Proof. When is first reached from , the walk adds with , so the new difference is at most in absolute value. The angle of is not changed again, because was reached before.
The walk is a breadth-first search, so the pairs of Lemma 3 are the edges of a spanning tree of each connected part of the dual graph. Other neighbouring pairs are not checked; for meshes whose triangles turn by similar angles they are close as well.
The least squares problem
Lemma 4. The energy is the sum of a function of the coordinates and a function of the coordinates of , and both have the same quadratic part , which does not depend on .
Proof. Row of is row of times , and row of contains only the coordinate of the vertices. So entry of is , where is the vector of coordinate of all vertices and has the entries , and at , and . The energy is , whose quadratic part in is with , the same for both and free of .
Lemma 5. If the triangulation is connected through shared edges and every vertex is in some triangle, the matrix obtained from by removing the row and the column of vertex 1 is positive definite.
Proof. By the proof of Lemma 4, , where is a row vector. Each term is at least 0, so is positive semidefinite. If , then for every , and since is invertible, on every triangle. Triangles that share an edge share two vertices, so by connectedness is constant on all vertices. If also , then . So the quadratic form of , which is restricted to , is positive for .
Theorem 1. For each , with fixed, has exactly one minimizer, and line L8 computes it.
Proof. With fixed, each coordinate part of the energy is a quadratic function of the free coordinates whose quadratic part is given by the positive definite (Lemmas 4 and 5). Such a function is strictly convex and has exactly one minimizer, the solution of its normal equations , where collects and is the column of for vertex 1 without its first entry. This is the system of line L8.
The ends and rigid motions
Theorem 2. and .
Proof. At , by Lemma 2, and , so , and has . A point with the energy 0 is a minimizer, and by Theorem 1 it is the only one, so . At , , so with , and .
Theorem 3. If for all , with , then is the source turned by about and moved so that goes to : .
Proof. , so . By Lemma 1, and . All angles are equal, so line L4 changes none of them, and . The shape with has , so and , with . By Theorem 1, .
Remark. does not change when all vertices move by the same vector, so the minimizers of without a fixed vertex are the translates of one shape, by Lemma 5. Fixing a different vertex picks a different translate, so the shapes for two choices of the fixed vertex differ at each time by a translation.
Complexity
Lines L1 to L4 take time for triangles. has one row and column per free vertex and a nonzero entry for each edge of the triangulation, so it is sparse, with nonzero entries. The implementation stores as a dense matrix and inverts it once, at the cost and memory, and then each frame costs . With a sparse Cholesky factorization of , as in practice, the factor is computed once and each frame costs two sparse triangular solves, close to linear in for planar meshes with a good ordering.
Properties
- Exact ends. and .
- Rigid motions are kept. A target that is a rotation and a translation of the source gives a rigid morph.
- Triangle orientations are kept in the targets. Each has a positive determinant when has.
- Not symmetric. Interpolating from to at the time does not give the same shapes in general, because the decomposition depends on which shape is the source. Alexa et al. give a symmetric variant.
- Translation by one vertex. The motion of the whole shape is set by the path of the fixed vertex; a different choice of the fixed vertex moves the shapes by a translation that depends on .
- Smooth in . For fixed angles, is an analytic function of , because the right side of line L8 is.
Variants and improvements
- Other matrix paths. Alexa et al. also consider the decomposition from the singular value decomposition, and they prefer the symmetric polar form because the singular value form behaves worse.
- Symmetric variant. Alexa et al. (Section 2.3) give a variant of the energy that treats the two shapes in the same way, so that the morph from to is the reverse of the morph from to .
- Consistent angles. Baxter, Barla and Anjyo (2008) make the angles of neighbouring triangles consistent and write the energy as normal equations that are factored once, which makes the interpolation interactive. They also interpolate more than two shapes.
- Three dimensions. The same construction works for compatible tetrahedral meshes, with the polar decomposition of 3 by 3 matrices and rotations interpolated as quaternions, for example by slerp.
- Compatible triangulations. If the two shapes are given only as outlines, a compatible triangulation of both must be built first, often with added interior vertices. Alexa et al. do this with compatible dissections.
When to use it
Use as-rigid-as-possible shape interpolation to morph the outline of a 2D character or object between two poses, as in cartoon in-betweening, when both poses can be triangulated with the same triangles. It is the right tool when parts of the shape turn by large angles, where linear interpolation shrinks them. For images rather than shapes, use a warp such as Beier-Neely morphing, which needs only line correspondences and no triangulation. For an interactive deformation of one shape by handles, use as-rigid-as-possible shape manipulation instead: it fits a shape to handle positions, while this method blends between two given shapes. The as-rigid-as-possible deformation of surfaces and the ARAP parameterization of a surface onto the plane use the same idea of local rotations, but they alternate local fits and a global solve and are not interpolations between two shapes.
Pitfalls
- Incompatible triangulations. The method needs the same triangles in both shapes. A triangle that is flipped in the target has , and its path passes through a degenerate triangle.
- Inconsistent angles. Without line L4, two neighbours that turn by about 180 degrees can turn in opposite directions, and the fit tears the mesh in the middle of the morph.
- Turns beyond 180 degrees. The polar decomposition only sees the angle modulo . A shape that should spin more than half a turn needs the extra turns added to the angles by hand.
- Thin triangles. Long thin triangles in the source make sensitive to small moves of the vertices. A good triangulation of the source helps.
- The fixed vertex. The path of vertex 1 is a straight line; if the whole shape should move on an arc, move the result by a rigid motion of its own.
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
as_rigid_as_possible_shape_interpolation.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-interpolation/. The authors are listed in prov/B6HGFM.jsonl.
"""As-rigid-as-possible shape interpolation of 2D triangulations (Alexa, Cohen-Or and Levin 2000).
The source and the target are two lists of 2D points with the same triangles
(compatible triangulations). For each triangle f, A_f is the linear part of
the affine map that takes the source triangle to the target triangle. Its
polar decomposition A_f = R(gamma_f) S_f, with a rotation R and a symmetric
S, gives the interpolated matrix
A_f(t) = R(t gamma_f) ((1 - t) I + t S_f).
The angles gamma_f are made consistent first: walking over the triangles
that share an edge, each angle is moved by a multiple of 2 pi to within pi of
its neighbour's angle (Baxter, Barla and Anjyo 2008). The vertices V(t)
minimize sum_f |B_f(V) - A_f(t)|_F^2, where B_f(V) is the linear part of the
affine map that takes the source triangle f to the triangle f of V. Vertex 0
is fixed at (1 - t) p_0 + t q_0. The energy is quadratic, the x and the y
coordinates separate, and both use the same matrix H, which does not depend
on t. H is inverted once.
"""
import math
from collections import deque
from anim import inv, lerp, matvec, mul, polar, rot2
def triangle_edges(points, tri):
"""Return the 2 by 2 matrix whose columns are the edges v_j - v_i and v_k - v_i of tri = (i, j, k)."""
i, j, k = tri
return [
[points[j][0] - points[i][0], points[k][0] - points[i][0]],
[points[j][1] - points[i][1], points[k][1] - points[i][1]],
]
def affine_part(source, target, tri):
"""Return the linear part of the affine map that takes triangle tri of source to that of target."""
return mul(triangle_edges(target, tri), inv(triangle_edges(source, tri)))
def triangle_neighbours(triangles):
"""Return, for each triangle, the list of triangles that share an edge with it."""
by_edge = {}
for f, tri in enumerate(triangles):
for a, b in ((tri[0], tri[1]), (tri[1], tri[2]), (tri[2], tri[0])):
by_edge.setdefault((min(a, b), max(a, b)), []).append(f)
nb = [[] for _ in triangles]
for fs in by_edge.values():
for f in fs:
nb[f].extend(g for g in fs if g != f)
return nb
def consistent_angles(angles, triangles):
"""Shift each angle by a multiple of 2 pi so that it is within pi of the neighbour it is reached from."""
nb = triangle_neighbours(triangles)
out = list(angles)
seen = [False] * len(out)
for start in range(len(out)):
if seen[start]:
continue
seen[start] = True
queue = deque([start])
while queue:
f = queue.popleft()
for g in nb[f]:
if not seen[g]:
out[g] += 2.0 * math.pi * round((out[f] - out[g]) / (2.0 * math.pi))
seen[g] = True
queue.append(g)
return out
class ARAPShapeInterpolation:
"""Interpolate between two compatible 2D triangulations; call the object with t in [0, 1]."""
def __init__(self, source, target, triangles, consistent=True):
n = len(source)
if len(target) != n or n < 3 or not triangles:
raise ValueError("source and target need the same three or more points and at least one triangle")
self.source = [tuple(map(float, p)) for p in source]
self.target = [tuple(map(float, p)) for p in target]
self.triangles = [tuple(tri) for tri in triangles]
self.stretch = []
angles = []
# Each row is a linear form on one coordinate of the vertices: entry (f, c) of B_f(V).
self.rows = []
for f, tri in enumerate(self.triangles): # @line L1
a = affine_part(self.source, self.target, tri) # @line L2
r, s = polar(a) # @line L3
angles.append(math.atan2(r[1][0], r[0][0]))
self.stretch.append(s)
m = inv(triangle_edges(self.source, tri))
i, j, k = tri
for c in range(2):
self.rows.append((f, c, ((i, -(m[0][c] + m[1][c])), (j, m[0][c]), (k, m[1][c]))))
self.angles = consistent_angles(angles, self.triangles) if consistent else angles # @line L4
h = [[0.0] * n for _ in range(n)]
for _, _, coef in self.rows: # @line L5
for va, ca in coef:
for vb, cb in coef:
h[va][vb] += ca * cb
self._h0 = [h[i][0] for i in range(1, n)]
try:
self._hinv = inv([row[1:] for row in h[1:]])
except ValueError:
raise ValueError("the triangulation must be connected") from None
def triangle_targets(self, t):
"""Return the matrices A_f(t) = R(t gamma_f) ((1 - t) I + t S_f)."""
out = []
for g, s in zip(self.angles, self.stretch):
blend = [[(1 - t) + t * s[0][0], t * s[0][1]], [t * s[1][0], (1 - t) + t * s[1][1]]]
out.append(mul(rot2(t * g), blend)) # @line L6
return out
def __call__(self, t):
n = len(self.source)
a = self.triangle_targets(t)
v0 = lerp(self.source[0], self.target[0], t) # @line L7
coords = []
for r in range(2): # @line L8
b = [0.0] * n
for f, c, coef in self.rows:
val = a[f][r][c]
for v, cv in coef:
b[v] += cv * val
rhs = [b[i] - self._h0[i - 1] * v0[r] for i in range(1, n)]
coords.append([v0[r]] + list(matvec(self._hinv, rhs)))
return [(x, y) for x, y in zip(coords[0], coords[1])] # @line L9
def energy(self, points, t):
"""Return sum_f |B_f(points) - A_f(t)|_F^2."""
a = self.triangle_targets(t)
e = 0.0
for f, c, coef in self.rows:
for r in range(2):
e += (sum(cv * points[v][r] for v, cv in coef) - a[f][r][c]) ** 2
return e
test_as_rigid_as_possible_shape_interpolation.py 136 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/as-rigid-as-possible-shape-interpolation/. The authors are listed in prov/B6HGFM.jsonl.
import math
import random
import pytest
import anim
from as_rigid_as_possible_shape_interpolation import (
ARAPShapeInterpolation,
affine_part,
consistent_angles,
)
def grid(nx, ny):
pts = [(float(x), float(y)) for y in range(ny) for x in range(nx)]
tris = []
for y in range(ny - 1):
for x in range(nx - 1):
a, b, c, d = y * nx + x, y * nx + x + 1, (y + 1) * nx + x, (y + 1) * nx + x + 1
tris.append((a, b, d))
tris.append((a, d, c))
return pts, tris
def rigid(points, ang, shift):
c, s = math.cos(ang), math.sin(ang)
return [(c * x - s * y + shift[0], s * x + c * y + shift[1]) for x, y in points]
def area(points, tri):
i, j, k = tri
return 0.5 * anim.cross2(anim.sub(points[j], points[i]), anim.sub(points[k], points[i]))
def max_gap(ps, qs):
return max(anim.norm(anim.sub(p, q)) for p, q in zip(ps, qs))
def bent(points, rng):
return [(x + 0.15 * y * y + rng.uniform(-0.05, 0.05), 1.2 * y + 0.1 * x + rng.uniform(-0.05, 0.05)) for x, y in points]
def test_ends_are_the_source_and_the_target(rng=random.Random(1)):
src, tris = grid(4, 3)
tgt = rigid(bent(src, rng), 1.1, (2.0, -1.0))
interp = ARAPShapeInterpolation(src, tgt, tris)
assert max_gap(interp(0.0), src) < 1e-12
assert max_gap(interp(1.0), tgt) < 1e-12
def test_rigid_motion_gives_a_rigid_morph():
src, tris = grid(3, 3)
ang, shift = 2.5, (4.0, 1.0)
tgt = rigid(src, ang, shift)
interp = ARAPShapeInterpolation(src, tgt, tris)
for t in (0.2, 0.5, 0.9):
v0 = anim.lerp(src[0], tgt[0], t)
ref = [anim.add(v0, p) for p in rigid([anim.sub(p, src[0]) for p in src], t * ang, (0.0, 0.0))]
assert max_gap(interp(t), ref) < 1e-12
def test_solution_minimizes_the_energy(rng=random.Random(2)):
src, tris = grid(4, 4)
tgt = rigid(bent(src, rng), -0.7, (1.0, 1.0))
interp = ARAPShapeInterpolation(src, tgt, tris)
t = 0.4
v = interp(t)
flat = [c for p in v[1:] for c in p]
def e(x):
pts = [v[0]] + [(x[2 * i], x[2 * i + 1]) for i in range(len(v) - 1)]
return interp.energy(pts, t)
g = anim.num_grad(e, flat)
assert max(abs(x) for x in g) < 1e-6
e0 = e(flat)
for _ in range(20):
d = [rng.gauss(0, 1e-2) for _ in flat]
assert e([a + b for a, b in zip(flat, d)]) > e0
def test_single_triangle_follows_the_matrix_path():
src = [(0.0, 0.0), (2.0, 0.0), (0.0, 1.0)]
tgt = [(1.0, 1.0), (1.0, 4.0), (0.0, 1.0)]
interp = ARAPShapeInterpolation(src, tgt, [(0, 1, 2)])
for t in (0.0, 0.3, 0.5, 1.0):
v = interp(t)
b = affine_part(src, v, (0, 1, 2))
a = interp.triangle_targets(t)[0]
assert max(abs(b[r][c] - a[r][c]) for r in range(2) for c in range(2)) < 1e-12
def test_polar_path_keeps_the_area_better_than_linear_interpolation():
src, tris = grid(3, 3)
tgt = rigid(src, 3.0, (0.0, 0.0))
interp = ARAPShapeInterpolation(src, tgt, tris)
mid = interp(0.5)
lin = [anim.lerp(p, q, 0.5) for p, q in zip(src, tgt)]
total = sum(area(src, tri) for tri in tris)
assert sum(area(mid, tri) for tri in tris) == pytest.approx(total, rel=1e-12)
# Linear interpolation of a turn by almost 180 degrees nearly collapses the shape.
assert abs(sum(area(lin, tri) for tri in tris)) < 0.01 * total
def test_consistent_angles_on_a_strip():
tris = [(0, 1, 2), (1, 3, 2), (2, 3, 4), (3, 5, 4)]
angles = [3.0, -3.1, 3.05, -3.0]
out = consistent_angles(angles, tris)
assert out[0] == 3.0
for a, b in zip(out, out[1:]):
assert abs(a - b) < math.pi
assert out[1] == pytest.approx(-3.1 + 2 * math.pi)
def test_consistent_angles_make_the_triangles_turn_the_same_way(rng=random.Random(3)):
src, tris = grid(4, 3)
# A turn by nearly 180 degrees with a small bend: some polar angles wrap around to near -pi.
tgt = rigid([(x + rng.uniform(-0.1, 0.1), y + 0.05 * x * x) for x, y in src], math.pi - 0.03, (0.0, 0.0))
raw = ARAPShapeInterpolation(src, tgt, tris, consistent=False)
assert max(raw.angles) > 0 and min(raw.angles) < 0
good = ARAPShapeInterpolation(src, tgt, tris)
assert max(good.angles) - min(good.angles) < 0.5
mid = good(0.5)
assert all(area(mid, tri) > 0 for tri in tris)
bad = raw(0.5)
assert min(area(bad, tri) for tri in tris) < 0.5 * min(area(mid, tri) for tri in tris)
def test_bad_input():
with pytest.raises(ValueError):
ARAPShapeInterpolation([(0.0, 0.0), (1.0, 0.0)], [(0.0, 0.0), (1.0, 0.0)], [(0, 1, 0)])
pts = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0), (5.0, 5.0), (6.0, 5.0), (5.0, 6.0)]
with pytest.raises(ValueError):
ARAPShapeInterpolation(pts, pts, [(0, 1, 2), (3, 4, 5)])
History
Alexa, Cohen-Or and Levin presented the method at SIGGRAPH 2000, with compatible triangulations of the two shapes made from compatible dissections, and with examples in 2D and 3D. Earlier shape morphs interpolated vertices or the intrinsic data of polygons, such as edge lengths and angles. Baxter, Barla and Anjyo (2008) made the angles consistent, wrote the energy as normal equations, and extended the method to more than two shapes. The idea of fitting a mesh to local rotations later led to as-rigid-as-possible shape manipulation and surface deformation.
References
- Marc Alexa, Daniel Cohen-Or and David Levin, As-rigid-as-possible shape interpolation, SIGGRAPH 2000, 157-164, Section 2 (the decomposition of each affine map, equation 5 for A(t), the quadratic energy of equation 8 with one fixed vertex, and the symmetric variant of Section 2.3) and Section 3 (compatible dissections)
- William Baxter, Pascal Barla and Ken-ichi Anjyo, Rigid shape interpolation using normal equations, NPAR 2008, 59-64, the choice of consistent rotation angles for neighbouring triangles, and the normal equations that are factored once
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 B6HGFM Edit this page History Report an error Markdown