Algorithm Search⌘K

Algorithmcore

Jacobian pseudoinverse method

Also called pseudoinverse inverse kinematics.

Iterates joint steps J^+ e that reduce the pose error e, giving least-norm joint motion for redundant arms.

Time
Θ(k m n min(m, n)) worst
Space
Θ(m n) extra
Where
k = the number of iterations; m = the dimension of the task; n = the number of joints
Properties
deterministicofflineiterative
Origin
Daniel E. Whitney, 1969

The Jacobian pseudoinverse method solves the inverse kinematics of a robot arm by iteration. From a guess qq, it measures the error ee between the desired pose and the pose that qq gives, and it moves the joints by Δq=J(q)+e\Delta q = J(q)^{+}e, where J+J^{+} is the Moore-Penrose pseudoinverse of the Jacobian, until the error is below a tolerance. Each step is the joint motion of least norm that removes the error to first order, or, if no joint motion can, the one of least norm among those that leave the smallest error. So the same short loop works for square, redundant and underactuated tasks, and near a solution it converges quadratically.

In plain words

You want the hand of a robot at a certain place, and you do not know the joint angles that put it there. Guess some angles and look at where the hand is. The hand is off by some amount. For small joint motions, the hand moves almost in a straight line, by a rule that you can compute at the present angles. So ask: what is the smallest joint motion that would move the hand by exactly the missing amount, if that rule were exact? Make that motion, look again, and repeat. Near the answer, each repeat roughly doubles the number of correct digits. If the arm has spare joints, picking the smallest motion keeps it from wandering.

The problem

Input.

  • The forward kinematics of an arm with nn joints, T(q)∈SE(3)T(q) \in SE(3), in the product of exponentials form T(q)=Me[B1]q1⋯e[Bn]qnT(q) = M e^{[\mathcal B_1]q_1} \cdots e^{[\mathcal B_n]q_n} with the body screw axes Bi\mathcal B_i.
  • A desired pose TdT_d.
  • An initial guess q0q_0, tolerances εω\varepsilon_\omega for the rotation and εv\varepsilon_v for the translation, and a maximum number of iterations kmax⁡k_{\max}.

Output. Joint values qq such that the body twist Vb=log⁡(T(q)−1Td)=(ωb,vb)\mathcal V_b = \log(T(q)^{-1}T_d) = (\omega_b, v_b) has ∣ωb∣≤εω|\omega_b| \le \varepsilon_\omega and ∣vb∣≤εv|v_b| \le \varepsilon_v, or FAILURE if no such qq is found within kmax⁡k_{\max} iterations.

For a position task, the error is the plain difference e=xd−f(q)e = x_d - f(q) of positions, and JJ is the position Jacobian; the loop is the same. In both cases the task has dimension mm (m=6m = 6 for a full pose), and JJ is m×nm \times n; n>mn > m (redundant), n=mn = m and n<mn < m are all allowed.

The algorithm

  1. PSEUDOINVERSE-IK(M, B_1..B_n, T_d, q0, ε_ω, ε_v, k_max)
  2. 1q ← q0
  3. 2for k ← 1 to k_max
  4. 3V_b ← log(T(q)^-1 T_d) ▷ pose error as a body twist (ω_b, v_b)
  5. 4if |ω_b| ≤ ε_ω and |v_b| ≤ ε_v then return q
  6. 5J_b ← BODY-JACOBIAN(q) ▷ 6 × n, in the end effector frame
  7. 6q ← q + J_b^+ V_b ▷ least norm, least squares step
  8. 7return FAILURE

Line L3 uses the matrix logarithm of SE(3), the inverse of the exponential map; Vb\mathcal V_b is the twist that, followed for unit time, takes the present end effector frame to the desired one. Line L5 is the body Jacobian, whose columns are the body screw axes moved to the present configuration; it is in the same frame and the same order (angular part first) as Vb\mathcal V_b. Line L6 needs Jb+VbJ_b^{+}V_b, which is the least squares solution of least norm of Jb Δq=VbJ_b\,\Delta q = V_b. The code on this page computes it from a singular value decomposition and treats singular values at or below 10−10σmax⁡10^{-10}\sigma_{\max} as zero; that tolerance is a rule of thumb.

Example

A 2R arm, position task. Planar arm with unit links, target xd=(1,1)x_d = (1, 1) m, start q0=(0.3,1.2)q_0 = (0.3, 1.2).

  • Line L3 (position form): f(q0)=(1.026074,1.293015)f(q_0) = (1.026074, 1.293015), so e=(−0.026074,−0.293015)e = (-0.026074, -0.293015) and ∣e∣=0.294|e| = 0.294 m.
  • Line L5: J(q0)=(−1.2930−0.99751.02610.0707)J(q_0) = \begin{pmatrix} -1.2930 & -0.9975 \\ 1.0261 & 0.0707 \end{pmatrix}, square and invertible, so J+=J−1J^{+} = J^{-1}.
  • Line L6: Δq=(−0.315572,0.435203)\Delta q = (-0.315572, 0.435203), and q1=(−0.015572,1.635203)q_1 = (-0.015572, 1.635203).

The next iterates are (−0.001187,1.572048)(-0.001187, 1.572048) and then (0.000000,1.570797)(0.000000, 1.570797), which approach the solution (0,π/2)(0, \pi/2). The error norms are

0.294,0.0517,0.00119,7.05⋅10−7,2.48⋅10−13,0,0.294,\quad 0.0517,\quad 0.00119,\quad 7.05 \cdot 10^{-7},\quad 2.48 \cdot 10^{-13},\quad 0,

and each one is about a constant times the square of the one before: quadratic convergence. From the start (1.3,−1.2)(1.3, -1.2) the same loop goes to the other solution, (π/2,−π/2)(\pi/2, -\pi/2), with the error norms 0.2700.270, 0.04440.0444, 8.35⋅10−48.35 \cdot 10^{-4}, 3.44⋅10−73.44 \cdot 10^{-7} and 5.92⋅10−145.92 \cdot 10^{-14}. The guess decides which solution the method finds.

