Algorithmresearch
Analytical derivatives of rigid body dynamics
Also called RNEA derivatives.
Carpentier and Mansard's recursion for the partial derivatives of inverse dynamics in O(n d) time for a tree of depth d (O(n^2) for a serial chain), and of forward dynamics through M^-1.
- Time
- O(n^3) forwardΘ(n d) inverse
- Space
- Θ(n d) extra
- Where
- d = the depth of the tree, the largest number of joints on a path from the base (d = n for a serial chain); n = the number of joints, one degree of freedom each
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Justin Carpentier, Nicolas Mansard, 2018
The analytical derivatives of rigid body dynamics are the partial derivatives of the joint forces by the joint positions and velocities , and the partial derivatives of the accelerations by , and . Carpentier and Mansard (2018) computed the derivatives of the inverse dynamics by differentiating each line of the recursive Newton-Euler algorithm (RNEA) with spatial algebra, and they obtained the derivatives of the forward dynamics from them with the inverse of the joint-space inertia matrix. The result is exact up to rounding, unlike finite differences, and much faster than finite differences or general automatic differentiation of the RNEA. The derivatives are what trajectory optimization, DDP and nonlinear MPC need at every step. The cost is for a tree of depth , which is for a serial chain. It cannot be , because the output of a serial chain has nonzero entries.
In plain words
An optimizer that plans the motion of a robot must know how a small change of a joint angle or speed changes the forces at all the joints. The simple way is to nudge each joint a little, run the force computation again, and compare. That needs many runs, and the nudge spoils the digits. This method works out the change directly. It follows the same two walks over the robot as the force computation, out to the tips and back to the base. Next to each link's motion it also carries how that motion changes with each joint above it. On the way back, it carries how each joint push changes. A link far out on a long arm depends on every joint before it, so the total work grows with the length of the arm times the number of links.
The problem
The robot is a tree of rigid bodies with the notation of the recursive Newton-Euler algorithm: body has the parent ( for the base), joint has the screw axis in the frame , with , and is the spatial inertia of body . Spatial vectors have the angular part first, and and are the spatial cross products of spatial vector algebra. is the set of body and its ancestors.
Input: the model, and gravity . Output: and the three matrices , and .
For the forward dynamics, the input is and the output is with , and .
The algorithm
The algorithm rests on two identities for the derivative of a joint transform. Since , for a motion vector and a force vector that do not depend on ,
For each body, the algorithm stores the derivatives of , and by the coordinates of the joints in ; all other derivatives are 0. In the pseudocode, is the derivative by , by or by , and a line with runs for each of the three.
RNEA-DERIVATIVES(model, q, q̇, q̈, a_g)- 1
for i ← 1 to n do ▷ forward pass, with the RNEA - 2
X_i ← Ad(T_{λ(i),i}(q_i)^-1) ; v_i, a_i, f_i as in the RNEA - 3
for k in anc(λ(i)): ∂_k v_i ← X_i ∂_k v_λ(i) ; ∂_k a_i ← X_i ∂_k a_λ(i) - 4
∂v_i/∂q_i ← crm(X_i v_λ(i)) S_i ; ∂a_i/∂q_i ← crm(X_i a_λ(i)) S_i - 5
∂v_i/∂q̇_i ← S_i ; ∂a_i/∂q̇_i ← crm(v_i) S_i ; ∂a_i/∂q̈_i ← S_i - 6
for k in anc(i), by q and by q̇: ∂_k a_i ← ∂_k a_i + crm(∂_k v_i) S_i q̇_i - 7
for k in anc(i): ∂_k f_i ← I_i ∂_k a_i + crf(∂_k v_i) I_i v_i + crf(v_i) I_i ∂_k v_i - 8
for i ← n downto 1 do ▷ backward pass - 9
τ_i ← S_i^T f_i ; for each stored k: ∂τ_i/∂u_k ← S_i^T ∂_k f_i - 10
if λ(i) ≠ 0 then - 11
for each stored k: ∂_k f_λ(i) ← ∂_k f_λ(i) + X_i^T ∂_k f_i - 12
∂f_λ(i)/∂q_i ← ∂f_λ(i)/∂q_i + X_i^T crf(S_i) f_i - 13
f_λ(i) ← f_λ(i) + X_i^T f_i - 14
return τ, ∂τ/∂q, ∂τ/∂q̇, ∂τ/∂q̈
Line L3 carries the derivatives of the parent through ; it is the first part of the product rule, for the joints above . Line L4 is the first identity, the derivative of itself by . Line L5 is the direct effect of and . Line L6 differentiates the velocity product through . Line L7 is the product rule on the Newton-Euler wrench ; for the derivatives by , the velocity does not change and only is left. In the backward pass, the derivatives of by the joints below arrive from the children through line L11, and line L12 is the second identity, the derivative of by .
The forward dynamics derivatives follow from the identity . Differentiate it:
where the derivatives of are evaluated at , not at . So the forward derivatives cost one forward dynamics, one call of RNEA-DERIVATIVES, which also returns , and a product with .
Example
Take the planar arm with two revolute joints about , links of 1 m and point masses of 1 kg at the link ends. Its inverse dynamics in closed form, with and and without gravity, is
At , rad/s and , the algorithm returns N m and
The closed form gives the same: , , , and does not depend on . The derivative by is 0 here, because does not depend on without gravity, and has the factors and , which are both 0 at this state.
For the forward dynamics at the same and with , the articulated-body algorithm gives rad/s. At this , the inverse dynamics derivative by is no longer 0: . With ,
The tests check the inverse dynamics values above, and they compare the inverse and forward derivatives on random trees of up to 7 joints with central finite differences (, tolerance ).
With gravity m/s along in the plane, at , and , the algorithm gives and .
Correctness
The derivative of a composition is the composition of the derivatives, so it is enough to differentiate each line of the RNEA in order. Two facts make this simple. First, depends only on , and the two identities above give its derivative in closed form. Second, and depend only on the joints in , and depends only on the joints that are on a common path with , so all other derivatives are 0 and need no storage. By induction over the forward pass, the stored derivatives of , and the body wrench are exact; by backward induction, the derivatives of the transmitted wrench are complete when the loop reaches , because all children have larger indices. The derivative of is , since is constant. The forward dynamics formulas follow from the chain rule applied to . The correctness proof of this page gives each step.
Proof: The differentiated Newton-Euler recursion returns the partial derivatives of the dynamicsfull
We use the notation of the page and of the recursive Newton-Euler algorithm (RNEA). Body has the parent . is the set of and its ancestors, and is the set of and its descendants. We write for the partial derivative by one coordinate , where is , or . The operators satisfy and .
Lemma 1 (the two identities). For a motion vector and a force vector that do not depend on ,
Proof. The joint pose is , so and . The derivative at is . Then . For the second identity, .
Lemma 2 (dependence). and depend only on , and with . The joint wrench and depend only on the coordinates of joints with or .
Proof. Lines L4 and L5 of the RNEA use only the parent, so the first claim follows by induction on . The body wrench depends on the coordinates of , and adds the of through transforms of joints in . A joint in for some is in or in .
So every derivative that the algorithm does not store in a dict is 0.
Lemma 3 (the forward pass). After line L7 for body , the dicts hold, for every , the derivatives , and by , by and by .
Proof. By induction on . Differentiate the RNEA lines , and , where .
- For , , and do not change with , so and the same for . This is line L3, with the dicts of the parent from the induction hypothesis.
- For and : and do not depend on , so Lemma 1 gives and . This is line L4.
- For and : , and the last term of gives from the factor . This is line L5. For : .
- For every and , the last term of also gives . This is line L6. For and this term is , so it does no harm.
- The product rule on gives . This is line L7. For the velocities do not change, and only is left.
Theorem. Line L14 returns , , and .
Proof. The value is the RNEA (its correctness proof applies line by line). The backward pass of the RNEA computes and . Differentiate:
by the product rule and Lemma 1, because depends on only. We show by backward induction on that, when the loop of line L8 reaches , the dicts of hold for every allowed by Lemma 2, and is complete. The dicts start with by Lemma 3. Each child was handled before ; at that time and its dicts were complete by the induction hypothesis, and lines L11 to L13 added the three terms of the sum. Nothing else changes these values.
Then because is constant, which is line L9. Every entry that the dicts do not hold is 0 by Lemma 2, and the output matrices start at 0. Since is affine in with the matrix , .
Corollary (forward dynamics). Let be the solution of . Then, at ,
Proof. The identity holds for all arguments. Differentiate it by with the chain rule: . The same holds for . By : . is invertible because it is positive definite.
Cost. For body the dicts of the forward pass have entries, and each entry costs a fixed number of products. In the backward pass, the dict of holds the joints of and , and each entry is moved once to the parent. The sum over all bodies of these sizes is the number of pairs on a common path, which is at most . So the time is for a tree of depth and for a serial chain.
Complexity
In the real RAM, body stores derivatives of each of and for each of , and , and each costs a fixed number of products. In the backward pass, the derivatives of cover the joints on a common path with , and each one is moved to the parent once. The number of such pairs is at most , so the time is for a tree of depth and for a serial chain. This is the order of the number of nonzero entries of the output, so it is optimal in order. The extra space is for the stored derivatives. An implementation that stores the output as dense matrices also spends to set them to zero.
Finite differences need or calls of the RNEA for the two derivatives, which is also , but with a much larger constant, and they lose about half of the digits. The forward dynamics derivatives add a forward dynamics in , the inverse and two products of matrices, which is when done densely.
Carpentier and Mansard (2018) report measurements in their library Pinocchio on a 2.2 GHz Intel Core i7. For a KUKA arm, the HyQ quadruped and the Atlas humanoid, the inverse dynamics took 1.20, 2.14 and 5.51 µs, its analytical derivatives 3.34, 7.01 and 16.72 µs, and finite differences of the inverse dynamics 21.26, 88.52 and 452.46 µs. The analytical derivatives of the forward dynamics took 5.78, 14.24 and 45.20 µs. These are measurements on one machine, not bounds.
Properties
- Exact. The derivatives are exact up to floating-point rounding. Central finite differences with a step have an error of order plus a rounding error of order .
- . The algorithm returns the joint-space inertia matrix as a side product, the same matrix that the composite rigid body algorithm computes.
- Sparsity follows the tree. and are 0 when joints and are on different branches, the same pattern as the branch-induced sparsity of .
- Gravity enters only . Gravity is a base acceleration that does not depend on , so it changes only.
- Linear in . is affine in , and does not depend on .
Variants and improvements
- Matrix form. Carpentier and Mansard (2018) write the same recursion with matrices per body in place of one derivative per joint, which suits vectorized linear algebra.
- Automatic differentiation. Forward or reverse mode automatic differentiation of an RNEA code gives the same numbers, and it works for any code, but it has a larger constant.
- Contact dynamics. The same idea extends to constrained and contact dynamics, where the derivatives of the contact forces are needed for contact-implicit trajectory optimization.
- Floating base. For a free base, the configuration lies on a Lie group, and the derivative by is taken in the tangent space; see floating-base dynamics.
- Second order. Some optimizers need the second derivatives of the dynamics; they can be obtained by differentiating the recursion again, at a higher cost.
When to use it
Use these derivatives inside gradient-based trajectory optimization, control-limited DDP, nonlinear MPC and linearization of a robot model around a trajectory. They also give the Jacobians of the dynamics for an extended Kalman filter that estimates joint states. For one-time checks or very small arms, finite differences are fine. For a robot with a floating base and many joints, the analytical derivatives are the fastest exact choice.
Pitfalls
- Forward derivatives at the wrong acceleration. needs at , not at . The example above shows the difference.
- The derivative of . Forgetting line L12 drops the term and gives wrong entries for the ancestors of , but correct diagonal entries.
- The sign convention of the joint transform. The identities hold for with in the child frame. With the exponential on the left, is in the parent frame, and the identities change.
- Finite differences as the reference. They agree only to about to in double precision. A test needs a tolerance to match.
- A claim of . The derivatives of a serial chain have nonzero entries, so no algorithm can output them in time.
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
rigid_body_dynamics_derivatives.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rigid-body-dynamics-derivatives/. The authors are listed in prov/M6C9BY.jsonl.
"""Analytical derivatives of inverse and forward dynamics (Carpentier and Mansard, 2018).
Spatial vectors follow Featherstone, Rigid Body Dynamics Algorithms (2008),
with the angular part first: a motion vector is (omega, v) and a force
vector is (n, f). Every quantity of body i is in the coordinates of the
frame of body i.
The tree has bodies 0 .. n-1. parent[i] < i is the parent body, or -1 for
the fixed base. Joint i has one degree of freedom with the screw axis
S_i (a 6-vector in the coordinates of body i). At joint value q_i the pose
of frame i in the frame of its parent is T_tree[i] exp([S_i] q_i). X_i is
the 6x6 matrix that maps motion vectors from parent coordinates to body i
coordinates, and its transpose maps force vectors from body i to the
parent.
The derivatives use two identities. If X_i depends on q_i as above, then
d(X_i m)/dq_i = crm(X_i m) S_i for a motion vector m, and
d(X_i^T f)/dq_i = X_i^T crf(S_i) f for a force vector f.
A derivative of a body quantity is stored as a dict from a joint index k
to the 6-vector of the partial derivative by the k-th coordinate. The
velocity and the acceleration of body i depend only on the joints on the
path from i to the root, so their dicts hold at most depth(i) entries.
"""
import rbm
# Gravity in the base frame, z up, in m/s^2.
GRAVITY = [0.0, 0.0, -9.81]
def spatial_inertia(mass, com, inertia_com):
"""Return the 6x6 spatial inertia about the frame origin.
mass in kg, com the center of mass c in the body frame, inertia_com
the 3x3 rotational inertia about the center of mass. The result is
[[I_c + m [c][c]^T, m [c]], [m [c]^T, m 1]].
"""
c = rbm.hat3(com)
top_left = rbm.add(inertia_com, rbm.scale(rbm.mul(c, rbm.transpose(c)), mass))
out = rbm.zeros(6, 6)
for r in range(3):
for k in range(3):
out[r][k] = top_left[r][k]
out[r][k + 3] = mass * c[r][k]
out[r + 3][k] = mass * c[k][r]
out[r + 3][r + 3] = mass
return out
def cross_motion(v, m):
"""Return crm(v) m = (w x m_w, v_lin x m_w + w x m_lin) for motion vectors."""
w, vl = v[:3], v[3:]
return rbm.cross(w, m[:3]) + rbm.add(rbm.cross(vl, m[:3]), rbm.cross(w, m[3:]))
def cross_force(v, f):
"""Return crf(v) f = (w x n + v_lin x f_lin, w x f_lin) for a force vector f."""
w, vl = v[:3], v[3:]
return rbm.add(rbm.cross(w, f[:3]), rbm.cross(vl, f[3:])) + rbm.cross(w, f[3:])
class Model:
"""A kinematic tree of rigid bodies, each with one joint to its parent."""
def __init__(self):
self.parent = []
self.tree = []
self.screw = []
self.inertia = []
@property
def n(self):
return len(self.parent)
def add_body(self, parent, tree, screw, inertia):
"""Append a body and return its index (see the module comment)."""
if not -1 <= parent < self.n:
raise ValueError("the parent must be -1 or an earlier body")
if len(screw) != 6 or len(inertia) != 6:
raise ValueError("a screw axis has 6 entries and an inertia is 6x6")
self.parent.append(parent)
self.tree.append(tree)
self.screw.append([float(x) for x in screw])
self.inertia.append(inertia)
return self.n - 1
def joint_transform(model, i, qi):
"""Return X_i, the motion transform from the parent of i to body i."""
pose = rbm.mul(model.tree[i], rbm.se3_exp(rbm.scale(model.screw[i], qi)))
return rbm.adjoint(rbm.T_inv(pose))
def _map(xs, d):
"""Return {k: X d[k]} for a dict d of motion vectors."""
return {k: rbm.matvec(xs, vec) for k, vec in d.items()}
def _add_into(d, k, vec):
d[k] = rbm.add(d[k], vec) if k in d else vec
def rnea(model, q, qd, qdd, gravity=GRAVITY):
"""Return tau = M(q) qdd + C(q, qd) qd + g(q) by the recursive Newton-Euler algorithm."""
return rnea_derivatives(model, q, qd, qdd, gravity)[0]
def rnea_derivatives(model, q, qd, qdd, gravity=GRAVITY):
"""Return (tau, dtau/dq, dtau/dqd, dtau/dqdd) at (q, qd, qdd).
The three Jacobians are n x n lists of rows; dtau/dqdd is the
joint-space inertia matrix M(q).
"""
n = model.n
if not len(q) == len(qd) == len(qdd) == n:
raise ValueError("q, qd and qdd need one entry per joint")
zero = [0.0] * 6
a_base = [0.0, 0.0, 0.0] + [-x for x in gravity]
xs, v, a, f = [None] * n, [None] * n, [None] * n, [None] * n
dv_q, da_q, dv_qd, da_qd, da_qdd = ([None] * n for _ in range(5))
df_q, df_qd, df_qdd = [None] * n, [None] * n, [None] * n
for i in range(n): # @line L1
p = model.parent[i]
s = model.screw[i]
inertia = model.inertia[i]
xs[i] = joint_transform(model, i, q[i]) # @line L2
vj = rbm.scale(s, qd[i])
xv = rbm.matvec(xs[i], zero if p < 0 else v[p])
xa = rbm.matvec(xs[i], a_base if p < 0 else a[p])
v[i] = rbm.add(xv, vj)
a[i] = rbm.add(rbm.add(xa, rbm.scale(s, qdd[i])), cross_motion(v[i], vj))
iv = rbm.matvec(inertia, v[i])
f[i] = rbm.add(rbm.matvec(inertia, a[i]), cross_force(v[i], iv))
# Derivatives by the joints above i: carried over from the parent.
dv_q[i] = {} if p < 0 else _map(xs[i], dv_q[p]) # @line L3
da_q[i] = {} if p < 0 else _map(xs[i], da_q[p])
dv_qd[i] = {} if p < 0 else _map(xs[i], dv_qd[p])
da_qd[i] = {} if p < 0 else _map(xs[i], da_qd[p])
da_qdd[i] = {} if p < 0 else _map(xs[i], da_qdd[p])
# The new column i.
dv_q[i][i] = cross_motion(xv, s) # @line L4
da_q[i][i] = cross_motion(xa, s)
dv_qd[i][i] = list(s) # @line L5
da_qd[i][i] = cross_motion(v[i], s)
da_qdd[i][i] = list(s)
for k in dv_q[i]: # @line L6
da_q[i][k] = rbm.add(da_q[i][k], cross_motion(dv_q[i][k], vj))
da_qd[i][k] = rbm.add(da_qd[i][k], cross_motion(dv_qd[i][k], vj))
df_q[i], df_qd[i] = {}, {}
for dv, da, df in ((dv_q[i], da_q[i], df_q[i]), (dv_qd[i], da_qd[i], df_qd[i])): # @line L7
for k in dv:
df[k] = rbm.add(rbm.add(rbm.matvec(inertia, da[k]), cross_force(dv[k], iv)),
cross_force(v[i], rbm.matvec(inertia, dv[k])))
df_qdd[i] = {k: rbm.matvec(inertia, vec) for k, vec in da_qdd[i].items()}
tau = [0.0] * n
d_q, d_qd, d_qdd = rbm.zeros(n, n), rbm.zeros(n, n), rbm.zeros(n, n)
for i in range(n - 1, -1, -1): # @line L8
s = model.screw[i]
tau[i] = rbm.dot(s, f[i])
for out, df in ((d_q, df_q[i]), (d_qd, df_qd[i]), (d_qdd, df_qdd[i])): # @line L9
for k, vec in df.items():
out[i][k] = rbm.dot(s, vec)
p = model.parent[i]
if p >= 0: # @line L10
xt = rbm.transpose(xs[i])
for src, dst in ((df_q[i], df_q[p]), (df_qd[i], df_qd[p]), (df_qdd[i], df_qdd[p])): # @line L11
for k, vec in src.items():
_add_into(dst, k, rbm.matvec(xt, vec))
_add_into(df_q[p], i, rbm.matvec(xt, cross_force(s, f[i]))) # @line L12
f[p] = rbm.add(f[p], rbm.matvec(xt, f[i])) # @line L13
return tau, d_q, d_qd, d_qdd # @line L14
def forward_dynamics_derivatives(model, q, qd, tau, gravity=GRAVITY):
"""Return (qdd, dqdd/dq, dqdd/dqd, dqdd/dtau) for qdd = FD(q, qd, tau).
qdd solves M qdd = tau - C qd - g. Then dFD/du = -M^(-1) dID/du at
(q, qd, qdd) for u = q and u = qd, and dFD/dtau = M^(-1).
"""
n = model.n
bias, _, _, m = rnea_derivatives(model, q, qd, [0.0] * n, gravity)
qdd = rbm.solve(m, rbm.sub(tau, bias))
_, d_q, d_qd, _ = rnea_derivatives(model, q, qd, qdd, gravity)
m_inv = rbm.inv(m)
return qdd, rbm.scale(rbm.mul(m_inv, d_q), -1.0), rbm.scale(rbm.mul(m_inv, d_qd), -1.0), m_inv
test_rigid_body_dynamics_derivatives.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rigid-body-dynamics-derivatives/. The authors are listed in prov/M6C9BY.jsonl.
"""Tests of the analytical derivatives against central finite differences (h = 1e-6, tolerance 1e-6)."""
import math
import random
import pytest
import rbm
from rigid_body_dynamics_derivatives import (
GRAVITY,
Model,
forward_dynamics_derivatives,
rnea,
rnea_derivatives,
spatial_inertia,
)
Z_AXIS = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
G_PLANE = [0.0, -9.81, 0.0]
TOL = 1e-6
def planar_2r():
"""2R arm in the x-y plane, links of 1 m, point masses of 1 kg at the link ends."""
model = Model()
point = spatial_inertia(1.0, [1.0, 0.0, 0.0], rbm.zeros(3, 3))
model.add_body(-1, rbm.eye(4), Z_AXIS, point)
model.add_body(0, rbm.make_T(rbm.eye(3), [1.0, 0.0, 0.0]), Z_AXIS, point)
return model
def closed_form_2r(q, qd, qdd, g=9.81):
c1, c2, s2 = math.cos(q[0]), math.cos(q[1]), math.sin(q[1])
c12 = math.cos(q[0] + q[1])
t1 = (3 + 2 * c2) * qdd[0] + (1 + c2) * qdd[1] - s2 * (2 * qd[0] * qd[1] + qd[1] ** 2) + g * (2 * c1 + c12)
t2 = (1 + c2) * qdd[0] + qdd[1] + s2 * qd[0] ** 2 + g * c12
return [t1, t2]
def random_model(rng, n, parents=None):
model = Model()
for i in range(n):
parent = rng.randrange(-1, i) if parents is None else parents[i]
tree = rbm.se3_exp([rng.uniform(-0.6, 0.6) for _ in range(6)])
u = [rng.gauss(0.0, 1.0) for _ in range(3)]
u = rbm.scale(u, 1.0 / rbm.norm(u))
if rng.random() < 0.8:
point = [rng.uniform(-0.3, 0.3) for _ in range(3)]
screw = u + [-x for x in rbm.cross(u, point)]
else:
screw = [0.0, 0.0, 0.0] + u
a = [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(3)]
ic = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(3), 0.05))
com = [rng.uniform(-0.3, 0.3) for _ in range(3)]
model.add_body(parent, tree, screw, spatial_inertia(rng.uniform(0.5, 2.0), com, ic))
return model
def maxdiff(a, b):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def numeric_id_jacobians(model, q, qd, qdd, g):
return (rbm.num_jacobian(lambda x: rnea(model, x, qd, qdd, g), q),
rbm.num_jacobian(lambda x: rnea(model, q, x, qdd, g), qd),
rbm.num_jacobian(lambda x: rnea(model, q, qd, x, g), qdd))
def test_2r_against_closed_form():
rng = random.Random(1)
model = planar_2r()
for _ in range(10):
q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
qd = [rng.uniform(-2, 2) for _ in range(2)]
qdd = [rng.uniform(-3, 3) for _ in range(2)]
tau, d_q, d_qd, m = rnea_derivatives(model, q, qd, qdd, G_PLANE)
assert max(abs(x - y) for x, y in zip(tau, closed_form_2r(q, qd, qdd))) < 1e-9
assert maxdiff(d_q, rbm.num_jacobian(lambda x: closed_form_2r(x, qd, qdd), q)) < TOL
assert maxdiff(d_qd, rbm.num_jacobian(lambda x: closed_form_2r(q, x, qdd), qd)) < TOL
c2 = math.cos(q[1])
assert maxdiff(m, [[3 + 2 * c2, 1 + c2], [1 + c2, 1.0]]) < 1e-12
def test_2r_hand_value():
"""At q = (0, pi/2), qd = (1, 1), qdd = 0 and no gravity: dtau/dqd = [[-2, -4], [2, 0]], dtau/dq = 0."""
_, d_q, d_qd, _ = rnea_derivatives(planar_2r(), [0.0, math.pi / 2], [1.0, 1.0], [0.0, 0.0], [0.0] * 3)
assert maxdiff(d_qd, [[-2.0, -4.0], [2.0, 0.0]]) < 1e-12
assert maxdiff(d_q, [[0.0, 0.0], [0.0, 0.0]]) < 1e-12
def test_inverse_dynamics_derivatives_on_random_trees():
rng = random.Random(2)
for n in (1, 5, 7):
model = random_model(rng, n)
q = [rng.uniform(-2, 2) for _ in range(n)]
qd = [rng.uniform(-1.5, 1.5) for _ in range(n)]
qdd = [rng.uniform(-3, 3) for _ in range(n)]
tau, d_q, d_qd, m = rnea_derivatives(model, q, qd, qdd)
n_q, n_qd, n_qdd = numeric_id_jacobians(model, q, qd, qdd, GRAVITY)
assert maxdiff(d_q, n_q) < TOL
assert maxdiff(d_qd, n_qd) < TOL
assert maxdiff(m, n_qdd) < TOL
assert maxdiff(m, rbm.transpose(m)) < 1e-12
def test_forward_dynamics_derivatives():
rng = random.Random(3)
model = random_model(rng, 6, [-1, 0, 1, 1, 3, -1])
def fd(q, qd, tau):
n = model.n
bias = rnea(model, q, qd, [0.0] * n)
m = rnea_derivatives(model, q, qd, [0.0] * n)[3]
return rbm.solve(m, rbm.sub(tau, bias))
q = [rng.uniform(-2, 2) for _ in range(6)]
qd = [rng.uniform(-1, 1) for _ in range(6)]
tau = [rng.uniform(-3, 3) for _ in range(6)]
qdd, d_q, d_qd, d_tau = forward_dynamics_derivatives(model, q, qd, tau)
assert max(abs(x - y) for x, y in zip(rnea(model, q, qd, qdd), tau)) < 1e-9
assert maxdiff(d_q, rbm.num_jacobian(lambda x: fd(x, qd, tau), q)) < TOL
assert maxdiff(d_qd, rbm.num_jacobian(lambda x: fd(q, x, tau), qd)) < TOL
assert maxdiff(d_tau, rbm.num_jacobian(lambda x: fd(q, qd, x), tau)) < TOL
def test_sparsity_follows_the_tree():
"""dtau_i/dq_k and dtau_i/dqd_k are 0 unless i and k lie on one path to the root."""
rng = random.Random(4)
parents = [-1, 0, 1, 0, 3, -1]
model = random_model(rng, 6, parents)
_, d_q, d_qd, _ = rnea_derivatives(model, [rng.uniform(-2, 2) for _ in range(6)],
[rng.uniform(-1, 1) for _ in range(6)], [0.5] * 6)
def path(i):
out = set()
while i >= 0:
out.add(i)
i = parents[i]
return out
for i in range(6):
for k in range(6):
if not (i in path(k) or k in path(i)):
assert d_q[i][k] == 0.0 and d_qd[i][k] == 0.0
def test_bad_input():
with pytest.raises(ValueError):
rnea_derivatives(planar_2r(), [0.0], [0.0, 0.0], [0.0, 0.0])
History
Before 2018, robot software computed the derivatives of the dynamics by finite differences or by automatic differentiation of the RNEA, and the Euler-Lagrange form gave symbolic derivatives for small arms. Carpentier and Mansard (2018) differentiated the RNEA in closed form with spatial algebra, derived the forward dynamics derivatives from it, and released the method in the open-source library Pinocchio. Their measurements showed the analytical derivatives several times faster than finite differences, with the gap growing with the size of the robot.
References
- Justin Carpentier and Nicolas Mansard, Analytical derivatives of rigid body dynamics algorithms, Robotics, Science and Systems XIV, 2018, Sections II to V (spatial algebra, the derivatives of the recursive Newton-Euler algorithm, the derivatives of forward dynamics, and the benchmarks)
- Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 2 (spatial vector algebra, the cross products and the derivatives of spatial vectors) and Chapter 5 (inverse dynamics)
- J. Y. S. Luh, M. W. Walker and R. P. C. Paul, On-line computational scheme for mechanical manipulators, Journal of Dynamic Systems, Measurement, and Control 102(2), 1980, pages 69 to 76 (the recursion that is differentiated)
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 M6C9BY Edit this page History Report an error Markdown