Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflinenot randomized

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 hh, a horizon of NN 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,

ϕ(qk+1)≥0,λk≥0,ϕ(qk+1) λk=0,\phi(q_{k+1}) \ge 0, \qquad \lambda_k \ge 0, \qquad \phi(q_{k+1})\,\lambda_k = 0,

where ϕ\phi is the distance to the contact surface and λk\lambda_k 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 q≥0q \ge 0 with thrust uku_k, gravity g=9.81g = 9.81 and ground force λk\lambda_k:

vk+1=vk+h(uk−g+λk),qk+1=qk+hvk+1,0≤qk+1⊥λk≥0.v_{k+1} = v_k + h(u_k - g + \lambda_k), \qquad q_{k+1} = q_k + h v_{k+1}, \qquad 0 \le q_{k+1} \perp \lambda_k \ge 0.

It starts at rest on the ground and must be at rest at height HH after NN steps, with the least energy E=h2∑kuk2E = \frac h2 \sum_k u_k^2. The velocities are eliminated: uk=(qk+1−2qk+qk−1)/h2+g−λku_k = (q_{k+1} - 2q_k + q_{k-1})/h^2 + g - \lambda_k, with q−1=q0=0q_{-1} = q_0 = 0 and qN−1=qN=Hq_{N-1} = q_N = H, so the variables are the heights q1,…,qN−2q_1, \dots, q_{N-2} and the forces λ0,…,λN−1\lambda_0, \dots, \lambda_{N-1}, and EE is a convex quadratic in them.

The algorithm

  1. CONTACT-IMPLICIT(problem, ε_0, μ_0, κ, ε_min)
  2. 1ε ← ε_0; μ ← μ_0
  3. 2x ← a start with q > 0, λ > 0 and q_{k+1} λ_k < ε for every k
  4. 3loop
  5. 4repeat ▷ Newton's method on φ(x) = E(x) - μ (Σ_j log x_j + Σ_k log(ε - q_{k+1} λ_k))
  6. 5H ← ∇²φ(x) + τI, with τ = 0 if that is positive definite, else the smallest of 10⁻⁸, 10⁻⁷, … that makes it so
  7. 6d ← -H⁻¹ ∇φ(x)
  8. 7halve s from 1 until x + s d is strictly feasible and lowers φ enough; x ← x + s d
  9. 8until the Newton decrement -∇φ(x)ᵀd / 2 is below tol
  10. 9if ε < ε_min then return x
  11. 10ε ← ε/κ; μ ← μ/κ
  12. 11in each pair with q_{k+1} λ_k ≥ ε, shrink the smaller factor so that the product is ε/2

The code uses ε0=μ0=0.1\varepsilon_0 = \mu_0 = 0.1, κ=4\kappa = 4, εmin⁡=10−7\varepsilon_{\min} = 10^{-7} and tol=10−10tol = 10^{-10}.

The complementarity qk+1λk=0q_{k+1}\lambda_k = 0 is relaxed to qk+1λk≤εq_{k+1}\lambda_k \le \varepsilon. For ε>0\varepsilon > 0 the feasible set has an interior, so a barrier method can work in it: lines L4 to L8 minimize the energy plus μ\mu 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 dd is a descent direction. Line L7 keeps every iterate strictly inside.

Lines L9 to L11 are the continuation. After each stage, ε\varepsilon and μ\mu 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 ε\varepsilon 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 H=0.5H = 0.5 at rest after N=10N = 10 steps of h=0.1h = 0.1. The table shows the stages of the continuation.

ε\varepsilon energy largest qk+1λkq_{k+1}\lambda_k
0.10.1 31.3672 9.5⋅10−29.5 \cdot 10^{-2}
0.0250.025 34.7303 2.4⋅10−22.4 \cdot 10^{-2}
6.3⋅10−36.3 \cdot 10^{-3} 35.6850 6.0⋅10−36.0 \cdot 10^{-3}
1.6⋅10−31.6 \cdot 10^{-3} 35.9310 1.5⋅10−31.5 \cdot 10^{-3}
3.9⋅10−43.9 \cdot 10^{-4} 35.9930 3.7⋅10−43.7 \cdot 10^{-4}
2.4⋅10−52.4 \cdot 10^{-5} 36.0124 2.3⋅10−52.3 \cdot 10^{-5}
9.5⋅10−89.5 \cdot 10^{-8} 36.0137 9.2⋅10−89.2 \cdot 10^{-8}