A redundant 3R arm. Planar arm with three unit links, target (1.5,1.0)(1.5, 1.0) m, start q0=(0,0.5,0.5)q_0 = (0, 0.5, 0.5), where f(q0)=(2.417885,1.320897)f(q_0) = (2.417885, 1.320897) and ∣e∣=0.972|e| = 0.972 m. Here J(q0)=(−1.3209−1.3209−0.84152.41791.41790.5403)J(q_0) = \begin{pmatrix} -1.3209 & -1.3209 & -0.8415 \\ 2.4179 & 1.4179 & 0.5403 \end{pmatrix} is 2×32 \times 3, and the first step is the least norm solution Δq=(−0.884752,0.839974,1.161099)\Delta q = (-0.884752, 0.839974, 1.161099). The error norms are 0.9720.972, 0.6830.683, 0.02970.0297, 1.99⋅10−41.99 \cdot 10^{-4}, 1.35⋅10−81.35 \cdot 10^{-8} and 2.2⋅10−162.2 \cdot 10^{-16}, and the loop ends at q=(−0.560477,1.141052,1.174410)q = (-0.560477, 1.141052, 1.174410), with ∣q∣=1.7307|q| = 1.7307. The target has a one-parameter family of solutions; the method picks one of them, and which one depends on q0q_0.

A pose task with more equations than joints. Write the same 2R arm as a spatial chain with M=(I,(2,0,0))M = (I, (2, 0, 0)) and the body screw axes B1=(0,0,1,0,2,0)\mathcal B_1 = (0, 0, 1, 0, 2, 0) and B2=(0,0,1,0,1,0)\mathcal B_2 = (0, 0, 1, 0, 1, 0), and ask for the pose TdT_d with rotation Rz(π/2)R_z(\pi/2) and position (1,1,0)(1, 1, 0), from q0=(0.2,1.3)q_0 = (0.2, 1.3). Now JbJ_b is 6×26 \times 2, with only the rows ωz\omega_z, vxv_x and vyv_y nonzero, and Jb+J_b^{+} gives the least squares step. The error norms (∣ωb∣,∣vb∣)(|\omega_b|, |v_b|) are (0.0708,0.2027)(0.0708, 0.2027), (0.0135,0.0136)(0.0135, 0.0136), (5.5⋅10−6,5.5⋅10−6)(5.5 \cdot 10^{-6}, 5.5 \cdot 10^{-6}) and (7.2⋅10−14,7.2⋅10−14)(7.2 \cdot 10^{-14}, 7.2 \cdot 10^{-14}), and the loop returns (0,π/2)(0, \pi/2).

A target out of reach. For the target (2.5,0)(2.5, 0) m, which is beyond the reach of 2 m, from (0.2,0.5)(0.2, 0.5), the error norms jump between about 0.5 and 2.2 and do not settle, and the loop returns FAILURE after 50 iterations. Near the stretched pose, which is the best the arm can do, JJ is close to singular, and the steps are huge.

Correctness

The step. By Penrose (1955), Δq=J+e\Delta q = J^{+}e is the unique vector that minimizes ∣JΔq−e∣|J\Delta q - e| and, among all minimizers, has the least norm. If JJ has full row rank, the minimum is 0 and Δq\Delta q is the least norm solution of JΔq=eJ\Delta q = e; if JJ is square and invertible, Δq=J−1e\Delta q = J^{-1}e is the Newton step; if JJ has full column rank, Δq=(JTJ)−1JTe\Delta q = (J^{\mathsf T}J)^{-1}J^{\mathsf T}e is the Gauss-Newton step.

Convergence, full row rank. Write G(q)G(q) for the error (the position error or the body twist error) and suppose that on a ball around q0q_0, σm(J(q))≥σ0>0\sigma_m(J(q)) \ge \sigma_0 > 0, the second derivative of GG is bounded by HH, and, for the twist error, DG=−A JbDG = -A\,J_b with ∣A−I∣≤L∣G∣|A - I| \le L|G|. Then each step gives ∣G(qk+1)∣≤C∣G(qk)∣2|G(q_{k+1})| \le C|G(q_k)|^2 with C=L+H/(2σ02)C = L + H/(2\sigma_0^2). If θ=C∣G(q0)∣<1\theta = C|G(q_0)| < 1 and the ball has radius at least ∣G(q0)∣/(σ0(1−θ))|G(q_0)|/(\sigma_0(1 - \theta)), the iterates stay in the ball, converge to a solution q∗q^*, and C∣G(qk)∣≤θ2kC|G(q_k)| \le \theta^{2^k}. For the position error, L=0L = 0.

Convergence, full column rank. If a solution q∗q^* exists and JJ has full column rank near it, then ∣qk+1−q∗∣≤D∣qk−q∗∣2|q_{k+1} - q^*| \le D|q_k - q^*|^2 for a constant DD, so the method converges quadratically from every start close enough to q∗q^*.

The proof below gives the details. The method is local: from a poor start, or when no solution exists, it can wander, cycle or stop at a singular configuration.

Proof: PSEUDOINVERSE-IK takes least norm least squares steps and converges quadratically near a solutionfull

We use the notation of the page. All vector norms are Euclidean, and the norm of a matrix is its largest singular value. The proof is in exact arithmetic, in the real RAM.

The loop of the page has the form

qk+1=qk+J(qk)+ G(qk),q_{k+1} = q_k + J(q_k)^{+}\,G(q_k),

where G:Rn→RmG : \mathbb{R}^n \to \mathbb{R}^m is the error and JJ is the matching Jacobian. For the position task, G(q)=xd−f(q)G(q) = x_d - f(q) and J=DfJ = Df, so DG=−JDG = -J. For the pose task, G(q)=log⁡(T(q)−1Td)G(q) = \log(T(q)^{-1}T_d) is the body twist error and J=JbJ = J_b. Line L4 returns as soon as GG is below the tolerance, and line L7 returns FAILURE after kmax⁡k_{\max} iterations, so the loop always stops; the content of the proof is what one step does and when the iterates converge.

