Algorithm Search⌘K

Algorithmadvanced

Articulated-body algorithm

Also called Featherstone's algorithm, ABA.

Forward dynamics of a kinematic tree in O(n) time by three passes that compute articulated-body inertias and then accelerations.

Time
Θ(n) worst
Space
Θ(n) extra
Where
n = the number of joints, one degree of freedom each, in a serial chain or a tree
Properties
deterministicofflineiterative
Origin
Roy Featherstone, 1983

The articulated-body algorithm (ABA) solves the forward dynamics problem of a robot made of rigid bodies in a serial chain or a tree: given the joint positions qq, velocities q˙\dot q and forces τ\tau, it returns the joint accelerations q¨\ddot q. It never forms the joint-space inertia matrix. Instead, it computes for each body its articulated-body inertia, the inertia that the body seems to have when the joints beyond it are free to move, and with these it finds the accelerations one joint at a time. It makes three passes over the bodies, so the cost is Θ(n)\Theta(n) for nn joints. The composite rigid body algorithm solves the same problem by forming M(q)M(q) and solving a linear system, which costs Θ(n3)\Theta(n^3) for a serial chain. The ABA inverts the recursive Newton-Euler algorithm, which solves the reverse problem in Θ(n)\Theta(n).

In plain words

When you push the first link of a robot arm whose joints are all free, the arm does not resist like one solid piece, because the outer links swing away instead of following. The algorithm finds how heavy each link feels with everything beyond it hanging free. It starts at the tips: the last link feels like itself. The link before it feels like itself plus the part of the last link that a free joint cannot let swing away. Going inward, each link gets the felt weight of its outer part. On the way back out, the first joint now knows exactly how hard its load resists, so its acceleration follows from its motor effort. With that acceleration known, the next joint is like a first joint, and so on to the tips.

The problem

The robot is a tree of nn rigid bodies with the notation of the recursive Newton-Euler algorithm: body ii has the parent λ(i)<i\lambda(i) < i (λ(i)=0\lambda(i) = 0 for the base), joint ii has the screw axis SiS_i in the frame {i}\{i\} of body ii, Xi=Ad(Tλ(i),i(qi)−1)X_i = \mathrm{Ad}(T_{\lambda(i),i}(q_i)^{-1}) maps motion vectors from {λ(i)}\{\lambda(i)\} to {i}\{i\} coordinates, and IiI_i is the spatial inertia of body ii about the origin of {i}\{i\}. Spatial vectors have the angular part first, and crm\mathrm{crm} and crf\mathrm{crf} are the spatial cross products for motion and force vectors (see spatial vector algebra). Gravity is 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, qq, q˙\dot q, τ∈Rn\tau \in \mathbb{R}^n, aga_g and fextf^{\mathrm{ext}}. Output: the vector q¨\ddot q with

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

the manipulator equation solved for q¨\ddot q. Equivalently, q¨\ddot q is the unique vector with RNEA(q,q˙,q¨)=τ\mathrm{RNEA}(q, \dot q, \ddot q) = \tau.

