Algorithm Search⌘K

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
Properties
deterministicofflineiterative
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 qq, velocities q˙\dot q and accelerations q¨\ddot q, it returns the joint forces τ\tau 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 Θ(n)\Theta(n) for nn joints, for a serial chain and for a branched tree. The inverse dynamics page states the problem, the Euler-Lagrange form gives the same τ\tau by symbolic differentiation, and the articulated-body algorithm solves the reverse problem, forward dynamics, in the same Θ(n)\Theta(n) 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 nn rigid bodies on a fixed base, numbered so that the parent λ(i)\lambda(i) of body ii has λ(i)<i\lambda(i) < i, with λ(i)=0\lambda(i) = 0 for the base. A serial chain is the case λ(i)=i−1\lambda(i) = i - 1. Joint ii connects body λ(i)\lambda(i) to body ii and has one degree of freedom with the screw axis Si∈R6S_i \in \mathbb{R}^6, given in the coordinates of a frame {i}\{i\} fixed to body ii. The pose of {i}\{i\} in {λ(i)}\{\lambda(i)\} is Tλ(i),i(qi)=Titreee[Si]qiT_{\lambda(i),i}(q_i) = T^{\mathrm{tree}}_i e^{[S_i] q_i}, where TitreeT^{\mathrm{tree}}_i is the pose at qi=0q_i = 0 and e[S]qe^{[S]q} is the exponential map.

Spatial vectors follow Featherstone (2008) with the angular part first. A motion vector, such as a twist, is v=(ω,vO)v = (\omega, v_O), and a force vector, such as a wrench, is f=(nO,f)f = (n_O, f). Xi=Ad(Tλ(i),i−1)X_i = \mathrm{Ad}(T_{\lambda(i),i}^{-1}) is the 6×66 \times 6 adjoint matrix that maps motion vectors from {λ(i)}\{\lambda(i)\} coordinates to {i}\{i\} coordinates, and XiTX_i^T maps force vectors from {i}\{i\} to {λ(i)}\{\lambda(i)\}. The spatial cross products are

crm(v) m=(ω×mω, vO×mω+ω×mv),crf(v) f=(ω×n+vO×f, ω×f),\mathrm{crm}(v)\, m = (\omega \times m_\omega,\ v_O \times m_\omega + \omega \times m_v), \qquad \mathrm{crf}(v)\, f = (\omega \times n + v_O \times f,\ \omega \times f),

with crf(v)=−crm(v)T\mathrm{crf}(v) = -\mathrm{crm}(v)^T. Body ii has the spatial inertia IiI_i about the origin of {i}\{i\}. Gravity is the spatial acceleration ag=(0,g)a_g = (0, g) with g=(0,0,−9.81)g = (0, 0, -9.81) m/s2^2 in base coordinates, and fiextf^{\mathrm{ext}}_i is an optional wrench of the outside world on body ii, in {i}\{i\} coordinates.

Input: the model, q,q˙,q¨∈Rnq, \dot q, \ddot q \in \mathbb{R}^n, aga_g and fextf^{\mathrm{ext}}. Output: τ∈Rn\tau \in \mathbb{R}^n with

τ=M(q)q¨+C(q,q˙)q˙+g(q)−∑iJi(q)Tfiext,\tau = M(q)\ddot q + C(q, \dot q)\dot q + g(q) - \textstyle\sum_i J_i(q)^T f^{\mathrm{ext}}_i ,

the manipulator equation, where JiJ_i is the Jacobian of the twist of body ii in {i}\{i\} coordinates.

The algorithm

  1. RNEA(model, q, q̇, q̈, a_g, f_ext)
  2. 1a_0 ← -a_g ; v_0 ← 0 ▷ gravity as a base acceleration
  3. 2for i ← 1 to n do ▷ outward pass
  4. 3X_i ← Ad(T_{λ(i),i}(q_i)^-1)
  5. 4v_i ← X_i v_λ(i) + S_i q̇_i
  6. 5a_i ← X_i a_λ(i) + S_i q̈_i + crm(v_i) S_i q̇_i
  7. 6f_i ← I_i a_i + crf(v_i) I_i v_i - f_ext,i ▷ Newton-Euler for body i
  8. 7for i ← n downto 1 do ▷ inward pass
  9. 8τ_i ← S_i^T f_i
  10. 9if λ(i) ≠ 0 then f_λ(i) ← f_λ(i) + X_i^T f_i
  11. 10return τ