The step

Lemma 1 (Penrose). For every m×nm \times n matrix JJ and every e∈Rme \in \mathbb{R}^m, the vector Δ=J+e\Delta = J^{+}e minimizes ∣JΔ−e∣|J\Delta - e|, and among all minimizers it is the unique one of least norm.

Proof. Let J=UΣVTJ = U\Sigma V^{\mathsf T} be a singular value decomposition with the nonzero singular values σ1,…,σr\sigma_1, \dots, \sigma_r, and J+=VΣ+UTJ^{+} = V\Sigma^{+}U^{\mathsf T}, where Σ+\Sigma^{+} is the n×mn \times m matrix with the entries 1/σi1/\sigma_i for i≤ri \le r and zeros elsewhere. Put y=VTΔy = V^{\mathsf T}\Delta and c=UTec = U^{\mathsf T}e. Since UU and VV are orthogonal, ∣JΔ−e∣2=∣Σy−c∣2=∑i≤r(σiyi−ci)2+∑i>rci2|J\Delta - e|^2 = |\Sigma y - c|^2 = \sum_{i \le r}(\sigma_i y_i - c_i)^2 + \sum_{i > r} c_i^2 and ∣Δ∣=∣y∣|\Delta| = |y|. The first sum is zero exactly when yi=ci/σiy_i = c_i/\sigma_i for i≤ri \le r, and the second does not depend on yy, so the minimizers are the yy with these rr entries and any other entries. The one of least norm has yi=0y_i = 0 for i>ri > r, that is y=Σ+cy = \Sigma^{+}c, and Δ=VΣ+UTe=J+e\Delta = V\Sigma^{+}U^{\mathsf T}e = J^{+}e. □\square

Corollary 2. If JJ has rank mm, then J+=JT(JJT)−1J^{+} = J^{\mathsf T}(JJ^{\mathsf T})^{-1}, JJ+=IJJ^{+} = I, and J+eJ^{+}e is the least norm solution of JΔ=eJ\Delta = e. If JJ has rank nn, then J+=(JTJ)−1JTJ^{+} = (J^{\mathsf T}J)^{-1}J^{\mathsf T} and J+J=IJ^{+}J = I. In both cases ∥J+∥=1/σmin⁡\|J^{+}\| = 1/\sigma_{\min}, the inverse of the smallest singular value of JJ.

Proof. With rank mm, r=mr = m and Σ+\Sigma^{+} is the transpose of Σ\Sigma with the entries inverted, so JJ+=UΣΣ+UT=IJJ^{+} = U\Sigma\Sigma^{+}U^{\mathsf T} = I, and the formulas follow by expanding JT(JJT)−1=VΣT(ΣΣT)−1UT=VΣ+UTJ^{\mathsf T}(JJ^{\mathsf T})^{-1} = V\Sigma^{\mathsf T}(\Sigma\Sigma^{\mathsf T})^{-1}U^{\mathsf T} = V\Sigma^{+}U^{\mathsf T}. The case of rank nn is the same with JTJJ^{\mathsf T}J. The singular values of J+J^{+} are the 1/σi1/\sigma_i. □\square

For a square invertible JJ the step is J−1GJ^{-1}G, the Newton step for G(q)=0G(q) = 0.

The error map of the pose task

Lemma 3. Let S(q)=T(q)−1TdS(q) = T(q)^{-1}T_d, and suppose that on a set Ω\Omega the rotation angle of S(q)S(q) stays below π\pi, so that G(q)=log⁡S(q)G(q) = \log S(q) is a smooth function. Then DG(q)=−A(q) Jb(q)DG(q) = -A(q)\,J_b(q), where A(q)=Jl(G(q))−1A(q) = \mathcal J_l(G(q))^{-1} and Jl\mathcal J_l is the left Jacobian of SE(3). AA is smooth, A=IA = I where G=0G = 0, and on a compact part of Ω\Omega there is a constant LL with ∥A(q)−I∥≤L∣G(q)∣\|A(q) - I\| \le L|G(q)|.

Proof. By the definition of the body Jacobian, T(q)−1 ∂T/∂qi=[Jb,i(q)]T(q)^{-1}\,\partial T/\partial q_i = [J_{b,i}(q)], the matrix of column ii of JbJ_b. So ∂S/∂qi=−T−1(∂T/∂qi)T−1Td=−[Jb,i] S\partial S/\partial q_i = -T^{-1}(\partial T/\partial q_i)T^{-1}T_d = -[J_{b,i}]\,S: a change of qq multiplies SS on the left by exp⁡(−[Jb dq])\exp(-[J_b\,dq]) to first order. The derivative of log⁡\log at S=e[V]S = e^{[V]} in the direction of a left perturbation e[ξ]Se^{[\xi]}S is Jl(V)−1ξ\mathcal J_l(V)^{-1}\xi; this is the definition of the left Jacobian, which is a smooth, invertible matrix function of VV for rotation angles below 2π2\pi, with Jl(0)=I\mathcal J_l(0) = I. With ξ=−Jb dq\xi = -J_b\,dq this gives DG=−Jl(G)−1JbDG = -\mathcal J_l(G)^{-1}J_b. The map V↦Jl(V)−1V \mapsto \mathcal J_l(V)^{-1} is smooth with the value II at V=0V = 0, so it is Lipschitz on a compact set, which gives LL. □\square

For the position task, A=IA = I and L=0L = 0. So both tasks fit the same frame: DG=−AJDG = -AJ with ∥A−I∥≤L∣G∣\|A - I\| \le L|G|.

Full row rank