The algorithm

  1. ABA(model, q, q̇, τ, a_g, f_ext)
  2. 1for i ← 1 to n do ▷ pass 1: velocities
  3. 2X_i ← Ad(T_{λ(i),i}(q_i)^-1)
  4. 3v_i ← X_i v_λ(i) + S_i q̇_i ▷ v_0 = 0
  5. 4c_i ← crm(v_i) S_i q̇_i
  6. 5I^A_i ← I_i ; p^A_i ← crf(v_i) I_i v_i - f_ext,i
  7. 6for i ← n downto 1 do ▷ pass 2: articulated inertias
  8. 7U_i ← I^A_i S_i ; D_i ← S_i^T U_i ; u_i ← τ_i - S_i^T p^A_i
  9. 8if λ(i) ≠ 0 then
  10. 9I^a ← I^A_i - U_i U_i^T / D_i
  11. 10p^a ← p^A_i + I^a c_i + U_i u_i / D_i
  12. 11I^A_λ(i) ← I^A_λ(i) + X_i^T I^a X_i ; p^A_λ(i) ← p^A_λ(i) + X_i^T p^a
  13. 12a_0 ← -a_g ▷ gravity as a base acceleration
  14. 13for i ← 1 to n do ▷ pass 3: accelerations
  15. 14a'_i ← X_i a_λ(i) + c_i
  16. 15q̈_i ← (u_i - U_i^T a'_i) / D_i
  17. 16a_i ← a'_i + S_i q̈_i
  18. 17return q̈

The second pass keeps the invariant fi=IiAai+piAf_i = I^A_i a_i + p^A_i: the wrench that joint ii transmits to body ii is an affine function of the acceleration of body ii, when the joints beyond it obey their own equations. IiAI^A_i is the articulated-body inertia and piAp^A_i is the bias force: the wrench needed when ai=0a_i = 0, which holds the velocity product terms, the external forces and the joint forces of the subtree. Line L7 solves the joint equation τi=SiTfi\tau_i = S_i^T f_i for q¨i\ddot q_i in terms of the parent acceleration. Lines L9 and L10 put that solution back into fif_i, which gives the inertia IaI^a and the bias pap^a that the parent feels through joint ii. Line L11 adds them to the parent. The third pass uses line L15, the joint equation solved for q¨i\ddot q_i, once the acceleration of the parent is known.

Example

Take the planar arm with two revolute joints about zz, links of 1 m, point masses of 1 kg at the link ends and no gravity. Frame {2}\{2\} is 1 m along link 1, both screw axes are S=(0,0,1,0,0,0)S = (0, 0, 1, 0, 0, 0), and 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 τ=0\tau = 0.

Pass 1 gives v1=(0,0,1, 0,0,0)v_1 = (0, 0, 1,\ 0, 0, 0), v2=(0,0,2, 1,0,0)v_2 = (0, 0, 2,\ 1, 0, 0), c1=0c_1 = 0 and c2=(0,0,0, 0,−1,0)c_2 = (0, 0, 0,\ 0, -1, 0). The bias forces are p1A=(0,0,0, −1,0,0)p^A_1 = (0, 0, 0,\ -1, 0, 0), the centripetal force on mass 1, and p2A=(0,0,2, −4,2,0)p^A_2 = (0, 0, 2,\ -4, 2, 0).

Pass 2, body 2: U2=I2S2=(0,0,1, 0,1,0)U_2 = I_2 S_2 = (0, 0, 1,\ 0, 1, 0), D2=1D_2 = 1 and u2=0−S2Tp2A=−2u_2 = 0 - S_2^T p^A_2 = -2. Line L9 removes from I2I_2 the part that joint 2 lets swing, and line L10 gives pa=(0,0,0, −4,0,0)p^a = (0, 0, 0,\ -4, 0, 0). After line L11,

I1A=(1−10001−12000−20020200001000020201−20002),p1A=(0,0,−4, −1,−4,0).I^A_1 = \begin{pmatrix} 1 & -1 & 0 & 0 & 0 & 1 \\ -1 & 2 & 0 & 0 & 0 & -2 \\ 0 & 0 & 2 & 0 & 2 & 0 \\ 0 & 0 & 0 & 1 & 0 & 0 \\ 0 & 0 & 2 & 0 & 2 & 0 \\ 1 & -2 & 0 & 0 & 0 & 2 \end{pmatrix}, \qquad p^A_1 = (0, 0, -4,\ -1, -4, 0).

Body 1: U1=(0,0,2, 0,2,0)U_1 = (0, 0, 2,\ 0, 2, 0), D1=2D_1 = 2 and u1=4u_1 = 4.

D1=2D_1 = 2 is the inertia that joint 1 feels with joint 2 free. With joint 2 locked, the whole arm is one rigid body and joint 1 feels M11=3M_{11} = 3 kg m2^2. With joint 2 free, it feels only M11−M122/M22=3−1=2M_{11} - M_{12}^2/M_{22} = 3 - 1 = 2 kg m2^2.

Pass 3: a1′=0a'_1 = 0, so q¨1=4/2=2\ddot q_1 = 4/2 = 2 rad/s2^2 and a1=(0,0,2, 0,0,0)a_1 = (0, 0, 2,\ 0, 0, 0). Then a2′=X2a1+c2=(0,0,2, 2,−1,0)a'_2 = X_2 a_1 + c_2 = (0, 0, 2,\ 2, -1, 0) and q¨2=(−2−U2Ta2′)/1=(−2−1)/1=−3\ddot q_2 = (-2 - U_2^T a'_2)/1 = (-2 - 1)/1 = -3 rad/s2^2.

So q¨=(2,−3)\ddot q = (2, -3) rad/s2^2. As a check, with M=(3111)M = \begin{pmatrix} 3 & 1 \\ 1 & 1 \end{pmatrix} and the velocity terms Cq˙=(−3,1)C\dot q = (-3, 1) N m from the RNEA example, Mq¨=(3,−1)=−Cq˙M\ddot q = (3, -1) = -C\dot q.

Correctness

The second pass proves fi=IiAai+piAf_i = I^A_i a_i + p^A_i by backward induction. For a leaf, fif_i is the Newton-Euler wrench Iiai+crf(vi)Iivi−fiextI_i a_i + \mathrm{crf}(v_i) I_i v_i - f^{\mathrm{ext}}_i. For an inner body, each child cc adds XcTfcX_c^T f_c, with fc=IcAac+pcAf_c = I^A_c a_c + p^A_c by induction and ac=Xcai+cc+Scq¨ca_c = X_c a_i + c_c + S_c \ddot q_c. The joint equation τc=ScTfc\tau_c = S_c^T f_c fixes q¨c\ddot q_c, and the result is affine in aia_i with the matrix XcTIcaXcX_c^T I^a_c X_c, which is lines L9 to L11. Each DiD_i is positive, because IiAI^A_i is the positive definite IiI_i plus positive semidefinite terms. The forward pass then evaluates the joint equations in the order from the base, and it gives the unique solution of RNEA(q,q˙,q¨)=τ\mathrm{RNEA}(q, \dot q, \ddot q) = \tau. The full proof is in the correctness proof of this page.

Proof: The articulated-body algorithm returns the forward dynamicsfull

We use the notation of the page and of the recursive Newton-Euler algorithm (RNEA). Body ii has the parent λ(i)<i\lambda(i) < i, and ν(i)\nu(i) is the set of ii and its descendants. For a given (q,q˙)(q, \dot q), every velocity viv_i is fixed by the first pass. For any vector q¨\ddot q, let ai(q¨)a_i(\ddot q) be the accelerations of the RNEA with a0=−aga_0 = -a_g, and let fi(q¨)f_i(\ddot q) be the wrench that joint ii transmits to body ii, so that RNEA(q,q˙,q¨)i=SiTfi(q¨)\mathrm{RNEA}(q, \dot q, \ddot q)_i = S_i^T f_i(\ddot q). We assume that every body has a positive definite spatial inertia IiI_i.

Lemma 1 (the transmitted inertia is positive semidefinite). Let IAI^A be symmetric positive definite, U=IASU = I^A S and D=STU>0D = S^T U > 0. Then Ia=IA−UUT/DI^a = I^A - U U^T / D is symmetric positive semidefinite and IaS=0I^a S = 0.

Proof. For a vector xx and a number tt, (x+St)TIA(x+St)=xTIAx+2t UTx+t2D(x + S t)^T I^A (x + S t) = x^T I^A x + 2 t\, U^T x + t^2 D. The minimum over tt is at t=−UTx/Dt = -U^T x / D and its value is xTIAx−(UTx)2/D=xTIaxx^T I^A x - (U^T x)^2/D = x^T I^a x. A minimum of a nonnegative function is nonnegative. Finally IaS=U−UD/D=0I^a S = U - U D / D = 0. □\square

Lemma 2 (positive definite articulated inertias). After the backward pass has finished body ii, IiAI^A_i is symmetric positive definite, and so Di=SiTIiASi>0D_i = S_i^T I^A_i S_i > 0.

Proof. Line L5 sets IiA=IiI^A_i = I_i, and line L11 adds XcTIcaXcX_c^T I^a_c X_c for each child cc. Each child is finished first because c>ic > i, so by induction and Lemma 1 each added term is positive semidefinite. A positive definite matrix plus positive semidefinite matrices is positive definite. □\square

Lemma 3 (the backward pass). Fix ii and a vector q¨\ddot q. Assume that τk=SkTfk(q¨)\tau_k = S_k^T f_k(\ddot q) for every k∈ν(i)k \in \nu(i) with k≠ik \ne i. Then

fi(q¨)=IiA ai(q¨)+piA,f_i(\ddot q) = I^A_i\, a_i(\ddot q) + p^A_i ,

where IiAI^A_i and piAp^A_i are the values after the backward pass has finished body ii.

Proof. By backward induction on ii. By the RNEA, fi=Iiai+crf(vi)Iivi−fiext+∑c: λ(c)=iXcTfcf_i = I_i a_i + \mathrm{crf}(v_i) I_i v_i - f^{\mathrm{ext}}_i + \sum_{c:\, \lambda(c) = i} X_c^T f_c. Take a child cc. The hypothesis holds for cc too, so by induction fc=IcAac+pcAf_c = I^A_c a_c + p^A_c. By Lemma 2 of the RNEA proof, ac=ac′+Scq¨ca_c = a'_c + S_c \ddot q_c with ac′=Xcai+cca'_c = X_c a_i + c_c, where cc=crm(vc)Scq˙cc_c = \mathrm{crm}(v_c) S_c \dot q_c is line L4. The joint equation of cc is then

τc=ScT(IcA(ac′+Scq¨c)+pcA)=UcTac′+Dcq¨c+ScTpcA,\tau_c = S_c^T \big(I^A_c (a'_c + S_c \ddot q_c) + p^A_c\big) = U_c^T a'_c + D_c \ddot q_c + S_c^T p^A_c ,

with Uc=IcAScU_c = I^A_c S_c and Dc=ScTUcD_c = S_c^T U_c, because IcAI^A_c is symmetric. Dc>0D_c > 0 by Lemma 2, so

q¨c=(uc−UcTac′)/Dc,uc=τc−ScTpcA.\ddot q_c = (u_c - U_c^T a'_c)/D_c, \qquad u_c = \tau_c - S_c^T p^A_c .

These are the quantities of line L7. Put this q¨c\ddot q_c back into fcf_c:

fc=IcAac′+Uc(uc−UcTac′)/Dc+pcA=Icaac′+pcA+Ucuc/Dc=IcaXcai+pca,f_c = I^A_c a'_c + U_c (u_c - U_c^T a'_c)/D_c + p^A_c = I^a_c a'_c + p^A_c + U_c u_c / D_c = I^a_c X_c a_i + p^a_c ,

with Ica=IcA−UcUcT/DcI^a_c = I^A_c - U_c U_c^T / D_c (line L9) and pca=pcA+Icacc+Ucuc/Dcp^a_c = p^A_c + I^a_c c_c + U_c u_c / D_c (line L10). So XcTfc=XcTIcaXc ai+XcTpcaX_c^T f_c = X_c^T I^a_c X_c\, a_i + X_c^T p^a_c. Summing over the children,

fi=(Ii+∑cXcTIcaXc)ai+(crf(vi)Iivi−fiext+∑cXcTpca).f_i = \Big(I_i + \sum_c X_c^T I^a_c X_c\Big) a_i + \Big(\mathrm{crf}(v_i) I_i v_i - f^{\mathrm{ext}}_i + \sum_c X_c^T p^a_c\Big).

Line L5 starts IiAI^A_i and piAp^A_i at the first terms, and line L11 adds the sums. A leaf has no children, and the formula is line L5 alone. □\square

Theorem. Line L17 returns the unique q¨\ddot q with RNEA(q,q˙,q¨)=τ\mathrm{RNEA}(q, \dot q, \ddot q) = \tau, that is q¨=M(q)−1(τ−C(q,q˙)q˙−g(q)+∑iJiTfiext)\ddot q = M(q)^{-1}\big(\tau - C(q,\dot q)\dot q - g(q) + \sum_i J_i^T f^{\mathrm{ext}}_i\big).

Proof. M(q)M(q) is positive definite (see the proof of the composite rigid body algorithm), so there is exactly one solution q¨∗\ddot q^*. For q¨∗\ddot q^*, every joint equation holds, so Lemma 3 applies to every body, and the argument in its proof gives, for every ii,

q¨i∗=(ui−UiTai′)/Di,ai′=Xiaλ(i)(q¨∗)+ci.\ddot q^*_i = (u_i - U_i^T a'_i)/D_i, \qquad a'_i = X_i a_{\lambda(i)}(\ddot q^*) + c_i .

The right side uses only q¨k∗\ddot q^*_k for the ancestors kk of ii, through aλ(i)a_{\lambda(i)}. The forward pass of lines L12 to L16 evaluates the same formulas in the order i=1,…,ni = 1, \ldots, n, starting from the same a0=−aga_0 = -a_g. By induction on ii, line L14 computes ai′a'_i, line L15 computes q¨i=q¨i∗\ddot q_i = \ddot q^*_i, and line L16 computes ai(q¨∗)a_i(\ddot q^*). ■\blacksquare

Cost. Every line does a fixed number of operations on 6×66 \times 6 matrices and 6-vectors, and each pass visits each body once. The time is Θ(n)\Theta(n), and the extra space is Θ(n)\Theta(n) for XiX_i, viv_i, cic_i, IiAI^A_i, piAp^A_i, UiU_i, DiD_i and uiu_i.

Massless bodies. Lemma 2 needs a positive definite IiI_i. With a body of zero mass, such as an inner body of a floating base modelled by six joints, DiD_i can still be positive through the inertia of the subtree. The implementation checks Di>0D_i > 0 and raises an error otherwise.

Complexity

In the real RAM, each step of each pass does a fixed number of operations on 6×66 \times 6 matrices and 6-vectors, so the time is Θ(n)\Theta(n) for any tree, and the extra space is Θ(n)\Theta(n). This is optimal in order, because the output has nn entries.

The constant is larger than that of the RNEA, mainly because line L11 moves a 6×66 \times 6 matrix through a transform for each body. Featherstone (2008, Chapter 10) gives exact operation counts for the ABA, the CRBA and the RNEA. Featherstone (1987) reports that the articulated-body method becomes faster than the composite rigid body method with a Cholesky solve for chains of about nine or more bodies. The crossover depends on the implementation and on the shape of the tree: for robots with short branches, the CRBA with a sparse factorization is often as fast.

Properties

  • No mass matrix. The ABA never forms or factors M(q)M(q); it solves Mq¨=τ−bM\ddot q = \tau - b implicitly by a recursive factorization along the tree.
  • Exact. The only errors are floating-point rounding. Featherstone (2008, Chapter 10) discusses the accuracy and the efficiency of the dynamics algorithms.
  • Linear in τ\tau and fextf^{\mathrm{ext}}. For fixed qq and q˙\dot q, q¨\ddot q is affine in τ\tau and in the external wrenches, with the matrix M−1M^{-1}.
  • Inverse of the RNEA. RNEA(q,q˙,ABA(q,q˙,τ))=τ\mathrm{RNEA}(q, \dot q, \mathrm{ABA}(q, \dot q, \tau)) = \tau for every τ\tau.
  • Articulated inertia bounds. IiAI^A_i lies between the inertia IiI_i of body ii alone and the composite inertia of the subtree of ii, in the order of positive semidefinite matrices; see articulated-body inertia.
  • The transmitted inertia is singular. IaSi=0I^a S_i = 0: a free joint transmits no inertia along its own axis.

Variants and improvements

  • Floating base. With a free base, the base is body 1 with a six degree of freedom joint; the ABA handles it with 6×66 \times 6 matrices UU and DD, and DD is the articulated inertia of the whole robot. See floating-base dynamics.
  • Multi-degree-of-freedom joints. For a joint with kk degrees of freedom, SiS_i is 6×k6 \times k, DiD_i is a k×kk \times k matrix and line L15 solves a small linear system.
  • Hybrid dynamics. Some joints may have a given acceleration and others a given force; the passes then mix the RNEA and the ABA. Featherstone (2008, Chapter 9) treats this as hybrid dynamics, together with floating bases.
  • Inverse of the mass matrix. With q˙=0\dot q = 0, no gravity and τ=ej\tau = e_j, the ABA returns column jj of M(q)−1M(q)^{-1}. So nn calls give M−1M^{-1} in Θ(n2)\Theta(n^2) without forming MM; the second pass does not depend on τ\tau except through uiu_i and can be shared.
  • Derivatives. The partial derivatives of q¨\ddot q by qq, q˙\dot q and τ\tau come from the derivatives of the RNEA and M−1M^{-1}; see analytical derivatives of rigid body dynamics.

When to use it

Use the ABA to simulate a robot: for long serial chains, for robots with many bodies, and in any loop that only needs q¨\ddot q. If you also need M(q)M(q), for example for a controller, the composite rigid body algorithm gives it, and a Cholesky solve is then almost free. For two or three joints, both methods are fast, and the simpler one is fine.

Pitfalls

  • Bodies without mass. A body with Ii=0I_i = 0, and no subtree with mass, gives Di=0D_i = 0 and a division by zero. A floating base modelled as six joints has five massless bodies; it works only because the last body of the base carries mass. The implementation raises an error if Di≤0D_i \le 0.
  • The sign of gravity. Line L12 sets a0=−aga_0 = -a_g, as in the RNEA.
  • Dropping IaciI^a c_i in line L10. The velocity product term of the child must enter the bias force of the parent; without it, the result is right only at zero velocity.
  • Using IiAI^A_i in place of IaI^a. The parent receives IaI^a, the inertia with the free joint removed, not IiAI^A_i. With IiAI^A_i, the result is the dynamics of the robot with the joint locked.
  • Comparing against a dense solve. For checks, compare with RNEA(q,q˙,q¨)=τ\mathrm{RNEA}(q, \dot q, \ddot q) = \tau, which tests the result without a second solver and its own rounding.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

articulated_body_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/articulated-body-algorithm/. The authors are listed in prov/0W0KC6.jsonl.
"""Articulated-body algorithm (ABA) for the forward dynamics of a kinematic tree.

Spatial vectors follow Featherstone, Rigid Body Dynamics Algorithms (2008),
with the angular part first: a motion vector is (omega, v) and a force
vector is (n, f). Every quantity of body i is in the coordinates of the
frame of body i.

The tree has bodies 0 .. n-1. parent[i] < i is the parent body, or -1 for
the fixed base. Joint i has one degree of freedom with the screw axis
S_i (a 6-vector in the coordinates of body i). At joint value q_i the pose
of frame i in the frame of its parent is T_tree[i] exp([S_i] q_i). X_i is
the 6x6 matrix that maps motion vectors from parent coordinates to body i
coordinates, and its transpose maps force vectors from body i to the
parent.
"""

import rbm

# Gravity in the base frame, z up, in m/s^2.
GRAVITY = [0.0, 0.0, -9.81]


def spatial_inertia(mass, com, inertia_com):
    """Return the 6x6 spatial inertia about the frame origin.

    mass in kg, com the center of mass c in the body frame, inertia_com
    the 3x3 rotational inertia about the center of mass. The result is
    [[I_c + m [c][c]^T, m [c]], [m [c]^T, m 1]].
    """
    c = rbm.hat3(com)
    top_left = rbm.add(inertia_com, rbm.scale(rbm.mul(c, rbm.transpose(c)), mass))
    out = rbm.zeros(6, 6)
    for r in range(3):
        for k in range(3):
            out[r][k] = top_left[r][k]
            out[r][k + 3] = mass * c[r][k]
            out[r + 3][k] = mass * c[k][r]
        out[r + 3][r + 3] = mass
    return out


def cross_motion(v, m):
    """Return crm(v) m = (w x m_w, v_lin x m_w + w x m_lin) for motion vectors."""
    w, vl = v[:3], v[3:]
    return rbm.cross(w, m[:3]) + rbm.add(rbm.cross(vl, m[:3]), rbm.cross(w, m[3:]))


def cross_force(v, f):
    """Return crf(v) f = (w x n + v_lin x f_lin, w x f_lin) for a force vector f."""
    w, vl = v[:3], v[3:]
    return rbm.add(rbm.cross(w, f[:3]), rbm.cross(vl, f[3:])) + rbm.cross(w, f[3:])


class Model:
    """A kinematic tree of rigid bodies, each with one joint to its parent."""

    def __init__(self):
        self.parent = []
        self.tree = []
        self.screw = []
        self.inertia = []

    @property
    def n(self):
        return len(self.parent)

    def add_body(self, parent, tree, screw, inertia):
        """Append a body and return its index (see the module comment)."""
        if not -1 <= parent < self.n:
            raise ValueError("the parent must be -1 or an earlier body")
        if len(screw) != 6 or len(inertia) != 6:
            raise ValueError("a screw axis has 6 entries and an inertia is 6x6")
        self.parent.append(parent)
        self.tree.append(tree)
        self.screw.append([float(x) for x in screw])
        self.inertia.append(inertia)
        return self.n - 1


def joint_transform(model, i, qi):
    """Return X_i, the motion transform from the parent of i to body i."""
    pose = rbm.mul(model.tree[i], rbm.se3_exp(rbm.scale(model.screw[i], qi)))
    return rbm.adjoint(rbm.T_inv(pose))


def aba(model, q, qd, tau, gravity=GRAVITY, f_ext=None):
    """Return the joint accelerations qdd = M(q)^(-1) (tau - C(q, qd) qd - g(q) + J^T f_ext).

    gravity is the acceleration of gravity in base coordinates. f_ext, if
    given, is a list of n external force vectors, each in the coordinates
    of its body (None for no force). Raise ValueError if an articulated
    inertia D_i is not positive, which happens only for bodies without
    mass or inertia.
    """
    n = model.n
    if not len(q) == len(qd) == len(tau) == n:
        raise ValueError("q, qd and tau need one entry per joint")
    zero = [0.0] * 6
    xs, v, c = [None] * n, [None] * n, [None] * n
    ia, pa = [None] * n, [None] * n
    for i in range(n):  # @line L1
        p = model.parent[i]
        s = model.screw[i]
        xs[i] = joint_transform(model, i, q[i])  # @line L2
        vj = rbm.scale(s, qd[i])
        v[i] = rbm.add(rbm.matvec(xs[i], zero if p < 0 else v[p]), vj)  # @line L3
        c[i] = cross_motion(v[i], vj)  # @line L4
        ia[i] = [list(row) for row in model.inertia[i]]  # @line L5
        pa[i] = cross_force(v[i], rbm.matvec(model.inertia[i], v[i]))
        if f_ext is not None and f_ext[i] is not None:
            pa[i] = rbm.sub(pa[i], f_ext[i])
    u_vec, d, u = [None] * n, [0.0] * n, [0.0] * n
    for i in range(n - 1, -1, -1):  # @line L6
        s = model.screw[i]
        u_vec[i] = rbm.matvec(ia[i], s)  # @line L7
        d[i] = rbm.dot(s, u_vec[i])
        if not d[i] > 0.0:
            raise ValueError("articulated inertia about joint %d is not positive" % i)
        u[i] = tau[i] - rbm.dot(s, pa[i])
        p = model.parent[i]
        if p >= 0:  # @line L8
            ui = u_vec[i]
            i_art = [[ia[i][r][k] - ui[r] * ui[k] / d[i] for k in range(6)] for r in range(6)]  # @line L9
            p_art = rbm.add(rbm.add(pa[i], rbm.matvec(i_art, c[i])), rbm.scale(ui, u[i] / d[i]))  # @line L10
            xt = rbm.transpose(xs[i])
            ia[p] = rbm.add(ia[p], rbm.mul(xt, rbm.mul(i_art, xs[i])))  # @line L11
            pa[p] = rbm.add(pa[p], rbm.matvec(xt, p_art))
    a_base = [0.0, 0.0, 0.0] + [-x for x in gravity]  # @line L12
    a = [None] * n
    qdd = [0.0] * n
    for i in range(n):  # @line L13
        p = model.parent[i]
        a_prime = rbm.add(rbm.matvec(xs[i], a_base if p < 0 else a[p]), c[i])  # @line L14
        qdd[i] = (u[i] - rbm.dot(u_vec[i], a_prime)) / d[i]  # @line L15
        a[i] = rbm.add(a_prime, rbm.scale(model.screw[i], qdd[i]))  # @line L16
    return qdd  # @line L17
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

Conventions (Lynch and Park, Modern Robotics, 2017):
- A matrix is a list of rows. A vector is a flat list.
- hat3(w) is the skew-symmetric matrix [w], so that [w] x = w x x.
- A twist or screw is a 6-vector (omega, v), angular part first.
  hat6(V) is the 4x4 matrix [[[omega], v], [0, 0]].
- A pose T is the 4x4 matrix [[R, p], [0, 1]].
- so3_exp and so3_log use exponential coordinates w = omega_hat * theta,
  with theta = |w| in [0, pi] for so3_log.
- se3_exp and se3_log use 6-vectors (w, v) = S * theta.
- Quaternions are Hamilton, scalar first: q = (w, x, y, z), with i j = k.
- Angles are in radians.

The helper holds no algorithm of a robotics page except the four maps
so3_exp, so3_log, se3_exp and se3_log. The pages so3-logarithm-map and
se3-exponential-map hold their own complete versions with comments.
"""

import math

# Below this angle, the coefficient functions of the exponential and the
# logarithm are evaluated by their Taylor series. The first omitted term
# of each series is of order theta^6 and is below 3e-16 for theta < 1e-2;
# it also multiplies [w] or [w]^2, which are small. Above the threshold,
# the closed forms such as (1 - cos(theta)) / theta^2 lose at most about
# 1e-16 / theta^2 to cancellation, which [w] or [w]^2 brings to 1e-14.
SERIES_THETA = 1e-2

# Above pi - NEAR_PI, so3_log takes the axis from the symmetric part of R
# (which is (R + I) / 2 at theta = pi) and not from the skew part.
NEAR_PI = 1e-2

# A pivot whose magnitude is at most PIVOT_TOL times the largest entry of
# the matrix makes solve, inv and pinv_right raise ValueError.
PIVOT_TOL = 1e-12


# ---------------------------------------------------------------- matrices


def zeros(n, m):
    """Return the n by m zero matrix."""
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(a, s):
    """Return s * a for a vector or a matrix a and a number s."""
    if _is_matrix(a):
        return [[s * x for x in row] for row in a]
    return [s * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(p * q for p, q in zip(row, x)) for row in a]


def dot(x, y):
    """Return the dot product of two vectors."""
    return sum(p * q for p, q in zip(x, y))


def norm(x):
    """Return the Euclidean norm of a vector."""
    return math.sqrt(dot(x, x))


def cross(a, b):
    """Return the cross product a x b of two 3-vectors."""
    return [
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    ]


def _max_abs(a):
    return max((abs(x) for row in a for x in row), default=0.0)


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    a is a square matrix. b is a vector or a matrix with one column per
    right-hand side; the result has the same shape as b. Raise ValueError
    if a pivot is at most PIVOT_TOL times the largest entry of a.
    """
    n = len(a)
    vec = not _is_matrix(b)
    rhs = [[x] for x in b] if vec else [list(row) for row in b]
    m = [list(map(float, row)) + list(map(float, r)) for row, r in zip(a, rhs)]
    k = len(rhs[0]) if rhs else 0
    tol = PIVOT_TOL * _max_abs(a)
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if abs(m[piv][c]) <= tol or m[piv][c] == 0.0:
            raise ValueError("matrix is singular to working precision")
        m[c], m[piv] = m[piv], m[c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            if f != 0.0:
                row_r, row_c = m[r], m[c]
                for j in range(c, n + k):
                    row_r[j] -= f * row_c[j]
    x = [[0.0] * k for _ in range(n)]
    for r in range(n - 1, -1, -1):
        for j in range(k):
            s = m[r][n + j] - sum(m[r][i] * x[i][j] for i in range(r + 1, n))
            x[r][j] = s / m[r][r]
    return [row[0] for row in x] if vec else x


def inv(a):
    """Return the inverse of the square matrix a (see solve for errors)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a by elimination."""
    n = len(a)
    m = [list(map(float, row)) for row in a]
    d = 1.0
    for c in range(n):
        piv = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[piv][c] == 0.0:
            return 0.0
        if piv != c:
            m[c], m[piv] = m[piv], m[c]
            d = -d
        d *= m[c][c]
        for r in range(c + 1, n):
            f = m[r][c] / m[c][c]
            for j in range(c, n):
                m[r][j] -= f * m[c][j]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T.

    a must be symmetric positive definite. Raise ValueError if a diagonal
    entry of the factor is not positive.
    """
    n = len(a)
    low = zeros(n, n)
    for i in range(n):
        for j in range(i + 1):
            s = a[i][j] - sum(low[i][k] * low[j][k] for k in range(j))
            if i == j:
                if s <= 0.0:
                    raise ValueError("matrix is not positive definite")
                low[i][i] = math.sqrt(s)
            else:
                low[i][j] = s / low[j][j]
    return low


def pinv_right(j):
    """Return the right pseudoinverse J^T (J J^T)^(-1) of a J with full row rank."""
    jt = transpose(j)
    return mul(jt, inv(mul(j, jt)))


# ---------------------------------------------------------------- hat and vee


def hat3(w):
    """Return the 3x3 skew-symmetric matrix [w] of a 3-vector w."""
    return [
        [0.0, -w[2], w[1]],
        [w[2], 0.0, -w[0]],
        [-w[1], w[0], 0.0],
    ]


def vee3(m):
    """Return the 3-vector w of a skew-symmetric matrix m = [w]."""
    return [m[2][1], m[0][2], m[1][0]]


def hat6(v):
    """Return the 4x4 matrix [V] = [[[omega], v], [0, 0]] of V = (omega, v)."""
    w = hat3(v[:3])
    return [
        [w[0][0], w[0][1], w[0][2], v[3]],
        [w[1][0], w[1][1], w[1][2], v[4]],
        [w[2][0], w[2][1], w[2][2], v[5]],
        [0.0, 0.0, 0.0, 0.0],
    ]


def vee6(m):
    """Return the 6-vector (omega, v) of a 4x4 matrix [V]."""
    return [m[2][1], m[0][2], m[1][0], m[0][3], m[1][3], m[2][3]]


# ---------------------------------------------------------------- rotations


def rot_x(a):
    """Return the rotation by a radians about the x axis."""
    c, s = math.cos(a), math.sin(a)
    return [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]


def rot_y(a):
    """Return the rotation by a radians about the y axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]


def rot_z(a):
    """Return the rotation by a radians about the z axis."""
    c, s = math.cos(a), math.sin(a)
    return [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]


def rpy(roll, pitch, yaw):
    """Return R = Rz(yaw) Ry(pitch) Rx(roll)."""
    return mul(rot_z(yaw), mul(rot_y(pitch), rot_x(roll)))


def so3_exp(w):
    """Return exp([w]) for exponential coordinates w = omega_hat * theta.

    Rodrigues' formula in the form I + A [w] + B [w]^2 with
    A = sin(theta) / theta and B = (1 - cos(theta)) / theta^2.
    """
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        a = 1.0 - t2 / 6.0 + t2 * t2 / 120.0
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
    else:
        a = math.sin(t) / t
        b = (1.0 - math.cos(t)) / (t * t)
    k = hat3(w)
    k2 = mul(k, k)
    return [[(1.0 if i == j else 0.0) + a * k[i][j] + b * k2[i][j] for j in range(3)] for i in range(3)]


def so3_log(r):
    """Return w = omega_hat * theta with exp([w]) = r and theta in [0, pi].

    theta = atan2(|s|, c), where c = (trace(r) - 1) / 2 = cos(theta) and
    s = vee(r - r^T) / 2 = sin(theta) omega_hat. For theta below
    SERIES_THETA, w = s (1 + theta^2 / 6 + 7 theta^4 / 360). For theta
    above pi - NEAR_PI, the axis comes from the symmetric part
    ((r + r^T) / 2 - c I) / (1 - c) = omega_hat omega_hat^T, and its sign
    from s. At theta = pi both signs are valid; the sign is then chosen so
    that the largest component of the axis is positive.
    """
    c = (r[0][0] + r[1][1] + r[2][2] - 1.0) / 2.0
    c = max(-1.0, min(1.0, c))
    s = [(r[2][1] - r[1][2]) / 2.0, (r[0][2] - r[2][0]) / 2.0, (r[1][0] - r[0][1]) / 2.0]
    sn = norm(s)
    t = math.atan2(sn, c)
    if t < SERIES_THETA:
        t2 = t * t
        f = 1.0 + t2 / 6.0 + 7.0 * t2 * t2 / 360.0
        return [f * x for x in s]
    if t <= math.pi - NEAR_PI:
        return [t / sn * x for x in s]
    b = [[(r[i][j] + r[j][i]) / 2.0 - (c if i == j else 0.0) for j in range(3)] for i in range(3)]
    # b = (1 - c) omega_hat omega_hat^T. Its column k with the largest
    # diagonal entry is (1 - c) omega_k omega_hat, with omega_k^2 >= 1/3.
    k = max(range(3), key=lambda i: b[i][i])
    col = [b[i][k] for i in range(3)]
    axis = [x / norm(col) for x in col]
    if dot(axis, s) < 0.0 or (dot(axis, s) == 0.0 and axis[k] < 0.0):
        axis = [-x for x in axis]
    return [t * x for x in axis]


# ---------------------------------------------------------------- poses


def make_T(r, p):
    """Return the 4x4 pose [[r, p], [0, 1]]."""
    return [
        [r[0][0], r[0][1], r[0][2], p[0]],
        [r[1][0], r[1][1], r[1][2], p[1]],
        [r[2][0], r[2][1], r[2][2], p[2]],
        [0.0, 0.0, 0.0, 1.0],
    ]


def _rp(t):
    return [row[:3] for row in t[:3]], [t[0][3], t[1][3], t[2][3]]


def T_inv(t):
    """Return the inverse [[R^T, -R^T p], [0, 1]] of a pose t."""
    r, p = _rp(t)
    rt = transpose(r)
    return make_T(rt, [-x for x in matvec(rt, p)])


def T_apply(t, x):
    """Return R x + p, the image of the point x under the pose t."""
    r, p = _rp(t)
    return add(matvec(r, x), p)


def se3_exp(xi):
    """Return exp([xi]) for a 6-vector xi = (w, v) = S * theta.

    The rotation is so3_exp(w). The translation is G v with
    G = I + B [w] + C [w]^2, B = (1 - cos(theta)) / theta^2 and
    C = (theta - sin(theta)) / theta^3, theta = |w|. For w = 0 this is a
    translation by v.
    """
    w, v = xi[:3], xi[3:]
    t = norm(w)
    if t < SERIES_THETA:
        t2 = t * t
        b = 0.5 - t2 / 24.0 + t2 * t2 / 720.0
        c = 1.0 / 6.0 - t2 / 120.0 + t2 * t2 / 5040.0
    else:
        b = (1.0 - math.cos(t)) / (t * t)
        c = (t - math.sin(t)) / (t * t * t)
    k = hat3(w)
    k2 = mul(k, k)
    g = [[(1.0 if i == j else 0.0) + b * k[i][j] + c * k2[i][j] for j in range(3)] for i in range(3)]
    return make_T(so3_exp(w), matvec(g, v))


def se3_log(t):
    """Return the 6-vector xi = (w, v) with se3_exp(xi) = t and |w| in [0, pi].

    w = so3_log(R) and v = G^(-1) p with
    G^(-1) = I - [w] / 2 + D [w]^2, D = (1 - (theta / 2) cot(theta / 2)) / theta^2.
    """
    r, p = _rp(t)
    w = so3_log(r)
    th = norm(w)
    if th < SERIES_THETA:
        t2 = th * th
        d = 1.0 / 12.0 + t2 / 720.0 + t2 * t2 / 30240.0
    else:
        half = th / 2.0
        d = (1.0 - half * math.cos(half) / math.sin(half)) / (th * th)
    k = hat3(w)
    k2 = mul(k, k)
    gi = [[(1.0 if i == j else 0.0) - 0.5 * k[i][j] + d * k2[i][j] for j in range(3)] for i in range(3)]
    return w + matvec(gi, p)


def adjoint(t):
    """Return the 6x6 adjoint [[R, 0], [[p] R, R]] of a pose t."""
    r, p = _rp(t)
    pr = mul(hat3(p), r)
    out = zeros(6, 6)
    for i in range(3):
        for j in range(3):
            out[i][j] = r[i][j]
            out[i + 3][j + 3] = r[i][j]
            out[i + 3][j] = pr[i][j]
    return out


# ---------------------------------------------------------------- quaternions


def quat_mul(q, r):
    """Return the Hamilton product q r of quaternions (w, x, y, z)."""
    a1, b1, c1, d1 = q
    a2, b2, c2, d2 = r
    return [
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    ]


def quat_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return [q[0], -q[1], -q[2], -q[3]]


def quat_to_rot(q):
    """Return the rotation matrix of the quaternion q, so that (0, R v) = q (0, v) q*.

    q need not be of unit length; the result is the rotation of q / |q|.
    """
    w, x, y, z = q
    n = w * w + x * x + y * y + z * z
    s = 2.0 / n
    return [
        [1.0 - s * (y * y + z * z), s * (x * y - w * z), s * (x * z + w * y)],
        [s * (x * y + w * z), 1.0 - s * (x * x + z * z), s * (y * z - w * x)],
        [s * (x * z - w * y), s * (y * z + w * x), 1.0 - s * (x * x + y * y)],
    ]


def quat_from_axis_angle(axis, angle):
    """Return (cos(angle / 2), sin(angle / 2) axis / |axis|).

    A zero axis is allowed only with angle 0 (the identity); otherwise
    raise ValueError.
    """
    n = norm(axis)
    if n == 0.0:
        if angle == 0.0:
            return [1.0, 0.0, 0.0, 0.0]
        raise ValueError("zero axis with a nonzero angle")
    s = math.sin(angle / 2.0) / n
    return [math.cos(angle / 2.0), s * axis[0], s * axis[1], s * axis[2]]


# ---------------------------------------------------------------- derivatives


def num_jacobian(f, x, h=1e-6):
    """Return the Jacobian of f at x by central differences with step h.

    f maps a list of n numbers to a list of m numbers; the result is m by n.
    """
    cols = []
    for i in range(len(x)):
        xp = list(x)
        xm = list(x)
        xp[i] += h
        xm[i] -= h
        fp, fm = f(xp), f(xm)
        cols.append([(a - b) / (2.0 * h) for a, b in zip(fp, fm)])
    return transpose(cols)


# ---------------------------------------------------------------- self-test


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_articulated_body_algorithm.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/articulated-body-algorithm/. The authors are listed in prov/0W0KC6.jsonl.
"""Tests of ABA against RNEA, a dense mass matrix solve and energy conservation."""

import math
import random

import pytest

import rbm
from articulated_body_algorithm import (
    GRAVITY,
    Model,
    aba,
    cross_force,
    cross_motion,
    joint_transform,
    spatial_inertia,
)

Z_AXIS = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]


def planar_2r():
    """2R arm in the x-y plane, links of 1 m, point masses of 1 kg at the link ends."""
    model = Model()
    point = spatial_inertia(1.0, [1.0, 0.0, 0.0], rbm.zeros(3, 3))
    model.add_body(-1, rbm.eye(4), Z_AXIS, point)
    model.add_body(0, rbm.make_T(rbm.eye(3), [1.0, 0.0, 0.0]), Z_AXIS, point)
    return model


def random_model(rng, n, parents=None):
    model = Model()
    for i in range(n):
        parent = rng.randrange(-1, i) if parents is None else parents[i]
        tree = rbm.se3_exp([rng.uniform(-0.6, 0.6) for _ in range(6)])
        u = [rng.gauss(0.0, 1.0) for _ in range(3)]
        u = rbm.scale(u, 1.0 / rbm.norm(u))
        if rng.random() < 0.8:
            point = [rng.uniform(-0.3, 0.3) for _ in range(3)]
            screw = u + [-x for x in rbm.cross(u, point)]
        else:
            screw = [0.0, 0.0, 0.0] + u
        a = [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(3)]
        ic = rbm.add(rbm.mul(a, rbm.transpose(a)), rbm.scale(rbm.eye(3), 0.05))
        com = [rng.uniform(-0.3, 0.3) for _ in range(3)]
        model.add_body(parent, tree, screw, spatial_inertia(rng.uniform(0.5, 2.0), com, ic))
    return model


def rnea_ref(model, q, qd, qdd, gravity, f_ext=None):
    """Plain recursive Newton-Euler inverse dynamics, used as the reference."""
    n = model.n
    a_base = [0.0, 0.0, 0.0] + [-x for x in gravity]
    xs, v, a, f = [None] * n, [None] * n, [None] * n, [None] * n
    for i in range(n):
        p = model.parent[i]
        s = model.screw[i]
        xs[i] = joint_transform(model, i, q[i])
        vj = rbm.scale(s, qd[i])
        v[i] = rbm.add(rbm.matvec(xs[i], [0.0] * 6 if p < 0 else v[p]), vj)
        a[i] = rbm.add(rbm.add(rbm.matvec(xs[i], a_base if p < 0 else a[p]), rbm.scale(s, qdd[i])),
                       cross_motion(v[i], vj))
        f[i] = rbm.add(rbm.matvec(model.inertia[i], a[i]),
                       cross_force(v[i], rbm.matvec(model.inertia[i], v[i])))
        if f_ext is not None and f_ext[i] is not None:
            f[i] = rbm.sub(f[i], f_ext[i])
    tau = [0.0] * n
    for i in range(n - 1, -1, -1):
        tau[i] = rbm.dot(model.screw[i], f[i])
        if model.parent[i] >= 0:
            f[model.parent[i]] = rbm.add(f[model.parent[i]], rbm.matvec(rbm.transpose(xs[i]), f[i]))
    return tau


def dense_forward_dynamics(model, q, qd, tau, gravity):
    """Build M from n + 1 RNEA calls and solve M qdd = tau - bias by elimination."""
    n = model.n
    zero = [0.0] * n
    bias = rnea_ref(model, q, qd, zero, gravity)
    cols = []
    for k in range(n):
        e = [1.0 if j == k else 0.0 for j in range(n)]
        cols.append(rnea_ref(model, q, zero, e, [0.0, 0.0, 0.0]))
    return rbm.solve(rbm.transpose(cols), rbm.sub(tau, bias))


def potential(model, q, g):
    total = 0.0
    pose = []
    for i in range(model.n):
        local = rbm.mul(model.tree[i], rbm.se3_exp(rbm.scale(model.screw[i], q[i])))
        p = model.parent[i]
        pose.append(local if p < 0 else rbm.mul(pose[p], local))
        inertia = model.inertia[i]
        mass = inertia[5][5]
        com = [inertia[2][4] / mass, inertia[0][5] / mass, inertia[1][3] / mass]
        total -= mass * rbm.dot(g, rbm.T_apply(pose[i], com))
    return total


def test_2r_check_values():
    model = planar_2r()
    qdd = aba(model, [0.0, math.pi / 2], [1.0, 1.0], [0.0, 0.0], [0.0, 0.0, 0.0])
    assert abs(qdd[0] - 2.0) < 1e-12 and abs(qdd[1] + 3.0) < 1e-12
    qdd = aba(model, [0.0, 0.0], [0.0, 0.0], [29.43, 9.81], [0.0, -9.81, 0.0])
    assert max(abs(x) for x in qdd) < 1e-12


def test_inverts_rnea_on_random_trees():
    rng = random.Random(1)
    for n in (1, 5, 6, 7):
        model = random_model(rng, n)
        for _ in range(3):
            q = [rng.uniform(-2, 2) for _ in range(n)]
            qd = [rng.uniform(-1.5, 1.5) for _ in range(n)]
            tau = [rng.uniform(-5, 5) for _ in range(n)]
            f_ext = [[rng.uniform(-1, 1) for _ in range(6)] if rng.random() < 0.4 else None for _ in range(n)]
            qdd = aba(model, q, qd, tau, GRAVITY, f_ext)
            back = rnea_ref(model, q, qd, qdd, GRAVITY, f_ext)
            assert max(abs(x - y) for x, y in zip(back, tau)) < 1e-9
            qdd_ref = [rng.uniform(-3, 3) for _ in range(n)]
            tau_ref = rnea_ref(model, q, qd, qdd_ref, GRAVITY, f_ext)
            got = aba(model, q, qd, tau_ref, GRAVITY, f_ext)
            assert max(abs(x - y) for x, y in zip(got, qdd_ref)) < 1e-9


def test_against_dense_solve():
    rng = random.Random(2)
    model = random_model(rng, 7)
    q = [rng.uniform(-2, 2) for _ in range(7)]
    qd = [rng.uniform(-1, 1) for _ in range(7)]
    tau = [rng.uniform(-5, 5) for _ in range(7)]
    got = aba(model, q, qd, tau)
    want = dense_forward_dynamics(model, q, qd, tau, GRAVITY)
    assert max(abs(x - y) for x, y in zip(got, want)) < 1e-9


def test_serial_chain_and_star():
    rng = random.Random(3)
    for parents in ([-1, 0, 1, 2, 3, 4], [-1, 0, 0, 0, 0, 0], [-1, -1, -1, 2, 2]):
        model = random_model(rng, len(parents), parents)
        n = model.n
        q = [rng.uniform(-2, 2) for _ in range(n)]
        qd = [rng.uniform(-1, 1) for _ in range(n)]
        tau = [rng.uniform(-5, 5) for _ in range(n)]
        qdd = aba(model, q, qd, tau)
        assert max(abs(x - y) for x, y in zip(rnea_ref(model, q, qd, qdd, GRAVITY), tau)) < 1e-9


def test_energy_is_constant_without_torque():
    """RK4 with dt = 5e-3 for 120 steps; tau = 0 and no friction. The drift must stay below 1e-6 J."""
    rng = random.Random(6)
    model = random_model(rng, 3, [-1, 0, 1])
    q = [0.3, -0.5, 0.8]
    qd = [0.5, -0.4, 0.2]
    zero = [0.0] * 3

    def deriv(x, v):
        return v, aba(model, x, v, zero)

    def energy(x, v):
        ke = 0.5 * rbm.dot(v, rnea_ref(model, x, [0.0] * 3, v, [0.0] * 3))  # (1/2) v^T M v
        return ke + potential(model, x, GRAVITY)

    e0 = energy(q, qd)
    dt = 5e-3
    for _ in range(120):
        k1 = deriv(q, qd)
        k2 = deriv(rbm.add(q, rbm.scale(k1[0], dt / 2)), rbm.add(qd, rbm.scale(k1[1], dt / 2)))
        k3 = deriv(rbm.add(q, rbm.scale(k2[0], dt / 2)), rbm.add(qd, rbm.scale(k2[1], dt / 2)))
        k4 = deriv(rbm.add(q, rbm.scale(k3[0], dt)), rbm.add(qd, rbm.scale(k3[1], dt)))
        q = [x + dt / 6 * (a + 2 * b + 2 * c + d) for x, a, b, c, d in zip(q, k1[0], k2[0], k3[0], k4[0])]
        qd = [x + dt / 6 * (a + 2 * b + 2 * c + d) for x, a, b, c, d in zip(qd, k1[1], k2[1], k3[1], k4[1])]
    assert max(abs(x - y) for x, y in zip(q, [0.3, -0.5, 0.8])) > 0.05
    assert abs(energy(q, qd) - e0) < 1e-6


def test_massless_body_is_rejected():
    model = Model()
    model.add_body(-1, rbm.eye(4), Z_AXIS, rbm.zeros(6, 6))
    with pytest.raises(ValueError):
        aba(model, [0.0], [0.0], [1.0])
    with pytest.raises(ValueError):
        aba(planar_2r(), [0.0], [0.0, 0.0], [0.0, 0.0])

History

Featherstone (1983) introduced articulated-body inertias and the O(n)O(n) algorithm for the forward dynamics of a serial robot. His 1987 book extended it, compared it with the composite rigid body method of Walker and Orin, and gave the crossover in efficiency. His 2008 book gives the algorithm for kinematic trees in the spatial notation that this page uses, and the chapter by Featherstone and Orin in the Springer Handbook of Robotics gives a short form. The name Featherstone's algorithm refers to the 1983 paper.

References

  1. Roy Featherstone, The calculation of robot dynamics using articulated-body inertias, The International Journal of Robotics Research 2(1), 1983, pages 13 to 30
  2. Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 7 (forward dynamics by propagation methods): the articulated-body inertia, its calculation and the articulated-body algorithm; Chapter 10 (accuracy and efficiency) for the operation counts
  3. Roy Featherstone, Robot Dynamics Algorithms, Kluwer Academic Publishers, 1987, the chapter on the articulated-body method and its comparison with the composite-rigid-body method
  4. Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 3, Dynamics, by Roy Featherstone and David E. Orin

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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