Algorithmresearch
Hierarchical quadratic programming
Also called HQP, lexicographic quadratic programming.
Solves a stack of equality and inequality tasks in strict priority, each optimized without degrading the higher ones.
- Time
- O(i (n + m)^3) worst
- Space
- O((n + m)^2) extra
- Where
- i = the total number of active-set iterations over all levels; m = the number of task rows over all levels; n = the number of variables
- Model
- Real RAM
- Properties
- deterministicexactonlinenot randomized
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Oussama Kanoun, Florent Lamiraux, Pierre Brice Wieber, Adrien Escande, Nicolas Mansard, 2011
Hierarchical quadratic programming (HQP) finds the joint velocities, accelerations or torques of a robot that meet a stack of tasks in strict priority. Each level of the stack is a set of linear equalities and linear inequalities , such as "keep the center of mass over the feet", "keep each joint inside its limits" or "move the hand to the target". The solver minimizes the error of the first level, then the error of the second level among the points that keep the first error optimal, and so on. It is lexicographic optimization where every objective is a least-squares error, so every step is a quadratic program. With equalities only, it gives the same answer as the classic task-priority method with null-space projections; its gain is that inequalities can sit at any level. HQP is the solver inside much of whole-body control for humanoid and legged robots, and it applies in the same way to a fixed arm with redundant joints.
In plain words
A robot often has more wishes than it can meet at once: do not fall, do not hit the joint stops, reach the cup, keep the head level. Some wishes matter more than others. A weighted sum lets a minor wish pull a little on a major one. A strict order does not.
HQP handles the wishes in order. It meets the first group as well as it can. Then it looks at all the ways to do that equally well, and among them it picks the ones that meet the second group best. It goes on down the list. A wish that cannot be met is met as closely as possible, and the rest of the list still gets the freedom that is left.
The problem
Input. The number of variables , and levels. Level has a matrix and a vector (equality tasks), and a matrix and a vector (inequality tasks). Any of them may be empty. Arithmetic and square roots cost one step each, as in the real RAM.
Output. A vector such that, for each in order, the error
is the least possible among the points that keep at their optimal values. The maximum is taken in each component. The optimal residuals and violations are the same for every optimal (Lemma 2 of the proof), so the output also reports them.
How it differs from close pages. The task-priority method and the pseudoinverse method handle equalities only, in closed form. A weighted QP sums the levels with weights, which is one QP but gives only a soft priority. Goal programming also has priority levels but is usually linear. Convex MPC for legged robots is one weighted QP over a horizon, and whole-body control often runs HQP or a weighted QP at each control step.
The algorithm
The cascade of Kanoun, Lamiraux and Wieber solves one QP per level. After a level is solved, its optimal residuals become hard constraints for the lower levels.
HQP((A_k, b_k, C_k, d_k) for k = 1..p)- 1
x ← 0; E ← no rows (hard equalities); G ← no rows (hard inequalities); Z ← I - 2
for k ← 1 to p - 3
(y, v) ← argmin ½|A_k(x + Zy) - b_k|² + ½|v|² + ½ε|y|² s.t. G(x + Zy) ≤ g, C_k(x + Zy) - d_k ≤ v - 4
x ← x + Zy; w_k ← A_k x - b_k; v_k ← max(0, C_k x - d_k) - 5
add the rows A_k x = b_k + w_k to E, and each violated row C_k,i x = d_k,i + v_k,i to E - 6
add each other row C_k,i x ≤ d_k,i to G - 7
Z ← an orthonormal basis of the null space of E - 8
return x and (w_k, v_k) for k = 1..p
Line L3 is a QP in the slack form of Kanoun et al.: the slack measures how much each inequality is violated, and its square is in the objective. The current satisfies , so every point satisfies too, and the equalities drop out. The start , is feasible, and the code solves the QP with the primal active-set method (Nocedal and Wright, Chapter 16), keeping each step in least-squares form and solving it by modified Gram-Schmidt. The damping (here ) makes the QP strictly convex; the code also uses it to pick, among equal optima, the one closest to the previous . Line L5 turns a violated row into an equality, because every optimal point violates it by the same amount (Lemma 2 of the proof). In code, a violation below counts as no violation, since the damping alone can cause one, and the row then stays an inequality with its bound moved by that tiny amount. Line L7 uses Gram-Schmidt and drops rows of that depend on the others; they are consistent, because satisfies them all.
Example
Take and three levels: a joint limit ; a task ; a rest posture , .
Level 1: meets the limit, so , and the row becomes a hard inequality. Level 2: the task can be met exactly without passing the limit, so and the line becomes a hard equality, with . Level 3: on that line, the point closest to the origin is , but it breaks the limit. The best point on the line with is , with posture error . So : the limit holds, the task holds, and the posture gives way.
A weighted QP does not keep the order. Measured, with the inequality written as a squared violation and the same damping:
| Weights (limit, task, posture) | Limit violation | Task error | |
|---|---|---|---|
| 1, 1, 1 | (1.000, 1.000) | 0 | 1.000 |
| 100, 10, 1 | (1.008, 1.811) | 0.008 | 0.181 |
| 10000, 100, 1 | (1.0001, 1.980) | 0.0001 | 0.020 |
| HQP | (1, 2) | 0 | 0 |
The weighted answer approaches the HQP answer as the ratios of the weights grow, but it never reaches it, and large ratios make the QP badly conditioned.
Correctness
The proof shows, in exact arithmetic with and an exact QP solver, that the cascade returns a lexicographic optimum. Lemma 1: the slack QP of line L3 has the same optimal value as the minimum of over the set left by the higher levels. Lemma 2: all optimal points of a level have the same residual , violate the same rows by the same amounts , and satisfy the other rows; so the set kept by lines L5 to L7 is exactly the optimal set of the level. The theorem follows by induction over the levels. With , each level loses at most , where is an undamped optimum. The active-set method stops after finitely many steps on a strictly convex QP when no step cycles. The tests compare the code with brute force over the active rows on random stacks, with the level-by-level null-space solution on stacks of equalities, and with hand cases.
Proof: The cascade of QPs returns a lexicographic optimum of the task errorsfull
Line numbers refer to the pseudocode on the hierarchical quadratic programming page. The proof is in exact arithmetic, with , a threshold of 0 for violated rows and an exact solver for each QP; the last two paragraphs treat and the active-set solver.
For level , let . Let and . A lexicographic optimum is a point of . We show by induction that every is nonempty and that the set described by and after level is exactly .
Lemma 1 (the slack form). Let be a nonempty polyhedron. Then exists, and it equals the minimum of over the pairs with and . At an optimal pair, .
Proof. For a fixed , the least subject to is reached at in each component, because can be 0 when the bound is negative and must be at least the bound otherwise. So the two problems have the same values for each . The slack problem is a convex QP whose objective is bounded below by 0 on a nonempty polyhedron, so it attains its minimum (the Frank-Wolfe theorem for quadratic programs).
Lemma 2 (the optimal residuals are unique). Let be a nonempty polyhedron and . Then there are vectors and such that every has and . Moreover,
Proof. Let and for . is convex, so and is the constant . is a sum of convex functions of : the terms and . A sum of convex functions that is affine on an interval has every term affine there, since each term is at most its chord and the chords add up to the sum. The term is a quadratic in with leading coefficient , so it is affine only if . For an inequality row, let , an affine function. If and is not constant, then equals near , which is strictly convex there, so it is not affine. Hence if , then is constant and . Exchanging and : if , then . This proves the first claim.
For the set equality: the inclusion is the first claim. Conversely, a point of the right side has , the violated rows at and the other rows not violated, so , and .
Lemma 3 (the null-space step). Let be a matrix, a vector and a point with . Let the columns of be a basis of the null space of . Then , where is the number of columns of .
Proof. . Conversely, if , then , so is in the null space and equals for some . Rows of that are linear combinations of other rows do not change the null space, so line L7 may drop them.
Theorem (the cascade is correct). For each , after line L7 of iteration , and the current is in . At line L8, , and are the optimal residuals of level .
Proof. By induction on . Before the loop, and are empty, , and . Assume the claim for . By Lemma 3 with , the feasible set of line L3 in the variable is , a nonempty polyhedron. By Lemma 1, line L3 minimizes over , so the new of line L4 is in , and by Lemma 2 its and are the vectors and of that lemma. Lines L5 and L6 add exactly the equalities and inequalities of Lemma 2 to and , so the new set is , and the new satisfies it.
The damping. With , line L3 minimizes . Let minimize the undamped level problem and the damped one. Then , so the level loses at most . Such a loss can make a row look violated by a tiny amount, which is why the code uses a tolerance in line L5 and keeps such a row as an inequality with its bound moved by the tiny violation; the current still satisfies every hard row, so the next level starts feasible. The damped QP is strictly convex: its objective is with of full column rank, because contains for and for .
The active-set solver. The method of active_set_lsq starts from the feasible point , , and keeps a working set of linearly independent active rows: a row enters only when it blocks a step in the null space of the working set, and then its normal has a positive product with , so it is not a combination of the working rows. Each step solves the equality-constrained problem on the working set exactly. When the step is zero or full, the multipliers come from ; if all are nonnegative, the point satisfies the KKT conditions of a convex QP and is optimal; otherwise the row with the most negative multiplier leaves. For a strictly convex QP, this method terminates in a finite number of iterations when no step of length zero repeats a working set (Nocedal and Wright, Chapter 16). The code also stops after iterations with an error; the tests never reach that limit.
The tests check the theorem on random data: test_inequality_stacks_match_brute_force enumerates, at each level, every choice of active, violated and free rows, takes the best feasible candidate, and compares the residuals and the point with the cascade to and , on 40 random stacks of three levels in three variables. test_equality_stacks_match_the_null_space_cascade compares stacks of equalities with an independent level-by-level solution in the null space of the higher levels.
Complexity
- Time. Each active-set iteration of level has at most variables (the step and the slacks) and at most constraints; the code computes a null-space basis of the working set and a least-squares step by Gram-Schmidt, in time. The number of iterations is finite but has no useful polynomial bound in general; with a good start it is small. Measured: 4 levels of 6 equalities and 6 inequalities each, on 30 variables, take about 1.8 s in this pure Python code. Escande, Mansard and Wieber report that their dedicated solver handles a hierarchy of equalities about 10 times faster than the classic method, and inequality hierarchies at the control rates of humanoid robots.
- Space. for the matrices of one level QP.
Properties
- Strict priority. A lower level never changes the optimal residual of a higher level (the test
test_lower_levels_never_degrade_higher_levelschecks this on random stacks). - Feasibility is not required. An infeasible level is solved in the least-squares sense, and the lower levels still run.
- Equalities match the null-space method. With no inequalities, the result is the task-priority solution with pseudoinverses of the projected tasks.
- Continuity is not guaranteed. When a row of an inequality becomes active or inactive, the solution can change direction suddenly; damping and smooth task gains reduce this.
- Exact up to the damping. The result is a lexicographic optimum up to , not an approximation by weights.
Variants and improvements
- Dedicated hierarchical solvers. Escande, Mansard and Wieber solve all levels in one active-set loop with a complete orthogonal decomposition shared by the levels, instead of one separate QP per level.
- Weighted QP. One QP with large weight ratios. It is simpler and is used in many controllers for legged robots, at the price of a soft priority.
- Damped levels. Adding at each level, or a final level , picks a unique answer and limits large motions near singular tasks, as in damped least squares.
- Warm start. At a control rate of 1 kHz, the active set of the last step is a good first guess and usually needs few changes.
- Dynamics levels. In whole-body control, the first level holds the equations of motion and the contact constraints, so the solution is physically consistent before any task is considered.
When to use it
Use HQP when a redundant robot has tasks with a clear order of importance and some of them are inequalities: joint limits, friction cones, collision distances, balance limits. For a few equality tasks, the closed-form task-priority method is faster and simpler. When the order is not strict, or a solver for one QP is already in place, a weighted QP is often enough.
Pitfalls
- Singular tasks. Near a singular configuration of a task, the step in its null space can be large. Damp it, or put a regularization level at the bottom.
- Thresholds. The test for a violated row needs a tolerance. A tiny violation caused by roundoff, made into an equality, removes freedom that the lower levels need.
- Feasible start. Each level QP needs a feasible start. The previous with is one; a start that breaks a hard row of a higher level is not.
- Too many levels. Each level costs a QP. Group tasks of the same importance into one level instead of giving each its own.
- Inconsistent units. Tasks in meters and radians on the same level are weighted by their units. Scale them before you put them together.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hierarchical-quadratic-programming/. The authors are listed in prov/7BEBTS.jsonl.
"""Hierarchical quadratic programming: a cascade of least-squares problems in strict priority.
A level k has equality tasks A_k x = b_k and inequality tasks C_k x <= d_k. Level 1 has
the highest priority. The solver finds the x that minimizes, in lexicographic order,
(1/2) |A_k x - b_k|^2 + (1/2) |max(0, C_k x - d_k)|^2, k = 1, 2, ..., p.
It solves one QP per level (the cascade of Kanoun, Lamiraux and Wieber 2011). Each level
keeps the optimal residuals of the higher levels fixed: the equality rows become hard
equalities with their optimal residual, the violated inequality rows become hard
equalities at their optimal violation, and the other inequality rows stay hard
inequalities. The equalities are removed by moving in their null space, x = x_prev + Z y,
and each level QP is solved by a primal active-set method from a feasible start.
A tiny damping eps |y|^2 makes each level QP strictly convex; it changes the optimal
residuals by O(eps) at most. Every QP is kept in least-squares form, (1/2)|F u - f|^2,
and each step is a least-squares solve by modified Gram-Schmidt, so the damping does
not square the condition number. Python standard library only.
"""
import math
TOL = 1e-10
def dot(a, b):
return sum(x * y for x, y in zip(a, b))
def null_space(rows, n):
"""Orthonormal basis (a list of vectors) of the null space of the given rows in R^n."""
q = []
for r in rows:
v = list(r)
for _ in range(2):
for b in q:
c = dot(v, b)
v = [v[i] - c * b[i] for i in range(n)]
nv = math.sqrt(dot(v, v))
if nv > 1e-9 * (1.0 + math.sqrt(dot(r, r))):
q.append([x / nv for x in v])
z = []
for j in range(n):
if len(q) + len(z) == n:
break
v = [1.0 if i == j else 0.0 for i in range(n)]
for _ in range(2):
for b in q + z:
c = dot(v, b)
v = [v[i] - c * b[i] for i in range(n)]
nv = math.sqrt(dot(v, v))
if nv > 1e-6:
z.append([x / nv for x in v])
return z
def least_squares(cols, rhs):
"""min |sum_j s_j cols[j] - rhs| by modified Gram-Schmidt on [cols | rhs]. Columns must be independent."""
k = len(cols)
q, rr = [], [[0.0] * k for _ in range(k)]
for j in range(k):
v = list(cols[j])
for i in range(j):
rr[i][j] = dot(q[i], v)
v = [v[t] - rr[i][j] * q[i][t] for t in range(len(v))]
rr[j][j] = math.sqrt(dot(v, v))
if rr[j][j] == 0.0:
raise ValueError("dependent columns")
q.append([x / rr[j][j] for x in v])
r = list(rhs)
zz = []
for i in range(k):
c = dot(q[i], r)
zz.append(c)
r = [r[t] - c * q[i][t] for t in range(len(r))]
s = [0.0] * k
for i in range(k - 1, -1, -1):
s[i] = (zz[i] - sum(rr[i][j] * s[j] for j in range(i + 1, k))) / rr[i][i]
return s
def solve_spd(a, b):
"""Solve a small symmetric positive definite system by Gaussian elimination with pivoting."""
n = len(a)
m = [list(a[i]) + [b[i]] for i in range(n)]
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 c in range(n - 1, -1, -1):
x[c] = (m[c][n] - sum(m[c][j] * x[j] for j in range(c + 1, n))) / m[c][c]
return x
def active_set_lsq(fm, f, a_in, b_in, u0, max_iter=None):
"""Minimize (1/2)|F u - f|^2 subject to a_in u <= b_in, from a feasible u0.
F must have full column rank, so the objective is strictly convex. This is the primal
active-set method of Nocedal and Wright (Algorithm 16.3); the working set W holds
linearly independent active rows. Returns (u, W, multipliers of W).
"""
n = len(u0)
m = len(a_in)
u = list(u0)
work = []
if max_iter is None:
max_iter = 50 * (n + m) + 50
for _ in range(max_iter):
# Step p: minimize |F (u + p) - f| with a_i . p = 0 for i in W, as p = N s.
basis = null_space([a_in[j] for j in work], n)
resid = [f[i] - dot(fm[i], u) for i in range(len(fm))]
cols = [[dot(row, col) for row in fm] for col in basis]
s = least_squares(cols, resid) if basis else []
p = [sum(s[j] * basis[j][i] for j in range(len(basis))) for i in range(n)]
block = None
if p and max(abs(x) for x in p) > TOL * (1.0 + max(abs(x) for x in u)):
alpha = 1.0
for j in range(m):
if j in work:
continue
ap = dot(a_in[j], p)
if ap > TOL:
t = (b_in[j] - dot(a_in[j], u)) / ap
if t < alpha:
alpha, block = max(t, 0.0), j
u = [u[i] + alpha * p[i] for i in range(n)]
if block is not None:
work.append(block)
continue
# u minimizes the objective on the working set; its multipliers solve A_W^T lam = -grad.
if not work:
return u, work, []
r2 = [dot(fm[i], u) - f[i] for i in range(len(fm))]
grad = [sum(fm[t][i] * r2[t] for t in range(len(fm))) for i in range(n)]
aw = [a_in[j] for j in work]
lam = solve_spd([[dot(x, y) for y in aw] for x in aw], [-dot(x, grad) for x in aw])
if min(lam) >= -1e-9 * (1.0 + max(abs(x) for x in lam)):
return u, work, lam
work.pop(min(range(len(work)), key=lambda i: lam[i]))
raise RuntimeError("active-set method did not converge")
def solve_hqp(levels, n, eps=1e-9, tau=1e-6):
"""Solve a stack of levels. Each level is a dict with optional keys A, b, C, d.
Returns (x, residuals) with residuals[k] = (w_k, v_k): w_k = A_k x - b_k and
v_k = max(0, C_k x - d_k), the optimal residuals of level k.
An inequality row counts as violated when its optimal violation exceeds
tau (1 + |d|); smaller violations come from the damping, and the row then stays an
inequality with its bound moved by the violation, so the current x stays feasible.
"""
x = [0.0] * n # @line L1
eq_rows, eq_rhs = [], []
in_rows, in_rhs = [], []
z = null_space([], n)
se = math.sqrt(eps)
out = []
for lev in levels: # @line L2
a, b = lev.get("A", []), lev.get("b", [])
c, d = lev.get("C", []), lev.get("d", [])
r, mc = len(z), len(c)
if r > 0:
# Level QP in u = (y, v): x = x_prev + Z y, and v >= C x - d is the slack of each inequality.
fm, f = [], []
for i in range(len(a)):
fm.append([dot(a[i], col) for col in z] + [0.0] * mc)
f.append(b[i] - dot(a[i], x))
for i in range(mc):
fm.append([0.0] * r + [1.0 if j == i else 0.0 for j in range(mc)])
f.append(0.0)
for i in range(r):
fm.append([se if j == i else 0.0 for j in range(r)] + [0.0] * mc)
f.append(0.0)
a_in, b_in = [], []
for row, rhs in zip(in_rows, in_rhs):
a_in.append([dot(row, col) for col in z] + [0.0] * mc)
b_in.append(rhs - dot(row, x))
for i in range(mc):
a_in.append([dot(c[i], col) for col in z] + [-1.0 if j == i else 0.0 for j in range(mc)])
b_in.append(d[i] - dot(c[i], x))
u0 = [0.0] * r + [max(0.0, dot(c[i], x) - d[i]) for i in range(mc)]
u, _, _ = active_set_lsq(fm, f, a_in, b_in, u0) # @line L3
y = u[:r]
x = [x[i] + sum(z[j][i] * y[j] for j in range(r)) for i in range(n)] # @line L4
w = [dot(a[i], x) - b[i] for i in range(len(a))] # @line L4
v = [max(0.0, dot(c[i], x) - d[i]) for i in range(mc)] # @line L4
out.append((w, v))
for i in range(len(a)): # @line L5
eq_rows.append(a[i])
eq_rhs.append(b[i] + w[i])
for i in range(mc):
if v[i] > tau * (1.0 + abs(d[i])):
eq_rows.append(c[i]) # @line L5
eq_rhs.append(d[i] + v[i])
else:
in_rows.append(c[i]) # @line L6
in_rhs.append(d[i] + v[i])
z = null_space(eq_rows, n) # @line L7
return x, out # @line L8
def weighted_qp(levels, n, weights, eps=1e-9):
"""The soft alternative: one QP with the levels summed with weights. For comparison only."""
fm, f, cons, cb = [], [], [], []
ineq = []
for lev, wt in zip(levels, weights):
s = math.sqrt(wt)
for row, bb in zip(lev.get("A", []), lev.get("b", [])):
fm.append([s * t for t in row])
f.append(s * bb)
for row, dd in zip(lev.get("C", []), lev.get("d", [])):
ineq.append(([s * t for t in row], s * dd))
m = len(ineq)
fm = [row + [0.0] * m for row in fm]
for k in range(m):
fm.append([0.0] * n + [1.0 if j == k else 0.0 for j in range(m)])
f.append(0.0)
for i in range(n):
fm.append([math.sqrt(eps) if j == i else 0.0 for j in range(n)] + [0.0] * m)
f.append(0.0)
for k, (row, dd) in enumerate(ineq):
cons.append(row + [-1.0 if j == k else 0.0 for j in range(m)])
cb.append(dd)
u0 = [0.0] * n + [max(0.0, -cb[k]) for k in range(m)]
u, _, _ = active_set_lsq(fm, f, cons, cb, u0)
return u[:n]
test_hierarchical_quadratic_programming.py 241 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hierarchical-quadratic-programming/. The authors are listed in prov/7BEBTS.jsonl.
import itertools
import math
import random
from hierarchical_quadratic_programming import active_set_lsq, solve_hqp, weighted_qp
def close(a, b, tol):
return all(abs(x - y) <= tol for x, y in zip(a, b))
def gauss(a, b):
"""Plain Gaussian elimination with partial pivoting; None if singular."""
n = len(a)
m = [list(a[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[p][c]) < 1e-11:
return None
m[c], m[p] = m[p], m[c]
for r in range(n):
if r != c:
f = m[r][c] / m[c][c]
for j in range(c, n + 1):
m[r][j] -= f * m[c][j]
return [m[i][n] / m[i][i] for i in range(n)]
def norm2(v):
return sum(x * x for x in v)
def test_strict_priority_on_one_variable():
# Level 1: x <= 1. Level 2: x = 3. The higher level wins.
x, res = solve_hqp([{"C": [[1.0]], "d": [1.0]}, {"A": [[1.0]], "b": [3.0]}], 1)
assert abs(x[0] - 1.0) < 1e-9
assert res[0][1] == [0.0] and abs(res[1][0][0] + 2.0) < 1e-9
# Swap the levels: now x = 3 and the inequality is violated by 2.
x, res = solve_hqp([{"A": [[1.0]], "b": [3.0]}, {"C": [[1.0]], "d": [1.0]}], 1)
assert abs(x[0] - 3.0) < 1e-7
assert abs(res[1][1][0] - 2.0) < 1e-7
def test_infeasible_level_is_solved_in_least_squares():
# Level 1 asks x >= 2 and x <= 1: the best compromise is 1.5. Level 2 (x = 0) cannot move it.
lv1 = {"C": [[-1.0], [1.0]], "d": [-2.0, 1.0]}
x, res = solve_hqp([lv1, {"A": [[1.0]], "b": [0.0]}], 1)
assert abs(x[0] - 1.5) < 1e-8
assert close(res[0][1], [0.5, 0.5], 1e-8)
assert abs(res[1][0][0] - 1.5) < 1e-8
def test_page_example():
# Level 1: x1 <= 1. Level 2: x1 + x2 = 3. Level 3: x1 = 0 and x2 = 0.
levels = [
{"C": [[1.0, 0.0]], "d": [1.0]},
{"A": [[1.0, 1.0]], "b": [3.0]},
{"A": [[1.0, 0.0], [0.0, 1.0]], "b": [0.0, 0.0]},
]
x, res = solve_hqp(levels, 2)
assert close(x, [1.0, 2.0], 1e-8)
assert abs(res[1][0][0]) < 1e-8
assert close(res[2][0], [1.0, 2.0], 1e-8)
# The weighted QP with weights 100, 10, 1 trades the levels against each other.
xw = weighted_qp(levels, 2, [100.0, 10.0, 1.0])
assert abs(xw[0] + xw[1] - 3.0) > 1e-2
def test_active_set_qp_against_vertex_enumeration():
# min (1/2)|u - c|^2 over a random polygon given by m half-planes, n = 2.
rng = random.Random(5)
for _ in range(60):
m = rng.randint(3, 6)
rows, rhs = [], []
for _ in range(m):
t = rng.uniform(0, 2 * math.pi)
rows.append([math.cos(t), math.sin(t)])
rhs.append(rng.uniform(0.2, 1.5)) # u = 0 is feasible
c = [rng.uniform(-3, 3), rng.uniform(-3, 3)]
u, _, _ = active_set_lsq([[1.0, 0.0], [0.0, 1.0]], c, rows, rhs, [0.0, 0.0])
best = None
cands = [c]
for i in range(m):
a, b = rows[i], rhs[i]
s = (sum(a[j] * c[j] for j in range(2)) - b)
cands.append([c[j] - s * a[j] for j in range(2)])
for k in range(i + 1, m):
p = gauss([rows[i], rows[k]], [rhs[i], rhs[k]])
if p is not None:
cands.append(p)
for p in cands:
if all(sum(r[j] * p[j] for j in range(2)) <= bb + 1e-9 for r, bb in zip(rows, rhs)):
val = norm2([p[j] - c[j] for j in range(2)])
if best is None or val < best:
best = val
assert abs(norm2([u[j] - c[j] for j in range(2)]) - best) < 1e-9
def null_space_cascade(levels, n):
"""Reference for equality-only stacks: solve the levels one by one in the null space of the higher levels."""
x = [0.0] * n
z = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)] # columns
for lev in levels:
a, b = lev["A"], lev["b"]
r = len(z)
if r == 0:
break
m = [[sum(row[i] * col[i] for i in range(n)) for col in z] for row in a]
res = [b[i] - sum(a[i][j] * x[j] for j in range(n)) for i in range(len(a))]
if len(a) >= r: # full column rank: normal equations
y = gauss([[sum(m[t][i] * m[t][j] for t in range(len(a))) for j in range(r)] for i in range(r)],
[sum(m[t][i] * res[t] for t in range(len(a))) for i in range(r)])
else: # full row rank: the minimum-norm solution
lam = gauss([[sum(m[i][t] * m[j][t] for t in range(r)) for j in range(len(a))] for i in range(len(a))], res)
y = [sum(m[t][i] * lam[t] for t in range(len(a))) for i in range(r)]
x = [x[i] + sum(z[j][i] * y[j] for j in range(r)) for i in range(n)]
# New basis: the null space of m in y coordinates, mapped back by z.
basis = []
for row in m:
v = list(row)
for q in basis:
c = sum(v[i] * q[i] for i in range(r))
v = [v[i] - c * q[i] for i in range(r)]
nv = math.sqrt(norm2(v))
if nv > 1e-9:
basis.append([t / nv for t in v])
nb = []
for j in range(r):
v = [1.0 if i == j else 0.0 for i in range(r)]
for q in basis + nb:
c = sum(v[i] * q[i] for i in range(r))
v = [v[i] - c * q[i] for i in range(r)]
nv = math.sqrt(norm2(v))
if nv > 1e-6 and len(basis) + len(nb) < r:
nb.append([t / nv for t in v])
z = [[sum(z[k][i] * q[k] for k in range(r)) for i in range(n)] for q in nb]
return x
def test_equality_stacks_match_the_null_space_cascade():
rng = random.Random(6)
for sizes, n in [((2, 2, 1), 6), ((1, 3), 3), ((2, 3, 2), 4), ((3, 3), 4)]:
for _ in range(10):
levels = [{"A": [[rng.gauss(0, 1) for _ in range(n)] for _ in range(k)],
"b": [rng.gauss(0, 1) for _ in range(k)]} for k in sizes]
x, res = solve_hqp(levels, n, eps=1e-12)
want = null_space_cascade(levels, n)
assert close(x, want, 1e-6)
def brute_force_hqp(levels, n, eps):
"""Level by level, enumerate which inequality rows are active, violated or free.
Uses the slack form of Kanoun et al.: the rows of higher levels stay A x = b + w* and
C x <= d + v*. Every candidate is the minimizer of a quadratic on an affine set; the
best feasible candidate is the optimum of the damped level problem.
"""
x_prev = [0.0] * n
eq, ineq = [], []
out = []
for lev in levels:
a, b = lev.get("A", []), lev.get("b", [])
c, d = lev.get("C", []), lev.get("d", [])
def f(x):
r = [sum(a[i][j] * x[j] for j in range(n)) - b[i] for i in range(len(a))]
s = [max(0.0, sum(c[i][j] * x[j] for j in range(n)) - d[i]) for i in range(len(c))]
return 0.5 * norm2(r) + 0.5 * norm2(s) + 0.5 * eps * norm2([x[i] - x_prev[i] for i in range(n)])
best = None
for hard_on in itertools.product((0, 1), repeat=len(ineq)):
for own in itertools.product((0, 1, 2), repeat=len(c)): # 0 free, 1 active, 2 violated
obj = [(row, rhs) for row, rhs in zip(a, b)]
obj += [(c[i], d[i]) for i in range(len(c)) if own[i] == 2]
cons = list(eq) + [ineq[i] for i in range(len(ineq)) if hard_on[i]]
cons += [(c[i], d[i]) for i in range(len(c)) if own[i] == 1]
if len(cons) > n:
continue
k = len(cons)
kkt = [[sum(r[i] * r[j] for r, _ in obj) + (eps if i == j else 0.0) for j in range(n)]
+ [cons[t][0][i] for t in range(k)] for i in range(n)]
kkt += [list(cons[t][0]) + [0.0] * k for t in range(k)]
rhs = [sum(r[i] * q for r, q in obj) + eps * x_prev[i] for i in range(n)] + [q for _, q in cons]
sol = gauss(kkt, rhs)
if sol is None:
continue
x = sol[:n]
if any(abs(sum(r[j] * x[j] for j in range(n)) - q) > 1e-7 for r, q in eq):
continue
if any(sum(r[j] * x[j] for j in range(n)) > q + 1e-9 for r, q in ineq):
continue
val = f(x)
if best is None or val < best[0]:
best = (val, x)
x = best[1]
w = [sum(a[i][j] * x[j] for j in range(n)) - b[i] for i in range(len(a))]
v = [max(0.0, sum(c[i][j] * x[j] for j in range(n)) - d[i]) for i in range(len(c))]
eq += [(a[i], b[i] + w[i]) for i in range(len(a))]
ineq += [(c[i], d[i] + v[i]) for i in range(len(c))]
out.append((w, v))
x_prev = x
return x_prev, out
def test_inequality_stacks_match_brute_force():
rng = random.Random(7)
n = 3
for trial in range(40):
levels = []
for k in range(3):
ne = rng.choice([0, 1]) if k < 2 else rng.choice([1, 2])
ni = rng.choice([1, 2])
levels.append({
"A": [[rng.gauss(0, 1) for _ in range(n)] for _ in range(ne)],
"b": [rng.gauss(0, 1) for _ in range(ne)],
"C": [[rng.gauss(0, 1) for _ in range(n)] for _ in range(ni)],
"d": [rng.gauss(0, 1) for _ in range(ni)],
})
x, res = solve_hqp(levels, n, eps=1e-9)
xb, resb = brute_force_hqp(levels, n, 1e-9)
for (w, v), (wb, vb) in zip(res, resb):
assert abs(norm2(w) + norm2(v) - norm2(wb) - norm2(vb)) < 1e-6
assert close(x, xb, 1e-5)
def test_lower_levels_never_degrade_higher_levels():
# Adding a level at the bottom does not change the optimal residuals of the levels above it.
rng = random.Random(8)
n = 4
for _ in range(20):
levels = [{"A": [[rng.gauss(0, 1) for _ in range(n)]], "b": [rng.gauss(0, 1)],
"C": [[rng.gauss(0, 1) for _ in range(n)] for _ in range(2)],
"d": [rng.gauss(0, 1) for _ in range(2)]} for _ in range(3)]
_, res3 = solve_hqp(levels, n)
extra = {"A": [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)], "b": [rng.gauss(0, 3) for _ in range(n)]}
_, res4 = solve_hqp(levels + [extra], n)
for (w, v), (w2, v2) in zip(res3, res4):
assert abs(norm2(w) + norm2(v) - norm2(w2) - norm2(v2)) < 1e-7
History
Task priorities for redundant robots go back to Nakamura, Hanafusa and Yoshikawa in 1987 and to Siciliano and Slotine in 1991, who solved each task in the null space of the higher ones with pseudoinverses. Sentis and Khatib built whole-body behaviors for humanoid robots on prioritized tasks in 2005. Inequalities did not fit this scheme: they were handled by weights or by switching. Kanoun, Lamiraux and Wieber showed in 2011 that a cascade of QPs, one per level with the higher levels fixed at their optimal slacks, puts an inequality at any priority level. Escande, Mansard and Wieber gave a solver for the whole hierarchy in 2014, fast enough for the control loop of a humanoid robot.
References
- Kinematic control of redundant manipulators: generalizing the task-priority framework to inequality task, the whole paper (one QP per priority level, with slack variables, and the higher levels fixed at their optimal slacks)
- Hierarchical quadratic programming: fast online humanoid-robot motion generation, the whole paper (the hierarchical active-set solver and the speed comparison with the cascade of QPs)
- Numerical Optimization (second edition), Chapter 16 (the active-set method for convex quadratic programs)
- Synthesis of whole-body behaviors through hierarchical control of behavioral primitives, the whole paper (task priorities for a humanoid robot, with equality tasks in null spaces)
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 7BEBTS Edit this page History Report an error Markdown