Algorithm Search⌘K

Algorithmresearch

Raghavan-Roth method

Also called Raghavan-Roth elimination.

Solves the general 6R inverse kinematics by dialytic elimination to one polynomial of degree 16 in the tangent of a half angle.

Time
Θ(d^3) worst
Space
Θ(d^2) extra
Where
d = the degree of the final polynomial (16 for a general 6R arm and 4 for the 3R position problem)
Properties
deterministicofflineiterative
Origin
Madhusudan Raghavan, Bernard Roth, 1990

The Raghavan-Roth method solves the inverse kinematics of a general arm with six revolute joints (a 6R arm) in closed form, up to the roots of one polynomial. It writes the pose equations as equations that are linear in products of sines and cosines, eliminates five joint angles by linear algebra, and is left with one polynomial of degree 16 in x3=tan⁡(θ3/2)x_3 = \tan(\theta_3/2). Each real root then gives one solution, found by solving linear systems. The key step is the dialytic elimination: multiply the equations by powers of a variable so that the products of the variables become unknowns of a square linear system, whose determinant must vanish. The implementation here runs the same steps on a smaller problem, the position of a general 3R arm, where the final polynomial is a quartic.

In plain words

An arm with six hinges in general position has no simple geometric shortcut. The equations that say "the hand is at this pose" mix sines and cosines of all six angles. The trick is to treat each product of sines and cosines as a new unknown. Then most of the equations become linear, and linear equations can be combined to cancel unknowns. After enough cancelling, only one angle is left, in one equation, a polynomial with at most 16 roots. Find its roots, and walk back through the linear equations to get the other angles. Some factors of the polynomial are false and must be removed first.

The problem

Input. The Denavit-Hartenberg parameters of an arm with revolute joints and a target: for the 6R arm a full pose of the hand, for the 3R demo a point pp for the origin of frame 3.

Output. All joint vectors that reach the target.

The arm must be general: special arms, such as arms with a spherical wrist, make some matrices of the method singular, and they have simpler methods anyway, see the Pieper criterion.

The algorithm

The pseudocode shows the 3R position version that the implementation runs. With Ti=Rz(θi)Tz(di)Tx(ai)Rx(αi)T_i = R_z(\theta_i)T_z(d_i)T_x(a_i)R_x(\alpha_i), the point is p=Rz(θ1)gp = R_z(\theta_1)g with gg free of θ1\theta_1, and hh is the part that depends on θ3\theta_3 only.

  1. RAGHAVAN-ROTH-3R(dh, p)
  2. 1from |p|^2 = |g|^2 and p_z = g_z: E_j: P_j c2 + Q_j s2 + K_j = 0 (j = 1, 2), with P_j, Q_j, K_j linear in (c3, s3)
  3. 2put c_i = (1 - x_i^2)/(1 + x_i^2), s_i = 2x_i/(1 + x_i^2) for i = 2, 3: E_j becomes A_j x2^2 + B_j x2 + C_j, coefficients of degree 2 in x3
  4. 3multiply each by 1 and by x2: M(x3) (x2^3, x2^2, x2, 1)^T = 0, with the 4 × 4 matrix M
  5. 4Δ(x3) ← det M(x3) ▷ degree 8
  6. 5q(x3) ← Δ(x3) / (4 (h̃1^2 + h̃2^2)) ▷ remove the extraneous factor; degree 4
  7. 6for each real root x3 of q
  8. 7θ3 ← 2 arctan x3; (c2, s2, 1) ∝ (P_1, Q_1, K_1) × (P_2, Q_2, K_2); θ2 ← atan2(s2, c2)
  9. 8θ1 ← atan2(p_y, p_x) - atan2(g_y, g_x)
  10. 9return the joint vectors that pass a forward kinematics check

The 6R method. Raghavan and Roth follow the same plan with more equations.

  1. Write the loop equation so that θ1\theta_1 and θ2\theta_2 are on one side, and take the two vectors p\mathbf p (a position) and l\mathbf l (an axis) on each side. From them form 14 scalar equations: the components of p\mathbf p and l\mathbf l, the products p⋅p\mathbf p \cdot \mathbf p and p⋅l\mathbf p \cdot \mathbf l, the vector p×l\mathbf p \times \mathbf l, and the vector (p⋅p)l−2(p⋅l)p(\mathbf p \cdot \mathbf p)\mathbf l - 2(\mathbf p \cdot \mathbf l)\mathbf p. These are linear in 8 products of the sines and cosines of θ1,θ2\theta_1, \theta_2 and in 9 products of those of θ4,θ5\theta_4, \theta_5, with coefficients that depend on θ3\theta_3.
  2. Eliminate the 8 products of θ1,θ2\theta_1, \theta_2 by linear algebra: this leaves 6 equations in the 9 products of θ4,θ5\theta_4, \theta_5.
  3. Put x4=tan⁡(θ4/2)x_4 = \tan(\theta_4/2) and x5=tan⁡(θ5/2)x_5 = \tan(\theta_5/2), multiply the 6 equations by x4x_4, and get 12 equations that are linear in 12 power products, with a 12×1212 \times 12 matrix Σ(x3)\Sigma(x_3).
  4. A solution needs det⁡Σ(x3)=0\det\Sigma(x_3) = 0. This determinant has degree 24 in x3x_3 and contains the factor (1+x32)4(1 + x_3^2)^4, which has no real roots. The rest is the polynomial of degree 16.
  5. For each real root, a null vector of Σ(x3)\Sigma(x_3) gives θ4\theta_4 and θ5\theta_5, and linear equations give θ1\theta_1, θ2\theta_2 and θ6\theta_6.

