Algorithm Search⌘K

Definitioncore

Yoshikawa manipulability measure

Also called manipulability index.

The number sqrt(det(J J^T)), proportional to the volume of the manipulability ellipsoid and zero at singularities.

The Yoshikawa manipulability measure of a robot arm at a configuration qq is the number w(q)=det⁡(J(q)J(q)T)w(q) = \sqrt{\det(J(q) J(q)^{\mathsf T})}, where JJ is the m×nm \times n Jacobian of the task and m≤nm \le n. It is the product of the singular values of JJ, so it is proportional to the volume of the manipulability ellipsoid, and it is zero exactly at the kinematic singularities. Tsuneo Yoshikawa proposed it in 1985 as one number that says how freely the end effector can move in all directions at once. A large ww is good; how small a ww counts as "near singular" is a rule of thumb that depends on the arm and its units.

Definition

Let JJ be an m×nm \times n real matrix with m≤nm \le n, the Jacobian of a task of dimension mm for an arm with nn joints.

Definition. The manipulability measure is

w=det⁡(JJT).w = \sqrt{\det(J J^{\mathsf T})}.

The matrix JJTJJ^{\mathsf T} is symmetric and positive semidefinite, so its determinant is not negative, and the root is real. For m>nm > n the matrix JJTJJ^{\mathsf T} has rank at most n<mn < m, its determinant is always zero, and the measure is not defined.

Equivalent forms. With the singular value decomposition J=UΣVTJ = U\Sigma V^{\mathsf T} and the singular values σ1≥⋯≥σm≥0\sigma_1 \ge \dots \ge \sigma_m \ge 0,

w=σ1σ2⋯σm,w = \sigma_1 \sigma_2 \cdots \sigma_m,

because det⁡(JJT)=det⁡(UΣΣTUT)=∏iσi2\det(JJ^{\mathsf T}) = \det(U \Sigma\Sigma^{\mathsf T} U^{\mathsf T}) = \prod_i \sigma_i^2. For a square JJ, w=∣det⁡J∣w = |\det J|. The velocity ellipsoid {Jq˙:∣q˙∣≤1}\{J\dot q : |\dot q| \le 1\} has the semi-axes σi\sigma_i, so its volume is cmwc_m w, where cmc_m is the volume of the unit ball of Rm\mathbb{R}^m (c2=πc_2 = \pi, c3=4π/3c_3 = 4\pi/3). By the Cauchy-Binet formula, det⁡(JJT)\det(JJ^{\mathsf T}) is also the sum of the squares of all the m×mm \times m minors of JJ.

Properties.

  • w(q)=0w(q) = 0 if and only if rank⁡J(q)<m\operatorname{rank} J(q) < m, that is, at a singularity of an arm with generic rank mm.
  • w(RJ)=w(J)w(RJ) = w(J) for an orthogonal m×mm \times m matrix RR, and w(JQ)=w(J)w(JQ) = w(J) for an orthogonal n×nn \times n matrix QQ: a rotation of the task frame or an orthogonal change of joint coordinates does not change ww.
  • More generally, w(AJ)=∣det⁡A∣ w(J)w(AJ) = |\det A|\,w(J) for any invertible m×mm \times m matrix AA. The adjoint map Ad⁡T\operatorname{Ad}_T and the factor between the geometric Jacobian and the space and body Jacobians have determinant ±1\pm 1, so all three give the same ww.
  • w(cJ)=∣c∣mw(J)w(cJ) = |c|^m w(J). If the linear rows of a 6×n6 \times n Jacobian change from meters to millimeters, ww grows by 10910^9 at every configuration. This keeps the order of configurations of one arm, but a single value of ww has no meaning without its units, and values of arms of different size cannot be compared.

Gradient. For the null space projection that pushes a redundant arm toward large ww, the partial derivatives are

∂w∂qi=w tr⁡ ⁣(J+∂J∂qi),J+=JT(JJT)−1,\frac{\partial w}{\partial q_i} = w\, \operatorname{tr}\!\left(J^{+} \frac{\partial J}{\partial q_i}\right), \qquad J^{+} = J^{\mathsf T}(JJ^{\mathsf T})^{-1},

