Algorithm Search⌘K

Algorithmadvanced

Paden-Kahan subproblems

Also called Paden-Kahan subproblem method.

Three geometric subproblems of rotating points about one or two axes, with closed solutions, to which many inverse kinematics reduce.

Time
Θ(n) worst
Space
Θ(1) extra
Where
n = the number of joints of an arm that splits into subproblems
Properties
deterministicofflineiterative
Origin
Bradley E. Paden, William Kahan, 1986

The Paden-Kahan subproblems are three small geometric problems about rotations of points, each with a closed form solution. Subproblem 1 finds the angle of one rotation that moves a point to another point. Subproblem 2 finds the angles of two rotations, about axes that meet, that move a point to another point. Subproblem 3 finds the angle of one rotation that brings a point to a given distance from another point. Many arms with six joints, among them most industrial arms, have an inverse kinematics that splits into a chain of these subproblems. The method then gives every solution, with no iteration and no starting guess.

In plain words

Pin a stick to a wall at one end, so that it can only swing in a circle. If you mark a point on the stick and another point on the circle, there is exactly one swing angle that carries the first point to the second. That is the first subproblem. The second subproblem uses two pins at the same place, one after the other, and asks for both angles. The third asks for the swing angles that put the point at a given distance from a fixed spot. Each answer comes from a short formula. For a robot arm, you choose points that some joints leave in place. Then the joints that do move them form one of these three problems, and you solve the arm a few joints at a time.

The problem

Input.

  • A revolute joint is a rotation about a line with a unit direction ω\omega through a point rr. The rotation by θ\theta takes a point xx to r+R(ω,θ)(x−r)r + R(\omega, \theta)(x - r), where R(ω,θ)=e[ω]θR(\omega, \theta) = e^{[\omega]\theta} by Rodrigues' formula. In twist form this is e[ξ]θxe^{[\xi]\theta}x with the screw axis ξ=(ω,−ω×r)\xi = (\omega, -\omega \times r).
  • Subproblem 1: one axis (ω,r)(\omega, r) and two points pp, qq. Find θ\theta with e[ξ]θp=qe^{[\xi]\theta}p = q.
  • Subproblem 2: two axes (ω1,r)(\omega_1, r) and (ω2,r)(\omega_2, r) that meet at rr and are not parallel, and two points pp, qq. Find all (θ1,θ2)(\theta_1, \theta_2) with e[ξ1]θ1e[ξ2]θ2p=qe^{[\xi_1]\theta_1}e^{[\xi_2]\theta_2}p = q.
  • Subproblem 3: one axis (ω,r)(\omega, r), two points pp, qq and a distance δ≥0\delta \ge 0. Find all θ\theta with ∣e[ξ]θp−q∣=δ|e^{[\xi]\theta}p - q| = \delta.

Output. The solutions, or the report that there are none. Subproblem 1 has 0 or 1 solution when pp is off the axis. Subproblems 2 and 3 have 0, 1 or 2.

Use on an arm. For an arm in the space form of the product of exponentials, T(θ)=e[S1]θ1⋯e[Sn]θnMT(\theta) = e^{[\mathcal S_1]\theta_1}\cdots e^{[\mathcal S_n]\theta_n}M, and a target pose TdT_d, the inverse kinematics asks for all θ\theta with T(θ)=TdT(\theta) = T_d. The trick is to apply both sides to a point that the last joints leave in place, or to compare distances that the first joints do not change.

