Algorithm Search⌘K

Algorithmresearch

Convex MPC for legged locomotion

Also called convex model predictive control of quadrupeds.

Plans the ground reaction forces of a legged robot over a short horizon as one QP per control step, with a single rigid body model made linear by small roll and pitch and the reference yaw.

Time
O(n^3 c^2) buildO(n^3 c^3) per_iteration
Space
O(n^2 c^2) extra
Where
c = the number of feet in contact per step; n = the number of steps in the horizon
Properties
deterministicnot exactonline
Origin
Jared Di Carlo, Patrick M. Wensing, Benjamin Katz, Gerardo Bledt, Sangbae Kim, 2018

Convex MPC for legged locomotion is a model predictive controller that plans the forces that the feet of a legged robot push on the ground over the next fraction of a second. It treats the robot as one rigid body, fixes the timing of the steps and the foot positions in advance, and assumes small roll and pitch, so that the predicted motion is linear in the forces. Each control step is then one convex quadratic program with friction and force limits, which a solver finds to optimality in a millisecond or less. Di Carlo et al. (2018) used it for many gaits of the MIT Cheetah 3. The QP is solved exactly, but the closed loop has no stability proof.

In plain words

A running quadruped touches the ground with two or four feet at a time, for a short time. In that time, the feet must push so that the body goes where it should and does not tip over. A foot can only push, not pull, and it slips if it pushes too much sideways.

The controller looks a short time ahead, for example half a second. It knows which feet will be on the ground and where. It treats the whole robot as one block and asks: which pushes, at each foot and each moment, keep the block closest to the plan? With the simplifications above, this question is a standard optimization problem with one best answer, and a computer finds it fast. The robot uses the first pushes, then asks the question again a few hundredths of a second later.

The problem

The robot has mass mm and body inertia IBI_B about its center of mass. Gravity is g=9.81g = 9.81 m/s2^2 along −z-z in the world frame {s}. The state is

x=(Θ,p,ω,v,g)∈R13,x = (\Theta, p, \omega, v, g) \in \mathbb{R}^{13},

with roll, pitch and yaw Θ\Theta (with R=Rz(ψ)Ry(θ)Rx(ϕ)R = R_z(\psi) R_y(\theta) R_x(\phi)), the position pp and velocity vv of the center of mass, and the angular velocity ω\omega in the world frame. The constant gg is a state so that gravity enters the model linearly. Foot ii is at rir_i relative to the center of mass and pushes with the force fif_i. The full single rigid body equations are

mv˙=∑ifi−mgez,ddt(Iwω)=∑iri×fi.m \dot v = \sum_i f_i - m g e_z, \qquad \frac{d}{dt}(I_w \omega) = \sum_i r_i \times f_i.

The method makes three approximations. It assumes small roll and pitch, so that Θ˙≈Rz(ψ)Tω\dot\Theta \approx R_z(\psi)^T \omega and Iw≈Rz(ψ)IBRz(ψ)TI_w \approx R_z(\psi) I_B R_z(\psi)^T. It drops the gyroscopic term ω×Iwω\omega \times I_w \omega. It takes the yaw ψk\psi_k, the contact sequence and the foot positions ri,kr_{i,k} from the reference trajectory, not from the solution. Then step kk of the horizon has the linear model x˙=A(ψk)x+B(ψk,r1,k,… )u\dot x = A(\psi_k) x + B(\psi_k, r_{1,k}, \dots) u, where uu stacks the forces of the feet in contact. The model is linear time-varying, not linearized about a fixed yaw.

Given the current state x0x_0, a reference Y1,…,YnY_1, \dots, Y_n for the next nn steps of length Δt\Delta t, diagonal weights LL and α>0\alpha > 0, the friction coefficient μ\mu and the force limits fmin⁡≤fz≤fmax⁡f_{\min} \le f_z \le f_{\max}, the task is

min⁡U∑k=1n(Xk−Yk)TL(Xk−Yk)+α∣U∣2\min_{U} \sum_{k=1}^{n} (X_k - Y_k)^T L (X_k - Y_k) + \alpha |U|^2

subject to the model, the friction constraints and the force limits, with zero force at the feet in swing.

The algorithm

  1. CONVEX-MPC(x_0, Y, schedule, footholds, yaw reference)
  2. 1for k ← 0 to n - 1: A_k, B_k ← discrete model at yaw ψ_k with the feet in contact at step k
  3. 2Φ, S ← stacked prediction, so that X = Φ x_0 + S U
  4. 3H_qp ← 2 (Sᵀ L S + α I) ; g_qp ← 2 Sᵀ L (Φ x_0 - Y)
  5. 4for each step k and each foot i in contact at step k:
  6. add |f_x| ≤ μ f_z, |f_y| ≤ μ f_z and f_min ≤ f_z ≤ f_max
  7. 5U* ← argmin ½ Uᵀ H_qp U + g_qpᵀ U subject to the rows of line L4
  8. 6return the forces of step 0 in U* ▷ swing feet get zero force