Make these assumptions on a closed ball B={q:∣q−q0∣≤R}B = \{q : |q - q_0| \le R\}.

  • (B1) J(q)J(q) has rank mm and σm(J(q))≥σ0>0\sigma_m(J(q)) \ge \sigma_0 > 0 for q∈Bq \in B.
  • (B2) ∣G(q+δ)−G(q)−DG(q)δ∣≤H2∣δ∣2|G(q + \delta) - G(q) - DG(q)\delta| \le \tfrac{H}{2}|\delta|^2 whenever qq and q+δq + \delta are in BB.
  • (B3) DG=−AJDG = -AJ on BB with ∥A(q)−I∥≤L∣G(q)∣\|A(q) - I\| \le L|G(q)|.

Let C=L+H/(2σ02)C = L + H/(2\sigma_0^2) and θ=C∣G(q0)∣\theta = C|G(q_0)|.

Theorem 4. If θ<1\theta < 1 and R≥∣G(q0)∣/(σ0(1−θ))R \ge |G(q_0)|/(\sigma_0(1 - \theta)), then all iterates lie in BB, C∣G(qk)∣≤θ2kC|G(q_k)| \le \theta^{2^k}, and qkq_k converges to a point q∗∈Bq^* \in B with G(q∗)=0G(q^*) = 0.

Proof. Write Gk=G(qk)G_k = G(q_k), Jk=J(qk)J_k = J(q_k) and δk=Jk+Gk\delta_k = J_k^{+}G_k.

One step. If qkq_k and qk+1q_{k+1} are in BB, then by (B2), (B3) and JkJk+=IJ_kJ_k^{+} = I (Corollary 2),

Gk+1=Gk−A(qk)Jkδk+rk=(I−A(qk))Gk+rk,∣rk∣≤H2∣δk∣2.G_{k+1} = G_k - A(q_k)J_k\delta_k + r_k = (I - A(q_k))G_k + r_k, \qquad |r_k| \le \tfrac{H}{2}|\delta_k|^2.

With ∣δk∣≤∣Gk∣/σ0|\delta_k| \le |G_k|/\sigma_0 (Corollary 2 and (B1)), ∣Gk+1∣≤L∣Gk∣2+H2σ02∣Gk∣2=C∣Gk∣2|G_{k+1}| \le L|G_k|^2 + \tfrac{H}{2\sigma_0^2}|G_k|^2 = C|G_k|^2.

Induction. We show by induction on kk that q0,…,qk∈Bq_0, \dots, q_k \in B and C∣Gj∣≤θ2jC|G_j| \le \theta^{2^j} for j≤kj \le k. For k=0k = 0 this is the definition of θ\theta, and q0∈Bq_0 \in B. Suppose it holds for kk. For j≤kj \le k, ∣δj∣≤∣Gj∣/σ0≤θ2j−1∣G0∣/σ0|\delta_j| \le |G_j|/\sigma_0 \le \theta^{2^j - 1}|G_0|/\sigma_0, because C∣Gj∣≤θ2jC|G_j| \le \theta^{2^j} and C∣G0∣=θC|G_0| = \theta give ∣Gj∣≤θ2j−1∣G0∣|G_j| \le \theta^{2^j - 1}|G_0| when C>0C > 0; when C=0C = 0, the one-step bound gives Gj=0G_j = 0 for j≥1j \ge 1, and the same inequality holds with θ0=1\theta^0 = 1. Since 2j−1≥j2^j - 1 \ge j,

∣qk+1−q0∣≤∑j=0k∣δj∣≤∣G0∣σ0∑j≥0θj=∣G0∣σ0(1−θ)≤R,|q_{k+1} - q_0| \le \sum_{j=0}^{k}|\delta_j| \le \frac{|G_0|}{\sigma_0}\sum_{j \ge 0}\theta^j = \frac{|G_0|}{\sigma_0(1 - \theta)} \le R,

so qk+1∈Bq_{k+1} \in B. Then the one-step bound applies, and C∣Gk+1∣≤(C∣Gk∣)2≤θ2k+1C|G_{k+1}| \le (C|G_k|)^2 \le \theta^{2^{k+1}}.

Limit. The same sum shows that ∑j∣δj∣\sum_j|\delta_j| converges, so qkq_k is a Cauchy sequence with a limit q∗∈Bq^* \in B, since BB is closed. GG is continuous and G(qk)→0G(q_k) \to 0, so G(q∗)=0G(q^*) = 0. □\square

So the error falls quadratically, ∣Gk+1∣≤C∣Gk∣2|G_{k+1}| \le C|G_k|^2, and the total joint motion is at most ∣G(q0)∣/(σ0(1−θ))|G(q_0)|/(\sigma_0(1 - \theta)). The limit is a solution in BB, but it need not be the solution nearest to q0q_0.

Full column rank

Theorem 5. Suppose G(q∗)=0G(q^*) = 0, and on the closed ball B∗={q:∣q−q∗∣≤R}B^* = \{q : |q - q^*| \le R\}: J(q)J(q) has rank nn with σn(J(q))≥σ0>0\sigma_n(J(q)) \ge \sigma_0 > 0 and ∥J(q)∥≤ΓJ\|J(q)\| \le \Gamma_J; ∥DG(q)∥≤Γ\|DG(q)\| \le \Gamma; (B2) holds; and (B3) holds. Let D=(LΓΓJ+H/2)/σ0D = (L\Gamma\Gamma_J + H/2)/\sigma_0. If q0∈B∗q_0 \in B^* and D∣q0−q∗∣<1D|q_0 - q^*| < 1, then ∣qk+1−q∗∣≤D∣qk−q∗∣2|q_{k+1} - q^*| \le D|q_k - q^*|^2 for every kk, and qk→q∗q_k \to q^*.

Proof. Let q=qk∈B∗q = q_k \in B^* and h=q∗−qh = q^* - q. By (B2) on the segment from qq to q∗q^*, 0=G(q∗)=G(q)+DG(q)h+r0 = G(q^*) = G(q) + DG(q)h + r with ∣r∣≤H2∣h∣2|r| \le \tfrac{H}{2}|h|^2, so G(q)=A(q)J(q)h−rG(q) = A(q)J(q)h - r. By Corollary 2, J+J=IJ^{+}J = I, so