from dlog⁡det⁡A=tr⁡(A−1dA)d \log\det A = \operatorname{tr}(A^{-1} dA) with A=JJTA = JJ^{\mathsf T} and dA=dJ JT+J dJTdA = dJ\,J^{\mathsf T} + J\,dJ^{\mathsf T}.

Computation. The code on this page follows the definition.

  1. MANIPULABILITY(J) ▷ J: m × n, with m ≤ n
  2. 1A ← J J^T ▷ m × m, symmetric
  3. 2d ← det A ▷ Gaussian elimination
  4. 3return sqrt(max(d, 0)) ▷ rounding can make d slightly negative

Line L1 costs Θ(m2n)\Theta(m^2 n) operations and line L2 costs Θ(m3)\Theta(m^3), so the total is Θ(m2n)\Theta(m^2 n) in the real RAM, with Θ(m2)\Theta(m^2) extra space. Forming JJTJJ^{\mathsf T} squares the singular values, so when σm2\sigma_m^2 is close to the rounding unit times σ12\sigma_1^2, most of dd is rounding error. For example, in double precision, a rotated 2×22 \times 2 matrix with the singular values 1 and 10−910^{-9} can give w≈3.6⋅10−9w \approx 3.6 \cdot 10^{-9} in place of 10−910^{-9}. A QR decomposition JT=QRJ^{\mathsf T} = QR avoids the square: then w=∣r11r22⋯rmm∣w = |r_{11} r_{22} \cdots r_{mm}|.

Examples and non-examples

The planar 2R arm. For the position task of a 2R arm with link lengths L1L_1 and L2L_2, JJ is square and w=∣det⁡J∣=L1L2∣sin⁡q2∣w = |\det J| = L_1 L_2 |\sin q_2|. At the check configuration q=(0,π/2)q = (0, \pi/2) with L1=L2=1L_1 = L_2 = 1 m, J=(−1−110)J = \begin{pmatrix} -1 & -1 \\ 1 & 0 \end{pmatrix}, w=1w = 1 m², and the singular values are 1.6181.618 and 0.6180.618, whose product is 1. This is the largest ww over all configurations, since ∣sin⁡q2∣≤1|\sin q_2| \le 1. For a fixed total length L1+L2L_1 + L_2, the product L1L2L_1 L_2 is largest when L1=L2L_1 = L_2, so the equal link arm has the largest best value of ww.

Close to a singularity. At q=(0,0.01)q = (0, 0.01) the same arm has w=sin⁡0.01≈0.0100w = \sin 0.01 \approx 0.0100, the singular values 2.2362.236 and 0.004470.00447, and the condition number 500500. At q2=0q_2 = 0 or q2=πq_2 = \pi, w=0w = 0.

A redundant arm. For the planar 3R arm with unit links and the position task, m=2m = 2 and n=3n = 3. At q=(0,π/2,−π/2)q = (0, \pi/2, -\pi/2),

J=(−1−10211),JJT=(2−3−36),w=3≈1.732.J = \begin{pmatrix} -1 & -1 & 0 \\ 2 & 1 & 1 \end{pmatrix}, \qquad JJ^{\mathsf T} = \begin{pmatrix} 2 & -3 \\ -3 & 6 \end{pmatrix}, \qquad w = \sqrt 3 \approx 1.732.

The three 2×22 \times 2 minors of JJ are 11, −1-1 and −1-1, and the sum of their squares is 33, as the Cauchy-Binet formula says.

Non-example: a distance to the singularities. A 2R arm with L1=L2=0.1L_1 = L_2 = 0.1 m at q2=π/2q_2 = \pi/2 has w=0.01w = 0.01, the same as the 1 m arm at q2=0.01q_2 = 0.01, but its condition number is 2.6182.618, the same as at the best posture of the 1 m arm. A small ww can come from a small arm, not from a nearby singularity; the condition number σ1/σm\sigma_1/\sigma_m does not depend on the scale.

