Algorithm Search⌘K

Algorithmresearch

Analytical derivatives of rigid body dynamics

Also called RNEA derivatives.

Carpentier and Mansard's recursion for the partial derivatives of inverse dynamics in O(n d) time for a tree of depth d (O(n^2) for a serial chain), and of forward dynamics through M^-1.

Time
O(n^3) forwardΘ(n d) inverse
Space
Θ(n d) extra
Where
d = the depth of the tree, the largest number of joints on a path from the base (d = n for a serial chain); n = the number of joints, one degree of freedom each
Properties
deterministicofflineiterative
Origin
Justin Carpentier, Nicolas Mansard, 2018

The analytical derivatives of rigid body dynamics are the partial derivatives of the joint forces τ=ID(q,q˙,q¨)\tau = \mathrm{ID}(q, \dot q, \ddot q) by the joint positions qq and velocities q˙\dot q, and the partial derivatives of the accelerations q¨=FD(q,q˙,τ)\ddot q = \mathrm{FD}(q, \dot q, \tau) by qq, q˙\dot q and τ\tau. Carpentier and Mansard (2018) computed the derivatives of the inverse dynamics by differentiating each line of the recursive Newton-Euler algorithm (RNEA) with spatial algebra, and they obtained the derivatives of the forward dynamics from them with the inverse of the joint-space inertia matrix. The result is exact up to rounding, unlike finite differences, and much faster than finite differences or general automatic differentiation of the RNEA. The derivatives are what trajectory optimization, DDP and nonlinear MPC need at every step. The cost is O(nd)O(n d) for a tree of depth dd, which is Θ(n2)\Theta(n^2) for a serial chain. It cannot be O(n)O(n), because the output of a serial chain has Θ(n2)\Theta(n^2) nonzero entries.

In plain words

An optimizer that plans the motion of a robot must know how a small change of a joint angle or speed changes the forces at all the joints. The simple way is to nudge each joint a little, run the force computation again, and compare. That needs many runs, and the nudge spoils the digits. This method works out the change directly. It follows the same two walks over the robot as the force computation, out to the tips and back to the base. Next to each link's motion it also carries how that motion changes with each joint above it. On the way back, it carries how each joint push changes. A link far out on a long arm depends on every joint before it, so the total work grows with the length of the arm times the number of links.

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\}, Xi=Ad(Tλ(i),i(qi)−1)X_i = \mathrm{Ad}(T_{\lambda(i),i}(q_i)^{-1}) with Tλ(i),i(qi)=Titreee[Si]qiT_{\lambda(i),i}(q_i) = T^{\mathrm{tree}}_i e^{[S_i] q_i}, and IiI_i is the spatial inertia of body ii. Spatial vectors have the angular part first, and crm\mathrm{crm} and crf\mathrm{crf} are the spatial cross products of spatial vector algebra. anc(i)\mathrm{anc}(i) is the set of body ii and its ancestors.

Input: the model, q,q˙,q¨∈Rnq, \dot q, \ddot q \in \mathbb{R}^n and gravity aga_g. Output: τ=ID(q,q˙,q¨)\tau = \mathrm{ID}(q, \dot q, \ddot q) and the three n×nn \times n matrices ∂τ/∂q\partial \tau/\partial q, ∂τ/∂q˙\partial \tau/\partial \dot q and ∂τ/∂q¨=M(q)\partial \tau/\partial \ddot q = M(q).

For the forward dynamics, the input is q,q˙,τq, \dot q, \tau and the output is q¨=FD(q,q˙,τ)\ddot q = \mathrm{FD}(q, \dot q, \tau) with ∂q¨/∂q\partial \ddot q/\partial q, ∂q¨/∂q˙\partial \ddot q/\partial \dot q and ∂q¨/∂τ\partial \ddot q/\partial \tau.

The algorithm

The algorithm rests on two identities for the derivative of a joint transform. Since Xi(qi+h)=Ad(e−[Si]h)Xi(qi)X_i(q_i + h) = \mathrm{Ad}(e^{-[S_i]h}) X_i(q_i), for a motion vector mm and a force vector ff that do not depend on qiq_i,

∂(Xim)∂qi=crm(Xim) Si,∂(XiTf)∂qi=XiT crf(Si) f.\frac{\partial (X_i m)}{\partial q_i} = \mathrm{crm}(X_i m)\, S_i, \qquad \frac{\partial (X_i^T f)}{\partial q_i} = X_i^T\, \mathrm{crf}(S_i)\, f .

