Algorithmcore
Recursive Newton-Euler algorithm
Also called RNEA, Luh-Walker-Paul algorithm.
Inverse dynamics in O(n) time by an outward pass of link velocities and accelerations and an inward pass of forces.
- 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
- J. Y. S. Luh, M. W. Walker, R. P. C. Paul, 1980
The recursive Newton-Euler algorithm (RNEA) solves the inverse dynamics problem of a robot made of rigid links: given the joint positions , velocities and accelerations , it returns the joint forces that produce this motion. It goes out from the base to the tips and computes the velocity and the acceleration of every link, and then it comes back from the tips to the base and adds up the forces that each joint must transmit. Both passes visit each link once, so the cost is for joints, for a serial chain and for a branched tree. The inverse dynamics page states the problem, the Euler-Lagrange form gives the same by symbolic differentiation, and the articulated-body algorithm solves the reverse problem, forward dynamics, in the same time. This page writes the algorithm with spatial vectors, as Featherstone does.
In plain words
Imagine a robot arm that must follow a planned motion. To know how hard each motor must push, start at the base and walk out along the arm. Each link moves like the link before it, plus the turn of its own joint, so you know how every link moves and how fast that motion changes. From that, each link tells you the push it needs to move that way. Now walk back from the tips. The last link gets its push only from its own joint. The link before it must push its own mass and also carry the push of every link that hangs on it. At each joint, the part of the push that turns the joint is the motor effort. Each link is visited twice, so a long arm costs a little more, never much more.
The problem
The robot is a tree of rigid bodies on a fixed base, numbered so that the parent of body has , with for the base. A serial chain is the case . Joint connects body to body and has one degree of freedom with the screw axis , given in the coordinates of a frame fixed to body . The pose of in is , where is the pose at and is the exponential map.
Spatial vectors follow Featherstone (2008) with the angular part first. A motion vector, such as a twist, is , and a force vector, such as a wrench, is . is the adjoint matrix that maps motion vectors from coordinates to coordinates, and maps force vectors from to . The spatial cross products are
with . Body has the spatial inertia about the origin of . Gravity is the spatial acceleration with m/s in base coordinates, and is an optional wrench of the outside world on body , in coordinates.
Input: the model, , and . Output: with
the manipulator equation, where is the Jacobian of the twist of body in coordinates.
The algorithm
RNEA(model, q, q̇, q̈, a_g, f_ext)- 1
a_0 ← -a_g ; v_0 ← 0 ▷ gravity as a base acceleration - 2
for i ← 1 to n do ▷ outward pass - 3
X_i ← Ad(T_{λ(i),i}(q_i)^-1) - 4
v_i ← X_i v_λ(i) + S_i q̇_i - 5
a_i ← X_i a_λ(i) + S_i q̈_i + crm(v_i) S_i q̇_i - 6
f_i ← I_i a_i + crf(v_i) I_i v_i - f_ext,i ▷ Newton-Euler for body i - 7
for i ← n downto 1 do ▷ inward pass - 8
τ_i ← S_i^T f_i - 9
if λ(i) ≠ 0 then f_λ(i) ← f_λ(i) + X_i^T f_i - 10
return τ
Line L4 adds the joint twist to the twist of the parent. Line L5 is its time derivative; the last term, , is the velocity product term, which holds the Coriolis and centripetal accelerations. Line L6 is the Newton-Euler equation of body : the wrench needed to give it the acceleration . Line L1 is a standard trick: if the base accelerates upward at , every body feels the same apparent force as gravity, so no gravity term is needed in line L6. After line L1, the variables are the true accelerations minus the gravity field, not the true accelerations.
In the inward pass, starts as the wrench of body alone. Line L9 adds it to the parent, so when the loop reaches body , is the wrench that joint must transmit to the whole subtree that hangs on it. Line L8 takes the component of this wrench along the joint axis: the joint torque for a revolute joint, the force for a prismatic joint. The other five components are carried by the bearings.
Example
Take a planar arm with two revolute joints about , two links of 1 m, and a point mass of 1 kg at the end of each link, with no gravity. Frame is at joint 1 and frame is at joint 2, 1 m along link 1, so is a translation by and both screw axes are . Each point mass is at in its own frame. Take , rad/s and .
- Lines L4 and L5 for body 1: and , because is parallel to .
- Line L6 for body 1: , and . This is the centripetal force of 1 N that pulls the mass toward joint 1.
- Line L4 for body 2: . The angular velocity is the sum of the two joint rates, and is the velocity of the origin of in coordinates.
- Line L5 for body 2: .
- Line L6 for body 2: .
- Lines L8 and L9 for body 2: N m, and is added to .
- Line L8 for body 1: , and N m.
So N m. The closed form of the Euler-Lagrange equations for this arm, and without gravity, gives the same values at and . With gravity m/s along in the plane of the arm, , and , the implementation and the closed form both give N m.
Correctness
The outward pass computes the true twist of every body. The twist of body is the twist of its parent, moved into the frame of , plus the twist of the joint (line L4). The acceleration (line L5) is the time derivative of line L4, where the derivative of gives the velocity product term. Line L6 is the Newton-Euler equation of one body. The inward pass is Newton's third law: the joint of body must supply the wrench of body and the wrenches that body passes to its children. Because every child has a larger index than its parent, the loop of line L7 finishes all children before their parent. The full proof, with the gravity trick and the lemma on the derivative of , is in the correctness proof of this page.
Proof: The recursive Newton-Euler algorithm returns the inverse dynamicsfull
We use the notation of the page. Body has the parent , and means the fixed base. The pose of frame in frame is , where the screw axis is given in the coordinates of frame . maps motion vectors from the coordinates of to the coordinates of , and maps force vectors from to . Every vector of body is in the coordinates of frame . The operators and are the spatial cross products, with and .
Lemma 1 (joint kinematics). , and .
Proof. Write with . Then , because commutes with , and so . For the second claim, . Since is a group morphism, , because is the matrix of the Lie bracket. Multiply by .
Lemma 2 (velocities and accelerations). Let be the twist of body and its spatial acceleration, both in frame , and let the base have and . Then and . These are lines L4 and L5.
Proof. With , the body twist is . The first term is by the definition of the adjoint map, and the second term is by Lemma 1. In body coordinates the components of the spatial acceleration are the time derivatives of the components of the twist, because the extra term of a moving frame is . So, by Lemma 1, . Now , since .
Lemma 3 (gravity). Start the recursion with , where is the spatial acceleration of gravity in base coordinates (line L1). Then line L5 gives in place of , where is the motion transform from the base to frame , and line L6 gives .
Proof. Lines L4 and L5 are linear in , and the term in reaches body as . The spatial inertia about the origin of frame , applied to the uniform field , gives the wrench of gravity on body : the force at the center of mass.
Lemma 4 (Newton-Euler equations). The net wrench on body , in frame , is . This is the spatial form of the Newton-Euler equations (Featherstone 2008, Chapter 2).
Theorem. Assume ideal joints: the constraint wrench of joint does no work on the motion . Let be the wrench that body applies to body through joint , and let be the joint force. Then line L10 returns these , that is .
Proof. The forward loop (lines L2 to L6) computes and for in order. Every parent has a smaller index, so and are known when line L4 needs them. By Lemmas 2 and 3, after line L6 is the net wrench on body minus the wrenches of gravity and of the outside world. These are the wrenches that the joints must supply.
The wrenches that the joints apply to body are from its parent and from each child , by Newton's third law, with to change the coordinates. So , that is
We show by backward induction on that, when the loop of line L7 reaches , the variable holds this value. Every child of has , so line L9 has added for each child before the loop reaches , and by the induction hypothesis each was complete at that time. Line L9 adds nothing else to .
For an ideal joint, is the sum of a constraint wrench with and the wrench of the actuator, and the joint force is defined by the power of the actuator, . So line L8 returns the joint force. The map from to is affine with the matrix , the rest is , and enters through , as in the manipulator equation.
Cost. Each of the steps of each loop does a fixed number of products, so the time is . The extra space is the transforms and the vectors , and , which is .
Complexity
In the real RAM, each step of each loop does a fixed number of products of matrices and 6-vectors, so the time is for any tree with joints. The extra space is for the transforms and the vectors , and . Featherstone (2008, Chapter 10) gives exact counts of multiplications and additions for several versions of the algorithm; a careful version does not form the matrices and uses the special structure of and .
Hollerbach (1980) compared the operation counts of the formulations of manipulator dynamics. The Lagrangian equations in the form of Uicker and Kahn need operations, a recursive Lagrangian form that Hollerbach gives needs , and the recursive Newton-Euler form needs fewer operations than both. Luh, Walker and Paul (1980) report about 4.5 ms for the Stanford arm on a PDP 11/45 computer; this is a measurement on that machine.
Properties
- Linear in the accelerations. For fixed and , is an affine function of . So $\mathrm{RNEA}(q, 0, e_j) $ with no gravity is column of , and is the bias .
- Linear in the inertial parameters. is linear in the ten parameters of each spatial inertia. This gives the regressor form of linearity in the dynamic parameters.
- Exact. The algorithm uses no approximation. The only errors are floating-point rounding.
- Coordinates. All the work of body happens in its own frame , where and are constant. Other versions use base coordinates for every body; they give the same .
- No mass matrix. The algorithm never forms , which is why it costs and not .
Variants and improvements
- Base coordinates. All vectors can be kept in base coordinates. Then the inertias change with and must be moved at each step, but the joint axes come straight from the product of exponentials. Both versions give the same and the same order of cost.
- Floating base. For a humanoid or a legged robot the base is a free body. The inverse dynamics then needs the base acceleration and contact forces as well; see floating-base dynamics.
- Bias forces only. The call gives in , which the composite rigid body algorithm uses for forward dynamics.
- Multi-degree-of-freedom joints. A spherical joint has a matrix , and lines L4, L5 and L8 use the matrix in place of the vector.
- Derivatives. Analytical derivatives of rigid body dynamics differentiate each line of the algorithm and give and for optimization and control.
- Closed loops. A mechanism with kinematic loops is cut into a spanning tree plus loop constraints, and the loop forces are found from the constraints. Featherstone (2008) treats closed loop systems in a chapter of their own.
When to use it
Use the RNEA wherever the joint forces of a known motion are needed: in computed torque control and other model-based controllers, in the feedforward of a planned trajectory, to identify the inertial parameters from measured torques, and to check a simulation. It is also the fastest way to get the bias forces . If you need itself, use the composite rigid body algorithm; if you need from , use the articulated-body algorithm. For a 2 or 3 joint arm, a closed form from the Euler-Lagrange equations is also fine.
Pitfalls
- The order of the bodies. The loops need . With another numbering the forward pass reads a parent that is not yet computed.
- Angular part first or last. Featherstone and Lynch and Park put the angular part first, but some texts and libraries put the linear part first. Mixing the two gives wrong forces without an error.
- The sign of gravity. Line L1 sets , not . With m/s, : the base accelerates upward.
- The variables . Because of the trick of line L1, the variables are not the true accelerations of the bodies. Do not use them as the output of a forward kinematics of accelerations.
- The spatial acceleration is not the classical one. is the derivative of the twist. The classical acceleration of the origin of is the linear part of plus . See spatial vector algebra.
- External wrenches. must be in the coordinates of and taken about the origin of . A force measured at a sensor needs a change of coordinates first.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.
Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.
The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""
import math
# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2
# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2
# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12
# ---------------------------------------------------------------- matrices
def zeros(n, m):
"""Return the n by m zero matrix."""
return [[0.0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix."""
return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(a, s):
"""Return s * a for a vector or a matrix a and a number s."""
if _is_matrix(a):
return [[s * x for x in row] for row in a]
return [s * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def mul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(p * q for p, q in zip(row, x)) for row in a]
def dot(x, y):
"""Return the dot product of two vectors."""
return sum(p * q for p, q in zip(x, y))
def norm(x):
"""Return the Euclidean norm of a vector."""
return math.sqrt(dot(x, x))
def cross(a, b):
"""Return the cross product a x b of two 3-vectors."""
return [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
def _max_abs(a):
return max((abs(x) for row in a for x in row), default=0.0)
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
a is a square matrix. b is a vector or a matrix with one column per
right-hand side; the result has the same shape as b. Raise ValueError
if a pivot is at most PIVOT_TOL times the largest entry of a.
"""
n = len(a)
vec = not _is_matrix(b)
rhs = [[x] for x in b] if vec else [list(row) for row in b]
m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
k = len(rhs[0]) if rhs else 0
tol = PIVOT_TOL * _max_abs(a)
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
raise ValueError("matrix is singular to working precision")
m[c], m[piv] = m[piv], m[c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
if f != 0.0:
row_r, row_c = m[r], m[c]
for j in range(c, n + k):
row_r[j] -= f * row_c[j]
x = [[0.0] * k for _ in range(n)]
for r in range(n - 1, -1, -1):
for j in range(k):
s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
x[r][j] = s / m[r][r]
return [row[0] for row in x] if vec else x
def inv(a):
"""Return the inverse of the square matrix a (see solve for errors)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a by elimination."""
n = len(a)
m = [list(map(float, row)) for row in a]
d = 1.0
for c in range(n):
piv = max(range(c, n), key=lambda r: abs(m[r][c]))
if m[piv][c] == 0.0:
return 0.0
if piv != c:
m[c], m[piv] = m[piv], m[c]
d = -d
d *= m[c][c]
for r in range(c + 1, n):
f = m[r][c] / m[c][c]
for j in range(c, n):
m[r][j] -= f * m[c][j]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T.
a must be symmetric positive definite. Raise ValueError if a diagonal
entry of the factor is not positive.
"""
n = len(a)
low = zeros(n, n)
for i in range(n):
for j in range(i + 1):
s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
if i == j:
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[i][i] = math.sqrt(s)
else:
low[i][j] = s / low[j][j]
return low
def pinv_right(j):
"""Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
jt = transpose(j)
return mul(jt, inv(mul(j, jt)))
# ---------------------------------------------------------------- hat and vee
def hat3(w):
"""Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
return [
[0.0, -w[2], w[1]],
[w[2], 0.0, -w[0]],
[-w[1], w[0], 0.0],
]
def vee3(m):
"""Return the 3-vector w of a skew-symmetric matrix m = [w]."""
return [m[2][1], m[0][2], m[1][0]]
def hat6(v):
"""Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
w = hat3(v[:3])
return [
[w[0][0], w[0][1], w[0][2], v[3]],
[w[1][0], w[1][1], w[1][2], v[4]],
[w[2][0], w[2][1], w[2][2], v[5]],
[0.0, 0.0, 0.0, 0.0],
]
def vee6(m):
"""Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]
# ---------------------------------------------------------------- rotations
def rot_x(a):
"""Return the rotation by a radians about the x axis."""
c, s = math.cos(a), math.sin(a)
return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
def rot_y(a):
"""Return the rotation by a radians about the y axis."""
c, s = math.cos(a), math.sin(a)
return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
def rot_z(a):
"""Return the rotation by a radians about the z axis."""
c, s = math.cos(a), math.sin(a)
return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
def rpy(roll, pitch, yaw):
"""Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))
def so3_exp(w):
"""Return exp([w]) for exponential coordinates w = omega_hat * theta.
Rodrigues' formula in the form I + A [w] + B [w]^2 with
A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
"""
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
else:
a = math.sin(t) / t
b = (1.0 - math.cos(t)) / (t * t)
k = hat3(w)
k2 = mul(k, k)
return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]
def so3_log(r):
"""Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].
theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
above pi - NEAR_PI, the axis comes from the symmetric part
((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
from s. At theta = pi both signs are valid; the sign is then chosen so
that the largest component of the axis is positive.
"""
c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
c = max(-1.0, min(1.0, c))
s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
sn = norm(s)
t = math.atan2(sn, c)
if t < SERIES_THETA:
t2 = t * t
f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
return [f * x for x in s]
if t <= math.pi - NEAR_PI:
return [t / sn * x for x in s]
b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
# b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
# diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
k = max(range(3), key=lambda i: b[i][i])
col = [b[i][k] for i in range(3)]
axis = [x / norm(col) for x in col]
if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
axis = [-x for x in axis]
return [t * x for x in axis]
# ---------------------------------------------------------------- poses
def make_T(r, p):
"""Return the 4x4 pose [[r, p], [0, 1]]."""
return [
[r[0][0], r[0][1], r[0][2], p[0]],
[r[1][0], r[1][1], r[1][2], p[1]],
[r[2][0], r[2][1], r[2][2], p[2]],
[0.0, 0.0, 0.0, 1.0],
]
def _rp(t):
return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]
def T_inv(t):
"""Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
r, p = _rp(t)
rt = transpose(r)
return make_T(rt, [-x for x in matvec(rt, p)])
def T_apply(t, x):
"""Return R x + p, the image of the point x under the pose t."""
r, p = _rp(t)
return add(matvec(r, x), p)
def se3_exp(xi):
"""Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.
The rotation is so3_exp(w). The translation is G v with
G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
translation by v.
"""
w, v = xi[:3], xi[3:]
t = norm(w)
if t < SERIES_THETA:
t2 = t * t
b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
else:
b = (1.0 - math.cos(t)) / (t * t)
c = (t - math.sin(t)) / (t * t * t)
k = hat3(w)
k2 = mul(k, k)
g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
return make_T(so3_exp(w), matvec(g, v))
def se3_log(t):
"""Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].
w = so3_log(R) and v = G^(-1) p with
G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
"""
r, p = _rp(t)
w = so3_log(r)
th = norm(w)
if th < SERIES_THETA:
t2 = th * th
d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
else:
half = th / 2.0
d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
k = hat3(w)
k2 = mul(k, k)
gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
return w + matvec(gi, p)
def adjoint(t):
"""Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
r, p = _rp(t)
pr = mul(hat3(p), r)
out = zeros(6, 6)
for i in range(3):
for j in range(3):
out[i][j] = r[i][j]
out[i + 3][j + 3] = r[i][j]
out[i + 3][j] = pr[i][j]
return out
# ---------------------------------------------------------------- quaternions
def quat_mul(q, r):
"""Return the Hamilton product q r of quaternions (w, x, y, z)."""
a1, b1, c1, d1 = q
a2, b2, c2, d2 = r
return [
a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
]
def quat_conj(q):
"""Return the conjugate (w, -x, -y, -z)."""
return [q[0], -q[1], -q[2], -q[3]]
def quat_to_rot(q):
"""Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.
q need not be of unit length; the result is the rotation of q / |q|.
"""
w, x, y, z = q
n = w * w + x * x + y * y + z * z
s = 2.0 / n
return [
[1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
[s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
[s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
]
def quat_from_axis_angle(axis, angle):
"""Return (cos(angle / 2), sin(angle / 2) axis / |axis|).
A zero axis is allowed only with angle 0 (the identity); otherwise
raise ValueError.
"""
n = norm(axis)
if n == 0.0:
if angle == 0.0:
return [1.0, 0.0, 0.0, 0.0]
raise ValueError("zero axis with a nonzero angle")
s = math.sin(angle / 2.0) / n
return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]
# ---------------------------------------------------------------- derivatives
def num_jacobian(f, x, h=1e-6):
"""Return the Jacobian of f at x by central differences with step h.
f maps a list of n numbers to a list of m numbers; the result is m by n.
"""
cols = []
for i in range(len(x)):
xp = list(x)
xm = list(x)
xp[i] += h
xm[i] -= h
fp, fm = f(xp), f(xm)
cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
return transpose(cols)
# ---------------------------------------------------------------- self-test
def self_test():
"""Check the area check values; return True or raise AssertionError."""
r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
w = so3_log(want)
assert abs(norm(w) - 2.0943951) < 1e-7
assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
return True
recursive_newton_euler_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-newton-euler-algorithm/. The authors are listed in prov/8QXENF.jsonl.
"""Recursive Newton-Euler algorithm (RNEA) for 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.
parent is -1 or an earlier body. tree is the 4x4 pose of the new
frame in the parent frame at q = 0. screw is (omega, v) with
|omega| = 1, or omega = 0 and |v| = 1. inertia is 6x6.
"""
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 rnea(model, q, qd, qdd, gravity=GRAVITY, f_ext=None):
"""Return the joint forces tau with tau = M(q) qdd + C(q, qd) qd + g(q) - J^T f_ext.
gravity is the 3-vector of 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).
"""
n = model.n
if not len(q) == len(qd) == len(qdd) == n:
raise ValueError("q, qd and qdd need one entry per joint")
a_base = [0.0, 0.0, 0.0] + [-x for x in gravity] # @line L1
zero = [0.0] * 6
xs, f = [None] * n, [None] * n
v, a = [None] * n, [None] * n
for i in range(n): # @line L2
p = model.parent[i]
s = model.screw[i]
xs[i] = joint_transform(model, i, q[i]) # @line L3
v_p = zero if p < 0 else v[p]
a_p = a_base if p < 0 else a[p]
vj = rbm.scale(s, qd[i])
v[i] = rbm.add(rbm.matvec(xs[i], v_p), vj) # @line L4
a[i] = rbm.add(rbm.add(rbm.matvec(xs[i], a_p), rbm.scale(s, qdd[i])), cross_motion(v[i], vj)) # @line L5
inertia = model.inertia[i]
f[i] = rbm.add(rbm.matvec(inertia, a[i]), cross_force(v[i], rbm.matvec(inertia, v[i]))) # @line L6
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): # @line L7
tau[i] = rbm.dot(model.screw[i], f[i]) # @line L8
p = model.parent[i]
if p >= 0: # @line L9
f[p] = rbm.add(f[p], rbm.matvec(rbm.transpose(xs[i]), f[i]))
return tau # @line L10
test_recursive_newton_euler_algorithm.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/recursive-newton-euler-algorithm/. The authors are listed in prov/8QXENF.jsonl.
"""Tests of RNEA against the closed form of the 2R arm and an Euler-Lagrange reference."""
import math
import random
import pytest
import rbm
from recursive_newton_euler_algorithm import GRAVITY, Model, rnea, spatial_inertia
G_PLANE = [0.0, -9.81, 0.0]
Z_AXIS = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
def planar_2r():
"""2R arm in the x-y plane (y up), links of 1 m, point masses of 1 kg at the link ends."""
model = Model()
point = spatial_inertia(1.0, [1.0, 0.0, 0.0], rbm.zeros(3, 3))
model.add_body(-1, rbm.eye(4), Z_AXIS, point)
model.add_body(0, rbm.make_T(rbm.eye(3), [1.0, 0.0, 0.0]), Z_AXIS, point)
return model
def closed_form_2r(q, qd, qdd, g=9.81):
c1, c2, s2 = math.cos(q[0]), math.cos(q[1]), math.sin(q[1])
c12 = math.cos(q[0] + q[1])
t1 = (3 + 2 * c2) * qdd[0] + (1 + c2) * qdd[1] - s2 * (2 * qd[0] * qd[1] + qd[1] ** 2) + g * (2 * c1 + c12)
t2 = (1 + c2) * qdd[0] + qdd[1] + s2 * qd[0] ** 2 + g * c12
return [t1, t2]
def random_model(rng, n):
model = Model()
for i in range(n):
parent = rng.randrange(-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
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
# ------------------------------------------------- Euler-Lagrange reference
def fk(model, q):
"""World pose of every body 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 body_jacobians(model, q):
"""J_i with V_i = J_i qd, the body twist of body i in its own frame."""
poses = fk(model, q)
jac = []
for i in range(model.n):
cols = [[0.0] * 6 for _ in range(model.n)]
k = i
inv_i = rbm.T_inv(poses[i])
while k >= 0:
cols[k] = rbm.matvec(rbm.adjoint(rbm.mul(inv_i, poses[k])), model.screw[k])
k = model.parent[k]
jac.append(rbm.transpose(cols))
return jac
def mass_matrix_ref(model, q):
m = rbm.zeros(model.n, model.n)
for j, inertia in zip(body_jacobians(model, q), model.inertia):
m = rbm.add(m, rbm.mul(rbm.transpose(j), rbm.mul(inertia, j)))
return m
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 tau_ref(model, q, qd, qdd, g, f_ext=None, h=1e-6):
"""M qdd + (dM/dt) qd - (1/2) d(qd^T M qd)/dq + dV/dq - sum J_i^T f_i."""
n = model.n
m = mass_matrix_ref(model, q)
m_dot = rbm.scale(rbm.sub(mass_matrix_ref(model, rbm.add(q, rbm.scale(qd, h))),
mass_matrix_ref(model, rbm.sub(q, rbm.scale(qd, h)))), 0.5 / h)
out = rbm.add(rbm.matvec(m, qdd), rbm.matvec(m_dot, qd))
for k in range(n):
qp, qm = list(q), list(q)
qp[k] += h
qm[k] -= h
ke_p = rbm.dot(qd, rbm.matvec(mass_matrix_ref(model, qp), qd))
ke_m = rbm.dot(qd, rbm.matvec(mass_matrix_ref(model, qm), qd))
out[k] += -0.25 * (ke_p - ke_m) / h + (potential(model, qp, g) - potential(model, qm, g)) / (2 * h)
if f_ext is not None:
for j, f in zip(body_jacobians(model, q), f_ext):
out = rbm.sub(out, rbm.matvec(rbm.transpose(j), f))
return out
# ------------------------------------------------- tests
def test_helper_self_test():
assert rbm.self_test()
def test_2r_check_values():
model = planar_2r()
tau = rnea(model, [0.3, 0.7], [0.5, -1.2], [2.0, -1.0], G_PLANE)
assert abs(tau[0] - 31.184) < 1e-3 and abs(tau[1] - 7.991) < 1e-3
tau = rnea(model, [0.0, 0.0], [0.0, 0.0], [0.0, 0.0], G_PLANE)
assert abs(tau[0] - 29.43) < 1e-12 and abs(tau[1] - 9.81) < 1e-12
tau = rnea(model, [0.0, math.pi / 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0])
assert abs(tau[0] + 3.0) < 1e-12 and abs(tau[1] - 1.0) < 1e-12
def test_2r_closed_form_random():
rng = random.Random(1)
model = planar_2r()
for _ in range(50):
q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
qd = [rng.uniform(-3, 3) for _ in range(2)]
qdd = [rng.uniform(-5, 5) for _ in range(2)]
got = rnea(model, q, qd, qdd, G_PLANE)
want = closed_form_2r(q, qd, qdd)
assert max(abs(x - y) for x, y in zip(got, want)) < 1e-9
def test_default_gravity_is_z_down():
model = Model()
model.add_body(-1, rbm.eye(4), [0.0, 0.0, 0.0, 0.0, 0.0, 1.0], spatial_inertia(2.0, [0.0] * 3, rbm.eye(3)))
assert abs(rnea(model, [0.4], [1.0], [0.0])[0] - 2.0 * 9.81) < 1e-12
assert abs(rnea(model, [0.4], [1.0], [1.5])[0] - 2.0 * (9.81 + 1.5)) < 1e-12
def test_random_trees_against_euler_lagrange():
rng = random.Random(2)
for n in (5, 6, 7):
model = random_model(rng, n)
q = [rng.uniform(-1.5, 1.5) for _ in range(n)]
qd = [rng.uniform(-1.0, 1.0) for _ in range(n)]
qdd = [rng.uniform(-2.0, 2.0) for _ in range(n)]
f_ext = [[rng.uniform(-1, 1) for _ in range(6)] if rng.random() < 0.5 else None for _ in range(n)]
got = rnea(model, q, qd, qdd, GRAVITY, f_ext)
want = tau_ref(model, q, qd, qdd, GRAVITY, [f or [0.0] * 6 for f in f_ext])
assert max(abs(x - y) for x, y in zip(got, want)) < 1e-6
def test_mass_matrix_from_rnea_is_symmetric_positive_definite():
rng = random.Random(3)
model = random_model(rng, 6)
q = [rng.uniform(-2, 2) for _ in range(6)]
zero = [0.0] * 6
g0 = rnea(model, q, zero, zero)
cols = []
for k in range(6):
e = [1.0 if j == k else 0.0 for j in range(6)]
cols.append(rbm.sub(rnea(model, q, zero, e), g0))
m = rbm.transpose(cols)
assert max(abs(m[i][j] - m[j][i]) for i in range(6) for j in range(6)) < 1e-12
rbm.cholesky(m)
ref = mass_matrix_ref(model, q)
assert max(abs(m[i][j] - ref[i][j]) for i in range(6) for j in range(6)) < 1e-12
def test_bad_input():
model = planar_2r()
with pytest.raises(ValueError):
rnea(model, [0.0], [0.0, 0.0], [0.0, 0.0])
with pytest.raises(ValueError):
model.add_body(5, rbm.eye(4), Z_AXIS, rbm.eye(6))
History
Luh, Walker and Paul (1980) gave the recursive Newton-Euler scheme in link coordinates and showed that it could run on-line for control, at a time when the Lagrangian equations were too slow. Hollerbach (1980) made the Lagrangian equations recursive and compared the costs of the formulations. Featherstone (1983, 1987) wrote the dynamics with spatial vectors, and his 2008 book gives the spatial form of the RNEA that this page uses. The name RNEA and the name Luh-Walker-Paul algorithm both refer to this recursion.
References
- Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 5 (inverse dynamics), Section 5.3 (the recursive Newton-Euler algorithm); Chapter 10 (accuracy and efficiency) for the operation counts
- J. Y. S. Luh, M. W. Walker and R. P. C. Paul, On-line computational scheme for mechanical manipulators, Journal of Dynamic Systems, Measurement, and Control 102(2), 1980, pages 69 to 76
- John M. Hollerbach, A recursive Lagrangian formulation of manipulator dynamics and a comparative study of dynamics formulation complexity, IEEE Transactions on Systems, Man, and Cybernetics 10(11), 1980, pages 730 to 736
- Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 8, Section 8.2 (dynamics of a single rigid body) and Section 8.3 (Newton-Euler inverse dynamics)
- Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 3, Dynamics, by Roy Featherstone and David E. Orin
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 8QXENF Edit this page History Report an error Markdown