Algorithmresearch
Contact-implicit trajectory optimization
Also called trajectory optimization through contact.
Posa's method that adds contact forces as variables with complementarity constraints, so the optimizer chooses when contacts happen.
- Solves
- Trajectory optimization
- Time
- O(T N^3) worst
- Space
- O(N^2) extra
- Where
- N = the number of time steps; T = the total number of Newton steps over all stages
- Model
- Real RAM
- Properties
- deterministicnot exactofflinenot randomized
- Evidence
- Proof sketchCode in 1 languages
Contact-implicit trajectory optimization plans motions in which contacts start and stop, such as walking, jumping and pushing, without fixing in advance when each contact happens. Posa, Cantu and Tedrake made the contact forces decision variables next to the states and controls, and wrote the physics of rigid contact as complementarity constraints: at each time step, either the distance to the ground is zero or the contact force is zero. The optimizer then chooses the contact sequence together with the motion. The resulting problem is a nonlinear program with complementarity constraints, which is hard: its constraints are not convex and violate the usual regularity conditions, so practical methods relax them or use special solvers. Like every method of trajectory optimization, it is local, and different starts can give different contact sequences.
In plain words
Picture planning a jump. You could decide first when the feet leave the ground and then plan each phase, but the best moment to leave the ground is part of what you want to find. Instead, let the planner choose the ground force at every moment, with one rule from physics: the ground can push only while the foot touches it. Now the planner can try all contact patterns at once and settle on the cheapest one it can reach. Without that rule, the planner cheats: it lets the ground push the body up through the air, and the plan looks free but is impossible. The rule makes the problem hard, so the planner first allows a little cheating and then less and less, until the plan obeys physics.
The problem
Input: a model with states, controls and contact forces, a time step , a horizon of steps, start and goal conditions, and a cost. Output: states, controls and contact forces that satisfy the time-stepping equations of motion, with the contact conditions of rigid contact: for each contact and step,
where is the distance to the contact surface and the normal force, and with friction forces limited by the friction cone. The equations of motion are the manipulator equation with the contact forces added, discretized as in Stewart-Trinkle time stepping.
This page uses the smallest case that shows the idea. A unit mass moves on a vertical line at height with thrust , gravity and ground force :
It starts at rest on the ground and must be at rest at height after steps, with the least energy . The velocities are eliminated: , with and , so the variables are the heights and the forces , and is a convex quadratic in them.
The algorithm
CONTACT-IMPLICIT(problem, ε_0, μ_0, κ, ε_min)- 1
ε ← ε_0; μ ← μ_0 - 2
x ← a start with q > 0, λ > 0 and q_{k+1} λ_k < ε for every k - 3
loop - 4
repeat ▷ Newton's method on φ(x) = E(x) - μ (Σ_j log x_j + Σ_k log(ε - q_{k+1} λ_k)) - 5
H ← ∇²φ(x) + τI, with τ = 0 if that is positive definite, else the smallest of 10⁻⁸, 10⁻⁷, … that makes it so - 6
d ← -H⁻¹ ∇φ(x) - 7
halve s from 1 until x + s d is strictly feasible and lowers φ enough; x ← x + s d - 8
until the Newton decrement -∇φ(x)ᵀd / 2 is below tol - 9
if ε < ε_min then return x - 10
ε ← ε/κ; μ ← μ/κ - 11
in each pair with q_{k+1} λ_k ≥ ε, shrink the smaller factor so that the product is ε/2
The code uses , , and .
The complementarity is relaxed to . For the feasible set has an interior, so a barrier method can work in it: lines L4 to L8 minimize the energy plus times a logarithmic barrier for all inequalities. The products are not convex, so the Hessian of the barrier can be indefinite, and line L5 adds a multiple of the identity until it is positive definite; then is a descent direction. Line L7 keeps every iterate strictly inside.
Lines L9 to L11 are the continuation. After each stage, and shrink together, and line L11 repairs the pairs whose product is now too large: in contact the height is the smaller factor and is pushed toward the ground, in flight the force is the smaller factor and is pushed toward zero. Each stage starts from the answer of the stage before, so the contact pattern found at a large guides the later stages.
This relaxation is a standard device for problems with complementarity constraints, and it is the choice of this page; the idea of the method does not depend on how the solver treats the constraints. In every version, the solver sees one problem and never enumerates contact sequences.
Example
The mass must reach height at rest after steps of . The table shows the stages of the continuation.
| energy | largest | |
|---|---|---|
| 31.3672 | ||
| 34.7303 | ||
| 35.6850 | ||
| 35.9310 | ||
| 35.9930 | ||
| 36.0124 | ||
| 36.0137 |
At a large the energy is lower, because the relaxed ground can still push a little while the mass is in the air. After eleven stages the motion is: the mass rests on the ground for four steps with and ground force , so the ground carries its weight for free; then it leaves the ground and rises through the heights , , , , and , with thrusts , , , , and . The energy is .
The optimizer chose the lift-off time. Fixing the number of steps on the ground and solving each case gives the energies (no step), , , , (four steps), , , and (eight steps): waiting saves the cost of carrying the weight, and leaving too late needs a hard push. A search over all contact sets confirms that is the global minimum. Running the thrust through a simulator with exact contact reproduces the heights within .
Starting the continuation at instead ends with five steps on the ground and energy : a local solution, one step late.
Without the complementarity, keeping only and , the same method returns energy . The thrust is zero; the mass rises to and sinks back to , and the "ground" pushes with forces between and while the mass is in the air. The same zero thrust in a simulator leaves the mass on the ground.
Correctness
The proof shows four things. The elimination of the velocities is exact. Every point that satisfies the complementarity is the motion that a simulator with exact contact produces from its thrust, because each time step has exactly one contact force that keeps the mass above the ground and pushes only in contact; so the optimized motion is physical. Without the complementarity, the optimizer can reach zero energy by letting the ground push through the air, and with it the energy is always positive; this is why the constraint matters. The barrier continuation keeps every iterate strictly feasible, each Newton step lowers the barrier function, and the result satisfies the relaxed complementarity with below . The problem with complementarity is a union of convex pieces, one for each contact set; the method is not guaranteed to find the best piece, and the example shows a start where it does not.
Proof: The complementarity makes the optimized motion physical, its absence allows levitation, and the barrier continuation keeps every iterate strictly feasiblefull
We use the notation of the page and of the code. A unit mass at height has thrust , gravity and ground force in step , with the time-stepping model
for , where means . The mass starts at rest on the ground, , and must end at rest at height . The energy is . The variables of the code are .
Lemma 1: the elimination of the velocities is exact
Claim. For every , put , , and . Then the first two equations of the model hold for every , the start is at rest on the ground, and the end is at rest at height . Conversely, every motion of the model with these ends arises in this way from its heights and forces.
Proof. With (which gives ), the formula for is solved for , and is the definition of . The end has and . Conversely, a motion of the model determines from the heights by the second equation and from the first.
So the problem is: minimize the convex quadratic subject to , and .
Lemma 2: a complementary solution is what the simulator does
Claim. Let satisfy , and for all . Then the forward simulation of the code, run with the thrust , produces exactly the heights and the forces of .
Proof. In one step, with given, put and . The model gives , so the step is the problem: find with and . It has exactly one solution: if , because a positive would need , which is impossible; and if , because would leave the height negative. This is the rule of the simulator. The pair of solves the same problem, so it is that solution, and then agrees as well. Induction over from the common start ends the proof.
So every feasible point of the problem with complementarity is a motion that a physics simulator would produce from its thrust: the ground pushes only while the mass touches it.
Theorem 1: without the complementarity, the optimizer levitates
Claim. Drop the condition and keep and . If , the minimum energy is , attained with and a positive ground force while the mass is in the air. With the complementarity, the minimum energy is positive.
Proof. Let and set the height differences for , and . They sum over to , and , so the ends are right. The second differences are and for . Choose ; then for all , and by the assumption. The heights are positive for , and the force is positive at the same steps when the assumption holds strictly, so this motion is not physical. Its energy is , the least possible.
With the complementarity, suppose , so . By Lemma 2 the motion is the simulation of from rest on the ground. In each step , so and the mass stays at , which contradicts . So every feasible point has positive energy. The minimum exists: by Theorem 2 below, the feasible set is a finite union of polyhedra, and a convex quadratic that is bounded below on a polyhedron attains its minimum there (the theorem of Frank and Wolfe). So the minimum is positive.
For the example of the page, , so the condition holds.
Theorem 2: the problem is a union of convex pieces
Claim. For each set of steps, let be the convex quadratic program: minimize with and for , and and for . The feasible set of the problem with complementarity is the union of the feasible sets of the , so its global minimum is the smallest of their minima. A step with fixed at can only be outside .
Proof. A point is feasible exactly when, for each , or (with both signs nonnegative); put in in the first case. Each has linear constraints and the convex objective .
The test of the page uses this to find the global minimum by enumeration. The number of pieces grows as , which is why the method of the page does not enumerate.
Theorem 3: the barrier continuation
Write on the open set where all and all .
Claim. (a) Every Newton step of lines L4 to L8 keeps in and lowers , and the line search of line L7 ends. (b) Line L11 maps the result into for the new . (c) So the returned has , and .
Proof. (a) Line L5 makes positive definite, so has whenever ; if the decrement is below the tolerance, line L8 stops before any step. is open and is continuously differentiable on it, so for all small the point lies in and . Halving reaches such a value after finitely many steps. (Line L5 itself ends, because is positive definite once exceeds the most negative eigenvalue of .) (b) Each height and each force belongs to exactly one product, so changing one pair does not change the others. Line L11 changes a pair only if its product is at least , and it replaces one factor by divided by the other, which is positive; the new product is . Variables stay positive. (c) follows from (a) and (b) by induction over the stages, since the last stage ends with .
What is not proved
The barrier problem is not convex, because the products are not convex functions, so Newton's method finds a local minimizer of each stage, and the path of the stages can end at a local solution of the original problem. The example of the page shows this: one start ends with the mass leaving the ground one step late, at a higher energy. Nothing here says that the limit of the stages is a minimizer, or even a stationary point in a strong sense; problems with complementarity constraints violate the usual constraint qualifications, which is why relaxations like this one are used. For the relaxed motion is not exactly physical; Lemma 2 applies only in the limit, and the test of the page measures the difference.
Complexity
Each Newton step forms and factors a dense matrix of size , at a cost of ; with Newton steps over all stages the total is , and the memory is . The matrix is banded, because each variable interacts only with the variables of nearby steps, so a banded factorization reduces a step to ; for a robot with coordinates and contacts the banded cost is per Newton step. The number of stages is about , eleven in the example, but there is no bound on the number of Newton steps per stage, because the problem is not convex.
The enumeration of contact sets that the test uses for checking costs convex solves; contact-implicit optimization exists to avoid this.
Properties
- No contact schedule. The contact sequence is an output, not an input.
- Physical in the limit. Complementarity makes the result a motion that a time-stepping simulator would produce; any relaxation is physical only in its limit.
- Local. The problem is not convex, and the result depends on the start and on the continuation schedule.
- Hard constraints. Problems with complementarity constraints violate the usual constraint qualifications, so general solvers need relaxations or special care.
- Deterministic. The same start and schedule give the same result.
Variants and improvements
- Friction. With friction, the tangential forces get their own complementarity conditions that encode sliding and sticking, as in the Stewart-Trinkle model; the original paper plans with friction.
- Relaxations and penalties. Instead of , the product can be added to the cost as a penalty, or replaced by a smoothed function whose zeros are the complementary pairs.
- Smooth contact models. A soft contact model, with forces that grow smoothly as bodies approach, removes the complementarity altogether and allows gradient methods such as control-limited DDP, at the price of some force at a distance.
- Interior point solvers. General interior point solvers can handle the relaxed problem with many variables, using the banded structure.
- Contact schedules fixed in advance. When the sequence of contacts is known, a hybrid formulation with one phase per contact mode gives smooth problems that are easier to solve; contact-implicit methods are for when the sequence is not known.
When to use it
Use contact-implicit trajectory optimization when the contact sequence is part of the answer: legged robots that may take steps, manipulation where an object may slide, roll or be pushed, and jumps and landings. Give it a reasonable start, and expect to try several. When the contact sequence is known, a formulation with fixed phases is faster and more reliable. When contacts are not part of the task, use a method for smooth problems, such as sequential convex optimization. Check every result in a simulator, because a relaxed solution can still use small forces through the air, and because discretization can hide effects like the Painlevé paradox.
Pitfalls
- Dropping the complementarity. With only the sign conditions, the ground pushes through the air, as the example shows. Line L4 must include the product terms.
- Infeasible restarts. After line L10 shrinks , the old answer violates the new bound; without line L11 the logarithm of line L4 is undefined.
- Too fast a schedule. A large in line L10 skips over contact patterns, and too large a start can lead to a worse local solution; the example ends one step late from .
- Indefinite Hessians. The barrier of the products has an indefinite Hessian; without the shift of line L5, the Newton direction need not go downhill.
- Trusting the relaxed answer. A final that is not small leaves forces in the air; check the largest product, and simulate the result.
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
# Part of https://algorithm.tamnd.com/contact-implicit-trajectory-optimization/. The authors are listed in prov/YCM0CN.jsonl.
"""Contact-implicit trajectory optimization for a point mass above the ground.
A point of unit mass moves on a vertical line, with height q >= 0 above the
ground. It has a thrust u and feels gravity g and a contact force lam from
the ground. The time-stepping model with step h is
v_(k+1) = v_k + h (u_k - g + lam_k), q_(k+1) = q_k + h v_(k+1),
0 <= q_(k+1) complementary to lam_k >= 0,
so the ground can push only while the mass touches it. The task: start at
rest on the ground and be at rest at height H after N steps, with the least
thrust energy (h/2) sum u_k^2. The contact forces are decision variables,
so the optimizer decides when the mass leaves the ground.
The velocities are eliminated: v_(k+1) = (q_(k+1) - q_k)/h, and the thrust
is the linear function u_k = (q_(k+1) - 2 q_k + q_(k-1))/h^2 + g - lam_k with
q_(-1) = q_0 = 0 (rest on the ground). The end at rest at height H fixes
q_(N-1) = q_N = H. The variables are x = (q_1, ..., q_(N-2), lam_0, ...,
lam_(N-1)).
The complementarity is relaxed to q_(k+1) lam_k <= eps, and the relaxed
problem is solved by a log barrier with Newton steps. The relaxation eps and
the barrier weight mu go to zero together, and each stage starts from the
answer of the stage before.
"""
import math
G = 9.81
class Problem:
def __init__(self, n_steps=10, h=0.1, height=0.5, g=G, contact=True):
"""contact=False drops the complementarity and keeps only q >= 0 and lam >= 0."""
if n_steps < 3:
raise ValueError("need at least three steps")
self.N, self.h, self.H, self.g = n_steps, h, height, g
self.nq = n_steps - 2 # free heights q_1 .. q_(N-2)
self.nx = self.nq + n_steps
self.contact = contact
def pairs(self):
"""The steps k whose pair (q_(k+1), lam_k) carries a complementarity constraint."""
return range(self.N) if self.contact else range(0)
def heights(self, x):
"""q_(-1), q_0, ..., q_N as a list of length N + 2."""
return [0.0, 0.0] + list(x[:self.nq]) + [self.H, self.H]
def forces(self, x):
return list(x[self.nq:])
def thrust(self, x):
q, lam, h = self.heights(x), self.forces(x), self.h
return [(q[k + 2] - 2.0 * q[k + 1] + q[k]) / h ** 2 + self.g - lam[k] for k in range(self.N)]
def thrust_jacobian(self):
"""u = M x + c, so du_k/dx_j = M[k][j]."""
m = [[0.0] * self.nx for _ in range(self.N)]
h2 = self.h ** 2
for k in range(self.N):
for idx, coef in ((k + 1, 1.0), (k, -2.0), (k - 1, 1.0)): # q_(k+1), q_k, q_(k-1)
if 1 <= idx <= self.nq:
m[k][idx - 1] += coef / h2
m[k][self.nq + k] = -1.0
return m
def energy(self, x):
return 0.5 * self.h * sum(u * u for u in self.thrust(x))
def gap(self, x, k):
"""The height q_(k+1) at the end of step k, which pairs with lam_k."""
return self.heights(x)[k + 2]
def gap_index(self, k):
"""Index of q_(k+1) in x, or None if it is fixed."""
return k if k + 1 <= self.nq else None
def complementarity(self, x):
"""The largest product q_(k+1) lam_k; zero exactly when the contact is physical."""
lam = self.forces(x)
return max(self.gap(x, k) * lam[k] for k in range(self.N))
def cholesky(a):
n = len(a)
low = [[0.0] * n for _ in range(n)]
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
return None
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def chol_solve(low, b):
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in reversed(range(n)):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def feasible(prob, x, eps):
"""Strict feasibility for the barrier: q > 0, lam > 0, q lam < eps."""
if any(v <= 0.0 for v in x):
return False
lam = prob.forces(x)
return all(prob.gap(x, k) * lam[k] < eps for k in prob.pairs())
def barrier(prob, x, eps, mu):
lam = prob.forces(x)
s = sum(math.log(v) for v in x)
s += sum(math.log(eps - prob.gap(x, k) * lam[k]) for k in prob.pairs())
return prob.energy(x) - mu * s
def barrier_derivatives(prob, x, eps, mu, m):
n, h = prob.nx, prob.h
u = prob.thrust(x)
grad = [h * sum(m[k][j] * u[k] for k in range(prob.N)) for j in range(n)]
hess = [[h * sum(m[k][i] * m[k][j] for k in range(prob.N)) for j in range(n)] for i in range(n)]
for j in range(n):
grad[j] -= mu / x[j]
hess[j][j] += mu / x[j] ** 2
lam = prob.forces(x)
for k in prob.pairs():
q, l_ = prob.gap(x, k), lam[k]
s = eps - q * l_
il, iq = prob.nq + k, prob.gap_index(k)
# -mu log(eps - q lam): gradient mu (lam, q)/s, Hessian mu/s^2 [[lam^2, eps], [eps, q^2]].
grad[il] += mu * q / s
hess[il][il] += mu * q * q / s ** 2
if iq is not None:
grad[iq] += mu * l_ / s
hess[iq][iq] += mu * l_ * l_ / s ** 2
hess[iq][il] += mu * eps / s ** 2
hess[il][iq] += mu * eps / s ** 2
return grad, hess
def newton(prob, x, eps, mu, m, iters=100, tol=1e-10):
for _ in range(iters): # @line L4
grad, hess = barrier_derivatives(prob, x, eps, mu, m)
tau, low = 0.0, cholesky(hess) # @line L5
while low is None:
tau = max(10.0 * tau, 1e-8)
low = cholesky([[hess[i][j] + (tau if i == j else 0.0) for j in range(len(x))] for i in range(len(x))])
d = chol_solve(low, [-v for v in grad]) # @line L6
dec = -sum(a * b for a, b in zip(grad, d))
if dec / 2.0 < tol: # @line L8
break
phi, s = barrier(prob, x, eps, mu), 1.0
while True: # @line L7
xn = [a + s * b for a, b in zip(x, d)]
if feasible(prob, xn, eps) and barrier(prob, xn, eps, mu) <= phi - 1e-4 * s * dec:
x = xn
break
s *= 0.5
if s < 1e-16:
return x
return x
def initial_point(prob, eps):
q = [prob.H * (k / (prob.N - 1)) for k in range(1, prob.nq + 1)]
x = q + [0.0] * prob.N
for k in range(prob.N):
x[prob.nq + k] = min(1.0, 0.5 * eps / prob.gap(x, k))
return x
def contact_implicit(prob, eps0=0.1, mu0=0.1, kappa=4.0, eps_min=1e-7, x0=None, log=None):
"""Returns x. log, if given, receives (eps, mu, energy, complementarity) after each stage."""
m = prob.thrust_jacobian()
eps, mu = eps0, mu0 # @line L1
x = initial_point(prob, eps) if x0 is None else list(x0) # @line L2
if not feasible(prob, x, eps):
raise ValueError("start is not strictly feasible")
while True: # @line L3
x = newton(prob, x, eps, mu, m)
if log is not None:
log.append((eps, mu, prob.energy(x), prob.complementarity(x)))
if eps < eps_min: # @line L9
return x
eps, mu = eps / kappa, mu / kappa # @line L10
x = restore(prob, x, eps) # @line L11
def restore(prob, x, eps):
"""Make x strictly feasible for a smaller eps: in each pair with q lam >= eps,
shrink the smaller of the two (the gap in contact, the force in flight)."""
x = list(x)
lam = prob.forces(x)
for k in prob.pairs():
q, iq = prob.gap(x, k), prob.gap_index(k)
if q * lam[k] < eps:
continue
if iq is not None and q < lam[k]:
x[iq] = 0.5 * eps / lam[k]
else:
x[prob.nq + k] = 0.5 * eps / q
return x
def simulate(prob, thrust):
"""Forward simulation with exact contact: the ground force is the smallest that keeps q >= 0."""
q, v, qs, lams = 0.0, 0.0, [0.0], []
for u in thrust:
v_free = v + prob.h * (u - prob.g)
q_free = q + prob.h * v_free
lam = 0.0 if q_free >= 0.0 else -q_free / prob.h ** 2
v = v_free + prob.h * lam
q = q + prob.h * v
qs.append(q)
lams.append(lam)
return qs, lams
test_contact_implicit_trajectory_optimization.py 149 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/contact-implicit-trajectory-optimization/. The authors are listed in prov/YCM0CN.jsonl.
import itertools
import random
import unittest
from contact_implicit_trajectory_optimization import (
Problem,
contact_implicit,
feasible,
restore,
simulate,
)
def solve(a, b):
n = len(b)
m = [row[:] + [b[i]] for i, row in enumerate(a)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
m[c], m[p] = m[p], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n + 1):
m[r][j] -= f * m[c][j]
x = [0.0] * n
for i in reversed(range(n)):
x[i] = (m[i][n] - sum(m[i][j] * x[j] for j in range(i + 1, n))) / m[i][i]
return x
def piece_minimum(prob, contact_set):
"""Unconstrained minimum of the energy on one piece: q_(k+1) = 0 for k in the set, lam_k = 0 otherwise."""
m = prob.thrust_jacobian()
c = prob.thrust([0.0] * prob.nx)
free = [k for k in range(prob.nq) if k not in contact_set] + [prob.nq + k for k in contact_set]
a = [[prob.h * sum(m[k][i] * m[k][j] for k in range(prob.N)) for j in free] for i in free]
b = [-prob.h * sum(m[k][i] * c[k] for k in range(prob.N)) for i in free]
x = [0.0] * prob.nx
for i, v in zip(free, solve(a, b)):
x[i] = v
return x
def global_minimum(prob):
"""The smallest energy over all contact sets whose piece minimum has q >= 0 and lam >= 0."""
best = None
for bits in itertools.product((0, 1), repeat=prob.nq):
x = piece_minimum(prob, {k for k in range(prob.nq) if bits[k]})
if min(x) >= -1e-12 and (best is None or prob.energy(x) < best[0]):
best = (prob.energy(x), x)
return best
def lift_off(prob, x):
return sum(1 for q in prob.heights(x)[2:] if q < 1e-4)
class TestWorkedExample(unittest.TestCase):
def test_hop_up_to_half_a_meter(self):
prob = Problem(10, 0.1, 0.5)
x = contact_implicit(prob)
self.assertAlmostEqual(prob.energy(x), 36.01368, places=4)
self.assertEqual(lift_off(prob, x), 4)
heights = prob.heights(x)[1:]
for got, want in zip(heights, [0, 0, 0, 0, 0, 0.07143, 0.18571, 0.31429, 0.42857, 0.5, 0.5]):
self.assertAlmostEqual(got, want, places=4)
for lam in prob.forces(x)[:4]:
self.assertAlmostEqual(lam, 9.81, places=4)
self.assertLess(prob.complementarity(x), 1e-6)
best, _ = global_minimum(prob)
self.assertAlmostEqual(prob.energy(x), best, places=4)
# The thrust, run through a simulator with exact contact, gives the same motion.
qs, lams = simulate(prob, prob.thrust(x))
self.assertLess(max(abs(a - b) for a, b in zip(qs, heights)), 1e-5)
self.assertLess(max(abs(a - b) for a, b in zip(lams, prob.forces(x))), 1e-2)
def test_another_start_ends_at_another_local_solution(self):
prob = Problem(10, 0.1, 0.5)
x = contact_implicit(prob, eps0=1.0, mu0=1.0)
self.assertEqual(lift_off(prob, x), 5)
piece = piece_minimum(prob, set(range(5)))
self.assertAlmostEqual(prob.energy(x), prob.energy(piece), places=4)
self.assertAlmostEqual(prob.energy(x), 36.55902, places=4)
self.assertGreater(prob.energy(x), global_minimum(prob)[0] + 0.5)
class TestWithoutComplementarity(unittest.TestCase):
def test_the_ground_pushes_through_the_air(self):
free = Problem(10, 0.1, 0.5, contact=False)
x = contact_implicit(free)
self.assertLess(free.energy(x), 1e-6)
self.assertGreater(free.complementarity(x), 1.0)
# The thrust that "worked" leaves the mass on the ground in a real simulation.
qs, _ = simulate(free, free.thrust(x))
self.assertLess(max(qs), 1e-9)
def test_explicit_levitating_motion_of_the_proof(self):
prob = Problem(10, 0.1, 0.5, contact=False)
n, h, height = prob.N, prob.h, prob.H
d = [2 * height / n * (n - 1 - k) / (n - 1) for k in range(n)]
q = [0.0]
for k in range(n - 2):
q.append(q[-1] + d[k])
lam = [((d[k] - (d[k - 1] if k > 0 else 0.0)) / h ** 2 + prob.g) for k in range(n)]
x = q[1:] + lam
self.assertAlmostEqual(prob.heights(x)[-2], q[-1] + d[n - 2], places=12)
self.assertLess(max(abs(u) for u in prob.thrust(x)), 1e-9)
self.assertGreater(min(lam), 0.0)
class TestPieces(unittest.TestCase):
def test_restore_gives_a_strictly_feasible_point(self):
rng = random.Random(2014)
prob = Problem(8, 0.1, 0.4)
for _ in range(200):
x = [rng.uniform(1e-3, 2.0) for _ in range(prob.nx)]
eps = rng.uniform(1e-6, 0.5)
y = restore(prob, x, eps)
self.assertTrue(feasible(prob, y, eps))
def test_thrust_is_linear_in_the_variables(self):
rng = random.Random(5)
prob = Problem(7, 0.1, 0.3)
m = prob.thrust_jacobian()
c = prob.thrust([0.0] * prob.nx)
for _ in range(20):
x = [rng.uniform(-1, 1) for _ in range(prob.nx)]
for k, u in enumerate(prob.thrust(x)):
self.assertAlmostEqual(u, c[k] + sum(m[k][j] * x[j] for j in range(prob.nx)), places=9)
class TestRandomized(unittest.TestCase):
def test_random_tasks_give_physical_motions(self):
rng = random.Random(81)
for _ in range(3):
n = rng.randint(5, 7)
prob = Problem(n, rng.choice([0.08, 0.1, 0.12]), rng.uniform(0.1, 0.4))
x = contact_implicit(prob)
self.assertTrue(min(x) > 0.0)
self.assertLess(prob.complementarity(x), 1e-6)
best, _ = global_minimum(prob)
self.assertGreater(prob.energy(x), best - 1e-4)
qs, _ = simulate(prob, prob.thrust(x))
self.assertLess(max(abs(a - b) for a, b in zip(qs, prob.heights(x)[1:])), 1e-4)
if __name__ == "__main__":
unittest.main()
History
Michael Posa, Cecilia Cantu and Russ Tedrake at MIT published the method in The International Journal of Robotics Research in 2014. It built on the time-stepping models of rigid contact, which write contact and friction as complementarity conditions, and on direct transcription methods for trajectory optimization, which make states and controls decision variables of one large nonlinear program. Its point was to make the contact forces decision variables as well, so that walking and manipulation tasks could be planned without a given contact sequence. At about the same time, Igor Mordatch, Emanuel Todorov and Zoran Popović planned contact-rich motions for animated characters with contact-invariant optimization, which treats contacts with smooth auxiliary variables, and both lines of work started a large body of research on planning through contact.
References
- Michael Posa, Cecilia Cantu and Russ Tedrake, A direct method for trajectory optimization of rigid bodies through contact, The International Journal of Robotics Research 33(1), 2014, 69-81, the whole paper (contact forces as decision variables with complementarity constraints)
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 YCM0CN Edit this page History Report an error Markdown