Algorithm Search⌘K

Definitioncore

Space and body Jacobian

Also called space Jacobian, body Jacobian.

The Jacobians of a chain that give the end effector twist in the fixed frame and in the end effector frame, related by an adjoint.

The space Jacobian Js(q)J_s(q) and the body Jacobian Jb(q)J_b(q) of a robot arm map the joint velocities q˙\dot q to the velocity of the end effector, written as a twist: Vs=Js(q)q˙\mathcal V_s = J_s(q)\dot q in the fixed frame {s}, and Vb=Jb(q)q˙\mathcal V_b = J_b(q)\dot q in the end effector frame {b}. Both are 6×n6 \times n matrices for an arm with nn joints, and they come straight from the screw axes of the product of exponentials formula: column ii is the screw axis of joint ii at the current configuration, seen from {s} or from {b}. The two are related by the adjoint map, Jb=AdTbsJsJ_b = \mathrm{Ad}_{T_{bs}} J_s. This page uses the conventions of Lynch and Park, with the angular part first; the geometric Jacobian of Siciliano et al. puts the linear part first and uses the velocity of the end effector origin, and the conversion is below.

Definition

A twist is V=(ω,v)∈R6\mathcal V = (\omega, v) \in \mathbb{R}^6, angular part first, with the 4×44 \times 4 matrix [V]=([ω]v00)[\mathcal V] = \begin{pmatrix} [\omega] & v \\ 0 & 0 \end{pmatrix}, where [ω]x=ω×x[\omega] x = \omega \times x. For a moving pose T(t)∈SE(3)T(t) \in SE(3) of the end effector frame {b} in {s}, the spatial twist and the body twist are defined by

[Vs]=T˙T−1,[Vb]=T−1T˙.[\mathcal V_s] = \dot T T^{-1}, \qquad [\mathcal V_b] = T^{-1} \dot T.

In Vs=(ωs,vs)\mathcal V_s = (\omega_s, v_s), ωs\omega_s is the angular velocity in {s} coordinates, and vsv_s is the velocity of the point of the body that is at the origin of {s}. In Vb=(ωb,vb)\mathcal V_b = (\omega_b, v_b), ωb\omega_b is the angular velocity in {b} coordinates and vbv_b is the velocity of the origin of {b}, in {b} coordinates.

Let the arm have forward kinematics in the space form T(q)=e[S1]q1⋯e[Sn]qnMT(q) = e^{[\mathcal S_1] q_1} \cdots e^{[\mathcal S_n] q_n} M and in the body form T(q)=Me[B1]q1⋯e[Bn]qnT(q) = M e^{[\mathcal B_1] q_1} \cdots e^{[\mathcal B_n] q_n}, with the screw axes Si\mathcal S_i in {s} and Bi=AdM−1Si\mathcal B_i = \mathrm{Ad}_{M^{-1}} \mathcal S_i in {b}, all at the home configuration.

Definition. The space Jacobian Js(q)J_s(q) is the 6×n6 \times n matrix with Vs=Js(q)q˙\mathcal V_s = J_s(q)\dot q for every q˙\dot q. Its columns are

Js1=S1,Jsi(q)=Ade[S1]q1⋯e[Si−1]qi−1(Si),i=2,…,n.J_{s1} = \mathcal S_1, \qquad J_{si}(q) = \mathrm{Ad}_{e^{[\mathcal S_1] q_1} \cdots e^{[\mathcal S_{i-1}] q_{i-1}}}(\mathcal S_i), \quad i = 2, \dots, n.

The body Jacobian Jb(q)J_b(q) is the 6×n6 \times n matrix with Vb=Jb(q)q˙\mathcal V_b = J_b(q)\dot q. Its columns are

Jbn=Bn,Jbi(q)=Ade−[Bn]qn⋯e−[Bi+1]qi+1(Bi),i=1,…,n−1.J_{bn} = \mathcal B_n, \qquad J_{bi}(q) = \mathrm{Ad}_{e^{-[\mathcal B_n] q_n} \cdots e^{-[\mathcal B_{i+1}] q_{i+1}}}(\mathcal B_i), \quad i = 1, \dots, n - 1.

Here AdT=(R0[p]RR)\mathrm{Ad}_T = \begin{pmatrix} R & 0 \\ [p] R & R \end{pmatrix} for T=(R,p)T = (R, p), and AdTV\mathrm{Ad}_T \mathcal V is the twist V\mathcal V written in the frame that TT maps from.