δ=J+G(q)=h+J+(A(q)−I)Jh−J+r.\delta = J^{+}G(q) = h + J^{+}(A(q) - I)J h - J^{+}r.

By the mean value inequality, ∣G(q)∣=∣G(q)−G(q∗)∣≤Γ∣h∣|G(q)| = |G(q) - G(q^*)| \le \Gamma|h|, so ∥A(q)−I∥≤LΓ∣h∣\|A(q) - I\| \le L\Gamma|h|. Hence ∣q+δ−q∗∣=∣δ−h∣≤1σ0(LΓ∣h∣ ΓJ∣h∣+H2∣h∣2)=D∣h∣2|q + \delta - q^*| = |\delta - h| \le \frac{1}{\sigma_0}\big(L\Gamma|h|\,\Gamma_J|h| + \tfrac{H}{2}|h|^2\big) = D|h|^2. If D∣h∣<1D|h| < 1, then ∣qk+1−q∗∣≤D∣h∣2<∣h∣≤R|q_{k+1} - q^*| \le D|h|^2 < |h| \le R, so qk+1∈B∗q_{k+1} \in B^* and D∣qk+1−q∗∣<D∣h∣<1D|q_{k+1} - q^*| < D|h| < 1. By induction the bound holds for every kk, and D∣qk−q∗∣≤(D∣q0−q∗∣)2k→0D|q_k - q^*| \le (D|q_0 - q^*|)^{2^k} \to 0. □\square

For a square JJ both theorems apply, and Theorem 5 is the classical local quadratic convergence of Newton's method.

What the theorems do not give

Both results are local. They need a start where the error is small compared with σ02/H\sigma_0^2/H, and they say nothing about starts far from every solution, about targets out of reach, or about singular solutions where σ0=0\sigma_0 = 0. In those cases the iteration can move far, cycle, or approach a singular configuration where the steps blow up, and the loop of the page ends with FAILURE after kmax⁡k_{\max} iterations.

Complexity

Each iteration evaluates T(q)T(q) and Jb(q)J_b(q) in Θ(n)\Theta(n) operations for a task of fixed size, the logarithm in Θ(1)\Theta(1), and the step J+eJ^{+}e. With a QR decomposition of JTJ^{\mathsf T} (full row rank) or of JJ (full column rank), or a singular value decomposition with a bounded number of sweeps, the step costs Θ(mnmin⁡(m,n))\Theta(mn\min(m, n)). So kk iterations cost Θ(k mnmin⁡(m,n))\Theta(k\,m n \min(m, n)) in the real RAM, with Θ(mn)\Theta(mn) extra space. The one-sided Jacobi decomposition of the code on this page also keeps an n×nn \times n matrix of rotations, so it uses Θ(n2)\Theta(n^2) more space and Θ(n2(m+n))\Theta(n^2(m + n)) operations per sweep. Because of the quadratic convergence, a start within the basin of a solution needs only a handful of iterations to reach full precision, as the examples show.

Properties

  • Local and fast. Near a nonsingular solution, the number of correct digits roughly doubles at each iteration.
  • Least norm steps. For a redundant arm, each step is the smallest joint motion that does the job to first order, which keeps the joints from drifting along the self-motion. The final solution is not the solution nearest to q0q_0, only the end of a path of least norm steps.
  • One answer. The method returns one solution, the one whose basin contains q0q_0; to find others, restart from other guesses.
  • Frame consistent. With the body twist error and the body Jacobian, both in the end effector frame, the result does not depend on the choice of the base frame.
  • Not robust at singularities. As σmin⁡(J)→0\sigma_{\min}(J) \to 0, the steps grow like 1/σmin⁡1/\sigma_{\min}; a target out of reach drives the arm to a singular pose.

Variants and improvements

  • Damped least squares. Replace J+J^{+} by JT(JJT+λ2I)−1J^{\mathsf T}(JJ^{\mathsf T} + \lambda^2 I)^{-1}, the Levenberg-Marquardt step of damped least squares inverse kinematics; it trades speed for robustness near singularities and out of reach. See also Levenberg-Marquardt.
  • The transpose. Use Δq=αJTe\Delta q = \alpha J^{\mathsf T}e, a gradient step on ∣e∣2/2|e|^2/2, in the Jacobian transpose method; it needs no inverse but converges only linearly.
  • A secondary goal. Add (I−J+J)z(I - J^{+}J)z to each step to pull a redundant arm toward a preferred posture; see null space projection and task priority inverse kinematics.
  • Step control. Scale the step or search along it to keep ∣e∣|e| decreasing, which enlarges the basin of convergence; limit the step of each joint to keep it inside its range.
  • The space form. The space twist error Vs=Ad⁡T(q)Vb\mathcal V_s = \operatorname{Ad}_{T(q)}\mathcal V_b with the space Jacobian Js=Ad⁡T(q)JbJ_s = \operatorname{Ad}_{T(q)}J_b gives the same step when JbJ_b has full row rank, because then Js+=Jb+Ad⁡T(q)−1J_s^{+} = J_b^{+}\operatorname{Ad}_{T(q)}^{-1}; for other ranks the two steps can differ.
  • Square arms. For n=mn = m and a nonsingular JJ, the method is the Newton-Raphson inverse kinematics iteration.
  • Rate control. Used once per control step with a small gain in place of the full step, the same formula is resolved-rate motion control.

When to use it

Use the pseudoinverse method when an arm has no closed form inverse kinematics, or has more joints than the task, and a reasonable initial guess is at hand: the present configuration, the last solution along a path, or a guess from a coarse table. If the target may be out of reach or close to a singularity, prefer damped least squares; if all solutions are needed, use an analytic method for the arm or many restarts.