Line L1 discretizes with a zero-order hold. The continuous matrix AA is nilpotent (A3=0A^3 = 0), so the hold is exact with three terms of the series. Line L2 is the condensed form: the states are eliminated, and only the forces of the feet in contact are variables. Lines L4 and L5 form a QP whose friction cone is a polyhedral friction cone with k=4k = 4 edges. This pyramid contains the Coulomb cone, so it slightly overestimates the friction; with μ/2\mu / \sqrt 2 in place of μ\mu it lies inside the cone. Di Carlo et al. solve the QP with the active-set solver qpOASES. The implementation here uses a dense primal-dual interior point method.

On the robot, the forces of line L6 are mapped to the joint torques of each stance leg with the transpose of the leg Jacobian, and the swing legs follow a foot trajectory. Foot placement is set by a separate heuristic; Di Carlo et al. use a Raibert-style law with an added term proportional to the speed error.

Example

The robot has m=10m = 10 kg, IB=diag⁡(0.1,0.25,0.3)I_B = \operatorname{diag}(0.1, 0.25, 0.3) kg m2^2 and four feet in contact at (±0.2,±0.12,−0.3)(\pm 0.2, \pm 0.12, -0.3) m from the center of mass. The weights are 20, 20 and 5 on roll, pitch and yaw, 1, 1 and 50 on the position, 0.5 on each angular velocity and 2 on each velocity, with α=10−6\alpha = 10^{-6}, μ=0.6\mu = 0.6, fmin⁡=0f_{\min} = 0 and fmax⁡=150f_{\max} = 150 N.

Standing. With x0x_0 at the reference and n=3n = 3 steps of 0.03 s, the QP gives fz=24.54f_z = 24.54 N at each foot and zero tangential force. The weight is mg/4=24.525m g / 4 = 24.525 N per foot; the difference of 0.05 percent is the effect of the force weight α\alpha on the plan over the short horizon.

Push. The robot starts at the reference height with a sideways velocity of 0.5 m/s and ω=(0.5,0,0.2)\omega = (0.5, 0, 0.2) rad/s. The MPC runs every 0.05 s with n=3n = 3, and the full nonlinear rigid body (with the gyroscopic term, rotation by the exponential map) is integrated at 1 ms with the forces held between solves.

tt (s) roll (rad) pyp_y (m) vyv_y (m/s) fzf_z left front, right front (N) fyf_y left front (N)
0.00 0.000 0.000 0.500 57.6, 0.0 -28.0
0.05 0.000 0.019 0.251 43.3, 0.0 -12.1
0.10 -0.020 0.028 0.130 44.8, 0.1 -12.5
0.20 -0.022 0.031 -0.002 31.0, 18.2 0.0
1.00 0.000 0.030 -0.002 30.7, 18.4 0.0

In the first solve the right feet carry no load: their bounds fz≥0f_z \ge 0 are active, and the left feet push sideways to stop the body. The sideways motion stops in about 0.2 s. The body then rests 3 cm to the left, and the forces split as (0.12+0.03)/0.24⋅49.05=30.66(0.12 + 0.03)/0.24 \cdot 49.05 = 30.66 N on each left foot, which is the static moment balance. The low weight on position and the short horizon make the return to py=0p_y = 0 slow.

Correctness

The proof file shows that the zero-order hold of line L1 is exact because A3=0A^3 = 0, that the condensed prediction of line L2 is the solution of the discrete model, that the k=4k = 4 pyramid contains the Coulomb cone, and that with α>0\alpha > 0 the QP of line L5 has a positive definite Hessian. So it has exactly one minimizer, which is characterized by the KKT conditions, and the solver returns it to the tolerance. This is a theorem about the model. The closed loop has no terminal cost or terminal set, and the model ignores roll and pitch in the kinematics, the gyroscopic term and the leg dynamics, so its stability on the robot is a measurement, not a theorem.

Proof: The convex MPC step solves a strictly convex QP of the linearized modelpartial

This file proves that each step of CONVEX-MPC computes the unique optimal force plan of the linear time-varying model that the method uses. It does not prove that the closed loop on the real robot, or on the full rigid body, is stable: the method has no terminal cost or terminal constraint, and the model is an approximation. Closed-loop stability is a measurement, made in simulation and on hardware.

The model. The state is x=(Θ,p,ω,v,g)∈R13x = (\Theta, p, \omega, v, g) \in \mathbb{R}^{13}, where Θ\Theta holds roll, pitch and yaw, ω\omega is the angular velocity in the world frame, and g=9.81g = 9.81 is a constant state. The exact relation between Θ˙\dot\Theta and ω\omega for R=Rz(ψ)Ry(θ)Rx(ϕ)R = R_z(\psi) R_y(\theta) R_x(\phi) is ω=E(ϕ,θ,ψ)Θ˙\omega = E(\phi, \theta, \psi) \dot\Theta with a matrix EE that equals Rz(ψ)R_z(\psi) when ϕ=θ=0\phi = \theta = 0. The method uses Θ˙=Rz(ψ)Tω\dot\Theta = R_z(\psi)^T \omega, so it assumes small roll and pitch. It also drops the gyroscopic term ω×Iω\omega \times I \omega and uses Iw=Rz(ψ)IBRz(ψ)TI_w = R_z(\psi) I_B R_z(\psi)^T. With the yaw ψk\psi_k and the foot positions ri,kr_{i,k} taken from the reference, the model on step kk is x˙=Akx+Bku\dot x = A_k x + B_k u with constant matrices, so the prediction is linear in the forces.

