Algorithm Search⌘K

Algorithmcore

Newton-Raphson inverse kinematics

Also called numerical inverse kinematics.

Solves the pose equations by Newton steps with the body Jacobian and the matrix logarithm of the pose error, from an initial guess.

Time
Θ(k n^3) worst
Space
Θ(n^2) extra
Where
k = the number of iterations; n = the number of joints and of task coordinates
Properties
deterministicofflineiterative
Origin
Donald L. Pieper, 1968

Newton-Raphson inverse kinematics finds joint values θ\theta with T(θ)=TdT(\theta) = T_d for a target pose TdT_d, starting from a guess θ0\theta^0. At each step it measures the pose error as a twist Vb\mathcal V_b, the matrix logarithm of T(θ)−1TdT(\theta)^{-1}T_d. Then it solves a linear system with the body Jacobian Jb(θ)J_b(\theta) for a joint step and adds the step to θ\theta. Near a solution where JbJ_b is invertible, the error falls quadratically, so a few steps reach full machine precision. The method finds one solution, the one that the guess leads to, and it can fail from a poor guess or at a kinematic singularity.

In plain words

You want the arm to put its hand at a given place and in a given direction. You start from a guess for the joints and look at where the hand is now. The gap between where the hand is and where it should be tells you how to turn the joints, if the arm moved in straight lines. The arm does not move in straight lines, so one correction is not exact, but it brings the hand much closer. You repeat the correction. When the guess is already close, each correction roughly doubles the number of correct digits. When the guess is far, the corrections can jump around, and the hand may end at another of the poses that reach the target, or nowhere.

The problem

Input.

  • An arm with nn joints in the body form of the product of exponentials, T(θ)=Me[B1]θ1⋯e[Bn]θnT(\theta) = Me^{[\mathcal B_1]\theta_1}\cdots e^{[\mathcal B_n]\theta_n}. Here MM is the home pose of the end effector and Bi=(ωi,vi)\mathcal B_i = (\omega_i, v_i) is the screw axis of joint ii in the end effector frame, with the angular part first.
  • A target pose TdT_d and an initial guess θ0\theta^0.
  • Tolerances εω\varepsilon_\omega and εv\varepsilon_v, and a step limit kmax⁡k_{\max}.

Output. A θ\theta with ∣ωb∣≤εω|\omega_b| \le \varepsilon_\omega and ∣vb∣≤εv|v_b| \le \varepsilon_v, where (ωb,vb)=log⁡(T(θ)−1Td)(\omega_b, v_b) = \log(T(\theta)^{-1}T_d), or FAILURE.

The algorithm below is for a full pose with n=6n = 6, so that JbJ_b is square. For a position task x(θ)=xdx(\theta) = x_d with as many joints as coordinates, the same loop uses the error xd−x(θ)x_d - x(\theta) and the Jacobian of xx. For an arm with more joints than task coordinates, the linear solve is replaced by a pseudoinverse, which is the Jacobian pseudoinverse method used as an iteration.

The algorithm

  1. NEWTON-RAPHSON-IK(M, B_1..B_n, T_d, θ0, ε_ω, ε_v, k_max)
  2. 1θ ← θ0
  3. 2for k ← 1 to k_max
  4. 3V_b ← log(T(θ)^-1 T_d) ▷ the pose error as a body twist (ω_b, v_b)
  5. 4if |ω_b| ≤ ε_ω and |v_b| ≤ ε_v then return θ
  6. 5J_b ← BODY-JACOBIAN(θ)
  7. 6solve J_b Δθ = V_b
  8. 7if J_b is singular then return FAILURE
  9. 8θ ← θ + Δθ
  10. 9return FAILURE

Line L3 uses the exponential map of SE(3) in reverse: Vb\mathcal V_b is the twist that, followed for unit time from the present pose, gives the target pose. Line L5 builds the body Jacobian column by column, with Jb,n=BnJ_{b,n} = \mathcal B_n and Jb,i=Ade−[Bn]θn⋯e−[Bi+1]θi+1BiJ_{b,i} = \mathrm{Ad}_{e^{-[\mathcal B_n]\theta_n}\cdots e^{-[\mathcal B_{i+1}]\theta_{i+1}}}\mathcal B_i. Line L6 is one Gaussian elimination with partial pivoting. In floating point, L7 means that a pivot is zero or close to zero.

