Algorithm Search⌘K

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
Properties
deterministicexactonlinenot randomized
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 Akx=bkA_kx = b_k and linear inequalities Ckx≤dkC_kx \le d_k, 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 nn, and pp levels. Level kk has a matrix AkA_k and a vector bkb_k (equality tasks), and a matrix CkC_k and a vector dkd_k (inequality tasks). Any of them may be empty. Arithmetic and square roots cost one step each, as in the real RAM.

Output. A vector xx such that, for each kk in order, the error

fk(x)=12∥Akx−bk∥2+12∥max⁡(0,Ckx−dk)∥2f_k(x) = \tfrac12\|A_kx - b_k\|^2 + \tfrac12\|\max(0, C_kx - d_k)\|^2

is the least possible among the points that keep f1,…,fk−1f_1, \dots, f_{k-1} at their optimal values. The maximum is taken in each component. The optimal residuals wk=Akx−bkw_k = A_kx - b_k and violations vk=max⁡(0,Ckx−dk)v_k = \max(0, C_kx - d_k) are the same for every optimal xx (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.

  1. HQP((A_k, b_k, C_k, d_k) for k = 1..p)
  2. 1x ← 0; E ← no rows (hard equalities); G ← no rows (hard inequalities); Z ← I
  3. 2for k ← 1 to p
  4. 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
  5. 4x ← x + Zy; w_k ← A_k x - b_k; v_k ← max(0, C_k x - d_k)
  6. 5add 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
  7. 6add each other row C_k,i x ≤ d_k,i to G
  8. 7Z ← an orthonormal basis of the null space of E
  9. 8return 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 vv measures how much each inequality is violated, and its square is in the objective. The current xx satisfies EE, so every point x+Zyx + Zy satisfies EE too, and the equalities drop out. The start y=0y = 0, v=max⁡(0,Ckx−dk)v = \max(0, C_kx - d_k) 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 ε\varepsilon (here 10−910^{-9}) makes the QP strictly convex; the code also uses it to pick, among equal optima, the one closest to the previous xx. 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 10−6(1+∣dk,i∣)10^{-6}(1 + |d_{k,i}|) 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 EE that depend on the others; they are consistent, because xx satisfies them all.

Example

Take x=(x1,x2)x = (x_1, x_2) and three levels: a joint limit x1≤1x_1 \le 1; a task x1+x2=3x_1 + x_2 = 3; a rest posture x1=0x_1 = 0, x2=0x_2 = 0.

Level 1: x=0x = 0 meets the limit, so v1=0v_1 = 0, and the row becomes a hard inequality. Level 2: the task can be met exactly without passing the limit, so w2=0w_2 = 0 and the line x1+x2=3x_1 + x_2 = 3 becomes a hard equality, with Z=(1,−1)/2Z = (1, -1)/\sqrt2. Level 3: on that line, the point closest to the origin is (1.5,1.5)(1.5, 1.5), but it breaks the limit. The best point on the line with x1≤1x_1 \le 1 is (1,2)(1, 2), with posture error w3=(1,2)w_3 = (1, 2). So x=(1,2)x = (1, 2): 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) xx 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 ε=0\varepsilon = 0 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 fkf_k over the set left by the higher levels. Lemma 2: all optimal points of a level have the same residual wkw_k, violate the same rows by the same amounts vkv_k, 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 ε>0\varepsilon > 0, each level loses at most 12ε∥y∗∥2\tfrac12\varepsilon\|y^*\|^2, where y∗y^* 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 ε=0\varepsilon = 0, a threshold of 0 for violated rows and an exact solver for each QP; the last two paragraphs treat ε>0\varepsilon > 0 and the active-set solver.

For level kk, let fk(x)=12∥Akx−bk∥2+12∥max⁡(0,Ckx−dk)∥2f_k(x) = \tfrac12\|A_kx - b_k\|^2 + \tfrac12\|\max(0, C_kx - d_k)\|^2. Let S0=RnS_0 = \mathbb{R}^n and Sk=argmin⁡{fk(x):x∈Sk−1}S_k = \operatorname{argmin}\{f_k(x) : x \in S_{k-1}\}. A lexicographic optimum is a point of SpS_p. We show by induction that every SkS_k is nonempty and that the set described by EE and GG after level kk is exactly SkS_k.

