Algorithm Search⌘K

Algorithmadvanced

Task-priority inverse kinematics

Also called prioritized inverse kinematics.

Nakamura's method that solves a stack of tasks, each lower task in the null space of the higher ones.

Time
Θ(k n^2 m) worst
Space
Θ(n^2 + m n) extra
Where
k = the number of iterations; m = the total number of task coordinates over all levels; n = the number of joints
Properties
deterministicofflineiterative
Origin
Yoshihiko Nakamura, Hideo Hanafusa, Tsuneo Yoshikawa, 1987

Task-priority inverse kinematics moves a redundant arm so that it meets several tasks with a strict order of importance. The first task is met as well as possible. The second task is then met as well as possible with joint motions that do not change the first task, which are the motions in the null space of the first Jacobian. Each further task uses only the motions left over by all tasks above it. For two tasks, the joint step is Δθ=J1+e1+(J2P1)+(e2−J2J1+e1)\Delta\theta = J_1^{+}e_1 + (J_2P_1)^{+}(e_2 - J_2J_1^{+}e_1) with the null space projector P1=I−J1+J1P_1 = I - J_1^{+}J_1. Repeating such steps solves the tasks at the position level.

In plain words

An arm with more joints than it needs for a job can do the job in many ways. You can use the spare freedom for a second wish, such as keeping the elbow away from a wall. But the wishes may conflict, and then you must say which one wins. This method puts the wishes in a list, most important first. It first finds the joint motion that best serves the first wish. Then, among all the motions that leave the first wish exactly as served, it picks the one that best serves the second wish, and so on down the list. A lower wish can never spoil a higher one. When a lower wish cannot be met, the arm gets as close to it as the higher wishes allow.

The problem

Input.

  • An arm with nn joints and pp tasks xi=fi(θ)x_i = f_i(\theta) with Jacobians Ji(θ)J_i(\theta) of size mi×nm_i \times n, ordered from the highest priority i=1i = 1 to the lowest i=pi = p.
  • The task errors ei=xi,d−fi(θ)e_i = x_{i,d} - f_i(\theta) at the present configuration, for one step. For the iteration, also the targets xi,dx_{i,d}, an initial guess θ0\theta^0 and a stopping rule.

Output of one step. The joint step Δθ\Delta\theta defined level by level. Level 1 keeps the Δθ\Delta\theta that minimize ∣J1Δθ−e1∣|J_1\Delta\theta - e_1|. Level ii keeps, among the steps kept at level i−1i - 1, those that minimize ∣JiΔθ−ei∣|J_i\Delta\theta - e_i|. The output is the step of least norm among those kept at level pp.

This is a lexicographic least squares problem: the tasks are ranked, not weighted.

The algorithm

  1. PRIORITY-STEP((J_1, e_1), ..., (J_p, e_p))
  2. 1Δθ ← 0 ; P ← I ▷ P projects onto the motions still free
  3. 2for i ← 1 to p
  4. 3A ← J_i P ▷ task i seen through the free motions
  5. 4A⁺ ← PSEUDOINVERSE(A)
  6. 5r ← e_i - J_i Δθ ▷ what the higher levels left of task i
  7. 6Δθ ← Δθ + A⁺ r
  8. 7P ← P - A⁺ A ▷ remove the motions that task i uses
  9. 8return Δθ

This is the recursive form of Siciliano and Slotine. For p=2p = 2 it gives the formula of Nakamura, Hanafusa and Yoshikawa, since then A=J2P1A = J_2P_1 and r=e2−J2J1+e1r = e_2 - J_2J_1^{+}e_1. The code on this page computes the pseudoinverse with a one-sided Jacobi singular value decomposition and treats singular values below 10−1010^{-10} times the largest as zero.

The iteration. For tasks at the position level, the code repeats θ←θ+PRIORITY-STEP(…)\theta \leftarrow \theta + \text{PRIORITY-STEP}(\ldots) with the Jacobians and errors at the present θ\theta. It stops when ∣Δθ∣≤10−12|\Delta\theta| \le 10^{-12}, not when all errors are zero, because a lower task may have no exact solution.

Example

Take a planar arm with three revolute joints and the link lengths 1, 0.8 and 0.5 m. The first task puts the hand at (1.2,0.6)(1.2, 0.6) m. This is two coordinates for three joints, so the arm has one degree of redundancy, a curve of joint values that all reach the target. The second task asks the elbow, the end of the first link, to be at c=0.5(cos⁡0.5,sin⁡0.5)=(0.438791,0.239713)c = 0.5(\cos 0.5, \sin 0.5) = (0.438791, 0.239713) m. The elbow always lies on the unit circle, so this task cannot be met exactly. The best the arm can do is the elbow angle θ1=0.5\theta_1 = 0.5 rad, with the elbow error 0.5 m, if the hand can still reach its target from there, which it can.