For each body, the algorithm stores the derivatives of viv_i, aia_i and fif_i by the coordinates of the joints in anc(i)\mathrm{anc}(i); all other derivatives are 0. In the pseudocode, ∂k\partial_k is the derivative by qkq_k, by q˙k\dot q_k or by q¨k\ddot q_k, and a line with ∂k\partial_k runs for each of the three.

  1. RNEA-DERIVATIVES(model, q, q̇, q̈, a_g)
  2. 1for i ← 1 to n do ▷ forward pass, with the RNEA
  3. 2X_i ← Ad(T_{λ(i),i}(q_i)^-1) ; v_i, a_i, f_i as in the RNEA
  4. 3for k in anc(λ(i)): ∂_k v_i ← X_i ∂_k v_λ(i) ; ∂_k a_i ← X_i ∂_k a_λ(i)
  5. 4∂v_i/∂q_i ← crm(X_i v_λ(i)) S_i ; ∂a_i/∂q_i ← crm(X_i a_λ(i)) S_i
  6. 5∂v_i/∂q̇_i ← S_i ; ∂a_i/∂q̇_i ← crm(v_i) S_i ; ∂a_i/∂q̈_i ← S_i
  7. 6for k in anc(i), by q and by q̇: ∂_k a_i ← ∂_k a_i + crm(∂_k v_i) S_i q̇_i
  8. 7for k in anc(i): ∂_k f_i ← I_i ∂_k a_i + crf(∂_k v_i) I_i v_i + crf(v_i) I_i ∂_k v_i
  9. 8for i ← n downto 1 do ▷ backward pass
  10. 9τ_i ← S_i^T f_i ; for each stored k: ∂τ_i/∂u_k ← S_i^T ∂_k f_i
  11. 10if λ(i) ≠ 0 then
  12. 11for each stored k: ∂_k f_λ(i) ← ∂_k f_λ(i) + X_i^T ∂_k f_i
  13. 12∂f_λ(i)/∂q_i ← ∂f_λ(i)/∂q_i + X_i^T crf(S_i) f_i
  14. 13f_λ(i) ← f_λ(i) + X_i^T f_i
  15. 14return τ, ∂τ/∂q, ∂τ/∂q̇, ∂τ/∂q̈

Line L3 carries the derivatives of the parent through XiX_i; it is the first part of the product rule, for the joints above ii. Line L4 is the first identity, the derivative of XiX_i itself by qiq_i. Line L5 is the direct effect of q˙i\dot q_i and q¨i\ddot q_i. Line L6 differentiates the velocity product crm(vi)Siq˙i\mathrm{crm}(v_i) S_i \dot q_i through viv_i. Line L7 is the product rule on the Newton-Euler wrench Iiai+crf(vi)IiviI_i a_i + \mathrm{crf}(v_i) I_i v_i; for the derivatives by q¨\ddot q, the velocity does not change and only Ii ∂kaiI_i\, \partial_k a_i is left. In the backward pass, the derivatives of fif_i by the joints below ii arrive from the children through line L11, and line L12 is the second identity, the derivative of XiTX_i^T by qiq_i.

The forward dynamics derivatives follow from the identity ID(q,q˙,FD(q,q˙,τ))=τ\mathrm{ID}(q, \dot q, \mathrm{FD}(q, \dot q, \tau)) = \tau. Differentiate it:

∂FD∂q=−M−1∂ID∂q,∂FD∂q˙=−M−1∂ID∂q˙,∂FD∂τ=M−1,\frac{\partial \mathrm{FD}}{\partial q} = -M^{-1} \frac{\partial \mathrm{ID}}{\partial q}, \qquad \frac{\partial \mathrm{FD}}{\partial \dot q} = -M^{-1} \frac{\partial \mathrm{ID}}{\partial \dot q}, \qquad \frac{\partial \mathrm{FD}}{\partial \tau} = M^{-1},

where the derivatives of ID\mathrm{ID} are evaluated at q¨=FD(q,q˙,τ)\ddot q = \mathrm{FD}(q, \dot q, \tau), not at q¨=0\ddot q = 0. So the forward derivatives cost one forward dynamics, one call of RNEA-DERIVATIVES, which also returns MM, and a product with M−1M^{-1}.

Example

Take the planar arm with two revolute joints about zz, links of 1 m and point masses of 1 kg at the link ends. Its inverse dynamics in closed form, with c2=cos⁡q2c_2 = \cos q_2 and s2=sin⁡q2s_2 = \sin q_2 and without gravity, is

τ1=(3+2c2)q¨1+(1+c2)q¨2−s2(2q˙1q˙2+q˙22),τ2=(1+c2)q¨1+q¨2+s2q˙12.\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), \qquad \tau_2 = (1 + c_2)\ddot q_1 + \ddot q_2 + s_2 \dot q_1^2 .

At q=(0,π/2)q = (0, \pi/2), q˙=(1,1)\dot q = (1, 1) rad/s and q¨=0\ddot q = 0, the algorithm returns τ=(−3,1)\tau = (-3, 1) N m and

∂τ∂q˙=(−2−420),∂τ∂q=0,∂τ∂q¨=M=(3111).\frac{\partial \tau}{\partial \dot q} = \begin{pmatrix} -2 & -4 \\ 2 & 0 \end{pmatrix}, \qquad \frac{\partial \tau}{\partial q} = 0, \qquad \frac{\partial \tau}{\partial \ddot q} = M = \begin{pmatrix} 3 & 1 \\ 1 & 1 \end{pmatrix}.

The closed form gives the same: ∂τ1/∂q˙1=−2s2q˙2=−2\partial\tau_1/\partial\dot q_1 = -2 s_2 \dot q_2 = -2, ∂τ1/∂q˙2=−2s2(q˙1+q˙2)=−4\partial\tau_1/\partial\dot q_2 = -2 s_2(\dot q_1 + \dot q_2) = -4, ∂τ2/∂q˙1=2s2q˙1=2\partial\tau_2/\partial\dot q_1 = 2 s_2 \dot q_1 = 2, and τ2\tau_2 does not depend on q˙2\dot q_2. The derivative by qq is 0 here, because τ\tau does not depend on q1q_1 without gravity, and ∂τ/∂q2\partial\tau/\partial q_2 has the factors s2q¨s_2 \ddot q and c2q˙2c_2 \dot q^2, which are both 0 at this state.