Lemma 1 (exact discretization). Let AA be the continuous matrix of line L1. Then A3=0A^3 = 0, and with the forces held constant over a step of length Δt\Delta t, the exact discrete model is x+=Adx+Bdux^+ = A_d x + B_d u with Ad=I+AΔt+A2Δt2/2A_d = I + A \Delta t + A^2 \Delta t^2 / 2 and Bd=(IΔt+AΔt2/2+A2Δt3/6)BB_d = (I \Delta t + A \Delta t^2 / 2 + A^2 \Delta t^3 / 6) B.

Proof. The nonzero blocks of AA map ω\omega to Θ˙\dot\Theta, vv to p˙\dot p and gg to v˙\dot v. The rows of ω\omega and gg are zero. So A2A^2 has only the block that maps gg to pp. The column of AA for pp is zero, because no derivative depends on pp, so A3=AA2=0A^3 = A A^2 = 0. The solution of x˙=Ax+Bu\dot x = A x + B u with constant uu is x(Δt)=eAΔtx(0)+∫0ΔteAsds Bux(\Delta t) = e^{A \Delta t} x(0) + \int_0^{\Delta t} e^{A s} ds\, B u, and both series end after the A2A^2 term. □\square

Lemma 2 (condensed prediction). Let Xk+1=AkXk+BkukX_{k+1} = A_k X_k + B_k u_k for k=0,…,H−1k = 0, \dots, H-1 with X0=x0X_0 = x_0. Then Xk=Φkx0+SkUX_k = \Phi_k x_0 + S_k U, where Φk=Ak−1⋯A0\Phi_k = A_{k-1} \cdots A_0 and the block of SkS_k for uju_j is Ak−1⋯Aj+1BjA_{k-1} \cdots A_{j+1} B_j for j<kj < k and zero otherwise.

Proof. By induction on kk. It holds for k=0k = 0 with S0=0S_0 = 0. If it holds for kk, then Xk+1=AkΦkx0+AkSkU+BkukX_{k+1} = A_k \Phi_k x_0 + A_k S_k U + B_k u_k, which is the claim for k+1k + 1. The function condense computes exactly x←Akxx \leftarrow A_k x and S←AkSS \leftarrow A_k S plus BkB_k in the columns of uku_k. □\square

Lemma 3 (the friction constraints). For each stance foot and step, the four rows ±fx−μfz≤0\pm f_x - \mu f_z \le 0 and ±fy−μfz≤0\pm f_y - \mu f_z \le 0 describe a pyramid with k=4k = 4 edges that contains the Coulomb cone fx2+fy2≤μfz\sqrt{f_x^2 + f_y^2} \le \mu f_z. A force in the pyramid can have fx2+fy2=2μfz\sqrt{f_x^2 + f_y^2} = \sqrt 2 \mu f_z, so the pyramid is an outer approximation. Replacing μ\mu by μ/2\mu / \sqrt 2 gives an inner one.

Proof. If fx2+fy2≤μfz\sqrt{f_x^2 + f_y^2} \le \mu f_z, then ∣fx∣≤μfz|f_x| \le \mu f_z and ∣fy∣≤μfz|f_y| \le \mu f_z. The corner fx=fy=μfzf_x = f_y = \mu f_z is in the pyramid with tangential size 2μfz\sqrt 2 \mu f_z. With μ′=μ/2\mu' = \mu / \sqrt 2, the pyramid gives fx2+fy2≤2μ′2fz2=μ2fz2f_x^2 + f_y^2 \le 2 \mu'^2 f_z^2 = \mu^2 f_z^2. □\square

Theorem (the QP step). With diagonal weights L⪰0L \succeq 0 and α>0\alpha > 0, the problem

min⁡U∑k=1H(Xk−Yk)TL(Xk−Yk)+α∣U∣2subject to the rows of Lemma 3 and fmin⁡≤fz≤fmax⁡\min_U \sum_{k=1}^{H} (X_k - Y_k)^T L (X_k - Y_k) + \alpha |U|^2 \quad \text{subject to the rows of Lemma 3 and } f_{\min} \le f_z \le f_{\max}

is a strictly convex QP with Hessian Hqp=2(∑kSkTLSk+αI)≻0H_{qp} = 2(\sum_k S_k^T L S_k + \alpha I) \succ 0 and linear term gqp=2∑kSkTL(Φkx0−Yk)g_{qp} = 2 \sum_k S_k^T L (\Phi_k x_0 - Y_k). If the feasible set is not empty, it has exactly one minimizer, and a point UU is that minimizer if and only if there are z≥0z \ge 0 with HqpU+gqp+GTz=0H_{qp} U + g_{qp} + G^T z = 0, GU≤hG U \le h and zi(h−GU)i=0z_i (h - G U)_i = 0 for each row ii.