The start θ0=(0,0.574014,2.230016)\theta^0 = (0, 0.574014, 2.230016) rad puts the hand on its target.

step θ\theta (rad) hand error (m) elbow error (m)
0 (0.000000, 0.574014, 2.230016) 2.5e-16 0.610260
1 (0.239713, 0.208759, 2.684896) 0.0139 0.532620
2 (0.368392, -0.030953, 2.862660) 0.0121 0.508574
3 (0.434006, -0.239992, 2.903268) 0.00787 0.502172
4 (0.466979, -0.390844, 2.889575) 0.00223 0.500545
42 (0.500000, -0.536467, 2.873908) 4e-16 0.500000

The hand error is not zero during the run, because each step keeps the hand still only to first order; the next step corrects it first. The distance of θ1\theta_1 to 0.5 halves at each step, which is linear convergence. A brute force search over the curve of joint values that reach the hand target confirms that 0.5 m is the least elbow error.

With the second task changed to put the end of the second link at (0.5,0.5)(0.5, 0.5) m, the iteration stops after 35 steps with that point at (0.705025,0.529289)(0.705025, 0.529289) m, the point of the circle of radius 0.5 m about the hand target that is nearest to (0.5,0.5)(0.5, 0.5). If instead the two tasks are stacked into one 4×34 \times 3 Jacobian and solved with one pseudoinverse per step, the hand is not kept on its target: in this run, it ends 1.53 m away from it.

Correctness

The proof page shows by induction over the levels that, after level ii of the loop, the steps kept by the levels 1,…,i1, \ldots, i form the set Δθ+range⁡(P)\Delta\theta + \operatorname{range}(P). Here PP is the orthogonal projector onto the motions that change none of the tasks 1,…,i1, \ldots, i, and Δθ\Delta\theta is the element of least norm of this set. Two facts carry the induction: (JiP)+(J_iP)^{+} has its range inside the range of PP, and P−(JiP)+(JiP)P - (J_iP)^{+}(J_iP) is again an orthogonal projector, onto the free motions that also leave task ii unchanged.

Consequences:

  • Strict priority. The tasks of lower priority cannot change JjΔθJ_j\Delta\theta for a task jj of higher priority.
  • The first task. If J1J_1 has full row rank, J1Δθ=e1J_1\Delta\theta = e_1 exactly.
  • Fixed points. If the iteration stops with Δθ=0\Delta\theta = 0 at a configuration where J1J_1 has full row rank, then e1=0e_1 = 0, and the gradient of 12∣e2∣2\tfrac12|e_2|^2 along the free motions is zero, so the second task is at a stationary point on the set where the first task is met.

The iteration has no global guarantee. A far start can give large steps, and near an algorithmic singularity the steps can be very large, as explained under Pitfalls.

Proof: The priority step solves the lexicographic least squares problem with the least norm, and its fixed points meet the first taskfull

We use the notation of the page, in exact arithmetic. For a matrix AA, A+A^{+} is the Moore-Penrose pseudoinverse. We use three standard facts about it: A+AA^{+}A is the orthogonal projector onto range⁡(AT)\operatorname{range}(A^{\mathsf T}), the range of A+A^{+} is range⁡(AT)\operatorname{range}(A^{\mathsf T}), and the minimizers of ∣Az−r∣|Az - r| are exactly z=A+r+wz = A^{+}r + w with w∈null⁡(A)w \in \operatorname{null}(A), among which A+rA^{+}r has the least norm.

Define the sets of kept steps by S0=RnS_0 = \mathbb R^n and Si=arg⁡min⁡x∈Si−1∣Jix−ei∣S_i = \arg\min_{x \in S_{i-1}}|J_ix - e_i|. Let Ni=⋂j≤inull⁡(Jj)N_i = \bigcap_{j \le i}\operatorname{null}(J_j), with N0=RnN_0 = \mathbb R^n. Write Δθi\Delta\theta_i and PiP_i for the values of Δθ\Delta\theta and PP after level ii of the loop, with Δθ0=0\Delta\theta_0 = 0 and P0=IP_0 = I.

Claim. For every i=0,…,pi = 0, \ldots, p:

  1. PiP_i is the orthogonal projector onto NiN_i;
  2. Si=Δθi+NiS_i = \Delta\theta_i + N_i;
  3. Δθi\Delta\theta_i is orthogonal to NiN_i, so it is the element of least norm of SiS_i.