For the forward dynamics at the same qq and q˙\dot q with τ=0\tau = 0, the articulated-body algorithm gives q¨=(2,−3)\ddot q = (2, -3) rad/s2^2. At this q¨\ddot q, the inverse dynamics derivative by qq is no longer 0: ∂ID/∂q=(0−10−2)\partial \mathrm{ID}/\partial q = \begin{pmatrix} 0 & -1 \\ 0 & -2 \end{pmatrix}. With M−1=12(1−1−13)M^{-1} = \tfrac12 \begin{pmatrix} 1 & -1 \\ -1 & 3 \end{pmatrix},

∂q¨∂q=(0−0.502.5),∂q¨∂q˙=(22−4−2),∂q¨∂τ=(0.5−0.5−0.51.5).\frac{\partial \ddot q}{\partial q} = \begin{pmatrix} 0 & -0.5 \\ 0 & 2.5 \end{pmatrix}, \qquad \frac{\partial \ddot q}{\partial \dot q} = \begin{pmatrix} 2 & 2 \\ -4 & -2 \end{pmatrix}, \qquad \frac{\partial \ddot q}{\partial \tau} = \begin{pmatrix} 0.5 & -0.5 \\ -0.5 & 1.5 \end{pmatrix}.

The tests check the inverse dynamics values above, and they compare the inverse and forward derivatives on random trees of up to 7 joints with central finite differences (h=10−6h = 10^{-6}, tolerance 10−610^{-6}).

With gravity 9.819.81 m/s2^2 along −y-y in the plane, at 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 algorithm gives ∂τ/∂q=(−14.052936816−10.371045548−8.254830361−9.352055189)\partial\tau/\partial q = \begin{pmatrix} -14.052936816 & -10.371045548 \\ -8.254830361 & -9.352055189 \end{pmatrix} and ∂τ/∂q˙=(1.5461224490.9019047620.6442176870)\partial\tau/\partial\dot q = \begin{pmatrix} 1.546122449 & 0.901904762 \\ 0.644217687 & 0 \end{pmatrix}.

Correctness

The derivative of a composition is the composition of the derivatives, so it is enough to differentiate each line of the RNEA in order. Two facts make this simple. First, XiX_i depends only on qiq_i, and the two identities above give its derivative in closed form. Second, viv_i and aia_i depend only on the joints in anc(i)\mathrm{anc}(i), and fif_i depends only on the joints that are on a common path with ii, so all other derivatives are 0 and need no storage. By induction over the forward pass, the stored derivatives of viv_i, aia_i and the body wrench are exact; by backward induction, the derivatives of the transmitted wrench fif_i are complete when the loop reaches ii, because all children have larger indices. The derivative of τi=SiTfi\tau_i = S_i^T f_i is SiT∂fiS_i^T \partial f_i, since SiS_i is constant. The forward dynamics formulas follow from the chain rule applied to ID(q,q˙,FD(q,q˙,τ))=τ\mathrm{ID}(q, \dot q, \mathrm{FD}(q, \dot q, \tau)) = \tau. The correctness proof of this page gives each step.

Proof: The differentiated Newton-Euler recursion returns the partial derivatives of the 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. anc(i)\mathrm{anc}(i) is the set of ii and its ancestors, and ν(i)\nu(i) is the set of ii and its descendants. We write ∂k\partial_k for the partial derivative by one coordinate uku_k, where uu is qq, q˙\dot q or q¨\ddot q. The operators satisfy crm(a)b=−crm(b)a\mathrm{crm}(a) b = -\mathrm{crm}(b) a and crf(a)=−crm(a)T\mathrm{crf}(a) = -\mathrm{crm}(a)^T.

Lemma 1 (the two identities). For a motion vector mm and a force vector ff that do not depend on qiq_i,

∂(Xim)∂qi=crm(Xim) Si,∂(XiTf)∂qi=XiT crf(Si) f.\frac{\partial (X_i m)}{\partial q_i} = \mathrm{crm}(X_i m)\, S_i, \qquad \frac{\partial (X_i^T f)}{\partial q_i} = X_i^T\, \mathrm{crf}(S_i)\, f .

Proof. The joint pose is T(qi)=Titreee[Si]qiT(q_i) = T^{\mathrm{tree}}_i e^{[S_i] q_i}, so T(qi+h)−1=e−[Si]hT(qi)−1T(q_i + h)^{-1} = e^{-[S_i] h} T(q_i)^{-1} and Xi(qi+h)=Ad(e−[Si]h)Xi(qi)X_i(q_i + h) = \mathrm{Ad}(e^{-[S_i]h}) X_i(q_i). The derivative at h=0h = 0 is ∂Xi/∂qi=−crm(Si)Xi\partial X_i / \partial q_i = -\mathrm{crm}(S_i) X_i. Then ∂(Xim)/∂qi=−crm(Si)Xim=crm(Xim)Si\partial(X_i m)/\partial q_i = -\mathrm{crm}(S_i) X_i m = \mathrm{crm}(X_i m) S_i. For the second identity, ∂XiT/∂qi=−XiTcrm(Si)T=XiTcrf(Si)\partial X_i^T / \partial q_i = -X_i^T \mathrm{crm}(S_i)^T = X_i^T \mathrm{crf}(S_i). □\square