Proof. Put Lemma 2 into the cost. The cost is UT(∑kSkTLSk+αI)U+2UT∑kSkTL(Φkx0−Yk)U^T (\sum_k S_k^T L S_k + \alpha I) U + 2 U^T \sum_k S_k^T L (\Phi_k x_0 - Y_k) plus a constant, which is 12UTHqpU+gqpTU\frac12 U^T H_{qp} U + g_{qp}^T U plus a constant. The matrix ∑kSkTLSk\sum_k S_k^T L S_k is positive semidefinite and αI\alpha I is positive definite, so Hqp≻0H_{qp} \succ 0 and the cost is strictly convex. The constraints are linear, so the feasible set is a closed convex polyhedron; a strictly convex quadratic that is bounded below on a nonempty closed convex set has exactly one minimizer. For a convex problem with linear constraints, the KKT conditions are necessary (no further constraint qualification is needed for linear constraints) and sufficient. □\square

Lines L2 and L3 build HqpH_{qp} and gqpg_{qp} as in the theorem, line L4 builds the rows, and line L5 solves the QP. The interior point method of solve_qp stops only when the KKT residuals and the average complementarity are below the tolerance, so its output is a KKT point up to that tolerance, which by the theorem is the minimizer up to the same order. The convergence of the Mehrotra predictor-corrector method in a bounded number of steps is not proved here; the code raises an error if it does not converge in 100 iterations.

What is not proved. The method applies only the first step of the plan (line L6) and solves again at the next control period. Without a terminal cost or a terminal constraint, there is no general guarantee that the receding-horizon loop is stable or that the QP stays feasible, and the model errors (roll and pitch, the gyroscopic term, leg dynamics and foot placement) are not bounded. The tests and the published experiments show that the loop works for the tested gaits; this is evidence, not proof.

Complexity

With nn horizon steps and cc feet in contact, the QP has N=3cnN = 3 c n variables and 6cn6 c n inequality rows, in the real-RAM model:

  • Lines L1 and L2 take O(n2c)O(n^2 c) operations, because SS has 13n×3cn13 n \times 3 c n entries and each block is a product of fixed-size matrices.
  • Line L3 takes O(n3c2)O(n^3 c^2) operations in general. The code skips zero entries and is O(n2c2)O(n^2 c^2) per state row with a nonzero weight.
  • Each interior point iteration factors an N×NN \times N matrix in O(N3)=O(n3c3)O(N^3) = O(n^3 c^3) operations. The friction rows touch only the forces of one foot, so adding them costs O(N)O(N).
  • The number of iterations is small in practice (about 10 here), but no bound is proved for the predictor-corrector version.

For n=10n = 10 and c=4c = 4 there are 120 variables. Di Carlo et al. report horizons of up to 0.5 s solved to optimality in under 1 ms, with the MPC running at 20 to 30 Hz.

Properties

  • Convex and global. Each step is a strictly convex QP, so the solver finds the global optimum of the model problem, with no initial guess and no local minima.
  • Fixed contact plan. The contact sequence and foot positions are inputs. The method does not choose when or where to step; that is a hybrid MPC or footstep planning problem.
  • Single rigid body. The legs are taken as massless. This works for robots with light legs, such as the Cheetah 3 and smaller quadrupeds, and less well for humanoids with heavy limbs.
  • Approximate friction. The pyramid with k=4k = 4 edges is an outer approximation of the Coulomb cone, so a planned force can slip by up to a factor 2\sqrt 2 in tangential size unless μ\mu is reduced.

Variants and improvements

  • Sparse form. Keep the states as variables with the model as equality constraints. The QP is larger but sparse and banded in time, and structure-exploiting solvers scale linearly in nn.
  • MPC plus whole-body control. The MPC runs at about 30 Hz and a whole-body controller at 500 Hz or more tracks its forces with the full robot model.
  • Full contact wrench. For feet with area, the force at a point is replaced by a contact wrench cone constraint, as in humanoid centroidal MPC.
  • Nonlinear and centroidal MPC. Without the small-angle assumptions, the problem is a nonlinear program, solved by sequential QP or by DDP-type methods, on the centroidal dynamics or the full model.

When to use it

Use it for quadrupeds and other robots with light legs, for gaits with a fixed timing such as trot, pace, bound and gallop, when the body roll and pitch stay moderate. It is a good default when a fast, robust force planner is needed and the contact plan comes from another layer. For walking humanoids with heavy legs, use a centroidal or whole-body model; for choosing the contact sequence itself, use hybrid MPC or contact-implicit trajectory optimization.

