Definitionadvanced
Centroidal momentum matrix
Also called CMM.
The matrix that maps joint and base velocities to the linear and angular momentum of the whole robot about its center of mass.
The centroidal momentum matrix (CMM) of a robot is the matrix that turns the velocities of all its joints, and of its base if the base is free, into the total momentum of the robot about its center of mass. The top three rows give the angular momentum about the center of mass and the bottom three rows give the linear momentum. Orin and Goswami (2008) named and studied the matrix for humanoid robots. It is the main tool of balance control and whole-body control of legged robots, because the rate of the centroidal momentum is set by the contact forces alone; see centroidal dynamics.
Definition
Take a robot of rigid bodies in a kinematic tree with one-degree-of-freedom joints, in the notation of spatial vector algebra with the angular part first. A floating base counts as six joints, three prismatic along the axes of the fixed frame and three revolute, with the first five bodies massless. Body has the spatial inertia in its frame , the pose and the twist in , and joint has the screw axis in . Let be the total mass and the center of mass. Let be the frame with its origin at and its axes parallel to , and let .
The centroidal momentum is the sum of the momenta of the bodies, moved to :
where is the angular momentum about the center of mass and is the linear momentum. Each is linear in , so is linear in . The centroidal momentum matrix is the matrix with
The columns. A unit rate of joint , with all other joints still, moves the subtree of as one rigid body with the twist in , and moves nothing else. So column is the momentum of that subtree about :
where is the composite inertia of the subtree of , as in the composite rigid body algorithm. This gives the matrix in time:
CENTROIDAL-MOMENTUM-MATRIX(model, q)C1 compute T_si for every body, and X_i ← Ad(T_{λ(i),i}^-1)C2 for i ← 1 to n do I^c_i ← I_iC3 for i ← n downto 1 do if λ(i) ≠ 0 then I^c_λ(i) ← I^c_λ(i) + X_i^T I^c_i X_iC4 m ← Σ_i m_i ; c ← (Σ_i m_i c_i) / m ; T_sG ← (1, c)C5 for j ← 1 to n doC6 A_G[:, j] ← Ad(T_sj^-1 T_sG)^T I^c_j S_jC7 return A_G, m, c
Properties.
- The linear rows. The bottom three rows are , the mass times the Jacobian of the center of mass, because the linear momentum of the robot is .
- The base columns. For a floating base, the columns of the three prismatic base joints are : moving the whole robot along an axis adds only linear momentum.
- The locked robot. If all joints but the base are still, the robot moves as one rigid body with some twist at , and , where is the inertia of the locked robot about . Orin and Goswami call the centroidal composite rigid body inertia.
- The rate. , and by the Newton-Euler equations for the whole robot this equals the sum of the external wrenches about , including gravity. This is the centroidal dynamics of the robot.
- Not integrable. The angular part is not the time derivative of any function of in general. So a robot can change its orientation with zero angular momentum, as a falling cat does.
- Relation to the inertia matrix. If the base is a free 6-dimensional joint with its velocity in the base frame , the first six rows of the joint-space inertia matrix give the momentum of the robot in . Moving that momentum to by gives for these velocity coordinates.
Examples and non-examples
The planar arm with two links. Take two revolute joints about at a fixed base, links of 1 m and point masses of 1 kg at the link ends. At , the masses are at and m, so kg and m. The nonzero rows of are
and the rows of , and are zero. As a check by hand, joint 1 moves the first mass with the velocity and the second with , so the linear momentum is , and the angular momentum about is . Joint 2 moves only the second mass, with the velocity , which gives and . At rad/s, .
Non-example: the momentum about a fixed point. The angular momentum about the base origin is not . At the same state it is kg m/s, which is also . Its rate contains the moment of gravity about , which is why the CMM uses the center of mass.
Non-example: the Jacobian of the center of mass. is only the bottom half of . It says nothing about the angular momentum, which matters for balance when the arms or the legs swing.
Non-example: the composite inertia. The inertia of the locked robot maps the twist of a rigid body to its momentum. It does not see the joint motions, so it gives only when the joints are still.
Related definitions
- Centroidal dynamics: the equation $\dot h_G = $ the sum of the external wrenches about , written with .
- Spatial inertia: the inertia of one body; sums them, moved to .
- Composite rigid body algorithm: computes the subtree inertias that give the columns.
- Joint-space inertia matrix: its base rows, moved to , are for a floating base.
- Geometric Jacobian: the bottom rows of are the mass times the Jacobian of the center of mass.
- Floating-base dynamics: the setting where the base columns of appear.
Code
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/centroidal-momentum-matrix/. The authors are listed in prov/M8T9ZN.jsonl.
"""Centroidal momentum matrix A_G(q) of a kinematic tree, with h_G = A_G qd.
Spatial vectors follow Featherstone, Rigid Body Dynamics Algorithms (2008),
with the angular part first: a motion vector is (omega, v) and a force or
momentum vector is (n, f). h_G = (k_G, l_G) holds the angular momentum
about the center of mass G and the linear momentum, both in the axes of
the base frame {s}. The frame G has its origin at the center of mass and
its axes parallel to {s}.
The tree has bodies 0 .. n-1. parent[i] < i is the parent body, or -1 for
the 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). A floating
base is modelled as a chain of six joints (three prismatic, three
revolute) whose first five bodies have no mass.
Column j of A_G is Ad(T_jG)^T I^c_j S_j, where I^c_j is the composite
inertia of the subtree of body j and T_jG is the pose of G in frame j.
"""
import rbm
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 mass_and_com(inertia):
"""Return (m, c) of a 6x6 spatial inertia."""
m = inertia[5][5]
if m <= 0.0:
return 0.0, [0.0, 0.0, 0.0]
return m, [inertia[2][4] / m, inertia[0][5] / m, inertia[1][3] / m]
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 body_poses(model, q):
"""Return the pose T_si of every body frame in the base frame."""
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 centroidal_momentum_matrix(model, q):
"""Return (A_G, m, c): the 6 x n matrix, the total mass and the center of mass.
Raise ValueError if the total mass is not positive.
"""
n = model.n
if len(q) != n:
raise ValueError("q needs one entry per joint")
poses = body_poses(model, q) # @line C1
xs = []
for i in range(n):
p = model.parent[i]
rel = poses[i] if p < 0 else rbm.mul(rbm.T_inv(poses[p]), poses[i])
xs.append(rbm.adjoint(rbm.T_inv(rel)))
ic = [[list(row) for row in model.inertia[i]] for i in range(n)] # @line C2
for i in range(n - 1, -1, -1): # @line C3
p = model.parent[i]
if p >= 0:
ic[p] = rbm.add(ic[p], rbm.mul(rbm.transpose(xs[i]), rbm.mul(ic[i], xs[i])))
total, moment = 0.0, [0.0, 0.0, 0.0] # @line C4
for i in range(n):
m_i, c_i = mass_and_com(model.inertia[i])
total += m_i
moment = rbm.add(moment, rbm.scale(rbm.T_apply(poses[i], c_i), m_i))
if not total > 0.0:
raise ValueError("the total mass must be positive")
com = rbm.scale(moment, 1.0 / total)
pose_g = rbm.make_T(rbm.eye(3), com)
cols = []
for j in range(n): # @line C5
x_jg = rbm.adjoint(rbm.mul(rbm.T_inv(poses[j]), pose_g))
cols.append(rbm.matvec(rbm.transpose(x_jg), rbm.matvec(ic[j], model.screw[j]))) # @line C6
return rbm.transpose(cols), total, com # @line C7
def centroidal_momentum(model, q, qd):
"""Return h_G = A_G(q) qd = (k_G, l_G)."""
a_g, _, _ = centroidal_momentum_matrix(model, q)
return rbm.matvec(a_g, 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_centroidal_momentum_matrix.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/centroidal-momentum-matrix/. The authors are listed in prov/M8T9ZN.jsonl.
"""Tests of the centroidal momentum matrix against the sum of the link momenta and m J_com."""
import math
import random
import pytest
import rbm
from centroidal_momentum_matrix import (
Model,
body_poses,
centroidal_momentum,
centroidal_momentum_matrix,
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_body(rng):
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)]
return spatial_inertia(rng.uniform(0.5, 2.0), com, ic)
def random_model(rng, n, floating=False):
"""A random tree; with floating=True it hangs below a six-joint floating base."""
model = Model()
first = 0
if floating:
massless = rbm.zeros(6, 6)
axes = [[0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1],
[1, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0]]
for k, axis in enumerate(axes):
model.add_body(k - 1, rbm.eye(4), axis, random_body(rng) if k == 5 else massless)
first = 6
for i in range(first, first + n):
parent = rng.randrange(first - 1, 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
model.add_body(parent, tree, screw, random_body(rng))
return model
def com_of(model, q):
poses = body_poses(model, q)
total, moment = 0.0, [0.0, 0.0, 0.0]
for pose, inertia in zip(poses, model.inertia):
m = inertia[5][5]
if m > 0.0:
c = [inertia[2][4] / m, inertia[0][5] / m, inertia[1][3] / m]
total += m
moment = rbm.add(moment, rbm.scale(rbm.T_apply(pose, c), m))
return rbm.scale(moment, 1.0 / total)
def momentum_brute(model, q, qd, h=1e-6):
"""Sum over the bodies of the momentum about G, with twists from finite differences of the poses."""
poses = body_poses(model, q)
plus = body_poses(model, rbm.add(q, rbm.scale(qd, h)))
minus = body_poses(model, rbm.sub(q, rbm.scale(qd, h)))
pose_g = rbm.make_T(rbm.eye(3), com_of(model, q))
total = [0.0] * 6
for t, tp, tm, inertia in zip(poses, plus, minus, model.inertia):
twist = rbm.vee6(rbm.mul(rbm.T_inv(t), rbm.scale(rbm.sub(tp, tm), 0.5 / h)))
h_body = rbm.matvec(inertia, twist)
x_ig = rbm.adjoint(rbm.mul(rbm.T_inv(t), pose_g))
total = rbm.add(total, rbm.matvec(rbm.transpose(x_ig), h_body))
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_hand_values():
model = planar_2r()
q = [0.0, math.pi / 2]
a_g, m, com = centroidal_momentum_matrix(model, q)
assert m == 2.0 and max(abs(x - y) for x, y in zip(com, [1.0, 0.5, 0.0])) < 1e-12
planar = [a_g[2], a_g[3], a_g[4]]
assert maxdiff(planar, [[0.5, 0.5], [-1.0, -1.0], [2.0, 0.0]]) < 1e-12
assert maxdiff([a_g[0], a_g[1], a_g[5]], [[0.0, 0.0]] * 3) < 1e-12
h = centroidal_momentum(model, q, [1.0, 1.0])
assert max(abs(x - y) for x, y in zip(h, [0.0, 0.0, 1.0, -2.0, 2.0, 0.0])) < 1e-12
def test_against_sum_of_link_momenta():
rng = random.Random(1)
for n, floating in ((5, False), (7, False), (4, True)):
model = random_model(rng, n, floating)
q = [rng.uniform(-1.5, 1.5) for _ in range(model.n)]
qd = [rng.uniform(-1, 1) for _ in range(model.n)]
got = centroidal_momentum(model, q, qd)
want = momentum_brute(model, q, qd)
assert max(abs(x - y) for x, y in zip(got, want)) < 1e-6
def test_linear_rows_are_mass_times_com_jacobian():
rng = random.Random(2)
model = random_model(rng, 6, True)
q = [rng.uniform(-1.5, 1.5) for _ in range(model.n)]
a_g, m, _ = centroidal_momentum_matrix(model, q)
j_com = rbm.num_jacobian(lambda x: com_of(model, x), q)
assert maxdiff(a_g[3:], rbm.scale(j_com, m)) < 1e-6
def test_floating_base_columns():
"""The three prismatic base columns give (0, m e_k): moving the whole robot adds only linear momentum."""
rng = random.Random(3)
model = random_model(rng, 4, True)
q = [rng.uniform(-1.5, 1.5) for _ in range(model.n)]
a_g, m, _ = centroidal_momentum_matrix(model, q)
for k in range(3):
col = [row[k] for row in a_g]
want = [0.0] * 6
want[3 + k] = m
assert max(abs(x - y) for x, y in zip(col, want)) < 1e-12
def test_bad_input():
model = Model()
model.add_body(-1, rbm.eye(4), Z_AXIS, rbm.zeros(6, 6))
with pytest.raises(ValueError):
centroidal_momentum_matrix(model, [0.0])
with pytest.raises(ValueError):
centroidal_momentum_matrix(planar_2r(), [0.0])
References
- David E. Orin and Ambarish Goswami, Centroidal momentum matrix of a humanoid robot: structure and properties, IEEE/RSJ International Conference on Intelligent Robots and Systems (IROS), 2008, pages 653 to 659
- David E. Orin, Ambarish Goswami and Sung-Hee Lee, Centroidal dynamics of a humanoid robot, Autonomous Robots 35(2-3), 2013, pages 161 to 176
- Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 2 (spatial inertia and momentum) and Chapter 6 (composite-rigid-body inertias)
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M8T9ZN Edit this page History Report an error Markdown