Example

A planar arm. Take the 2R arm with link lengths L1=L2=1L_1 = L_2 = 1 m, with the hand at x(θ)=(cos⁡θ1+cos⁡(θ1+θ2),sin⁡θ1+sin⁡(θ1+θ2))x(\theta) = (\cos\theta_1 + \cos(\theta_1 + \theta_2), \sin\theta_1 + \sin(\theta_1 + \theta_2)). The target (1,1)(1, 1) m has two solutions, (0,π/2)(0, \pi/2) and (π/2,−π/2)(\pi/2, -\pi/2). At (0,π/2)(0, \pi/2) the Jacobian is [[−1,−1],[1,0]][[-1, -1], [1, 0]] with determinant 1.

Start at θ0=(0.3,1.2)\theta^0 = (0.3, 1.2) rad. The hand is at (1.026073,1.293015)(1.026073, 1.293015), so the error is (−0.026073,−0.293015)(-0.026073, -0.293015) with norm 0.2940.294. The Jacobian is [[−1.2930,−0.9975],[1.0261,0.0707]][[-1.2930, -0.9975], [1.0261, 0.0707]], and the step is Δθ=(−0.315572,0.435203)\Delta\theta = (-0.315572, 0.435203).

step 0 1 2 3 4
error (m) 0.294 0.0517 0.00119 7.05e-7 2.48e-13

The iteration ends at (0,π/2)(0, \pi/2). Each error is about a constant times the square of the one before, which is quadratic convergence. From θ0=(1.3,−1.2)\theta^0 = (1.3, -1.2) the errors are 0.270, 0.0444, 8.35e-4, 3.44e-7 and 5.92e-14, and the iteration ends at the other solution (π/2,−π/2)(\pi/2, -\pi/2).

An elbow arm. Take the 6R elbow arm of the Paden-Kahan subproblems page, with M=(I,(0,2.5,1))M = (I, (0, 2.5, 1)) in m. Its body screw axes are B1=(0,0,1,−2.5,0,0)\mathcal B_1 = (0, 0, 1, -2.5, 0, 0), B2=(−1,0,0,0,0,−2.5)\mathcal B_2 = (-1, 0, 0, 0, 0, -2.5), B3=(−1,0,0,0,0,−1.5)\mathcal B_3 = (-1, 0, 0, 0, 0, -1.5), B4=(0,0,1,−0.5,0,0)\mathcal B_4 = (0, 0, 1, -0.5, 0, 0), B5=(−1,0,0,0,0,−0.5)\mathcal B_5 = (-1, 0, 0, 0, 0, -0.5) and B6=(0,1,0,0,0,0)\mathcal B_6 = (0, 1, 0, 0, 0, 0). The target is the pose of θ∗=(0.3,−0.4,0.9,0.5,0.7,−0.6)\theta^* = (0.3, -0.4, 0.9, 0.5, 0.7, -0.6) rad, with the position (−0.748090,1.797966,0.466418)(-0.748090, 1.797966, 0.466418) m.

  • From (0.5,−0.6,1.1,0.3,0.9,−0.8)(0.5, -0.6, 1.1, 0.3, 0.9, -0.8), the norms ∣Vb∣|\mathcal V_b| are 0.504, 0.0412, 8.27e-4, 7.14e-7 and 6.02e-13, and the iteration ends at θ∗\theta^*.
  • From (0,0,0.5,0,0.5,0)(0, 0, 0.5, 0, 0.5, 0), the norms are 1.6, 0.366, 1.22, 0.402, 0.0235, 2.98e-4, 6.9e-8 and 6.83e-15. The error grows at the third step, and then the quadratic phase starts; the iteration ends at θ∗\theta^*.
  • From (1,1,1,1,1,1)(1, 1, 1, 1, 1, 1), the iteration takes 11 evaluations and ends at angles that wrap to (0.3,−0.4,0.9,−2.641593,2.441593,2.541593)(0.3, -0.4, 0.9, -2.641593, 2.441593, 2.541593). This is the wrist flip of θ∗\theta^*, another of the 8 solutions in the table of the Paden-Kahan page. The raw angles before wrapping are as large as 524 rad, so wrap the output into the joint range.
  • From θ=0\theta = 0 the arm is stretched out and det⁡Jb=0\det J_b = 0, so the loop returns FAILURE at L7 after one evaluation.