At a large ε\varepsilon 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 u=0u = 0 and ground force 9.819.81, so the ground carries its weight for free; then it leaves the ground and rises through the heights 0.07140.0714, 0.18570.1857, 0.31430.3143, 0.42860.4286, 0.50.5 and 0.50.5, with thrusts 16.9516.95, 14.1014.10, 11.2411.24, 8.388.38, 5.525.52 and 2.672.67. The energy is 36.013736.0137.

The optimizer chose the lift-off time. Fixing the number of steps on the ground and solving each case gives the energies 49.63349.633 (no step), 45.39045.390, 41.47141.471, 38.14738.147, 36.01436.014 (four steps), 36.55936.559, 44.24744.247, 76.93576.935 and 259.62259.62 (eight steps): waiting saves the cost of carrying the weight, and leaving too late needs a hard push. A search over all 282^8 contact sets confirms that 36.013736.0137 is the global minimum. Running the thrust through a simulator with exact contact reproduces the heights within 2⋅10−72 \cdot 10^{-7}.

Starting the continuation at ε0=μ0=1\varepsilon_0 = \mu_0 = 1 instead ends with five steps on the ground and energy 36.55936.559: a local solution, one step late.

Without the complementarity, keeping only q≥0q \ge 0 and λ≥0\lambda \ge 0, the same method returns energy 5⋅10−115 \cdot 10^{-11}. The thrust is zero; the mass rises to 0.7250.725 and sinks back to 0.50.5, and the "ground" pushes with forces between 4.64.6 and 31.631.6 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 ε\varepsilon below εmin⁡\varepsilon_{\min}. The problem with complementarity is a union of 2N−22^{N-2} 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 q≥0q \ge 0 has thrust uku_k, gravity g>0g > 0 and ground force λk\lambda_k in step kk, with the time-stepping model

vk+1=vk+h(uk−g+λk),qk+1=qk+hvk+1,0≤qk+1⊥λk≥0,v_{k+1} = v_k + h(u_k - g + \lambda_k), \qquad q_{k+1} = q_k + h v_{k+1}, \qquad 0 \le q_{k+1} \perp \lambda_k \ge 0,

for k=0,…,N−1k = 0, \dots, N - 1, where a⊥ba \perp b means ab=0ab = 0. The mass starts at rest on the ground, q0=v0=0q_0 = v_0 = 0, and must end at rest at height H>0H > 0. The energy is E=h2∑kuk2E = \frac h2 \sum_k u_k^2. The variables of the code are x=(q1,…,qN−2,λ0,…,λN−1)x = (q_1, \dots, q_{N-2}, \lambda_0, \dots, \lambda_{N-1}).

Lemma 1: the elimination of the velocities is exact

Claim. For every xx, put q−1=q0=0q_{-1} = q_0 = 0, qN−1=qN=Hq_{N-1} = q_N = H, vk+1=(qk+1−qk)/hv_{k+1} = (q_{k+1} - q_k)/h and uk=(qk+1−2qk+qk−1)/h2+g−λku_k = (q_{k+1} - 2q_k + q_{k-1})/h^2 + g - \lambda_k. Then the first two equations of the model hold for every kk, the start is at rest on the ground, and the end is at rest at height HH. Conversely, every motion of the model with these ends arises in this way from its heights and forces.

Proof. With vk=(qk−qk−1)/hv_k = (q_k - q_{k-1})/h (which gives v0=0v_0 = 0), the formula for uku_k is vk+1=vk+h(uk−g+λk)v_{k+1} = v_k + h(u_k - g + \lambda_k) solved for uku_k, and qk+1=qk+hvk+1q_{k+1} = q_k + h v_{k+1} is the definition of vk+1v_{k+1}. The end has qN=Hq_N = H and vN=(qN−qN−1)/h=0v_N = (q_N - q_{N-1})/h = 0. Conversely, a motion of the model determines vkv_k from the heights by the second equation and uku_k from the first. □\square

So the problem is: minimize the convex quadratic E(x)E(x) subject to qk≥0q_k \ge 0, λk≥0\lambda_k \ge 0 and qk+1λk=0q_{k+1}\lambda_k = 0.

Lemma 2: a complementary solution is what the simulator does