Lemma 1 (the slack form). Let PP be a nonempty polyhedron. Then min⁡{fk(x):x∈P}\min\{f_k(x) : x \in P\} exists, and it equals the minimum of 12∥Akx−bk∥2+12∥v∥2\tfrac12\|A_kx - b_k\|^2 + \tfrac12\|v\|^2 over the pairs (x,v)(x, v) with x∈Px \in P and Ckx−dk≤vC_kx - d_k \le v. At an optimal pair, v=max⁡(0,Ckx−dk)v = \max(0, C_kx - d_k).

Proof. For a fixed xx, the least ∥v∥2\|v\|^2 subject to v≥Ckx−dkv \ge C_kx - d_k is reached at vi=max⁡(0,(Ckx−dk)i)v_i = \max(0, (C_kx - d_k)_i) in each component, because viv_i 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 xx. 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). □\square

Lemma 2 (the optimal residuals are unique). Let PP be a nonempty polyhedron and S=argmin⁡{fk(x):x∈P}S = \operatorname{argmin}\{f_k(x) : x \in P\}. Then there are vectors w∗w^* and v∗≥0v^* \ge 0 such that every x∈Sx \in S has Akx−bk=w∗A_kx - b_k = w^* and max⁡(0,Ckx−dk)=v∗\max(0, C_kx - d_k) = v^*. Moreover,

S={x∈P:Akx=bk+w∗, Ck,ix=dk,i+vi∗ for vi∗>0, Ck,ix≤dk,i for vi∗=0}.S = \{x \in P : A_kx = b_k + w^*,\ C_{k,i}x = d_{k,i} + v^*_i \text{ for } v^*_i > 0,\ C_{k,i}x \le d_{k,i} \text{ for } v^*_i = 0\}.

Proof. Let x1,x2∈Sx_1, x_2 \in S and x(t)=(1−t)x1+tx2x(t) = (1 - t)x_1 + tx_2 for t∈[0,1]t \in [0, 1]. SS is convex, so x(t)∈Sx(t) \in S and fk(x(t))f_k(x(t)) is the constant f∗f^*. fkf_k is a sum of convex functions of tt: the terms 12(ai⋅x(t)−bi)2\tfrac12(a_i\cdot x(t) - b_i)^2 and 12max⁡(0,ci⋅x(t)−di)2\tfrac12\max(0, c_i\cdot x(t) - d_i)^2. 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 12(ai⋅x(t)−bi)2\tfrac12(a_i\cdot x(t) - b_i)^2 is a quadratic in tt with leading coefficient 12(ai⋅(x2−x1))2\tfrac12(a_i\cdot(x_2 - x_1))^2, so it is affine only if ai⋅x1=ai⋅x2a_i\cdot x_1 = a_i\cdot x_2. For an inequality row, let s(t)=ci⋅x(t)−dis(t) = c_i\cdot x(t) - d_i, an affine function. If s(0)>0s(0) > 0 and ss is not constant, then 12max⁡(0,s)2\tfrac12\max(0, s)^2 equals 12s2\tfrac12 s^2 near t=0t = 0, which is strictly convex there, so it is not affine. Hence if ci⋅x1>dic_i\cdot x_1 > d_i, then ss is constant and ci⋅x2=ci⋅x1c_i\cdot x_2 = c_i\cdot x_1. Exchanging x1x_1 and x2x_2: if ci⋅x1≤dic_i\cdot x_1 \le d_i, then ci⋅x2≤dic_i\cdot x_2 \le d_i. This proves the first claim.

For the set equality: the inclusion ⊆\subseteq is the first claim. Conversely, a point x∈Px \in P of the right side has Akx−bk=w∗A_kx - b_k = w^*, the violated rows at vi∗v^*_i and the other rows not violated, so fk(x)=12∥w∗∥2+12∥v∗∥2=f∗f_k(x) = \tfrac12\|w^*\|^2 + \tfrac12\|v^*\|^2 = f^*, and x∈Sx \in S. □\square