Proof. By induction on ii. For i=0i = 0 all three hold, since P0=IP_0 = I, S0=Rn=0+N0S_0 = \mathbb R^n = 0 + N_0 and Δθ0=0\Delta\theta_0 = 0.

Assume the claim for i−1i - 1, and write P=Pi−1P = P_{i-1}, A=JiPA = J_iP and r=ei−JiΔθi−1r = e_i - J_i\Delta\theta_{i-1}, as in lines L3 to L5. Since PP is the orthogonal projector onto Ni−1N_{i-1}, every x∈Si−1x \in S_{i-1} is x=Δθi−1+Pzx = \Delta\theta_{i-1} + Pz for some z∈Rnz \in \mathbb R^n, and then Jix−ei=Az−rJ_ix - e_i = Az - r. So Si={Δθi−1+Pz:z minimizes ∣Az−r∣}={Δθi−1+PA+r+Pw:w∈null⁡(A)}S_i = \{\Delta\theta_{i-1} + Pz : z \text{ minimizes } |Az - r|\} = \{\Delta\theta_{i-1} + PA^{+}r + Pw : w \in \operatorname{null}(A)\}.

The range of A+A^{+} is in the range of PP. range⁡(A+)=range⁡(AT)=range⁡(PJiT)⊆range⁡(P)\operatorname{range}(A^{+}) = \operatorname{range}(A^{\mathsf T}) = \operatorname{range}(PJ_i^{\mathsf T}) \subseteq \operatorname{range}(P), using PT=PP^{\mathsf T} = P. So PA+=A+PA^{+} = A^{+}, and the first part of the set is Δθi−1+A+r=Δθi\Delta\theta_{i-1} + A^{+}r = \Delta\theta_i, the value of line L6.

The free part. {Pw:w∈null⁡(A)}\{Pw : w \in \operatorname{null}(A)\} is the set Ni−1∩null⁡(Ji)=NiN_{i-1} \cap \operatorname{null}(J_i) = N_i. Indeed, if Aw=0Aw = 0, then v=Pw∈Ni−1v = Pw \in N_{i-1} and Jiv=JiPw=Aw=0J_iv = J_iPw = Aw = 0; conversely, if v∈Niv \in N_i, then Pv=vPv = v and Av=Jiv=0Av = J_iv = 0, so v=Pvv = Pv with v∈null⁡(A)v \in \operatorname{null}(A). This proves part 2.

The projector. Q=A+AQ = A^{+}A is the orthogonal projector onto range⁡(AT)⊆range⁡(P)\operatorname{range}(A^{\mathsf T}) \subseteq \operatorname{range}(P), so PQ=QPQ = Q, and taking transposes, QP=QQP = Q. Then P−QP - Q is symmetric and (P−Q)2=P−PQ−QP+Q=P−Q(P - Q)^2 = P - PQ - QP + Q = P - Q, so P−QP - Q is an orthogonal projector. Its range is range⁡(P)∩range⁡(Q)⊥=Ni−1∩null⁡(A)\operatorname{range}(P) \cap \operatorname{range}(Q)^{\perp} = N_{i-1} \cap \operatorname{null}(A), and the last paragraph shows that this is NiN_i. So Pi=P−QP_i = P - Q, the value of line L7, is the orthogonal projector onto NiN_i, which is part 1.

Least norm. Δθi−1\Delta\theta_{i-1} is orthogonal to Ni−1⊇NiN_{i-1} \supseteq N_i by the induction hypothesis. A+rA^{+}r is in range⁡(AT)\operatorname{range}(A^{\mathsf T}), which is orthogonal to null⁡(A)⊇Ni\operatorname{null}(A) \supseteq N_i. So Δθi\Delta\theta_i is orthogonal to NiN_i, and for every v∈Niv \in N_i, ∣Δθi+v∣2=∣Δθi∣2+∣v∣2|\Delta\theta_i + v|^2 = |\Delta\theta_i|^2 + |v|^2. This is part 3. □\square

So the output Δθp\Delta\theta_p is the step of least norm that solves the lexicographic least squares problem of the page.

Consequences

Strict priority. Sp⊆SjS_p \subseteq S_j for every jj, and two elements of SjS_j differ by an element of NjN_j, which no task 1,…,j1, \ldots, j sees. So JlΔθp=JlΔθjJ_l\Delta\theta_p = J_l\Delta\theta_j for all l≤jl \le j: the levels below jj do not change what the levels up to jj achieve.