Manocha and Canny (1994) do not expand the determinant: they write Σ(x3)\Sigma(x_3) as a matrix polynomial of degree 2 and find its roots as the eigenvalues of a generalized eigenvalue problem, which is much more accurate.

Example

The 3R arm has (a1,α1,d1)=(0.5 m,120°,0.5 m)(a_1, \alpha_1, d_1) = (0.5\text{ m}, 120°, 0.5\text{ m}), (a2,α2,d2)=(0.5 m,30°,1.0 m)(a_2, \alpha_2, d_2) = (0.5\text{ m}, 30°, 1.0\text{ m}) and (a3,α3,d3)=(1.5 m,0°,0 m)(a_3, \alpha_3, d_3) = (1.5\text{ m}, 0°, 0\text{ m}). The target is the point that the joint vector (1,−0.5,−1)(1, -0.5, -1) rad reaches: p=(0.209252,1.203738,−1.059310)p = (0.209252, 1.203738, -1.059310) m.

  • The determinant Δ(x3)\Delta(x_3) of the 4×44 \times 4 matrix has degree 8.
  • The extraneous factor is h~12+h~22=4+2.75x32+x34\tilde h_1^2 + \tilde h_2^2 = 4 + 2.75x_3^2 + x_3^4, which is positive for all real x3x_3.
  • The quotient is the quartic 2.474388x34−9.122939x33+4.164800x32+4.377061x3−0.5595872.474388x_3^4 - 9.122939x_3^3 + 4.164800x_3^2 + 4.377061x_3 - 0.559587.
  • Its four roots are real: x3=−0.546302x_3 = -0.546302, 0.1179230.117923, 1.2070931.207093 and 2.9082362.908236.
x3x_3 θ1\theta_1 (rad) θ2\theta_2 (rad) θ3\theta_3 (rad)
-0.546302 1.000000 -0.500000 -1.000000
0.117923 -2.125286 -2.692609 0.234761
1.207093 -2.873565 2.405672 1.757909
2.908236 2.098607 2.860655 2.479220

Forward kinematics puts each of the four joint vectors on pp to about 10−1510^{-15} m. The first row is the joint vector that made the target, and the other three are the other solutions.

Correctness

The proof page proves, for the 3R version and a general arm, that the real roots of the quartic give exactly the solutions, one each.

  • ∣p∣2|p|^2 and pzp_z do not depend on θ1\theta_1, so they give two equations in θ2\theta_2 and θ3\theta_3, and θ1\theta_1 follows from the other two.
  • The two equations are linear in (c2,s2)(c_2, s_2); they have a solution on the unit circle exactly when (h12+h22) q=0(h_1^2 + h_2^2)\,q = 0, which is the condition on θ3\theta_3.
  • The determinant of the dialytic matrix is the resultant of the two quadratics in x2x_2, and it equals 4(h~12+h~22)q~4(\tilde h_1^2 + \tilde h_2^2)\tilde q; the first factor is extraneous.
  • The null vector of the 2×32 \times 3 coefficient matrix gives (c2,s2)(c_2, s_2), so each root gives one solution.

For the 6R arm the same argument runs on the 14 equations, and Raghavan and Roth prove that the polynomial of degree 16 has the solutions among its roots; see the 16 solutions theorem for the bound.

Proof: For the 3R position problem, the real roots of the quartic left after the dialytic elimination give exactly the solutionsfull

This page proves the correctness of the 3R version that the implementation runs. The 6R method of Raghavan and Roth follows the same steps on a larger system, and its proof is in their paper; the page only describes it.

Setting

The arm has Denavit-Hartenberg parameters (ai,αi,di)(a_i, \alpha_i, d_i), with Ti=Rz(θi) Tz(di) Tx(ai) Rx(αi)T_i = R_z(\theta_i)\,T_z(d_i)\,T_x(a_i)\,R_x(\alpha_i), and the task is to put the origin of frame 3 at the point pp. Write ci=cos⁡θic_i = \cos\theta_i, si=sin⁡θis_i = \sin\theta_i, and caica_i, saisa_i for the cosine and sine of αi\alpha_i. We call the arm and the target general if a1≠0a_1 \ne 0, sa1≠0sa_1 \ne 0, h12+h22>0h_1^2 + h_2^2 > 0 for every θ3\theta_3 (with hh below), (px,py)≠(0,0)(p_x, p_y) \ne (0, 0), and the quartic below is not the zero polynomial.

Step 1: two equations free of θ1\theta_1

Multiplying out the transforms gives p=Rz(θ1) gp = R_z(\theta_1)\,g, with

g=(a1,0,d1)+Rx(α1) Rz(θ2) h,h=(a2,0,d2)+Rx(α2)(a3c3,a3s3,d3).g = (a_1, 0, d_1) + R_x(\alpha_1)\,R_z(\theta_2)\,h, \qquad h = (a_2, 0, d_2) + R_x(\alpha_2)(a_3c_3, a_3s_3, d_3).