Lemma 3 (the null-space step). Let EE be a matrix, ee a vector and x0x_0 a point with Ex0=eEx_0 = e. Let the columns of ZZ be a basis of the null space of EE. Then {x:Ex=e}={x0+Zy:y∈Rr}\{x : Ex = e\} = \{x_0 + Zy : y \in \mathbb{R}^{r}\}, where rr is the number of columns of ZZ.

Proof. E(x0+Zy)=eE(x_0 + Zy) = e. Conversely, if Ex=eEx = e, then E(x−x0)=0E(x - x_0) = 0, so x−x0x - x_0 is in the null space and equals ZyZy for some yy. Rows of EE that are linear combinations of other rows do not change the null space, so line L7 may drop them. □\square

Theorem (the cascade is correct). For each kk, after line L7 of iteration kk, Sk={x:Ex=e, Gx≤g}S_k = \{x : Ex = e,\ Gx \le g\} and the current xx is in SkS_k. At line L8, x∈Spx \in S_p, and (wk,vk)(w_k, v_k) are the optimal residuals of level kk.

Proof. By induction on kk. Before the loop, EE and GG are empty, S0=RnS_0 = \mathbb{R}^n, and x=0∈S0x = 0 \in S_0. Assume the claim for k−1k - 1. By Lemma 3 with x0=xx_0 = x, the feasible set of line L3 in the variable x+Zyx + Zy is {x′:Ex′=e,Gx′≤g}=Sk−1\{x' : Ex' = e, Gx' \le g\} = S_{k-1}, a nonempty polyhedron. By Lemma 1, line L3 minimizes fkf_k over Sk−1S_{k-1}, so the new xx of line L4 is in SkS_k, and by Lemma 2 its wkw_k and vkv_k are the vectors w∗w^* and v∗v^* of that lemma. Lines L5 and L6 add exactly the equalities and inequalities of Lemma 2 to EE and GG, so the new set is SkS_k, and the new xx satisfies it. □\square

The damping. With ε>0\varepsilon > 0, line L3 minimizes fk(x+Zy)+12ε∥y∥2f_k(x + Zy) + \tfrac12\varepsilon\|y\|^2. Let y∗y^* minimize the undamped level problem and yεy_\varepsilon the damped one. Then fk(x+Zyε)≤fk(x+Zyε)+12ε∥yε∥2≤fk(x+Zy∗)+12ε∥y∗∥2f_k(x + Zy_\varepsilon) \le f_k(x + Zy_\varepsilon) + \tfrac12\varepsilon\|y_\varepsilon\|^2 \le f_k(x + Zy^*) + \tfrac12\varepsilon\|y^*\|^2, so the level loses at most 12ε∥y∗∥2\tfrac12\varepsilon\|y^*\|^2. 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 xx still satisfies every hard row, so the next level starts feasible. The damped QP is strictly convex: its objective is 12∥Fu−f∥2\tfrac12\|Fu - f\|^2 with FF of full column rank, because FF contains εI\sqrt\varepsilon I for yy and II for vv.

The active-set solver. The method of active_set_lsq starts from the feasible point y=0y = 0, v=max⁡(0,Ckx−dk)v = \max(0, C_kx - d_k), and keeps a working set of linearly independent active rows: a row enters only when it blocks a step pp in the null space of the working set, and then its normal has a positive product with pp, 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 AWTλ=−∇A_W^T\lambda = -\nabla; 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 50(n+m)+5050(n + m) + 50 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 10−610^{-6} and 10−510^{-5}, 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 kk has at most n+mn + m variables (the step yy and the slacks) and at most mm constraints; the code computes a null-space basis of the working set and a least-squares step by Gram-Schmidt, in O((n+m)3)O((n + m)^3) 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. O((n+m)2)O((n + m)^2) 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_levels checks 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 O(ε)O(\varepsilon), 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 ε∥x∥2\varepsilon\|x\|^2 at each level, or a final level x=0x = 0, 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 xx with v=max⁡(0,Cx−d)v = \max(0, Cx - d) 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.

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

  1. 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)
  2. 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)
  3. Numerical Optimization (second edition), Chapter 16 (the active-set method for convex quadratic programs)
  4. 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.

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