The first task. If J1J_1 has full row rank, the minimum of ∣J1x−e1∣|J_1x - e_1| is 0, so J1Δθp=e1J_1\Delta\theta_p = e_1.

Two levels. With P1=I−J1+J1P_1 = I - J_1^{+}J_1, the loop gives Δθ2=J1+e1+(J2P1)+(e2−J2J1+e1)\Delta\theta_2 = J_1^{+}e_1 + (J_2P_1)^{+}(e_2 - J_2J_1^{+}e_1), the formula of Nakamura, Hanafusa and Yoshikawa.

Fixed points of the iteration

Let the iteration stop with Δθp=0\Delta\theta_p = 0 at a configuration θˉ\bar\theta with J1(θˉ)J_1(\bar\theta) of full row rank.

  • By part 3, Δθ1=J1+e1\Delta\theta_1 = J_1^{+}e_1 is orthogonal to N1N_1, and every later increment A+rA^{+}r lies in N1N_1 (its range is in the range of Pi−1⊆P_{i-1} \subseteq the range of P1P_1). So Δθp=0\Delta\theta_p = 0 forces J1+e1=0J_1^{+}e_1 = 0. Since J1J_1 has full row rank, J1+J_1^{+} is injective, and e1=0e_1 = 0.
  • Then Δθ1=0\Delta\theta_1 = 0, r=e2r = e_2 at level 2, and the increment of level 2 is (J2P1)+e2(J_2P_1)^{+}e_2. It is orthogonal to N2N_2 while the later increments lie in N2N_2, so it is zero too. Since null⁡(A+)=null⁡(AT)\operatorname{null}(A^{+}) = \operatorname{null}(A^{\mathsf T}), this means P1J2Te2=0P_1J_2^{\mathsf T}e_2 = 0. As −J2Te2-J_2^{\mathsf T}e_2 is the gradient of 12∣e2∣2\tfrac12|e_2|^2, its projection onto the motions that keep the first task to first order is zero.

So a fixed point meets the first task exactly and is a stationary point of the second task error on the set where the first task holds. Nothing more is claimed: the iteration need not converge, and a stationary point need not be the best one.

Complexity

One step with pp levels and m=∑imim = \sum_i m_i task coordinates forms JiPJ_iP in Θ(min2)\Theta(m_in^2), computes a pseudoinverse of an mi×nm_i \times n matrix, and updates PP in Θ(min2)\Theta(m_in^2), in the real RAM. With a pseudoinverse that costs Θ(mi2n)\Theta(m_i^2n), for example through a factorization of AATAA^{\mathsf T} when AA has full row rank, one step costs Θ(n2m)\Theta(n^2m), and kk steps cost Θ(kn2m)\Theta(kn^2m). A singular value decomposition by Jacobi sweeps, as in the code, costs Θ(min2)\Theta(m_in^2) per sweep, with a number of sweeps that is small in practice but not bounded by a formula. The extra space is PP and the Jacobians, Θ(n2+mn)\Theta(n^2 + mn). The number of iterations kk is not bounded in general; in the example it is 42.

Properties

  • Strict hierarchy. A higher task is never traded for a lower one, unlike a weighted sum of the task errors.
  • Least norm. Among all steps that serve the tasks in order, the method takes the shortest one.
  • Equality tasks only. The basic method handles tasks of the form JiΔθ=eiJ_i\Delta\theta = e_i; inequalities, such as joint limits, need a hierarchical quadratic program.
  • Local. At the position level, the iteration is a local method, like the other Jacobian methods.

Variants and improvements

  • Two levels with a gradient. A common special case keeps one task and adds (I−J1+J1)z(I - J_1^{+}J_1)z with zz the negative gradient of a cost, such as the distance to joint limits; this is the classical null space projection.
  • Many levels. Siciliano and Slotine gave the recursive formula of lines L1 to L8 for any number of levels.
  • Robust to algorithmic singularities. Chiaverini (1997) drops the term −J2J1+e1-J_2J_1^{+}e_1 for the lower task and uses damped least squares for the projected Jacobian, which removes the large steps at the cost of exact priority.
  • Damping. Replacing each pseudoinverse by a damped least squares inverse bounds the steps near singularities, and the priority is then only approximate.
  • Inequalities. Hierarchical quadratic programming solves a stack of equality and inequality tasks in priority order, and it is the usual tool in whole-body control.

When to use it

Use task-priority inverse kinematics on a redundant arm or a humanoid when some tasks must be met exactly, such as the hand pose, and others are wishes, such as a posture, a gaze direction or the distance to an obstacle. When the tasks are equally important and a trade-off is wanted, weight them in one least squares problem instead. When there are inequalities, use hierarchical quadratic programming.