Pitfalls

  • Large roll or pitch. The relation Θ˙=RzTω\dot\Theta = R_z^T \omega is wrong for large roll and pitch, and the model degrades on steep slopes or in flips.
  • Infeasible QP. With tight force limits and a large disturbance, the constraints can have no solution. Production code softens some constraints or falls back to a safe policy.
  • Swing feet in the plan. A foot that is planned to be in contact but is not, because it lands late, gets force that it cannot apply. Contact detection must update the schedule.
  • Weight on the force. With α=0\alpha = 0, the Hessian is only semidefinite when the tracking cost does not fix all forces, and the solution is not unique; the solver may then jump between solutions from one step to the next.
  • The friction model. Using μ\mu in the pyramid lets the planned force exceed the true cone at the corners; slippage on low-friction ground often comes from this.

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.

convex_mpc_legged_locomotion.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/convex-mpc-legged-locomotion/. The authors are listed in prov/01NY1Z.jsonl.
"""Convex model predictive control of a legged robot (after Di Carlo et al. 2018).

The robot is one rigid body of mass m and body inertia I_B, pushed by point
contact forces at its feet. The state has 13 entries,

    x = (roll, pitch, yaw, p (3), omega (3, world frame), v (3), g),

where g = 9.81 is kept as a constant state so that gravity enters the linear
model. With small roll and pitch, and with the yaw and the foot positions
taken from the reference, the model is linear and time-varying:

    Theta' = Rz(yaw)^T omega,  p' = v,  omega' = I_w^(-1) sum r_i x f_i,
    v' = sum f_i / m - g e_z,  with I_w = Rz I_B Rz^T.

The planner stacks the horizon into one quadratic program in the stance
forces, with a friction pyramid with k = 4 edges and bounds on the normal
force, and solves it with a dense primal-dual interior point method.
Matrices are lists of rows; small linear algebra comes from rbm.py.
"""

import math

import rbm

G = 9.81
NX = 13


def model_matrices(m, inertia_body, yaw, feet):
    """Return the continuous A (13x13) and B (13 x 3n) for the feet in contact.

    feet is a list of foot positions relative to the center of mass, in the
    world frame. The columns of B come in triples (fx, fy, fz), one per foot.
    """
    rz = rbm.rot_z(yaw)
    a = rbm.zeros(NX, NX)
    rzt = rbm.transpose(rz)
    for i in range(3):
        for j in range(3):
            a[i][6 + j] = rzt[i][j]
        a[3 + i][9 + i] = 1.0
    a[11][12] = -1.0
    i_world = rbm.mul(rz, rbm.mul(inertia_body, rzt))
    i_inv = rbm.inv(i_world)
    b = rbm.zeros(NX, 3 * len(feet))
    for f, r in enumerate(feet):
        w = rbm.mul(i_inv, rbm.hat3(r))
        for i in range(3):
            for j in range(3):
                b[6 + i][3 * f + j] = w[i][j]
            b[9 + i][3 * f + i] = 1.0 / m
    return a, b


def discretize(a, b, dt):
    """Exact zero-order hold. A is nilpotent (A^3 = 0), so the series ends."""
    a2 = rbm.mul(a, a)
    n = len(a)
    ad = [[(1.0 if i == j else 0.0) + a[i][j] * dt + a2[i][j] * dt * dt / 2 for j in range(n)] for i in range(n)]
    m = [[(dt if i == j else 0.0) + a[i][j] * dt * dt / 2 + a2[i][j] * dt ** 3 / 6 for j in range(n)] for i in range(n)]
    return ad, rbm.mul(m, b)


def condense(x0, steps):
    """Stack the horizon: X = Aqp x0 + Bqp U.

    steps[k] = (A_k, B_k) for k = 0 .. H-1. Return (Aqp x0 as a list of
    H state vectors, Bqp as a list of H blocks of size 13 x n_u, offsets).
    """
    offsets = []
    n_u = 0
    for _, bk in steps:
        offsets.append(n_u)
        n_u += len(bk[0])
    free = []
    blocks = []
    x = list(x0)
    s = rbm.zeros(NX, n_u)
    for k, (ak, bk) in enumerate(steps):
        x = rbm.matvec(ak, x)
        s = rbm.mul(ak, s)
        for i in range(NX):
            for j in range(len(bk[0])):
                s[i][offsets[k] + j] += bk[i][j]
        free.append(x)
        blocks.append([row[:] for row in s])
    return free, blocks, n_u


def friction_rows(steps, mu, f_min, f_max):
    """Inequalities G u <= h as sparse rows: the k = 4 pyramid and the normal force bounds."""
    rows, h = [], []
    base = 0
    for _, bk in steps:
        for f in range(len(bk[0]) // 3):
            ix, iy, iz = base + 3 * f, base + 3 * f + 1, base + 3 * f + 2
            for it in (ix, iy):
                rows.append([(it, 1.0), (iz, -mu)])
                h.append(0.0)
                rows.append([(it, -1.0), (iz, -mu)])
                h.append(0.0)
            rows.append([(iz, -1.0)])
            h.append(-f_min)
            rows.append([(iz, 1.0)])
            h.append(f_max)
        base += len(bk[0])
    return rows, h


def _chol_solve(lower, b):
    n = len(b)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(lower[i][k] * y[k] for k in range(i))) / lower[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(lower[k][i] * x[k] for k in range(i + 1, n))) / lower[i][i]
    return x