A target out of reach. For the 2R arm and the target (2.5,0)(2.5, 0) m, which is farther than the reach of 2 m, the error never goes below 0.4 m and the loop returns FAILURE at L9.

Correctness

What a returned θ\theta means. The loop returns θ\theta only at L4, where ∣Vb∣|\mathcal V_b| is within the tolerances. Since exp⁡(log⁡X)=X\exp(\log X) = X, the pose T(θ)e[Vb]=TdT(\theta)e^{[\mathcal V_b]} = T_d is reached by a twist of size at most the tolerance from T(θ)T(\theta).

Local quadratic convergence. Let θ∗\theta^* be a solution with Jb(θ∗)J_b(\theta^*) invertible, and let g(θ)=log⁡(T(θ)−1Td)g(\theta) = \log(T(\theta)^{-1}T_d). Then g(θ∗)=0g(\theta^*) = 0, and near θ∗\theta^* the derivative of gg is Dg(θ)=−A(g(θ))Jb(θ)Dg(\theta) = -A(g(\theta))J_b(\theta), where AA is a smooth 6×66 \times 6 matrix function with A(0)=IA(0) = I. So the step of L6 differs from the exact Newton step for g=0g = 0 by a matrix that is I+O(∣g(θ)∣)I + O(|g(\theta)|). The proof page shows that there are r>0r > 0 and KK with ∣θk+1−θ∗∣≤K∣θk−θ∗∣2|\theta^{k+1} - \theta^*| \le K|\theta^k - \theta^*|^2 for every θk\theta^k within rr of θ∗\theta^*. So the errors go to zero quadratically when K∣θ0−θ∗∣<1K|\theta^0 - \theta^*| < 1. For the position task, g(θ)=xd−x(θ)g(\theta) = x_d - x(\theta) and Dg=−JDg = -J exactly, and this is the plain Newton method for systems.

What is not claimed. There is no guarantee from a far start: the iteration can cycle, diverge, stop at a singular JbJ_b, or converge to a solution other than the nearest one. If the target is out of reach, there is no solution and the loop cannot succeed. The radius rr depends on the arm, the target and the bound on ∣Jb−1∣|J_b^{-1}|, and it shrinks to zero as θ∗\theta^* approaches a singularity.

Proof: Newton-Raphson inverse kinematics converges quadratically near a solution with an invertible body Jacobianfull

We use the notation of the page, in exact arithmetic. The arm has n=6n = 6 joints, T(θ)=Me[B1]θ1⋯e[B6]θ6T(\theta) = Me^{[\mathcal B_1]\theta_1}\cdots e^{[\mathcal B_6]\theta_6}, and Jb(θ)J_b(\theta) is its body Jacobian. Norms of matrices are the operator norms of the vector norms.

Claim 1 (output). If the algorithm returns θ\theta, then Vb=log⁡(T(θ)−1Td)\mathcal V_b = \log(T(\theta)^{-1}T_d) satisfies ∣ωb∣≤εω|\omega_b| \le \varepsilon_\omega and ∣vb∣≤εv|v_b| \le \varepsilon_v, and T(θ)e[Vb]=TdT(\theta)e^{[\mathcal V_b]} = T_d.

Proof. The only return of a θ\theta is at L4, after the test on Vb\mathcal V_b. The logarithm returns a twist with e[Vb]=T(θ)−1Tde^{[\mathcal V_b]} = T(\theta)^{-1}T_d, so T(θ)e[Vb]=TdT(\theta)e^{[\mathcal V_b]} = T_d. □\square

The derivative of the error

Let g(θ)=log⁡(T(θ)−1Td)g(\theta) = \log(T(\theta)^{-1}T_d), defined and smooth on the set of θ\theta where the rotation angle of T(θ)−1TdT(\theta)^{-1}T_d is less than π\pi. This set is open and contains every solution θ∗\theta^*, since there T(θ∗)−1Td=IT(\theta^*)^{-1}T_d = I.