Lemma 2 (dependence). viv_i and aia_i depend only on qkq_k, q˙k\dot q_k and q¨k\ddot q_k with k∈anc(i)k \in \mathrm{anc}(i). The joint wrench fif_i and τi\tau_i depend only on the coordinates of joints kk with k∈anc(i)k \in \mathrm{anc}(i) or k∈ν(i)k \in \nu(i).

Proof. Lines L4 and L5 of the RNEA use only the parent, so the first claim follows by induction on ii. The body wrench flBf^B_l depends on the coordinates of anc(l)\mathrm{anc}(l), and fif_i adds the flBf^B_l of l∈ν(i)l \in \nu(i) through transforms of joints in ν(i)\nu(i). A joint kk in anc(l)\mathrm{anc}(l) for some l∈ν(i)l \in \nu(i) is in anc(i)\mathrm{anc}(i) or in ν(i)\nu(i). □\square

So every derivative that the algorithm does not store in a dict is 0.

Lemma 3 (the forward pass). After line L7 for body ii, the dicts hold, for every k∈anc(i)k \in \mathrm{anc}(i), the derivatives ∂kvi\partial_k v_i, ∂kai\partial_k a_i and ∂kfiB\partial_k f^B_i by qkq_k, by q˙k\dot q_k and by q¨k\ddot q_k.

Proof. By induction on ii. Differentiate the RNEA lines vi=Xivλ+Siq˙iv_i = X_i v_{\lambda} + S_i \dot q_i, ai=Xiaλ+Siq¨i+crm(vi)Siq˙ia_i = X_i a_{\lambda} + S_i \ddot q_i + \mathrm{crm}(v_i) S_i \dot q_i and fiB=Iiai+crf(vi)Iivif^B_i = I_i a_i + \mathrm{crf}(v_i) I_i v_i, where λ=λ(i)\lambda = \lambda(i).

  • For k∈anc(λ)k \in \mathrm{anc}(\lambda), XiX_i, qiq_i and q˙i\dot q_i do not change with uku_k, so ∂k(Xivλ)=Xi ∂kvλ\partial_k (X_i v_\lambda) = X_i\, \partial_k v_\lambda and the same for aa. This is line L3, with the dicts of the parent from the induction hypothesis.
  • For k=ik = i and u=qu = q: vλv_\lambda and aλa_\lambda do not depend on qiq_i, so Lemma 1 gives ∂i(Xivλ)=crm(Xivλ)Si\partial_i (X_i v_\lambda) = \mathrm{crm}(X_i v_\lambda) S_i and ∂i(Xiaλ)=crm(Xiaλ)Si\partial_i (X_i a_\lambda) = \mathrm{crm}(X_i a_\lambda) S_i. This is line L4.
  • For k=ik = i and u=q˙u = \dot q: ∂ivi=Si\partial_i v_i = S_i, and the last term of aia_i gives crm(vi)Si\mathrm{crm}(v_i) S_i from the factor q˙i\dot q_i. This is line L5. For u=q¨u = \ddot q: ∂iai=Si\partial_i a_i = S_i.
  • For every kk and u∈{q,q˙}u \in \{q, \dot q\}, the last term of aia_i also gives crm(∂kvi)Siq˙i\mathrm{crm}(\partial_k v_i) S_i \dot q_i. This is line L6. For k=ik = i and u=q˙u = \dot q this term is crm(Si)Siq˙i=0\mathrm{crm}(S_i) S_i \dot q_i = 0, so it does no harm.
  • The product rule on fiBf^B_i gives ∂kfiB=Ii ∂kai+crf(∂kvi)Iivi+crf(vi)Ii ∂kvi\partial_k f^B_i = I_i\, \partial_k a_i + \mathrm{crf}(\partial_k v_i) I_i v_i + \mathrm{crf}(v_i) I_i\, \partial_k v_i. This is line L7. For u=q¨u = \ddot q the velocities do not change, and only Ii ∂kaiI_i\, \partial_k a_i is left. □\square

Theorem. Line L14 returns τ=RNEA(q,q˙,q¨)\tau = \mathrm{RNEA}(q, \dot q, \ddot q), ∂τ/∂q\partial \tau / \partial q, ∂τ/∂q˙\partial \tau / \partial \dot q and ∂τ/∂q¨=M(q)\partial \tau / \partial \ddot q = M(q).

Proof. The value τ\tau is the RNEA (its correctness proof applies line by line). The backward pass of the RNEA computes fi=fiB+∑c: λ(c)=iXcTfcf_i = f^B_i + \sum_{c:\, \lambda(c) = i} X_c^T f_c and τi=SiTfi\tau_i = S_i^T f_i. Differentiate:

∂kfi=∂kfiB+∑c(XcT ∂kfc+[k=c] [u=q]  XcT crf(Sc)fc),\partial_k f_i = \partial_k f^B_i + \sum_c \Big( X_c^T\, \partial_k f_c + [k = c]\,[u = q]\; X_c^T\, \mathrm{crf}(S_c) f_c \Big),