def _g_times(rows, u):
    return [sum(c * u[i] for i, c in row) for row in rows]


def _gt_times(rows, z, n):
    out = [0.0] * n
    for row, zi in zip(rows, z):
        for i, c in row:
            out[i] += c * zi
    return out


def solve_qp(hm, g, rows, h, tol=1e-12, max_iter=100):
    """Minimize u^T hm u / 2 + g^T u subject to G u <= h (Mehrotra predictor-corrector).

    hm must be symmetric positive definite. Return (u, z), where z holds the
    multipliers of the inequalities.
    """
    n, m = len(g), len(h)
    u = [0.0] * n
    s = [max(hi - gi, 1.0) for hi, gi in zip(h, _g_times(rows, u))]
    z = [1.0] * m
    scale = 1.0 + max(abs(v) for v in g + h)
    for _ in range(max_iter):
        gu = _g_times(rows, u)
        rd = [a + b + c for a, b, c in zip(rbm.matvec(hm, u), g, _gt_times(rows, z, n))]
        rp = [a + b - c for a, b, c in zip(gu, s, h)]
        mu = sum(a * b for a, b in zip(s, z)) / m
        if max(abs(v) for v in rd + rp) < tol * scale and mu < tol * scale:
            return u, z
        k = [row[:] for row in hm]
        d = [zi / si for zi, si in zip(z, s)]
        for row, di in zip(rows, d):
            for i, ci in row:
                for j, cj in row:
                    k[i][j] += di * ci * cj
        lower = rbm.cholesky(k)

        def newton(rc):
            # Solve for (du, ds, dz) with complementarity residual rc.
            w = [(zi * rpi - rci) / si for zi, rpi, rci, si in zip(z, rp, rc, s)]
            rhs = [-a - b for a, b in zip(rd, _gt_times(rows, w, n))]
            du = _chol_solve(lower, rhs)
            gdu = _g_times(rows, du)
            ds = [-a - b for a, b in zip(rp, gdu)]
            dz = [(-rci - zi * dsi) / si for rci, zi, dsi, si in zip(rc, z, ds, s)]
            return du, ds, dz

        def max_step(v, dv):
            a = 1.0
            for vi, dvi in zip(v, dv):
                if dvi < 0:
                    a = min(a, -vi / dvi)
            return a

        rc = [si * zi for si, zi in zip(s, z)]
        du, ds, dz = newton(rc)
        a_aff = min(max_step(s, ds), max_step(z, dz))
        mu_aff = sum((si + a_aff * dsi) * (zi + a_aff * dzi) for si, dsi, zi, dzi in zip(s, ds, z, dz)) / m
        sigma = (mu_aff / mu) ** 3
        rc = [si * zi + dsi * dzi - sigma * mu for si, zi, dsi, dzi in zip(s, z, ds, dz)]
        du, ds, dz = newton(rc)
        a = 0.99 * min(max_step(s, ds), max_step(z, dz))
        a = min(a, 1.0)
        u = [ui + a * v for ui, v in zip(u, du)]
        s = [si + a * v for si, v in zip(s, ds)]
        z = [zi + a * v for zi, v in zip(z, dz)]
    raise ValueError("the interior point method did not converge")


def build_qp(x0, ref, steps, weights, alpha):
    """Return (Hqp, gqp, n_u) of the condensed problem.

    Cost: sum over k of (X_k - ref_k)^T diag(weights) (X_k - ref_k) + alpha |U|^2.
    """
    free, blocks, n_u = condense(x0, steps)  # @line L2
    hm = [[2 * alpha if i == j else 0.0 for j in range(n_u)] for i in range(n_u)]
    g = [0.0] * n_u
    for xk, bk, yk in zip(free, blocks, ref):  # @line L3
        for r in range(NX):
            w = weights[r]
            if w == 0.0:
                continue
            row = bk[r]
            nz = [j for j in range(n_u) if row[j] != 0.0]
            e = xk[r] - yk[r]
            for i in nz:
                g[i] += 2 * w * row[i] * e
                for j in nz:
                    hm[i][j] += 2 * w * row[i] * row[j]
    return hm, g, n_u


def convex_mpc(x0, ref, plan, m, inertia_body, dt, weights, alpha, mu, f_min, f_max):
    """One MPC solve.

    plan[k] = (yaw_k, feet_k) for k = 0 .. H-1, where feet_k lists the
    positions (relative to the center of mass, world frame) of the feet in
    contact at step k. ref[k] is the wanted state X_(k+1).
    Return (forces of the feet in contact at step 0 as 3-vectors, U, z).
    """
    steps = []
    for yaw, feet in plan:  # @line L1
        a, b = model_matrices(m, inertia_body, yaw, feet)
        steps.append(discretize(a, b, dt))
    hm, g, n_u = build_qp(x0, ref, steps, weights, alpha)
    rows, h = friction_rows(steps, mu, f_min, f_max)  # @line L4
    u, z = solve_qp(hm, g, rows, h)  # @line L5
    n0 = len(plan[0][1])
    return [u[3 * i: 3 * i + 3] for i in range(n0)], u, z  # @line L6


