Algorithmcore
Composite rigid body algorithm
Also called CRBA, Walker-Orin method.
Builds the joint-space inertia matrix from the inertias of the subtrees beyond each joint, in O(n d) time for a tree of depth d, which is O(n^2) for a serial chain.
- Time
- Θ(n d) worst
- Space
- Θ(n) 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
- Michael W. Walker, David E. Orin, 1982
The composite rigid body algorithm (CRBA) computes the joint-space inertia matrix of a robot that is a serial chain or a tree of rigid bodies. It uses one idea: when only joint accelerates, everything beyond joint moves as one rigid body, the composite body of that subtree. The algorithm sums the spatial inertias of each subtree from the tips inward, and then reads each entry of as a product of a composite inertia with two joint axes. Together with one call of the recursive Newton-Euler algorithm for the bias forces and a Cholesky factorization, it solves the forward dynamics problem. The articulated-body algorithm solves the same problem in without forming ; the CRBA costs more for long chains but is often faster for the small trees of real robots.
In plain words
Picture a robot arm with all its joints locked except one. If you push that one joint, the part of the arm beyond it swings as one stiff piece. How hard that piece resists the push depends on its total mass and how far the mass is from the joint. The algorithm finds this resistance for every joint. It starts at the tip, where the stiff piece is only the last link. Moving inward, each piece is the next link plus the piece that hangs on it, so the work done for one joint is reused for the next. The resistance felt at a joint when another joint moves is found from the same stiff pieces. The result is a table of numbers that tells how the motion of every joint couples to every other joint.
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 of body , maps motion vectors from to coordinates, and is the spatial inertia of body about the origin of . Spatial vectors have the angular part first, as in Featherstone (2008).
Input: the model and . Output: the symmetric matrix of the manipulator equation . Featherstone writes for this matrix; here and are the same.
For the forward dynamics problem, the CRBA is one step: compute the bias as , compute by the CRBA, and solve .
The algorithm
CRBA(model, q)- 1
for i ← 1 to n do X_i ← Ad(T_{λ(i),i}(q_i)^-1) ; I^c_i ← I_i ; H ← 0 - 2
for i ← n downto 1 do - 3
if λ(i) ≠ 0 then I^c_λ(i) ← I^c_λ(i) + X_i^T I^c_i X_i - 4
F ← I^c_i S_i ▷ the wrench to accelerate the subtree of i - 5
H_ii ← S_i^T F - 6
j ← i - 7
while λ(j) ≠ 0 do ▷ climb to the base - 8
F ← X_j^T F ; j ← λ(j) - 9
H_ij ← S_j^T F ; H_ji ← H_ij - 10
return H
is the composite inertia of the subtree of body , in the coordinates of . Line L3 moves it into the frame of the parent and adds it to the parent's composite inertia. Because every child has a larger index than its parent, the loop of line L2 completes before it uses it.
Line L4 has a physical meaning. If only joint accelerates, at unit rate, with no velocity and no gravity, the subtree of moves as one rigid body with the acceleration , and is the wrench that joint must transmit. Joint feels of it (line L5). Every joint between and the base must transmit the same wrench, moved into its own frame (line L8), and feels of it (line L9). So is the force at joint per unit acceleration of joint . Entries for pairs of joints on different branches are never written and stay 0.
Example
Take the planar arm with two revolute joints, links of 1 m, and point masses of 1 kg at the link ends. Frame is 1 m along link 1, both screw axes are , and each point mass is at in its own frame. Take .
- : . Line L4 gives : an angular momentum of 1 about the joint and a linear part of 1 N along of . Line L5 gives .
- Line L8 moves into : . Line L9 gives .
- Line L3 for also made , the inertia of both masses about joint 1. Its third column is : the two masses at and m have a moment of inertia kg m about the axis through joint 1.
- : line L4 gives and line L5 gives .
So , which is the closed form at .
For forward dynamics, take , rad/s, gravity m/s along in the plane, and N m. The RNEA gives the bias , and the Cholesky solve of gives rad/s to rounding, which is the motion that the RNEA example produced this from.
Correctness
With and no gravity, the RNEA gives , and it shows that collects the wrenches of the bodies in the subtree of , where sums the accelerations of the joints on the path from to the base. The coefficient of in is then a sum over the bodies that are beyond both and . If is on the path from to the base, this set is the subtree of , and the sum is , where is the product of the joint transforms from to . If and are on different branches, the set is empty and the entry is 0. Lines L4 to L9 compute the first case for every pair, and the climb of line L8 builds one joint at a time. The same sum shows , which is twice the kinetic energy, so is symmetric positive definite when every body has positive mass and inertia. The correctness proof of this page gives the details.
Proof: The composite rigid body algorithm returns the joint-space inertia matrixfull
We use the notation of the page and of the recursive Newton-Euler algorithm. Body has the parent . For an ancestor of (or ), is the product of the joint transforms on the path, from down to , with . Write for the set of and its ancestors and for the set of and its descendants (the subtree of ).
Lemma 1 (the matrix). is the matrix of the linear map of the inverse dynamics with and no gravity. Its entries are
Proof. Run the recursive Newton-Euler algorithm with and . All velocities are 0, so , and by induction . The body wrench is , and the backward pass adds the wrenches of the subtree, so and . The coefficient of in collects the bodies with and , that is .
Corollary 2 (three cases). Define the composite inertia .
- If , then and , so .
- If , then by the same argument .
- Otherwise and are not on one path to the base, is empty, and . This is branch-induced sparsity.
Lemma 3 (the recursion of line L3). .
Proof. is the disjoint union of and the sets of the children . For , .
Theorem. Line L10 returns .
Proof. Line L1 sets for all . The loop of line L2 visits . We claim that, when the loop reaches , the variable holds the composite inertia of Lemma 3. Each child of has , so line L3 has already added to , and by induction was complete at that time. No other line changes .
Line L4 sets , and line L5 sets , which is the first case of Corollary 2 with . The loop of lines L7 to L9 climbs the path to the base. We show that after line L8 has moved to its parent, . This holds before the first step with . A step replaces by and by , and , so . Line L9 then sets , which is the transpose of the scalar because is symmetric. So it is by the first case of Corollary 2, since is an ancestor of . Line L9 also stores it as , which is correct by the second case.
Every pair with one on the path of the other is written once in this way, and every other pair keeps its initial value 0, which is correct by the third case.
Kinetic energy and definiteness. With , Lemma 1 gives , which is twice the kinetic energy. If every is positive definite, the sum is 0 only when every . Then for every , so because . So is symmetric positive definite.
Cost. Line L3 costs a fixed number of products per body, and the climb from body costs one transform per ancestor. The total is , which is for a tree of depth and for a serial chain.
Complexity
In the real RAM, line L3 costs a fixed number of products per body, and the climb from body costs one transform and one dot product per ancestor of . The time is . For a tree of depth this is ; for a serial chain, and the time is ; for a robot with short branches, such as a legged robot with a floating base, it is much less. These counts do not include the factorization. The extra space is besides the output matrix. A dense output matrix also costs to set to zero; a sparse storage of only the nonzero entries avoids this.
The forward dynamics also needs the factorization. A dense Cholesky factorization costs , and the two triangular solves cost . Featherstone (2008, Chapter 6) shows that the factorization in the order keeps the zeros of branch-induced sparsity, and then costs . Exact operation counts of the CRBA and of its use for forward dynamics are in Featherstone (2008, Chapter 10).
Properties
- Exact. No approximation, only floating-point rounding.
- Symmetric by construction. Line L9 writes each pair once and copies it, so the output is exactly symmetric, also in floating point.
- Branch-induced sparsity. when joints and are on different branches. The zeros do not depend on .
- Positive definite. is symmetric positive definite when every body has positive mass and positive definite rotational inertia, as the proof shows.
- Independent of and . depends only on . One evaluation can serve several right sides, for example in an implicit integrator or for the operational space quantities.
- Kinetic energy. is the kinetic energy of the robot, a cheap check of an implementation.
Variants and improvements
- Column by column. The simplest way to build calls the RNEA times, with , no velocity and no gravity, to get column . This costs for any tree, with a larger constant than the CRBA, and it ignores the sparsity. The tests of this page use it as the reference.
- Sparse factorization. Featherstone (2008, Chapter 6) factors in an order that creates no fill-in, so the cost of the factorization and of the solves follows the shape of the tree.
- Centroidal momentum. The composite inertias also give the centroidal momentum matrix at almost no extra cost.
- Derivatives. The derivatives of rigid body dynamics give as as a side product.
- Floating base. With a free-floating base, the first block of is the composite inertia of the whole robot, ; see floating-base dynamics.
When to use it
Use the CRBA when you need itself: for the operational space formulation, for a quadratic program of a whole-body controller, to compute the kinetic energy, or for a forward dynamics with a few joints. For forward dynamics of a long serial chain, the articulated-body algorithm is faster; Featherstone (1987) reports that it becomes faster than the composite rigid body method for chains of about nine bodies or more. For robots with short branches, such as legged robots and humanoids, the CRBA with a sparse factorization is competitive.
Pitfalls
- Missing bias forces. Forward dynamics needs on the right side; the CRBA gives only the matrix.
- The order of the bodies. Line L3 must run for a child before its parent uses . With and a loop from down, this holds.
- The transform direction. Line L8 needs , the force transform from to . Using gives wrong off-diagonal entries but correct diagonal entries, so a test of the diagonal alone does not catch it.
- Cholesky on a matrix that is not positive definite. With massless bodies, such as the first five bodies of a floating base modelled by six joints, is still positive definite only if the masses beyond them make it so. Check the pivots.
- Dense storage for a tree. Storing and factoring as a dense matrix throws away the sparsity of a branched robot.
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/composite-rigid-body-algorithm/. The authors are listed in prov/7BWY71.jsonl.
"""Composite rigid body algorithm (CRBA) for the joint-space inertia matrix.
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.
crba(model, q) returns H(q). forward_dynamics solves H qdd = tau - C with
the bias C from one Newton-Euler pass with qdd = 0 and a Cholesky factor.
"""
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 crba(model, q):
"""Return the joint-space inertia matrix H(q), an n x n list of rows."""
n = model.n
if len(q) != n:
raise ValueError("q needs one entry per joint")
xs = [joint_transform(model, i, q[i]) for i in range(n)] # @line L1
ic = [[list(row) for row in model.inertia[i]] for i in range(n)]
h = rbm.zeros(n, n)
for i in range(n - 1, -1, -1): # @line L2
p = model.parent[i]
if p >= 0: # @line L3
ic[p] = rbm.add(ic[p], rbm.mul(rbm.transpose(xs[i]), rbm.mul(ic[i], xs[i])))
f = rbm.matvec(ic[i], model.screw[i]) # @line L4
h[i][i] = rbm.dot(model.screw[i], f) # @line L5
j = i # @line L6
while model.parent[j] >= 0: # @line L7
f = rbm.matvec(rbm.transpose(xs[j]), f) # @line L8
j = model.parent[j]
h[i][j] = h[j][i] = rbm.dot(f, model.screw[j]) # @line L9
return h # @line L10
def bias_forces(model, q, qd, gravity=GRAVITY):
"""Return C(q, qd) qd + g(q) by one Newton-Euler pass with qdd = 0."""
n = model.n
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
for i in range(n):
p = model.parent[i]
xs[i] = joint_transform(model, i, q[i])
vj = rbm.scale(model.screw[i], qd[i])
v[i] = rbm.add(rbm.matvec(xs[i], [0.0] * 6 if p < 0 else v[p]), vj)
a[i] = rbm.add(rbm.matvec(xs[i], a_base if p < 0 else a[p]), cross_motion(v[i], vj))
inertia = model.inertia[i]
f[i] = rbm.add(rbm.matvec(inertia, a[i]), cross_force(v[i], rbm.matvec(inertia, v[i])))
out = [0.0] * n
for i in range(n - 1, -1, -1):
out[i] = rbm.dot(model.screw[i], f[i])
if model.parent[i] >= 0:
f[model.parent[i]] = rbm.add(f[model.parent[i]], rbm.matvec(rbm.transpose(xs[i]), f[i]))
return out
def cholesky_solve(h, b):
"""Solve h x = b for a symmetric positive definite h with h = L L^T."""
low = rbm.cholesky(h)
n = len(b)
y = [0.0] * n
for i in range(n):
y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def forward_dynamics(model, q, qd, tau, gravity=GRAVITY):
"""Return qdd = H^(-1) (tau - C qd - g) with H from crba."""
rhs = rbm.sub(tau, bias_forces(model, q, qd, gravity))
return cholesky_solve(crba(model, q), rhs)
def kinetic_energy(model, q, qd):
"""Return (1/2) qd^T H(q) qd."""
return 0.5 * rbm.dot(qd, rbm.matvec(crba(model, q), qd))
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_composite_rigid_body_algorithm.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/composite-rigid-body-algorithm/. The authors are listed in prov/7BWY71.jsonl.
"""Tests of CRBA against the 2R closed form, RNEA columns and the kinetic energy."""
import math
import random
import pytest
import rbm
from composite_rigid_body_algorithm import (
GRAVITY,
Model,
cross_force,
cross_motion,
crba,
forward_dynamics,
joint_transform,
spatial_inertia,
)
Z_AXIS = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
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 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 rnea_ref(model, q, qd, qdd, gravity):
"""Plain recursive Newton-Euler inverse dynamics, used as the reference."""
n = model.n
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
for i in range(n):
p = model.parent[i]
s = model.screw[i]
xs[i] = joint_transform(model, i, q[i])
vj = rbm.scale(s, qd[i])
v[i] = rbm.add(rbm.matvec(xs[i], [0.0] * 6 if p < 0 else v[p]), vj)
a[i] = rbm.add(rbm.add(rbm.matvec(xs[i], a_base if p < 0 else a[p]), rbm.scale(s, qdd[i])),
cross_motion(v[i], vj))
f[i] = rbm.add(rbm.matvec(model.inertia[i], a[i]),
cross_force(v[i], rbm.matvec(model.inertia[i], v[i])))
tau = [0.0] * n
for i in range(n - 1, -1, -1):
tau[i] = rbm.dot(model.screw[i], f[i])
if model.parent[i] >= 0:
f[model.parent[i]] = rbm.add(f[model.parent[i]], rbm.matvec(rbm.transpose(xs[i]), f[i]))
return tau
def fk(model, q):
out = []
for i in range(model.n):
local = rbm.mul(model.tree[i], rbm.se3_exp(rbm.scale(model.screw[i], q[i])))
p = model.parent[i]
out.append(local if p < 0 else rbm.mul(out[p], local))
return out
def kinetic_energy_brute(model, q, qd, h=1e-6):
"""Sum of (1/2) V_i^T I_i V_i, with V_i from finite differences of the poses."""
poses = fk(model, q)
plus = fk(model, rbm.add(q, rbm.scale(qd, h)))
minus = fk(model, rbm.sub(q, rbm.scale(qd, h)))
total = 0.0
for t, tp, tm, inertia in zip(poses, plus, minus, model.inertia):
tdot = rbm.scale(rbm.sub(tp, tm), 0.5 / h)
twist = rbm.vee6(rbm.mul(rbm.T_inv(t), tdot))
total += 0.5 * rbm.dot(twist, rbm.matvec(inertia, twist))
return total
def potential(model, q, g):
total = 0.0
for pose, inertia in zip(fk(model, q), model.inertia):
mass = inertia[5][5]
com = [inertia[2][4] / mass, inertia[0][5] / mass, inertia[1][3] / mass]
total -= mass * rbm.dot(g, rbm.T_apply(pose, com))
return total
def maxdiff(a, b):
return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def test_2r_closed_form():
rng = random.Random(1)
model = planar_2r()
for _ in range(30):
q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
c2 = math.cos(q[1])
assert maxdiff(crba(model, q), [[3 + 2 * c2, 1 + c2], [1 + c2, 1.0]]) < 1e-12
def test_2r_forward_dynamics_check_value():
qdd = forward_dynamics(planar_2r(), [0.0, math.pi / 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0])
assert abs(qdd[0] - 2.0) < 1e-12 and abs(qdd[1] + 3.0) < 1e-12
def test_columns_against_rnea():
rng = random.Random(2)
zero3 = [0.0, 0.0, 0.0]
for n in (5, 6, 7):
model = random_model(rng, n)
q = [rng.uniform(-2, 2) for _ in range(n)]
h = crba(model, q)
zero = [0.0] * n
for k in range(n):
e = [1.0 if j == k else 0.0 for j in range(n)]
col = rnea_ref(model, q, zero, e, zero3)
assert max(abs(h[r][k] - col[r]) for r in range(n)) < 1e-12
def test_symmetric_positive_definite_and_kinetic_energy():
rng = random.Random(3)
for n in (5, 7):
model = random_model(rng, n)
q = [rng.uniform(-2, 2) for _ in range(n)]
qd = [rng.uniform(-1, 1) for _ in range(n)]
h = crba(model, q)
assert maxdiff(h, rbm.transpose(h)) == 0.0
rbm.cholesky(h)
ke = 0.5 * rbm.dot(qd, rbm.matvec(h, qd))
assert abs(ke - kinetic_energy_brute(model, q, qd)) < 1e-8
def test_branch_induced_sparsity():
rng = random.Random(4)
parents = [-1, 0, 1, 0, 3, -1]
model = random_model(rng, 6, parents)
h = crba(model, [rng.uniform(-2, 2) for _ in range(6)])
def path(i):
out = set()
while i >= 0:
out.add(i)
i = parents[i]
return out
for i in range(6):
for j in range(6):
related = i in path(j) or j in path(i)
assert (h[i][j] == 0.0) == (not related)
def test_forward_dynamics_inverts_rnea():
rng = random.Random(5)
model = random_model(rng, 6)
for _ in range(5):
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 = forward_dynamics(model, q, qd, tau)
assert max(abs(x - y) for x, y in zip(rnea_ref(model, q, qd, qdd, GRAVITY), tau)) < 1e-9
def test_energy_is_constant_without_torque():
"""RK4 with dt = 5e-3 for 120 steps; tau = 0 and no friction. The drift must stay below 1e-6 J."""
rng = random.Random(6)
model = random_model(rng, 3, [-1, 0, 1])
q = [0.3, -0.5, 0.8]
qd = [0.5, -0.4, 0.2]
zero = [0.0] * 3
def deriv(x, v):
return v, forward_dynamics(model, x, v, zero)
def energy(x, v):
return 0.5 * rbm.dot(v, rbm.matvec(crba(model, x), v)) + potential(model, x, GRAVITY)
e0 = energy(q, qd)
dt = 5e-3
for _ in range(120):
k1 = deriv(q, qd)
k2 = deriv(rbm.add(q, rbm.scale(k1[0], dt / 2)), rbm.add(qd, rbm.scale(k1[1], dt / 2)))
k3 = deriv(rbm.add(q, rbm.scale(k2[0], dt / 2)), rbm.add(qd, rbm.scale(k2[1], dt / 2)))
k4 = deriv(rbm.add(q, rbm.scale(k3[0], dt)), rbm.add(qd, rbm.scale(k3[1], dt)))
q = [x + dt / 6 * (a + 2 * b + 2 * c + d) for x, a, b, c, d in zip(q, k1[0], k2[0], k3[0], k4[0])]
qd = [x + dt / 6 * (a + 2 * b + 2 * c + d) for x, a, b, c, d in zip(qd, k1[1], k2[1], k3[1], k4[1])]
assert max(abs(x - y) for x, y in zip(q, [0.3, -0.5, 0.8])) > 0.05
assert abs(energy(q, qd) - e0) < 1e-6
def test_bad_input():
with pytest.raises(ValueError):
crba(planar_2r(), [0.0])
History
Walker and Orin (1982) compared four methods for the dynamic simulation of robot arms. Their third method computes the inertia matrix from composite rigid bodies, and it was the fastest of the four in their comparison. Featherstone (1987, 2008) rewrote the method with spatial vectors as the composite-rigid-body algorithm, extended it to trees, and showed how branch-induced sparsity makes the factorization cheaper. The name Walker-Orin method refers to the 1982 paper.
References
- Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 6 (forward dynamics by inertia matrix methods): Section 6.2 (the composite-rigid-body algorithm) and Section 6.4 (branch-induced sparsity); Chapter 10 (accuracy and efficiency) for the operation counts
- M. W. Walker and D. E. Orin, Efficient dynamic computer simulation of robotic mechanisms, Journal of Dynamic Systems, Measurement, and Control 104(3), 1982, pages 205 to 211 (method 3)
- Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 3, Dynamics, by Roy Featherstone and David E. Orin
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 8, Section 8.5 (forward dynamics of open chains)
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 7BWY71 Edit this page History Report an error Markdown