The algorithm

  1. SUBPROBLEM-1(ω, r, p, q) ▷ θ with e^{[ξ]θ} p = q
  2. 1u ← p - r ; v ← q - r
  3. 2u' ← u - ω ω^T u ; v' ← v - ω ω^T v ▷ parts orthogonal to the axis
  4. 3if ω^T u ≠ ω^T v or |u'| ≠ |v'| then return NO SOLUTION
  5. 4return atan2(ω^T (u' × v'), u'^T v')
  6. SUBPROBLEM-2(ω1, ω2, r, p, q) ▷ θ1, θ2 with e^{[ξ1]θ1} e^{[ξ2]θ2} p = q
  7. 5u ← p - r ; v ← q - r ; k ← ω1^T ω2
  8. 6α ← (k ω2^T u - ω1^T v) / (k^2 - 1) ; β ← (k ω1^T v - ω2^T u) / (k^2 - 1)
  9. 7γ² ← (|u|^2 - α^2 - β^2 - 2αβk) / |ω1 × ω2|^2
  10. 8if γ² < 0 then return NO SOLUTION
  11. 9for γ in {+√γ², -√γ²} ▷ one value when γ² = 0
  12. 10c ← r + α ω1 + β ω2 + γ (ω1 × ω2) ▷ the point between the two rotations
  13. 11θ2 ← SUBPROBLEM-1(ω2, r, p, c) ; θ1 ← SUBPROBLEM-1(ω1, r, c, q)
  14. 12output (θ1, θ2)
  15. SUBPROBLEM-3(ω, r, p, q, δ) ▷ θ with |e^{[ξ]θ} p - q| = δ
  16. 13u ← p - r ; v ← q - r ; u', v' as in L2
  17. 14δ'^2 ← δ^2 - (ω^T (p - q))^2
  18. 15θ0 ← atan2(ω^T (u' × v'), u'^T v')
  19. 16c ← (|u'|^2 + |v'|^2 - δ'^2) / (2 |u'| |v'|)
  20. 17if |c| > 1 then return NO SOLUTION
  21. 18return θ0 - arccos c and θ0 + arccos c ▷ one angle when |c| = 1

Line L4 is the signed angle from u′u' to v′v' about ω\omega. Line L6 comes from two linear equations: the point cc rotates about ω2\omega_2 from pp and about ω1\omega_1 to qq, so ω2T(c−r)=ω2Tu\omega_2^{\mathsf T}(c - r) = \omega_2^{\mathsf T}u and ω1T(c−r)=ω1Tv\omega_1^{\mathsf T}(c - r) = \omega_1^{\mathsf T}v. Line L7 then fixes the length of c−rc - r to ∣u∣|u|. Lines L14 to L16 are the law of cosines in the plane orthogonal to the axis. In floating point, the tests in L3, L8 and L17 use a small tolerance, and the code on this page clamps cc into [−1,1][-1, 1] when it is out by less than the tolerance.

An elbow arm. The code on this page solves an arm with six revolute joints in the layout of Murray, Li and Sastry. Axis 1 is vertical through the base. Axes 2 and 3 are horizontal and parallel, through the shoulder qsq_s and the elbow. Axes 4, 5 and 6 meet at the wrist center qwq_w. The solution takes four steps.

  1. The last three joints fix qwq_w, so g1=TdM−1g_1 = T_dM^{-1} sends qwq_w to the place pw=g1qwp_w = g_1q_w that the first three joints must reach. The first two joints turn about axes through qsq_s, so they keep the distance to qsq_s, and ∣e[ξ3]θ3qw−qs∣=∣pw−qs∣|e^{[\xi_3]\theta_3}q_w - q_s| = |p_w - q_s|. Subproblem 3 gives up to two values of θ3\theta_3.
  2. Subproblem 2 on the axes 1 and 2, which meet at qsq_s, moves e[ξ3]θ3qwe^{[\xi_3]\theta_3}q_w to pwp_w and gives up to two pairs (θ1,θ2)(\theta_1, \theta_2).
  3. Now g2=(e[ξ1]θ1e[ξ2]θ2e[ξ3]θ3)−1g1=e[ξ4]θ4e[ξ5]θ5e[ξ6]θ6g_2 = (e^{[\xi_1]\theta_1}e^{[\xi_2]\theta_2}e^{[\xi_3]\theta_3})^{-1}g_1 = e^{[\xi_4]\theta_4}e^{[\xi_5]\theta_5}e^{[\xi_6]\theta_6}. A point pp on axis 6 is left in place by joint 6, so subproblem 2 on the axes 4 and 5 with pp and g2pg_2p gives up to two pairs (θ4,θ5)(\theta_4, \theta_5).
  4. Subproblem 1 on axis 6, with a point off that axis, gives θ6\theta_6.

This gives up to 2⋅2⋅2=82 \cdot 2 \cdot 2 = 8 solutions.

Example

Take the elbow arm with a base height, two arm links and a tool offset of l0=l1=l2=1l_0 = l_1 = l_2 = 1 and l3=0.5l_3 = 0.5. At θ=0\theta = 0, the shoulder is qs=(0,0,1)q_s = (0, 0, 1), the elbow (0,1,1)(0, 1, 1), the wrist center qw=(0,2,1)q_w = (0, 2, 1) and the tool point (0,2.5,1)(0, 2.5, 1). The axes are ω1=ω4=(0,0,1)\omega_1 = \omega_4 = (0, 0, 1), ω2=ω3=ω5=(−1,0,0)\omega_2 = \omega_3 = \omega_5 = (-1, 0, 0) and ω6=(0,1,0)\omega_6 = (0, 1, 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), with the position (−0.748090,1.797966,0.466418)(-0.748090, 1.797966, 0.466418).

  • Step 1: pw=(−0.531536,1.718310,0.909993)p_w = (-0.531536, 1.718310, 0.909993) and ∣pw−qs∣=1.800894|p_w - q_s| = 1.800894. With two unit links, ∣pw−qs∣2=2+2cos⁡θ3|p_w - q_s|^2 = 2 + 2\cos\theta_3, so cos⁡θ3=0.621610\cos\theta_3 = 0.621610, and subproblem 3 returns θ3=±0.9\theta_3 = \pm 0.9.
  • Step 2: for θ3=0.9\theta_3 = 0.9, subproblem 2 returns (θ1,θ2)=(0.3,−0.4)(\theta_1, \theta_2) = (0.3, -0.4) and (−2.841593,2.641593)(-2.841593, 2.641593), the shoulder turned by π\pi. For θ3=−0.9\theta_3 = -0.9 it returns (0.3,0.5)(0.3, 0.5) and (−2.841593,−2.741593)(-2.841593, -2.741593).
  • Steps 3 and 4 give two wrist solutions for each of the four arm solutions.
θ1\theta_1 θ2\theta_2 θ3\theta_3 θ4\theta_4 θ5\theta_5 θ6\theta_6
0.300000 -0.400000 0.900000 0.500000 0.700000 -0.600000
0.300000 -0.400000 0.900000 -2.641593 2.441593 2.541593
0.300000 0.500000 -0.900000 -1.336808 1.957305 -2.257324
0.300000 0.500000 -0.900000 1.804785 1.184287 0.884269
-2.841593 2.641593 0.900000 1.336808 -1.957305 0.884269
-2.841593 2.641593 0.900000 -1.804785 -1.184287 -2.257324
-2.841593 -2.741593 -0.900000 2.641593 -2.441593 -0.600000
-2.841593 -2.741593 -0.900000 -0.500000 -0.700000 2.541593

The forward kinematics of each row matches the target to within 3⋅10−153 \cdot 10^{-15}. In each pair of rows, the second wrist solution is the first one with θ4\theta_4 and θ6\theta_6 moved by π\pi and θ5\theta_5 replaced by π−θ5\pi - \theta_5, modulo 2π2\pi, which is the usual wrist flip.

Correctness

Subproblem 1. A rotation about ω\omega keeps the component of uu along ω\omega and turns the orthogonal part u′u' by θ\theta in the plane orthogonal to ω\omega. So a solution exists exactly when ωTu=ωTv\omega^{\mathsf T}u = \omega^{\mathsf T}v and ∣u′∣=∣v′∣|u'| = |v'|, and then θ\theta is the signed angle from u′u' to v′v', which L4 computes. If u′=0u' = 0, the point is on the axis and every θ\theta works.

Subproblem 2. If (θ1,θ2)(\theta_1, \theta_2) is a solution, put c=e[ξ2]θ2pc = e^{[\xi_2]\theta_2}p. Then z=c−rz = c - r has the same component along ω2\omega_2 as uu, the same component along ω1\omega_1 as vv, and the length ∣u∣|u|. Since ω1\omega_1, ω2\omega_2 and ω1×ω2\omega_1 \times \omega_2 form a basis, these three facts give z=αω1+βω2+γ(ω1×ω2)z = \alpha\omega_1 + \beta\omega_2 + \gamma(\omega_1 \times \omega_2) with α\alpha, β\beta from L6 and γ2\gamma^2 from L7. Conversely, each such cc meets the conditions of subproblem 1 twice, once for p→cp \to c about ω2\omega_2 and once for c→qc \to q about ω1\omega_1, so L11 gives a solution. So the solutions are in one to one correspondence with the real roots γ\gamma, and there are at most 2 when pp is off both axes.

Subproblem 3. The distance splits into the part along ω\omega, which the rotation does not change, and the part in the orthogonal plane. So ∣e[ξ]θp−q∣2=(ωT(p−q))2+∣u′∣2+∣v′∣2−2∣u′∣∣v′∣cos⁡(θ0−θ)|e^{[\xi]\theta}p - q|^2 = (\omega^{\mathsf T}(p - q))^2 + |u'|^2 + |v'|^2 - 2|u'||v'|\cos(\theta_0 - \theta), and the condition is cos⁡(θ0−θ)=c\cos(\theta_0 - \theta) = c with cc from L16.

The arm. Every solution of the arm passes the tests of the four steps, and every output of the four steps satisfies T(θ)=TdT(\theta) = T_d, so the method returns exactly the set of solutions. The proof page gives the details, with the hypotheses that the chosen points are off the axes.

Proof: The three subproblems return exactly their solution sets, and the elbow arm solution returns exactly the inverse kinematics solutionsfull

We use the notation of the page. The proof is in exact arithmetic, in the real RAM. All axes have unit directions, and R(ω,θ)=e[ω]θR(\omega, \theta) = e^{[\omega]\theta} is the rotation by θ\theta about ω\omega. For a vector xx, write x′=x−ωωTxx' = x - \omega\omega^{\mathsf T}x for its part orthogonal to ω\omega.

Lemma 0. For every xx, R(ω,θ)x=ωωTx+cos⁡θ x′+sin⁡θ ω×x′R(\omega, \theta)x = \omega\omega^{\mathsf T}x + \cos\theta\,x' + \sin\theta\,\omega \times x'. So the rotation keeps ωTx\omega^{\mathsf T}x and ∣x′∣|x'|, and it turns x′x' by the angle θ\theta in the plane orthogonal to ω\omega, in the positive sense about ω\omega.

Proof. This is Rodrigues' formula R=I+sin⁡θ[ω]+(1−cos⁡θ)[ω]2R = I + \sin\theta[\omega] + (1 - \cos\theta)[\omega]^2 with [ω]x=ω×x′[\omega]x = \omega \times x' and [ω]2x=−x′[\omega]^2x = -x'. □\square

Subproblem 1

Claim. Let u=p−ru = p - r and v=q−rv = q - r with u′≠0u' \ne 0. A θ\theta with e[ξ]θp=qe^{[\xi]\theta}p = q exists if and only if ωTu=ωTv\omega^{\mathsf T}u = \omega^{\mathsf T}v and ∣u′∣=∣v′∣|u'| = |v'|, and then it is unique modulo 2π2\pi and equal to atan2⁡(ωT(u′×v′),u′Tv′)\operatorname{atan2}(\omega^{\mathsf T}(u' \times v'), u'^{\mathsf T}v').

Proof. The equation e[ξ]θp=qe^{[\xi]\theta}p = q is R(ω,θ)u=vR(\omega, \theta)u = v. By Lemma 0, the part along ω\omega gives ωTu=ωTv\omega^{\mathsf T}u = \omega^{\mathsf T}v and the orthogonal part gives cos⁡θ u′+sin⁡θ ω×u′=v′\cos\theta\,u' + \sin\theta\,\omega \times u' = v', which forces ∣u′∣=∣v′∣|u'| = |v'|. Conversely, if both conditions hold, u′u' and ω×u′\omega \times u' are an orthogonal basis of the plane with equal lengths, so v′=cos⁡θ u′+sin⁡θ ω×u′v' = \cos\theta\,u' + \sin\theta\,\omega \times u' for exactly one θ\theta modulo 2π2\pi. Taking dot products with u′u' and with ω×u′\omega \times u' gives u′Tv′=∣u′∣2cos⁡θu'^{\mathsf T}v' = |u'|^2\cos\theta and ωT(u′×v′)=(ω×u′)Tv′=∣u′∣2sin⁡θ\omega^{\mathsf T}(u' \times v') = (\omega \times u')^{\mathsf T}v' = |u'|^2\sin\theta. Both have the positive factor ∣u′∣2|u'|^2, so atan2 returns θ\theta. □\square