Why the columns are right. By the product rule, T˙T−1=∑i∂T∂qiT−1q˙i\dot T T^{-1} = \sum_i \frac{\partial T}{\partial q_i} T^{-1} \dot q_i. Write Ei=e[S1]q1⋯e[Si−1]qi−1E_i = e^{[\mathcal S_1] q_1} \cdots e^{[\mathcal S_{i-1}] q_{i-1}}. Since ddqie[Si]qi=[Si]e[Si]qi\frac{d}{dq_i} e^{[\mathcal S_i] q_i} = [\mathcal S_i] e^{[\mathcal S_i] q_i}, all factors after EiE_i cancel against T−1T^{-1}, and ∂T∂qiT−1=Ei[Si]Ei−1=[AdEiSi]\frac{\partial T}{\partial q_i} T^{-1} = E_i [\mathcal S_i] E_i^{-1} = [\mathrm{Ad}_{E_i} \mathcal S_i]. So column ii of JsJ_s is AdEiSi\mathrm{Ad}_{E_i} \mathcal S_i: the screw axis of joint ii after joints 11 to i−1i - 1 have moved it. The body case is the mirror image: T−1∂T/∂qiT^{-1} \partial T / \partial q_i keeps the factors after joint ii, which gives the adjoint of e−[Bn]qn⋯e−[Bi+1]qi+1e^{-[\mathcal B_n] q_n} \cdots e^{-[\mathcal B_{i+1}] q_{i+1}}.

The relation. Since T−1T˙=T−1(T˙T−1)TT^{-1} \dot T = T^{-1} (\dot T T^{-1}) T, the two twists satisfy Vb=AdT−1Vs\mathcal V_b = \mathrm{Ad}_{T^{-1}} \mathcal V_s, so for all qq

Jb(q)=AdTbs(q)Js(q),Js(q)=AdTsb(q)Jb(q),J_b(q) = \mathrm{Ad}_{T_{bs}(q)} J_s(q), \qquad J_s(q) = \mathrm{Ad}_{T_{sb}(q)} J_b(q),

with Tsb=T(q)T_{sb} = T(q) and Tbs=T(q)−1T_{bs} = T(q)^{-1}. AdT\mathrm{Ad}_T is invertible, so JsJ_s and JbJ_b have the same rank at every qq, and the kinematic singularities do not depend on the frame.

Relation to the geometric Jacobian. The geometric Jacobian J=(JP,JO)J = (J_P, J_O) gives the velocity p˙e\dot p_e of the end effector origin and the angular velocity, linear part first. With T(q)=(Re,pe)T(q) = (R_e, p_e), ωs=JOq˙\omega_s = J_O \dot q, vs=p˙e−ωs×pev_s = \dot p_e - \omega_s \times p_e, ωb=ReTωs\omega_b = R_e^{\mathsf T} \omega_s and vb=ReTp˙ev_b = R_e^{\mathsf T} \dot p_e. So JsJ_s has the blocks JOJ_O over JP+[pe]JOJ_P + [p_e] J_O, and JbJ_b has ReTJOR_e^{\mathsf T} J_O over ReTJPR_e^{\mathsf T} J_P. Murray, Li and Sastry use the same twists as Lynch and Park but write the linear part first, so their Jacobians have the two blocks of rows swapped.

Computation. Both forms build the product of exponentials once, from one end of the chain. The code on this page follows these lines.

  1. SPACE-JACOBIAN(S_1, ..., S_n, q)
  2. 1T ← I
  3. 2for i ← 1 to n
  4. 3J_si ← Ad_T S_i ▷ T = e^[S_1]q_1 ... e^[S_(i-1)]q_(i-1)
  5. 4T ← T e^{[S_i] q_i}
  6. 5return J_s
  7. BODY-JACOBIAN(B_1, ..., B_n, q)
  8. 6T ← I
  9. 7for i ← n down to 1
  10. 8J_bi ← Ad_T B_i ▷ T = e^-[B_n]q_n ... e^-[B_(i+1)]q_(i+1)
  11. 9T ← T e^{-[B_i] q_i}
  12. 10return J_b

Each pass of the loop costs one exponential of SE(3), one 4×44 \times 4 product and one 6×66 \times 6 adjoint times a vector, which is a constant number of operations. So each Jacobian costs Θ(n)\Theta(n) operations and Θ(n)\Theta(n) space in the real RAM.

Examples and non-examples

The planar 2R arm. Two revolute joints about vertical axes through (0,0,0)(0, 0, 0) and (1,0,0)(1, 0, 0), links L1=L2=1L_1 = L_2 = 1 m, and the end effector frame at (2,0,0)(2, 0, 0) at home, so M=(I,(2,0,0))M = (I, (2, 0, 0)). A revolute axis with unit direction ω\omega through the point aa has the screw axis (ω,−ω×a)(\omega, -\omega \times a), so

