Algorithmcore
Resolved-rate motion control
Also called resolved motion rate control.
Whitney's scheme that turns a desired end effector velocity into joint rates through the inverse or pseudoinverse Jacobian.
- Time
- Θ(N m^2 n) worst
- Space
- Θ(m n) extra
- Where
- N = the number of control steps; m = the dimension of the task; n = the number of joints
- Model
- Real RAM
- Properties
- deterministiconlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Daniel E. Whitney, 1969
Resolved-rate motion control moves the end effector of a robot arm along a desired path by commanding joint velocities, not joint positions. At each control step it reads the joint values , forms the Jacobian , and solves for the joint rates, where is the desired end effector velocity plus a correction for the present error. For a square, nonsingular the solution is ; for a redundant arm it is the least norm solution with the pseudoinverse. Daniel Whitney introduced the scheme in 1969, and it is still the basic way to drive an arm in Cartesian coordinates, for example from a joystick.
In plain words
You want the hand of a robot to move in a straight line, but you can only tell each motor how fast to turn. At this moment, a small turn of each motor moves the hand in some known direction. So you ask: which mix of motor speeds moves the hand exactly the way I want right now? That is a small system of linear equations, and you solve it. A moment later the arm has a new shape, so you ask again, and you keep doing this many times each second. Because each answer is only right for an instant, the hand slowly drifts away from the path. A small correction, which pulls the hand back toward where it should be, removes the drift.
The problem
Input.
- A forward kinematics map from joint values to task coordinates , with , and its Jacobian .
- A desired task path for , with its velocity .
- A start configuration , a gain matrix (often with ), a time step and a number of steps .
Output. Joint rates for the steps , and the joint values that they produce, such that stays close to , with .
The scheme needs to have full row rank along the path. For a position task, is the position of the end effector. For a full pose, is a twist and the error is a twist too, for example the body twist of the logarithm of , and must be the Jacobian in the same frame and the same order as .
The algorithm
RESOLVED-RATE(FK, JACOBIAN, q0, x_d, x_d', K, Δt, N)- 1
q ← q0 - 2
for k ← 0 to N - 1 - 3
t ← k Δt - 4
e ← x_d(t) - FK(q) ▷ task error - 5
J ← JACOBIAN(q) - 6
v ← x_d'(t) + K e ▷ feedforward plus feedback - 7
q' ← J^+ v ▷ least norm solution of J q' = v - 8
q ← q + Δt q' ▷ the joint servos run q' for one step - 9
return q_0, q_1, ..., q_N
Line L7 uses , which is when ; it is computed by solving the system and setting . On a real robot, line L8 is done by the joint velocity servos; in simulation it is one explicit Euler step. With , the scheme is open loop, as in Whitney's paper. With positive definite, it is the closed-loop form of Siciliano et al., which keeps the error small.
Example
Take a planar 2R arm with unit links and the position task . The tip must go around the circle with center m and radius 0.3 m at 1 rad/s:
The start is the inverse kinematics solution with at : .
- Line L4: .
- Line L5: , with , far from singular.
- Line L6: m/s.
- Line L7: rad/s.
- Line L8: with s, .
The table gives the tip error at the end of the run.
| gain | s | s | s |
|---|---|---|---|
| 0 (open loop) | m | m | m |
| 10 s⁻¹ | m | m |
Open loop, the error grows along the path and halves when the step halves: it is the first order drift of the Euler steps. With , the error stays bounded by about times a constant over , and at s the final joint values are , against the exact .
To see the feedback act on a start error, move the start to , which puts the tip m away from . Open loop, the error stays near 0.1 m for the whole run, and it is m at the end. With and s, the error decays like and stays below m from s on.
Correctness
The step. If has full row rank, then satisfies , and among all solutions it has the least norm, because every other solution differs from it by a vector of , which is orthogonal to .
Continuous time. If the joints follow exactly, then the error satisfies
So the error obeys a linear equation with no coupling to the arm: . With and , every error decays at the rate ; with the error stays at , so the open-loop scheme tracks the path exactly from an exact start, and keeps any start error.
Discrete time. The proof below shows the following bound for . Let on a neighborhood of the path, let bound , let bound the second derivative of , and let bound . Then for and small enough,
where bounds the joint rates. For , . Both bounds match the example: the open-loop error grows with and is proportional to , and the closed-loop error is proportional to .
Proof: RESOLVED-RATE gives least norm joint rates and bounded tracking errorfull
We use the notation of the page. The task map is with , of class , with the Jacobian . All vector norms are Euclidean, and the norm of a matrix is the induced norm, its largest singular value. The proof is in exact arithmetic, in the real RAM.
Lines L4 to L8 of RESOLVED-RATE compute, for and ,
The step
Lemma 1. Let be an matrix of rank , and let . For every :
- ;
- every with satisfies , so is the unique solution of least norm;
- , where is the smallest singular value of .
Proof. Since has rank , the matrix is positive definite, hence invertible, and . If , then . The vector with lies in , and . So is a sum of two orthogonal vectors, which gives item 2; equality holds only for . For item 3, write with orthogonal and and . Then , and , whose singular values are . The largest is .
So line L7 computes the least norm joint velocity that produces the task velocity exactly, as the page claims.
Continuous time
Proposition 2. Let be a solution of on , with and of rank for all . Then , so . If is symmetric and positive semidefinite with smallest eigenvalue , then .
Proof. By the chain rule and Lemma 1, . This linear equation with constant coefficients has the unique solution . For the bound, , so does not increase.
For the error stays equal to : the open-loop law tracks the path exactly from an exact start, and keeps any start error.
One discrete step
Make these assumptions.
- (A1) is on , with and .
- (A2) is a set on which , and is a constant such that whenever the segment from to lies in . (Such an exists when is compact and convex, by Taylor's theorem with the bound of the second derivative of .)
- (A3) The iterates and the segments between consecutive iterates lie in , and .
Lemma 3. Under (A1) to (A3), for every ,
where .
Proof. By Taylor's theorem with remainder, with . By (A2) and (A3), with . By Lemma 1, . Subtracting,
with . The bound on is item 3 of Lemma 1 with .
The open-loop bound
Theorem 4. Under (A1) to (A3) with , let . Then for .
Proof. With , , so and by Lemma 3. Then , and by induction .
So, from an exact start, the open-loop error at a fixed time is : halving the step halves the bound, as in the example on the page.
The closed-loop bound
Theorem 5. Under (A1) to (A3) with and , fix a number , and let
If and , then for ,
In particular .
Proof. The constants and depend on , , , , and , but not on or on the iterates, so the conditions on can be met by taking small; there is no circular argument.
First, for every . With , is a convex combination of and .
Now induct on . For , . Suppose . Then , so , and by Lemma 3. Since , the matrix has norm , so
Remark. For a symmetric positive definite with eigenvalues in and , the same proof works with , with replaced by in the rate and in the final term, and by in .
So the closed-loop error forgets the start error at the geometric rate and then stays within of the path for all , a bound that does not grow with the length of the run. Both theorems need (A3): the iterates must stay where is well conditioned. Near a kinematic singularity , and , and the bounds blow up, which is the failure described on the page.
Complexity
Each step evaluates and , which costs for a serial arm with a task of fixed size, forms in , solves an system in , and multiplies by in . Since , a step costs , and steps cost in the real RAM. The extra space is for and its products, plus if the whole joint path is kept. For a 6-joint arm and a 6-dimensional task, a step is a few hundred arithmetic operations, small enough for a control loop that runs many hundreds of times per second.
Properties
- Online. Each step needs only the present and the present values of and ; the path can come from a joystick or a sensor as it goes.
- Local. The scheme follows the path step by step; it does not plan, and it does not see joint limits or obstacles unless a null space term is added.
- Linear error dynamics. In continuous time, the task error obeys whatever the arm, as long as has full row rank.
- Least norm rates. For a redundant arm, is the smallest joint velocity that gives ; this is a choice, and other inverses give other motions with the same task velocity.
- Not repeatable. For a redundant arm, a closed task path in general does not give a closed joint path with pseudoinverse rates; Klein and Huang (1983) discussed this lack of repeatability.
- Fails at singularities. As , the joint rates for a fixed grow like , and at a kinematic singularity line L7 is undefined.
Variants and improvements
- Damped least squares. Replace by , which bounds the joint rates near singularities at the price of a tracking error; see damped least squares inverse kinematics.
- The transpose. Replace by , which needs no inverse; for and it gives , so never increases; see the Jacobian transpose method.
- A null space term. For a redundant arm, add to pursue a second goal, as in null space projection.
- Orientation. For a full pose, use the twist error from the matrix logarithm of with the body Jacobian, or Euler angle errors with the analytic Jacobian.
- Acceleration level. Resolved acceleration control differentiates once more and commands joint accelerations, which a computed torque loop turns into torques.
- Rate limits. If exceeds a joint speed limit, scaling the whole vector down keeps the direction of the end effector motion and slows it.
- Visual servoing. Image-based visual servoing uses the same law with the interaction matrix of image features in place of .
When to use it
Use resolved-rate control to drive an end effector in Cartesian coordinates in real time: teleoperation with a joystick or a master arm, small corrections from a force or vision sensor, and smooth paths that stay away from singularities. Add feedback () whenever the controller integrates the rates itself, to remove the drift. For a single goal pose with no path to follow, the Jacobian pseudoinverse method of inverse kinematics is the same step used as an iteration. Near singularities, use damped least squares; for paths with joint limits and obstacles, plan the path first.
Pitfalls
- Singularities. A path that passes near a singularity asks for huge joint rates. Watch or the manipulability, and switch to damping or slow down; the threshold is a rule of thumb for each arm.
- Open-loop drift. With , the Euler steps and the servo errors add up, and the tip leaves the path. Use .
- Gain and step. For the discrete loop, the error of a fixed target follows , which changes sign at every step for and diverges for . Keep well below 1.
- Frames and order. The velocity and the Jacobian must be in the same frame and use the same order of the angular and the linear parts; a space twist with a body Jacobian gives wrong motion without an error.
- Mixed units. For a pose task, minimizes a sum of squares of joint rates, but the gain mixes rad and m; scale the angular and the linear errors on purpose.
- Joint limits. The scheme does not see them; a joint can reach its limit while the task is still feasible for another posture.
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
# 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
resolved_rate_motion_control.py 49 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/resolved-rate-motion-control/. The authors are listed in prov/XNS6ZX.jsonl.
"""Resolved-rate motion control of a position task, with a fixed time step.
The task is x = fk(q) in R^m with Jacobian jac(q), an m by n matrix of
full row rank (m <= n). Each step sets the joint rate
q' = J^+ (x_d'(t) + K (x_d(t) - fk(q)))
with the right pseudoinverse J^+ = J^T (J J^T)^-1, and moves the joints by
one explicit Euler step q <- q + dt q'. With K = 0 this is the open-loop
scheme of Whitney (1969); with K > 0 the task error is fed back
(Siciliano et al., Robotics, Section 3.7.1).
rbm.pinv_right raises ValueError when J J^T is singular to working
precision, that is, at a kinematic singularity.
"""
import rbm
def joint_rate(j, v):
"""Return the minimum-norm q' with J q' = v."""
return rbm.matvec(rbm.pinv_right(j), v)
def _gain_times(gain, e):
if isinstance(gain, list):
return rbm.matvec(gain, e)
return [gain * x for x in e]
def resolved_rate(fk, jac, q0, xd, xd_dot, gain, dt, steps):
"""Return the list of joint vectors q_0, q_1, ..., q_steps.
xd(t) and xd_dot(t) give the desired task position and velocity.
gain is a number k (K = k I) or an m by m matrix K.
"""
q = [float(x) for x in q0] # @line L1
path = [q]
for k in range(steps): # @line L2
t = k * dt # @line L3
e = rbm.sub(xd(t), fk(q)) # @line L4
j = jac(q) # @line L5
v = rbm.add(xd_dot(t), _gain_times(gain, e)) # @line L6
qdot = joint_rate(j, v) # @line L7
q = [x + dt * d for x, d in zip(q, qdot)] # @line L8
path.append(q)
return path # @line L9
test_resolved_rate_motion_control.py 166 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/resolved-rate-motion-control/. The authors are listed in prov/XNS6ZX.jsonl.
"""Tests of resolved-rate control with explicit Euler steps on planar 2R and
3R arms with unit links: the 2R check values, the minimum-norm joint rate
against a KKT solve, first-order drift of the open-loop scheme, a bounded
error with feedback, agreement with closed-form 2R inverse kinematics, the
linear error dynamics, and the error at a singularity."""
import math
import random
import pytest
import rbm
from resolved_rate_motion_control import joint_rate, resolved_rate
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 fk_planar(q):
a = x = y = 0.0
for t in q:
a += t
x += math.cos(a)
y += math.sin(a)
return [x, y]
def jac_planar(q):
n = len(q)
out = [[0.0] * n, [0.0] * n]
for j in range(n):
a = sum(q[: j + 1])
for i in range(j + 1):
out[0][i] -= math.sin(a)
out[1][i] += math.cos(a)
return out
def ik_2r(x, elbow):
"""Closed-form inverse kinematics of the 2R arm with unit links."""
c2 = (x[0] ** 2 + x[1] ** 2 - 2.0) / 2.0
q2 = elbow * math.acos(c2)
q1 = math.atan2(x[1], x[0]) - math.atan2(math.sin(q2), 1.0 + math.cos(q2))
return [q1, q2]
CENTER = [1.0, 0.8]
RADIUS = 0.3
OMEGA = 1.0
def circle(t):
return [CENTER[0] + RADIUS * math.cos(OMEGA * t), CENTER[1] + RADIUS * math.sin(OMEGA * t)]
def circle_dot(t):
return [-RADIUS * OMEGA * math.sin(OMEGA * t), RADIUS * OMEGA * math.cos(OMEGA * t)]
def final_error(path, dt):
t = (len(path) - 1) * dt
return rbm.norm(rbm.sub(circle(t), fk_planar(path[-1])))
def test_2r_check_values():
q = [0.0, math.pi / 2.0]
assert maxdiff(fk_planar(q), [1.0, 1.0]) < 1e-15
assert maxdiff(jac_planar(q), [[-1.0, -1.0], [1.0, 0.0]]) < 1e-15
for q in ([0.4, 1.1], [0.2, -0.7, 1.3]):
assert maxdiff(rbm.num_jacobian(fk_planar, q), jac_planar(q)) < 1e-6
for elbow in (1.0, -1.0):
assert maxdiff(fk_planar(ik_2r([1.0, 1.0], elbow)), [1.0, 1.0]) < 1e-12
assert maxdiff(ik_2r([1.0, 1.0], -1.0), [math.pi / 2.0, -math.pi / 2.0]) < 1e-12
def test_joint_rate_is_minimum_norm():
rng = random.Random(11)
for _ in range(5):
q = [rng.uniform(-1.0, 1.0) for _ in range(3)]
j = jac_planar(q)
v = [rng.uniform(-1.0, 1.0) for _ in range(2)]
qd = joint_rate(j, v)
kkt = rbm.zeros(5, 5)
for i in range(3):
kkt[i][i] = 1.0
for r in range(2):
for c in range(3):
kkt[3 + r][c] = j[r][c]
kkt[c][3 + r] = j[r][c]
sol = rbm.solve(kkt, [0.0, 0.0, 0.0] + v)
assert maxdiff(qd, sol[:3]) < 1e-12
assert maxdiff(rbm.matvec(j, qd), v) < 1e-12
# square case: the pseudoinverse is the inverse
j = jac_planar([0.0, math.pi / 2.0])
assert maxdiff(joint_rate(j, [0.0, 1.0]), rbm.solve(j, [0.0, 1.0])) < 1e-15
def test_open_loop_drift_is_first_order():
q0 = ik_2r(circle(0.0), 1.0)
errs = []
for dt in (0.02, 0.01, 0.005):
steps = int(round(2.0 / dt))
path = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, 0.0, dt, steps)
errs.append(final_error(path, dt))
assert errs[0] < 0.05
for a, b in zip(errs, errs[1:]):
assert 1.6 < a / b < 2.4
def test_feedback_bounds_the_error():
q0 = ik_2r(circle(0.0), 1.0)
q0 = [q0[0] + 0.1, q0[1] - 0.1]
dt, k = 0.01, 20.0
path = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, k, dt, 300)
errs = [rbm.norm(rbm.sub(circle(i * dt), fk_planar(q))) for i, q in enumerate(path)]
assert errs[0] > 0.05
assert max(errs[100:]) < 2e-3
# the open-loop run from the same start keeps its initial error
path0 = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, 0.0, dt, 300)
assert final_error(path0, dt) > 0.04
# the tracked joints are close to the closed-form solution of the same branch
t = 300 * dt
assert maxdiff(path[-1], ik_2r(circle(t), 1.0)) < 5e-3
def test_error_halves_with_the_step():
q0 = ik_2r(circle(0.0), -1.0)
out = []
for dt in (0.01, 0.005):
steps = int(round(2.0 / dt))
path = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, 10.0, dt, steps)
out.append(final_error(path, dt))
assert out[1] < 1e-3
assert 1.6 < out[0] / out[1] < 2.4
def test_linear_error_dynamics_for_a_fixed_target():
x_d = [1.2, 0.6]
dt, k = 0.01, 5.0
path = resolved_rate(fk_planar, jac_planar, [0.1, 1.4], lambda t: x_d, lambda t: [0.0, 0.0], k, dt, 400)
errs = [rbm.norm(rbm.sub(x_d, fk_planar(q))) for q in path]
# near the solution, e_{j+1} = (1 - k dt) e_j + O(|e_j|^2)
for a, b in zip(errs[200:260], errs[201:261]):
assert abs(b / a - (1.0 - k * dt)) < 1e-3
assert errs[-1] < 1e-4 * errs[0]
def test_3r_redundant_tracking():
q0 = [0.3, -0.9, 1.4]
dt, k = 0.005, 10.0
path = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, k, dt, 1000)
errs = [rbm.norm(rbm.sub(circle(i * dt), fk_planar(q))) for i, q in enumerate(path)]
assert max(errs[400:]) < 1e-3
# a matrix gain gives the same run as the number k
path_m = resolved_rate(fk_planar, jac_planar, q0, circle, circle_dot, [[k, 0.0], [0.0, k]], dt, 50)
assert maxdiff(path_m[-1], path[50]) < 1e-14
def test_singular_configuration_raises():
with pytest.raises(ValueError):
joint_rate(jac_planar([0.3, 0.0]), [1.0, 0.0])
History
Whitney (1969) proposed to command the velocity of the end effector and to resolve it into joint rates through the inverse of the Jacobian, for manipulators and for arm prostheses, and named the method resolved motion rate control. Liégeois (1977) added the projection onto the null space for redundant arms, and Klein and Huang (1983) reviewed pseudoinverse rate control of redundant arms and its lack of repeatability. Textbooks such as Siciliano et al. (2009) present it with feedback of the task error as the Jacobian inverse algorithm of closed-loop inverse kinematics, and Lynch and Park (2017) as inverse velocity kinematics.
References
- Daniel E. Whitney, Resolved motion rate control of manipulators and human prostheses, IEEE Transactions on Man-Machine Systems, 1969, the whole paper (the end effector velocity command resolved into joint rates by the inverse Jacobian)
- Bruno Siciliano, Lorenzo Sciavicco, Luigi Villani and Giuseppe Oriolo, Robotics: Modelling, Planning and Control, Springer, 2009, Chapter 3, Section 3.5 (inverse differential kinematics, the inverse and the pseudoinverse) and Section 3.7.1 (the Jacobian inverse algorithm with feedback of the task error)
- Kevin M. Lynch and Frank C. Park, Modern Robotics: Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 6, Section 6.3 (inverse velocity kinematics, joint rates from the pseudoinverse of the Jacobian)
- Charles A. Klein and Ching-Hsiang Huang, Review of pseudoinverse control for use with kinematically redundant manipulators, IEEE Transactions on Systems, Man, and Cybernetics 13, 245-250, 1983, the whole paper (pseudoinverse rate control of redundant arms and the lack of repeatability for closed task paths)
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 XNS6ZX Edit this page History Report an error Markdown