Pitfalls

  • Algorithmic singularities. J2P1J_2P_1 can lose rank even when J1J_1 and J2J_2 both have full rank, when the two tasks need the same motion. Near such a configuration, (J2P1)+(J_2P_1)^{+} gives very large steps; use a damped inverse or the form of Chiaverini.
  • Rank tolerance. The pseudoinverse needs a threshold on the singular values; a threshold that is too small lets near-singular directions blow up, and one that is too large drops real motions.
  • Weights do not give priority. Stacking the tasks into one Jacobian with weights only trades the errors against each other, and the first task is not met, as in the example.
  • Units. Each level compares only errors of its own task, but a task that mixes positions and angles still needs a choice of scale.
  • The order of the product. P1P_1 must multiply J2J_2 on the right, J2P1J_2P_1; the range of (J2P1)+(J_2P_1)^{+} is then inside the null space of J1J_1.

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.

task_priority_inverse_kinematics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/task-priority-inverse-kinematics/. The authors are listed in prov/791J72.jsonl.
"""Task-priority inverse kinematics.

- pinv(a, tol) is the Moore-Penrose pseudoinverse by a one-sided Jacobi
  singular value decomposition. Singular values below tol times the largest
  one are treated as zero.
- priority_step(tasks) takes a list of (J_i, e_i), highest priority first,
  and returns the joint step of the recursive form of Siciliano and Slotine:
  dq_i = dq_(i-1) + (J_i P_(i-1))^+ (e_i - J_i dq_(i-1)), with
  P_i = P_(i-1) - (J_i P_(i-1))^+ (J_i P_(i-1)) and P_0 = I.
  For two tasks this is the step of Nakamura, Hanafusa and Yoshikawa,
  dq = J1^+ e1 + (J2 P1)^+ (e2 - J2 J1^+ e1).
- ik_task_priority(tasks, q0, ...) iterates the step for position tasks
  given as (fk_i, jac_i, x_d_i). It stops when the step is small, because a
  lower task may not be reachable, and returns (q, steps).

Matrices are lists of rows. The module needs only the standard library.
"""

import math


def transpose(a):
    return [list(col) for col in zip(*a)]


def mul(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 [sum(r * v for r, v in zip(row, x)) for row in a]


def eye(n):
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def norm(x):
    return math.sqrt(sum(v * v for v in x))


def svd(a):
    """Return (u_cols, s, v_cols) with a = sum_i s_i u_i v_i^T, by one-sided Jacobi on the columns of a."""
    m, n = len(a), len(a[0])
    w = [[a[i][j] for i in range(m)] for j in range(n)]  # the columns of a
    v = eye(n)  # v[j] is column j of V
    for _ in range(60):
        rotated = False
        for p in range(n - 1):
            for q in range(p + 1, n):
                alpha = sum(x * x for x in w[p])
                beta = sum(x * x for x in w[q])
                gamma = sum(x * y for x, y in zip(w[p], w[q]))
                if abs(gamma) <= 1e-15 * math.sqrt(alpha * beta) or gamma == 0.0:
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                s = c * t
                w[p], w[q] = [c * x - s * y for x, y in zip(w[p], w[q])], [s * x + c * y for x, y in zip(w[p], w[q])]
                v[p], v[q] = [c * x - s * y for x, y in zip(v[p], v[q])], [s * x + c * y for x, y in zip(v[p], v[q])]
        if not rotated:
            break
    s = [norm(col) for col in w]
    u = [[x / sv for x in col] if sv > 0.0 else [0.0] * m for col, sv in zip(w, s)]
    return u, s, v


def pinv(a, tol=1e-10):
    """Return the n by m Moore-Penrose pseudoinverse of the m by n matrix a."""
    m, n = len(a), len(a[0])
    u, s, v = svd(a)
    smax = max(s) if s else 0.0
    out = [[0.0] * m for _ in range(n)]
    for uk, sk, vk in zip(u, s, v):
        if sk > tol * smax and sk > 0.0:
            for i in range(n):
                f = vk[i] / sk
                for j in range(m):
                    out[i][j] += f * uk[j]
    return out


def priority_step(tasks, n=None, tol=1e-10):
    """Return the joint step for a stack of tasks [(J_1, e_1), (J_2, e_2), ...], highest first."""
    if n is None:
        n = len(tasks[0][0][0])
    dq = [0.0] * n  # @line L1
    p = eye(n)  # @line L1
    for j, e in tasks:  # @line L2
        jp = mul(j, p)  # @line L3
        jp_pinv = pinv(jp, tol)  # @line L4
        r = [a - b for a, b in zip(e, matvec(j, dq))]  # @line L5
        dq = [a + b for a, b in zip(dq, matvec(jp_pinv, r))]  # @line L6
        q = mul(jp_pinv, jp)
        p = [[pij - qij for pij, qij in zip(prow, qrow)] for prow, qrow in zip(p, q)]  # @line L7
    return dq  # @line L8


def ik_task_priority(tasks, q0, eps=1e-12, max_iter=500, tol=1e-10):
    """Iterate priority steps for position tasks [(fk_i, jac_i, x_d_i), ...]; return (q, steps)."""
    q = [float(x) for x in q0]
    for k in range(max_iter):
        stack = [(jac(q), [a - b for a, b in zip(x_d, fk(q))]) for fk, jac, x_d in tasks]
        dq = priority_step(stack, len(q), tol)
        q = [a + b for a, b in zip(q, dq)]
        if norm(dq) <= eps:
            return q, k + 1
    return q, max_iter
test_task_priority_inverse_kinematics.py 241 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/task-priority-inverse-kinematics/. The authors are listed in prov/791J72.jsonl.
"""Tests of task-priority inverse kinematics: the pseudoinverse against the
four Penrose conditions, the step against the closed two-task formula and
against random perturbations in the null space, strict priority in a stack
of three tasks, and the 3R example of the page against a brute force search
over the self-motion of the arm."""

import math
import random

from task_priority_inverse_kinematics import eye, ik_task_priority, matvec, mul, norm, pinv, priority_step, svd, transpose


def rand_matrix(rng, m, n, rank=None):
    if rank is None:
        return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]
    a = [[rng.uniform(-1.0, 1.0) for _ in range(rank)] for _ in range(m)]
    b = [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(rank)]
    return mul(a, b)