S1=(0,0,1,0,0,0),S2=(0,0,1,0,−1,0),B1=(0,0,1,0,2,0),B2=(0,0,1,0,1,0).\mathcal S_1 = (0, 0, 1, 0, 0, 0), \quad \mathcal S_2 = (0, 0, 1, 0, -1, 0), \quad \mathcal B_1 = (0, 0, 1, 0, 2, 0), \quad \mathcal B_2 = (0, 0, 1, 0, 1, 0).

At q=(0,π/2)q = (0, \pi/2), T(q)=(Rz(π/2),(1,1,0))T(q) = (R_z(\pi/2), (1, 1, 0)). Column 1 of JsJ_s is S1\mathcal S_1, and column 2 is Ade[S1]⋅0S2=S2\mathrm{Ad}_{e^{[\mathcal S_1] \cdot 0}} \mathcal S_2 = \mathcal S_2. Column 2 of JbJ_b is B2\mathcal B_2, and column 1 is Ade−[B2]π/2B1=(0,0,1,1,1,0)\mathrm{Ad}_{e^{-[\mathcal B_2]\pi/2}} \mathcal B_1 = (0, 0, 1, 1, 1, 0). In full, with the rows (ωx,ωy,ωz,vx,vy,vz)(\omega_x, \omega_y, \omega_z, v_x, v_y, v_z):

Js=(000011000−100),Jb=(000011101100).J_s = \begin{pmatrix} 0 & 0 \\ 0 & 0 \\ 1 & 1 \\ 0 & 0 \\ 0 & -1 \\ 0 & 0 \end{pmatrix}, \qquad J_b = \begin{pmatrix} 0 & 0 \\ 0 & 0 \\ 1 & 1 \\ 1 & 0 \\ 1 & 1 \\ 0 & 0 \end{pmatrix}.

The relation Jb=AdT−1JsJ_b = \mathrm{Ad}_{T^{-1}} J_s holds: T−1=(Rz(−π/2),(−1,1,0))T^{-1} = (R_z(-\pi/2), (-1, 1, 0)), and for column 1, Rz(−π/2) ω=(0,0,1)R_z(-\pi/2)\,\omega = (0, 0, 1) and [(−1,1,0)](0,0,1)=(1,1,0)[(-1, 1, 0)](0, 0, 1) = (1, 1, 0). The velocity of the end effector origin is RevbR_e v_b: for q˙=(1,0)\dot q = (1, 0) it is Rz(π/2)(1,1,0)=(−1,1,0)R_z(\pi/2)(1, 1, 0) = (-1, 1, 0), the first column of the linear Jacobian (−1−110)\begin{pmatrix} -1 & -1 \\ 1 & 0 \end{pmatrix} of the 2R check values, whose determinant is sin⁡q2=1\sin q_2 = 1. The vsv_s part of column 1 of JsJ_s is zero although the end effector moves, because vsv_s is the velocity of the body point at the origin of {s}, which is on the axis of joint 1.

Where the columns depend on qq. Column ii of JsJ_s depends only on q1,…,qi−1q_1, \dots, q_{i-1}, so the first column is constant. Column ii of JbJ_b depends only on qi+1,…,qnq_{i+1}, \dots, q_n, so the last column is constant. In the 2R example, moving q2q_2 changes column 1 of JbJ_b but not column 1 of JsJ_s.

A prismatic joint. Its screw axis is (0,v)(0, v) with ∣v∣=1|v| = 1, and the adjoint keeps the first three entries zero, so its column has no angular part in either Jacobian.

Non-example: the geometric Jacobian. The lower block of JsJ_s is JP+[pe]JOJ_P + [p_e] J_O, not JPJ_P; the two agree only for columns whose angular part is zero or when pe=0p_e = 0.

Non-example: the analytic Jacobian. The derivative of a minimal pose vector such as position and Euler angles is the analytic Jacobian; it is not a map to a twist, and it has extra singular points from the angles.

Non-example: ∂ξ/∂q\partial \xi / \partial q for ξ=log⁡T(q)\xi = \log T(q). The derivative of the exponential coordinates of the pose is not JsJ_s or JbJ_b; it differs by the Jacobian of the exponential map of SE(3), which equals II only at ξ=0\xi = 0.

  • Geometric Jacobian: linear part first, with the velocity of the end effector origin.
  • Analytic Jacobian: the derivative of a minimal pose vector.
  • Adjoint map: the change of frame of twists that relates JsJ_s and JbJ_b.
  • Jacobian statics duality: τ=JsTFs=JbTFb\tau = J_s^{\mathsf T} \mathcal F_s = J_b^{\mathsf T} \mathcal F_b, where Fs\mathcal F_s and Fb\mathcal F_b are the same wrench in {s} and in {b}.
  • Kinematic singularity: a configuration where JsJ_s, and so JbJ_b, loses rank.
  • Jacobian pseudoinverse method: numerical inverse kinematics that uses JbJ_b and the body twist error.
  • Screw motion: the motion that a single column produces when only its joint moves.