So h=(a2+a3c3, ca2a3s3−sa2d3, d2+sa2a3s3+ca2d3)h = (a_2 + a_3c_3,\ ca_2a_3s_3 - sa_2d_3,\ d_2 + sa_2a_3s_3 + ca_2d_3) depends on θ3\theta_3 only. A rotation about zz keeps the length and the zz coordinate, so ∣p∣2=∣g∣2|p|^2 = |g|^2 and pz=gzp_z = g_z. With f=Rz(θ2)h=(c2h1−s2h2, s2h1+c2h2, h3)f = R_z(\theta_2)h = (c_2h_1 - s_2h_2,\ s_2h_1 + c_2h_2,\ h_3), these two equations become

E1: 2a1h1 c2−2a1h2 s2+K=0,E2: sa1h2 c2+sa1h1 s2+L=0,E_1:\ 2a_1h_1\,c_2 - 2a_1h_2\,s_2 + K = 0, \qquad E_2:\ sa_1h_2\,c_2 + sa_1h_1\,s_2 + L = 0,

with K=∣h∣2+a12−d12−∣p∣2+2d1pzK = |h|^2 + a_1^2 - d_1^2 - |p|^2 + 2d_1p_z and L=d1+ca1h3−pzL = d_1 + ca_1h_3 - p_z. For E1E_1 we used gz=pzg_z = p_z to replace the term 2d1(sa1f2+ca1h3)2d_1(sa_1f_2 + ca_1h_3) by 2d1(pz−d1)2d_1(p_z - d_1). Conversely, if θ2,θ3\theta_2, \theta_3 satisfy E1E_1 and E2E_2, then ∣g∣=∣p∣|g| = |p| and gz=pzg_z = p_z, so (gx,gy)(g_x, g_y) and (px,py)(p_x, p_y) have the same length. If that length is not 0, exactly one θ1\theta_1 modulo 2π2\pi rotates the one onto the other, θ1=atan2⁡(py,px)−atan2⁡(gy,gx)\theta_1 = \operatorname{atan2}(p_y, p_x) - \operatorname{atan2}(g_y, g_x), and then Rz(θ1)g=pR_z(\theta_1)g = p. So the solutions are in one to one correspondence with the pairs (θ2,θ3)(\theta_2, \theta_3) that satisfy E1E_1 and E2E_2.

Step 2: the condition on θ3\theta_3

Write EjE_j as Pjc2+Qjs2+Kj=0P_jc_2 + Q_js_2 + K_j = 0, with (P1,Q1,K1)=(2a1h1,−2a1h2,K)(P_1, Q_1, K_1) = (2a_1h_1, -2a_1h_2, K) and (P2,Q2,K2)=(sa1h2,sa1h1,L)(P_2, Q_2, K_2) = (sa_1h_2, sa_1h_1, L). Let D=P1Q2−P2Q1=2a1sa1(h12+h22)D = P_1Q_2 - P_2Q_1 = 2a_1sa_1(h_1^2 + h_2^2), X=Q1K2−Q2K1X = Q_1K_2 - Q_2K_1 and Y=K1P2−K2P1Y = K_1P_2 - K_2P_1. For a general arm D≠0D \ne 0, so the linear system has the unique solution (c2,s2)=(X/D,Y/D)(c_2, s_2) = (X/D, Y/D) by Cramer's rule, and a θ2\theta_2 exists if and only if X2+Y2=D2X^2 + Y^2 = D^2. Expanding, the cross terms of X2+Y2X^2 + Y^2 cancel, and

X2+Y2−D2=(h12+h22) q,q=4a12L2+sa12K2−4a12sa12(h12+h22).X^2 + Y^2 - D^2 = (h_1^2 + h_2^2)\,q, \qquad q = 4a_1^2L^2 + sa_1^2K^2 - 4a_1^2sa_1^2(h_1^2 + h_2^2).

Since h12+h22>0h_1^2 + h_2^2 > 0, a θ3\theta_3 gives a solution if and only if q=0q = 0 at θ3\theta_3, and then θ2\theta_2 is unique. So the number of solutions equals the number of zeros of qq in θ3\theta_3 modulo 2π2\pi.

Step 3: the dialytic matrix gives the same polynomial

With xi=tan⁡(θi/2)x_i = \tan(\theta_i/2), ci=(1−xi2)/(1+xi2)c_i = (1 - x_i^2)/(1 + x_i^2) and si=2xi/(1+xi2)s_i = 2x_i/(1 + x_i^2). Every coefficient Pj,Qj,KjP_j, Q_j, K_j has the form u+vc3+ws3u + vc_3 + ws_3, so its product with 1+x321 + x_3^2 is the polynomial (u+v)+2wx3+(u−v)x32(u + v) + 2wx_3 + (u - v)x_3^2; we mark such products with a tilde. Multiplying EjE_j by (1+x22)(1+x32)(1 + x_2^2)(1 + x_3^2) gives the quadratic Ajx22+Bjx2+CjA_jx_2^2 + B_jx_2 + C_j with Aj=K~j−P~jA_j = \tilde K_j - \tilde P_j, Bj=2Q~jB_j = 2\tilde Q_j and Cj=K~j+P~jC_j = \tilde K_j + \tilde P_j. Multiplying each quadratic by 11 and by x2x_2 gives four equations, linear in (x23,x22,x2,1)(x_2^3, x_2^2, x_2, 1), with the 4×44 \times 4 matrix M(x3)M(x_3) of line L3; this is the Sylvester matrix of the two quadratics, and its determinant is their resultant. For two quadratics the resultant is (A1C2−A2C1)2−(A1B2−A2B1)(B1C2−B2C1)(A_1C_2 - A_2C_1)^2 - (A_1B_2 - A_2B_1)(B_1C_2 - B_2C_1), and substituting Aj,Bj,CjA_j, B_j, C_j gives