by the product rule and Lemma 1, because XcX_c depends on qcq_c only. We show by backward induction on ii that, when the loop of line L8 reaches ii, the dicts of fif_i hold ∂kfi\partial_k f_i for every kk allowed by Lemma 2, and fif_i is complete. The dicts start with ∂kfiB\partial_k f^B_i by Lemma 3. Each child c>ic > i was handled before ii; at that time fcf_c and its dicts were complete by the induction hypothesis, and lines L11 to L13 added the three terms of the sum. Nothing else changes these values.

Then ∂kτi=SiT ∂kfi\partial_k \tau_i = S_i^T\, \partial_k f_i because SiS_i is constant, which is line L9. Every entry that the dicts do not hold is 0 by Lemma 2, and the output matrices start at 0. Since τ\tau is affine in q¨\ddot q with the matrix M(q)M(q), ∂τ/∂q¨=M(q)\partial\tau/\partial\ddot q = M(q). ■\blacksquare

Corollary (forward dynamics). Let FD(q,q˙,τ)\mathrm{FD}(q, \dot q, \tau) be the solution q¨\ddot q of RNEA(q,q˙,q¨)=τ\mathrm{RNEA}(q, \dot q, \ddot q) = \tau. Then, at q¨=FD(q,q˙,τ)\ddot q = \mathrm{FD}(q, \dot q, \tau),

∂FD∂q=−M−1∂RNEA∂q,∂FD∂q˙=−M−1∂RNEA∂q˙,∂FD∂τ=M−1.\frac{\partial \mathrm{FD}}{\partial q} = -M^{-1} \frac{\partial \mathrm{RNEA}}{\partial q}, \qquad \frac{\partial \mathrm{FD}}{\partial \dot q} = -M^{-1} \frac{\partial \mathrm{RNEA}}{\partial \dot q}, \qquad \frac{\partial \mathrm{FD}}{\partial \tau} = M^{-1}.

Proof. The identity RNEA(q,q˙,FD(q,q˙,τ))=τ\mathrm{RNEA}(q, \dot q, \mathrm{FD}(q, \dot q, \tau)) = \tau holds for all arguments. Differentiate it by qq with the chain rule: ∂RNEA/∂q+M ∂FD/∂q=0\partial \mathrm{RNEA}/\partial q + M\, \partial \mathrm{FD}/\partial q = 0. The same holds for q˙\dot q. By τ\tau: M ∂FD/∂τ=1M\, \partial \mathrm{FD}/\partial \tau = 1. MM is invertible because it is positive definite. ■\blacksquare

Cost. For body ii the dicts of the forward pass have depth(i)\mathrm{depth}(i) entries, and each entry costs a fixed number of 6×66 \times 6 products. In the backward pass, the dict of fif_i holds the joints of anc(i)\mathrm{anc}(i) and ν(i)\nu(i), and each entry is moved once to the parent. The sum over all bodies of these sizes is the number of pairs (i,k)(i, k) on a common path, which is at most 2∑idepth(i)2 \sum_i \mathrm{depth}(i). So the time is O(nd)O(n d) for a tree of depth dd and Θ(n2)\Theta(n^2) for a serial chain.

Complexity

In the real RAM, body ii stores depth(i)\mathrm{depth}(i) derivatives of each of viv_i and aia_i for each of qq, q˙\dot q and q¨\ddot q, and each costs a fixed number of 6×66 \times 6 products. In the backward pass, the derivatives of fif_i cover the joints on a common path with ii, and each one is moved to the parent once. The number of such pairs (i,k)(i, k) is at most 2∑idepth(i)2\sum_i \mathrm{depth}(i), so the time is O(nd)O(n d) for a tree of depth dd and Θ(n2)\Theta(n^2) for a serial chain. This is the order of the number of nonzero entries of the output, so it is optimal in order. The extra space is Θ(nd)\Theta(n d) for the stored derivatives. An implementation that stores the output as dense matrices also spends Θ(n2)\Theta(n^2) to set them to zero.

Finite differences need 2n+12n + 1 or 4n+14n + 1 calls of the RNEA for the two derivatives, which is also Θ(n2)\Theta(n^2), but with a much larger constant, and they lose about half of the digits. The forward dynamics derivatives add a forward dynamics in Θ(n)\Theta(n), the inverse M−1M^{-1} and two products of n×nn \times n matrices, which is O(n3)O(n^3) when done densely.

Carpentier and Mansard (2018) report measurements in their library Pinocchio on a 2.2 GHz Intel Core i7. For a KUKA arm, the HyQ quadruped and the Atlas humanoid, the inverse dynamics took 1.20, 2.14 and 5.51 µs, its analytical derivatives 3.34, 7.01 and 16.72 µs, and finite differences of the inverse dynamics 21.26, 88.52 and 452.46 µs. The analytical derivatives of the forward dynamics took 5.78, 14.24 and 45.20 µs. These are measurements on one machine, not bounds.

Properties

  • Exact. The derivatives are exact up to floating-point rounding. Central finite differences with a step hh have an error of order h2h^2 plus a rounding error of order ε/h\varepsilon/h.
  • ∂τ/∂q¨=M(q)\partial\tau/\partial\ddot q = M(q). The algorithm returns the joint-space inertia matrix as a side product, the same matrix that the composite rigid body algorithm computes.
  • Sparsity follows the tree. ∂τi/∂qk\partial\tau_i/\partial q_k and ∂τi/∂q˙k\partial\tau_i/\partial\dot q_k are 0 when joints ii and kk are on different branches, the same pattern as the branch-induced sparsity of MM.
  • Gravity enters only ∂τ/∂q\partial\tau/\partial q. Gravity is a base acceleration that does not depend on q˙\dot q, so it changes ∂τ/∂q\partial\tau/\partial q only.
  • Linear in q¨\ddot q. ∂τ/∂q\partial\tau/\partial q is affine in q¨\ddot q, and ∂τ/∂q˙\partial\tau/\partial\dot q does not depend on q¨\ddot q.

