Algorithm Search⌘K

Techniquecore

Null-space projection

Also called self-motion projection.

Adds (I - J^+ J) z to a joint velocity, which pursues a secondary goal z without disturbing the main task.

Null-space projection is the standard way to use the spare joints of a redundant arm. Given a joint velocity J+x˙J^{+}\dot x that does the main task, it adds the term (I−J+J) z(I - J^{+}J)\,z, where zz is any joint velocity that serves a second goal and I−J+JI - J^{+}J is the orthogonal projector onto the null space of the Jacobian JJ. The added motion changes only the posture of the arm, not the task, so the second goal is pursued as far as the task allows. With zz the negative gradient of a cost, this is the gradient projection method of Liégeois (1977).

In plain words

A person can hold a cup still in front of the face and still move the elbow up and down. The hand does the task, and the elbow has freedom left over. This technique uses that freedom on purpose. First it finds the joint motion that does the task. Then it takes a wish for some other motion, for example "keep the joints near the middle of their range", and removes from the wish every part that would move the hand. What is left only changes the shape of the arm. Adding it to the first motion gives a motion that still does the task and also goes toward the wish as far as it can.

When it applies

  • The arm is redundant for the task: JJ is m×nm \times n with m<nm < n.
  • JJ has full row rank mm along the path, so J+=JT(JJT)−1J^{+} = J^{\mathsf T}(JJ^{\mathsf T})^{-1} exists and is bounded.
  • The control is at the velocity level, as in resolved-rate motion control, or at the step level of pseudoinverse inverse kinematics.
  • The second goal can be written as a joint velocity zz, often z=−k0∇h(q)z = -k_0 \nabla h(q) for a cost hh to make small, or z=+k0∇w(q)z = +k_0 \nabla w(q) for a measure ww to make large.
  • The second goal has lower priority: when it conflicts with the task, the task wins.

The template

Let JJ be an m×nm \times n matrix of rank mm, let J+=JT(JJT)−1J^{+} = J^{\mathsf T}(JJ^{\mathsf T})^{-1} be its pseudoinverse, and let

P=I−J+J.P = I - J^{+}J.

Facts about PP.

  • JP=J−JJT(JJT)−1J=0JP = J - JJ^{\mathsf T}(JJ^{\mathsf T})^{-1}J = 0, so every PzPz lies in null⁡(J)\operatorname{null}(J).
  • PT=PP^{\mathsf T} = P and P2=PP^2 = P, so PP is the orthogonal projector onto null⁡(J)\operatorname{null}(J), of rank n−mn - m.
  • PJ+=0PJ^{+} = 0: the least norm solution J+x˙J^{+}\dot x lies in range⁡(JT)\operatorname{range}(J^{\mathsf T}), orthogonal to the null space.

The step. For a task velocity x˙\dot x and a wish zz,

q˙=J+x˙+Pz.\dot q = J^{+}\dot x + Pz.