class RigidBody:
    """Full nonlinear rigid body for closed-loop tests: no small-angle approximation."""

    def __init__(self, m, inertia_body, p, rot, v, w):
        self.m = m
        self.ib = inertia_body
        self.p = list(p)
        self.rot = [row[:] for row in rot]
        self.v = list(v)
        self.w = list(w)

    def step(self, feet_world, forces, dt, g=G):
        """Semi-implicit Euler step; the rotation is updated with the exact so3_exp."""
        total = [0.0, 0.0, -self.m * g]
        torque = [0.0, 0.0, 0.0]
        for foot, f in zip(feet_world, forces):
            r = [a - b for a, b in zip(foot, self.p)]
            total = [a + b for a, b in zip(total, f)]
            torque = [a + b for a, b in zip(torque, rbm.cross(r, f))]
        iw = rbm.mul(self.rot, rbm.mul(self.ib, rbm.transpose(self.rot)))
        gyro = rbm.cross(self.w, rbm.matvec(iw, self.w))
        wdot = rbm.solve(iw, [a - b for a, b in zip(torque, gyro)])
        self.v = [a + dt * b / self.m for a, b in zip(self.v, total)]
        self.p = [a + dt * b for a, b in zip(self.p, self.v)]
        self.w = [a + dt * b for a, b in zip(self.w, wdot)]
        self.rot = rbm.mul(rbm.so3_exp([dt * a for a in self.w]), self.rot)

    def rpy(self):
        """Return (roll, pitch, yaw) with R = Rz(yaw) Ry(pitch) Rx(roll)."""
        r = self.rot
        pitch = -math.asin(max(-1.0, min(1.0, r[2][0])))
        roll = math.atan2(r[2][1], r[2][2])
        yaw = math.atan2(r[1][0], r[0][0])
        return roll, pitch, yaw

    def state(self, g=G):
        return list(self.rpy()) + self.p + self.w + self.v + [g]
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    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 _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(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 product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-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 _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, 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:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    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 quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_convex_mpc_legged_locomotion.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/convex-mpc-legged-locomotion/. The authors are listed in prov/01NY1Z.jsonl.
# The closed-loop test integrates the full rigid body with semi-implicit Euler
# (rotation by so3_exp) at dt = 1e-3 s, at most 1000 steps.

import random

import rbm
from convex_mpc_legged_locomotion import (
    G,
    RigidBody,
    build_qp,
    convex_mpc,
    discretize,
    friction_rows,
    model_matrices,
    solve_qp,
)

M = 10.0
IB = [[0.1, 0.0, 0.0], [0.0, 0.25, 0.0], [0.0, 0.0, 0.3]]
FEET = [[0.2, 0.12, -0.3], [0.2, -0.12, -0.3], [-0.2, 0.12, -0.3], [-0.2, -0.12, -0.3]]
W = [20, 20, 5, 1, 1, 50, 0.5, 0.5, 0.5, 2, 2, 2, 0]
REF = [0, 0, 0, 0, 0, 0.3, 0, 0, 0, 0, 0, 0, G]


def test_zero_order_hold_matches_fine_integration():
    rng = random.Random(1)
    a, b = model_matrices(M, IB, 0.4, FEET)
    dt = 0.05
    ad, bd = discretize(a, b, dt)
    x = [rng.uniform(-1, 1) for _ in range(12)] + [G]
    u = [rng.uniform(-20, 20) for _ in range(12)]
    want = [p + q for p, q in zip(rbm.matvec(ad, x), rbm.matvec(bd, u))]
    # RK4 on x' = A x + B u with 100 steps.
    bu = rbm.matvec(b, u)

    def f(y):
        return [p + q for p, q in zip(rbm.matvec(a, y), bu)]

    h = dt / 100
    y = list(x)
    for _ in range(100):
        k1 = f(y)
        k2 = f([p + h / 2 * q for p, q in zip(y, k1)])
        k3 = f([p + h / 2 * q for p, q in zip(y, k2)])
        k4 = f([p + h * q for p, q in zip(y, k3)])
        y = [p + h / 6 * (q + 2 * r + 2 * s + t) for p, q, r, s, t in zip(y, k1, k2, k3, k4)]
    for p, q in zip(y, want):
        assert abs(p - q) < 1e-12


def test_standing_robot_puts_a_quarter_of_the_weight_on_each_foot():
    plan = [(0.0, FEET)] * 3
    forces, _, _ = convex_mpc(REF, [REF] * 3, plan, M, IB, 0.03, W, 1e-6, 0.6, 0.0, 150.0)
    for f in forces:
        assert abs(f[2] - M * G / 4) < 0.01 * M * G / 4
        assert abs(f[0]) < 1e-6 and abs(f[1]) < 1e-6


def small_qp(mu):
    feet = [FEET[0], FEET[3]]
    x0 = [0.05, -0.03, 0, 0, 0, 0.29, 0.4, 0, 0, 0, 0.8, -0.2, G]
    steps = [discretize(*model_matrices(M, IB, 0.0, feet), 0.04)] * 2
    hm, g, _ = build_qp(x0, [REF] * 2, steps, W, 1e-4)
    rows, h = friction_rows(steps, mu, 2.0, 50.0)
    return hm, g, rows, h


def test_kkt_conditions_hold():
    hm, g, rows, h = small_qp(0.1)
    u, z = solve_qp(hm, g, rows, h)
    n = len(u)
    grad = [p + q for p, q in zip(rbm.matvec(hm, u), g)]
    for row, zi in zip(rows, z):
        for i, c in row:
            grad[i] += c * zi
    scale = max(abs(v) for v in g)
    assert max(abs(v) for v in grad) < 1e-8 * scale
    active = 0
    for row, hi, zi in zip(rows, h, z):
        slack = hi - sum(c * u[i] for i, c in row)
        assert slack > -1e-8 and zi > -1e-12
        assert abs(slack * zi) < 1e-6
        active += zi > 1e-6
    # The friction pyramid binds for this push.
    assert active >= 4
    assert n == 12


def test_matches_hildreth_dual_coordinate_ascent():
    hm, g, rows, h = small_qp(0.1)
    u, _ = solve_qp(hm, g, rows, h)
    n, m = len(g), len(rows)
    gm = [[0.0] * n for _ in range(m)]
    for i, row in enumerate(rows):
        for j, c in row:
            gm[i][j] = c
    hinv = rbm.inv(hm)
    hg = rbm.matvec(hinv, g)
    ghi = rbm.mul(gm, hinv)
    p = rbm.mul(ghi, rbm.transpose(gm))
    d = [hi + v for hi, v in zip(h, rbm.matvec(gm, hg))]
    lam = [0.0] * m
    for _ in range(1000):
        for i in range(m):
            r = sum(p[i][j] * lam[j] for j in range(m)) + d[i]
            lam[i] = max(0.0, lam[i] - r / p[i][i])
    uh = [-a - b for a, b in zip(hg, rbm.matvec(rbm.transpose(ghi), lam))]
    for a, b in zip(u, uh):
        assert abs(a - b) < 1e-5 * max(abs(v) for v in u)


def test_push_recovery_on_the_full_rigid_body():
    feet_w = [[a, b, c + 0.3] for a, b, c in FEET]
    body = RigidBody(M, IB, [0.0, 0.0, 0.3], rbm.eye(3), [0.0, 0.5, 0.0], [0.5, 0.0, 0.2])
    mu, f_max, dt_mpc, horizon = 0.6, 150.0, 0.05, 3
    steps = 0
    for _ in range(20):
        x = body.state()
        rel = [[a - b for a, b in zip(f, body.p)] for f in feet_w]
        forces, _, _ = convex_mpc(x, [REF] * horizon, [(x[2], rel)] * horizon, M, IB, dt_mpc, W, 1e-6, mu, 0.0, f_max)
        for f in forces:
            assert -1e-6 <= f[2] <= f_max + 1e-6
            assert abs(f[0]) <= mu * f[2] + 1e-6 and abs(f[1]) <= mu * f[2] + 1e-6
        for _ in range(50):
            body.step(feet_w, forces, 1e-3)
            steps += 1
    assert steps <= 1000
    x = body.state()
    # Attitude and speed are back near the reference; the sideways drift stays small.
    assert max(abs(v) for v in x[0:3]) < 0.005
    assert max(abs(v) for v in x[6:12]) < 0.01
    assert abs(x[4]) < 0.05 and abs(x[5] - 0.3) < 0.005

History

Linear MPC for walking with the ZMP as a constraint goes back to Wieber (2006). For quadrupeds, Di Carlo, Wensing, Katz, Bledt and Kim presented the convex MPC of the MIT Cheetah 3 at IROS 2018. Their key steps were the single rigid body model with the yaw taken from the reference, which keeps the problem a QP, and the condensed form solved by an active-set solver. The method is now a common baseline for quadruped control.

References

  1. Jared Di Carlo, Patrick M. Wensing, Benjamin Katz, Gerardo Bledt and Sangbae Kim, Dynamic locomotion in the MIT Cheetah 3 through convex model-predictive control, IEEE/RSJ International Conference on Intelligent Robots and Systems, 2018, pages 1 to 9
  2. Pierre-Brice Wieber, Trajectory free linear model predictive control for stable walking in the presence of strong perturbations, IEEE-RAS International Conference on Humanoid Robots, 2006, pages 137 to 142
  3. Jorge Nocedal and Stephen J. Wright, Numerical Optimization, second edition, Springer, 2006, Chapter 16 (quadratic programming, interior point methods for QP)

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 correctness
  • a full proof of time.build
  • a full proof of time.per_iteration
  • 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
  • a scene preset for the example