Algorithmcore
Jacobian pseudoinverse method
Also called pseudoinverse inverse kinematics.
Iterates joint steps J^+ e that reduce the pose error e, giving least-norm joint motion for redundant arms.
- Time
- Θ(k m n min(m, n)) worst
- Space
- Θ(m n) extra
- Where
- k = the number of iterations; m = the dimension of the task; n = the number of joints
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel E. Whitney, 1969
The Jacobian pseudoinverse method solves the inverse kinematics of a robot arm by iteration. From a guess , it measures the error between the desired pose and the pose that gives, and it moves the joints by , where is the Moore-Penrose pseudoinverse of the Jacobian, until the error is below a tolerance. Each step is the joint motion of least norm that removes the error to first order, or, if no joint motion can, the one of least norm among those that leave the smallest error. So the same short loop works for square, redundant and underactuated tasks, and near a solution it converges quadratically.
In plain words
You want the hand of a robot at a certain place, and you do not know the joint angles that put it there. Guess some angles and look at where the hand is. The hand is off by some amount. For small joint motions, the hand moves almost in a straight line, by a rule that you can compute at the present angles. So ask: what is the smallest joint motion that would move the hand by exactly the missing amount, if that rule were exact? Make that motion, look again, and repeat. Near the answer, each repeat roughly doubles the number of correct digits. If the arm has spare joints, picking the smallest motion keeps it from wandering.
The problem
Input.
- The forward kinematics of an arm with joints, , in the product of exponentials form with the body screw axes .
- A desired pose .
- An initial guess , tolerances for the rotation and for the translation, and a maximum number of iterations .
Output. Joint values such that the body twist has and , or FAILURE if no such is found within iterations.
For a position task, the error is the plain difference of positions, and is the position Jacobian; the loop is the same. In both cases the task has dimension ( for a full pose), and is ; (redundant), and are all allowed.
The algorithm
PSEUDOINVERSE-IK(M, B_1..B_n, T_d, q0, ε_ω, ε_v, k_max)- 1
q ← q0 - 2
for k ← 1 to k_max - 3
V_b ← log(T(q)^-1 T_d) ▷ pose error as a body twist (ω_b, v_b) - 4
if |ω_b| ≤ ε_ω and |v_b| ≤ ε_v then return q - 5
J_b ← BODY-JACOBIAN(q) ▷ 6 × n, in the end effector frame - 6
q ← q + J_b^+ V_b ▷ least norm, least squares step - 7
return FAILURE
Line L3 uses the matrix logarithm of SE(3), the inverse of the exponential map; is the twist that, followed for unit time, takes the present end effector frame to the desired one. Line L5 is the body Jacobian, whose columns are the body screw axes moved to the present configuration; it is in the same frame and the same order (angular part first) as . Line L6 needs , which is the least squares solution of least norm of . The code on this page computes it from a singular value decomposition and treats singular values at or below as zero; that tolerance is a rule of thumb.
Example
A 2R arm, position task. Planar arm with unit links, target m, start .
- Line L3 (position form): , so and m.
- Line L5: , square and invertible, so .
- Line L6: , and .
The next iterates are and then , which approach the solution . The error norms are
and each one is about a constant times the square of the one before: quadratic convergence. From the start the same loop goes to the other solution, , with the error norms , , , and . The guess decides which solution the method finds.
A redundant 3R arm. Planar arm with three unit links, target m, start , where and m. Here is , and the first step is the least norm solution . The error norms are , , , , and , and the loop ends at , with . The target has a one-parameter family of solutions; the method picks one of them, and which one depends on .
A pose task with more equations than joints. Write the same 2R arm as a spatial chain with and the body screw axes and , and ask for the pose with rotation and position , from . Now is , with only the rows , and nonzero, and gives the least squares step. The error norms are , , and , and the loop returns .
A target out of reach. For the target m, which is beyond the reach of 2 m, from , the error norms jump between about 0.5 and 2.2 and do not settle, and the loop returns FAILURE after 50 iterations. Near the stretched pose, which is the best the arm can do, is close to singular, and the steps are huge.
Correctness
The step. By Penrose (1955), is the unique vector that minimizes and, among all minimizers, has the least norm. If has full row rank, the minimum is 0 and is the least norm solution of ; if is square and invertible, is the Newton step; if has full column rank, is the Gauss-Newton step.
Convergence, full row rank. Write for the error (the position error or the body twist error) and suppose that on a ball around , , the second derivative of is bounded by , and, for the twist error, with . Then each step gives with . If and the ball has radius at least , the iterates stay in the ball, converge to a solution , and . For the position error, .
Convergence, full column rank. If a solution exists and has full column rank near it, then for a constant , so the method converges quadratically from every start close enough to .
The proof below gives the details. The method is local: from a poor start, or when no solution exists, it can wander, cycle or stop at a singular configuration.
Proof: PSEUDOINVERSE-IK takes least norm least squares steps and converges quadratically near a solutionfull
We use the notation of the page. All vector norms are Euclidean, and the norm of a matrix is its largest singular value. The proof is in exact arithmetic, in the real RAM.
The loop of the page has the form
where is the error and is the matching Jacobian. For the position task, and , so . For the pose task, is the body twist error and . Line L4 returns as soon as is below the tolerance, and line L7 returns FAILURE after iterations, so the loop always stops; the content of the proof is what one step does and when the iterates converge.
The step
Lemma 1 (Penrose). For every matrix and every , the vector minimizes , and among all minimizers it is the unique one of least norm.
Proof. Let be a singular value decomposition with the nonzero singular values , and , where is the matrix with the entries for and zeros elsewhere. Put and . Since and are orthogonal, and . The first sum is zero exactly when for , and the second does not depend on , so the minimizers are the with these entries and any other entries. The one of least norm has for , that is , and .
Corollary 2. If has rank , then , , and is the least norm solution of . If has rank , then and . In both cases , the inverse of the smallest singular value of .
Proof. With rank , and is the transpose of with the entries inverted, so , and the formulas follow by expanding . The case of rank is the same with . The singular values of are the .
For a square invertible the step is , the Newton step for .
The error map of the pose task
Lemma 3. Let , and suppose that on a set the rotation angle of stays below , so that is a smooth function. Then , where and is the left Jacobian of SE(3). is smooth, where , and on a compact part of there is a constant with .
Proof. By the definition of the body Jacobian, , the matrix of column of . So : a change of multiplies on the left by to first order. The derivative of at in the direction of a left perturbation is ; this is the definition of the left Jacobian, which is a smooth, invertible matrix function of for rotation angles below , with . With this gives . The map is smooth with the value at , so it is Lipschitz on a compact set, which gives .
For the position task, and . So both tasks fit the same frame: with .
Full row rank
Make these assumptions on a closed ball .
- (B1) has rank and for .
- (B2) whenever and are in .
- (B3) on with .
Let and .
Theorem 4. If and , then all iterates lie in , , and converges to a point with .
Proof. Write , and .
One step. If and are in , then by (B2), (B3) and (Corollary 2),
With (Corollary 2 and (B1)), .
Induction. We show by induction on that and for . For this is the definition of , and . Suppose it holds for . For , , because and give when ; when , the one-step bound gives for , and the same inequality holds with . Since ,
so . Then the one-step bound applies, and .
Limit. The same sum shows that converges, so is a Cauchy sequence with a limit , since is closed. is continuous and , so .
So the error falls quadratically, , and the total joint motion is at most . The limit is a solution in , but it need not be the solution nearest to .
Full column rank
Theorem 5. Suppose , and on the closed ball : has rank with and ; ; (B2) holds; and (B3) holds. Let . If and , then for every , and .
Proof. Let and . By (B2) on the segment from to , with , so . By Corollary 2, , so
By the mean value inequality, , so . Hence . If , then , so and . By induction the bound holds for every , and .
For a square both theorems apply, and Theorem 5 is the classical local quadratic convergence of Newton's method.
What the theorems do not give
Both results are local. They need a start where the error is small compared with , and they say nothing about starts far from every solution, about targets out of reach, or about singular solutions where . In those cases the iteration can move far, cycle, or approach a singular configuration where the steps blow up, and the loop of the page ends with FAILURE after iterations.
Complexity
Each iteration evaluates and in operations for a task of fixed size, the logarithm in , and the step . With a QR decomposition of (full row rank) or of (full column rank), or a singular value decomposition with a bounded number of sweeps, the step costs . So iterations cost in the real RAM, with extra space. The one-sided Jacobi decomposition of the code on this page also keeps an matrix of rotations, so it uses more space and operations per sweep. Because of the quadratic convergence, a start within the basin of a solution needs only a handful of iterations to reach full precision, as the examples show.
Properties
- Local and fast. Near a nonsingular solution, the number of correct digits roughly doubles at each iteration.
- Least norm steps. For a redundant arm, each step is the smallest joint motion that does the job to first order, which keeps the joints from drifting along the self-motion. The final solution is not the solution nearest to , only the end of a path of least norm steps.
- One answer. The method returns one solution, the one whose basin contains ; to find others, restart from other guesses.
- Frame consistent. With the body twist error and the body Jacobian, both in the end effector frame, the result does not depend on the choice of the base frame.
- Not robust at singularities. As , the steps grow like ; a target out of reach drives the arm to a singular pose.
Variants and improvements
- Damped least squares. Replace by , the Levenberg-Marquardt step of damped least squares inverse kinematics; it trades speed for robustness near singularities and out of reach. See also Levenberg-Marquardt.
- The transpose. Use , a gradient step on , in the Jacobian transpose method; it needs no inverse but converges only linearly.
- A secondary goal. Add to each step to pull a redundant arm toward a preferred posture; see null space projection and task priority inverse kinematics.
- Step control. Scale the step or search along it to keep decreasing, which enlarges the basin of convergence; limit the step of each joint to keep it inside its range.
- The space form. The space twist error with the space Jacobian gives the same step when has full row rank, because then ; for other ranks the two steps can differ.
- Square arms. For and a nonsingular , the method is the Newton-Raphson inverse kinematics iteration.
- Rate control. Used once per control step with a small gain in place of the full step, the same formula is resolved-rate motion control.
When to use it
Use the pseudoinverse method when an arm has no closed form inverse kinematics, or has more joints than the task, and a reasonable initial guess is at hand: the present configuration, the last solution along a path, or a guess from a coarse table. If the target may be out of reach or close to a singularity, prefer damped least squares; if all solutions are needed, use an analytic method for the arm or many restarts.
Pitfalls
- Units. For a pose task, the error mixes radians and meters, and minimizes a joint norm that mixes radians and, for prismatic joints, meters. Scale the rows and columns on purpose.
- Frames. and must be in the same frame and the same order; a space twist error with a body Jacobian, or the linear part first in one and last in the other, breaks the convergence without an error.
- The rank tolerance. If the pseudoinverse keeps tiny singular values, the step can be huge near a singularity; if it drops singular values that are only small, the step loses a direction. The cut, here , is a rule of thumb.
- Joint wrapping. Revolute joint values can grow by multiples of ; wrap them into the range of the joints after the loop.
- Joint limits. The plain method does not see them, and it can return a solution outside the range of a joint.
- No convergence. A target out of reach, or a start far from every solution, leads to steps that jump around; bound the number of iterations and report FAILURE.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-pseudoinverse-method/. The authors are listed in prov/MNF4KJ.jsonl.
"""Inverse kinematics by repeated pseudoinverse steps.
- pinv(a, rtol) is the Moore-Penrose pseudoinverse of any matrix, from a
one-sided Jacobi singular value decomposition. Singular values at most
rtol times the largest one count as zero.
- ik_pose(m, blist, t_d, q0, ...) is the algorithm of the page: the error
is the body twist V_b = log(T(q)^-1 T_d), and the step is J_b^+ V_b.
This is the numerical inverse kinematics algorithm of Lynch and Park,
Modern Robotics, Section 6.2.2.
- ik_position(fk, jac, x_d, q0, ...) is the same loop for a position task
x = fk(q) in R^m, with the error x_d - fk(q).
The arm is in the product of exponentials form: T(q) = M exp([B1] q1) ...
exp([Bn] qn) with body screw axes B_i = (omega, v), angular part first.
Matrices are lists of rows. ik_pose and ik_position return None when they
do not reach the tolerance within max_iter steps.
"""
import math
import rbm
def _columns(a):
return [list(c) for c in zip(*a)]
def svd(a, sweeps=60):
"""Return (u_cols, sigma, v_cols) with a = sum_j sigma_j u_j v_j^T.
One-sided Jacobi (Hestenes): rotate pairs of columns of a until all
columns are orthogonal. The rotations are collected in v. u_j is the
column j divided by its norm sigma_j; for sigma_j = 0, u_j is zero.
"""
m, n = len(a), len(a[0])
w = _columns(a) # n columns of length m
v = [[1.0 if i == j else 0.0 for i in range(n)] for j in range(n)] # columns of V
for _ in range(sweeps):
rotated = False
for p in range(n - 1):
for r in range(p + 1, n):
alpha = rbm.dot(w[p], w[p])
beta = rbm.dot(w[r], w[r])
gamma = rbm.dot(w[p], w[r])
if gamma == 0.0 or abs(gamma) <= 1e-15 * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
c = 1.0 / math.sqrt(1.0 + t * t)
s = c * t
for vec in (w, v):
x, y = vec[p], vec[r]
vec[p] = [c * xi - s * yi for xi, yi in zip(x, y)]
vec[r] = [s * xi + c * yi for xi, yi in zip(x, y)]
if not rotated:
break
sigma = [rbm.norm(col) for col in w]
u = [[x / s for x in col] if s > 0.0 else [0.0] * m for col, s in zip(w, sigma)]
return u, sigma, v
def pinv(a, rtol=1e-10):
"""Return the n by m pseudoinverse of the m by n matrix a.
a^+ = sum over sigma_j > rtol * max(sigma) of v_j u_j^T / sigma_j.
"""
m, n = len(a), len(a[0])
u, sigma, v = svd(a)
smax = max(sigma) if sigma else 0.0
out = rbm.zeros(n, m)
for uj, sj, vj in zip(u, sigma, v):
if sj > rtol * smax and sj > 0.0:
for i in range(n):
f = vj[i] / sj
if f != 0.0:
row = out[i]
for k in range(m):
row[k] += f * uj[k]
return out
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_jacobian(blist, q):
"""Return the 6 by n body Jacobian; column i is Ad of exp(-[B_n] q_n)...exp(-[B_i+1] q_i+1) applied to B_i."""
n = len(blist)
t = rbm.eye(4)
cols = [None] * n
for i in range(n - 1, -1, -1):
cols[i] = rbm.matvec(rbm.adjoint(t), blist[i])
t = rbm.mul(t, rbm.se3_exp([-y * q[i] for y in blist[i]]))
return rbm.transpose(cols)
def ik_pose(m, blist, t_d, q0, eps_w=1e-10, eps_v=1e-10, max_iter=100, rtol=1e-10):
"""Return joint values q with T(q) = t_d within (eps_w, eps_v), or None."""
q = [float(x) for x in q0] # @line L1
for _ in range(max_iter): # @line L2
vb = rbm.se3_log(rbm.mul(rbm.T_inv(fk_body(m, blist, q)), t_d)) # @line L3
if rbm.norm(vb[:3]) <= eps_w and rbm.norm(vb[3:]) <= eps_v: # @line L4
return q
jb = body_jacobian(blist, q) # @line L5
step = rbm.matvec(pinv(jb, rtol), vb)
q = [x + d for x, d in zip(q, step)] # @line L6
return None # @line L7
def ik_position(fk, jac, x_d, q0, eps=1e-11, max_iter=100, rtol=1e-10):
"""Return q with |x_d - fk(q)| <= eps, or None, by steps q <- q + J^+ e."""
q = [float(x) for x in q0]
for _ in range(max_iter):
e = rbm.sub(x_d, fk(q))
if rbm.norm(e) <= eps:
return q
step = rbm.matvec(pinv(jac(q), rtol), e)
q = [x + d for x, d in zip(q, step)]
return None
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_jacobian_pseudoinverse_method.py 240 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jacobian-pseudoinverse-method/. The authors are listed in prov/MNF4KJ.jsonl.
"""Tests of pseudoinverse inverse kinematics: the Penrose conditions, the
minimum-norm step against a KKT solve, the 2R check values, a 7R position
task, a 6R full pose task, and failure on a target out of reach."""
import math
import random
import rbm
from jacobian_pseudoinverse_method import body_jacobian, fk_body, ik_pose, ik_position, pinv, svd
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 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_screws(rng, n):
"""Revolute screw axes S = (omega, -omega x p) in the space frame."""
out = []
for _ in range(n):
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 fk_space(slist, m, q):
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 space_jacobian(slist, q):
t = rbm.eye(4)
cols = []
for s, x in zip(slist, q):
cols.append(rbm.matvec(rbm.adjoint(t), s))
t = rbm.mul(t, rbm.se3_exp([y * x for y in s]))
return rbm.transpose(cols)
def position_jacobian(slist, m, q):
"""Rows of p' = v_s + omega x p, the velocity of the tool point."""
js = space_jacobian(slist, q)
t = fk_space(slist, m, q)
p = [t[0][3], t[1][3], t[2][3]]
out = rbm.zeros(3, len(q))
for c in range(len(q)):
w = [js[i][c] for i in range(3)]
v = [js[i + 3][c] for i in range(3)]
col = rbm.add(v, rbm.cross(w, p))
for i in range(3):
out[i][c] = col[i]
return out
def fk2(q):
return [math.cos(q[0]) + math.cos(q[0] + q[1]), math.sin(q[0]) + math.sin(q[0] + q[1])]
def jac2(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 [[-s1 - s12, -s12], [c1 + c12, c12]]
def penrose(a, x, tol):
ax = rbm.mul(a, x)
xa = rbm.mul(x, a)
assert maxdiff(rbm.mul(ax, a), a) < tol
assert maxdiff(rbm.mul(xa, x), x) < tol
assert maxdiff(ax, rbm.transpose(ax)) < tol
assert maxdiff(xa, rbm.transpose(xa)) < tol
def test_svd_reconstructs():
rng = random.Random(1)
for m, n in [(2, 3), (3, 7), (6, 6), (6, 7), (4, 2)]:
a = rand_matrix(rng, m, n)
u, s, v = svd(a)
back = rbm.zeros(m, n)
for uj, sj, vj in zip(u, s, v):
for i in range(m):
for k in range(n):
back[i][k] += sj * uj[i] * vj[k]
assert maxdiff(back, a) < 1e-12
def test_pinv_penrose_conditions():
rng = random.Random(2)
for m, n in [(2, 3), (3, 7), (6, 7), (5, 3)]:
a = rand_matrix(rng, m, n)
penrose(a, pinv(a), 1e-11)
# rank 2 matrix of size 3 by 5: the product of 3x2 and 2x5 factors
a = rbm.mul(rand_matrix(rng, 3, 2), rand_matrix(rng, 2, 5))
x = pinv(a)
penrose(a, x, 1e-10)
# the zero matrix has the zero pseudoinverse
assert maxdiff(pinv(rbm.zeros(2, 3)), rbm.zeros(3, 2)) == 0.0
def test_pinv_against_closed_forms():
rng = random.Random(3)
a = rand_matrix(rng, 3, 6)
assert maxdiff(pinv(a), rbm.pinv_right(a)) < 1e-11
b = rand_matrix(rng, 4, 4)
assert maxdiff(pinv(b), rbm.inv(b)) < 1e-9
# tall matrix with full column rank: (A^T A)^-1 A^T
c = rand_matrix(rng, 5, 2)
ct = rbm.transpose(c)
assert maxdiff(pinv(c), rbm.mul(rbm.inv(rbm.mul(ct, c)), ct)) < 1e-11
def test_step_is_minimum_norm():
rng = random.Random(4)
for _ in range(5):
j = rand_matrix(rng, 3, 7)
e = [rng.uniform(-1.0, 1.0) for _ in range(3)]
step = rbm.matvec(pinv(j), e)
# KKT system of min |d|^2 / 2 subject to J d = e
kkt = rbm.zeros(10, 10)
for i in range(7):
kkt[i][i] = 1.0
for r in range(3):
for c in range(7):
kkt[7 + r][c] = j[r][c]
kkt[c][7 + r] = j[r][c]
sol = rbm.solve(kkt, [0.0] * 7 + e)
assert maxdiff(step, sol[:7]) < 1e-11
# any other solution step + n with J n = 0 is longer
nul = rbm.sub(rbm.eye(7), rbm.mul(pinv(j), j))
z = [rng.uniform(-1.0, 1.0) for _ in range(7)]
other = rbm.add(step, rbm.matvec(nul, z))
assert maxdiff(rbm.matvec(j, other), e) < 1e-11
assert rbm.norm(other) >= rbm.norm(step)
def test_2r_check_values():
q = [0.0, math.pi / 2.0]
assert maxdiff(fk2(q), [1.0, 1.0]) < 1e-15
assert maxdiff(jac2(q), [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15
assert maxdiff(rbm.num_jacobian(fk2, [0.4, 1.1]), jac2([0.4, 1.1])) < 1e-6
def test_2r_reaches_both_solutions():
up = ik_position(fk2, jac2, [1.0, 1.0], [0.3, 1.2])
assert up is not None
assert maxdiff(up, [0.0, math.pi / 2.0]) < 1e-9
down = ik_position(fk2, jac2, [1.0, 1.0], [1.3, -1.2])
assert down is not None
assert maxdiff(down, [math.pi / 2.0, -math.pi / 2.0]) < 1e-9
for q in (up, down):
assert maxdiff(fk2(q), [1.0, 1.0]) < 1e-9
def test_2r_out_of_reach_fails():
assert ik_position(fk2, jac2, [2.5, 0.0], [0.2, 0.5], max_iter=50) is None
def test_7r_position_round_trip():
rng = random.Random(7)
slist = rand_screws(rng, 7)
m = rbm.make_T(rbm.eye(3), [1.0, 0.5, 0.2])
def fk(q):
t = fk_space(slist, m, q)
return [t[0][3], t[1][3], t[2][3]]
def jac(q):
return position_jacobian(slist, m, q)
q = [rng.uniform(-1.0, 1.0) for _ in range(7)]
assert maxdiff(rbm.num_jacobian(fk, q), jac(q)) < 1e-6
for _ in range(4):
q_true = [rng.uniform(-math.pi, math.pi) for _ in range(7)]
x_d = fk(q_true)
q0 = [x + rng.uniform(-0.3, 0.3) for x in q_true]
q = ik_position(fk, jac, x_d, q0)
assert q is not None
assert maxdiff(fk(q), x_d) < 1e-9
def test_body_jacobian_against_finite_differences():
rng = random.Random(8)
slist = rand_screws(rng, 6)
m = rbm.make_T(rbm.rot_z(0.3), [0.5, 0.2, 0.7])
blist = [rbm.matvec(rbm.adjoint(rbm.T_inv(m)), s) for s in slist]
q = [rng.uniform(-1.0, 1.0) for _ in range(6)]
t = fk_body(m, blist, q)
assert maxdiff(t, fk_space(slist, m, q)) < 1e-12
h = 1e-6
ti = rbm.T_inv(t)
jb = body_jacobian(blist, q)
for i in range(6):
qp, qm = list(q), list(q)
qp[i] += h
qm[i] -= h
d = rbm.scale(rbm.sub(fk_body(m, blist, qp), fk_body(m, blist, qm)), 1.0 / (2.0 * h))
col = rbm.vee6(rbm.mul(ti, d))
assert maxdiff(col, [row[i] for row in jb]) < 1e-6
def test_6r_full_pose_round_trip():
rng = random.Random(9)
slist = rand_screws(rng, 6)
m = rbm.make_T(rbm.rot_x(0.4), [0.6, -0.2, 0.9])
blist = [rbm.matvec(rbm.adjoint(rbm.T_inv(m)), s) for s in slist]
for _ in range(4):
q_true = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
t_d = fk_body(m, blist, q_true)
q0 = [x + rng.uniform(-0.2, 0.2) for x in q_true]
q = ik_pose(m, blist, t_d, q0)
assert q is not None
assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9
def test_planar_pose_check_values():
# The 2R arm as a spatial chain: body screws of the page, M = (I, (2, 0, 0)).
m = rbm.make_T(rbm.eye(3), [2.0, 0.0, 0.0])
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]]
t_d = rbm.make_T(rbm.rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
q = ik_pose(m, blist, t_d, [0.2, 1.3])
assert q is not None
assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-9
History
Penrose (1955) defined the generalized inverse by four equations and showed that it gives the least squares solution of least norm, which is the step of this method. Whitney (1969) resolved end effector rates into joint rates through the inverse of the Jacobian, and the same linear step, repeated until the pose error vanishes, solves the position problem. Klein and Huang (1983) reviewed pseudoinverse control of redundant arms, and later work added damping near singularities. Lynch and Park (2017) present the loop of this page, with the body twist error from the matrix logarithm, as their numerical inverse kinematics algorithm.
References
- Roger Penrose, A generalized inverse for matrices, Mathematical Proceedings of the Cambridge Philosophical Society 51(3), 406-413, 1955, the whole paper (the four equations that define the generalized inverse, and the least squares solution of least norm)
- Kevin M. Lynch and Frank C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 6, Section 6.2 (numerical inverse kinematics, the Newton-Raphson method in 6.2.1 and the numerical inverse kinematics algorithm with the body twist error and the pseudoinverse in 6.2.2)
- Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.5 (the pseudoinverse solution of the differential kinematics) and Section 3.7 (inverse kinematics algorithms)
- Daniel E. Whitney, Resolved motion rate control of manipulators and human prostheses, IEEE Transactions on Man-Machine Systems, 1969, the whole paper (joint rates from the inverse of the Jacobian)
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag MNF4KJ Edit this page History Report an error Markdown