If u′=0u' = 0, then pp is on the axis, every θ\theta leaves it in place, and there is a solution if and only if q=pq = p.

Subproblem 2

Claim. Let the axes (ω1,r)(\omega_1, r) and (ω2,r)(\omega_2, r) meet at rr with ω1≠±ω2\omega_1 \ne \pm\omega_2, let u=p−ru = p - r, v=q−rv = q - r, and suppose that pp is off axis 2 and qq is off axis 1. Then the pairs (θ1,θ2)(\theta_1, \theta_2) modulo 2π2\pi with e[ξ1]θ1e[ξ2]θ2p=qe^{[\xi_1]\theta_1}e^{[\xi_2]\theta_2}p = q are in one to one correspondence with the real γ\gamma that satisfy line L7, and L9 to L12 output exactly these pairs.

Proof. Let k=ω1Tω2k = \omega_1^{\mathsf T}\omega_2, so ∣k∣<1|k| < 1 and ∣ω1×ω2∣2=1−k2>0|\omega_1 \times \omega_2|^2 = 1 - k^2 > 0. The three vectors ω1\omega_1, ω2\omega_2 and ω1×ω2\omega_1 \times \omega_2 are a basis, so every vector has the form z=αω1+βω2+γ(ω1×ω2)z = \alpha\omega_1 + \beta\omega_2 + \gamma(\omega_1 \times \omega_2).