Claim. Let xx satisfy qk≥0q_k \ge 0, λk≥0\lambda_k \ge 0 and qk+1λk=0q_{k+1}\lambda_k = 0 for all kk. Then the forward simulation of the code, run with the thrust u(x)u(x), produces exactly the heights q1,…,qNq_1, \dots, q_N and the forces λ0,…,λN−1\lambda_0, \dots, \lambda_{N-1} of xx.

Proof. In one step, with qk,vkq_k, v_k given, put vfree=vk+h(uk−g)v^{\text{free}} = v_k + h(u_k - g) and qfree=qk+hvfreeq^{\text{free}} = q_k + h v^{\text{free}}. The model gives qk+1=qfree+h2λkq_{k+1} = q^{\text{free}} + h^2 \lambda_k, so the step is the problem: find λ≥0\lambda \ge 0 with qfree+h2λ≥0q^{\text{free}} + h^2\lambda \ge 0 and λ(qfree+h2λ)=0\lambda(q^{\text{free}} + h^2\lambda) = 0. It has exactly one solution: λ=0\lambda = 0 if qfree≥0q^{\text{free}} \ge 0, because a positive λ\lambda would need qfree+h2λ=0q^{\text{free}} + h^2\lambda = 0, which is impossible; and λ=−qfree/h2\lambda = -q^{\text{free}}/h^2 if qfree<0q^{\text{free}} < 0, because λ=0\lambda = 0 would leave the height negative. This is the rule of the simulator. The pair (qk+1,λk)(q_{k+1}, \lambda_k) of xx solves the same problem, so it is that solution, and then vk+1v_{k+1} agrees as well. Induction over kk from the common start q0=v0=0q_0 = v_0 = 0 ends the proof. □\square

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 qk+1λk=0q_{k+1}\lambda_k = 0 and keep q≥0q \ge 0 and λ≥0\lambda \ge 0. If 2H/(N(N−1))≤gh22H/(N(N-1)) \le g h^2, the minimum energy is 00, attained with u≡0u \equiv 0 and a positive ground force while the mass is in the air. With the complementarity, the minimum energy is positive.

Proof. Let D=2H/ND = 2H/N and set the height differences dk=qk+1−qk=D(N−1−k)/(N−1)d_k = q_{k+1} - q_k = D(N - 1 - k)/(N - 1) for k=0,…,N−1k = 0, \dots, N - 1, and d−1=0d_{-1} = 0. They sum over k=0,…,N−2k = 0, \dots, N - 2 to DN/2=HD N/2 = H, and dN−1=0d_{N-1} = 0, so the ends are right. The second differences are d0−d−1=Dd_0 - d_{-1} = D and dk−dk−1=−D/(N−1)d_k - d_{k-1} = -D/(N - 1) for k≥1k \ge 1. Choose λk=(dk−dk−1)/h2+g\lambda_k = (d_k - d_{k-1})/h^2 + g; then uk=0u_k = 0 for all kk, and λk≥g−D/((N−1)h2)≥0\lambda_k \ge g - D/((N-1)h^2) \ge 0 by the assumption. The heights are positive for k≥1k \ge 1, and the force is positive at the same steps when the assumption holds strictly, so this motion is not physical. Its energy is 00, the least possible.

With the complementarity, suppose E=0E = 0, so u≡0u \equiv 0. By Lemma 2 the motion is the simulation of u≡0u \equiv 0 from rest on the ground. In each step qfree=−h2g<0q^{\text{free}} = -h^2 g < 0, so λk=g\lambda_k = g and the mass stays at q=0q = 0, which contradicts qN=H>0q_N = H > 0. 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. □\square

For the example of the page, 2H/(N(N−1))=1/90≤9.81⋅0.012H/(N(N-1)) = 1/90 \le 9.81 \cdot 0.01, so the condition holds.

Theorem 2: the problem is a union of convex pieces

Claim. For each set SS of steps, let PSP_S be the convex quadratic program: minimize EE with qk+1=0q_{k+1} = 0 and λk≥0\lambda_k \ge 0 for k∈Sk \in S, and qk+1≥0q_{k+1} \ge 0 and λk=0\lambda_k = 0 for k∉Sk \notin S. The feasible set of the problem with complementarity is the union of the feasible sets of the PSP_S, so its global minimum is the smallest of their minima. A step kk with qk+1q_{k+1} fixed at HH can only be outside SS.

