Algorithmadvanced
ZMP preview control
Also called Kajita preview control.
Kajita's walking pattern generator: an LQ preview controller on the cart-table model that moves the center of mass so that the ZMP follows a planned reference known for the next N steps.
- Time
- O(N) gains · per_step
- Space
- O(N) extra
- Where
- N = the number of preview steps; the state has 4 entries per horizontal axis
- Model
- Real RAM
- Properties
- deterministicnot exactonline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Shuuji Kajita, Fumio Kanehiro, Kenji Kaneko, Kiyoshi Fujiwara, Kensuke Harada, Kazuhito Yokoi, Hirohisa Hirukawa, 2003
ZMP preview control computes a center of mass (CoM) motion for a walking robot so that its zero moment point (ZMP) follows a reference that the footstep plan fixes in advance. It models the robot as a cart on a table, which is the linear inverted pendulum with the CoM acceleration as a state, and it solves a discrete-time linear quadratic problem in which the next reference values are known. The result is a fixed linear law: a state feedback plus a weighted sum of the future reference changes. It is optimal for the cart-table model only, and it is not a stability proof for the robot that executes the motion.
In plain words
To walk, a robot must keep its ZMP inside the foot that carries it. The footstep plan says where each foot will be and when, so the wanted ZMP path is known for the next second or two.
The CoM cannot simply copy this path. To move the ZMP to the next foot, the body must already be moving toward that foot, because the ZMP sits behind the body when the body speeds up. So the body has to start moving before the step.
Preview control looks at the planned ZMP path for a fixed time ahead and chooses the body motion that keeps the ZMP close to the plan with small, smooth pushes. The weights on the future plan are computed once. While the robot walks, each control step needs only a sum over the window ahead.
The problem
Take one horizontal axis; the other axis is the same problem with its own reference. The CoM moves at the constant height above flat ground, m/s, and . The state is for the CoM position , and the input is the jerk . The ZMP of this cart-table model is
which is the LIPM equation solved for . With the sampling period and a jerk held constant over each period, the exact discrete model is
A reference sequence for the ZMP is given, and at step the values are known. With the ZMP error and the increments and , the task is to choose to minimize
with , and . This is the form of Katayama et al. (1985) that Kajita et al. (2003) used. Because the cost is on the increments, the controller has integral action on the ZMP error.
The algorithm
The incremental state obeys , where , and . The gains are computed once, offline.
PREVIEW-GAINS(T, z_c, N, Q_e, Q_x, R)- 1
A, B, C ← cart-table model with period T and height z_c - 2
Ã, B̃ ← incremental model of (A, B, C) - 3
P ← stabilizing solution of the DARE for (Ã, B̃, diag(Q_e, Q_x), R) - 4
s ← R + B̃ᵀ P B̃ ; K ← s⁻¹ B̃ᵀ P Ã - 5
A_c ← Ã - B̃ K - 6
v ← P e_1 - 7
for j ← 1 to N - 8
f_j ← s⁻¹ B̃ᵀ v ▷ weight of the reference change j steps ahead - 9
v ← A_cᵀ v return K, f_1, ..., f_NPREVIEW-CONTROL(r, x_0)- 10
x_prev ← x_0 ; u ← 0 - 11
for k ← 0, 1, 2, ... - 12
e ← C x_k - r_k - 13
Δx ← x_k - x_prev - 14
Δu ← -K (e, Δx) + Σ_{j=1}^{N} f_j (r_{k+j} - r_{k+j-1}) - 15
u ← u + Δu - 16
x_prev ← x_k ; x_{k+1} ← A x_k + B u ▷ on a robot: pass x_{k+1} to the whole-body controller
Line L3 solves the discrete algebraic Riccati equation; value iteration from converges because the incremental model is controllable and the error is observable. Line L14 is the whole online law. Kajita et al. write it as an integral of the error, a state feedback on and a weighted sum of the future reference values themselves; that form is the same law after a summation by parts.
On a robot, the CoM trajectory of line L16 is the output. Inverse kinematics or a whole-body controller then finds joint motions that realize it, and the real ZMP differs from the model ZMP by the effect of the limbs, which the cart-table model ignores.
Example
Take m, s, , , and a preview of steps (1.6 s). Lines L1 to L9 give, rounded,
| quantity | value |
|---|---|
| on | |
The first preview weight equals the error gain, the weights peak at and then decay, and after 1.6 s they are below 1 percent of the peak. This is why a preview of about 1.5 s is enough for these weights; a longer window adds almost nothing.
Now let the robot stand at , and let the reference step from 0 to 0.1 m at s (). The closed loop of lines L10 to L16 gives
| (s) | (m) | (m/s) | (m) |
|---|---|---|---|
| 1.0 | 0.0014 | 0.0056 | -0.0001 |
| 1.5 | 0.0088 | 0.0310 | 0.0000 |
| 1.9 | 0.0358 | 0.1256 | 0.0001 |
| 2.0 | 0.0508 | 0.1699 | 0.0673 |
| 2.5 | 0.0915 | 0.0299 | 0.1000 |
| 4.0 | 0.1000 | 0.0002 | 0.1000 |
The CoM starts to move about a second before the step and is half way at the step time, while the ZMP stays near 0. Just before the step the ZMP moves 3.1 mm the wrong way, to m at s, which is the non-minimum phase behavior of the cart-table model. With a preview of only 0.2 s (), the same step pushes the ZMP to m before the step: the controller sees the step too late and must throw the ZMP far back to start the CoM.
Correctness
The proof file shows that the incremental model is controllable and the ZMP error observable for every and , so the Riccati equation has a stabilizing solution and is Schur stable. It then shows by dynamic programming that, when the reference does not change after step , line L14 gives the unique optimal first input of the problem, with . If the reference is constant from some step on, the ZMP error goes to zero. All of this is a theorem about the cart-table model. It is not a proof that the robot stays balanced; that depends on how well the whole-body motion realizes the CoM path and on the ZMP reference staying inside the support polygon.
Proof: The preview law is the optimal control of the incremental cart-table problemfull
This proof is about the cart-table model only. It shows that the law of ZMP-PREVIEW-CONTROL is the exact minimizer of its quadratic cost and that the closed loop of the model is stable. It says nothing about the stability of a real multibody robot.
Setting. The sampling period is and . The cart-table model is , , with
Write , , , and . Then and , so
The weights are with and , and .
Lemma 1 (controllability and observability). The pair is controllable, and the pair is observable.
Proof. The matrix is upper triangular with all diagonal entries 1, so its only eigenvalue is 1. By the Popov-Belevitch-Hautus test it is enough to check the rank at . The first column of is zero, so the rank of is the rank of the matrix with rows and :
It is upper triangular with determinant , so the rank is 4. For observability, stack on . The row gives the first column, and the last three columns contain the rows , and , which are independent. So the rank is 4.
Because with , Lemma 1 gives that is stabilizable and is detectable. The standard theory of the discrete algebraic Riccati equation then gives a unique symmetric with
such that is Schur stable, where and . The value iteration from converges to this . This is what line L3 computes, and lines L4 and L5 compute and .
Theorem (optimality). Fix a step and a preview length , and assume for every . For every horizon , the problem
has a unique minimizer, and its first input is
Proof. We use dynamic programming backward from . We claim that the optimal cost to go from step is , where , does not depend on , and
The claim holds at by the terminal cost. Assume it holds at . Put into . Up to terms that do not depend on or , the cost of the input at step is
This is a quadratic in the scalar with leading coefficient , so the minimizer is unique. Setting the derivative to zero gives , so . Put back. The terms quadratic in are by the Riccati equation. For the terms linear in , differentiate the minimum with respect to ; because is a stationary point, only the explicit dependence counts, and the part of the gradient that is linear in is , where we used . So the linear term is , which is the claim at step .
Now unroll the recursion from step . Because for and , the vector at step is
With , the first input is .
The code computes these gains. Line L6 sets . In the loop of lines L7 to L9, before pass the vector is , line L8 appends , and line L9 multiplies by . Lines L12 to L15 form , apply the law of the theorem, and add to . Line L16 is the exact discrete model.
Remarks.
- The terminal cost is the optimal cost of the problem without reference changes, because is the stabilizing solution. So the theorem also gives the first input of the infinite-horizon problem when the reference is constant after the preview window. If the reference changes after step , the law ignores those changes and is optimal only for the truncated reference.
- If the reference is constant from some step on, then from there and . Because is Schur stable, , so the ZMP error and the increments go to zero. The integrator in removes a constant offset of the ZMP.
- Lemma 1 holds for every and , but the gains that the iteration gives depend on , , and , and the numbers in the page are computed, not derived.
Complexity
In the real-RAM model, with preview steps and the 4-entry incremental state of one axis:
- Lines L4 to L9 take operations, because each pass is a product of a matrix and a vector.
- Line L3 by value iteration takes a number of iterations that depends on the decay rate of , each of constant cost; a Schur method on the symplectic pencil takes constant time.
- Each control step costs for the sum in line L14, and the memory is for the weights and the reference window.
Properties
- Optimal only for the model. The law minimizes the quadratic cost for the cart-table model with a known reference. It does not enforce the support polygon, joint limits or torque limits.
- Integral action. The cost on increments puts the ZMP error through an integrator, so a constant offset of the ZMP is removed.
- Linear and time invariant. The gains do not depend on the reference, so they are computed once for a given and .
- Constant height. The model needs a constant CoM height and zero change of angular momentum about the CoM; both are approximations on a real robot.
Variants and improvements
- Two-stage controller. Kajita et al. (2003) run the preview controller a second time on the error between the model ZMP and the ZMP of the multibody model, to correct the effect of the limbs.
- Model predictive control. Wieber (2006) solves a finite-horizon quadratic program at each step and adds the ZMP constraint as a hard inequality, which gives better behavior under strong pushes. See linear MPC.
- Divergent component of motion. Controllers based on the capture point plan only the unstable part of the LIPM and do not need a long preview window.
- Varying height. Without the constant height, the ZMP is a nonlinear function of the CoM motion, and the problem is usually solved as a nonlinear or sequential convex program.
When to use it
Use it to generate CoM paths for walking on flat ground when the footstep timing and positions are fixed for the next second or more. It is cheap and robust as a pattern generator. If the ZMP must satisfy hard limits, or if the plan must change from step to step in reaction to pushes, a model predictive controller or a capture point controller is a better fit. For running, jumping or rough terrain, the LIPM assumptions fail, and centroidal dynamics models are used.
Pitfalls
- Short preview. With a window much shorter than the time constant of the weights, the ZMP error before each step is large, as in the example above.
- Reference outside the foot. The controller tracks whatever reference it gets. A ZMP reference that leaves the support polygon gives a CoM path that the robot cannot realize.
- Model ZMP versus real ZMP. The limbs have mass, so the ZMP of the robot differs from the model ZMP. Without the second stage or a whole-body correction, this error is not corrected.
- Ill-conditioned weights. Very small with a small makes the gains large; a fixed number of Riccati iterations may not converge, so test the convergence.
- Sign conventions. Some texts write the law in terms of , others in terms of , and the signs of the gains differ. Mixing the two forms gives a controller that tracks the wrong reference.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the 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
zmp_preview_control.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zmp-preview-control/. The authors are listed in prov/CQQDWX.jsonl.
"""ZMP preview control on the cart-table model (Kajita et al. 2003).
One horizontal axis. The state is x = (c, c', c'') of the center of mass,
the input is the jerk u = c''', and the output is the ZMP of the
cart-table model, p = c - (zc / g) c''. The controller works on the
incremental state X = (e, dx), where e = p - p_ref is the ZMP error and
dx = x_k - x_(k-1), with the input du = u_k - u_(k-1). It minimizes
sum over k of Qe e_k^2 + dx_k^T Qx dx_k + R du_k^2
and uses the next N reference values. The law is
du_k = -K X_k + sum_(j = 1..N) f_j (p_ref[k + j] - p_ref[k + j - 1]).
Matrices are lists of rows; the linear algebra is in rbm.py.
"""
import rbm
G = 9.81
def cart_table(T, zc, g=G):
"""Return A, B, C of the cart-table model sampled with period T."""
A = [[1.0, T, T * T / 2.0], [0.0, 1.0, T], [0.0, 0.0, 1.0]]
B = [T ** 3 / 6.0, T * T / 2.0, T]
C = [1.0, 0.0, -zc / g]
return A, B, C
def augment(A, B, C):
"""Return the incremental model X+ = At X + Bt du - I1 dr."""
ca = [rbm.dot(C, [A[i][j] for i in range(3)]) for j in range(3)]
at = [[1.0] + ca] + [[0.0] + list(A[i]) for i in range(3)]
bt = [rbm.dot(C, B)] + list(B)
return at, bt
def solve_dare(at, bt, q, r, tol=1e-12, max_iter=200000):
"""Solve P = Q + A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A by iteration.
The input is scalar, so R + B^T P B is a number. The iteration starts
at P = Q and stops when no entry changes by more than tol times the
largest entry of P.
"""
n = len(at)
p = [row[:] for row in q]
a_t = rbm.transpose(at)
for _ in range(max_iter):
pb = rbm.matvec(p, bt)
s = r + rbm.dot(bt, pb)
bpa = [rbm.dot(pb, [at[i][j] for i in range(n)]) for j in range(n)]
apa = rbm.mul(a_t, rbm.mul(p, at))
new = [[q[i][j] + apa[i][j] - bpa[i] * bpa[j] / s for j in range(n)] for i in range(n)]
big = max(abs(v) for row in new for v in row)
diff = max(abs(new[i][j] - p[i][j]) for i in range(n) for j in range(n))
p = new
if diff <= tol * big:
return p
raise ValueError("the Riccati iteration did not converge")
def preview_gains(T, zc, n_preview, qe=1.0, qx=0.0, r=1e-6, g=G):
"""Return (K, f, P): the state gain, the N preview gains and the Riccati solution."""
A, B, C = cart_table(T, zc, g) # @line L1
at, bt = augment(A, B, C) # @line L2
q = rbm.zeros(4, 4)
q[0][0] = qe
for i in range(1, 4):
q[i][i] = qx
p = solve_dare(at, bt, q, r) # @line L3
pb = rbm.matvec(p, bt)
s = r + rbm.dot(bt, pb)
k = [rbm.dot(pb, [at[i][j] for i in range(4)]) / s for j in range(4)] # @line L4
ac = [[at[i][j] - bt[i] * k[j] for j in range(4)] for i in range(4)] # @line L5
ac_t = rbm.transpose(ac)
v = [p[i][0] for i in range(4)] # @line L6: v = P I1
f = []
for _ in range(n_preview): # @line L7
f.append(rbm.dot(bt, v) / s) # @line L8
v = rbm.matvec(ac_t, v) # @line L9
return k, f, p
def preview_control(p_ref, T, zc, n_preview, x0=None, qe=1.0, qx=0.0, r=1e-6, g=G):
"""Run the closed loop on the cart-table model.
p_ref[k] is the ZMP reference at step k; values past the end repeat the
last one. Return (xs, ps, us): the states x_0 .. x_K, the ZMP p_0 .. p_(K-1)
and the jerks u_0 .. u_(K-1), where K = len(p_ref).
"""
A, B, C = cart_table(T, zc, g)
k_gain, f, _ = preview_gains(T, zc, n_preview, qe, qx, r, g)
last = len(p_ref) - 1
def ref(i):
return p_ref[min(i, last)]
x = list(x0) if x0 is not None else [ref(0), 0.0, 0.0]
x_prev = list(x) # @line L10
u = 0.0
xs, ps, us = [list(x)], [], []
for kk in range(len(p_ref)): # @line L11
p = rbm.dot(C, x)
e = p - ref(kk) # @line L12
dx = [a - b for a, b in zip(x, x_prev)] # @line L13
du = -(k_gain[0] * e + rbm.dot(k_gain[1:], dx)) # @line L14
du += sum(f[j - 1] * (ref(kk + j) - ref(kk + j - 1)) for j in range(1, n_preview + 1))
u += du # @line L15
x_prev = x
x = [a + b * u for a, b in zip(rbm.matvec(A, x), B)] # @line L16
ps.append(p)
us.append(u)
xs.append(list(x))
return xs, ps, us
def walking_reference(T, step_time, n_steps, step_length, half_width, settle=1.0):
"""Return ZMP references (px, py) for straight walking.
The ZMP rests at 0 for settle seconds, then moves to each foot in turn:
foot i (i = 1 .. n_steps) is at x = (i - 1) step_length and
y = +half_width or -half_width, alternating, for step_time seconds.
At the end it returns to the middle of the last two feet.
"""
px, py = [], []
m = int(round(settle / T))
px += [0.0] * m
py += [0.0] * m
s = int(round(step_time / T))
for i in range(1, n_steps + 1):
x = (i - 1) * step_length
y = half_width if i % 2 == 1 else -half_width
px += [x] * s
py += [y] * s
x_end = (n_steps - 1) * step_length
px += [x_end] * (2 * m)
py += [0.0] * (2 * m)
return px, py
test_zmp_preview_control.py 124 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/zmp-preview-control/. The authors are listed in prov/CQQDWX.jsonl.
import random
import rbm
from zmp_preview_control import augment, cart_table, preview_control, preview_gains, walking_reference
ZC = 0.8
def test_cart_table_is_exact_for_constant_jerk():
# The discrete model must agree with c(t) = c0 + v t + a t^2 / 2 + u t^3 / 6.
T = 0.05
A, B, _ = cart_table(T, ZC)
rng = random.Random(3)
x = [rng.uniform(-1, 1) for _ in range(3)]
u = rng.uniform(-5, 5)
y = list(x)
for _ in range(20):
y = [a + b * u for a, b in zip(rbm.matvec(A, y), B)]
t = 20 * T
want = [
x[0] + x[1] * t + x[2] * t * t / 2 + u * t ** 3 / 6,
x[1] + x[2] * t + u * t * t / 2,
x[2] + u * t,
]
for i in range(3):
assert abs(y[i] - want[i]) < 1e-12
def test_riccati_residual_is_small():
T = 0.01
A, B, C = cart_table(T, ZC)
at, bt = augment(A, B, C)
k, f, p = preview_gains(T, ZC, 160)
r = 1e-6
q = rbm.zeros(4, 4)
q[0][0] = 1.0
pb = rbm.matvec(p, bt)
s = r + rbm.dot(bt, pb)
bpa = [rbm.dot(pb, [at[i][j] for i in range(4)]) for j in range(4)]
apa = rbm.mul(rbm.transpose(at), rbm.mul(p, at))
big = max(abs(v) for row in p for v in row)
for i in range(4):
for j in range(4):
res = q[i][j] + apa[i][j] - bpa[i] * bpa[j] / s - p[i][j]
assert abs(res) < 1e-8 * big
# The first preview gain equals the error gain, and after 1.6 s the gains are small.
assert abs(f[0] - k[0]) < 1e-9 * abs(k[0])
assert abs(f[-1]) < 0.01 * max(abs(v) for v in f)
def batch_optimum(T, ref, horizon, r=1e-6):
"""Minimize sum_k X_k^T Q X_k + R du_k^2 + X_H^T P X_H by least squares."""
A, B, C = cart_table(T, ZC)
at, bt = augment(A, B, C)
_, _, p = preview_gains(T, ZC, 1, r=r)
q = rbm.zeros(4, 4)
q[0][0] = 1.0
# X_k = S_k du + c_k, built step by step.
s_mat = [[0.0] * horizon for _ in range(4)]
c = [0.0] * 4
hess = [[0.0] * horizon for _ in range(horizon)]
grad = [0.0] * horizon
for i in range(horizon):
hess[i][i] += r
for kk in range(horizon):
new_s = [[0.0] * horizon for _ in range(4)]
for a in range(4):
for col in range(horizon):
new_s[a][col] = sum(at[a][b] * s_mat[b][col] for b in range(4))
new_s[a][kk] += bt[a]
dr = ref[kk + 1] - ref[kk]
c = rbm.matvec(at, c)
c[0] -= dr
s_mat = new_s
w = p if kk == horizon - 1 else q
ws = rbm.mul(w, s_mat)
wc = rbm.matvec(w, c)
for i in range(horizon):
for j in range(horizon):
hess[i][j] += sum(s_mat[a][i] * ws[a][j] for a in range(4))
grad[i] += sum(s_mat[a][i] * wc[a] for a in range(4))
return rbm.solve(hess, [-g for g in grad])
def test_matches_batch_optimum_when_preview_covers_all_changes():
# With every reference change inside the preview window, the preview law is
# the infinite-horizon optimum, which equals a finite problem with terminal cost P.
T, horizon = 0.05, 40
ref = [0.0] * 10 + [0.1] * 10 + [-0.05] * 30
_, _, us = preview_control(ref[:horizon], T, ZC, horizon)
du = [us[0]] + [us[i] - us[i - 1] for i in range(1, horizon)]
want = batch_optimum(T, ref, horizon)
scale = max(abs(v) for v in want)
for a, b in zip(du, want):
assert abs(a - b) < 1e-6 * scale
def test_zmp_tracks_walking_reference():
T = 0.01
px, py = walking_reference(T, 0.8, 6, 0.3, 0.1)
for ref, final in ((px, 1.5), (py, 0.0)):
xs, ps, _ = preview_control(ref, T, ZC, 160)
# Away from the switch instants the ZMP is close to the reference.
switches = [i for i in range(1, len(ref)) if ref[i] != ref[i - 1]]
for i in range(len(ref)):
if all(abs(i - s) > 15 for s in switches):
assert abs(ps[i] - ref[i]) < 0.01
# At the end the CoM rests over the last ZMP.
assert abs(xs[-1][0] - final) < 1e-3
assert abs(xs[-1][1]) < 1e-3
def test_com_moves_before_the_zmp_step():
T = 0.01
ref = [0.0] * 200 + [0.1] * 300
xs, ps, _ = preview_control(ref, T, ZC, 160)
# The CoM has started to move 0.1 s before the step, and the ZMP has not.
assert xs[190][0] > 0.02
assert abs(ps[190]) < 1e-3
# The ZMP first moves a little the wrong way (the model is non-minimum phase).
assert min(ps[:200]) < 0.0
History
Katayama, Ohki, Inoue and Kato published the discrete-time LQ preview controller with integral action in 1985. Kajita and colleagues used it in 2003 on the cart-table model, which they obtained by writing the 3D linear inverted pendulum of 2001 with the CoM acceleration as a state, and used it to generate walking patterns for a humanoid. Wieber's 2006 linear MPC replaced the infinite-horizon law by a constrained quadratic program, and later work moved to the divergent component of motion and to centroidal models.
References
- Shuuji Kajita, Fumio Kanehiro, Kenji Kaneko, Kiyoshi Fujiwara, Kensuke Harada, Kazuhito Yokoi and Hirohisa Hirukawa, Biped walking pattern generation by using preview control of zero-moment point, IEEE International Conference on Robotics and Automation, 2003, pages 1620 to 1626
- Tohru Katayama, Takahira Ohki, Toshio Inoue and Tomoyuki Kato, Design of an optimal controller for a discrete-time system subject to previewable demand, International Journal of Control 41(3), 1985, pages 677 to 699
- Shuuji Kajita, Hirohisa Hirukawa, Kensuke Harada and Kazuhito Yokoi, Introduction to Humanoid Robotics, Springer Tracts in Advanced Robotics 101, Springer, 2014, Chapter 4 (biped walking)
- 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
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 CQQDWX Edit this page History Report an error Markdown