Then Jq˙=x˙J\dot q = \dot x for every zz. Of all joint velocities with Jq˙=x˙J\dot q = \dot x, this one is the closest to zz. The solutions form the affine set J+x˙+null⁡(J)J^{+}\dot x + \operatorname{null}(J), and the closest point to zz is J+x˙+P(z−J+x˙)=J+x˙+PzJ^{+}\dot x + P(z - J^{+}\dot x) = J^{+}\dot x + Pz, since PJ+=0PJ^{+} = 0. Equivalently, q˙\dot q solves the problem: minimize ∣q˙−z∣2|\dot q - z|^2 subject to Jq˙=x˙J\dot q = \dot x, whose Lagrange condition gives the same answer.

  1. NULL-SPACE-STEP(J, x', z) ▷ J: m × n of rank m; x': task velocity; z: wish
  2. 1J^+ ← J^T (J J^T)^-1
  3. 2P ← I - J^+ J ▷ projector onto null(J)
  4. 3return J^+ x' + P z

Gradient projection. With z=−k0∇h(q)z = -k_0\nabla h(q) and k0>0k_0 > 0, the cost changes at the rate

h˙=∇hTq˙=∇hTJ+x˙−k0∣P∇h∣2.\dot h = \nabla h^{\mathsf T}\dot q = \nabla h^{\mathsf T} J^{+}\dot x - k_0 |P\nabla h|^2.

When the task is to hold still, x˙=0\dot x = 0, the cost never increases, and it stops changing exactly when P∇h=0P\nabla h = 0, that is, when ∇h∈range⁡(JT)\nabla h \in \operatorname{range}(J^{\mathsf T}). That is the Lagrange condition for a minimum of hh on the self-motion set {q:f(q)=x}\{q : f(q) = x\}, so the posture slides toward a constrained local minimum of hh. When the task moves, the first term can raise hh, and the second term only works against it. A discrete controller also adds feedback on the task error, x˙=x˙d+Ke\dot x = \dot x_d + K e, to correct the drift of the Euler steps.

Cost. Line L1 costs Θ(m2n+m3)\Theta(m^2 n + m^3), and line L2 costs Θ(mn2)\Theta(m n^2), which dominates since m≤nm \le n; the total is Θ(mn2)\Theta(m n^2) time and Θ(n2)\Theta(n^2) extra space for PP in the real RAM. If PP itself is not needed, Pz=z−J+(Jz)Pz = z - J^{+}(Jz) costs only Θ(m2n)\Theta(m^2 n).

Classic examples

A hand example. Take the planar 3R arm with unit links at q=(0,π/2,−π/2)q = (0, \pi/2, -\pi/2), with the tip at (2,1)(2, 1) m. Then

J=(−1−10211),null⁡(J)=span⁡{ν}, ν=(1,−1,−1),P=ννT3=13(1−1−1−111−111).J = \begin{pmatrix} -1 & -1 & 0 \\ 2 & 1 & 1 \end{pmatrix}, \qquad \operatorname{null}(J) = \operatorname{span}\{\nu\},\ \nu = (1, -1, -1), \qquad P = \frac{\nu\nu^{\mathsf T}}{3} = \frac{1}{3}\begin{pmatrix} 1 & -1 & -1 \\ -1 & 1 & 1 \\ -1 & 1 & 1 \end{pmatrix}.

To hold the tip still while joint 3 is asked to turn at z=(0,0,3)z = (0, 0, 3) rad/s, the step gives q˙=Pz=−ν=(−1,1,1)\dot q = Pz = -\nu = (-1, 1, 1) rad/s. Joint 3 turns at 1 rad/s, not 3, and the other two joints move too, because the tip must not move: J(−1,1,1)T=(0,0)J(-1, 1, 1)^{\mathsf T} = (0, 0). To move the tip at x˙=(0.3,0)\dot x = (0.3, 0) m/s with no wish, the least norm solution is J+x˙=(0,−0.3,0.3)J^{+}\dot x = (0, -0.3, 0.3) rad/s.

Keeping the joints near zero. Take the same arm with the cost h(q)=∣q∣2/2h(q) = |q|^2/2, so ∇h=q\nabla h = q, and start at q0=(0.2,1.2,−0.9)q_0 = (0.2, 1.2, -0.9), where h=1.145h = 1.145 and the tip is at xd=(2.0276,1.6635)x_d = (2.0276, 1.6635). Integrate q˙=J+(10 (xd−f(q)))+P(−q)\dot q = J^{+}(10\,(x_d - f(q))) + P(-q) with Euler steps of 0.01 s.

time qq hh
0 s (0.2,1.2,−0.9)(0.2, 1.2, -0.9) 1.145
1 s (−0.0096,1.2211,−0.3829)(-0.0096, 1.2211, -0.3829) 0.8189
5 s (0.037,0.6941,0.5519)(0.037, 0.6941, 0.5519) 0.3939
15 s (0.0568,0.6401,0.6084)(0.0568, 0.6401, 0.6084) 0.3916

The tip stays within 9.9⋅10−59.9 \cdot 10^{-5} m of xdx_d the whole time, hh decreases at every step, and at 15 s the projected gradient ∣P∇h∣|P\nabla h| is 4.8⋅10−54.8 \cdot 10^{-5}. The length of the projected gradient does not fall at every step: it grows from 0.44 to 0.62 before it goes down, because PP changes with qq. The arm ends near a posture where ∣q∣|q| is locally smallest among all postures that keep the tip at xdx_d; the task alone does not fix this posture.

Joint limits. Liégeois (1977) used the gradient of a cost on the joint values to keep each joint away from its limits. A common form of such a cost, as in Siciliano et al., is h(q)=∑i((qi−qˉi)/(qi,max⁡−qi,min⁡))2h(q) = \sum_i \big((q_i - \bar q_i)/(q_{i,\max} - q_{i,\min})\big)^2, where qˉi\bar q_i is the middle of the range of joint ii.

Singularities. With z=k0∇wz = k_0 \nabla w, where ww is the Yoshikawa measure, the self-motion moves the arm toward postures of large manipulability; Yoshikawa (1985) suggested this use, and Siciliano et al. list it with joint limits and obstacle distance as standard objectives.

Variations

  • Weighted norm. With a positive definite weight WW, JW+=W−1JT(JW−1JT)−1J^{+}_W = W^{-1}J^{\mathsf T}(JW^{-1}J^{\mathsf T})^{-1} and PW=I−JW+JP_W = I - J^{+}_W J. Then PWP_W is a projector onto null⁡(J)\operatorname{null}(J) that is orthogonal in the inner product of WW, not in the plain one.
  • Several tasks. Task priority inverse kinematics (Nakamura, Hanafusa and Yoshikawa, 1987) replaces zz by the best solution of a second task inside null⁡(J1)\operatorname{null}(J_1): q˙=J1+x˙1+(J2P1)+(x˙2−J2J1+x˙1)\dot q = J_1^{+}\dot x_1 + (J_2 P_1)^{+}(\dot x_2 - J_2 J_1^{+}\dot x_1). Nested projectors give a full hierarchy, and hierarchical quadratic programming adds inequality constraints.
  • Torque level. In the operational space formulation, the projector acts on torques, τ=JTF+(I−JTJˉT)τ0\tau = J^{\mathsf T}F + (I - J^{\mathsf T}\bar J^{\mathsf T})\tau_0, with a pseudoinverse Jˉ\bar J weighted by the inertia matrix, so that τ0\tau_0 does not cause a task acceleration.
  • Without forming PP. Pz=z−J+(Jz)Pz = z - J^{+}(Jz), or Pz=z−QQTzPz = z - Q Q^{\mathsf T}z with an orthonormal basis QQ of range⁡(JT)\operatorname{range}(J^{\mathsf T}) from a QR decomposition of JTJ^{\mathsf T}.
  • Position level. In pseudoinverse inverse kinematics, adding P zP\,z to each Newton step pulls the solution toward a preferred posture.

Pitfalls

  • Near a singularity of JJ. (JJT)−1(JJ^{\mathsf T})^{-1} blows up, J+x˙J^{+}\dot x asks for huge rates, and at the singular point the null space jumps to a larger dimension. A pseudoinverse that drops singular values below a tolerance, or damped least squares, keeps the rates bounded; the tolerance or damping is a rule of thumb, and with damping JP≠0JP \ne 0, so the second goal leaks into the task.
  • Drift. PzPz is in null⁡(J)\operatorname{null}(J) only to first order, so Euler steps move the tip a little. In the example above, without the feedback term the tip drifts by up to 1.7⋅10−31.7 \cdot 10^{-3} m over the 15 s; with a gain of 10 the error stays below 10−410^{-4} m.
  • Only part of the wish. PzPz is the part of zz that the task allows; when zz is nearly in range⁡(JT)\operatorname{range}(J^{\mathsf T}), almost nothing is left. The goal is reached only if the self-motion can reach it.
  • Local minima. Gradient projection stops at any constrained stationary point of hh, which can be a local minimum or a saddle.
  • The gain k0k_0. A large k0k_0 speeds the second goal but raises joint rates and can make Euler steps unstable; its value is set by trial for each arm.
  • A cost on the wrong variables. hh must be a function of qq; a cost on the task variables has a gradient in range⁡(JT)\operatorname{range}(J^{\mathsf T}), and its projection is zero.

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.

null_space_projection.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/null-space-projection/. The authors are listed in prov/SA0J6T.jsonl.
"""Null-space projection of a secondary joint velocity.

J is an m by n task Jacobian of full row rank (m < n for a redundant arm).

- projector(j) returns P = I - J^+ J with J^+ = J^T (J J^T)^-1.
- null_space_step(j, xdot, z) returns q' = J^+ x' + P z, the joint
  velocity closest to z among all joint velocities with J q' = x'.
- gradient_projection_run(...) integrates q' = J^+ (K e) + P (-k0 grad h)
  with explicit Euler steps: the task point is held (or pulled back) by the
  first term, and the secondary cost h(q) decreases through the second
  term (the gradient projection of Liegeois, 1977).

Matrices are lists of rows.
"""

import rbm


def projector(j):
    """Return the n by n matrix I - J^+ J."""
    jp = rbm.pinv_right(j)
    return rbm.sub(rbm.eye(len(j[0])), rbm.mul(jp, j))


def null_space_step(j, xdot, z):
    """Return J^+ x' + (I - J^+ J) z."""
    jp = rbm.pinv_right(j)  # @line L1
    p = rbm.sub(rbm.eye(len(j[0])), rbm.mul(jp, j))  # @line L2
    return rbm.add(rbm.matvec(jp, xdot), rbm.matvec(p, z))  # @line L3


def gradient_projection_run(fk, jac, grad_h, q0, x_d, gain, k0, dt, steps):
    """Return the joint path of q' = J^+ (gain (x_d - fk(q))) + P (-k0 grad h(q))."""
    q = [float(x) for x in q0]
    path = [q]
    for _ in range(steps):
        j = jac(q)
        e = rbm.sub(x_d, fk(q))
        z = [-k0 * g for g in grad_h(q)]
        qdot = null_space_step(j, [gain * x for x in e], z)
        q = [x + dt * d for x, d in zip(q, qdot)]
        path.append(q)
    return path
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_null_space_projection.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/null-space-projection/. The authors are listed in prov/SA0J6T.jsonl.
"""Tests of null-space projection: the projector identities, the closest
joint velocity against a KKT solve, the planar 3R example of the page, and
a gradient projection run that lowers a joint cost while the tip stays."""

import math
import random

import rbm
from null_space_projection import gradient_projection_run, null_space_step, projector


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


def fk3(q):
    a = x = y = 0.0
    for t in q:
        a += t
        x += math.cos(a)
        y += math.sin(a)
    return [x, y]


def jac3(q):
    n = len(q)
    out = [[0.0] * n, [0.0] * n]
    for j in range(n):
        a = sum(q[: j + 1])
        for i in range(j + 1):
            out[0][i] -= math.sin(a)
            out[1][i] += math.cos(a)
    return out


def test_projector_identities():
    rng = random.Random(41)
    for m, n in [(2, 3), (3, 7), (6, 7), (1, 4)]:
        j = rand_matrix(rng, m, n)
        p = projector(j)
        assert maxdiff(rbm.mul(j, p), rbm.zeros(m, n)) < 1e-12
        assert maxdiff(rbm.mul(p, p), p) < 1e-12
        assert maxdiff(p, rbm.transpose(p)) < 1e-12
        assert abs(sum(p[i][i] for i in range(n)) - (n - m)) < 1e-12


def test_step_is_closest_to_z():
    rng = random.Random(42)
    for m, n in [(2, 3), (3, 7), (6, 7)]:
        j = rand_matrix(rng, m, n)
        xdot = [rng.uniform(-1.0, 1.0) for _ in range(m)]
        z = [rng.uniform(-1.0, 1.0) for _ in range(n)]
        qd = null_space_step(j, xdot, z)
        assert maxdiff(rbm.matvec(j, qd), xdot) < 1e-12
        # KKT system of min |q' - z|^2 / 2 subject to J q' = x'
        kkt = rbm.zeros(n + m, n + m)
        for i in range(n):
            kkt[i][i] = 1.0
        for r in range(m):
            for c in range(n):
                kkt[n + r][c] = j[r][c]
                kkt[c][n + r] = j[r][c]
        sol = rbm.solve(kkt, z + xdot)
        assert maxdiff(qd, sol[:n]) < 1e-12


def test_planar_3r_example():
    q = [0.0, math.pi / 2.0, -math.pi / 2.0]
    assert maxdiff(fk3(q), [2.0, 1.0]) < 1e-15
    j = jac3(q)
    assert maxdiff(j, [[-1.0, -1.0, 0.0], [2.0, 1.0, 1.0]]) < 1e-15
    assert maxdiff(rbm.num_jacobian(fk3, [0.3, 0.8, -0.4]), jac3([0.3, 0.8, -0.4])) < 1e-6
    p = projector(j)
    n = [1.0, -1.0, -1.0]
    nn = rbm.dot(n, n)
    assert maxdiff(p, [[a * b / nn for b in n] for a in n]) < 1e-15
    qd = null_space_step(j, [0.0, 0.0], [0.0, 0.0, 3.0])
    assert maxdiff(qd, [-1.0, 1.0, 1.0]) < 1e-14


def test_gradient_projection_lowers_the_cost_and_keeps_the_tip():
    q0 = [0.2, 1.2, -0.9]
    x_d = fk3(q0)

    def grad_h(q):
        return list(q)  # h(q) = |q|^2 / 2, distance from the middle of the joint range

    path = gradient_projection_run(fk3, jac3, grad_h, q0, x_d, 10.0, 1.0, 0.01, 1500)
    hs = [rbm.dot(q, q) / 2.0 for q in path]
    tips = [rbm.norm(rbm.sub(fk3(q), x_d)) for q in path]
    assert max(tips) < 1e-3
    assert hs[-1] < 0.8 * hs[0]
    assert all(b <= a + 1e-12 for a, b in zip(hs, hs[1:]))
    # at the end the gradient of h has no component left in the null space
    qe = path[-1]
    assert rbm.norm(rbm.matvec(projector(jac3(qe)), grad_h(qe))) < 1e-3

Exercises

  1. Show that P=I−J+JP = I - J^{+}J is symmetric and idempotent, that JP=0JP = 0, and that rank⁡P=n−m\operatorname{rank}P = n - m.
  2. Show that q˙=J+x˙+Pz\dot q = J^{+}\dot x + Pz minimizes ∣q˙−z∣|\dot q - z| subject to Jq˙=x˙J\dot q = \dot x, first with the projection argument and then with a Lagrange multiplier.
  3. For the 3R arm at q=(0,π/2,−π/2)q = (0, \pi/2, -\pi/2), compute PzPz for z=(1,0,0)z = (1, 0, 0) and check that J Pz=0J\,Pz = 0.
  4. Show that with x˙=0\dot x = 0 and z=−k0∇hz = -k_0\nabla h, hh is nonincreasing, and that P∇h=0P\nabla h = 0 is the Lagrange condition for a minimum of hh on the self-motion set.
  5. Show that PW=I−JW+JP_W = I - J^{+}_W J satisfies PW2=PWP_W^2 = P_W and WPW=PWTWW P_W = P_W^{\mathsf T}W, and give an example where PWP_W is not symmetric.

References

  1. Alain Liégeois, Automatic supervisory control of the configuration and behavior of multibody mechanisms, IEEE Transactions on Systems, Man, and Cybernetics 7(12), 868-871, 1977, the whole paper (the general solution with the projector I - J^+ J and the gradient of a secondary cost, used for joint limits)
  2. Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.5 (inverse differential kinematics for redundant manipulators, the null space projector and the objective functions for joint limits, manipulability and obstacles)
  3. Yoshihiko Nakamura, Hideo Hanafusa and Tsuneo Yoshikawa, Task-priority based redundancy control of robot manipulators, The International Journal of Robotics Research 6(2), 3-15, 1987, the whole paper (a second task solved in the null space of the first)
  4. Yoshihiko Nakamura, Advanced Robotics: Redundancy and Optimization, Addison-Wesley, 1991, the chapter on differential kinematics and redundancy (the projector onto the null space and the general solution)

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)
WritingW2 basic
  • three classic examples