Algorithmcore
Damped least squares inverse kinematics
Also called DLS inverse kinematics, Wampler's method.
Uses the step J^T (J J^T + l^2 I)^-1 e, which stays bounded near singularities at the cost of some tracking error.
- Time
- Θ(k m^2 n) worst
- Space
- Θ(m n) extra
- Where
- k = the number of iterations; m = the number of task coordinates; n = the number of joints with m at most n
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Charles W. Wampler, Yoshihiko Nakamura, Hideo Hanafusa, 1986
Damped least squares inverse kinematics moves the joints of an arm toward a target with the step , where is the Jacobian and is the task error. The damping factor makes the matrix invertible at every configuration, also at a kinematic singularity. The step is never longer than , so the joints do not jump near a singularity, as they do with the pseudoinverse. The price is that one step does not remove the whole error, even where the pseudoinverse step would. The step is the Tikhonov regularization of the linear least squares problem .
In plain words
To move the hand of an arm toward a target, you need to know how much to turn each joint. At some poses of the arm, a tiny motion of the hand needs a huge turn of the joints, for example when the arm is almost straight and the target is a little farther out. A method that insists on the exact motion then asks for wild joint motions. Damped least squares asks for a compromise instead. It looks for a joint motion that brings the hand close to where it should go, but it also pays a penalty for every large joint motion. Far from such poses, the penalty hardly matters, and the result is almost the exact motion. Near them, the penalty wins, and the joints move only a little. Repeating such steps brings the hand to the target, if it can be reached.
The problem
Input.
- A task map from joint values to task coordinates, with , and its Jacobian , an matrix. For a full pose, is a twist error and is the matching geometric Jacobian, as in Newton-Raphson inverse kinematics.
- A target , an initial guess , a damping factor , a tolerance and a step limit .
Output. A with , or the last iterate with the report that the tolerance was not met. For a target out of reach, the last iterate is the useful answer, often an arm stretched toward the target.
One step. For a fixed and , the damped least squares step is the unique minimizer of
The algorithm
DLS-IK(f, J, x_d, θ0, λ, ε, k_max)- 1
θ ← θ0 - 2
for k ← 1 to k_max - 3
e ← x_d - f(θ) - 4
if |e| ≤ ε then return θ - 5
J ← JACOBIAN(θ) - 6
solve (J J^T + λ^2 I) y = e ▷ an m by m system, positive definite - 7
Δθ ← J^T y - 8
θ ← θ + Δθ - 9
return θ with the report that the tolerance was not met
Lines L6 and L7 can also be written , an system with the same result. Use the smaller of the two systems. With the singular value decomposition , the step is
The pseudoinverse uses the factor , which grows without bound as . The damped factor is close to when , goes to 0 when , and is at most , with equality at .
Example
All examples use the planar 2R arm with m, with the hand at .
One step near a singularity. At rad the arm is almost straight, the hand is at m and . For the target m the error is m, with m.
| step | (rad) | (rad) | residual (m) |
|---|---|---|---|
| exact solve | 22.09 | 0 | |
| DLS, | 3.683 | 0.0823 | |
| DLS, | 0.0958 | 0.0986 | |
| DLS, | 0.0812 | 0.0992 |
The exact step turns the elbow by almost 20 rad, which is useless, since the linear model is only valid for small steps. The damped steps are small and point the right way.
Iteration to a reachable target. For the target m from rad, both damping factors end at the solution .
| errors (m) at steps 0 to 4 | steps to | |
|---|---|---|
| 0.1 | 0.294, 0.0415, 0.00138, 3.45e-5, 8.8e-7 | 7 |
| 0.5 | 0.294, 0.123, 0.051, 0.0206, 0.00823 | 24 |
The convergence is linear. At the solution, has the eigenvalues , so the least singular value is . The proof page shows that the error ratio tends to , which is 0.0255 for and 0.396 for , and these are the ratios that the iteration shows.
A target out of reach. For the target m, which is beyond the reach of 2 m, start at rad. With , the errors are 1.132, 0.5404, 0.5021, 0.5001, and the arm stops stretched along the x axis, with the hand at , the nearest point to the target. With , the iteration does not settle: the error jumps between about 0.51 and 1.48 m for as long as it runs, and every step still obeys the bound . With it falls into a cycle of two bent poses, mirror images of each other, with the error 0.601 m. These are measured results on this one arm, not general rules.
Correctness
The proof page proves these facts for .
- The matrices and are positive definite, so L6 always has one solution, and the two forms of the step are equal.
- The step is the unique minimizer of .
- The step has the singular value form above, so for every .
- As , the step tends to the pseudoinverse step , for every .
- The residual after one linear step is , which is not zero unless . This is the tracking error that the damping costs.
- If has full row rank, the step is zero only when , so the iteration can stop only at a solution.
- If and is invertible at a solution , the iteration converges to from every start close enough, and the error falls by a factor that tends to at most per step.
There is no global guarantee. From a far start, or for a target out of reach, the iteration can cycle, as in the example.
Proof: The damped least squares step is the bounded minimizer of the damped objective, and the iteration converges linearly near a regular solutionfull
We use the notation of the page, in exact arithmetic, with . is an real matrix, , and norms are Euclidean norms or the matching operator norms.
Claim 1. and are symmetric positive definite, and
Proof. For every , , and the same holds for the other matrix. The identity holds by expanding both sides. Multiply it on the left by and on the right by .
So line L6 always has exactly one solution, and the two forms of the step on the page are equal.
Claim 2. The step is the unique minimizer of .
Proof. is a quadratic function with a positive definite Hessian , so it is strictly convex. Its gradient is zero exactly at .
Claim 3. Let be a singular value decomposition with , orthonormal and orthonormal . Then and .
Proof. Complete the to an orthonormal basis of . In this basis is diagonal, with on and on the other basis vectors. Since , applying the inverse gives the formula. By the inequality of the arithmetic and geometric means, , so each factor is at most , with equality at . Then .
The bound does not depend on , so it holds at singular configurations too. It is reached when has a singular value equal to and is along the matching .
Claim 4. As , , for every .
Proof. There are finitely many terms, and each factor tends to since .
Claim 5. . In particular the residual is zero only when .
Proof. With , .
Claim 6. If has full row rank, then only if .
Proof. , and is injective when has full row rank, so gives and .
So a fixed point of the iteration at a configuration with full row rank is a solution. At a singular configuration, a fixed point with can exist, such as the stretched arm with a target out of reach on the page, where is orthogonal to the range of .
Local convergence
Claim 7. Let , let be twice continuously differentiable, and let be a solution, , with invertible and least singular value . Let . For every there is such that every start with gives iterates with , so the iteration converges to .
Proof. The iteration is with . is continuously differentiable, since the inverse exists everywhere by Claim 1, and . At the term with vanishes, so only the derivative of , which is , contributes:
with , using Claim 1. This matrix is symmetric with the eigenvalues , all in , and the largest is . So . By continuity of , there is with on the ball of radius around . On this convex ball, the mean value inequality gives , so each iterate stays in the ball and the distance falls by at least the factor .
For the 2R arm of the page at , has the eigenvalues , so for and for . For a generic start the error along the eigenvector of dominates, and the measured ratios of the errors approach , as the tests check.
For the solutions form a manifold, and has the eigenvalue 1 along its tangent space, so the claim does not apply as stated, and we do not prove a result for that case here. The result is local, and nothing is claimed for far starts or for targets out of reach.
Complexity
One step forms in , solves the system in , and forms in , in the real RAM. With , this is per step, plus the cost of and , which is for a serial chain. So steps cost . The extra space is the Jacobian and the matrix, . The number of steps is not bounded in general; near a regular solution, it grows like with the rate above.
Properties
- Always defined. The step exists at every configuration and for every error, also at singularities and for targets out of reach.
- Bounded steps. .
- Slower than Newton. Near a regular solution the convergence is linear, not quadratic, and slower for larger .
- A trade-off in one number. Small gives accurate but possibly large steps; large gives small steps and slow progress.
- Redundant arms. For , the step has no component in the null space of , as for the pseudoinverse.
Variants and improvements
- Variable damping. Nakamura and Hanafusa let the damping grow as the arm approaches a singularity and vanish far from it, using a measure of the distance to the singularity such as the manipulability.
- Damping only where needed. Using the singular value form, one can damp only the small singular values, or add damping only along the directions of the least singular vectors.
- Selectively damped least squares. Buss and Kim (2005) choose a separate damping for each singular direction from the size of the joint motion it would cause.
- Levenberg-Marquardt. Choosing at each step from the decrease of the error gives the Levenberg-Marquardt method, which behaves like Newton near a regular solution and like gradient descent far from it.
- With a secondary task. For a redundant arm, a null space term can be added to the step. If the projector is built from the damped inverse instead of , the term is no longer exactly in the null space.
When to use it
Use damped least squares when the arm may pass near a singularity, or when the target may be out of reach, and a smooth, bounded joint motion matters more than exact tracking at each step. This is the usual case for real time control of an arm and for character animation. Use Newton-Raphson inverse kinematics when the solution is regular and a fast final convergence matters. Use the Jacobian transpose method when even the small linear solve is too costly.
Pitfalls
- Choosing . The damping factor is a tuning parameter, and no value is best for all arms and tasks. Nakamura and Hanafusa make it depend on the distance to a singularity, and Buss says that it must be chosen for the arm and the targets at hand.
- Units. The penalty and the error mix rad and m, so the value of changes with the units of the task.
- Oscillation. A small with a target out of reach can make the arm jump back and forth, as in the example; a larger or a limit on the step length helps.
- Tracking error. In real time control, each step leaves the residual , so the hand lags behind a moving target.
- The wrong form. The form is wasteful for a redundant arm with ; use the form.
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/damped-least-squares-inverse-kinematics/. The authors are listed in prov/J6EXM0.jsonl.
"""Inverse kinematics by damped least squares steps.
- dls_step(j, e, lam) returns dq = J^T (J J^T + lam^2 I)^-1 e, the step of
the page. It solves an m by m system, where m is the number of task
coordinates.
- dls_step_normal(j, e, lam) returns the same step in the form
(J^T J + lam^2 I)^-1 J^T e, which solves an n by n system.
- ik_dls(fk, jac, x_d, q0, lam, ...) is the iteration of the page. It
returns (q, history, ok): the last joint vector, the error norms before
each step, and whether the tolerance was met. When the target is out of
reach, q is the last iterate, which is the useful answer of the method.
- planar_fk and planar_jacobian give a planar arm with n revolute joints,
used by the tests and the example of the page.
Matrices are lists of rows, as in the shared helper rbm.
"""
import math
import rbm
def dls_step(j, e, lam):
"""Return J^T (J J^T + lam^2 I)^-1 e."""
m = len(j)
jt = rbm.transpose(j)
a = rbm.add(rbm.mul(j, jt), rbm.scale(rbm.eye(m), lam * lam)) # @line L6
y = rbm.solve(a, e) # @line L6
return rbm.matvec(jt, y) # @line L7
def dls_step_normal(j, e, lam):
"""Return (J^T J + lam^2 I)^-1 J^T e, the same step as dls_step."""
jt = rbm.transpose(j)
n = len(jt)
a = rbm.add(rbm.mul(jt, j), rbm.scale(rbm.eye(n), lam * lam))
return rbm.solve(a, rbm.matvec(jt, e))
def ik_dls(fk, jac, x_d, q0, lam, eps=1e-10, max_iter=500):
"""Return (q, history, ok) for the task fk(q) = x_d by damped least squares steps."""
q = [float(x) for x in q0] # @line L1
history = []
for _ in range(max_iter): # @line L2
e = rbm.sub(x_d, fk(q)) # @line L3
history.append(rbm.norm(e))
if history[-1] <= eps: # @line L4
return q, history, True
j = jac(q) # @line L5
dq = dls_step(j, e, lam)
q = [x + d for x, d in zip(q, dq)] # @line L8
return q, history, False # @line L9
def planar_fk(lengths, q):
"""Return the hand position of a planar arm with the given link lengths."""
x = y = a = 0.0
for length, t in zip(lengths, q):
a += t
x += length * math.cos(a)
y += length * math.sin(a)
return [x, y]
def planar_jacobian(lengths, q):
"""Return the 2 by n Jacobian of planar_fk."""
angles = []
a = 0.0
for t in q:
a += t
angles.append(a)
n = len(q)
row_x = [-sum(lengths[k] * math.sin(angles[k]) for k in range(i, n)) for i in range(n)]
row_y = [sum(lengths[k] * math.cos(angles[k]) for k in range(i, n)) for i in range(n)]
return [row_x, row_y]
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_damped_least_squares_inverse_kinematics.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/damped-least-squares-inverse-kinematics/. The authors are listed in prov/J6EXM0.jsonl.
"""Tests of damped least squares inverse kinematics: the two forms of the
step, the step as the minimizer of the damped objective (against random
perturbations), the bound |dq| <= |e| / (2 lam), the limit lam -> 0 against
the pseudoinverse, the example of the page, the local linear rate, random
reachable targets, and a target out of reach."""
import math
import random
import rbm
from damped_least_squares_inverse_kinematics import dls_step, dls_step_normal, ik_dls, planar_fk, planar_jacobian
def rand_matrix(rng, m, n):
return [[rng.uniform(-1.0, 1.0) for _ in range(n)] for _ in range(m)]
def objective(j, e, lam, dq):
r = rbm.sub(rbm.matvec(j, dq), e)
return rbm.dot(r, r) + lam * lam * rbm.dot(dq, dq)
def maxdiff(a, b):
return max(abs(x - y) for x, y in zip(a, b))
def test_two_forms_agree():
rng = random.Random(1)
for m, n in ((2, 2), (2, 3), (3, 2), (6, 6), (3, 7), (6, 4)):
for _ in range(10):
j = rand_matrix(rng, m, n)
e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
lam = rng.uniform(0.01, 1.0)
assert maxdiff(dls_step(j, e, lam), dls_step_normal(j, e, lam)) < 1e-9
def test_step_minimizes_damped_objective():
rng = random.Random(2)
for m, n in ((2, 3), (3, 3), (6, 7), (3, 2)):
for _ in range(10):
j = rand_matrix(rng, m, n)
e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
lam = rng.uniform(0.05, 1.0)
dq = dls_step(j, e, lam)
best = objective(j, e, lam, dq)
# The gradient J^T (J dq - e) + lam^2 dq is zero.
r = rbm.sub(rbm.matvec(j, dq), e)
grad = [g + lam * lam * d for g, d in zip(rbm.matvec(rbm.transpose(j), r), dq)]
assert rbm.norm(grad) < 1e-10
# No random perturbation does better.
for _ in range(50):
s = rng.choice((1e-3, 1e-1, 1.0))
trial = [d + rng.uniform(-s, s) for d in dq]
assert objective(j, e, lam, trial) >= best - 1e-12
def test_step_bound():
rng = random.Random(3)
for _ in range(200):
m, n = rng.choice(((2, 2), (2, 3), (3, 6), (6, 6)))
if rng.random() < 0.5:
j = rand_matrix(rng, m, n)
else:
# rank one, so that J J^T is singular
u = [rng.uniform(-3.0, 3.0) for _ in range(m)]
v = [rng.uniform(-3.0, 3.0) for _ in range(n)]
j = [[a * b for b in v] for a in u]
e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
lam = rng.uniform(0.01, 1.0)
assert rbm.norm(dls_step(j, e, lam)) <= rbm.norm(e) / (2.0 * lam) * (1.0 + 1e-9)
# The bound is reached: one singular value equal to lam, and e along it.
j = [[0.3, 0.0], [0.0, 2.0]]
dq = dls_step(j, [1.0, 0.0], 0.3)
assert abs(rbm.norm(dq) - 1.0 / 0.6) < 1e-12
def test_small_lambda_gives_pseudoinverse():
rng = random.Random(4)
for m, n in ((2, 2), (2, 3), (3, 5), (6, 7)):
for _ in range(5):
j = rand_matrix(rng, m, n)
e = [rng.uniform(-1.0, 1.0) for _ in range(m)]
ref = rbm.matvec(rbm.pinv_right(j), e)
assert maxdiff(dls_step(j, e, 1e-7), ref) < 1e-6 * (1.0 + rbm.norm(ref))
L2 = [1.0, 1.0]
def fk2(q):
return planar_fk(L2, q)
def jac2(q):
return planar_jacobian(L2, q)
def test_planar_jacobian_against_finite_differences():
rng = random.Random(5)
lengths = [1.0, 0.8, 0.5, 0.3]
for _ in range(10):
q = [rng.uniform(-math.pi, math.pi) for _ in range(4)]
num = rbm.num_jacobian(lambda x: planar_fk(lengths, x), q, 1e-6)
got = planar_jacobian(lengths, q)
assert max(abs(a - b) for ra, rb in zip(num, got) for a, b in zip(ra, rb)) < 1e-6
j = jac2([0.0, math.pi / 2.0])
assert maxdiff(j[0] + j[1], [-1.0, -1.0, 1.0, 0.0]) < 1e-15
assert maxdiff(fk2([0.0, math.pi / 2.0]), [1.0, 1.0]) < 1e-15
def test_example_of_the_page():
q = [0.0, 0.01]
e = rbm.sub([1.9, 0.2], fk2(q))
j = jac2(q)
newton = rbm.solve(j, e)
assert maxdiff(newton, [-9.804667, 19.799833]) < 1e-6
dq = dls_step(j, e, 0.1)
assert maxdiff(dq, [0.056365, 0.077488]) < 1e-6
assert rbm.norm(dq) <= rbm.norm(e) / 0.2
q, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], 0.1)
assert ok and len(hist) == 8
for got, want in zip(hist, [0.294, 0.0415, 0.00138, 3.45e-5]):
assert abs(got - want) < 0.005 * want
assert maxdiff(q, [0.0, math.pi / 2.0]) < 1e-10
q, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], 0.5)
assert ok and len(hist) == 25
def test_local_linear_rate():
# Near the solution (0, pi/2), the error ratio tends to lam^2 / (s^2 + lam^2), s the least singular value.
s2 = (3.0 - math.sqrt(5.0)) / 2.0
for lam in (0.1, 0.5):
_, hist, ok = ik_dls(fk2, jac2, [1.0, 1.0], [0.3, 1.2], lam)
assert ok
rate = lam * lam / (s2 + lam * lam)
ratios = [b / a for a, b in zip(hist, hist[1:]) if 1e-9 < b and a < 1e-3]
assert ratios and all(abs(r - rate) < 0.02 * rate for r in ratios)
def test_random_reachable_targets():
rng = random.Random(6)
lengths = [1.0, 0.8, 0.5]
for _ in range(30):
q_star = [rng.uniform(-math.pi, math.pi) for _ in range(3)]
x_d = planar_fk(lengths, q_star)
q0 = [rng.uniform(-math.pi, math.pi) for _ in range(3)]
q, hist, ok = ik_dls(lambda x: planar_fk(lengths, x), lambda x: planar_jacobian(lengths, x), x_d, q0, 0.1, max_iter=2000)
assert ok
assert maxdiff(planar_fk(lengths, q), x_d) < 1e-9
def test_out_of_reach():
# With lam = 0.5 the arm stretches toward the target and stops at the nearest point.
q, hist, ok = ik_dls(fk2, jac2, [2.5, 0.0], [0.2, 0.5], 0.5, max_iter=200)
assert not ok
assert abs(hist[-1] - 0.5) < 1e-12
assert maxdiff(fk2(q), [2.0, 0.0]) < 1e-12
# Every step stays bounded by |e| / (2 lam).
q = [0.2, 0.5]
for _ in range(50):
e = rbm.sub([2.5, 0.0], fk2(q))
dq = dls_step(jac2(q), e, 0.1)
assert rbm.norm(dq) <= rbm.norm(e) / 0.2 * (1.0 + 1e-9)
q = [a + b for a, b in zip(q, dq)]
History
Wampler (1986) and Nakamura and Hanafusa (1986) brought the damped least squares step to the inverse kinematics of arms in the same year, independently. Wampler derived it as the minimizer of a sum of the squared error and the squared joint motion. Nakamura and Hanafusa called it the singularity robust inverse and studied its behavior near singularities with a damping that changes with the configuration. The same regularization was known much earlier in numerical analysis as Tikhonov regularization, and in nonlinear least squares as the Levenberg-Marquardt method. Buss (2004) compared the transpose, pseudoinverse and damped least squares methods in a survey that is often cited in computer animation.
References
- Charles W. Wampler II, Manipulator inverse kinematic solutions based on vector formulations and damped least-squares methods, IEEE Transactions on Systems, Man, and Cybernetics 16(1), 93-101, 1986, the damped least squares formulation of the inverse kinematics step
- Yoshihiko Nakamura and Hideo Hanafusa, Inverse kinematic solutions with singularity robustness for robot manipulator control, Journal of Dynamic Systems, Measurement, and Control 108(3), 163-171, 1986, the singularity robust inverse and its damping factor
- Samuel R. Buss, Introduction to Inverse Kinematics with Jacobian Transpose, Pseudoinverse and Damped Least Squares methods, unpublished survey, University of California, San Diego, 2004, the sections on damped least squares and on the singular value decomposition of the step
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 J6EXM0 Edit this page History Report an error Markdown