Variants and improvements

  • Matrix form. Carpentier and Mansard (2018) write the same recursion with 6×n6 \times n matrices per body in place of one derivative per joint, which suits vectorized linear algebra.
  • Automatic differentiation. Forward or reverse mode automatic differentiation of an RNEA code gives the same numbers, and it works for any code, but it has a larger constant.
  • Contact dynamics. The same idea extends to constrained and contact dynamics, where the derivatives of the contact forces are needed for contact-implicit trajectory optimization.
  • Floating base. For a free base, the configuration lies on a Lie group, and the derivative by qq is taken in the tangent space; see floating-base dynamics.
  • Second order. Some optimizers need the second derivatives of the dynamics; they can be obtained by differentiating the recursion again, at a higher cost.

When to use it

Use these derivatives inside gradient-based trajectory optimization, control-limited DDP, nonlinear MPC and linearization of a robot model around a trajectory. They also give the Jacobians of the dynamics for an extended Kalman filter that estimates joint states. For one-time checks or very small arms, finite differences are fine. For a robot with a floating base and many joints, the analytical derivatives are the fastest exact choice.

Pitfalls

  • Forward derivatives at the wrong acceleration. ∂FD/∂q=−M−1 ∂ID/∂q\partial\mathrm{FD}/\partial q = -M^{-1}\, \partial\mathrm{ID}/\partial q needs ∂ID/∂q\partial\mathrm{ID}/\partial q at q¨=FD(q,q˙,τ)\ddot q = \mathrm{FD}(q, \dot q, \tau), not at q¨=0\ddot q = 0. The example above shows the difference.
  • The derivative of XiTX_i^T. Forgetting line L12 drops the term XiTcrf(Si)fiX_i^T \mathrm{crf}(S_i) f_i and gives wrong entries ∂τj/∂qi\partial\tau_j/\partial q_i for the ancestors jj of ii, but correct diagonal entries.
  • The sign convention of the joint transform. The identities hold for T=Ttreee[Si]qiT = T^{\mathrm{tree}} e^{[S_i]q_i} with SiS_i in the child frame. With the exponential on the left, SiS_i is in the parent frame, and the identities change.
  • Finite differences as the reference. They agree only to about 10−610^{-6} to 10−810^{-8} in double precision. A test needs a tolerance to match.
  • A claim of O(n)O(n). The derivatives of a serial chain have Θ(n2)\Theta(n^2) nonzero entries, so no algorithm can output them in O(n)O(n) time.

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
rigid_body_dynamics_derivatives.py 188 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rigid-body-dynamics-derivatives/. The authors are listed in prov/M6C9BY.jsonl.
"""Analytical derivatives of inverse and forward dynamics (Carpentier and Mansard, 2018).

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.

The derivatives use two identities. If X_i depends on q_i as above, then
d(X_i m)/dq_i = crm(X_i m) S_i for a motion vector m, and
d(X_i^T f)/dq_i = X_i^T crf(S_i) f for a force vector f.

A derivative of a body quantity is stored as a dict from a joint index k
to the 6-vector of the partial derivative by the k-th coordinate. The
velocity and the acceleration of body i depend only on the joints on the
path from i to the root, so their dicts hold at most depth(i) entries.
"""

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 _map(xs, d):
    """Return {k: X d[k]} for a dict d of motion vectors."""
    return {k: rbm.matvec(xs, vec) for k, vec in d.items()}


def _add_into(d, k, vec):
    d[k] = rbm.add(d[k], vec) if k in d else vec


def rnea(model, q, qd, qdd, gravity=GRAVITY):
    """Return tau = M(q) qdd + C(q, qd) qd + g(q) by the recursive Newton-Euler algorithm."""
    return rnea_derivatives(model, q, qd, qdd, gravity)[0]