det⁡M(x3)=4[(K~1P~2−K~2P~1)2+X~2−D~2]=4 (h~12+h~22) q~,\det M(x_3) = 4\big[(\tilde K_1\tilde P_2 - \tilde K_2\tilde P_1)^2 + \tilde X^2 - \tilde D^2\big] = 4\,\big(\tilde h_1^2 + \tilde h_2^2\big)\,\tilde q,

where every tilde quantity is the polynomial in x3x_3 of the same quantity times the right power of 1+x321 + x_3^2. Here h~12+h~22=(1+x32)2(h12+h22)\tilde h_1^2 + \tilde h_2^2 = (1 + x_3^2)^2(h_1^2 + h_2^2) is the extraneous factor of line L5: it has no real root for a general arm, so it gives no solution. The quotient q~=(1+x32)2q\tilde q = (1 + x_3^2)^2q is a polynomial of degree at most 4 in x3x_3, and for real x3x_3 it is zero exactly when qq is zero. The tests check the identity det⁡M=4(h~12+h~22)q~\det M = 4(\tilde h_1^2 + \tilde h_2^2)\tilde q coefficient by coefficient.

Step 4: back substitution

Take a real root x3x_3 of q~\tilde q and θ3=2arctan⁡x3\theta_3 = 2\arctan x_3. The vector (c2,s2,1)(c_2, s_2, 1) is a null vector of the 2×32 \times 3 matrix with rows (Pj,Qj,Kj)(P_j, Q_j, K_j). Since D≠0D \ne 0, that matrix has rank 2, its null space is one dimensional, and the cross product of the rows, (X,Y,D)(X, Y, D), spans it. So (c2,s2)=(X/D,Y/D)(c_2, s_2) = (X/D, Y/D), as line L7 computes, and by Step 2 it lies on the unit circle. Line L8 then gives θ1\theta_1 by Step 1. □\square

Conclusion

For a general arm and target, the algorithm returns every solution, and each real root of q~\tilde q gives exactly one solution. The angle θ3=π\theta_3 = \pi is the root x3=∞x_3 = \infty; it shows up as a drop of the degree of q~\tilde q, and the implementation then tests it as a candidate. Since q~\tilde q has degree at most 4, a general 3R arm has at most 4 solutions for a position. The implementation checks every candidate by forward kinematics, which guards against roots that rounding has moved off the real axis or onto it.

Complexity

For a fixed arm type, every step has a fixed size, so the work is a constant. In terms of the degree dd of the final polynomial, building the matrix costs a constant for a fixed number of joints, and finding all roots costs Θ(d3)\Theta(d^3) with a companion matrix or with the eigenvalue form of Manocha and Canny, whose matrices have size proportional to dd, in the real RAM, counting a fixed number of QR iterations per eigenvalue, as is usual. The back substitution costs Θ(1)\Theta(1) per root. For the 6R arm this is an eigenvalue problem of size 24, which runs in well under a millisecond.

Properties

  • All solutions. The method finds every solution, with no starting guess, unlike Newton-Raphson inverse kinematics.
  • General arms only. Special geometry makes some matrices singular; such arms need a special version or a different method.
  • Extraneous roots. The determinant contains factors that give no solution, such as (1+x32)4(1 + x_3^2)^4 for the 6R arm; they must be removed or the roots checked.
  • Half angle at π\pi. The angle θ3=π\theta_3 = \pi maps to x3=∞x_3 = \infty and shows up only as a drop of the degree.
  • Numerical accuracy. Expanding the determinant into coefficients is badly conditioned; the eigenvalue form is the accurate way.

Variants and improvements

  • Eigenvalue form. Manocha and Canny (1994) solve the matrix polynomial as a generalized eigenvalue problem and get all solutions fast and accurately.
  • Lee and Liang. Lee and Liang (1988) first reached a polynomial of degree 16, for the equivalent 7R closed loop.
  • Continuation. Homotopy continuation, as in Tsai and Morgan (1985), tracks all solutions from a start system instead of eliminating.
  • Other elimination. Gröbner bases and other resultants give the same polynomial in other ways, with more cost.
  • Special arms. When three axes meet or are parallel, the problem splits into smaller ones, see kinematic decoupling and the Paden-Kahan subproblems.

When to use it

Use the Raghavan-Roth method, in the eigenvalue form, when an arm with six revolute joints has no special geometry and all solutions are needed, for example in design studies of new arms or in offline planning that must choose among all poses. For an arm with a spherical wrist, use the closed form of kinematic decoupling; for one solution near the current pose, use damped least squares.

