Algorithmadvanced
Articulated-body algorithm
Also called Featherstone's algorithm, ABA.
Forward dynamics of a kinematic tree in O(n) time by three passes that compute articulated-body inertias and then accelerations.
- Time
- Θ(n) worst
- Space
- Θ(n) extra
- Where
- n = the number of joints, one degree of freedom each, in a serial chain or a tree
- Model
- Real RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Roy Featherstone, 1983
The articulated-body algorithm (ABA) solves the forward dynamics problem of a robot made of rigid bodies in a serial chain or a tree: given the joint positions , velocities and forces , it returns the joint accelerations . It never forms the joint-space inertia matrix. Instead, it computes for each body its articulated-body inertia, the inertia that the body seems to have when the joints beyond it are free to move, and with these it finds the accelerations one joint at a time. It makes three passes over the bodies, so the cost is for joints. The composite rigid body algorithm solves the same problem by forming and solving a linear system, which costs for a serial chain. The ABA inverts the recursive Newton-Euler algorithm, which solves the reverse problem in .
In plain words
When you push the first link of a robot arm whose joints are all free, the arm does not resist like one solid piece, because the outer links swing away instead of following. The algorithm finds how heavy each link feels with everything beyond it hanging free. It starts at the tips: the last link feels like itself. The link before it feels like itself plus the part of the last link that a free joint cannot let swing away. Going inward, each link gets the felt weight of its outer part. On the way back out, the first joint now knows exactly how hard its load resists, so its acceleration follows from its motor effort. With that acceleration known, the next joint is like a first joint, and so on to the tips.
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, and and are the spatial cross products for motion and force vectors (see spatial vector algebra). Gravity is with m/s in base coordinates, and is an optional wrench of the outside world on body in coordinates.
Input: the model, , , , and . Output: the vector with
the manipulator equation solved for . Equivalently, is the unique vector with .
The algorithm
ABA(model, q, q̇, τ, a_g, f_ext)- 1
for i ← 1 to n do ▷ pass 1: velocities - 2
X_i ← Ad(T_{λ(i),i}(q_i)^-1) - 3
v_i ← X_i v_λ(i) + S_i q̇_i ▷ v_0 = 0 - 4
c_i ← crm(v_i) S_i q̇_i - 5
I^A_i ← I_i ; p^A_i ← crf(v_i) I_i v_i - f_ext,i - 6
for i ← n downto 1 do ▷ pass 2: articulated inertias - 7
U_i ← I^A_i S_i ; D_i ← S_i^T U_i ; u_i ← τ_i - S_i^T p^A_i - 8
if λ(i) ≠ 0 then - 9
I^a ← I^A_i - U_i U_i^T / D_i - 10
p^a ← p^A_i + I^a c_i + U_i u_i / D_i - 11
I^A_λ(i) ← I^A_λ(i) + X_i^T I^a X_i ; p^A_λ(i) ← p^A_λ(i) + X_i^T p^a - 12
a_0 ← -a_g ▷ gravity as a base acceleration - 13
for i ← 1 to n do ▷ pass 3: accelerations - 14
a'_i ← X_i a_λ(i) + c_i - 15
q̈_i ← (u_i - U_i^T a'_i) / D_i - 16
a_i ← a'_i + S_i q̈_i - 17
return q̈
The second pass keeps the invariant : the wrench that joint transmits to body is an affine function of the acceleration of body , when the joints beyond it obey their own equations. is the articulated-body inertia and is the bias force: the wrench needed when , which holds the velocity product terms, the external forces and the joint forces of the subtree. Line L7 solves the joint equation for in terms of the parent acceleration. Lines L9 and L10 put that solution back into , which gives the inertia and the bias that the parent feels through joint . Line L11 adds them to the parent. The third pass uses line L15, the joint equation solved for , once the acceleration of the parent is known.
Example
Take the planar arm with two revolute joints about , links of 1 m, point masses of 1 kg at the link ends and no gravity. Frame is 1 m along link 1, both screw axes are , and each point mass is at in its own frame. Take , rad/s and .
Pass 1 gives , , and . The bias forces are , the centripetal force on mass 1, and .
Pass 2, body 2: , and . Line L9 removes from the part that joint 2 lets swing, and line L10 gives . After line L11,
Body 1: , and .
is the inertia that joint 1 feels with joint 2 free. With joint 2 locked, the whole arm is one rigid body and joint 1 feels kg m. With joint 2 free, it feels only kg m.
Pass 3: , so rad/s and . Then and rad/s.
So rad/s. As a check, with and the velocity terms N m from the RNEA example, .
Correctness
The second pass proves by backward induction. For a leaf, is the Newton-Euler wrench . For an inner body, each child adds , with by induction and . The joint equation fixes , and the result is affine in with the matrix , which is lines L9 to L11. Each is positive, because is the positive definite plus positive semidefinite terms. The forward pass then evaluates the joint equations in the order from the base, and it gives the unique solution of . The full proof is in the correctness proof of this page.
Proof: The articulated-body algorithm returns the forward dynamicsfull
We use the notation of the page and of the recursive Newton-Euler algorithm (RNEA). Body has the parent , and is the set of and its descendants. For a given , every velocity is fixed by the first pass. For any vector , let be the accelerations of the RNEA with , and let be the wrench that joint transmits to body , so that . We assume that every body has a positive definite spatial inertia .
Lemma 1 (the transmitted inertia is positive semidefinite). Let be symmetric positive definite, and . Then is symmetric positive semidefinite and .
Proof. For a vector and a number , . The minimum over is at and its value is . A minimum of a nonnegative function is nonnegative. Finally .
Lemma 2 (positive definite articulated inertias). After the backward pass has finished body , is symmetric positive definite, and so .
Proof. Line L5 sets , and line L11 adds for each child . Each child is finished first because , so by induction and Lemma 1 each added term is positive semidefinite. A positive definite matrix plus positive semidefinite matrices is positive definite.
Lemma 3 (the backward pass). Fix and a vector . Assume that for every with . Then
where and are the values after the backward pass has finished body .
Proof. By backward induction on . By the RNEA, . Take a child . The hypothesis holds for too, so by induction . By Lemma 2 of the RNEA proof, with , where is line L4. The joint equation of is then
with and , because is symmetric. by Lemma 2, so
These are the quantities of line L7. Put this back into :
with (line L9) and (line L10). So . Summing over the children,
Line L5 starts and at the first terms, and line L11 adds the sums. A leaf has no children, and the formula is line L5 alone.
Theorem. Line L17 returns the unique with , that is .
Proof. is positive definite (see the proof of the composite rigid body algorithm), so there is exactly one solution . For , every joint equation holds, so Lemma 3 applies to every body, and the argument in its proof gives, for every ,
The right side uses only for the ancestors of , through . The forward pass of lines L12 to L16 evaluates the same formulas in the order , starting from the same . By induction on , line L14 computes , line L15 computes , and line L16 computes .
Cost. Every line does a fixed number of operations on matrices and 6-vectors, and each pass visits each body once. The time is , and the extra space is for , , , , , , and .
Massless bodies. Lemma 2 needs a positive definite . With a body of zero mass, such as an inner body of a floating base modelled by six joints, can still be positive through the inertia of the subtree. The implementation checks and raises an error otherwise.
Complexity
In the real RAM, each step of each pass does a fixed number of operations on matrices and 6-vectors, so the time is for any tree, and the extra space is . This is optimal in order, because the output has entries.
The constant is larger than that of the RNEA, mainly because line L11 moves a matrix through a transform for each body. Featherstone (2008, Chapter 10) gives exact operation counts for the ABA, the CRBA and the RNEA. Featherstone (1987) reports that the articulated-body method becomes faster than the composite rigid body method with a Cholesky solve for chains of about nine or more bodies. The crossover depends on the implementation and on the shape of the tree: for robots with short branches, the CRBA with a sparse factorization is often as fast.
Properties
- No mass matrix. The ABA never forms or factors ; it solves implicitly by a recursive factorization along the tree.
- Exact. The only errors are floating-point rounding. Featherstone (2008, Chapter 10) discusses the accuracy and the efficiency of the dynamics algorithms.
- Linear in and . For fixed and , is affine in and in the external wrenches, with the matrix .
- Inverse of the RNEA. for every .
- Articulated inertia bounds. lies between the inertia of body alone and the composite inertia of the subtree of , in the order of positive semidefinite matrices; see articulated-body inertia.
- The transmitted inertia is singular. : a free joint transmits no inertia along its own axis.
Variants and improvements
- Floating base. With a free base, the base is body 1 with a six degree of freedom joint; the ABA handles it with matrices and , and is the articulated inertia of the whole robot. See floating-base dynamics.
- Multi-degree-of-freedom joints. For a joint with degrees of freedom, is , is a matrix and line L15 solves a small linear system.
- Hybrid dynamics. Some joints may have a given acceleration and others a given force; the passes then mix the RNEA and the ABA. Featherstone (2008, Chapter 9) treats this as hybrid dynamics, together with floating bases.
- Inverse of the mass matrix. With , no gravity and , the ABA returns column of . So calls give in without forming ; the second pass does not depend on except through and can be shared.
- Derivatives. The partial derivatives of by , and come from the derivatives of the RNEA and ; see analytical derivatives of rigid body dynamics.
When to use it
Use the ABA to simulate a robot: for long serial chains, for robots with many bodies, and in any loop that only needs . If you also need , for example for a controller, the composite rigid body algorithm gives it, and a Cholesky solve is then almost free. For two or three joints, both methods are fast, and the simpler one is fine.
Pitfalls
- Bodies without mass. A body with , and no subtree with mass, gives and a division by zero. A floating base modelled as six joints has five massless bodies; it works only because the last body of the base carries mass. The implementation raises an error if .
- The sign of gravity. Line L12 sets , as in the RNEA.
- Dropping in line L10. The velocity product term of the child must enter the bias force of the parent; without it, the result is right only at zero velocity.
- Using in place of . The parent receives , the inertia with the free joint removed, not . With , the result is the dynamics of the robot with the joint locked.
- Comparing against a dense solve. For checks, compare with , which tests the result without a second solver and its own rounding.
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/articulated-body-algorithm/. The authors are listed in prov/0W0KC6.jsonl.
"""Articulated-body algorithm (ABA) for the forward dynamics of a kinematic tree.
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.
"""
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 aba(model, q, qd, tau, gravity=GRAVITY, f_ext=None):
"""Return the joint accelerations qdd = M(q)^(-1) (tau - C(q, qd) qd - g(q) + J^T f_ext).
gravity is the acceleration of gravity in base coordinates. f_ext, if
given, is a list of n external force vectors, each in the coordinates
of its body (None for no force). Raise ValueError if an articulated
inertia D_i is not positive, which happens only for bodies without
mass or inertia.
"""
n = model.n
if not len(q) == len(qd) == len(tau) == n:
raise ValueError("q, qd and tau need one entry per joint")
zero = [0.0] * 6
xs, v, c = [None] * n, [None] * n, [None] * n
ia, pa = [None] * n, [None] * n
for i in range(n): # @line L1
p = model.parent[i]
s = model.screw[i]
xs[i] = joint_transform(model, i, q[i]) # @line L2
vj = rbm.scale(s, qd[i])
v[i] = rbm.add(rbm.matvec(xs[i], zero if p < 0 else v[p]), vj) # @line L3
c[i] = cross_motion(v[i], vj) # @line L4
ia[i] = [list(row) for row in model.inertia[i]] # @line L5
pa[i] = cross_force(v[i], rbm.matvec(model.inertia[i], v[i]))
if f_ext is not None and f_ext[i] is not None:
pa[i] = rbm.sub(pa[i], f_ext[i])
u_vec, d, u = [None] * n, [0.0] * n, [0.0] * n
for i in range(n - 1, -1, -1): # @line L6
s = model.screw[i]
u_vec[i] = rbm.matvec(ia[i], s) # @line L7
d[i] = rbm.dot(s, u_vec[i])
if not d[i] > 0.0:
raise ValueError("articulated inertia about joint %d is not positive" % i)
u[i] = tau[i] - rbm.dot(s, pa[i])
p = model.parent[i]
if p >= 0: # @line L8
ui = u_vec[i]
i_art = [[ia[i][r][k] - ui[r] * ui[k] / d[i] for k in range(6)] for r in range(6)] # @line L9
p_art = rbm.add(rbm.add(pa[i], rbm.matvec(i_art, c[i])), rbm.scale(ui, u[i] / d[i])) # @line L10
xt = rbm.transpose(xs[i])
ia[p] = rbm.add(ia[p], rbm.mul(xt, rbm.mul(i_art, xs[i]))) # @line L11
pa[p] = rbm.add(pa[p], rbm.matvec(xt, p_art))
a_base = [0.0, 0.0, 0.0] + [-x for x in gravity] # @line L12
a = [None] * n
qdd = [0.0] * n
for i in range(n): # @line L13
p = model.parent[i]
a_prime = rbm.add(rbm.matvec(xs[i], a_base if p < 0 else a[p]), c[i]) # @line L14
qdd[i] = (u[i] - rbm.dot(u_vec[i], a_prime)) / d[i] # @line L15
a[i] = rbm.add(a_prime, rbm.scale(model.screw[i], qdd[i])) # @line L16
return qdd # @line L17
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_articulated_body_algorithm.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/articulated-body-algorithm/. The authors are listed in prov/0W0KC6.jsonl.
"""Tests of ABA against RNEA, a dense mass matrix solve and energy conservation."""
import math
import random
import pytest
import rbm
from articulated_body_algorithm import (
GRAVITY,
Model,
aba,
cross_force,
cross_motion,
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, f_ext=None):
"""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])))
if f_ext is not None and f_ext[i] is not None:
f[i] = rbm.sub(f[i], f_ext[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 dense_forward_dynamics(model, q, qd, tau, gravity):
"""Build M from n + 1 RNEA calls and solve M qdd = tau - bias by elimination."""
n = model.n
zero = [0.0] * n
bias = rnea_ref(model, q, qd, zero, gravity)
cols = []
for k in range(n):
e = [1.0 if j == k else 0.0 for j in range(n)]
cols.append(rnea_ref(model, q, zero, e, [0.0, 0.0, 0.0]))
return rbm.solve(rbm.transpose(cols), rbm.sub(tau, bias))
def potential(model, q, g):
total = 0.0
pose = []
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]
pose.append(local if p < 0 else rbm.mul(pose[p], local))
inertia = model.inertia[i]
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[i], com))
return total
def test_2r_check_values():
model = planar_2r()
qdd = aba(model, [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
qdd = aba(model, [0.0, 0.0], [0.0, 0.0], [29.43, 9.81], [0.0, -9.81, 0.0])
assert max(abs(x) for x in qdd) < 1e-12
def test_inverts_rnea_on_random_trees():
rng = random.Random(1)
for n in (1, 5, 6, 7):
model = random_model(rng, n)
for _ in range(3):
q = [rng.uniform(-2, 2) for _ in range(n)]
qd = [rng.uniform(-1.5, 1.5) for _ in range(n)]
tau = [rng.uniform(-5, 5) for _ in range(n)]
f_ext = [[rng.uniform(-1, 1) for _ in range(6)] if rng.random() < 0.4 else None for _ in range(n)]
qdd = aba(model, q, qd, tau, GRAVITY, f_ext)
back = rnea_ref(model, q, qd, qdd, GRAVITY, f_ext)
assert max(abs(x - y) for x, y in zip(back, tau)) < 1e-9
qdd_ref = [rng.uniform(-3, 3) for _ in range(n)]
tau_ref = rnea_ref(model, q, qd, qdd_ref, GRAVITY, f_ext)
got = aba(model, q, qd, tau_ref, GRAVITY, f_ext)
assert max(abs(x - y) for x, y in zip(got, qdd_ref)) < 1e-9
def test_against_dense_solve():
rng = random.Random(2)
model = random_model(rng, 7)
q = [rng.uniform(-2, 2) for _ in range(7)]
qd = [rng.uniform(-1, 1) for _ in range(7)]
tau = [rng.uniform(-5, 5) for _ in range(7)]
got = aba(model, q, qd, tau)
want = dense_forward_dynamics(model, q, qd, tau, GRAVITY)
assert max(abs(x - y) for x, y in zip(got, want)) < 1e-9
def test_serial_chain_and_star():
rng = random.Random(3)
for parents in ([-1, 0, 1, 2, 3, 4], [-1, 0, 0, 0, 0, 0], [-1, -1, -1, 2, 2]):
model = random_model(rng, len(parents), parents)
n = model.n
q = [rng.uniform(-2, 2) for _ in range(n)]
qd = [rng.uniform(-1, 1) for _ in range(n)]
tau = [rng.uniform(-5, 5) for _ in range(n)]
qdd = aba(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, aba(model, x, v, zero)
def energy(x, v):
ke = 0.5 * rbm.dot(v, rnea_ref(model, x, [0.0] * 3, v, [0.0] * 3)) # (1/2) v^T M v
return ke + 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_massless_body_is_rejected():
model = Model()
model.add_body(-1, rbm.eye(4), Z_AXIS, rbm.zeros(6, 6))
with pytest.raises(ValueError):
aba(model, [0.0], [0.0], [1.0])
with pytest.raises(ValueError):
aba(planar_2r(), [0.0], [0.0, 0.0], [0.0, 0.0])
History
Featherstone (1983) introduced articulated-body inertias and the algorithm for the forward dynamics of a serial robot. His 1987 book extended it, compared it with the composite rigid body method of Walker and Orin, and gave the crossover in efficiency. His 2008 book gives the algorithm for kinematic trees in the spatial notation that this page uses, and the chapter by Featherstone and Orin in the Springer Handbook of Robotics gives a short form. The name Featherstone's algorithm refers to the 1983 paper.
References
- Roy Featherstone, The calculation of robot dynamics using articulated-body inertias, The International Journal of Robotics Research 2(1), 1983, pages 13 to 30
- Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 7 (forward dynamics by propagation methods): the articulated-body inertia, its calculation and the articulated-body algorithm; Chapter 10 (accuracy and efficiency) for the operation counts
- Roy Featherstone, Robot Dynamics Algorithms, Kluwer Academic Publishers, 1987, the chapter on the articulated-body method and its comparison with the composite-rigid-body method
- Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 3, Dynamics, by Roy Featherstone and David E. Orin
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 0W0KC6 Edit this page History Report an error Markdown