Suppose (θ1,θ2)(\theta_1, \theta_2) is a solution, and put z=R(ω2,θ2)uz = R(\omega_2, \theta_2)u, so that R(ω1,θ1)z=vR(\omega_1, \theta_1)z = v. By Lemma 0, ω2Tz=ω2Tu\omega_2^{\mathsf T}z = \omega_2^{\mathsf T}u, ω1Tz=ω1Tv\omega_1^{\mathsf T}z = \omega_1^{\mathsf T}v and ∣z∣=∣u∣|z| = |u|. The first two equations read αk+β=ω2Tu\alpha k + \beta = \omega_2^{\mathsf T}u and α+βk=ω1Tv\alpha + \beta k = \omega_1^{\mathsf T}v, a linear system with determinant k2−1≠0k^2 - 1 \ne 0, whose solution is the pair (α,β)(\alpha, \beta) of line L6. Since ω1×ω2\omega_1 \times \omega_2 is orthogonal to ω1\omega_1 and ω2\omega_2, ∣z∣2=α2+β2+2αβk+γ2(1−k2)|z|^2 = \alpha^2 + \beta^2 + 2\alpha\beta k + \gamma^2(1 - k^2), and ∣z∣=∣u∣|z| = |u| is the equation of line L7. So zz is one of the vectors built in L10.

Conversely, let γ\gamma be a real root of L7 and zz the vector of L10, with c=r+zc = r + z. Then ω2Tz=ω2Tu\omega_2^{\mathsf T}z = \omega_2^{\mathsf T}u and ∣z∣=∣u∣|z| = |u|, so ∣z′∣=∣u′∣|z'| = |u'| for the parts orthogonal to ω2\omega_2. Since pp is off axis 2, u′≠0u' \ne 0, and the claim on subproblem 1 gives a unique θ2\theta_2 with R(ω2,θ2)u=zR(\omega_2, \theta_2)u = z. In the same way, ω1Tz=ω1Tv\omega_1^{\mathsf T}z = \omega_1^{\mathsf T}v and ∣z∣=∣u∣=∣v∣|z| = |u| = |v| give a unique θ1\theta_1 with R(ω1,θ1)z=vR(\omega_1, \theta_1)z = v; here ∣u∣=∣v∣|u| = |v| is necessary for any solution, since rotations about lines through rr keep the distance to rr. So each root γ\gamma gives one solution, and different roots give different zz and so different θ2\theta_2. Every solution arises in this way by the first part. L7 has two real roots when γ2>0\gamma^2 > 0, one when γ2=0\gamma^2 = 0, and none when γ2<0\gamma^2 < 0, which is the test of L8. □\square

Subproblem 3

Claim. Let u=p−ru = p - r and v=q−rv = q - r with u′≠0u' \ne 0 and v′≠0v' \ne 0. The set of θ\theta with ∣e[ξ]θp−q∣=δ|e^{[\xi]\theta}p - q| = \delta is {θ0±arccos⁡c}\{\theta_0 \pm \arccos c\} modulo 2π2\pi if ∣c∣≤1|c| \le 1 and empty otherwise, with θ0\theta_0 and cc from lines L15 and L16.

Proof. By Lemma 0, e[ξ]θp−q=R(ω,θ)u−v=ω ωT(u−v)+(R(ω,θ)u′−v′)e^{[\xi]\theta}p - q = R(\omega, \theta)u - v = \omega\,\omega^{\mathsf T}(u - v) + (R(\omega, \theta)u' - v'), a sum of two orthogonal parts. So ∣e[ξ]θp−q∣2=(ωT(p−q))2+∣R(ω,θ)u′−v′∣2|e^{[\xi]\theta}p - q|^2 = (\omega^{\mathsf T}(p - q))^2 + |R(\omega, \theta)u' - v'|^2. The vector R(ω,θ)u′R(\omega, \theta)u' has length ∣u′∣|u'| and makes the signed angle θ0−θ\theta_0 - \theta with v′v', where θ0\theta_0 is the signed angle from u′u' to v′v' (by the computation in subproblem 1). By the law of cosines, ∣R(ω,θ)u′−v′∣2=∣u′∣2+∣v′∣2−2∣u′∣∣v′∣cos⁡(θ0−θ)|R(\omega, \theta)u' - v'|^2 = |u'|^2 + |v'|^2 - 2|u'||v'|\cos(\theta_0 - \theta). So the equation is cos⁡(θ0−θ)=c\cos(\theta_0 - \theta) = c with c=(∣u′∣2+∣v′∣2−δ′2)/(2∣u′∣∣v′∣)c = (|u'|^2 + |v'|^2 - \delta'^2)/(2|u'||v'|) and δ′2=δ2−(ωT(p−q))2\delta'^2 = \delta^2 - (\omega^{\mathsf T}(p - q))^2. For ∣c∣>1|c| > 1 it has no solution, and otherwise its solutions are θ=θ0±arccos⁡c\theta = \theta_0 \pm \arccos c, which coincide when ∣c∣=1|c| = 1. □\square

The elbow arm

Let the arm be T(θ)=e[S1]θ1⋯e[S6]θ6MT(\theta) = e^{[\mathcal S_1]\theta_1}\cdots e^{[\mathcal S_6]\theta_6}M, with axis 1 through qsq_s, axes 2 and 3 parallel, axis 2 through qsq_s, and axes 4, 5 and 6 through qwq_w. Write Ei=e[Si]θiE_i = e^{[\mathcal S_i]\theta_i}. We assume that the target is generic in the sense that each point given to a subproblem is off the axes of that subproblem; the code checks no more than this.

Claim. The four steps of the page return exactly the set of θ\theta modulo 2π2\pi with T(θ)=TdT(\theta) = T_d.