Pitfalls

  • Expanding the determinant. Forming the coefficients of the polynomial of degree 16 loses many digits; prefer the eigenvalue form.
  • Dividing by a factor. Long division by an extraneous factor can be inaccurate when its leading coefficient is small; the implementation here uses a least squares division.
  • Near double roots. Two solutions that are close give roots that rounding can push off the real axis; check by forward kinematics and with a tolerance.
  • Degenerate arms. If a1=0a_1 = 0 or sin⁡α1=0\sin\alpha_1 = 0 in the 3R version, the two equations no longer fix θ2\theta_2, and the method needs a special case.

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.

raghavan_roth_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/raghavan-roth-method/. The authors are listed in prov/MTT21K.jsonl.
"""The elimination of Raghavan and Roth, shown on the position problem of a
general 3R arm.

The arm has standard Denavit-Hartenberg parameters (a_i, alpha_i, d_i) for
i = 1, 2, 3, with T_i = Rz(theta_i) Tz(d_i) Tx(a_i) Rx(alpha_i). The task is
to put the origin of frame 3 at a point p. A general 3R arm has at most 4
solutions.

The steps are the same as for the 6R arm, on a smaller system:

- two equations free of theta_1, from |p|^2 and p_z, each linear in
  (cos theta_2, sin theta_2, 1) with coefficients linear in
  (cos theta_3, sin theta_3);
- the half angle substitution x = tan(theta / 2) for theta_2 and theta_3;
- the dialytic step: multiply each equation by x2 to get a 4 by 4 system in
  the power products (x2^3, x2^2, x2, 1), whose determinant is a polynomial
  of degree 8 in x3;
- the removal of an extraneous factor, which leaves a quartic;
- the roots of the quartic, then theta_2 from a null vector and theta_1
  from the first two coordinates of p.

Polynomials are lists of coefficients, the constant first. The module needs
only the standard library.
"""

import cmath
import itertools
import math


# Polynomial arithmetic.

def padd(a, b):
    n = max(len(a), len(b))
    return [(a[i] if i < len(a) else 0.0) + (b[i] if i < len(b) else 0.0) for i in range(n)]


def pscale(s, a):
    return [s * x for x in a]


def pmul(a, b):
    out = [0.0] * (len(a) + len(b) - 1)
    for i, x in enumerate(a):
        for j, y in enumerate(b):
            out[i + j] += x * y
    return out


def peval(a, x):
    out = 0.0
    for c in reversed(a):
        out = out * x + c
    return out


def ptrim(a, rel=1e-12):
    scale = max((abs(c) for c in a), default=0.0)
    a = list(a)
    while len(a) > 1 and abs(a[-1]) <= rel * scale:
        a.pop()
    return a


def exact_divide(a, b):
    """Return (q, residual) where q minimizes |a - b q| in least squares.

    When b divides a, this gives the quotient without the loss of accuracy
    that long division from one end has when that end of b is small.
    """
    n = len(a) - len(b) + 1
    # Column j of the convolution matrix is b shifted by j.
    cols = [[0.0] * j + list(b) + [0.0] * (n - 1 - j) for j in range(n)]
    g = [[sum(x * y for x, y in zip(ci, cj)) for cj in cols] for ci in cols]
    r = [sum(x * y for x, y in zip(ci, a)) for ci in cols]
    for c in range(n):  # Gaussian elimination with partial pivoting
        piv = max(range(c, n), key=lambda i: abs(g[i][c]))
        g[c], g[piv], r[c], r[piv] = g[piv], g[c], r[piv], r[c]
        for i in range(c + 1, n):
            f = g[i][c] / g[c][c]
            g[i] = [x - f * y for x, y in zip(g[i], g[c])]
            r[i] -= f * r[c]
    q = [0.0] * n
    for i in range(n - 1, -1, -1):
        q[i] = (r[i] - sum(g[i][j] * q[j] for j in range(i + 1, n))) / g[i][i]
    res = padd(a, pscale(-1.0, pmul(b, q)))
    return q, math.sqrt(sum(x * x for x in res))


def roots(a, iters=500):
    """All complex roots of the polynomial a, by the Durand-Kerner iteration."""
    a = ptrim(a)
    n = len(a) - 1
    if n < 1:
        return []
    mon = [c / a[-1] for c in a]
    z = [(0.4 + 0.9j) ** k for k in range(n)]
    for _ in range(iters):
        delta = 0.0
        for i in range(n):
            num = peval(mon, z[i])
            den = 1.0
            for j in range(n):
                if j != i:
                    den *= z[i] - z[j]
            step = num / den
            z[i] -= step
            delta = max(delta, abs(step))
        if delta < 1e-15:
            break
    return z


# The arm.

def dh_matrix(theta, d, a, alpha):
    ct, st, ca, sa = math.cos(theta), math.sin(theta), math.cos(alpha), math.sin(alpha)
    return [[ct, -st * ca, st * sa, a * ct],
            [st, ct * ca, -ct * sa, a * st],
            [0.0, sa, ca, d],
            [0.0, 0.0, 0.0, 1.0]]


def mat4(a, b):
    return [[sum(a[i][k] * b[k][j] for k in range(4)) for j in range(4)] for i in range(4)]


def fk(dh, q):
    """The position of the origin of frame 3; dh is [(a_i, alpha_i, d_i)] for i = 1, 2, 3."""
    t = [[1.0 if i == j else 0.0 for j in range(4)] for i in range(4)]
    for (a, alpha, d), theta in zip(dh, q):
        t = mat4(t, dh_matrix(theta, d, a, alpha))
    return [t[0][3], t[1][3], t[2][3]]