def mdiff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def vdiff(a, b):
    return max(abs(x - y) for x, y in zip(a, b))


def sub(a, b):
    return [x - y for x, y in zip(a, b)]


def test_svd_and_penrose_conditions():
    rng = random.Random(1)
    for m, n, rank in ((2, 3, None), (3, 2, None), (4, 4, None), (3, 5, 2), (5, 3, 1), (6, 7, None), (2, 3, 1)):
        for _ in range(5):
            a = rand_matrix(rng, m, n, rank)
            u, s, v = svd(a)
            rec = [[sum(sk * uk[i] * vk[j] for uk, sk, vk in zip(u, s, v)) for j in range(n)] for i in range(m)]
            assert mdiff(rec, a) < 1e-12
            x = pinv(a)
            assert mdiff(mul(mul(a, x), a), a) < 1e-10
            assert mdiff(mul(mul(x, a), x), x) < 1e-9
            ax, xa = mul(a, x), mul(x, a)
            assert mdiff(ax, transpose(ax)) < 1e-10
            assert mdiff(xa, transpose(xa)) < 1e-10
    # Full row rank: J^+ = J^T (J J^T)^-1, checked on a 2 by 3 matrix with the explicit 2 by 2 inverse.
    a = [[1.0, 2.0, 0.5], [0.0, 1.0, -1.0]]
    g = mul(a, transpose(a))
    d = g[0][0] * g[1][1] - g[0][1] * g[1][0]
    ginv = [[g[1][1] / d, -g[0][1] / d], [-g[1][0] / d, g[0][0] / d]]
    assert mdiff(pinv(a), mul(transpose(a), ginv)) < 1e-12


def test_two_tasks_against_the_closed_formula():
    rng = random.Random(2)
    n = 6
    for m1, m2 in ((2, 2), (3, 2), (2, 3), (3, 3)):
        for _ in range(10):
            j1, j2 = rand_matrix(rng, m1, n), rand_matrix(rng, m2, n)
            e1 = [rng.uniform(-1.0, 1.0) for _ in range(m1)]
            e2 = [rng.uniform(-1.0, 1.0) for _ in range(m2)]
            j1p = pinv(j1)
            p1 = [[a - b for a, b in zip(ra, rb)] for ra, rb in zip(eye(n), mul(j1p, j1))]
            ref = [a + b for a, b in zip(matvec(j1p, e1), matvec(pinv(mul(j2, p1)), sub(e2, matvec(j2, matvec(j1p, e1)))))]
            dq = priority_step([(j1, e1), (j2, e2)])
            assert vdiff(dq, ref) < 1e-10
            # The first task is met exactly.
            assert vdiff(matvec(j1, dq), e1) < 1e-10