Code

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.

rbm.pyI0RawGitHub
# 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
space_and_body_jacobian.py 63 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/space-and-body-jacobian/. The authors are listed in prov/DQFEN4.jsonl.
"""Space and body Jacobians of an open chain in product of exponentials form.

Lynch and Park, Modern Robotics, Section 5.1:
- T(q) = exp([S1] q1) ... exp([Sn] qn) M with space screw axes S_i, and
  column i of J_s is Ad of exp([S1] q1) ... exp([S_i-1] q_i-1) applied to S_i.
- T(q) = M exp([B1] q1) ... exp([Bn] qn) with body screw axes B_i, and
  column i of J_b is Ad of exp(-[Bn] qn) ... exp(-[B_i+1] q_i+1) applied to B_i.
- B_i = Ad of M^-1 applied to S_i, and J_b = Ad of T^-1 applied to J_s.

A screw axis is (omega, v), angular part first. Matrices are lists of rows.
"""

import rbm


def space_jacobian(slist, q):
    """Return the 6 by n space Jacobian J_s(q)."""
    t = rbm.eye(4)  # @line L1
    cols = []
    for s, x in zip(slist, q):  # @line L2
        cols.append(rbm.matvec(rbm.adjoint(t), s))  # @line L3
        t = rbm.mul(t, rbm.se3_exp([y * x for y in s]))  # @line L4
    return rbm.transpose(cols)  # @line L5


def body_jacobian(blist, q):
    """Return the 6 by n body Jacobian J_b(q)."""
    n = len(blist)
    t = rbm.eye(4)  # @line L6
    cols = [None] * n
    for i in range(n - 1, -1, -1):  # @line L7
        cols[i] = rbm.matvec(rbm.adjoint(t), blist[i])  # @line L8
        t = rbm.mul(t, rbm.se3_exp([-y * q[i] for y in blist[i]]))  # @line L9
    return rbm.transpose(cols)  # @line L10


def fk_space(slist, m, q):
    """Return T(q) = exp([S1] q1) ... exp([Sn] qn) M."""
    t = rbm.eye(4)
    for s, x in zip(slist, q):
        t = rbm.mul(t, rbm.se3_exp([y * x for y in s]))
    return rbm.mul(t, m)


def 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_screws(slist, m):
    """Return B_i = Ad of M^-1 applied to S_i."""
    ad = rbm.adjoint(rbm.T_inv(m))
    return [rbm.matvec(ad, s) for s in slist]


def space_to_body(js, t):
    """Return J_b = Ad of T^-1 times J_s."""
    return rbm.mul(rbm.adjoint(rbm.T_inv(t)), js)
test_space_and_body_jacobian.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/space-and-body-jacobian/. The authors are listed in prov/DQFEN4.jsonl.
"""Tests of the space and body Jacobians: central finite differences of
the forward kinematics, the 2R check values, the adjoint relation, and the
velocity of the tool point."""

import math
import random

import rbm
from space_and_body_jacobian import (
    body_jacobian,
    body_screws,
    fk_body,
    fk_space,
    space_jacobian,
    space_to_body,
)

H = 1e-6


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


def rand_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):
    """Random screw axes: revolute (omega, -omega x p), and prismatic (0, v) for every third joint."""
    out = []
    for i in range(n):
        if i % 3 == 2:
            out.append([0.0, 0.0, 0.0] + rand_unit(rng))
        else:
            w = rand_unit(rng)
            p = [rng.uniform(-1.0, 1.0) for _ in range(3)]
            out.append(w + rbm.cross(p, w))
    return out


def fd_twists(fk, q):
    """Return the space and body Jacobians by central differences of T(q)."""
    t = fk(q)
    ti = rbm.T_inv(t)
    cols_s, cols_b = [], []
    for i in range(len(q)):
        qp, qm = list(q), list(q)
        qp[i] += H
        qm[i] -= H
        d = rbm.scale(rbm.sub(fk(qp), fk(qm)), 1.0 / (2.0 * H))
        cols_s.append(rbm.vee6(rbm.mul(d, ti)))
        cols_b.append(rbm.vee6(rbm.mul(ti, d)))
    return rbm.transpose(cols_s), rbm.transpose(cols_b)