def lin(u, v, w):
    """(1 + x^2)(u + v cos + w sin) with cos = (1 - x^2)/(1 + x^2) and sin = 2x/(1 + x^2)."""
    return [u + v, 2.0 * w, u - v]


def coefficient_polys(dh, p):
    """Return the polynomials in x3 of P1, Q1, K, P2, Q2, L and of h1, h2,
    each multiplied by (1 + x3^2).

    E1: P1 cos2 + Q1 sin2 + K = 0 comes from |p|^2, and
    E2: P2 cos2 + Q2 sin2 + L = 0 comes from p_z.
    """
    (a1, al1, d1), (a2, al2, d2), (a3, al3, d3) = dh
    ca1, sa1, ca2, sa2 = math.cos(al1), math.sin(al1), math.cos(al2), math.sin(al2)
    pp = sum(x * x for x in p)
    h1 = lin(a2, a3, 0.0)
    h2 = lin(-sa2 * d3, 0.0, ca2 * a3)
    hh0 = a2 * a2 + d2 * d2 + a3 * a3 + d3 * d3 + 2.0 * ca2 * d2 * d3
    k = lin(hh0 + a1 * a1 - d1 * d1 - pp + 2.0 * d1 * p[2], 2.0 * a2 * a3, 2.0 * d2 * sa2 * a3)  # @line L1
    ell = lin(d1 - p[2] + ca1 * (d2 + ca2 * d3), 0.0, ca1 * sa2 * a3)  # @line L1
    p1, q1 = pscale(2.0 * a1, h1), pscale(-2.0 * a1, h2)  # @line L1
    p2, q2 = pscale(sa1, h2), pscale(sa1, h1)  # @line L1
    return p1, q1, k, p2, q2, ell, h1, h2


def dialytic_matrix(dh, p):
    """The 4 by 4 matrix of polynomials in x3 that multiplies (x2^3, x2^2, x2, 1)."""
    p1, q1, k, p2, q2, ell, _, _ = coefficient_polys(dh, p)
    rows = []
    for pj, qj, kj in ((p1, q1, k), (p2, q2, ell)):
        # (1 + x2^2)(P cos2 + Q sin2 + K) = (K - P) x2^2 + 2Q x2 + (K + P)  @line L2
        a, b, c = padd(kj, pscale(-1.0, pj)), pscale(2.0, qj), padd(kj, pj)
        rows.append([a, b, c, [0.0]])  # @line L3
        rows.append([[0.0], a, b, c])  # @line L3
    return [rows[0], rows[1], rows[2], rows[3]]


def poly_det(m):
    """The determinant of a square matrix of polynomials, by the Leibniz formula."""
    n = len(m)
    out = [0.0]
    for perm in itertools.permutations(range(n)):
        inv = sum(1 for i in range(n) for j in range(i + 1, n) if perm[i] > perm[j])
        term = [1.0]
        for i in range(n):
            term = pmul(term, m[i][perm[i]])
        out = padd(out, pscale(-1.0 if inv % 2 else 1.0, term))
    return out


def extraneous_factor(dh, p):
    """(1 + x3^2)^2 (h1^2 + h2^2): a factor of the determinant that gives no solution."""
    h1, h2 = coefficient_polys(dh, p)[6:8]
    return padd(pmul(h1, h1), pmul(h2, h2))


def direct_quartic(dh, p):
    """The quartic 4 a1^2 L^2 + sin^2(alpha1) K^2 - 4 a1^2 sin^2(alpha1)(h1^2 + h2^2), times (1 + x3^2)^2."""
    (a1, al1, _), _, _ = dh
    sa1 = math.sin(al1)
    _, _, k, _, _, ell, h1, h2 = coefficient_polys(dh, p)
    e = padd(pmul(h1, h1), pmul(h2, h2))
    return padd(padd(pscale(4.0 * a1 * a1, pmul(ell, ell)), pscale(sa1 * sa1, pmul(k, k))), pscale(-4.0 * a1 * a1 * sa1 * sa1, e))