def null_basis(a, n):
    """Return an orthonormal basis of the null space of a, from the SVD of a."""
    u, s, v = svd(a)
    smax = max(s)
    return [vk for sk, vk in zip(s, v) if sk <= 1e-10 * smax]


def test_second_task_is_best_in_the_null_space():
    rng = random.Random(3)
    n = 6
    for _ in range(20):
        j1, j2 = rand_matrix(rng, 2, n), rand_matrix(rng, 3, n)
        e1 = [rng.uniform(-1.0, 1.0) for _ in range(2)]
        e2 = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        dq = priority_step([(j1, e1), (j2, e2)])
        best = norm(sub(matvec(j2, dq), e2))
        basis = null_basis(j1 + [[0.0] * n for _ in range(n - 2)], n)
        assert len(basis) == n - 2
        for _ in range(100):
            s = rng.choice((1e-3, 1e-1, 1.0))
            trial = list(dq)
            for b in basis:
                z = rng.uniform(-s, s)
                trial = [t + z * x for t, x in zip(trial, b)]
            assert vdiff(matvec(j1, trial), e1) < 1e-9
            assert norm(sub(matvec(j2, trial), e2)) >= best - 1e-12


def test_strict_priority_in_a_stack():
    rng = random.Random(4)
    n = 7
    for _ in range(10):
        tasks = [(rand_matrix(rng, m, n), [rng.uniform(-1.0, 1.0) for _ in range(m)]) for m in (2, 3, 3)]
        full = priority_step(tasks)
        for k in (1, 2):
            part = priority_step(tasks[:k])
            for j, _ in tasks[:k]:
                assert vdiff(matvec(j, full), matvec(j, part)) < 1e-9


LENGTHS = [1.0, 0.8, 0.5]


def fk(q):
    x = y = a = 0.0
    for length, t in zip(LENGTHS, q):
        a += t
        x += length * math.cos(a)
        y += length * math.sin(a)
    return [x, y]


def jac(q):
    ang = []
    a = 0.0
    for t in q:
        a += t
        ang.append(a)
    return [[-sum(LENGTHS[k] * math.sin(ang[k]) for k in range(i, 3)) for i in range(3)],
            [sum(LENGTHS[k] * math.cos(ang[k]) for k in range(i, 3)) for i in range(3)]]


def elbow(q):
    return [LENGTHS[0] * math.cos(q[0]), LENGTHS[0] * math.sin(q[0])]


def jac_elbow(q):
    return [[-LENGTHS[0] * math.sin(q[0]), 0.0, 0.0], [LENGTHS[0] * math.cos(q[0]), 0.0, 0.0]]


X_D = [1.2, 0.6]


def start_on_target():
    """A joint vector with the hand on X_D and q1 = 0."""
    dx, dy = X_D[0] - LENGTHS[0], X_D[1]
    c3 = (dx * dx + dy * dy - LENGTHS[1] ** 2 - LENGTHS[2] ** 2) / (2.0 * LENGTHS[1] * LENGTHS[2])
    q3 = math.acos(c3)
    q2 = math.atan2(dy, dx) - math.atan2(LENGTHS[2] * math.sin(q3), LENGTHS[1] + LENGTHS[2] * math.cos(q3))
    return [0.0, q2, q3]


def brute_force_elbow(c, steps=20000):
    """Least elbow error over the self-motion: q1 on a grid, the rest a 2R arm that must reach X_D.

    The best grid cell is refined by a ternary search, since the error is unimodal there.
    """
    def feasible(a):
        d = math.hypot(X_D[0] - LENGTHS[0] * math.cos(a), X_D[1] - LENGTHS[0] * math.sin(a))
        return abs(LENGTHS[1] - LENGTHS[2]) <= d <= LENGTHS[1] + LENGTHS[2]

    def err(a):
        return math.hypot(LENGTHS[0] * math.cos(a) - c[0], LENGTHS[0] * math.sin(a) - c[1])

    h = 2.0 * math.pi / steps
    best = min((err(a), a) for a in (-math.pi + h * i for i in range(steps)) if feasible(a))
    lo, hi = best[1] - h, best[1] + h
    for _ in range(60):
        m1, m2 = lo + (hi - lo) / 3.0, hi - (hi - lo) / 3.0
        if err(m1) < err(m2):
            hi = m2
        else:
            lo = m1
    a = 0.5 * (lo + hi)
    assert feasible(a)
    return err(a), a