Non-example: the analytic Jacobian. For the analytic Jacobian JAJ_A, J=diag⁡(I,T(ϕ))JAJ = \operatorname{diag}(I, T(\phi))J_A, so w(J)=∣det⁡T(ϕ)∣ w(JA)w(J) = |\det T(\phi)|\,w(J_A). The measure of JAJ_A depends on the choice of angles and is not a property of the arm.

Non-example: a product of joint ranges. The measure is a local, first order quantity at one configuration; it says nothing about how far the joints can move before a joint limit.

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
yoshikawa_manipulability_measure.py 69 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yoshikawa-manipulability-measure/. The authors are listed in prov/WRDGRM.jsonl.
"""Yoshikawa's manipulability measure w = sqrt(det(J J^T)) and related numbers.

J is an m by n Jacobian with m <= n. w is the product of the m singular
values of J, and it is zero exactly when J has rank below m.

- manipulability(j) computes w from the determinant of J J^T.
- singular_values(j) computes the singular values as the square roots of
  the eigenvalues of J J^T, by the cyclic Jacobi eigenvalue method.
- condition_number(j) is sigma_max / sigma_min (infinite at a singularity).

Matrices are lists of rows.
"""

import math

import rbm


def manipulability(j):
    """Return sqrt(det(J J^T)); raise ValueError if J has more rows than columns."""
    if len(j) > len(j[0]):
        raise ValueError("w is defined for m <= n only")
    a = rbm.mul(j, rbm.transpose(j))  # @line L1
    d = rbm.det(a)  # @line L2
    return math.sqrt(max(d, 0.0))  # @line L3