Lemma 1. On this set, Dg(θ)=−A(g(θ))Jb(θ)Dg(\theta) = -A(g(\theta))J_b(\theta), where AA is a smooth 6×66 \times 6 matrix function on the twists with rotation angle less than π\pi, and A(0)=IA(0) = I.

Proof. Write X(θ)=T(θ)−1TdX(\theta) = T(\theta)^{-1}T_d. By the definition of the body Jacobian, T−1∂T/∂θi=[Jb,i]T^{-1}\partial T/\partial\theta_i = [J_{b,i}], the twist of column ii in matrix form. Differentiating T−1T=IT^{-1}T = I gives ∂T−1/∂θi=−T−1(∂T/∂θi)T−1=−[Jb,i]T−1\partial T^{-1}/\partial\theta_i = -T^{-1}(\partial T/\partial\theta_i)T^{-1} = -[J_{b,i}]T^{-1}. So ∂X/∂θi=−[Jb,i]X\partial X/\partial\theta_i = -[J_{b,i}]X, a perturbation of XX on the left by the twist −Jb,i-J_{b,i}. The exponential map V↦e[V]V \mapsto e^{[V]} is a local diffeomorphism at every twist with rotation angle less than π\pi, so its inverse log⁡\log is smooth there. The derivative of log⁡\log at X=e[V]X = e^{[V]} along a left perturbation δX=[W]X\delta X = [W]X is a linear map W↦A(V)WW \mapsto A(V)W, smooth in VV. At V=0V = 0, e[V]=I+[V]+O(∣V∣2)e^{[V]} = I + [V] + O(|V|^2), so log⁡(I+[W])=W+O(∣W∣2)\log(I + [W]) = W + O(|W|^2) and A(0)=IA(0) = I. The chain rule gives ∂g/∂θi=A(g(θ))(−Jb,i)\partial g/\partial\theta_i = A(g(\theta))(-J_{b,i}). □\square

Local quadratic convergence

Claim 2. Let θ∗\theta^* be a solution with Jb(θ∗)J_b(\theta^*) invertible. There are r>0r > 0 and K≥0K \ge 0 such that, for every θ\theta with ∣θ−θ∗∣≤r|\theta - \theta^*| \le r, the matrix Jb(θ)J_b(\theta) is invertible and the step θ+=θ+Jb(θ)−1g(θ)\theta^+ = \theta + J_b(\theta)^{-1}g(\theta) of L6 and L8 satisfies ∣θ+−θ∗∣≤K∣θ−θ∗∣2|\theta^+ - \theta^*| \le K|\theta - \theta^*|^2.

Proof. Since JbJ_b is continuous and Jb(θ∗)J_b(\theta^*) is invertible, there are r0>0r_0 > 0 and β\beta such that, for ∣θ−θ∗∣≤r0|\theta - \theta^*| \le r_0, θ\theta is in the domain of gg, Jb(θ)J_b(\theta) is invertible and ∣Jb(θ)−1∣≤β|J_b(\theta)^{-1}| \le \beta. On the compact ball BB of radius r0r_0, the smooth functions gg, DgDg, D2gD^2g, JbJ_b and A∘gA \circ g are bounded, so there are constants γ\gamma, μ\mu and ν\nu with the three bounds below for θ∈B\theta \in B and e=θ−θ∗e = \theta - \theta^*.

  1. Taylor's theorem at θ\theta, applied to g(θ∗)=0g(\theta^*) = 0, gives 0=g(θ)−Dg(θ)e+R0 = g(\theta) - Dg(\theta)e + R with ∣R∣≤γ∣e∣2|R| \le \gamma|e|^2.
  2. Since g(θ∗)=0g(\theta^*) = 0 and DgDg is bounded on BB, ∣g(θ)∣≤μ∣e∣|g(\theta)| \le \mu|e|.
  3. Since AA is smooth with A(0)=IA(0) = I, ∣I−A(g(θ))∣≤ν∣g(θ)∣|I - A(g(\theta))| \le \nu|g(\theta)|, and ∣Jb(θ)∣≤ν|J_b(\theta)| \le \nu.