def test_example_of_the_page():
    q0 = start_on_target()
    assert vdiff(q0, [0.0, 0.574014, 2.230016]) < 1e-6
    assert vdiff(fk(q0), X_D) < 1e-12
    c = [0.5 * math.cos(0.5), 0.5 * math.sin(0.5)]
    q = q0
    errs = []
    for _ in range(2):
        stack = [(jac(q), sub(X_D, fk(q))), (jac_elbow(q), sub(c, elbow(q)))]
        q = [a + b for a, b in zip(q, priority_step(stack))]
        errs.append((norm(sub(X_D, fk(q))), norm(sub(c, elbow(q)))))
    assert vdiff(q, [0.368392, -0.030953, 2.862660]) < 1e-6
    assert vdiff(errs[0], [0.0139, 0.532620]) < 1e-4
    q, steps = ik_task_priority([(fk, jac, X_D), (elbow, jac_elbow, c)], q0)
    assert steps == 42
    assert vdiff(q, [0.5, -0.536467, 2.873908]) < 1e-6
    assert norm(sub(X_D, fk(q))) < 1e-12
    err, a = brute_force_elbow(c)
    assert abs(norm(sub(c, elbow(q))) - err) < 1e-8 and abs(q[0] - a) < 1e-4


def test_other_secondary_targets_against_brute_force():
    for r, phi in ((0.3, 1.0), (0.6, -0.3), (0.5, 1.4)):
        c = [r * math.cos(phi), r * math.sin(phi)]
        q, steps = ik_task_priority([(fk, jac, X_D), (elbow, jac_elbow, c)], start_on_target(), max_iter=2000)
        assert steps < 2000
        assert norm(sub(X_D, fk(q))) < 1e-12
        err, a = brute_force_elbow(c)
        assert abs(norm(sub(c, elbow(q))) - err) < 1e-8
        assert abs(math.remainder(q[0] - a, 2.0 * math.pi)) < 1e-4


def wrist(q):
    """The end of link 2."""
    a1, a2 = q[0], q[0] + q[1]
    return [LENGTHS[0] * math.cos(a1) + LENGTHS[1] * math.cos(a2), LENGTHS[0] * math.sin(a1) + LENGTHS[1] * math.sin(a2)]


def jac_wrist(q):
    a1, a2 = q[0], q[0] + q[1]
    s1, c1, s2, c2 = math.sin(a1), math.cos(a1), math.sin(a2), math.cos(a2)
    return [[-LENGTHS[0] * s1 - LENGTHS[1] * s2, -LENGTHS[1] * s2, 0.0], [LENGTHS[0] * c1 + LENGTHS[1] * c2, LENGTHS[1] * c2, 0.0]]


def test_coupled_secondary_task():
    # The end of link 2 must lie on the circle of radius 0.5 about X_D; the best point is the one nearest to c.
    c = [0.5, 0.5]
    d = sub(c, X_D)
    best = [x + LENGTHS[2] * y / norm(d) for x, y in zip(X_D, d)]
    q, steps = ik_task_priority([(fk, jac, X_D), (wrist, jac_wrist, c)], start_on_target(), max_iter=2000)
    assert steps < 2000
    assert norm(sub(X_D, fk(q))) < 1e-12
    assert vdiff(wrist(q), best) < 1e-8
    # One pseudoinverse of the stacked Jacobian gives a compromise instead: the hand misses its target.
    q = start_on_target()
    for _ in range(300):
        j = jac(q) + jac_wrist(q)
        e = sub(X_D, fk(q)) + sub(c, wrist(q))
        q = [a + b for a, b in zip(q, matvec(pinv(j), e))]
    assert norm(sub(X_D, fk(q))) > 1e-2

History

Redundant arms had been controlled with the pseudoinverse plus a null space term since the 1970s. Nakamura, Hanafusa and Yoshikawa (1987) gave the task-priority formulation, with the second task solved in the null space of the first and the pseudoinverse of the projected Jacobian J2P1J_2P_1, and studied the singularities it brings. Siciliano and Slotine (1991) extended it to any number of levels with the recursive formula. Chiaverini (1997) proposed a form that stays bounded at algorithmic singularities. Later work, such as hierarchical quadratic programming, added inequality tasks to the hierarchy.

References

  1. Yoshihiko Nakamura, Hideo Hanafusa and Tsuneo Yoshikawa, Task-priority based redundancy control of robot manipulators, The International Journal of Robotics Research 6(2), 3-15, 1987, the two-level task-priority solution with the pseudoinverse of the projected Jacobian
  2. Bruno Siciliano and Jean-Jacques E. Slotine, A general framework for managing multiple tasks in highly redundant robotic systems, Fifth International Conference on Advanced Robotics (ICAR), 1991, the recursive formula for any number of priority levels

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
  • at least three sources
  • a scene preset for the example