def solve_3r(dh, p, tol=1e-7):
    """Return the list of joint vectors (theta1, theta2, theta3) that put the origin of frame 3 at p."""
    (a1, al1, d1), (a2, al2, d2), (a3, al3, d3) = dh
    ca1, sa1, ca2, sa2 = math.cos(al1), math.sin(al1), math.cos(al2), math.sin(al2)
    delta = poly_det(dialytic_matrix(dh, p))  # @line L4
    quartic, _ = exact_divide(delta, pscale(4.0, extraneous_factor(dh, p)))  # @line L5
    quartic = ptrim(quartic)
    candidates = []
    for z in roots(quartic):  # @line L6
        if abs(z.imag) <= 1e-6 * (1.0 + abs(z)):
            candidates.append(2.0 * math.atan(z.real))  # @line L7
    if len(quartic) < 5:
        candidates.append(math.pi)  # the degree dropped: x3 = infinity is a root
    sols = []
    pz = p[2]
    for t3 in candidates:
        c3, s3 = math.cos(t3), math.sin(t3)
        h = [a2 + a3 * c3, ca2 * a3 * s3 - sa2 * d3, d2 + sa2 * a3 * s3 + ca2 * d3]
        hh = sum(x * x for x in h)
        k = hh + a1 * a1 - d1 * d1 - sum(x * x for x in p) + 2.0 * d1 * pz
        ell = d1 + ca1 * h[2] - pz
        r1 = (2.0 * a1 * h[0], -2.0 * a1 * h[1], k)
        r2 = (sa1 * h[1], sa1 * h[0], ell)
        # (cos2, sin2, 1) is a null vector of the 2 by 3 matrix [r1; r2].  @line L7
        n0, n1, n2 = r1[1] * r2[2] - r1[2] * r2[1], r1[2] * r2[0] - r1[0] * r2[2], r1[0] * r2[1] - r1[1] * r2[0]
        if abs(n2) < 1e-12:
            continue
        t2 = math.atan2(n1 / n2, n0 / n2)  # @line L7
        c2, s2 = math.cos(t2), math.sin(t2)
        f = [c2 * h[0] - s2 * h[1], s2 * h[0] + c2 * h[1], h[2]]
        g = [a1 + f[0], ca1 * f[1] - sa1 * f[2], d1 + sa1 * f[1] + ca1 * f[2]]
        t1 = math.atan2(p[1], p[0]) - math.atan2(g[1], g[0])  # @line L8
        q = [math.remainder(t1, 2.0 * math.pi), t2, t3]
        err = math.sqrt(sum((x - y) ** 2 for x, y in zip(fk(dh, q), p)))
        if err <= tol * (1.0 + math.sqrt(sum(x * x for x in p))):  # @line L9
            if all(max(abs(math.remainder(x - y, 2.0 * math.pi)) for x, y in zip(q, s)) > 1e-6 for s in sols):
                sols.append(q)
    return sols  # @line L9
test_raghavan_roth_method.py 140 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/raghavan-roth-method/. The authors are listed in prov/MTT21K.jsonl.
"""Tests of the elimination of Raghavan and Roth on the 3R position problem:
the determinant of the dialytic matrix against the product of the extraneous
factor and the quartic found by hand, the example of the page, every root
checked by forward kinematics, and the solution set against a brute force
of Newton's method from many starts."""

import math
import random

from raghavan_roth_method import (
    coefficient_polys, dialytic_matrix, direct_quartic, exact_divide, extraneous_factor, fk, peval,
    pmul, poly_det, pscale, roots, solve_3r)


def rand_arm(rng):
    return [(rng.uniform(0.2, 1.5), rng.uniform(-3.0, 3.0), rng.uniform(-1.0, 1.0)) for _ in range(3)]


def same(q, r, tol=1e-6):
    return max(abs(math.remainder(a - b, 2.0 * math.pi)) for a, b in zip(q, r)) < tol


def test_polynomial_helpers():
    a = [1.0, -3.0, 2.0]  # 2x^2 - 3x + 1 = (2x - 1)(x - 1)
    zs = sorted(z.real for z in roots(a))
    assert abs(zs[0] - 0.5) < 1e-12 and abs(zs[1] - 1.0) < 1e-12
    b = [2.0, 0.0, 1.0]
    q, res = exact_divide(pmul(a, b), b)
    assert max(abs(x - y) for x, y in zip(q, a)) < 1e-12 and res < 1e-12


def test_determinant_is_four_times_extraneous_factor_times_quartic():
    rng = random.Random(1)
    for _ in range(30):
        dh = rand_arm(rng)
        p = fk(dh, [rng.uniform(-3.0, 3.0) for _ in range(3)])
        delta = poly_det(dialytic_matrix(dh, p))
        assert len(delta) == 9  # degree 8
        prod = pscale(4.0, pmul(extraneous_factor(dh, p), direct_quartic(dh, p)))
        scale = max(abs(c) for c in delta)
        assert max(abs(x - y) for x, y in zip(delta, prod)) < 1e-10 * scale
        # The extraneous factor (1 + x3^2)^2 (h1^2 + h2^2) has no real root for these arms.
        e = extraneous_factor(dh, p)
        assert min(peval(e, -10.0 + 0.01 * k) for k in range(2001)) > 0.0


def test_example_of_the_page():
    dh = [(0.5, 2.0 * math.pi / 3.0, 0.5), (0.5, math.pi / 6.0, 1.0), (1.5, 0.0, 0.0)]
    p = fk(dh, [1.0, -0.5, -1.0])
    assert max(abs(a - b) for a, b in zip(p, [0.209252, 1.203738, -1.059310])) < 1e-6
    e = extraneous_factor(dh, p)
    assert max(abs(a - b) for a, b in zip(e, [4.0, 0.0, 2.75, 0.0, 1.0])) < 1e-12
    delta = poly_det(dialytic_matrix(dh, p))
    quartic, res = exact_divide(delta, pscale(4.0, e))
    assert res < 1e-10
    assert max(abs(a - b) for a, b in zip(quartic, [-0.559587, 4.377061, 4.164800, -9.122939, 2.474388])) < 1e-6
    sols = sorted(solve_3r(dh, p), key=lambda q: math.tan(q[2] / 2.0))
    assert len(sols) == 4
    expect = [[1.0, -0.5, -1.0], [-2.125286, -2.692609, 0.234761], [-2.873565, 2.405672, 1.757909], [2.098607, 2.860655, 2.479220]]
    for q, r in zip(sols, expect):
        assert same(q, r, 1e-6)
    xs = [math.tan(q[2] / 2.0) for q in sols]
    assert max(abs(a - b) for a, b in zip(xs, [-0.546302, 0.117923, 1.207093, 2.908236])) < 1e-6