By Lemma 1 and bound 1, g(θ)=−A(g(θ))Jb(θ)e−Rg(\theta) = -A(g(\theta))J_b(\theta)e - R. So

θ+−θ∗=e+Jb−1g(θ)=Jb−1(I−A(g(θ)))Jbe−Jb−1R.\theta^+ - \theta^* = e + J_b^{-1}g(\theta) = J_b^{-1}\bigl(I - A(g(\theta))\bigr)J_be - J_b^{-1}R.

By bounds 2 and 3, the first term has norm at most β⋅νμ∣e∣⋅ν∣e∣=βν2μ∣e∣2\beta \cdot \nu\mu|e| \cdot \nu|e| = \beta\nu^2\mu|e|^2, and the second at most βγ∣e∣2\beta\gamma|e|^2. So the claim holds with r=r0r = r_0 and K=β(ν2μ+γ)K = \beta(\nu^2\mu + \gamma). □\square

Corollary. If ∣θ0−θ∗∣≤min⁡(r,1/(2K))|\theta^0 - \theta^*| \le \min(r, 1/(2K)), then every iterate stays in the ball, and ∣θk−θ∗∣≤21−2k/K|\theta^k - \theta^*| \le 2^{1 - 2^k}/K for k≥1k \ge 1.

Proof. Put dk=K∣θk−θ∗∣d_k = K|\theta^k - \theta^*|. Then d0≤1/2d_0 \le 1/2 and Claim 2 gives dk+1≤dk2d_{k+1} \le d_k^2, so dk≤d02k≤2−2kd_k \le d_0^{2^k} \le 2^{-2^k} by induction. Each dk≤d0d_k \le d_0, so ∣θk−θ∗∣≤∣θ0−θ∗∣≤r|\theta^k - \theta^*| \le |\theta^0 - \theta^*| \le r and Claim 2 applies again at every step. So ∣θk−θ∗∣≤2−2k/K≤21−2k/K|\theta^k - \theta^*| \le 2^{-2^k}/K \le 2^{1 - 2^k}/K. Since gg is continuous with g(θ∗)=0g(\theta^*) = 0, Vb→0\mathcal V_b \to 0, so the test of L4 succeeds after finitely many steps for any positive tolerances, and the algorithm returns a θ\theta as in Claim 1. □\square

The position task

For g(θ)=xd−x(θ)g(\theta) = x_d - x(\theta) with a square Jacobian JJ, Dg=−JDg = -J, so A=IA = I and the first term in the proof of Claim 2 is zero. The step is the exact Newton step, and the claim and the corollary hold with K=βγK = \beta\gamma.

Limits of the result

The result is local. It says nothing about starts outside the ball, where the examples of the page show growth of the error and convergence to another solution. If Jb(θ∗)J_b(\theta^*) is singular, β\beta does not exist, and the iteration can converge slowly or fail.

Complexity

One iteration computes T(θ)T(\theta) with nn matrix exponentials and products, JbJ_b with nn adjoint maps, one SE(3) logarithm, and one linear solve. The first three cost Θ(n)\Theta(n) in the real RAM, and the solve costs Θ(n3)\Theta(n^3) for an n×nn \times n system, so kk iterations cost Θ(kn3)\Theta(kn^3), and Θ(k)\Theta(k) for a fixed arm. The extra space is the Jacobian, Θ(n2)\Theta(n^2). The number of iterations kk is not bounded in general. Near a regular solution, quadratic convergence means that the number of iterations from a close start grows like log⁡log⁡(1/ε)\log\log(1/\varepsilon), which is why the examples above end in 4 or 5 steps once the error is small. The step counts in the examples are measured, not bounds.

Properties

  • One solution. The method returns at most one solution, the one in whose basin of attraction the guess lies.
  • Local. Convergence is local and quadratic near a regular solution, with no global guarantee.
  • No tuning. Apart from the tolerances and the step limit, there is no step size, gain or damping to choose.
  • Frame of the error. The error and the Jacobian are both in the end effector frame; the space form with Vs=AdTVb\mathcal V_s = \mathrm{Ad}_{T}\mathcal V_b and JsJ_s gives the same steps.
  • Singularities. At a singular JbJ_b the step is not defined, and near one the steps are very large.