Proof. Let θ\theta be a solution and g1=TdM−1=E1E2⋯E6g_1 = T_dM^{-1} = E_1E_2\cdots E_6. The rotations E4E_4, E5E_5 and E6E_6 fix qwq_w, so pw=g1qw=E1E2E3qwp_w = g_1q_w = E_1E_2E_3q_w. The rotations E1E_1 and E2E_2 fix qsq_s and keep distances, so ∣E3qw−qs∣=∣E1E2E3qw−qs∣=∣pw−qs∣|E_3q_w - q_s| = |E_1E_2E_3q_w - q_s| = |p_w - q_s|, and θ3\theta_3 is among the outputs of step 1 by the claim on subproblem 3. Then E1E2(E3qw)=pwE_1E_2(E_3q_w) = p_w, so (θ1,θ2)(\theta_1, \theta_2) is among the outputs of step 2 by the claim on subproblem 2. Next g2=(E1E2E3)−1g1=E4E5E6g_2 = (E_1E_2E_3)^{-1}g_1 = E_4E_5E_6, and for a point pp on axis 6, E6p=pE_6p = p, so E4E5p=g2pE_4E_5p = g_2p and (θ4,θ5)(\theta_4, \theta_5) is among the outputs of step 3. Finally (E4E5)−1g2=E6(E_4E_5)^{-1}g_2 = E_6, and step 4 returns θ6\theta_6 by the claim on subproblem 1.

Conversely, take an output of the four steps. Step 4 gives E6=(E4E5)−1g2E_6 = (E_4E_5)^{-1}g_2 on the point p′p' used there, and we must show it on all points. Both sides are rigid motions that fix qwq_w: the left side because qwq_w is on axis 6, and the right side because E4E_4 and E5E_5 fix qwq_w and step 3 ensures g2p=E4E5pg_2p = E_4E_5p for the point p≠qwp \ne q_w on axis 6, while g2qw=(E1E2E3)−1g1qw=(E1E2E3)−1pw=qwg_2q_w = (E_1E_2E_3)^{-1}g_1q_w = (E_1E_2E_3)^{-1}p_w = q_w by step 2. So H=E4E5E6H = E_4E_5E_6 and g2g_2 are two rigid motions that agree on qwq_w, on pp (since E6E_6 fixes pp) and on p′p'. These three points are not on one line, because p′p' is off axis 6 and qwq_w and pp span that axis. A rigid motion of space that preserves orientation is fixed by the images of three points not on a line, so H=g2H = g_2. Then E1E2E3E4E5E6=E1E2E3g2=g1E_1E_2E_3E_4E_5E_6 = E_1E_2E_3g_2 = g_1, and T(θ)=g1M=TdT(\theta) = g_1M = T_d. □\square

Counting. Step 1 gives at most 2 values, and steps 2 and 3 at most 2 each, while step 4 gives 1, so there are at most 2⋅2⋅2=82 \cdot 2 \cdot 2 = 8 solutions. The example of the page, and the test against a multi-start Newton search, show a target with all 8.

Complexity

Each subproblem is a fixed number of dot products, cross products, square roots and calls to atan2 and arccos, so it costs Θ(1)\Theta(1) in the real RAM. An arm that splits into subproblems needs a fixed number of them per solution, and the products of the nn joint exponentials that form g1g_1, g2g_2 and g3g_3 cost Θ(n)\Theta(n). For a fixed arm with six joints, all eight solutions take a few hundred arithmetic operations.

Properties

  • All solutions. Each subproblem returns all of its solutions, so the arm solution lists the full finite set, not one solution near a guess.
  • No iteration. There is no starting point, no tolerance on convergence and no failure mode from a poor guess.
  • Frame free. The formulas use only axes and points, so they work in any base frame and do not need Denavit-Hartenberg parameters.
  • Geometry first. The method needs the arm to have the right geometry, such as two axes that meet, or a point that some joints leave in place.
  • Degenerate cases. If pp lies on an axis, subproblem 1 has infinitely many solutions; for the arm, this happens at a kinematic singularity, such as the wrist with the axes 4 and 6 in line.

Variants and improvements

  • More subproblems. Paden's thesis describes four subproblems, and the textbook form keeps three. Elias and Wen add subproblems 4 to 6 and use the six of them to solve arms with three intersecting or three parallel axes, among other layouts.
  • Approximate answers. Elias and Wen also give each subproblem a form that returns an approximate answer when there is no exact solution, which is useful near the edge of the workspace.
  • Translations. Prismatic joints lead to similar subproblems, such as a translation along an axis followed by a rotation.
  • Other arms. The Stanford arm, with a prismatic third joint, and arms with offsets also reduce to subproblems with a different order of steps.
  • Arms that do not split. For a general 6R arm, use an algebraic method such as the Raghavan-Roth method, or a numerical one such as Newton-Raphson inverse kinematics.

When to use it

Use the subproblems when the arm has three axes that meet in a point, or other special geometry that lets you isolate joints, and you want all solutions in closed form. This covers most industrial arms with a spherical wrist; see Pieper's criterion and kinematic decoupling. When the arm does not have such geometry, use an algebraic or a numerical method.

Pitfalls

  • Points on an axis. The point given to a subproblem must be off the axes of that subproblem, or the angle is not determined. Choose it once for the arm, not for each target.
  • Tolerances. The exact tests of L3, L8 and L17 must be tests with a small tolerance in floating point, or a reachable target near the edge of the workspace can be rejected.
  • The order of the rotations. Subproblem 2 is about e[ξ1]θ1e[ξ2]θ2e^{[\xi_1]\theta_1}e^{[\xi_2]\theta_2}, the second rotation first applied to pp; swapping the axes swaps the meaning of the output.
  • Duplicate solutions. When γ=0\gamma = 0 or c=±1c = \pm 1, the two branches coincide; return one solution, or the caller counts it twice.
  • Angle ranges. The angles come out of atan2 and arccos and need wrapping into the range of each joint, and the joint limits must be checked after.

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.