Pitfalls

  • Units. For a pose task, the error mixes radians and meters, and J+J^{+} minimizes a joint norm that mixes radians and, for prismatic joints, meters. Scale the rows and columns on purpose.
  • Frames. Vb\mathcal V_b and JbJ_b must be in the same frame and the same order; a space twist error with a body Jacobian, or the linear part first in one and last in the other, breaks the convergence without an error.
  • The rank tolerance. If the pseudoinverse keeps tiny singular values, the step can be huge near a singularity; if it drops singular values that are only small, the step loses a direction. The cut, here 10−10σmax⁡10^{-10}\sigma_{\max}, is a rule of thumb.
  • Joint wrapping. Revolute joint values can grow by multiples of 2π2\pi; wrap them into the range of the joints after the loop.
  • Joint limits. The plain method does not see them, and it can return a solution outside the range of a joint.
  • No convergence. A target out of reach, or a start far from every solution, leads to steps that jump around; bound the number of iterations and report FAILURE.

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.

jacobian_pseudoinverse_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-pseudoinverse-method/. The authors are listed in prov/MNF4KJ.jsonl.
"""Inverse kinematics by repeated pseudoinverse steps.

- pinv(a, rtol) is the Moore-Penrose pseudoinverse of any matrix, from a
  one-sided Jacobi singular value decomposition. Singular values at most
  rtol times the largest one count as zero.
- ik_pose(m, blist, t_d, q0, ...) is the algorithm of the page: the error
  is the body twist V_b = log(T(q)^-1 T_d), and the step is J_b^+ V_b.
  This is the numerical inverse kinematics algorithm of Lynch and Park,
  Modern Robotics, Section 6.2.2.
- ik_position(fk, jac, x_d, q0, ...) is the same loop for a position task
  x = fk(q) in R^m, with the error x_d - fk(q).

The arm is in the product of exponentials form: T(q) = M exp([B1] q1) ...
exp([Bn] qn) with body screw axes B_i = (omega, v), angular part first.
Matrices are lists of rows. ik_pose and ik_position return None when they
do not reach the tolerance within max_iter steps.
"""

import math

import rbm


def _columns(a):
    return [list(c) for c in zip(*a)]


def svd(a, sweeps=60):
    """Return (u_cols, sigma, v_cols) with a = sum_j sigma_j u_j v_j^T.

    One-sided Jacobi (Hestenes): rotate pairs of columns of a until all
    columns are orthogonal. The rotations are collected in v. u_j is the
    column j divided by its norm sigma_j; for sigma_j = 0, u_j is zero.
    """
    m, n = len(a), len(a[0])
    w = _columns(a)  # n columns of length m
    v = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)]  # columns of V
    for _ in range(sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                alpha = rbm.dot(w[p], w[p])
                beta = rbm.dot(w[r], w[r])
                gamma = rbm.dot(w[p], w[r])
                if gamma == 0.0 or abs(gamma) <= 1e-15 * math.sqrt(alpha * beta):
                    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
                for vec in (w, v):
                    x, y = vec[p], vec[r]
                    vec[p] = [c * xi - s * yi for xi, yi in zip(x, y)]
                    vec[r] = [s * xi + c * yi for xi, yi in zip(x, y)]
        if not rotated:
            break
    sigma = [rbm.norm(col) for col in w]
    u = [[x / s for x in col] if s > 0.0 else [0.0] * m for col, s in zip(w, sigma)]
    return u, sigma, v


def pinv(a, rtol=1e-10):
    """Return the n by m pseudoinverse of the m by n matrix a.

    a^+ = sum over sigma_j > rtol * max(sigma) of v_j u_j^T / sigma_j.
    """
    m, n = len(a), len(a[0])
    u, sigma, v = svd(a)
    smax = max(sigma) if sigma else 0.0
    out = rbm.zeros(n, m)
    for uj, sj, vj in zip(u, sigma, v):
        if sj > rtol * smax and sj > 0.0:
            for i in range(n):
                f = vj[i] / sj
                if f != 0.0:
                    row = out[i]
                    for k in range(m):
                        row[k] += f * uj[k]
    return out


def fk_body(m, blist, q):
    """Return T(q) = M exp([B1] q1) ... exp([Bn] qn)."""
    t = [row[:] for row in m]
    for b, x in zip(blist, q):
        t = rbm.mul(t, rbm.se3_exp([y * x for y in b]))
    return t


def body_jacobian(blist, q):
    """Return the 6 by n body Jacobian; column i is Ad of exp(-[B_n] q_n)...exp(-[B_i+1] q_i+1) applied to B_i."""
    n = len(blist)
    t = rbm.eye(4)
    cols = [None] * n
    for i in range(n - 1, -1, -1):
        cols[i] = rbm.matvec(rbm.adjoint(t), blist[i])
        t = rbm.mul(t, rbm.se3_exp([-y * q[i] for y in blist[i]]))
    return rbm.transpose(cols)


def ik_pose(m, blist, t_d, q0, eps_w=1e-10, eps_v=1e-10, max_iter=100, rtol=1e-10):
    """Return joint values q with T(q) = t_d within (eps_w, eps_v), or None."""
    q = [float(x) for x in q0]  # @line L1
    for _ in range(max_iter):  # @line L2
        vb = rbm.se3_log(rbm.mul(rbm.T_inv(fk_body(m, blist, q)), t_d))  # @line L3
        if rbm.norm(vb[:3]) <= eps_w and rbm.norm(vb[3:]) <= eps_v:  # @line L4
            return q
        jb = body_jacobian(blist, q)  # @line L5
        step = rbm.matvec(pinv(jb, rtol), vb)
        q = [x + d for x, d in zip(q, step)]  # @line L6
    return None  # @line L7


def ik_position(fk, jac, x_d, q0, eps=1e-11, max_iter=100, rtol=1e-10):
    """Return q with |x_d - fk(q)| <= eps, or None, by steps q <- q + J^+ e."""
    q = [float(x) for x in q0]
    for _ in range(max_iter):
        e = rbm.sub(x_d, fk(q))
        if rbm.norm(e) <= eps:
            return q
        step = rbm.matvec(pinv(jac(q), rtol), e)
        q = [x + d for x, d in zip(q, step)]
    return None
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

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

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

import math

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

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

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


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


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


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


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


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


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


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


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


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


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


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

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


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


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


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

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


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


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


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


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


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


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


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


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


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


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


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


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

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


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

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


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


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


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


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


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


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

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


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

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


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


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


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


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

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


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

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


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


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

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


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


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_jacobian_pseudoinverse_method.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-pseudoinverse-method/. The authors are listed in prov/MNF4KJ.jsonl.
"""Tests of pseudoinverse inverse kinematics: the Penrose conditions, the
minimum-norm step against a KKT solve, the 2R check values, a 7R position
task, a 6R full pose task, and failure on a target out of reach."""

import math
import random

import rbm
from jacobian_pseudoinverse_method import body_jacobian, fk_body, ik_pose, ik_position, pinv, svd


def maxdiff(a, b):
    if a and isinstance(a[0], list):
        return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    return max(abs(x - y) for x, y in zip(a, b))


def rand_matrix(rng, m, n):
    return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]