Variants and improvements

  • Redundant arms. With more joints than task coordinates, replace the solve with the pseudoinverse step Δθ=Jb+Vb\Delta\theta = J_b^{+}\mathcal V_b, the Jacobian pseudoinverse method.
  • Damping. Damped least squares solves (JTJ+λ2I)Δθ=JTe(J^{\mathsf T}J + \lambda^2I)\Delta\theta = J^{\mathsf T}e and stays defined at singularities, at the cost of slower convergence; with λ\lambda chosen per step it is the Levenberg-Marquardt method.
  • Steepest descent. The Jacobian transpose method uses Δθ=αJTe\Delta\theta = \alpha J^{\mathsf T}e, which needs no solve but converges linearly.
  • Line search. Scaling the step by α∈(0,1]\alpha \in (0, 1] so that ∣Vb∣|\mathcal V_b| decreases makes the iteration more robust from a far start.
  • Restarts. Running the iteration from many random guesses finds several solutions, but with no guarantee of finding all of them.
  • Joint limits. Clamping or projecting θ\theta after each step keeps the joints in range, but it can stop the convergence.

When to use it

Use Newton-Raphson inverse kinematics when the arm has no closed form solution, a good guess is known, and the solution is regular, for example to refine an analytic solution, or to track a target that moves a little between calls, starting from the last solution. When the arm has a closed form, such as an arm with a spherical wrist, use kinematic decoupling or the Paden-Kahan subproblems, which return all solutions. When the arm may pass near a singularity, use damped least squares.

Pitfalls

  • The error. The error must be log⁡(T−1Td)\log(T^{-1}T_d), or an equivalent twist, not the difference Td−TT_d - T of the matrices, which has 12 entries and does not match the 6 columns of JJ.
  • The frames. The body twist goes with the body Jacobian, and the space twist with the space Jacobian; a mixed pair gives wrong steps away from the solution.
  • Units. εω\varepsilon_\omega is in rad and εv\varepsilon_v in m, so one tolerance on ∣Vb∣|\mathcal V_b| mixes units; keep two.
  • Angles that grow. The output angles can be far outside (−π,π](-\pi, \pi]; wrap them, and then check joint limits.
  • Far starts. A step from a far guess can be huge and land in another basin; limit the step size or use a line search.
  • The logarithm at π\pi. When the rotation error is close to π\pi, the logarithm is not smooth; a start with such a large rotation error needs care.

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.

newton_raphson_inverse_kinematics.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newton-raphson-inverse-kinematics/. The authors are listed in prov/85CD1Z.jsonl.
"""Inverse kinematics by Newton-Raphson steps.

- ik_newton(m, blist, t_d, q0, ...) is the algorithm of the page for an arm
  with as many joints as the task has dimensions (six for a full pose).
  The error is the body twist V_b = log(T(q)^-1 T_d) and the step solves
  J_b(q) dq = V_b. This is the Newton-Raphson method of Lynch and Park,
  Modern Robotics, Section 6.2, for a square Jacobian.
- newton_position(fk, jac, x_d, q0, ...) is the same loop for a position
  task x = fk(q) with as many joints as coordinates.

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.
Both functions return (q, history), where history lists the error norm
before each step, and q is None when the loop fails: the tolerance is not
met within max_iter steps, or the Jacobian is singular to working
precision.
"""

import rbm


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_newton(m, blist, t_d, q0, eps_w=1e-10, eps_v=1e-10, max_iter=50):
    """Return (q, history) with T(q) = t_d within (eps_w, eps_v), or (None, history)."""
    q = [float(x) for x in q0]  # @line L1
    history = []
    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
        history.append(rbm.norm(vb))
        if rbm.norm(vb[:3]) <= eps_w and rbm.norm(vb[3:]) <= eps_v:  # @line L4
            return q, history
        jb = body_jacobian(blist, q)  # @line L5
        try:
            step = rbm.solve(jb, vb)  # @line L6
        except ValueError:
            return None, history  # @line L7
        q = [x + d for x, d in zip(q, step)]  # @line L8
    return None, history  # @line L9