paden_kahan_subproblems.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/paden-kahan-subproblems/. The authors are listed in prov/MGK2K1.jsonl.
"""The three Paden-Kahan subproblems and an elbow arm solved with them.

Each subproblem is about rotations about unit axes w that pass through a
point r. A rotation by theta takes a point x to r + Rot(w, theta) (x - r),
which is exp([xi] theta) x for the revolute twist xi = (w, -w x r).

- subproblem1(w, r, p, q): theta with exp([xi] theta) p = q.
- subproblem2(w1, w2, r, p, q): all (theta1, theta2) with
  exp([xi1] theta1) exp([xi2] theta2) p = q, for two axes that meet at r.
- subproblem3(w, r, p, q, delta): all theta with |exp([xi] theta) p - q| = delta.

elbow_ik(g_d, lengths) applies them to a six joint elbow arm with a
spherical wrist (the arm of Murray, Li and Sastry, Section 3.3) and
returns every solution, up to 8. The arm is in the space form of the
product of exponentials, T(theta) = exp([S1] theta1) ... exp([S6] theta6) M.
The subproblems return an empty list, or None for subproblem 1, when
there is no solution.
"""

import math

import rbm

TOL = 1e-9


def _proj(w, x):
    """Return the part of x orthogonal to the unit vector w."""
    d = rbm.dot(w, x)
    return [xi - d * wi for xi, wi in zip(x, w)]


def rotate_about(w, r, theta, x):
    """Return the image of the point x under the rotation by theta about the line (w, r)."""
    rot = rbm.so3_exp([theta * wi for wi in w])
    return rbm.add(r, rbm.matvec(rot, rbm.sub(x, r)))


def subproblem1(w, r, p, q, tol=TOL):
    """Return theta with Rot(w, theta) (p - r) = q - r, or None if there is none.

    If p lies on the axis, every theta works and 0.0 is returned.
    """
    u = rbm.sub(p, r)  # @line L1
    v = rbm.sub(q, r)
    u1 = _proj(w, u)  # @line L2
    v1 = _proj(w, v)
    scale = 1.0 + rbm.norm(u) + rbm.norm(v)
    if abs(rbm.dot(w, u) - rbm.dot(w, v)) > tol * scale or abs(rbm.norm(u1) - rbm.norm(v1)) > tol * scale:  # @line L3
        return None
    if rbm.norm(u1) <= tol * scale:
        return 0.0
    return math.atan2(rbm.dot(w, rbm.cross(u1, v1)), rbm.dot(u1, v1))  # @line L4


def subproblem2(w1, w2, r, p, q, tol=TOL):
    """Return the list of (theta1, theta2) with Rot1(theta1) Rot2(theta2) p = q.

    The axes (w1, r) and (w2, r) meet at r and are not parallel. The list
    has 0, 1 or 2 pairs.
    """
    u = rbm.sub(p, r)  # @line L5
    v = rbm.sub(q, r)
    k = rbm.dot(w1, w2)
    if abs(rbm.norm(u) - rbm.norm(v)) > tol * (1.0 + rbm.norm(u)):
        return []
    alpha = (k * rbm.dot(w2, u) - rbm.dot(w1, v)) / (k * k - 1.0)  # @line L6
    beta = (k * rbm.dot(w1, v) - rbm.dot(w2, u)) / (k * k - 1.0)
    w12 = rbm.cross(w1, w2)
    g2 = (rbm.dot(u, u) - alpha * alpha - beta * beta - 2.0 * alpha * beta * k) / rbm.dot(w12, w12)  # @line L7
    if g2 < -tol * (1.0 + rbm.dot(u, u)):  # @line L8
        return []
    g = math.sqrt(max(g2, 0.0))
    gammas = [g, -g] if g > tol * (1.0 + rbm.norm(u)) else [0.0]
    out = []
    for gamma in gammas:  # @line L9
        z = [alpha * a + beta * b + gamma * c for a, b, c in zip(w1, w2, w12)]  # @line L10
        c = rbm.add(r, z)
        th2 = subproblem1(w2, r, p, c, tol=1e-6)  # @line L11
        th1 = subproblem1(w1, r, c, q, tol=1e-6)
        if th1 is not None and th2 is not None:
            out.append((th1, th2))  # @line L12
    return out


def subproblem3(w, r, p, q, delta, tol=TOL):
    """Return the list of theta with |Rot(w, theta) (p - r) + r - q| = delta.

    The list has 0, 1 or 2 angles in (-pi, pi].
    """
    u = rbm.sub(p, r)  # @line L13
    v = rbm.sub(q, r)
    u1 = _proj(w, u)
    v1 = _proj(w, v)
    d2 = delta * delta - rbm.dot(w, rbm.sub(p, q)) ** 2  # @line L14
    th0 = math.atan2(rbm.dot(w, rbm.cross(u1, v1)), rbm.dot(u1, v1))  # @line L15
    nu, nv = rbm.norm(u1), rbm.norm(v1)
    if nu <= tol or nv <= tol:
        return []
    c = (nu * nu + nv * nv - d2) / (2.0 * nu * nv)  # @line L16
    if abs(c) > 1.0 + tol:  # @line L17
        return []
    c = max(-1.0, min(1.0, c))
    a = math.acos(c)
    if a <= tol:
        return [_wrap(th0)]
    return [_wrap(th0 - a), _wrap(th0 + a)]  # @line L18


def _wrap(x):
    """Return x moved into (-pi, pi]."""
    y = math.fmod(x + math.pi, 2.0 * math.pi)
    if y <= 0.0:
        y += 2.0 * math.pi
    return y - math.pi


# ---------------------------------------------------------------- the elbow arm


