Algorithmcore
Newton-Raphson inverse kinematics
Also called numerical inverse kinematics.
Solves the pose equations by Newton steps with the body Jacobian and the matrix logarithm of the pose error, from an initial guess.
- Time
- Θ(k n^3) worst
- Space
- Θ(n^2) extra
- Where
- k = the number of iterations; n = the number of joints and of task coordinates
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Donald L. Pieper, 1968
Newton-Raphson inverse kinematics finds joint values with for a target pose , starting from a guess . At each step it measures the pose error as a twist , the matrix logarithm of . Then it solves a linear system with the body Jacobian for a joint step and adds the step to . Near a solution where is invertible, the error falls quadratically, so a few steps reach full machine precision. The method finds one solution, the one that the guess leads to, and it can fail from a poor guess or at a kinematic singularity.
In plain words
You want the arm to put its hand at a given place and in a given direction. You start from a guess for the joints and look at where the hand is now. The gap between where the hand is and where it should be tells you how to turn the joints, if the arm moved in straight lines. The arm does not move in straight lines, so one correction is not exact, but it brings the hand much closer. You repeat the correction. When the guess is already close, each correction roughly doubles the number of correct digits. When the guess is far, the corrections can jump around, and the hand may end at another of the poses that reach the target, or nowhere.
The problem
Input.
- An arm with joints in the body form of the product of exponentials, . Here is the home pose of the end effector and is the screw axis of joint in the end effector frame, with the angular part first.
- A target pose and an initial guess .
- Tolerances and , and a step limit .
Output. A with and , where , or FAILURE.
The algorithm below is for a full pose with , so that is square. For a position task with as many joints as coordinates, the same loop uses the error and the Jacobian of . For an arm with more joints than task coordinates, the linear solve is replaced by a pseudoinverse, which is the Jacobian pseudoinverse method used as an iteration.
The algorithm
NEWTON-RAPHSON-IK(M, B_1..B_n, T_d, θ0, ε_ω, ε_v, k_max)- 1
θ ← θ0 - 2
for k ← 1 to k_max - 3
V_b ← log(T(θ)^-1 T_d) ▷ the pose error as a body twist (ω_b, v_b) - 4
if |ω_b| ≤ ε_ω and |v_b| ≤ ε_v then return θ - 5
J_b ← BODY-JACOBIAN(θ) - 6
solve J_b Δθ = V_b - 7
if J_b is singular then return FAILURE - 8
θ ← θ + Δθ - 9
return FAILURE
Line L3 uses the exponential map of SE(3) in reverse: is the twist that, followed for unit time from the present pose, gives the target pose. Line L5 builds the body Jacobian column by column, with and . Line L6 is one Gaussian elimination with partial pivoting. In floating point, L7 means that a pivot is zero or close to zero.
Example
A planar arm. Take the 2R arm with link lengths m, with the hand at . The target m has two solutions, and . At the Jacobian is with determinant 1.
Start at rad. The hand is at , so the error is with norm . The Jacobian is , and the step is .
| step | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| error (m) | 0.294 | 0.0517 | 0.00119 | 7.05e-7 | 2.48e-13 |
The iteration ends at . Each error is about a constant times the square of the one before, which is quadratic convergence. From the errors are 0.270, 0.0444, 8.35e-4, 3.44e-7 and 5.92e-14, and the iteration ends at the other solution .
An elbow arm. Take the 6R elbow arm of the Paden-Kahan subproblems page, with in m. Its body screw axes are , , , , and . The target is the pose of rad, with the position m.
- From , the norms are 0.504, 0.0412, 8.27e-4, 7.14e-7 and 6.02e-13, and the iteration ends at .
- From , the norms are 1.6, 0.366, 1.22, 0.402, 0.0235, 2.98e-4, 6.9e-8 and 6.83e-15. The error grows at the third step, and then the quadratic phase starts; the iteration ends at .
- From , the iteration takes 11 evaluations and ends at angles that wrap to . This is the wrist flip of , another of the 8 solutions in the table of the Paden-Kahan page. The raw angles before wrapping are as large as 524 rad, so wrap the output into the joint range.
- From the arm is stretched out and , so the loop returns FAILURE at L7 after one evaluation.
A target out of reach. For the 2R arm and the target m, which is farther than the reach of 2 m, the error never goes below 0.4 m and the loop returns FAILURE at L9.
Correctness
What a returned means. The loop returns only at L4, where is within the tolerances. Since , the pose is reached by a twist of size at most the tolerance from .
Local quadratic convergence. Let be a solution with invertible, and let . Then , and near the derivative of is , where is a smooth matrix function with . So the step of L6 differs from the exact Newton step for by a matrix that is . The proof page shows that there are and with for every within of . So the errors go to zero quadratically when . For the position task, and exactly, and this is the plain Newton method for systems.
What is not claimed. There is no guarantee from a far start: the iteration can cycle, diverge, stop at a singular , or converge to a solution other than the nearest one. If the target is out of reach, there is no solution and the loop cannot succeed. The radius depends on the arm, the target and the bound on , and it shrinks to zero as approaches a singularity.
Proof: Newton-Raphson inverse kinematics converges quadratically near a solution with an invertible body Jacobianfull
We use the notation of the page, in exact arithmetic. The arm has joints, , and is its body Jacobian. Norms of matrices are the operator norms of the vector norms.
Claim 1 (output). If the algorithm returns , then satisfies and , and .
Proof. The only return of a is at L4, after the test on . The logarithm returns a twist with , so .
The derivative of the error
Let , defined and smooth on the set of where the rotation angle of is less than . This set is open and contains every solution , since there .
Lemma 1. On this set, , where is a smooth matrix function on the twists with rotation angle less than , and .
Proof. Write . By the definition of the body Jacobian, , the twist of column in matrix form. Differentiating gives . So , a perturbation of on the left by the twist . The exponential map is a local diffeomorphism at every twist with rotation angle less than , so its inverse is smooth there. The derivative of at along a left perturbation is a linear map , smooth in . At , , so and . The chain rule gives .
Local quadratic convergence
Claim 2. Let be a solution with invertible. There are and such that, for every with , the matrix is invertible and the step of L6 and L8 satisfies .
Proof. Since is continuous and is invertible, there are and such that, for , is in the domain of , is invertible and . On the compact ball of radius , the smooth functions , , , and are bounded, so there are constants , and with the three bounds below for and .
- Taylor's theorem at , applied to , gives with .
- Since and is bounded on , .
- Since is smooth with , , and .
By Lemma 1 and bound 1, . So
By bounds 2 and 3, the first term has norm at most , and the second at most . So the claim holds with and .
Corollary. If , then every iterate stays in the ball, and for .
Proof. Put . Then and Claim 2 gives , so by induction. Each , so and Claim 2 applies again at every step. So . Since is continuous with , , so the test of L4 succeeds after finitely many steps for any positive tolerances, and the algorithm returns a as in Claim 1.
The position task
For with a square Jacobian , , so and the first term in the proof of Claim 2 is zero. The step is the exact Newton step, and the claim and the corollary hold with .
Limits of the result
The result is local. It says nothing about starts outside the ball, where the examples of the page show growth of the error and convergence to another solution. If is singular, does not exist, and the iteration can converge slowly or fail.
Complexity
One iteration computes with matrix exponentials and products, with adjoint maps, one SE(3) logarithm, and one linear solve. The first three cost in the real RAM, and the solve costs for an system, so iterations cost , and for a fixed arm. The extra space is the Jacobian, . The number of iterations is not bounded in general. Near a regular solution, quadratic convergence means that the number of iterations from a close start grows like , which is why the examples above end in 4 or 5 steps once the error is small. The step counts in the examples are measured, not bounds.
Properties
- One solution. The method returns at most one solution, the one in whose basin of attraction the guess lies.
- Local. Convergence is local and quadratic near a regular solution, with no global guarantee.
- No tuning. Apart from the tolerances and the step limit, there is no step size, gain or damping to choose.
- Frame of the error. The error and the Jacobian are both in the end effector frame; the space form with and gives the same steps.
- Singularities. At a singular the step is not defined, and near one the steps are very large.
Variants and improvements
- Redundant arms. With more joints than task coordinates, replace the solve with the pseudoinverse step , the Jacobian pseudoinverse method.
- Damping. Damped least squares solves and stays defined at singularities, at the cost of slower convergence; with chosen per step it is the Levenberg-Marquardt method.
- Steepest descent. The Jacobian transpose method uses , which needs no solve but converges linearly.
- Line search. Scaling the step by so that decreases makes the iteration more robust from a far start.
- Restarts. Running the iteration from many random guesses finds several solutions, but with no guarantee of finding all of them.
- Joint limits. Clamping or projecting after each step keeps the joints in range, but it can stop the convergence.
When to use it
Use Newton-Raphson inverse kinematics when the arm has no closed form solution, a good guess is known, and the solution is regular, for example to refine an analytic solution, or to track a target that moves a little between calls, starting from the last solution. When the arm has a closed form, such as an arm with a spherical wrist, use kinematic decoupling or the Paden-Kahan subproblems, which return all solutions. When the arm may pass near a singularity, use damped least squares.
Pitfalls
- The error. The error must be , or an equivalent twist, not the difference of the matrices, which has 12 entries and does not match the 6 columns of .
- The frames. The body twist goes with the body Jacobian, and the space twist with the space Jacobian; a mixed pair gives wrong steps away from the solution.
- Units. is in rad and in m, so one tolerance on mixes units; keep two.
- Angles that grow. The output angles can be far outside ; wrap them, and then check joint limits.
- Far starts. A step from a far guess can be huge and land in another basin; limit the step size or use a line search.
- The logarithm at . When the rotation error is close to , the logarithm is not smooth; a start with such a large rotation error needs care.
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/newton-raphson-inverse-kinematics/. The authors are listed in prov/85CD1Z.jsonl.
"""Inverse kinematics by Newton-Raphson steps.
- ik_newton(m, blist, t_d, q0, ...) is the algorithm of the page for an arm
with as many joints as the task has dimensions (six for a full pose).
The error is the body twist V_b = log(T(q)^-1 T_d) and the step solves
J_b(q) dq = V_b. This is the Newton-Raphson method of Lynch and Park,
Modern Robotics, Section 6.2, for a square Jacobian.
- newton_position(fk, jac, x_d, q0, ...) is the same loop for a position
task x = fk(q) with as many joints as coordinates.
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.
Both functions return (q, history), where history lists the error norm
before each step, and q is None when the loop fails: the tolerance is not
met within max_iter steps, or the Jacobian is singular to working
precision.
"""
import rbm
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_newton(m, blist, t_d, q0, eps_w=1e-10, eps_v=1e-10, max_iter=50):
"""Return (q, history) with T(q) = t_d within (eps_w, eps_v), or (None, history)."""
q = [float(x) for x in q0] # @line L1
history = []
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
history.append(rbm.norm(vb))
if rbm.norm(vb[:3]) <= eps_w and rbm.norm(vb[3:]) <= eps_v: # @line L4
return q, history
jb = body_jacobian(blist, q) # @line L5
try:
step = rbm.solve(jb, vb) # @line L6
except ValueError:
return None, history # @line L7
q = [x + d for x, d in zip(q, step)] # @line L8
return None, history # @line L9
def newton_position(fk, jac, x_d, q0, eps=1e-12, max_iter=50):
"""Return (q, history) with |x_d - fk(q)| <= eps by steps J(q) dq = x_d - fk(q)."""
q = [float(x) for x in q0]
history = []
for _ in range(max_iter):
e = rbm.sub(x_d, fk(q))
history.append(rbm.norm(e))
if rbm.norm(e) <= eps:
return q, history
try:
step = rbm.solve(jac(q), e)
except ValueError:
return None, history
q = [x + d for x, d in zip(q, step)]
return None, history
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_newton_raphson_inverse_kinematics.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/newton-raphson-inverse-kinematics/. The authors are listed in prov/85CD1Z.jsonl.
"""Tests of Newton-Raphson inverse kinematics: the 2R check values against
the closed form, the body Jacobian against finite differences, quadratic
convergence on random 6R arms, the example of the page, and failure at a
singular start."""
import math
import random
import rbm
from newton_raphson_inverse_kinematics import body_jacobian, fk_body, ik_newton, newton_position
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 closed_form_2r(x, y):
"""All solutions of the unit 2R arm by the law of cosines."""
c2 = (x * x + y * y - 2.0) / 2.0
out = []
for s in (1.0, -1.0):
q2 = s * math.acos(c2)
q1 = math.atan2(y, x) - math.atan2(math.sin(q2), 1.0 + math.cos(q2))
out.append((q1, q2))
return out
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 test_2r_check_values():
j = jac2([0.0, math.pi / 2.0])
assert maxdiff(j, [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15
assert abs(rbm.det(j) - 1.0) < 1e-15
assert maxdiff(fk2([0.0, math.pi / 2.0]), [1.0, 1.0]) < 1e-15
q, hist = newton_position(fk2, jac2, [1.0, 1.0], [0.3, 1.2])
for got, want in zip(hist, [0.294, 0.0517, 0.00119, 7.05e-7]):
assert abs(got - want) < 0.005 * want
assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-12
q, _ = newton_position(fk2, jac2, [1.0, 1.0], [1.3, -1.2])
assert maxdiff(q, [math.pi / 2.0, -math.pi / 2.0]) < 1e-12
def test_2r_against_closed_form():
rng = random.Random(1)
for _ in range(200):
r = rng.uniform(0.3, 1.9)
a = rng.uniform(-math.pi, math.pi)
x, y = r * math.cos(a), r * math.sin(a)
sols = closed_form_2r(x, y)
q0 = [rng.uniform(-math.pi, math.pi), rng.uniform(-math.pi, math.pi)]
q, _ = newton_position(fk2, jac2, [x, y], q0, max_iter=100)
if q is None:
continue
assert maxdiff(fk2(q), [x, y]) < 1e-11
assert min(max(abs(math.remainder(a - b, 2.0 * math.pi)) for a, b in zip(q, s)) for s in sols) < 1e-9
def rand_unit(rng):
while True:
v = [rng.uniform(-1.0, 1.0) for _ in range(3)]
n = rbm.norm(v)
if 0.2 < n <= 1.0:
return [x / n for x in v]
def rand_arm(rng, n=6):
blist = []
for _ in range(n):
w = rand_unit(rng)
p = [rng.uniform(-1.0, 1.0) for _ in range(3)]
blist.append(w + rbm.cross(p, w))
m = rbm.make_T(rbm.so3_exp([rng.uniform(-1.0, 1.0) for _ in range(3)]), [rng.uniform(-1.0, 1.0) for _ in range(3)])
return m, blist
def test_body_jacobian_against_finite_differences():
rng = random.Random(2)
h = 1e-6
for _ in range(5):
m, blist = rand_arm(rng)
q = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
t_inv = rbm.T_inv(fk_body(m, blist, q))
jb = body_jacobian(blist, q)
for i in range(6):
qp, qm = list(q), list(q)
qp[i] += h
qm[i] -= h
dp = rbm.se3_log(rbm.mul(t_inv, fk_body(m, blist, qp)))
dm = rbm.se3_log(rbm.mul(t_inv, fk_body(m, blist, qm)))
col = [(a - b) / (2.0 * h) for a, b in zip(dp, dm)]
assert maxdiff(col, [row[i] for row in jb]) < 1e-6
def test_quadratic_convergence_on_random_arms():
rng = random.Random(3)
done = 0
for _ in range(12):
m, blist = rand_arm(rng)
q_star = [rng.uniform(-math.pi, math.pi) for _ in range(6)]
jb = body_jacobian(blist, q_star)
if abs(rbm.det(jb)) < 0.1:
continue # too close to a singularity for a clean test
t_d = fk_body(m, blist, q_star)
q0 = [x + rng.uniform(-0.05, 0.05) for x in q_star]
q, hist = ik_newton(m, blist, t_d, q0)
assert q is not None and len(hist) <= 8
assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9
assert maxdiff(q, q_star) < 1e-8
for a, b in zip(hist, hist[1:]):
if a < 1e-2 and b > 1e-13:
assert b <= 200.0 * a * a
done += 1
assert done >= 6
def elbow_arm():
"""The elbow arm of the page in body form: M = (I, (0, 2.5, 1)) and the body screw axes."""
m = rbm.make_T(rbm.eye(3), [0.0, 2.5, 1.0])
blist = [
[0.0, 0.0, 1.0, -2.5, 0.0, 0.0],
[-1.0, 0.0, 0.0, 0.0, 0.0, -2.5],
[-1.0, 0.0, 0.0, 0.0, 0.0, -1.5],
[0.0, 0.0, 1.0, -0.5, 0.0, 0.0],
[-1.0, 0.0, 0.0, 0.0, 0.0, -0.5],
[0.0, 1.0, 0.0, 0.0, 0.0, 0.0],
]
return m, blist
def test_example_of_the_page():
m, blist = elbow_arm()
q_star = [0.3, -0.4, 0.9, 0.5, 0.7, -0.6]
t_d = fk_body(m, blist, q_star)
assert maxdiff([t_d[i][3] for i in range(3)], [-0.748090, 1.797966, 0.466418]) < 1e-6
q, hist = ik_newton(m, blist, t_d, [0.5, -0.6, 1.1, 0.3, 0.9, -0.8])
for got, want in zip(hist, [0.504, 0.0412, 0.000827, 7.14e-7]):
assert abs(got - want) < 0.005 * want
assert maxdiff(q, q_star) < 1e-10
# From a far start, the loop wanders and ends at another solution, the wrist flip.
q, hist = ik_newton(m, blist, t_d, [1.0] * 6)
assert q is not None and len(hist) == 11
wrapped = [math.remainder(x, 2.0 * math.pi) for x in q]
assert maxdiff(wrapped, [0.3, -0.4, 0.9, 0.5 - math.pi, math.pi - 0.7, -0.6 + math.pi]) < 1e-9
assert maxdiff(fk_body(m, blist, q), t_d) < 1e-9
def test_singular_start_fails():
m, blist = elbow_arm()
assert abs(rbm.det(body_jacobian(blist, [0.0] * 6))) < 1e-12
t_d = fk_body(m, blist, [0.3, -0.4, 0.9, 0.5, 0.7, -0.6])
q, hist = ik_newton(m, blist, t_d, [0.0] * 6)
assert q is None and len(hist) == 1
def test_out_of_reach_fails():
q, hist = newton_position(fk2, jac2, [2.5, 0.0], [0.2, 0.5], max_iter=50)
assert q is None and min(hist) > 0.4
History
Pieper (1968) studied the kinematics of computer controlled arms in his Stanford thesis. Besides the closed form solution for arms with three intersecting axes, he described numerical methods for general arms, among them Newton-Raphson iteration. Iterative methods with the Jacobian then became the usual tool for arms with no closed form, in the forms of the pseudoinverse, the transpose and damped least squares. Lynch and Park (2017) give the modern form with the product of exponentials, the body Jacobian and the matrix logarithm of the pose error.
References
- 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 with the body Jacobian and the matrix logarithm)
- Donald L. Pieper, The Kinematics of Manipulators under Computer Control, PhD thesis, Stanford University, 1968 (Stanford Artificial Intelligence Memo AIM-72), Chapter IV, Section 4.1 (the Newton-Raphson method)
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 85CD1Z Edit this page History Report an error Markdown