Line L4 adds the joint twist to the twist of the parent. Line L5 is its time derivative; the last term, crm(vi)Siq˙i\mathrm{crm}(v_i) S_i \dot q_i, is the velocity product term, which holds the Coriolis and centripetal accelerations. Line L6 is the Newton-Euler equation of body ii: the wrench needed to give it the acceleration aia_i. Line L1 is a standard trick: if the base accelerates upward at −g-g, every body feels the same apparent force as gravity, so no gravity term is needed in line L6. After line L1, the variables aia_i are the true accelerations minus the gravity field, not the true accelerations.

In the inward pass, fif_i starts as the wrench of body ii alone. Line L9 adds it to the parent, so when the loop reaches body ii, fif_i is the wrench that joint ii 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 zz, two links of 1 m, and a point mass of 1 kg at the end of each link, with no gravity. Frame {1}\{1\} is at joint 1 and frame {2}\{2\} is at joint 2, 1 m along link 1, so T2treeT^{\mathrm{tree}}_2 is a translation by (1,0,0)(1, 0, 0) and both screw axes are S=(0,0,1,0,0,0)S = (0, 0, 1, 0, 0, 0). Each point mass is at (1,0,0)(1, 0, 0) in its own frame. Take q=(0,π/2)q = (0, \pi/2), q˙=(1,1)\dot q = (1, 1) rad/s and q¨=0\ddot q = 0.

  • Lines L4 and L5 for body 1: v1=(0,0,1, 0,0,0)v_1 = (0, 0, 1,\ 0, 0, 0) and a1=0a_1 = 0, because S1S_1 is parallel to v1v_1.
  • Line L6 for body 1: I1v1=(0,0,1, 0,1,0)I_1 v_1 = (0, 0, 1,\ 0, 1, 0), and f1=crf(v1)I1v1=(0,0,0, −1,0,0)f_1 = \mathrm{crf}(v_1) I_1 v_1 = (0, 0, 0,\ -1, 0, 0). This is the centripetal force of 1 N that pulls the mass toward joint 1.
  • Line L4 for body 2: v2=(0,0,2, 1,0,0)v_2 = (0, 0, 2,\ 1, 0, 0). The angular velocity is the sum of the two joint rates, and (1,0,0)(1, 0, 0) is the velocity of the origin of {2}\{2\} in {2}\{2\} coordinates.
  • Line L5 for body 2: a2=crm(v2)S2q˙2=(0,0,0, 0,−1,0)a_2 = \mathrm{crm}(v_2) S_2 \dot q_2 = (0, 0, 0,\ 0, -1, 0).
  • Line L6 for body 2: f2=(0,0,1, −4,1,0)f_2 = (0, 0, 1,\ -4, 1, 0).
  • Lines L8 and L9 for body 2: τ2=S2Tf2=1\tau_2 = S_2^T f_2 = 1 N m, and X2Tf2=(0,0,−3, −1,−4,0)X_2^T f_2 = (0, 0, -3,\ -1, -4, 0) is added to f1f_1.
  • Line L8 for body 1: f1=(0,0,−3, −2,−4,0)f_1 = (0, 0, -3,\ -2, -4, 0), and τ1=−3\tau_1 = -3 N m.

So τ=(−3,1)\tau = (-3, 1) N m. The closed form of the Euler-Lagrange equations for this arm, τ1=(3+2c2)q¨1+(1+c2)q¨2−s2(2q˙1q˙2+q˙22)\tau_1 = (3 + 2c_2)\ddot q_1 + (1 + c_2)\ddot q_2 - s_2(2\dot q_1 \dot q_2 + \dot q_2^2) and τ2=(1+c2)q¨1+q¨2+s2q˙12\tau_2 = (1 + c_2)\ddot q_1 + \ddot q_2 + s_2 \dot q_1^2 without gravity, gives the same values at c2=0c_2 = 0 and s2=1s_2 = 1. With gravity g=9.81g = 9.81 m/s2^2 along −y-y in the plane of the arm, q=(0.3,0.7)q = (0.3, 0.7), q˙=(0.5,−1.2)\dot q = (0.5, -1.2) and q¨=(2,−1)\ddot q = (2, -1), the implementation and the closed form both give τ=(31.183981854,7.991104417)\tau = (31.183981854, 7.991104417) N m.