def newton_position(fk, jac, x_d, q0, eps=1e-12, max_iter=50):
    """Return (q, history) with |x_d - fk(q)| <= eps by steps J(q) dq = x_d - fk(q)."""
    q = [float(x) for x in q0]
    history = []
    for _ in range(max_iter):
        e = rbm.sub(x_d, fk(q))
        history.append(rbm.norm(e))
        if rbm.norm(e) <= eps:
            return q, history
        try:
            step = rbm.solve(jac(q), e)
        except ValueError:
            return None, history
        q = [x + d for x, d in zip(q, step)]
    return None, history
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_newton_raphson_inverse_kinematics.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newton-raphson-inverse-kinematics/. The authors are listed in prov/85CD1Z.jsonl.
"""Tests of Newton-Raphson inverse kinematics: the 2R check values against
the closed form, the body Jacobian against finite differences, quadratic
convergence on random 6R arms, the example of the page, and failure at a
singular start."""

import math
import random

import rbm
from newton_raphson_inverse_kinematics import body_jacobian, fk_body, ik_newton, newton_position


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 closed_form_2r(x, y):
    """All solutions of the unit 2R arm by the law of cosines."""
    c2 = (x * x + y * y - 2.0) / 2.0
    out = []
    for s in (1.0, -1.0):
        q2 = s * math.acos(c2)
        q1 = math.atan2(y, x) - math.atan2(math.sin(q2), 1.0 + math.cos(q2))
        out.append((q1, q2))
    return out


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 test_2r_check_values():
    j = jac2([0.0, math.pi / 2.0])
    assert maxdiff(j, [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15
    assert abs(rbm.det(j) - 1.0) < 1e-15
    assert maxdiff(fk2([0.0, math.pi / 2.0]), [1.0, 1.0]) < 1e-15
    q, hist = newton_position(fk2, jac2, [1.0, 1.0], [0.3, 1.2])
    for got, want in zip(hist, [0.294, 0.0517, 0.00119, 7.05e-7]):
        assert abs(got - want) < 0.005 * want
    assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-12
    q, _ = newton_position(fk2, jac2, [1.0, 1.0], [1.3, -1.2])
    assert maxdiff(q, [math.pi / 2.0, -math.pi / 2.0]) < 1e-12


def test_2r_against_closed_form():
    rng = random.Random(1)
    for _ in range(200):
        r = rng.uniform(0.3, 1.9)
        a = rng.uniform(-math.pi, math.pi)
        x, y = r * math.cos(a), r * math.sin(a)
        sols = closed_form_2r(x, y)
        q0 = [rng.uniform(-math.pi, math.pi), rng.uniform(-math.pi, math.pi)]
        q, _ = newton_position(fk2, jac2, [x, y], q0, max_iter=100)
        if q is None:
            continue
        assert maxdiff(fk2(q), [x, y]) < 1e-11
        assert min(max(abs(math.remainder(a - b, 2.0 * math.pi)) for a, b in zip(q, s)) for s in sols) < 1e-9


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_arm(rng, n=6):
    blist = []
    for _ in range(n):
        w = rand_unit(rng)
        p = [rng.uniform(-1.0, 1.0) for _ in range(3)]
        blist.append(w + rbm.cross(p, w))
    m = rbm.make_T(rbm.so3_exp([rng.uniform(-1.0, 1.0) for _ in range(3)]), [rng.uniform(-1.0, 1.0) for _ in range(3)])
    return m, blist


def test_body_jacobian_against_finite_differences():
    rng = random.Random(2)
    h = 1e-6
    for _ in range(5):
        m, blist = rand_arm(rng)
        q = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
        t_inv = rbm.T_inv(fk_body(m, blist, q))
        jb = body_jacobian(blist, q)
        for i in range(6):
            qp, qm = list(q), list(q)
            qp[i] += h
            qm[i] -= h
            dp = rbm.se3_log(rbm.mul(t_inv, fk_body(m, blist, qp)))
            dm = rbm.se3_log(rbm.mul(t_inv, fk_body(m, blist, qm)))
            col = [(a - b) / (2.0 * h) for a, b in zip(dp, dm)]
            assert maxdiff(col, [row[i] for row in jb]) < 1e-6


def test_quadratic_convergence_on_random_arms():
    rng = random.Random(3)
    done = 0
    for _ in range(12):
        m, blist = rand_arm(rng)
        q_star = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
        jb = body_jacobian(blist, q_star)
        if abs(rbm.det(jb)) < 0.1:
            continue  # too close to a singularity for a clean test
        t_d = fk_body(m, blist, q_star)
        q0 = [x + rng.uniform(-0.05, 0.05) for x in q_star]
        q, hist = ik_newton(m, blist, t_d, q0)
        assert q is not None and len(hist) <= 8
        assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9
        assert maxdiff(q, q_star) < 1e-8
        for a, b in zip(hist, hist[1:]):
            if a < 1e-2 and b > 1e-13:
                assert b <= 200.0 * a * a
        done += 1
    assert done >= 6


def elbow_arm():
    """The elbow arm of the page in body form: M = (I, (0, 2.5, 1)) and the body screw axes."""
    m = rbm.make_T(rbm.eye(3), [0.0, 2.5, 1.0])
    blist = [
        [0.0, 0.0, 1.0, -2.5, 0.0, 0.0],
        [-1.0, 0.0, 0.0, 0.0, 0.0, -2.5],
        [-1.0, 0.0, 0.0, 0.0, 0.0, -1.5],
        [0.0, 0.0, 1.0, -0.5, 0.0, 0.0],
        [-1.0, 0.0, 0.0, 0.0, 0.0, -0.5],
        [0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
    ]
    return m, blist


def test_example_of_the_page():
    m, blist = elbow_arm()
    q_star = [0.3, -0.4, 0.9, 0.5, 0.7, -0.6]
    t_d = fk_body(m, blist, q_star)
    assert maxdiff([t_d[i][3] for i in range(3)], [-0.748090, 1.797966, 0.466418]) < 1e-6
    q, hist = ik_newton(m, blist, t_d, [0.5, -0.6, 1.1, 0.3, 0.9, -0.8])
    for got, want in zip(hist, [0.504, 0.0412, 0.000827, 7.14e-7]):
        assert abs(got - want) < 0.005 * want
    assert maxdiff(q, q_star) < 1e-10
    # From a far start, the loop wanders and ends at another solution, the wrist flip.
    q, hist = ik_newton(m, blist, t_d, [1.0] * 6)
    assert q is not None and len(hist) == 11
    wrapped = [math.remainder(x, 2.0 * math.pi) for x in q]
    assert maxdiff(wrapped, [0.3, -0.4, 0.9, 0.5 - math.pi, math.pi - 0.7, -0.6 + math.pi]) < 1e-9
    assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9


def test_singular_start_fails():
    m, blist = elbow_arm()
    assert abs(rbm.det(body_jacobian(blist, [0.0] * 6))) < 1e-12
    t_d = fk_body(m, blist, [0.3, -0.4, 0.9, 0.5, 0.7, -0.6])
    q, hist = ik_newton(m, blist, t_d, [0.0] * 6)
    assert q is None and len(hist) == 1


def test_out_of_reach_fails():
    q, hist = newton_position(fk2, jac2, [2.5, 0.0], [0.2, 0.5], max_iter=50)
    assert q is None and min(hist) > 0.4

History

Pieper (1968) studied the kinematics of computer controlled arms in his Stanford thesis. Besides the closed form solution for arms with three intersecting axes, he described numerical methods for general arms, among them Newton-Raphson iteration. Iterative methods with the Jacobian then became the usual tool for arms with no closed form, in the forms of the pseudoinverse, the transpose and damped least squares. Lynch and Park (2017) give the modern form with the product of exponentials, the body Jacobian and the matrix logarithm of the pose error.

References

  1. 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 with the body Jacobian and the matrix logarithm)
  2. Donald L. Pieper, The Kinematics of Manipulators under Computer Control, PhD thesis, Stanford University, 1968 (Stanford Artificial Intelligence Memo AIM-72), Chapter IV, Section 4.1 (the Newton-Raphson method)

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