def rand_unit(rng):
    while True:
        v = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        n = rbm.norm(v)
        if 0.2 < n <= 1.0:
            return [x / n for x in v]


def rand_screws(rng, n):
    """Revolute screw axes S = (omega, -omega x p) in the space frame."""
    out = []
    for _ in range(n):
        w = rand_unit(rng)
        p = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        out.append(w + rbm.cross(p, w))
    return out


def fk_space(slist, m, q):
    t = rbm.eye(4)
    for s, x in zip(slist, q):
        t = rbm.mul(t, rbm.se3_exp([y * x for y in s]))
    return rbm.mul(t, m)


def space_jacobian(slist, q):
    t = rbm.eye(4)
    cols = []
    for s, x in zip(slist, q):
        cols.append(rbm.matvec(rbm.adjoint(t), s))
        t = rbm.mul(t, rbm.se3_exp([y * x for y in s]))
    return rbm.transpose(cols)


def position_jacobian(slist, m, q):
    """Rows of p' = v_s + omega x p, the velocity of the tool point."""
    js = space_jacobian(slist, q)
    t = fk_space(slist, m, q)
    p = [t[0][3], t[1][3], t[2][3]]
    out = rbm.zeros(3, len(q))
    for c in range(len(q)):
        w = [js[i][c] for i in range(3)]
        v = [js[i + 3][c] for i in range(3)]
        col = rbm.add(v, rbm.cross(w, p))
        for i in range(3):
            out[i][c] = col[i]
    return out


def fk2(q):
    return [math.cos(q[0]) + math.cos(q[0] + q[1]), math.sin(q[0]) + math.sin(q[0] + q[1])]


def jac2(q):
    s1, c1 = math.sin(q[0]), math.cos(q[0])
    s12, c12 = math.sin(q[0] + q[1]), math.cos(q[0] + q[1])
    return [[-s1 - s12, -s12], [c1 + c12, c12]]


def penrose(a, x, tol):
    ax = rbm.mul(a, x)
    xa = rbm.mul(x, a)
    assert maxdiff(rbm.mul(ax, a), a) < tol
    assert maxdiff(rbm.mul(xa, x), x) < tol
    assert maxdiff(ax, rbm.transpose(ax)) < tol
    assert maxdiff(xa, rbm.transpose(xa)) < tol


def test_svd_reconstructs():
    rng = random.Random(1)
    for m, n in [(2, 3), (3, 7), (6, 6), (6, 7), (4, 2)]:
        a = rand_matrix(rng, m, n)
        u, s, v = svd(a)
        back = rbm.zeros(m, n)
        for uj, sj, vj in zip(u, s, v):
            for i in range(m):
                for k in range(n):
                    back[i][k] += sj * uj[i] * vj[k]
        assert maxdiff(back, a) < 1e-12


def test_pinv_penrose_conditions():
    rng = random.Random(2)
    for m, n in [(2, 3), (3, 7), (6, 7), (5, 3)]:
        a = rand_matrix(rng, m, n)
        penrose(a, pinv(a), 1e-11)
    # rank 2 matrix of size 3 by 5: the product of 3x2 and 2x5 factors
    a = rbm.mul(rand_matrix(rng, 3, 2), rand_matrix(rng, 2, 5))
    x = pinv(a)
    penrose(a, x, 1e-10)
    # the zero matrix has the zero pseudoinverse
    assert maxdiff(pinv(rbm.zeros(2, 3)), rbm.zeros(3, 2)) == 0.0


def test_pinv_against_closed_forms():
    rng = random.Random(3)
    a = rand_matrix(rng, 3, 6)
    assert maxdiff(pinv(a), rbm.pinv_right(a)) < 1e-11
    b = rand_matrix(rng, 4, 4)
    assert maxdiff(pinv(b), rbm.inv(b)) < 1e-9
    # tall matrix with full column rank: (A^T A)^-1 A^T
    c = rand_matrix(rng, 5, 2)
    ct = rbm.transpose(c)
    assert maxdiff(pinv(c), rbm.mul(rbm.inv(rbm.mul(ct, c)), ct)) < 1e-11


def test_step_is_minimum_norm():
    rng = random.Random(4)
    for _ in range(5):
        j = rand_matrix(rng, 3, 7)
        e = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        step = rbm.matvec(pinv(j), e)
        # KKT system of min |d|^2 / 2 subject to J d = e
        kkt = rbm.zeros(10, 10)
        for i in range(7):
            kkt[i][i] = 1.0
        for r in range(3):
            for c in range(7):
                kkt[7 + r][c] = j[r][c]
                kkt[c][7 + r] = j[r][c]
        sol = rbm.solve(kkt, [0.0] * 7 + e)
        assert maxdiff(step, sol[:7]) < 1e-11
        # any other solution step + n with J n = 0 is longer
        nul = rbm.sub(rbm.eye(7), rbm.mul(pinv(j), j))
        z = [rng.uniform(-1.0, 1.0) for _ in range(7)]
        other = rbm.add(step, rbm.matvec(nul, z))
        assert maxdiff(rbm.matvec(j, other), e) < 1e-11
        assert rbm.norm(other) >= rbm.norm(step)