def elbow_arm(l0=1.0, l1=1.0, l2=1.0, l3=0.5):
    """Return (axes, M, points) of the elbow arm with a spherical wrist.

    axes is a list of six (w, r) pairs at the zero configuration. The
    shoulder is at (0, 0, l0), the elbow at (0, l1, l0) and the wrist
    center at (0, l1 + l2, l0); the tool point is l3 further along y.
    """
    qs = [0.0, 0.0, l0]
    qe = [0.0, l1, l0]
    qw = [0.0, l1 + l2, l0]
    z, mx, y = [0.0, 0.0, 1.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0]
    axes = [(z, [0.0, 0.0, 0.0]), (mx, qs), (mx, qe), (z, qw), (mx, qw), (y, qw)]
    m = rbm.make_T(rbm.eye(3), [0.0, l1 + l2 + l3, l0])
    return axes, m, {"shoulder": qs, "elbow": qe, "wrist": qw}


def screw(w, r):
    """Return the space screw axis (w, -w x r) of a revolute joint."""
    return list(w) + [-x for x in rbm.cross(w, r)]


def fk(axes, m, theta):
    """Return T(theta) = exp([S1] theta1) ... exp([Sn] thetan) M."""
    t = rbm.eye(4)
    for (w, r), th in zip(axes, theta):
        t = rbm.mul(t, rbm.se3_exp([x * th for x in screw(w, r)]))
    return rbm.mul(t, m)


def elbow_ik(axes, m, points, g_d):
    """Return every theta (a list of 6-tuples) with fk(axes, m, theta) = g_d."""
    qs, qw = points["shoulder"], points["wrist"]
    g1 = rbm.mul(g_d, rbm.T_inv(m))
    pw = rbm.T_apply(g1, qw)  # where the wrist center must go
    delta = rbm.norm(rbm.sub(pw, qs))
    (w1, _), (w2, _), (w3, r3), (w4, _), (w5, _), (w6, _) = axes
    sols = []
    for th3 in subproblem3(w3, r3, qw, qs, delta):
        p3 = rotate_about(w3, r3, th3, qw)
        for th1, th2 in subproblem2(w1, w2, qs, p3, pw):
            t123 = fk(axes[:3], rbm.eye(4), [th1, th2, th3])
            g2 = rbm.mul(rbm.T_inv(t123), g1)  # = exp([S4] th4) exp([S5] th5) exp([S6] th6)
            p6 = rbm.add(qw, w6)  # a point on axis 6, off axes 4 and 5
            for th4, th5 in subproblem2(w4, w5, qw, p6, rbm.T_apply(g2, p6)):
                t45 = fk(axes[3:5], rbm.eye(4), [th4, th5])
                g3 = rbm.mul(rbm.T_inv(t45), g2)  # = exp([S6] th6)
                p = rbm.add(qw, w4)  # a point off axis 6
                th6 = subproblem1(w6, qw, p, rbm.T_apply(g3, p), tol=1e-6)
                if th6 is not None:
                    sols.append(tuple(_wrap(x) for x in (th1, th2, th3, th4, th5, th6)))
    return sols
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_paden_kahan_subproblems.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/paden-kahan-subproblems/. The authors are listed in prov/MGK2K1.jsonl.
"""Tests of the Paden-Kahan subproblems: each subproblem against a scan of
the angle, and the elbow arm against forward kinematics and against a
multi-start Newton search for all solutions."""

import math
import random

import rbm
from paden_kahan_subproblems import (
    elbow_arm,
    elbow_ik,
    fk,
    rotate_about,
    screw,
    subproblem1,
    subproblem2,
    subproblem3,
)


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_point(rng):
    return [rng.uniform(-1.0, 1.0) for _ in range(3)]


def angle_diff(a, b):
    d = math.fmod(a - b, 2.0 * math.pi)
    return min(abs(d), 2.0 * math.pi - abs(d))


def circle(w, r, p):
    """Return t -> Rot(w, t) (p - r) + r, by Rodrigues' formula with the parts of p - r fixed once."""
    u = rbm.sub(p, r)
    d = rbm.dot(w, u)
    par = rbm.add(r, rbm.scale(w, d))
    perp = rbm.sub(u, rbm.scale(w, d))
    side = rbm.cross(w, u)
    return lambda t: [a + math.cos(t) * b + math.sin(t) * c for a, b, c in zip(par, perp, side)]


def scan_roots(f, n=4000):
    """Return the roots of a 2 pi periodic f found by sign changes on a grid, refined by bisection."""
    xs = [-math.pi + 2.0 * math.pi * i / n for i in range(n + 1)]
    fs = [f(x) for x in xs]
    roots = []
    for i in range(n):
        if fs[i] == 0.0 or fs[i] * fs[i + 1] < 0.0:
            a, b, fa = xs[i], xs[i + 1], fs[i]
            for _ in range(60):
                mid = 0.5 * (a + b)
                fm = f(mid)
                if fa * fm <= 0.0:
                    b = mid
                else:
                    a, fa = mid, fm
            roots.append(0.5 * (a + b))
    return roots


def test_subproblem1_recovers_the_angle():
    rng = random.Random(1)
    for _ in range(200):
        w, r, p = rand_unit(rng), rand_point(rng), rand_point(rng)
        th = rng.uniform(-math.pi, math.pi)
        q = rotate_about(w, r, th, p)
        got = subproblem1(w, r, p, q)
        assert got is not None and angle_diff(got, th) < 1e-9


def test_subproblem1_no_solution():
    w, r, p = [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], [1.0, 0.0, 0.0]
    assert subproblem1(w, r, p, [0.0, 2.0, 0.0]) is None  # wrong radius
    assert subproblem1(w, r, p, [0.0, 1.0, 0.5]) is None  # wrong height


def test_subproblem3_against_scan():
    rng = random.Random(2)
    counts = {0: 0, 1: 0, 2: 0}
    for _ in range(40):
        w, r, p, q = rand_unit(rng), rand_point(rng), rand_point(rng), rand_point(rng)
        delta = rng.uniform(0.0, 2.5)
        c = circle(w, r, p)

        def f(t):
            return rbm.norm(rbm.sub(c(t), q)) - delta

        got = subproblem3(w, r, p, q, delta)
        want = scan_roots(f, 1000)
        assert len(got) == len(want)
        counts[len(got)] += 1
        for t in got:
            assert abs(f(t)) < 1e-9
            assert min(angle_diff(t, x) for x in want) < 1e-6
    assert counts[0] > 0 and counts[2] > 0