def rnea_derivatives(model, q, qd, qdd, gravity=GRAVITY):
    """Return (tau, dtau/dq, dtau/dqd, dtau/dqdd) at (q, qd, qdd).

    The three Jacobians are n x n lists of rows; dtau/dqdd is the
    joint-space inertia matrix M(q).
    """
    n = model.n
    if not len(q) == len(qd) == len(qdd) == n:
        raise ValueError("q, qd and qdd need one entry per joint")
    zero = [0.0] * 6
    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
    dv_q, da_q, dv_qd, da_qd, da_qdd = ([None] * n for _ in range(5))
    df_q, df_qd, df_qdd = [None] * n, [None] * n, [None] * n
    for i in range(n):  # @line L1
        p = model.parent[i]
        s = model.screw[i]
        inertia = model.inertia[i]
        xs[i] = joint_transform(model, i, q[i])  # @line L2
        vj = rbm.scale(s, qd[i])
        xv = rbm.matvec(xs[i], zero if p < 0 else v[p])
        xa = rbm.matvec(xs[i], a_base if p < 0 else a[p])
        v[i] = rbm.add(xv, vj)
        a[i] = rbm.add(rbm.add(xa, rbm.scale(s, qdd[i])), cross_motion(v[i], vj))
        iv = rbm.matvec(inertia, v[i])
        f[i] = rbm.add(rbm.matvec(inertia, a[i]), cross_force(v[i], iv))
        # Derivatives by the joints above i: carried over from the parent.
        dv_q[i] = {} if p < 0 else _map(xs[i], dv_q[p])  # @line L3
        da_q[i] = {} if p < 0 else _map(xs[i], da_q[p])
        dv_qd[i] = {} if p < 0 else _map(xs[i], dv_qd[p])
        da_qd[i] = {} if p < 0 else _map(xs[i], da_qd[p])
        da_qdd[i] = {} if p < 0 else _map(xs[i], da_qdd[p])
        # The new column i.
        dv_q[i][i] = cross_motion(xv, s)  # @line L4
        da_q[i][i] = cross_motion(xa, s)
        dv_qd[i][i] = list(s)  # @line L5
        da_qd[i][i] = cross_motion(v[i], s)
        da_qdd[i][i] = list(s)
        for k in dv_q[i]:  # @line L6
            da_q[i][k] = rbm.add(da_q[i][k], cross_motion(dv_q[i][k], vj))
            da_qd[i][k] = rbm.add(da_qd[i][k], cross_motion(dv_qd[i][k], vj))
        df_q[i], df_qd[i] = {}, {}
        for dv, da, df in ((dv_q[i], da_q[i], df_q[i]), (dv_qd[i], da_qd[i], df_qd[i])):  # @line L7
            for k in dv:
                df[k] = rbm.add(rbm.add(rbm.matvec(inertia, da[k]), cross_force(dv[k], iv)),
                                cross_force(v[i], rbm.matvec(inertia, dv[k])))
        df_qdd[i] = {k: rbm.matvec(inertia, vec) for k, vec in da_qdd[i].items()}
    tau = [0.0] * n
    d_q, d_qd, d_qdd = rbm.zeros(n, n), rbm.zeros(n, n), rbm.zeros(n, n)
    for i in range(n - 1, -1, -1):  # @line L8
        s = model.screw[i]
        tau[i] = rbm.dot(s, f[i])
        for out, df in ((d_q, df_q[i]), (d_qd, df_qd[i]), (d_qdd, df_qdd[i])):  # @line L9
            for k, vec in df.items():
                out[i][k] = rbm.dot(s, vec)
        p = model.parent[i]
        if p >= 0:  # @line L10
            xt = rbm.transpose(xs[i])
            for src, dst in ((df_q[i], df_q[p]), (df_qd[i], df_qd[p]), (df_qdd[i], df_qdd[p])):  # @line L11
                for k, vec in src.items():
                    _add_into(dst, k, rbm.matvec(xt, vec))
            _add_into(df_q[p], i, rbm.matvec(xt, cross_force(s, f[i])))  # @line L12
            f[p] = rbm.add(f[p], rbm.matvec(xt, f[i]))  # @line L13
    return tau, d_q, d_qd, d_qdd  # @line L14


def forward_dynamics_derivatives(model, q, qd, tau, gravity=GRAVITY):
    """Return (qdd, dqdd/dq, dqdd/dqd, dqdd/dtau) for qdd = FD(q, qd, tau).

    qdd solves M qdd = tau - C qd - g. Then dFD/du = -M^(-1) dID/du at
    (q, qd, qdd) for u = q and u = qd, and dFD/dtau = M^(-1).
    """
    n = model.n
    bias, _, _, m = rnea_derivatives(model, q, qd, [0.0] * n, gravity)
    qdd = rbm.solve(m, rbm.sub(tau, bias))
    _, d_q, d_qd, _ = rnea_derivatives(model, q, qd, qdd, gravity)
    m_inv = rbm.inv(m)
    return qdd, rbm.scale(rbm.mul(m_inv, d_q), -1.0), rbm.scale(rbm.mul(m_inv, d_qd), -1.0), m_inv
test_rigid_body_dynamics_derivatives.py 151 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/rigid-body-dynamics-derivatives/. The authors are listed in prov/M6C9BY.jsonl.
"""Tests of the analytical derivatives against central finite differences (h = 1e-6, tolerance 1e-6)."""

import math
import random

import pytest

import rbm
from rigid_body_dynamics_derivatives import (
    GRAVITY,
    Model,
    forward_dynamics_derivatives,
    rnea,
    rnea_derivatives,
    spatial_inertia,
)

Z_AXIS = [0.0, 0.0, 1.0, 0.0, 0.0, 0.0]
G_PLANE = [0.0, -9.81, 0.0]
TOL = 1e-6


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 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, 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 maxdiff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def numeric_id_jacobians(model, q, qd, qdd, g):
    return (rbm.num_jacobian(lambda x: rnea(model, x, qd, qdd, g), q),
            rbm.num_jacobian(lambda x: rnea(model, q, x, qdd, g), qd),
            rbm.num_jacobian(lambda x: rnea(model, q, qd, x, g), qdd))