Correctness

The outward pass computes the true twist of every body. The twist of body ii is the twist of its parent, moved into the frame of ii, plus the twist Siq˙iS_i \dot q_i of the joint (line L4). The acceleration (line L5) is the time derivative of line L4, where the derivative of XiX_i 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 ii must supply the wrench of body ii and the wrenches that body ii 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 XiX_i, 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 ii has the parent λ(i)<i\lambda(i) < i, and λ(i)=0\lambda(i) = 0 means the fixed base. The pose of frame ii in frame λ(i)\lambda(i) is Tλ(i),i(qi)=Titreee[Si]qiT_{\lambda(i),i}(q_i) = T^{\mathrm{tree}}_i e^{[S_i] q_i}, where the screw axis SiS_i is given in the coordinates of frame ii. Xi=Ad(Tλ(i),i−1)X_i = \mathrm{Ad}(T_{\lambda(i),i}^{-1}) maps motion vectors from the coordinates of λ(i)\lambda(i) to the coordinates of ii, and XiTX_i^T maps force vectors from ii to λ(i)\lambda(i). Every vector of body ii is in the coordinates of frame ii. The operators crm\mathrm{crm} and crf\mathrm{crf} are the spatial cross products, with crf(v)=−crm(v)T\mathrm{crf}(v) = -\mathrm{crm}(v)^T and crm(a)b=−crm(b)a\mathrm{crm}(a) b = -\mathrm{crm}(b) a.

Lemma 1 (joint kinematics). Tλ(i),i−1ddtTλ(i),i=[Si]q˙iT_{\lambda(i),i}^{-1} \tfrac{d}{dt} T_{\lambda(i),i} = [S_i]\dot q_i, and ddtXi=−crm(Siq˙i)Xi\tfrac{d}{dt} X_i = -\mathrm{crm}(S_i \dot q_i) X_i.

Proof. Write T=TtreeET = T^{\mathrm{tree}} E with E=e[Si]qiE = e^{[S_i] q_i}. Then T˙=TtreeE[Si]q˙i\dot T = T^{\mathrm{tree}} E [S_i] \dot q_i, because [Si][S_i] commutes with EE, and so T−1T˙=[Si]q˙iT^{-1}\dot T = [S_i]\dot q_i. For the second claim, T(qi+h)−1=e−[Si]hT(qi)−1T(q_i + h)^{-1} = e^{-[S_i] h} T(q_i)^{-1}. Since Ad\mathrm{Ad} is a group morphism, Xi(qi+h)=Ad(e−[Si]h)Xi(qi)=(1−h crm(Si)+O(h2))Xi(qi)X_i(q_i + h) = \mathrm{Ad}(e^{-[S_i] h}) X_i(q_i) = (1 - h\, \mathrm{crm}(S_i) + O(h^2)) X_i(q_i), because crm(S)\mathrm{crm}(S) is the matrix adS\mathrm{ad}_S of the Lie bracket. Multiply by q˙i\dot q_i. □\square

Lemma 2 (velocities and accelerations). Let viv_i be the twist of body ii and aia_i its spatial acceleration, both in frame ii, and let the base have v0=0v_0 = 0 and a0=0a_0 = 0. Then vi=Xivλ(i)+Siq˙iv_i = X_i v_{\lambda(i)} + S_i \dot q_i and ai=Xiaλ(i)+Siq¨i+crm(vi)Siq˙ia_i = X_i a_{\lambda(i)} + S_i \ddot q_i + \mathrm{crm}(v_i) S_i \dot q_i. These are lines L4 and L5.