def test_subproblem2_against_scan():
    rng = random.Random(3)
    for trial in range(30):
        w1, w2, r, p = rand_unit(rng), rand_unit(rng), rand_point(rng), rand_point(rng)
        if trial % 2 == 0:
            t1, t2 = rng.uniform(-3.0, 3.0), rng.uniform(-3.0, 3.0)
            q = rotate_about(w1, r, t1, rotate_about(w2, r, t2, p))
        else:  # a point at the right distance from r, usually without a solution
            d = rand_unit(rng)
            q = rbm.add(r, rbm.scale(d, rbm.norm(rbm.sub(p, r))))
        got = subproblem2(w1, w2, r, p, q)
        # Brute force: theta2 is a solution angle exactly when the point
        # Rot2(theta2) p has the height of q along w1.
        c2 = circle(w2, r, p)
        want = scan_roots(lambda t: rbm.dot(w1, rbm.sub(c2(t), q)), 1000)
        assert len(got) == len(want)
        for th1, th2 in got:
            img = rotate_about(w1, r, th1, rotate_about(w2, r, th2, p))
            assert rbm.norm(rbm.sub(img, q)) < 1e-9
            assert min(angle_diff(th2, x) for x in want) < 1e-6
        if trial % 2 == 0:
            assert any(angle_diff(a, t1) < 1e-8 and angle_diff(b, t2) < 1e-8 for a, b in got)


def pose_err(a, b):
    return max(abs(a[i][j] - b[i][j]) for i in range(4) for j in range(4))


def space_jacobian(axes, theta):
    t = rbm.eye(4)
    cols = []
    for (w, r), th in zip(axes, theta):
        s = screw(w, r)
        cols.append(rbm.matvec(rbm.adjoint(t), s))
        t = rbm.mul(t, rbm.se3_exp([x * th for x in s]))
    return rbm.transpose(cols)


def newton(axes, m, g_d, th, iters=30):
    """Plain Newton-Raphson on the space twist error; returns theta or None."""
    th = list(th)
    for _ in range(iters):
        t = fk(axes, m, th)
        vs = rbm.matvec(rbm.adjoint(t), rbm.se3_log(rbm.mul(rbm.T_inv(t), g_d)))
        if rbm.norm(vs) < 1e-12:
            return th
        try:
            step = rbm.solve(space_jacobian(axes, th), vs)
        except ValueError:
            return None
        if rbm.norm(step) > 2.0:
            step = rbm.scale(step, 2.0 / rbm.norm(step))
        th = [a + b for a, b in zip(th, step)]
    return None


def same(a, b, tol=1e-6):
    return all(angle_diff(x, y) < tol for x, y in zip(a, b))


def test_elbow_ik_forward_kinematics():
    axes, m, pts = elbow_arm()
    rng = random.Random(4)
    for _ in range(60):
        th = [rng.uniform(-3.0, 3.0) for _ in range(6)]
        g = fk(axes, m, th)
        sols = elbow_ik(axes, m, pts, g)
        assert 1 <= len(sols) <= 8
        for s in sols:
            assert pose_err(fk(axes, m, s), g) < 1e-9
        assert any(same(s, th, 1e-7) for s in sols)
        for i in range(len(sols)):
            for j in range(i):
                assert not same(sols[i], sols[j])


def test_elbow_ik_against_multistart_newton():
    axes, m, pts = elbow_arm(1.0, 1.2, 0.9, 0.4)
    rng = random.Random(5)
    for _ in range(1):
        g = fk(axes, m, [rng.uniform(-2.5, 2.5) for _ in range(6)])
        sols = elbow_ik(axes, m, pts, g)
        found = []
        for _ in range(48):
            q = newton(axes, m, g, [rng.uniform(-math.pi, math.pi) for _ in range(6)])
            if q is not None and pose_err(fk(axes, m, q), g) < 1e-9:
                if not any(same(q, f) for f in found):
                    found.append(q)
        assert len(found) == len(sols) == 8
        for q in found:
            assert any(same(q, s) for s in sols)


def test_example_of_the_page():
    axes, m, pts = elbow_arm()
    th = [0.3, -0.4, 0.9, 0.5, 0.7, -0.6]
    sols = elbow_ik(axes, m, pts, fk(axes, m, th))
    assert len(sols) == 8
    thirds = sorted(round(s[2], 6) for s in sols)
    assert thirds == [-0.9] * 4 + [0.9] * 4


def test_out_of_reach():
    axes, m, pts = elbow_arm()
    g = rbm.make_T(rbm.eye(3), [0.0, 3.0, 1.0])  # wrist center 2.5 from the shoulder, reach 2
    assert elbow_ik(axes, m, pts, g) == []

History

Paden (1986) wrote rigid motions as exponentials of twists in his Berkeley thesis and described a small set of subproblems that occur again and again in robot kinematics. He solved the Stanford arm and an elbow arm with them. The name joins Paden and William Kahan, whose part in the idea was not published as a paper. Murray, Li and Sastry (1994) gave the three subproblems their standard form in their textbook. Elias and Wen (2025) extended the set to six subproblems and solved many more arm layouts with them.

References

  1. Bradley E. Paden, Kinematics and Control of Robot Manipulators, PhD thesis, University of California, Berkeley, 1986 (Technical Report UCB/ERL M86/5), Chapter 2 (subproblems written with exponentials of twists) and Chapter 3 (the Stanford arm and an elbow arm solved with them)
  2. Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 3, Section 3.3 (inverse kinematics, the Paden-Kahan subproblems and their use on an elbow arm)
  3. Alexander J. Elias and John T. Wen, IK-Geo: Unified robot inverse kinematics using subproblem decomposition, Mechanism and Machine Theory 209, 105971, 2025, the subproblems 1 to 3 in a least squares form, the new subproblems 4 to 6, and the arms with three intersecting or three parallel axes

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