Proof. A point is feasible exactly when, for each kk, qk+1=0q_{k+1} = 0 or λk=0\lambda_k = 0 (with both signs nonnegative); put kk in SS in the first case. Each PSP_S has linear constraints and the convex objective EE. □\square

The test of the page uses this to find the global minimum by enumeration. The number of pieces grows as 2N−22^{N-2}, which is why the method of the page does not enumerate.

Theorem 3: the barrier continuation

Write φ(x)=E(x)−μ(∑jlog⁡xj+∑klog⁡(ε−qk+1λk))\varphi(x) = E(x) - \mu\bigl(\sum_j \log x_j + \sum_k \log(\varepsilon - q_{k+1}\lambda_k)\bigr) on the open set Ωε\Omega_\varepsilon where all xj>0x_j > 0 and all qk+1λk<εq_{k+1}\lambda_k < \varepsilon.

Claim. (a) Every Newton step of lines L4 to L8 keeps xx in Ωε\Omega_\varepsilon and lowers φ\varphi, and the line search of line L7 ends. (b) Line L11 maps the result into Ωε′\Omega_{\varepsilon'} for the new ε′=ε/κ\varepsilon' = \varepsilon/\kappa. (c) So the returned xx has q>0q > 0, λ>0\lambda > 0 and max⁡kqk+1λk<εfinal<εmin⁡\max_k q_{k+1}\lambda_k < \varepsilon_{\text{final}} < \varepsilon_{\min}.

Proof. (a) Line L5 makes H+τIH + \tau I positive definite, so d=−(H+τI)−1∇φd = -(H + \tau I)^{-1}\nabla\varphi has ∇φTd=−dT(H+τI)d<0\nabla\varphi^{\mathsf T} d = -d^{\mathsf T}(H + \tau I)d < 0 whenever ∇φ≠0\nabla\varphi \ne 0; if the decrement −∇φTd/2-\nabla\varphi^{\mathsf T} d/2 is below the tolerance, line L8 stops before any step. Ωε\Omega_\varepsilon is open and φ\varphi is continuously differentiable on it, so for all small s>0s > 0 the point x+sdx + sd lies in Ωε\Omega_\varepsilon and φ(x+sd)≤φ(x)+10−4 s ∇φTd\varphi(x + sd) \le \varphi(x) + 10^{-4}\, s\, \nabla\varphi^{\mathsf T} d. Halving ss reaches such a value after finitely many steps. (Line L5 itself ends, because H+τIH + \tau I is positive definite once τ\tau exceeds the most negative eigenvalue of HH.) (b) Each height qk+1q_{k+1} and each force λk\lambda_k 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 ε′\varepsilon', and it replaces one factor by ε′/2\varepsilon'/2 divided by the other, which is positive; the new product is ε′/2<ε′\varepsilon'/2 < \varepsilon'. Variables stay positive. (c) follows from (a) and (b) by induction over the stages, since the last stage ends with ε<εmin⁡\varepsilon < \varepsilon_{\min}. ■\blacksquare

What is not proved

The barrier problem is not convex, because the products qk+1λkq_{k+1}\lambda_k 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 ε>0\varepsilon > 0 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 2N−22N - 2, at a cost of O(N3)O(N^3); with TT Newton steps over all stages the total is O(TN3)O(TN^3), and the memory is O(N2)O(N^2). The matrix is banded, because each variable interacts only with the variables of nearby steps, so a banded factorization reduces a step to O(N)O(N); for a robot with nn coordinates and cc contacts the banded cost is O(N(n+c)3)O(N(n + c)^3) per Newton step. The number of stages is about log⁡κ(ε0/εmin⁡)+1\log_\kappa(\varepsilon_0/\varepsilon_{\min}) + 1, 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 2N−22^{N-2} 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 qλ≤εq\lambda \le \varepsilon, 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 ε\varepsilon, the old answer violates the new bound; without line L11 the logarithm of line L4 is undefined.
  • Too fast a schedule. A large κ\kappa in line L10 skips over contact patterns, and too large a start ε0\varepsilon_0 can lead to a worse local solution; the example ends one step late from ε0=1\varepsilon_0 = 1.
  • 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 ε\varepsilon 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.

contact_implicit_trajectory_optimization.pyI0RawGitHub
# 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

  1. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example