def test_2r_against_closed_form():
    rng = random.Random(1)
    model = planar_2r()
    for _ in range(10):
        q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
        qd = [rng.uniform(-2, 2) for _ in range(2)]
        qdd = [rng.uniform(-3, 3) for _ in range(2)]
        tau, d_q, d_qd, m = rnea_derivatives(model, q, qd, qdd, G_PLANE)
        assert max(abs(x - y) for x, y in zip(tau, closed_form_2r(q, qd, qdd))) < 1e-9
        assert maxdiff(d_q, rbm.num_jacobian(lambda x: closed_form_2r(x, qd, qdd), q)) < TOL
        assert maxdiff(d_qd, rbm.num_jacobian(lambda x: closed_form_2r(q, x, qdd), qd)) < TOL
        c2 = math.cos(q[1])
        assert maxdiff(m, [[3 + 2 * c2, 1 + c2], [1 + c2, 1.0]]) < 1e-12


def test_2r_hand_value():
    """At q = (0, pi/2), qd = (1, 1), qdd = 0 and no gravity: dtau/dqd = [[-2, -4], [2, 0]], dtau/dq = 0."""
    _, d_q, d_qd, _ = rnea_derivatives(planar_2r(), [0.0, math.pi / 2], [1.0, 1.0], [0.0, 0.0], [0.0] * 3)
    assert maxdiff(d_qd, [[-2.0, -4.0], [2.0, 0.0]]) < 1e-12
    assert maxdiff(d_q, [[0.0, 0.0], [0.0, 0.0]]) < 1e-12


def test_inverse_dynamics_derivatives_on_random_trees():
    rng = random.Random(2)
    for n in (1, 5, 7):
        model = random_model(rng, n)
        q = [rng.uniform(-2, 2) for _ in range(n)]
        qd = [rng.uniform(-1.5, 1.5) for _ in range(n)]
        qdd = [rng.uniform(-3, 3) for _ in range(n)]
        tau, d_q, d_qd, m = rnea_derivatives(model, q, qd, qdd)
        n_q, n_qd, n_qdd = numeric_id_jacobians(model, q, qd, qdd, GRAVITY)
        assert maxdiff(d_q, n_q) < TOL
        assert maxdiff(d_qd, n_qd) < TOL
        assert maxdiff(m, n_qdd) < TOL
        assert maxdiff(m, rbm.transpose(m)) < 1e-12


def test_forward_dynamics_derivatives():
    rng = random.Random(3)
    model = random_model(rng, 6, [-1, 0, 1, 1, 3, -1])

    def fd(q, qd, tau):
        n = model.n
        bias = rnea(model, q, qd, [0.0] * n)
        m = rnea_derivatives(model, q, qd, [0.0] * n)[3]
        return rbm.solve(m, rbm.sub(tau, bias))

    q = [rng.uniform(-2, 2) for _ in range(6)]
    qd = [rng.uniform(-1, 1) for _ in range(6)]
    tau = [rng.uniform(-3, 3) for _ in range(6)]
    qdd, d_q, d_qd, d_tau = forward_dynamics_derivatives(model, q, qd, tau)
    assert max(abs(x - y) for x, y in zip(rnea(model, q, qd, qdd), tau)) < 1e-9
    assert maxdiff(d_q, rbm.num_jacobian(lambda x: fd(x, qd, tau), q)) < TOL
    assert maxdiff(d_qd, rbm.num_jacobian(lambda x: fd(q, x, tau), qd)) < TOL
    assert maxdiff(d_tau, rbm.num_jacobian(lambda x: fd(q, qd, x), tau)) < TOL


def test_sparsity_follows_the_tree():
    """dtau_i/dq_k and dtau_i/dqd_k are 0 unless i and k lie on one path to the root."""
    rng = random.Random(4)
    parents = [-1, 0, 1, 0, 3, -1]
    model = random_model(rng, 6, parents)
    _, d_q, d_qd, _ = rnea_derivatives(model, [rng.uniform(-2, 2) for _ in range(6)],
                                       [rng.uniform(-1, 1) for _ in range(6)], [0.5] * 6)

    def path(i):
        out = set()
        while i >= 0:
            out.add(i)
            i = parents[i]
        return out

    for i in range(6):
        for k in range(6):
            if not (i in path(k) or k in path(i)):
                assert d_q[i][k] == 0.0 and d_qd[i][k] == 0.0


def test_bad_input():
    with pytest.raises(ValueError):
        rnea_derivatives(planar_2r(), [0.0], [0.0, 0.0], [0.0, 0.0])

History

Before 2018, robot software computed the derivatives of the dynamics by finite differences or by automatic differentiation of the RNEA, and the Euler-Lagrange form gave symbolic derivatives for small arms. Carpentier and Mansard (2018) differentiated the RNEA in closed form with spatial algebra, derived the forward dynamics derivatives from it, and released the method in the open-source library Pinocchio. Their measurements showed the analytical derivatives several times faster than finite differences, with the gap growing with the size of the robot.

References

  1. Justin Carpentier and Nicolas Mansard, Analytical derivatives of rigid body dynamics algorithms, Robotics, Science and Systems XIV, 2018, Sections II to V (spatial algebra, the derivatives of the recursive Newton-Euler algorithm, the derivatives of forward dynamics, and the benchmarks)
  2. Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 2 (spatial vector algebra, the cross products and the derivatives of spatial vectors) and Chapter 5 (inverse dynamics)
  3. 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 (the recursion that is differentiated)

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.forward
  • a full proof of time.inverse
  • 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