Proof. With T0,i=T0,λ(i)Tλ(i),iT_{0,i} = T_{0,\lambda(i)} T_{\lambda(i),i}, the body twist is [vi]=T0,i−1T˙0,i=Tλ(i),i−1[vλ(i)]Tλ(i),i+Tλ(i),i−1T˙λ(i),i[v_i] = T_{0,i}^{-1}\dot T_{0,i} = T_{\lambda(i),i}^{-1} [v_{\lambda(i)}] T_{\lambda(i),i} + T_{\lambda(i),i}^{-1}\dot T_{\lambda(i),i}. The first term is [Xivλ(i)][X_i v_{\lambda(i)}] by the definition of the adjoint map, and the second term is [Si]q˙i[S_i]\dot q_i 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 crm(vi)vi=0\mathrm{crm}(v_i) v_i = 0. So, by Lemma 1, ai=ddt(Xivλ(i))+Siq¨i=Xiaλ(i)−crm(Siq˙i)Xivλ(i)+Siq¨ia_i = \tfrac{d}{dt}(X_i v_{\lambda(i)}) + S_i \ddot q_i = X_i a_{\lambda(i)} - \mathrm{crm}(S_i \dot q_i) X_i v_{\lambda(i)} + S_i \ddot q_i. Now −crm(Siq˙i)Xivλ(i)=crm(Xivλ(i))Siq˙i=crm(vi−Siq˙i)Siq˙i=crm(vi)Siq˙i-\mathrm{crm}(S_i\dot q_i) X_i v_{\lambda(i)} = \mathrm{crm}(X_i v_{\lambda(i)}) S_i \dot q_i = \mathrm{crm}(v_i - S_i\dot q_i) S_i \dot q_i = \mathrm{crm}(v_i) S_i \dot q_i, since crm(Si)Si=0\mathrm{crm}(S_i)S_i = 0. □\square

Lemma 3 (gravity). Start the recursion with a0=−aga_0 = -a_g, where ag=(0,g)a_g = (0, g) is the spatial acceleration of gravity in base coordinates (line L1). Then line L5 gives ai−Xi,0 aga_i - X_{i,0}\,a_g in place of aia_i, where Xi,0X_{i,0} is the motion transform from the base to frame ii, and line L6 gives fiB=Iiai+crf(vi)Iivi−IiXi,0ag−fiextf^B_i = I_i a_i + \mathrm{crf}(v_i) I_i v_i - I_i X_{i,0} a_g - f^{\mathrm{ext}}_i.

Proof. Lines L4 and L5 are linear in a0a_0, and the term in a0a_0 reaches body ii as Xi,0a0X_{i,0} a_0. The spatial inertia IiI_i about the origin of frame ii, applied to the uniform field Xi,0agX_{i,0} a_g, gives the wrench of gravity on body ii: the force migm_i g at the center of mass. □\square

Lemma 4 (Newton-Euler equations). The net wrench on body ii, in frame ii, is Iiai+crf(vi)IiviI_i a_i + \mathrm{crf}(v_i) I_i v_i. This is the spatial form of the Newton-Euler equations (Featherstone 2008, Chapter 2).

Theorem. Assume ideal joints: the constraint wrench of joint ii does no work on the motion SiS_i. Let fif_i be the wrench that body λ(i)\lambda(i) applies to body ii through joint ii, and let τi=SiTfi\tau_i = S_i^T f_i be the joint force. Then line L10 returns these τi\tau_i, that is τ=M(q)q¨+C(q,q˙)q˙+g(q)−∑iJiTfiext\tau = M(q)\ddot q + C(q, \dot q)\dot q + g(q) - \sum_i J_i^T f^{\mathrm{ext}}_i.

Proof. The forward loop (lines L2 to L6) computes viv_i and aia_i for i=1,…,ni = 1, \ldots, n in order. Every parent has a smaller index, so vλ(i)v_{\lambda(i)} and aλ(i)a_{\lambda(i)} are known when line L4 needs them. By Lemmas 2 and 3, fiBf^B_i after line L6 is the net wrench on body ii 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 ii are fif_i from its parent and −XcTfc-X_c^T f_c from each child cc, by Newton's third law, with XcTX_c^T to change the coordinates. So fi−∑c: λ(c)=iXcTfc=fiBf_i - \sum_{c:\, \lambda(c) = i} X_c^T f_c = f^B_i, that is

fi=fiB+∑c: λ(c)=iXcTfc.f_i = f^B_i + \sum_{c:\, \lambda(c) = i} X_c^T f_c.