def test_2r_check_values():
    q = [0.0, math.pi / 2.0]
    assert maxdiff(fk2(q), [1.0, 1.0]) < 1e-15
    assert maxdiff(jac2(q), [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15
    assert maxdiff(rbm.num_jacobian(fk2, [0.4, 1.1]), jac2([0.4, 1.1])) < 1e-6


def test_2r_reaches_both_solutions():
    up = ik_position(fk2, jac2, [1.0, 1.0], [0.3, 1.2])
    assert up is not None
    assert maxdiff(up, [0.0, math.pi / 2.0]) < 1e-9
    down = ik_position(fk2, jac2, [1.0, 1.0], [1.3, -1.2])
    assert down is not None
    assert maxdiff(down, [math.pi / 2.0, -math.pi / 2.0]) < 1e-9
    for q in (up, down):
        assert maxdiff(fk2(q), [1.0, 1.0]) < 1e-9


def test_2r_out_of_reach_fails():
    assert ik_position(fk2, jac2, [2.5, 0.0], [0.2, 0.5], max_iter=50) is None


def test_7r_position_round_trip():
    rng = random.Random(7)
    slist = rand_screws(rng, 7)
    m = rbm.make_T(rbm.eye(3), [1.0, 0.5, 0.2])

    def fk(q):
        t = fk_space(slist, m, q)
        return [t[0][3], t[1][3], t[2][3]]

    def jac(q):
        return position_jacobian(slist, m, q)

    q = [rng.uniform(-1.0, 1.0) for _ in range(7)]
    assert maxdiff(rbm.num_jacobian(fk, q), jac(q)) < 1e-6
    for _ in range(4):
        q_true = [rng.uniform(-math.pi, math.pi) for _ in range(7)]
        x_d = fk(q_true)
        q0 = [x + rng.uniform(-0.3, 0.3) for x in q_true]
        q = ik_position(fk, jac, x_d, q0)
        assert q is not None
        assert maxdiff(fk(q), x_d) < 1e-9


def test_body_jacobian_against_finite_differences():
    rng = random.Random(8)
    slist = rand_screws(rng, 6)
    m = rbm.make_T(rbm.rot_z(0.3), [0.5, 0.2, 0.7])
    blist = [rbm.matvec(rbm.adjoint(rbm.T_inv(m)), s) for s in slist]
    q = [rng.uniform(-1.0, 1.0) for _ in range(6)]
    t = fk_body(m, blist, q)
    assert maxdiff(t, fk_space(slist, m, q)) < 1e-12
    h = 1e-6
    ti = rbm.T_inv(t)
    jb = body_jacobian(blist, q)
    for i in range(6):
        qp, qm = list(q), list(q)
        qp[i] += h
        qm[i] -= h
        d = rbm.scale(rbm.sub(fk_body(m, blist, qp), fk_body(m, blist, qm)), 1.0 / (2.0 * h))
        col = rbm.vee6(rbm.mul(ti, d))
        assert maxdiff(col, [row[i] for row in jb]) < 1e-6


def test_6r_full_pose_round_trip():
    rng = random.Random(9)
    slist = rand_screws(rng, 6)
    m = rbm.make_T(rbm.rot_x(0.4), [0.6, -0.2, 0.9])
    blist = [rbm.matvec(rbm.adjoint(rbm.T_inv(m)), s) for s in slist]
    for _ in range(4):
        q_true = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
        t_d = fk_body(m, blist, q_true)
        q0 = [x + rng.uniform(-0.2, 0.2) for x in q_true]
        q = ik_pose(m, blist, t_d, q0)
        assert q is not None
        assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9


def test_planar_pose_check_values():
    # The 2R arm as a spatial chain: body screws of the page, M = (I, (2, 0, 0)).
    m = rbm.make_T(rbm.eye(3), [2.0, 0.0, 0.0])
    blist = [[0.0, 0.0, 1.0, 0.0, 2.0, 0.0], [0.0, 0.0, 1.0, 0.0, 1.0, 0.0]]
    t_d = rbm.make_T(rbm.rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    q = ik_pose(m, blist, t_d, [0.2, 1.3])
    assert q is not None
    assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-9

History

Penrose (1955) defined the generalized inverse by four equations and showed that it gives the least squares solution of least norm, which is the step of this method. Whitney (1969) resolved end effector rates into joint rates through the inverse of the Jacobian, and the same linear step, repeated until the pose error vanishes, solves the position problem. Klein and Huang (1983) reviewed pseudoinverse control of redundant arms, and later work added damping near singularities. Lynch and Park (2017) present the loop of this page, with the body twist error from the matrix logarithm, as their numerical inverse kinematics algorithm.

References

  1. Roger Penrose, A generalized inverse for matrices, Mathematical Proceedings of the Cambridge Philosophical Society 51(3), 406-413, 1955, the whole paper (the four equations that define the generalized inverse, and the least squares solution of least norm)
  2. Kevin M. Lynch and Frank C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 6, Section 6.2 (numerical inverse kinematics, the Newton-Raphson method in 6.2.1 and the numerical inverse kinematics algorithm with the body twist error and the pseudoinverse in 6.2.2)
  3. Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.5 (the pseudoinverse solution of the differential kinematics) and Section 3.7 (inverse kinematics algorithms)
  4. Daniel E. Whitney, Resolved motion rate control of manipulators and human prostheses, IEEE Transactions on Man-Machine Systems, 1969, the whole paper (joint rates from the inverse of the Jacobian)

Where this leads

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