Techniqueadvanced
Spacetime constraints
Also called spacetime optimization.
Find a character motion as the solution of a constrained optimization over the whole trajectory that meets key poses and minimizes muscle effort.
Spacetime constraints is a way to make a motion by optimization instead of by simulation or by hand. The unknown is the whole trajectory of the character, at all times at once, together with the forces of its muscles. The animator gives constraints, such as a pose at the start, a pose at the end and a foot on the floor at a given time. The laws of motion are also constraints, one for each time sample. Among all trajectories that meet the constraints, the method picks the one that uses the least effort, usually the integral of the squared muscle forces. Witkin and Kass (1988) introduced the idea, with a jumping lamp as the main example, and solved the problem by sequential quadratic programming (SQP). The same frame, often without the dynamics, is the base of motion retargeting and of much later work on motion editing.
In plain words
A simulation goes forward in time: you give the forces, and you get the motion. But an animator often knows where the character must be and when, and does not know the forces. Spacetime constraints turns the question around. It writes down the position and the force at every time step as unknowns. It says which conditions must hold: start here, land there, obey Newton's law at every step. Many motions meet all of these conditions. So it asks for the one that is the least tiring, the one with the smallest sum of squared forces. That gives motions that anticipate, follow through and look natural, because a body that saves effort moves that way. A solver for constrained optimization finds that motion.
When it applies
- The motion has a fixed duration and known events at known times, such as a take-off and a landing.
- The character has few enough degrees of freedom, or the time is short enough, that the whole trajectory fits in one optimization. The number of unknowns is the number of degrees of freedom times the number of time samples, for the states and again for the forces.
- The constraints and the objective are smooth, so that their derivatives exist and Newton-type methods work.
- A good first guess exists, because the problem is not convex once the dynamics are nonlinear, and the solver finds a local minimum near the guess.
The template
- Discretize the time. Choose samples with the step . The unknowns are the states at every sample and the forces or torques at the interior samples.
- Write the dynamics as constraints. Replace the derivatives by finite differences, for example , and write the equation of motion at each interior sample as one constraint .
- Write the user constraints. Add the poses, positions and velocities that must hold at given times, such as , a zero velocity at the start, and a foot on the floor at a contact time.
- Choose the objective. The usual choice is the effort . Other terms, such as a smoothness term or a distance to a reference motion, are added with weights.
- Solve. Use SQP: at the current guess, linearize the constraints, take a quadratic model of the Lagrangian, and solve one linear KKT system for the step and the new multipliers. Repeat until the step and the constraint values are small.
- Edit and solve again. The animator changes a constraint, and the solver starts from the last solution, which is usually a good guess.
The code in impl/python does steps 1 to 5 for a body with one degree of freedom, with the dense KKT solve below.
SPACETIME(n, h, dynamics, boundary, effort)- 1
z ← a first guess of all states and forces ▷ a straight line and zero forces - 2
repeat - 3
c ← the constraint values at z, J ← their Jacobian - 4
H ← the Hessian of effort + Σ λ_i ∇²c_i - 5
solve [H Jᵀ; J 0] [Δz; λ] = [-∇effort; -c] - 6
z ← z + Δz - 7
until Δz is small - 8
return the states and forces of z
When the dynamics are linear and the effort is quadratic, the problem is a quadratic program with equality constraints, and the first step of line L5 is the exact solution. For nonlinear dynamics, the terms in line L4 make the step a Newton step on the KKT conditions, which converges fast near a regular local minimum.
Classic examples
The spacetime toy. A unit mass moves from to , at rest at both ends, and the force is . The effort is . The Euler-Lagrange equation of this functional is , so is a cubic, and the four end conditions give . Then and the minimum is . The force pushes forward in the first half and brakes in the second half, which is the anticipation and follow through of the classic principles of animation, found here by the optimization.
With the velocity conditions written as and , the discrete minimum is exactly , which is for , for and for . It tends to 12 at the rate , because the one-sided velocity conditions are first order.
| discrete minimum | largest error of against | |
|---|---|---|
| 10 | 16.667 | 0.0373 |
| 20 | 14.035 | 0.0163 |
| 40 | 12.955 | 0.0076 |
Gravity. Under a constant gravity , the force is , and the effort is . The middle term is zero because the body is at rest at both ends. So the optimal path is the same cubic, and the minimum is . The discrete problem behaves the same: the path does not change, and the effort grows by exactly .
A pendulum. For an angle with , the dynamics are nonlinear. In the code, a swing from to radian in one second with and converges in 4 SQP steps from a straight line guess, and a swing up from to in two seconds converges in 9 steps. These are measurements of this toy, not bounds.
The jumping lamp. The main example of Witkin and Kass is a desk lamp made of a few rigid links with hinge joints, which jumps by pushing with its joints. The constraints are the start pose, the end pose after the landing, and the contact of the base with the floor before the take-off and after the landing. The optimal jumps show a crouch before the take-off and a squash at the landing, without the animator asking for them.
Variations
- Kinematic spacetime. Drop the dynamics and keep the kinematic constraints over the whole motion, with an objective that keeps the motion close to a given one. Motion retargeting by Gleicher (1998) works this way, with the change written as a smooth displacement curve.
- Subsets of time. Optimizing a long motion at once is slow. Later work, for example the spacetime windows of Cohen (1992), optimizes a part of the time at a time.
- Other bases. The trajectory can be written with B-spline control points instead of samples, which reduces the number of unknowns and keeps the motion smooth.
- Other objectives. A distance to a reference motion, a smoothness term or the work of the joints can replace or join the effort term. Each changes the motion that the method finds.
- Inverse kinematics. Style-based inverse kinematics solves one pose at a time under constraints, with a learned objective. It is a pose problem, not a trajectory problem, but it uses the same idea of constraints plus a preference.
Pitfalls
- Local minima. With nonlinear dynamics or contact, the problem has many local minima, and the result depends on the first guess. Start from a plausible motion, or from the solution of an easier problem.
- Size. The KKT system has one row per unknown and per constraint. A dense solve, as in the toy code, costs the cube of that size. Use the band or sparse structure: each constraint touches only a few neighboring samples.
- Contacts and events at fixed times. The method needs to know when each contact starts and ends. If the times are wrong, the motion is forced into an odd shape. Choose them with care, or add them as unknowns with extra work.
- Time step. A coarse step makes the finite differences poor, and the discrete optimum can differ much from the continuous one, as the table of the toy shows for small .
- Scaling. States, forces and constraints with very different sizes make the KKT system ill conditioned. Scale the units first.
Code
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.
This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.
Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""
import math
# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6
# ---------------------------------------------------------------- vectors
def add(a, b):
"""Return a + b."""
return tuple(x + y for x, y in zip(a, b))
def sub(a, b):
"""Return a - b."""
return tuple(x - y for x, y in zip(a, b))
def scale(a, s):
"""Return s a for a number s."""
return tuple(s * x for x in a)
def dot(a, b):
"""Return the dot product of a and b."""
return sum(x * y for x, y in zip(a, b))
def cross(a, b):
"""Return the cross product of two 3D vectors."""
return (
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
)
def cross2(a, b):
"""Return the scalar 2D cross product a_x b_y - a_y b_x."""
return a[0] * b[1] - a[1] * b[0]
def norm(a):
"""Return the Euclidean length of a."""
return math.sqrt(sum(x * x for x in a))
def normalize(a):
"""Return a / |a|. Raise ValueError for the zero vector."""
n = norm(a)
if n == 0.0:
raise ValueError("cannot normalize the zero vector")
return tuple(x / n for x in a)
def lerp(a, b, t):
"""Return (1 - t) a + t b."""
return tuple((1 - t) * x + t * y for x, y in zip(a, b))
# ---------------------------------------------------------------- matrices
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None)."""
if m is None:
m = n
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def mul(a, b):
"""Return the matrix product a b."""
bt = list(zip(*b))
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the vector a x as a tuple."""
return tuple(sum(p * q for p, q in zip(row, x)) for row in a)
def transpose(a):
"""Return the transpose of a."""
return [list(col) for col in zip(*a)]
def _lu(a):
"""Gaussian elimination with partial pivoting on a copy of a square a.
Return (lu, perm, sign), or None if a pivot is exactly zero.
"""
n = len(a)
lu = [list(map(float, row)) for row in a]
perm = list(range(n))
sign = 1.0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(lu[i][k]))
if lu[p][k] == 0.0:
return None
if p != k:
lu[k], lu[p] = lu[p], lu[k]
perm[k], perm[p] = perm[p], perm[k]
sign = -sign
piv = lu[k][k]
for i in range(k + 1, n):
f = lu[i][k] / piv
lu[i][k] = f
if f != 0.0:
rk = lu[k]
ri = lu[i]
for j in range(k + 1, n):
ri[j] -= f * rk[j]
return lu, perm, sign
def det(a):
"""Return the determinant of a square matrix."""
n = len(a)
if n == 1:
return a[0][0]
if n == 2:
return a[0][0] * a[1][1] - a[0][1] * a[1][0]
if n == 3:
return (
a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
- a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
+ a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
)
r = _lu(a)
if r is None:
return 0.0
lu, _, sign = r
d = sign
for i in range(n):
d *= lu[i][i]
return d
def _lu_solve(lu, perm, b):
n = len(lu)
y = [float(b[perm[i]]) for i in range(n)]
for i in range(n):
s = y[i]
row = lu[i]
for j in range(i):
s -= row[j] * y[j]
y[i] = s
for i in range(n - 1, -1, -1):
s = y[i]
row = lu[i]
for j in range(i + 1, n):
s -= row[j] * y[j]
y[i] = s / row[i]
return y
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (returns a list) or a matrix given as a list of rows
(returns a list of rows, one column of x per column of b).
Raise ValueError if a is singular.
"""
r = _lu(a)
if r is None:
raise ValueError("singular matrix")
lu, perm, _ = r
if len(b) > 0 and isinstance(b[0], (list, tuple)):
cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
return [list(row) for row in zip(*cols)]
return _lu_solve(lu, perm, b)
def inv(a):
"""Return the inverse of a square matrix. Raise ValueError if singular."""
return solve(a, eye(len(a)))
# ---------------------------------------------------------------- polar decomposition
def rot2(theta):
"""Return the 2 by 2 rotation matrix by the angle theta."""
c, s = math.cos(theta), math.sin(theta)
return [[c, -s], [s, c]]
def _frob(a):
return math.sqrt(sum(x * x for row in a for x in row))
def _sym_eig3(s):
"""Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).
Return (values, vectors), where vectors[k] is the unit eigenvector of
values[k].
"""
a = [list(map(float, row)) for row in s]
v = eye(3)
for _ in range(50):
off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
break
for p, q in ((0, 1), (0, 2), (1, 2)):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(3):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(3):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
for k in range(3):
vkp, vkq = v[k][p], v[k][q]
v[k][p] = c * vkp - sn * vkq
v[k][q] = sn * vkp + c * vkq
values = [a[i][i] for i in range(3)]
vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
return values, vectors
def polar(f, tol=1e-14, max_iter=100):
"""Return (R, S) with F = R S, det R = +1 and S symmetric.
2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
the rotation that maximizes trace(R^T F), and S = R^T F.
3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
is above 1e-2. It stops when the relative change in the Frobenius norm is
at most tol, or after max_iter steps. The iteration gives the orthogonal
polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
If det F > 0, S is symmetric positive definite. If det F < 0, S is
symmetric with one negative eigenvalue. Raise ValueError for a singular
3 by 3 F.
"""
n = len(f)
if n == 2:
theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
r = rot2(theta)
s = mul(transpose(r), f)
s01 = 0.5 * (s[0][1] + s[1][0])
s[0][1] = s[1][0] = s01
return r, s
if n != 3:
raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
x = [list(map(float, row)) for row in f]
change = float("inf")
for _ in range(max_iter):
xi = inv(x)
if change > 1e-2:
g = math.sqrt(_frob(xi) / _frob(x))
else:
g = 1.0
xit = transpose(xi)
y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
x = y
if change <= tol:
break
u = x
s = mul(transpose(u), f)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
if det(u) < 0.0:
values, vectors = _sym_eig3(s)
k = min(range(3), key=lambda i: values[i])
v = vectors[k]
h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
u = mul(u, h)
s = mul(h, s)
s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
return u, s
# ---------------------------------------------------------------- quaternions
def q_mul(p, q):
"""Return the Hamilton product p q."""
a1, b1, c1, d1 = p
a2, b2, c2, d2 = q
return (
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
)
def q_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return (q[0], -q[1], -q[2], -q[3])
def q_dot(p, q):
"""Return the dot product of p and q as vectors of R^4."""
return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]
def q_normalize(q):
"""Return q / |q|."""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("cannot normalize the zero quaternion")
return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)
def q_from_axis_angle(axis, angle):
"""Return the unit quaternion of the rotation by angle about axis (any length)."""
u = normalize(axis)
s = math.sin(0.5 * angle)
return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])
def q_to_mat3(q):
"""Return the 3 by 3 rotation matrix of a unit quaternion."""
w, x, y, z = q
return [
[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
[2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
[2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
]
def q_rotate(q, v):
"""Return the vector part of q (0, v) q* for a unit quaternion q."""
r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
return (r[1], r[2], r[3])
def q_log(q):
"""Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).
For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
"""
n = math.sqrt(q_dot(q, q))
if n == 0.0:
raise ValueError("log of the zero quaternion")
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
lw = math.log(n)
if vn == 0.0:
return (lw, 0.0, 0.0, 0.0)
phi = math.atan2(vn, q[0])
f = phi / vn
return (lw, f * q[1], f * q[2], f * q[3])
def q_exp(q):
"""Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
ew = math.exp(q[0])
if vn == 0.0:
return (ew, 0.0, 0.0, 0.0)
f = ew * math.sin(vn) / vn
return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])
def slerp(q0, q1, t):
"""Spherical linear interpolation of unit quaternions on the short arc.
If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
normalized linear interpolation is returned. See
robotics/rigid-body-motion/spherical-linear-interpolation.
"""
if q_dot(q0, q1) < 0.0:
q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
w = 2.0 * math.atan2(a, b)
if w < SLERP_SMALL_ANGLE:
return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
s = math.sin(w)
c0 = math.sin((1 - t) * w) / s
c1 = math.sin(t * w) / s
return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))
def q_from_mat3(r):
"""Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.
Shepperd's method: take the largest of the trace, r00, r11 and r22, and
divide by the component that it gives. See
robotics/rigid-body-motion/shepperd-method.
"""
t = r[0][0] + r[1][1] + r[2][2]
k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
if k == 0:
w = math.sqrt(1.0 + t) / 2.0
f = 4.0 * w
q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
elif k == 1:
x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
f = 4.0 * x
q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
elif k == 2:
y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
f = 4.0 * y
q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
else:
z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
f = 4.0 * z
q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
if q[0] < 0.0:
q = (-q[0], -q[1], -q[2], -q[3])
return q
# ---------------------------------------------------------------- transforms
def make_T(r, t):
"""Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
d = len(t)
m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
m.append([0.0] * d + [1.0])
return m
def T_mul(a, b):
"""Return the product a b of two homogeneous transforms."""
return mul(a, b)
def T_inv(m):
"""Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].
The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
"""
d = len(m) - 1
a = [row[:d] for row in m[:d]]
t = [m[i][d] for i in range(d)]
ai = inv(a)
ti = matvec(ai, t)
return make_T(ai, tuple(-x for x in ti))
def T_apply(m, p):
"""Apply a homogeneous transform to a point p and return a tuple."""
d = len(m) - 1
return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))
# ---------------------------------------------------------------- derivatives
def num_grad(f, x, h=1e-6):
"""Return the gradient of a scalar f at x by central differences of step h."""
x = list(x)
g = []
for i in range(len(x)):
xi = x[i]
x[i] = xi + h
fp = f(x)
x[i] = xi - h
fm = f(x)
x[i] = xi
g.append((fp - fm) / (2.0 * h))
return g
spacetime_constraints.py 91 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spacetime-constraints/. The authors are listed in prov/5ZYH4C.jsonl.
"""Spacetime constraints on a one degree of freedom body (Witkin and Kass 1988).
The trajectory x(t) on [0, T] is sampled at n + 1 times with step h = T / n.
The unknowns are the states x_0 .. x_n and the controls f_1 .. f_(n-1), one per
interior time. The constraints are
dynamics (x_(i+1) - 2 x_i + x_(i-1)) / h^2 + k sin(x_i) + g - f_i = 0,
boundary x_0 = a, (x_1 - x_0) / h = 0, x_n = b, (x_n - x_(n-1)) / h = 0,
and the objective is the effort R = h sum f_i^2. With k = 0 this is a unit
mass under a constant gravity g, pushed by the force f. With g = 0 it is a
pendulum, x the angle and k = gravity / length, turned by the torque f.
The constrained problem is solved by sequential quadratic programming: at
each step the constraints are linearized, the Lagrangian is modeled to
second order, and one linear KKT system gives the step and the new
multipliers. For k = 0 the problem is a quadratic program, and the first step
is exact.
"""
import math
from anim import solve
def residuals(z, n, h, k, g, a, b):
"""Return the constraint values c(z): n - 1 dynamics rows, then 4 boundary rows."""
x, f = z[: n + 1], z[n + 1 :]
c = []
for i in range(1, n):
c.append((x[i + 1] - 2.0 * x[i] + x[i - 1]) / (h * h) + k * math.sin(x[i]) + g - f[i - 1])
c.append(x[0] - a)
c.append((x[1] - x[0]) / h)
c.append(x[n] - b)
c.append((x[n] - x[n - 1]) / h)
return c
def jacobian(z, n, h, k):
"""Return the dense Jacobian of the constraints, one row per constraint."""
size = 2 * n
rows = []
for i in range(1, n):
r = [0.0] * size
r[i - 1] += 1.0 / (h * h)
r[i] += -2.0 / (h * h) + k * math.cos(z[i])
r[i + 1] += 1.0 / (h * h)
r[n + i] = -1.0
rows.append(r)
for idx, coef in (((0,), (1.0,)), ((0, 1), (-1.0 / h, 1.0 / h)), ((n,), (1.0,)), ((n - 1, n), (-1.0 / h, 1.0 / h))):
r = [0.0] * size
for j, w in zip(idx, coef):
r[j] = w
rows.append(r)
return rows
def effort(z, n, h):
"""Return R = h sum f_i^2."""
return h * sum(v * v for v in z[n + 1 :])
def spacetime(n, k=0.0, g=0.0, a=0.0, b=1.0, duration=1.0, max_iter=50, tol=1e-11):
"""Solve the spacetime problem. Return (x, f, effort, iterations)."""
h = duration / n
size = 2 * n
z = [a + (b - a) * i / n for i in range(n + 1)] + [0.0] * (n - 1) # @line L1
lam = [0.0] * (n + 3)
for it in range(1, max_iter + 1): # @line L2
c = residuals(z, n, h, k, g, a, b) # @line L3
jac = jacobian(z, n, h, k)
grad = [0.0] * (n + 1) + [2.0 * h * v for v in z[n + 1 :]]
m = len(c)
kkt = [[0.0] * (size + m) for _ in range(size + m)]
for i in range(1, n): # @line L4
kkt[i][i] = -lam[i - 1] * k * math.sin(z[i])
for j in range(n + 1, size):
kkt[j][j] = 2.0 * h
for r in range(m):
for j in range(size):
kkt[size + r][j] = jac[r][j]
kkt[j][size + r] = jac[r][j]
rhs = [-v for v in grad] + [-v for v in c]
sol = solve(kkt, rhs) # @line L5
dz, lam = sol[:size], sol[size:]
z = [p + q for p, q in zip(z, dz)] # @line L6
if max(abs(v) for v in dz) <= tol * (1.0 + max(abs(v) for v in z)): # @line L7
break
return z[: n + 1], z[n + 1 :], effort(z, n, h), it # @line L8
test_spacetime_constraints.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spacetime-constraints/. The authors are listed in prov/5ZYH4C.jsonl.
"""Tests of spacetime constraints on a one degree of freedom body.
The toy of the page: a unit mass from x(0) = 0 to x(1) = 1, at rest at both
ends, minimizing the integral of x''^2. The exact discrete minimum is
12 n^2 / ((n - 1)(n - 2)), which tends to 12, and the path tends to
3 t^2 - 2 t^3. Gravity adds g^2 h (n - 1) and leaves the path the same. For
the nonlinear pendulum, the constraints hold and the solution is a
stationary point and a local minimum of the effort after the forces are
eliminated, a reference that does not use the KKT system.
"""
import math
import random
from spacetime_constraints import residuals, spacetime
def eliminated_effort(x, n, h, k, g):
"""Effort of a path x that meets the boundary rows, with f from the dynamics."""
e = 0.0
for i in range(1, n):
f = (x[i + 1] - 2.0 * x[i] + x[i - 1]) / (h * h) + k * math.sin(x[i]) + g
e += h * f * f
return e
def test_toy_exact_discrete_minimum():
for n in (10, 20, 40):
_, _, e, it = spacetime(n)
assert abs(e - 12.0 * n * n / ((n - 1) * (n - 2))) < 1e-8
assert it == 2
def test_toy_tends_to_the_cubic():
errs = []
for n in (10, 20, 40):
x, _, e, _ = spacetime(n)
errs.append(max(abs(x[i] - (3 * (i / n) ** 2 - 2 * (i / n) ** 3)) for i in range(n + 1)))
assert errs[0] > errs[1] > errs[2]
assert errs[2] < 0.01
assert abs(e - 12.0) < 1.0
def test_toy_force_is_linear_in_time():
n = 20
_, f, _, _ = spacetime(n)
d = [f[i + 1] - f[i] for i in range(len(f) - 1)]
assert all(abs(v - d[0]) < 1e-8 for v in d)
assert d[0] < 0.0 and f[0] > 0.0 > f[-1]
def test_gravity_adds_a_constant():
n = 20
g = 9.81
x0, _, e0, _ = spacetime(n)
x1, f1, e1, _ = spacetime(n, g=g)
assert abs(e1 - e0 - g * g * (n - 1) / n) < 1e-8
assert max(abs(p - q) for p, q in zip(x0, x1)) < 1e-10
def test_linear_case_matches_unconstrained_least_squares():
# Eliminate the forces and the boundary rows, and solve the normal
# equations of the remaining least squares problem in x_2 .. x_(n-2).
n, g = 12, 2.0
h = 1.0 / n
x, _, e, _ = spacetime(n, g=g)
free = list(range(2, n - 1))
base = [0.0, 0.0] + [0.0] * (n - 3) + [1.0, 1.0]
rows, rhs = [], []
for i in range(1, n):
r = [0.0] * len(free)
known = g
for j, w in ((i - 1, 1.0), (i, -2.0), (i + 1, 1.0)):
if j in free:
r[free.index(j)] += w / (h * h)
else:
known += w * base[j] / (h * h)
rows.append(r)
rhs.append(-known)
m = len(free)
ata = [[sum(r[a] * r[b] for r in rows) for b in range(m)] for a in range(m)]
atb = [sum(r[a] * v for r, v in zip(rows, rhs)) for a in range(m)]
for p in range(m):
for q in range(p + 1, m):
t = ata[q][p] / ata[p][p]
for c in range(p, m):
ata[q][c] -= t * ata[p][c]
atb[q] -= t * atb[p]
sol = [0.0] * m
for p in range(m - 1, -1, -1):
sol[p] = (atb[p] - sum(ata[p][c] * sol[c] for c in range(p + 1, m))) / ata[p][p]
for j, v in zip(free, sol):
assert abs(x[j] - v) < 1e-9
assert abs(e - eliminated_effort(x, n, h, 0.0, g)) < 1e-9
def test_pendulum_meets_the_constraints_and_is_a_local_minimum():
n, k = 20, 9.81
h = 1.0 / n
x, f, e, it = spacetime(n, k=k, b=1.0)
assert it < 15
c = residuals(list(x) + list(f), n, h, k, 0.0, 0.0, 1.0)
assert max(abs(v) for v in c) < 1e-9
free = list(range(2, n - 1))
def j(vals):
y = list(x)
for idx, v in zip(free, vals):
y[idx] = v
return eliminated_effort(y, n, h, k, 0.0)
start = [x[i] for i in free]
eps = 1e-6
for a in range(len(free)):
up = list(start)
dn = list(start)
up[a] += eps
dn[a] -= eps
assert abs(j(up) - j(dn)) / (2 * eps) < 1e-4
rng = random.Random(4)
for _ in range(30):
assert j([v + rng.gauss(0, 1e-3) for v in start]) >= e - 1e-12
def test_swing_up_converges():
n, k = 20, 9.81
x, f, _, it = spacetime(n, k=k, b=math.pi, duration=2.0)
h = 2.0 / n
c = residuals(list(x) + list(f), n, h, k, 0.0, 0.0, math.pi)
assert it < 30
assert max(abs(v) for v in c) < 1e-9
Exercises
- Show that meets the four end conditions of the toy, and compute . Answer: , , is zero at 0 and 1, and the integral of is 12.
- Show that a constant gravity does not change the optimal path of the toy. Answer: the effort is , and the middle term is zero for every path that meets the end conditions, so the effort differs from the toy by the constant .
- Derive the discrete minimum . Answer: with , the end conditions give and . The least norm under these two conditions is linear in , and its squared norm is . The effort is .
References
- Andrew Witkin and Michael Kass, Spacetime constraints, SIGGRAPH 88, Computer Graphics 22(4), 159-168, the formulation of the motion as a constrained optimization over the whole trajectory, with the states and the forces sampled in time, the dynamics as constraints and an effort objective, solved by sequential quadratic programming (general locator)
- Michael Gleicher, Retargetting motion to new characters, SIGGRAPH 98, 33-42, the use of a spacetime formulation without the dynamics, with kinematic constraints over the whole motion (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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5ZYH4C Edit this page History Report an error Markdown