We show by backward induction on ii that, when the loop of line L7 reaches ii, the variable fif_i holds this value. Every child cc of ii has c>ic > i, so line L9 has added XcTfcX_c^T f_c for each child before the loop reaches ii, and by the induction hypothesis each fcf_c was complete at that time. Line L9 adds nothing else to fif_i.

For an ideal joint, fif_i is the sum of a constraint wrench ficf^c_i with SiTfic=0S_i^T f^c_i = 0 and the wrench of the actuator, and the joint force τi\tau_i is defined by the power of the actuator, τiq˙i=SiTfi q˙i\tau_i \dot q_i = S_i^T f_i\, \dot q_i. So line L8 returns the joint force. The map from q¨\ddot q to τ\tau is affine with the matrix M(q)M(q), the rest is C(q,q˙)q˙+g(q)C(q,\dot q)\dot q + g(q), and fextf^{\mathrm{ext}} enters through JiTJ_i^T, as in the manipulator equation. ■\blacksquare

Cost. Each of the nn steps of each loop does a fixed number of 6×66 \times 6 products, so the time is Θ(n)\Theta(n). The extra space is the nn transforms and the nn vectors viv_i, aia_i and fif_i, which is Θ(n)\Theta(n).

Complexity

In the real RAM, each step of each loop does a fixed number of products of 6×66 \times 6 matrices and 6-vectors, so the time is Θ(n)\Theta(n) for any tree with nn joints. The extra space is Θ(n)\Theta(n) for the transforms and the vectors viv_i, aia_i and fif_i. Featherstone (2008, Chapter 10) gives exact counts of multiplications and additions for several versions of the algorithm; a careful version does not form the 6×66 \times 6 matrices and uses the special structure of XiX_i and IiI_i.

Hollerbach (1980) compared the operation counts of the formulations of manipulator dynamics. The Lagrangian equations in the form of Uicker and Kahn need O(n4)O(n^4) operations, a recursive Lagrangian form that Hollerbach gives needs O(n)O(n), 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 qq and q˙\dot q, τ\tau is an affine function of q¨\ddot q. So $\mathrm{RNEA}(q, 0, e_j) $ with no gravity is column jj of M(q)M(q), and RNEA(q,q˙,0)\mathrm{RNEA}(q, \dot q, 0) is the bias C(q,q˙)q˙+g(q)C(q, \dot q)\dot q + g(q).
  • Linear in the inertial parameters. τ\tau 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 ii happens in its own frame {i}\{i\}, where SiS_i and IiI_i are constant. Other versions use base coordinates for every body; they give the same τ\tau.
  • No mass matrix. The algorithm never forms M(q)M(q), which is why it costs Θ(n)\Theta(n) and not Θ(n2)\Theta(n^2).

Variants and improvements

  • Base coordinates. All vectors can be kept in base coordinates. Then the inertias change with qq and must be moved at each step, but the joint axes come straight from the product of exponentials. Both versions give the same τ\tau 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 RNEA(q,q˙,0)\mathrm{RNEA}(q, \dot q, 0) gives Cq˙+gC\dot q + g in Θ(n)\Theta(n), which the composite rigid body algorithm uses for forward dynamics.
  • Multi-degree-of-freedom joints. A spherical joint has a 6×36 \times 3 matrix SiS_i, 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 ∂τ/∂q\partial\tau/\partial q and ∂τ/∂q˙\partial\tau/\partial\dot q 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 Cq˙+gC\dot q + g. If you need M(q)M(q) itself, use the composite rigid body algorithm; if you need q¨\ddot q from τ\tau, 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 λ(i)<i\lambda(i) < i. 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 a0=−aga_0 = -a_g, not +ag+a_g. With g=(0,0,−9.81)g = (0, 0, -9.81) m/s2^2, a0=(0,0,0, 0,0,9.81)a_0 = (0, 0, 0,\ 0, 0, 9.81): the base accelerates upward.
  • The variables aia_i. Because of the trick of line L1, the variables aia_i 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. aia_i is the derivative of the twist. The classical acceleration of the origin of {i}\{i\} is the linear part of aia_i plus ωi×vO,i\omega_i \times v_{O,i}. See spatial vector algebra.
  • External wrenches. fiextf^{\mathrm{ext}}_i must be in the coordinates of {i}\{i\} and taken about the origin of {i}\{i\}. 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.

rbm.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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)
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example