TWO_R_S = [[0.0, 0.0, 1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0, -1.0, 0.0]]
TWO_R_M = rbm.make_T(rbm.eye(3), [2.0, 0.0, 0.0])


def test_2r_check_values():
    q = [0.0, math.pi / 2.0]
    blist = body_screws(TWO_R_S, TWO_R_M)
    assert maxdiff(blist, [[0.0, 0.0, 1.0, 0.0, 2.0, 0.0], [0.0, 0.0, 1.0, 0.0, 1.0, 0.0]]) < 1e-15
    t = fk_space(TWO_R_S, TWO_R_M, q)
    assert maxdiff(t, rbm.make_T(rbm.rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])) < 1e-15
    js = space_jacobian(TWO_R_S, q)
    want_s = [[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [0.0, 0.0], [0.0, -1.0], [0.0, 0.0]]
    assert maxdiff(js, want_s) < 1e-15
    jb = body_jacobian(blist, q)
    want_b = [[0.0, 0.0], [0.0, 0.0], [1.0, 1.0], [1.0, 0.0], [1.0, 1.0], [0.0, 0.0]]
    assert maxdiff(jb, want_b) < 1e-15
    # velocity of the tool point p = (1, 1, 0): p' = v_s + omega x p
    p = [1.0, 1.0, 0.0]
    lin = []
    for c in range(2):
        w = [js[i][c] for i in range(3)]
        v = [js[i + 3][c] for i in range(3)]
        lin.append(rbm.add(v, rbm.cross(w, p))[:2])
    assert maxdiff(rbm.transpose(lin), [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15


def test_against_finite_differences():
    rng = random.Random(5)
    for n in (2, 4, 6, 7):
        slist = rand_arm(rng, n)
        m = rbm.make_T(rbm.rpy(0.3, -0.2, 0.5), [0.4, 0.1, 0.8])
        blist = body_screws(slist, m)
        q = [rng.uniform(-math.pi, math.pi) for _ in range(n)]
        fs, fb = fd_twists(lambda x: fk_space(slist, m, x), q)
        assert maxdiff(space_jacobian(slist, q), fs) < 1e-6
        assert maxdiff(body_jacobian(blist, q), fb) < 1e-6


def test_adjoint_relation_and_both_forms_of_fk():
    rng = random.Random(6)
    slist = rand_arm(rng, 6)
    m = rbm.make_T(rbm.rot_y(0.7), [0.2, -0.5, 1.0])
    blist = body_screws(slist, m)
    for _ in range(5):
        q = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
        t = fk_space(slist, m, q)
        assert maxdiff(t, fk_body(m, blist, q)) < 1e-12
        js = space_jacobian(slist, q)
        jb = body_jacobian(blist, q)
        assert maxdiff(space_to_body(js, t), jb) < 1e-12
        assert maxdiff(rbm.mul(rbm.adjoint(t), jb), js) < 1e-12


def test_first_column_is_the_first_axis():
    rng = random.Random(7)
    slist = rand_arm(rng, 5)
    blist = body_screws(slist, rbm.make_T(rbm.eye(3), [1.0, 0.0, 0.0]))
    q = [rng.uniform(-1.0, 1.0) for _ in range(5)]
    js = space_jacobian(slist, q)
    jb = body_jacobian(blist, q)
    assert maxdiff([row[0] for row in js], slist[0]) == 0.0
    assert maxdiff([row[4] for row in jb], blist[4]) == 0.0
    # at q = 0 every column is the screw axis itself
    zero = [0.0] * 5
    assert maxdiff(space_jacobian(slist, zero), rbm.transpose(slist)) < 1e-15
    assert maxdiff(body_jacobian(blist, zero), rbm.transpose(blist)) < 1e-15

References

  1. Kevin M. Lynch and Frank C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 5, Section 5.1.1 (the space Jacobian), Section 5.1.2 (the body Jacobian), Section 5.1.3 (visualizing them) and Section 5.1.4 (the relation by the adjoint)
  2. Richard M. Murray, Zexiang Li and S. Shankar Sastry, A Mathematical Introduction to Robotic Manipulation, CRC Press, 1994, Chapter 3 (the spatial and body manipulator Jacobians); the book writes a twist with the linear part first
  3. Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.1 (the geometric Jacobian, for the comparison with the twist form)

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 proofH0 no proof
  • add a proof in proofs/ (06.5)
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)
WritingW4 complete
  • a review of the text: no review record reviews/DQFEN4/text.yaml