def newton_solutions(dh, p, rng, starts=30):
    """Brute force: Newton's method on fk(q) = p from many random starts."""
    found = []
    for _ in range(starts):
        q = [rng.uniform(-math.pi, math.pi) for _ in range(3)]
        for _ in range(25):
            f = [a - b for a, b in zip(fk(dh, q), p)]
            if max(abs(x) for x in f) < 1e-13:
                break
            h = 1e-7
            cols = []
            for j in range(3):
                qp, qm = list(q), list(q)
                qp[j] += h
                qm[j] -= h
                cols.append([(a - b) / (2.0 * h) for a, b in zip(fk(dh, qp), fk(dh, qm))])
            jm = [[cols[j][i] for j in range(3)] for i in range(3)]
            det = (jm[0][0] * (jm[1][1] * jm[2][2] - jm[1][2] * jm[2][1])
                   - jm[0][1] * (jm[1][0] * jm[2][2] - jm[1][2] * jm[2][0])
                   + jm[0][2] * (jm[1][0] * jm[2][1] - jm[1][1] * jm[2][0]))
            if abs(det) < 1e-12:
                break
            # Cramer's rule for jm dq = -f.
            dq = []
            for j in range(3):
                mj = [row[:] for row in jm]
                for i in range(3):
                    mj[i][j] = -f[i]
                dj = (mj[0][0] * (mj[1][1] * mj[2][2] - mj[1][2] * mj[2][1])
                      - mj[0][1] * (mj[1][0] * mj[2][2] - mj[1][2] * mj[2][0])
                      + mj[0][2] * (mj[1][0] * mj[2][1] - mj[1][1] * mj[2][0]))
                dq.append(dj / det)
            q = [a + b for a, b in zip(q, dq)]
        if max(abs(a - b) for a, b in zip(fk(dh, q), p)) < 1e-10:
            q = [math.remainder(x, 2.0 * math.pi) for x in q]
            if all(not same(q, r) for r in found):
                found.append(q)
    return found


def test_against_newton_from_many_starts():
    rng = random.Random(2)
    counts = {}
    for _ in range(8):
        dh = rand_arm(rng)
        q_true = [rng.uniform(-3.0, 3.0) for _ in range(3)]
        p = fk(dh, q_true)
        sols = solve_3r(dh, p)
        assert 1 <= len(sols) <= 4
        counts[len(sols)] = counts.get(len(sols), 0) + 1
        for q in sols:
            assert max(abs(a - b) for a, b in zip(fk(dh, q), p)) < 1e-9
        assert any(same(q, q_true) for q in sols)
        brute = newton_solutions(dh, p, rng)
        # Every solution that Newton finds is one of ours, and with 30 starts Newton finds them all here.
        for q in brute:
            assert any(same(q, r) for r in sols)
        assert len(brute) == len(sols)
    assert counts.get(4, 0) >= 1 and counts.get(2, 0) >= 1


def test_back_substitution_satisfies_both_equations():
    rng = random.Random(3)
    for _ in range(20):
        dh = rand_arm(rng)
        p = fk(dh, [rng.uniform(-3.0, 3.0) for _ in range(3)])
        for q in solve_3r(dh, p):
            x3 = math.tan(q[2] / 2.0)
            w = 1.0 + x3 * x3
            p1, q1, k, p2, q2, ell = (peval(c, x3) / w for c in coefficient_polys(dh, p)[:6])
            c2, s2 = math.cos(q[1]), math.sin(q[1])
            assert abs(p1 * c2 + q1 * s2 + k) < 1e-9
            assert abs(p2 * c2 + q2 * s2 + ell) < 1e-9

History

Pieper (1968) solved arms with three intersecting axes in closed form and noted that the general 6R arm was much harder. Duffy and Crane (1980) reduced the general 7R closed loop, equivalent to the 6R arm, to a polynomial of degree 32 in one half angle tangent, as the determinant of a 16×1616 \times 16 matrix. Tsai and Morgan (1985) found 16 solutions by continuation and conjectured that 16 is the bound, and Primrose (1986) proved that there are at most 16. Lee and Liang (1988) reached a polynomial of degree 16. Raghavan and Roth presented their elimination in 1990 and published it in 1993; it is the form found in most texts. Manocha and Canny (1994) turned it into an eigenvalue problem.

References

  1. Madhusudan Raghavan and Bernard Roth, Inverse kinematics of the general 6R manipulator and related linkages, Journal of Mechanical Design 115(3), 502-508, 1993, the 14 equations, the elimination to a 12 by 12 matrix and the polynomial of degree 16
  2. Hong-You Lee and Chong-Gao Liang, Displacement analysis of the general spatial 7-link 7R mechanism, Mechanism and Machine Theory 23(3), 219-226, 1988, the first reduction to a polynomial of degree 16 for the 7R loop, which is equivalent to the 6R arm
  3. Dinesh Manocha and John F. Canny, Efficient inverse kinematics for general 6R manipulators, IEEE Transactions on Robotics and Automation 10(5), 648-657, 1994, the matrix polynomial of the elimination solved as an eigenvalue problem

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