def sym_eigenvalues(a, sweeps=50):
    """Return the eigenvalues of the symmetric matrix a by cyclic Jacobi rotations."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    for _ in range(sweeps):
        off = sum(m[i][k] ** 2 for i in range(n) for k in range(n) if i != k)
        if off <= 1e-30 * max(1.0, sum(m[i][i] ** 2 for i in range(n))):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if m[p][q] == 0.0:
                    continue
                theta = (m[q][q] - m[p][p]) / (2.0 * m[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                s = t * c
                for k in range(n):
                    mkp, mkq = m[k][p], m[k][q]
                    m[k][p] = c * mkp - s * mkq
                    m[k][q] = s * mkp + c * mkq
                for k in range(n):
                    mpk, mqk = m[p][k], m[q][k]
                    m[p][k] = c * mpk - s * mqk
                    m[q][k] = s * mpk + c * mqk
    return sorted((m[i][i] for i in range(n)), reverse=True)


def singular_values(j):
    """Return the min(m, n) singular values of J, largest first."""
    if len(j) <= len(j[0]):
        a = rbm.mul(j, rbm.transpose(j))
    else:
        a = rbm.mul(rbm.transpose(j), j)
    return [math.sqrt(max(x, 0.0)) for x in sym_eigenvalues(a)]


def condition_number(j):
    """Return sigma_max / sigma_min, or infinity if sigma_min is zero."""
    s = singular_values(j)
    return math.inf if s[-1] == 0.0 else s[0] / s[-1]
test_yoshikawa_manipulability_measure.py 103 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/yoshikawa-manipulability-measure/. The authors are listed in prov/WRDGRM.jsonl.
"""Tests of the manipulability measure: the 2R closed form, the product of
singular values, |det J| for square J, invariance under rotations, scaling,
zero at singularities, and the best posture of the 2R arm."""

import math
import random

import pytest

import rbm
from yoshikawa_manipulability_measure import condition_number, manipulability, singular_values


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


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


def rand_rotation(rng):
    w = [rng.uniform(-1.0, 1.0) for _ in range(3)]
    return rbm.so3_exp(w)


def rand_orthogonal(rng, n):
    """Product of random Givens rotations, an n by n orthogonal matrix."""
    q = rbm.eye(n)
    for _ in range(3 * n):
        i, k = rng.sample(range(n), 2)
        a = rng.uniform(-math.pi, math.pi)
        g = rbm.eye(n)
        g[i][i] = g[k][k] = math.cos(a)
        g[i][k] = -math.sin(a)
        g[k][i] = math.sin(a)
        q = rbm.mul(q, g)
    return q


def test_2r_check_values():
    j = jac_2r(1.0, 1.0, [0.0, math.pi / 2.0])
    assert max(abs(x - y) for r, s in zip(j, [[-1.0, -1.0], [1.0, 0.0]]) for x, y in zip(r, s)) < 1e-15
    assert abs(manipulability(j) - 1.0) < 1e-14
    s = singular_values(j)
    assert abs(s[0] - (1.0 + math.sqrt(5.0)) / 2.0) < 1e-12
    assert abs(s[1] - (math.sqrt(5.0) - 1.0) / 2.0) < 1e-12
    assert abs(condition_number(j) - (3.0 + math.sqrt(5.0)) / 2.0) < 1e-12
    rng = random.Random(31)
    for _ in range(20):
        l1, l2 = rng.uniform(0.2, 2.0), rng.uniform(0.2, 2.0)
        q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
        assert abs(manipulability(jac_2r(l1, l2, q)) - l1 * l2 * abs(math.sin(q[1]))) < 1e-12


def test_product_of_singular_values():
    rng = random.Random(32)
    for m, n in [(2, 3), (3, 7), (6, 6), (6, 7), (1, 4)]:
        j = rand_matrix(rng, m, n)
        assert abs(manipulability(j) - math.prod(singular_values(j))) < 1e-12


def test_square_is_abs_det():
    rng = random.Random(33)
    for n in (2, 3, 6):
        j = rand_matrix(rng, n, n)
        assert abs(manipulability(j) - abs(rbm.det(j))) < 1e-12


def test_invariance_and_scaling():
    rng = random.Random(34)
    j = rand_matrix(rng, 3, 6)
    w = manipulability(j)
    r = rand_rotation(rng)
    assert abs(manipulability(rbm.mul(r, j)) - w) < 1e-12
    q = rand_orthogonal(rng, 6)
    assert abs(manipulability(rbm.mul(j, q)) - w) < 1e-12
    assert abs(manipulability(rbm.scale(j, 2.0)) - 8.0 * w) < 1e-11


def test_zero_at_singularities():
    rng = random.Random(35)
    # rank 2 Jacobian of size 3 by 5
    j = rbm.mul(rand_matrix(rng, 3, 2), rand_matrix(rng, 2, 5))
    assert manipulability(j) < 1e-7
    assert manipulability(jac_2r(1.0, 1.0, [0.7, 0.0])) < 1e-7
    assert condition_number([[1.0, 0.0], [0.0, 0.0]]) == math.inf
    with pytest.raises(ValueError):
        manipulability(rand_matrix(rng, 3, 2))


def test_best_posture_of_2r():
    grid = [k * math.pi / 180.0 for k in range(-180, 181)]
    best = max(grid, key=lambda q2: manipulability(jac_2r(1.0, 1.0, [0.3, q2])))
    assert abs(abs(best) - math.pi / 2.0) < 1e-12
    # with L1 + L2 = 2 fixed, w at q2 = pi / 2 is L1 L2, largest at L1 = L2 = 1
    lengths = [k / 100.0 for k in range(1, 200)]
    best_l1 = max(lengths, key=lambda l1: manipulability(jac_2r(l1, 2.0 - l1, [0.0, math.pi / 2.0])))
    assert abs(best_l1 - 1.0) < 1e-12

References

  1. Tsuneo Yoshikawa, Manipulability of robotic mechanisms, The International Journal of Robotics Research 4(2), 3-9, 1985, the whole paper (the definition of the measure w, its relation to the ellipsoid volume and to the singular values, and the best postures of simple arms)
  2. Kevin M. Lynch and Frank C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 5, Section 5.4 (manipulability, the volume measure among three scalar measures)
  3. Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.5 (the manipulability measure as an objective for redundancy) and Section 3.9 (manipulability ellipsoids)

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/WRDGRM/text.yaml