Algorithm Search⌘K

Algorithmcore

Composite rigid body algorithm

Also called CRBA, Walker-Orin method.

Builds the joint-space inertia matrix from the inertias of the subtrees beyond each joint, in O(n d) time for a tree of depth d, which is O(n^2) for a serial chain.

Time
Θ(n d) worst
Space
Θ(n) 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
Michael W. Walker, David E. Orin, 1982

The composite rigid body algorithm (CRBA) computes the joint-space inertia matrix M(q)M(q) of a robot that is a serial chain or a tree of rigid bodies. It uses one idea: when only joint jj accelerates, everything beyond joint jj moves as one rigid body, the composite body of that subtree. The algorithm sums the spatial inertias of each subtree from the tips inward, and then reads each entry of MM as a product of a composite inertia with two joint axes. Together with one call of the recursive Newton-Euler algorithm for the bias forces and a Cholesky factorization, it solves the forward dynamics problem. The articulated-body algorithm solves the same problem in Θ(n)\Theta(n) without forming MM; the CRBA costs more for long chains but is often faster for the small trees of real robots.

In plain words

Picture a robot arm with all its joints locked except one. If you push that one joint, the part of the arm beyond it swings as one stiff piece. How hard that piece resists the push depends on its total mass and how far the mass is from the joint. The algorithm finds this resistance for every joint. It starts at the tip, where the stiff piece is only the last link. Moving inward, each piece is the next link plus the piece that hangs on it, so the work done for one joint is reused for the next. The resistance felt at a joint when another joint moves is found from the same stiff pieces. The result is a table of numbers that tells how the motion of every joint couples to every other joint.

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, as in Featherstone (2008).

Input: the model and q∈Rnq \in \mathbb{R}^n. Output: the symmetric matrix H=M(q)∈Rn×nH = M(q) \in \mathbb{R}^{n \times n} of the manipulator equation M(q)q¨+C(q,q˙)q˙+g(q)=τM(q)\ddot q + C(q, \dot q)\dot q + g(q) = \tau. Featherstone writes HH for this matrix; here HH and MM are the same.

For the forward dynamics problem, the CRBA is one step: compute the bias b=C(q,q˙)q˙+g(q)b = C(q, \dot q)\dot q + g(q) as RNEA(q,q˙,0)\mathrm{RNEA}(q, \dot q, 0), compute HH by the CRBA, and solve Hq¨=τ−bH \ddot q = \tau - b.

The algorithm

  1. CRBA(model, q)
  2. 1for i ← 1 to n do X_i ← Ad(T_{λ(i),i}(q_i)^-1) ; I^c_i ← I_i ; H ← 0
  3. 2for i ← n downto 1 do
  4. 3if λ(i) ≠ 0 then I^c_λ(i) ← I^c_λ(i) + X_i^T I^c_i X_i
  5. 4F ← I^c_i S_i ▷ the wrench to accelerate the subtree of i
  6. 5H_ii ← S_i^T F
  7. 6j ← i
  8. 7while λ(j) ≠ 0 do ▷ climb to the base
  9. 8F ← X_j^T F ; j ← λ(j)
  10. 9H_ij ← S_j^T F ; H_ji ← H_ij
  11. 10return H

IicI^c_i is the composite inertia of the subtree of body ii, in the coordinates of {i}\{i\}. Line L3 moves it into the frame of the parent and adds it to the parent's composite inertia. Because every child has a larger index than its parent, the loop of line L2 completes IicI^c_i before it uses it.

Line L4 has a physical meaning. If only joint ii accelerates, at unit rate, with no velocity and no gravity, the subtree of ii moves as one rigid body with the acceleration SiS_i, and F=IicSiF = I^c_i S_i is the wrench that joint ii must transmit. Joint ii feels SiTFS_i^T F of it (line L5). Every joint jj between ii and the base must transmit the same wrench, moved into its own frame (line L8), and feels SjTFS_j^T F of it (line L9). So HjiH_{ji} is the force at joint jj per unit acceleration of joint ii. Entries for pairs of joints on different branches are never written and stay 0.

Example

Take the planar arm with two revolute joints, links of 1 m, and point masses of 1 kg at the link ends. 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).

  • i=2i = 2: I2c=I2I^c_2 = I_2. Line L4 gives F=I2S2=(0,0,1, 0,1,0)F = I_2 S_2 = (0, 0, 1,\ 0, 1, 0): an angular momentum of 1 about the joint and a linear part of 1 N along yy of {2}\{2\}. Line L5 gives H22=1H_{22} = 1.
  • Line L8 moves FF into {1}\{1\}: X2TF=(0,0,1, −1,0,0)X_2^T F = (0, 0, 1,\ -1, 0, 0). Line L9 gives H12=H21=1H_{12} = H_{21} = 1.
  • Line L3 for i=2i = 2 also made I1c=I1+X2TI2X2I^c_1 = I_1 + X_2^T I_2 X_2, the inertia of both masses about joint 1. Its third column is (0,0,3, −1,2,0)(0, 0, 3,\ -1, 2, 0): the two masses at (1,0)(1, 0) and (1,1)(1, 1) m have a moment of inertia 1+2=31 + 2 = 3 kg m2^2 about the zz axis through joint 1.
  • i=1i = 1: line L4 gives F=I1cS1=(0,0,3, −1,2,0)F = I^c_1 S_1 = (0, 0, 3,\ -1, 2, 0) and line L5 gives H11=3H_{11} = 3.

So M=(3111)M = \begin{pmatrix} 3 & 1 \\ 1 & 1 \end{pmatrix}, which is the closed form (3+2c21+c21+c21)\begin{pmatrix} 3 + 2c_2 & 1 + c_2 \\ 1 + c_2 & 1 \end{pmatrix} at c2=0c_2 = 0.

For forward dynamics, take q=(0.3,0.7)q = (0.3, 0.7), q˙=(0.5,−1.2)\dot q = (0.5, -1.2) rad/s, gravity 9.819.81 m/s2^2 along −y-y in the plane, and τ=(31.183981854,7.991104417)\tau = (31.183981854, 7.991104417) N m. The RNEA gives the bias bb, and the Cholesky solve of Mq¨=τ−bM\ddot q = \tau - b gives q¨=(2,−1)\ddot q = (2, -1) rad/s2^2 to rounding, which is the motion that the RNEA example produced this τ\tau from.

Correctness

With q˙=0\dot q = 0 and no gravity, the RNEA gives τ=M(q)q¨\tau = M(q)\ddot q, and it shows that τi\tau_i collects the wrenches IlalI_l a_l of the bodies ll in the subtree of ii, where ala_l sums the accelerations Skq¨kS_k \ddot q_k of the joints kk on the path from ll to the base. The coefficient of q¨j\ddot q_j in τi\tau_i is then a sum over the bodies that are beyond both ii and jj. If jj is on the path from ii to the base, this set is the subtree of ii, and the sum is SiTIicXi←jSjS_i^T I^c_i X_{i \leftarrow j} S_j, where Xi←jX_{i \leftarrow j} is the product of the joint transforms from jj to ii. If ii and jj are on different branches, the set is empty and the entry is 0. Lines L4 to L9 compute the first case for every pair, and the climb of line L8 builds Xi←jTFX_{i \leftarrow j}^T F one joint at a time. The same sum shows q˙TMq˙=∑lvlTIlvl\dot q^T M \dot q = \sum_l v_l^T I_l v_l, which is twice the kinetic energy, so MM is symmetric positive definite when every body has positive mass and inertia. The correctness proof of this page gives the details.

Proof: The composite rigid body algorithm returns the joint-space inertia matrixfull

We use the notation of the page and of the recursive Newton-Euler algorithm. Body ii has the parent λ(i)<i\lambda(i) < i. For an ancestor jj of ii (or j=ij = i), Xi←j=XiXλ(i)⋯X_{i \leftarrow j} = X_i X_{\lambda(i)} \cdots is the product of the joint transforms on the path, from jj down to ii, with Xi←i=1X_{i \leftarrow i} = 1. Write anc(i)\mathrm{anc}(i) for the set of ii and its ancestors and ν(i)\nu(i) for the set of ii and its descendants (the subtree of ii).

Lemma 1 (the matrix). M(q)M(q) is the matrix of the linear map q¨↦τ\ddot q \mapsto \tau of the inverse dynamics with q˙=0\dot q = 0 and no gravity. Its entries are

Hij=SiT(∑l∈ν(i)∩ν(j)Xl←iTIlXl←j)Sj.H_{ij} = S_i^T \Big( \sum_{l \in \nu(i) \cap \nu(j)} X_{l \leftarrow i}^T I_l X_{l \leftarrow j} \Big) S_j .

Proof. Run the recursive Newton-Euler algorithm with q˙=0\dot q = 0 and a0=0a_0 = 0. All velocities are 0, so al=Xlaλ(l)+Slq¨la_l = X_l a_{\lambda(l)} + S_l\ddot q_l, and by induction al=∑k∈anc(l)Xl←kSkq¨ka_l = \sum_{k \in \mathrm{anc}(l)} X_{l \leftarrow k} S_k \ddot q_k. The body wrench is IlalI_l a_l, and the backward pass adds the wrenches of the subtree, so fi=∑l∈ν(i)Xl←iTIlalf_i = \sum_{l \in \nu(i)} X_{l \leftarrow i}^T I_l a_l and τi=SiTfi\tau_i = S_i^T f_i. The coefficient of q¨j\ddot q_j in τi\tau_i collects the bodies ll with l∈ν(i)l \in \nu(i) and j∈anc(l)j \in \mathrm{anc}(l), that is l∈ν(i)∩ν(j)l \in \nu(i) \cap \nu(j). □\square

Corollary 2 (three cases). Define the composite inertia Iic=∑l∈ν(i)Xl←iTIlXl←iI^c_i = \sum_{l \in \nu(i)} X_{l \leftarrow i}^T I_l X_{l \leftarrow i}.

  • If j∈anc(i)j \in \mathrm{anc}(i), then ν(i)∩ν(j)=ν(i)\nu(i) \cap \nu(j) = \nu(i) and Xl←j=Xl←iXi←jX_{l \leftarrow j} = X_{l \leftarrow i} X_{i \leftarrow j}, so Hij=SiTIicXi←jSjH_{ij} = S_i^T I^c_i X_{i \leftarrow j} S_j.
  • If i∈anc(j)i \in \mathrm{anc}(j), then by the same argument Hij=(Xj←iSi)TIjcSj=HjiH_{ij} = (X_{j \leftarrow i} S_i)^T I^c_j S_j = H_{ji}.
  • Otherwise ii and jj are not on one path to the base, ν(i)∩ν(j)\nu(i) \cap \nu(j) is empty, and Hij=0H_{ij} = 0. This is branch-induced sparsity.

Lemma 3 (the recursion of line L3). Iic=Ii+∑c: λ(c)=iXcTIccXcI^c_i = I_i + \sum_{c:\, \lambda(c) = i} X_c^T I^c_c X_c.

Proof. ν(i)\nu(i) is the disjoint union of {i}\{i\} and the sets ν(c)\nu(c) of the children cc. For l∈ν(c)l \in \nu(c), Xl←i=Xl←cXcX_{l \leftarrow i} = X_{l \leftarrow c} X_c. □\square

Theorem. Line L10 returns H=M(q)H = M(q).

Proof. Line L1 sets Iic=IiI^c_i = I_i for all ii. The loop of line L2 visits i=n,…,1i = n, \ldots, 1. We claim that, when the loop reaches ii, the variable IicI^c_i holds the composite inertia of Lemma 3. Each child cc of ii has c>ic > i, so line L3 has already added XcTIccXcX_c^T I^c_c X_c to IicI^c_i, and by induction IccI^c_c was complete at that time. No other line changes IicI^c_i.

Line L4 sets F=IicSiF = I^c_i S_i, and line L5 sets Hii=SiTFH_{ii} = S_i^T F, which is the first case of Corollary 2 with j=ij = i. The loop of lines L7 to L9 climbs the path to the base. We show that after line L8 has moved jj to its parent, F=Xi←jTIicSiF = X_{i \leftarrow j}^T I^c_i S_i. This holds before the first step with j=ij = i. A step replaces FF by XjTFX_{j}^T F and jj by λ(j)\lambda(j), and Xi←λ(j)=Xi←jXjX_{i \leftarrow \lambda(j)} = X_{i \leftarrow j} X_j, so Xi←λ(j)T=XjTXi←jTX_{i \leftarrow \lambda(j)}^T = X_j^T X_{i \leftarrow j}^T. Line L9 then sets Hij=SjTF=SjTXi←jTIicSiH_{ij} = S_j^T F = S_j^T X_{i \leftarrow j}^T I^c_i S_i, which is the transpose of the scalar SiTIicXi←jSjS_i^T I^c_i X_{i \leftarrow j} S_j because IicI^c_i is symmetric. So it is HijH_{ij} by the first case of Corollary 2, since jj is an ancestor of ii. Line L9 also stores it as HjiH_{ji}, which is correct by the second case.

Every pair (i,j)(i, j) with one on the path of the other is written once in this way, and every other pair keeps its initial value 0, which is correct by the third case. ■\blacksquare

Kinetic energy and definiteness. With vl=∑k∈anc(l)Xl←kSkq˙kv_l = \sum_{k \in \mathrm{anc}(l)} X_{l \leftarrow k} S_k \dot q_k, Lemma 1 gives q˙THq˙=∑lvlTIlvl\dot q^T H \dot q = \sum_l v_l^T I_l v_l, which is twice the kinetic energy. If every IlI_l is positive definite, the sum is 0 only when every vl=0v_l = 0. Then Siq˙i=vi−Xivλ(i)=0S_i \dot q_i = v_i - X_i v_{\lambda(i)} = 0 for every ii, so q˙=0\dot q = 0 because Si≠0S_i \ne 0. So HH is symmetric positive definite.

Cost. Line L3 costs a fixed number of 6×66 \times 6 products per body, and the climb from body ii costs one transform per ancestor. The total is Θ(n+∑idepth(i))\Theta(n + \sum_i \mathrm{depth}(i)), which 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, line L3 costs a fixed number of 6×66 \times 6 products per body, and the climb from body ii costs one transform and one dot product per ancestor of ii. The time is Θ(n+∑idepth(i))\Theta(n + \sum_i \mathrm{depth}(i)). For a tree of depth dd this is O(nd)O(n d); for a serial chain, d=nd = n and the time is Θ(n2)\Theta(n^2); for a robot with short branches, such as a legged robot with a floating base, it is much less. These counts do not include the factorization. The extra space is Θ(n)\Theta(n) besides the output matrix. A dense output matrix also costs Θ(n2)\Theta(n^2) to set to zero; a sparse storage of only the nonzero entries avoids this.

The forward dynamics also needs the factorization. A dense Cholesky factorization costs Θ(n3)\Theta(n^3), and the two triangular solves cost Θ(n2)\Theta(n^2). Featherstone (2008, Chapter 6) shows that the factorization in the order LTLL^T L keeps the zeros of branch-induced sparsity, and then costs O(nd2)O(n d^2). Exact operation counts of the CRBA and of its use for forward dynamics are in Featherstone (2008, Chapter 10).

Properties

  • Exact. No approximation, only floating-point rounding.
  • Symmetric by construction. Line L9 writes each pair once and copies it, so the output is exactly symmetric, also in floating point.
  • Branch-induced sparsity. Hij=0H_{ij} = 0 when joints ii and jj are on different branches. The zeros do not depend on qq.
  • Positive definite. M(q)M(q) is symmetric positive definite when every body has positive mass and positive definite rotational inertia, as the proof shows.
  • Independent of q˙\dot q and gg. MM depends only on qq. One evaluation can serve several right sides, for example in an implicit integrator or for the operational space quantities.
  • Kinetic energy. 12q˙TM(q)q˙\tfrac12 \dot q^T M(q) \dot q is the kinetic energy of the robot, a cheap check of an implementation.

Variants and improvements

  • Column by column. The simplest way to build MM calls the RNEA nn times, with q¨=ej\ddot q = e_j, no velocity and no gravity, to get column jj. This costs Θ(n2)\Theta(n^2) for any tree, with a larger constant than the CRBA, and it ignores the sparsity. The tests of this page use it as the reference.
  • Sparse factorization. Featherstone (2008, Chapter 6) factors H=LTLH = L^T L in an order that creates no fill-in, so the cost of the factorization and of the solves follows the shape of the tree.
  • Centroidal momentum. The composite inertias IicI^c_i also give the centroidal momentum matrix at almost no extra cost.
  • Derivatives. The derivatives of rigid body dynamics give MM as ∂τ/∂q¨\partial\tau/\partial\ddot q as a side product.
  • Floating base. With a free-floating base, the first 6×66 \times 6 block of MM is the composite inertia of the whole robot, I1cI^c_1; see floating-base dynamics.

When to use it

Use the CRBA when you need M(q)M(q) itself: for the operational space formulation, for a quadratic program of a whole-body controller, to compute the kinetic energy, or for a forward dynamics with a few joints. For forward dynamics of a long serial chain, the articulated-body algorithm is faster; Featherstone (1987) reports that it becomes faster than the composite rigid body method for chains of about nine bodies or more. For robots with short branches, such as legged robots and humanoids, the CRBA with a sparse factorization is competitive.

Pitfalls

  • Missing bias forces. Forward dynamics needs τ−Cq˙−g\tau - C\dot q - g on the right side; the CRBA gives only the matrix.
  • The order of the bodies. Line L3 must run for a child before its parent uses IcI^c. With λ(i)<i\lambda(i) < i and a loop from nn down, this holds.
  • The transform direction. Line L8 needs XjTX_j^T, the force transform from {j}\{j\} to {λ(j)}\{\lambda(j)\}. Using XjX_j gives wrong off-diagonal entries but correct diagonal entries, so a test of the diagonal alone does not catch it.
  • Cholesky on a matrix that is not positive definite. With massless bodies, such as the first five bodies of a floating base modelled by six joints, MM is still positive definite only if the masses beyond them make it so. Check the pivots.
  • Dense storage for a tree. Storing and factoring MM as a dense matrix throws away the sparsity of a branched robot.

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.

composite_rigid_body_algorithm.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/composite-rigid-body-algorithm/. The authors are listed in prov/7BWY71.jsonl.
"""Composite rigid body algorithm (CRBA) for the joint-space inertia matrix.

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.

crba(model, q) returns H(q). forward_dynamics solves H qdd = tau - C with
the bias C from one Newton-Euler pass with qdd = 0 and a Cholesky factor.
"""

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 crba(model, q):
    """Return the joint-space inertia matrix H(q), an n x n list of rows."""
    n = model.n
    if len(q) != n:
        raise ValueError("q needs one entry per joint")
    xs = [joint_transform(model, i, q[i]) for i in range(n)]  # @line L1
    ic = [[list(row) for row in model.inertia[i]] for i in range(n)]
    h = rbm.zeros(n, n)
    for i in range(n - 1, -1, -1):  # @line L2
        p = model.parent[i]
        if p >= 0:  # @line L3
            ic[p] = rbm.add(ic[p], rbm.mul(rbm.transpose(xs[i]), rbm.mul(ic[i], xs[i])))
        f = rbm.matvec(ic[i], model.screw[i])  # @line L4
        h[i][i] = rbm.dot(model.screw[i], f)  # @line L5
        j = i  # @line L6
        while model.parent[j] >= 0:  # @line L7
            f = rbm.matvec(rbm.transpose(xs[j]), f)  # @line L8
            j = model.parent[j]
            h[i][j] = h[j][i] = rbm.dot(f, model.screw[j])  # @line L9
    return h  # @line L10


def bias_forces(model, q, qd, gravity=GRAVITY):
    """Return C(q, qd) qd + g(q) by one Newton-Euler pass with qdd = 0."""
    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]
        xs[i] = joint_transform(model, i, q[i])
        vj = rbm.scale(model.screw[i], 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.matvec(xs[i], a_base if p < 0 else a[p]), cross_motion(v[i], vj))
        inertia = model.inertia[i]
        f[i] = rbm.add(rbm.matvec(inertia, a[i]), cross_force(v[i], rbm.matvec(inertia, v[i])))
    out = [0.0] * n
    for i in range(n - 1, -1, -1):
        out[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 out


def cholesky_solve(h, b):
    """Solve h x = b for a symmetric positive definite h with h = L L^T."""
    low = rbm.cholesky(h)
    n = len(b)
    y = [0.0] * n
    for i in range(n):
        y[i] = (b[i] - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def forward_dynamics(model, q, qd, tau, gravity=GRAVITY):
    """Return qdd = H^(-1) (tau - C qd - g) with H from crba."""
    rhs = rbm.sub(tau, bias_forces(model, q, qd, gravity))
    return cholesky_solve(crba(model, q), rhs)


def kinetic_energy(model, q, qd):
    """Return (1/2) qd^T H(q) qd."""
    return 0.5 * rbm.dot(qd, rbm.matvec(crba(model, q), qd))
rbm.py 482 lines
# SPDX-License-Identifier: MIT
# Shared helper of the robotics pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small linear algebra, rotations, poses and quaternions for the robotics pages.

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

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

import math

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

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

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


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


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


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


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


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


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


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


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


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


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


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


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


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


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


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

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


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


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


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

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


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


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


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


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


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


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


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


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


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


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


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


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

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


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

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


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


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


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


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


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


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

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


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

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


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


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


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


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


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

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


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

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


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


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

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


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


def self_test():
    """Check the area check values; return True or raise AssertionError."""
    r = so3_exp([2.0 * math.pi / 3.0 / math.sqrt(3.0)] * 3)
    want = [[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]
    assert max(abs(r[i][j] - want[i][j]) for i in range(3) for j in range(3)) < 1e-12
    w = so3_log(want)
    assert abs(norm(w) - 2.0943951) < 1e-7
    assert max(abs(x - 2.0 * math.pi / 3.0 / math.sqrt(3.0)) for x in w) < 1e-12
    t = se3_exp([0.0, 0.0, math.pi / 2.0, math.pi / 2.0, 0.0, 0.0])
    want_t = make_T(rot_z(math.pi / 2.0), [1.0, 1.0, 0.0])
    assert max(abs(t[i][j] - want_t[i][j]) for i in range(4) for j in range(4)) < 1e-12
    return True
test_composite_rigid_body_algorithm.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/composite-rigid-body-algorithm/. The authors are listed in prov/7BWY71.jsonl.
"""Tests of CRBA against the 2R closed form, RNEA columns and the kinetic energy."""

import math
import random

import pytest

import rbm
from composite_rigid_body_algorithm import (
    GRAVITY,
    Model,
    cross_force,
    cross_motion,
    crba,
    forward_dynamics,
    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):
    """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])))
    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 fk(model, q):
    out = []
    for i in range(model.n):
        local = rbm.mul(model.tree[i], rbm.se3_exp(rbm.scale(model.screw[i], q[i])))
        p = model.parent[i]
        out.append(local if p < 0 else rbm.mul(out[p], local))
    return out


def kinetic_energy_brute(model, q, qd, h=1e-6):
    """Sum of (1/2) V_i^T I_i V_i, with V_i from finite differences of the poses."""
    poses = fk(model, q)
    plus = fk(model, rbm.add(q, rbm.scale(qd, h)))
    minus = fk(model, rbm.sub(q, rbm.scale(qd, h)))
    total = 0.0
    for t, tp, tm, inertia in zip(poses, plus, minus, model.inertia):
        tdot = rbm.scale(rbm.sub(tp, tm), 0.5 / h)
        twist = rbm.vee6(rbm.mul(rbm.T_inv(t), tdot))
        total += 0.5 * rbm.dot(twist, rbm.matvec(inertia, twist))
    return total


def potential(model, q, g):
    total = 0.0
    for pose, inertia in zip(fk(model, q), model.inertia):
        mass = inertia[5][5]
        com = [inertia[2][4] / mass, inertia[0][5] / mass, inertia[1][3] / mass]
        total -= mass * rbm.dot(g, rbm.T_apply(pose, com))
    return total


def maxdiff(a, b):
    return max(abs(x - y) for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def test_2r_closed_form():
    rng = random.Random(1)
    model = planar_2r()
    for _ in range(30):
        q = [rng.uniform(-math.pi, math.pi) for _ in range(2)]
        c2 = math.cos(q[1])
        assert maxdiff(crba(model, q), [[3 + 2 * c2, 1 + c2], [1 + c2, 1.0]]) < 1e-12


def test_2r_forward_dynamics_check_value():
    qdd = forward_dynamics(planar_2r(), [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


def test_columns_against_rnea():
    rng = random.Random(2)
    zero3 = [0.0, 0.0, 0.0]
    for n in (5, 6, 7):
        model = random_model(rng, n)
        q = [rng.uniform(-2, 2) for _ in range(n)]
        h = crba(model, q)
        zero = [0.0] * n
        for k in range(n):
            e = [1.0 if j == k else 0.0 for j in range(n)]
            col = rnea_ref(model, q, zero, e, zero3)
            assert max(abs(h[r][k] - col[r]) for r in range(n)) < 1e-12


def test_symmetric_positive_definite_and_kinetic_energy():
    rng = random.Random(3)
    for n in (5, 7):
        model = random_model(rng, n)
        q = [rng.uniform(-2, 2) for _ in range(n)]
        qd = [rng.uniform(-1, 1) for _ in range(n)]
        h = crba(model, q)
        assert maxdiff(h, rbm.transpose(h)) == 0.0
        rbm.cholesky(h)
        ke = 0.5 * rbm.dot(qd, rbm.matvec(h, qd))
        assert abs(ke - kinetic_energy_brute(model, q, qd)) < 1e-8


def test_branch_induced_sparsity():
    rng = random.Random(4)
    parents = [-1, 0, 1, 0, 3, -1]
    model = random_model(rng, 6, parents)
    h = crba(model, [rng.uniform(-2, 2) for _ in range(6)])

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

    for i in range(6):
        for j in range(6):
            related = i in path(j) or j in path(i)
            assert (h[i][j] == 0.0) == (not related)


def test_forward_dynamics_inverts_rnea():
    rng = random.Random(5)
    model = random_model(rng, 6)
    for _ in range(5):
        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 = forward_dynamics(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, forward_dynamics(model, x, v, zero)

    def energy(x, v):
        return 0.5 * rbm.dot(v, rbm.matvec(crba(model, x), v)) + 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_bad_input():
    with pytest.raises(ValueError):
        crba(planar_2r(), [0.0])

History

Walker and Orin (1982) compared four methods for the dynamic simulation of robot arms. Their third method computes the inertia matrix from composite rigid bodies, and it was the fastest of the four in their comparison. Featherstone (1987, 2008) rewrote the method with spatial vectors as the composite-rigid-body algorithm, extended it to trees, and showed how branch-induced sparsity makes the factorization cheaper. The name Walker-Orin method refers to the 1982 paper.

References

  1. Roy Featherstone, Rigid Body Dynamics Algorithms, Springer, 2008, Chapter 6 (forward dynamics by inertia matrix methods): Section 6.2 (the composite-rigid-body algorithm) and Section 6.4 (branch-induced sparsity); Chapter 10 (accuracy and efficiency) for the operation counts
  2. M. W. Walker and D. E. Orin, Efficient dynamic computer simulation of robotic mechanisms, Journal of Dynamic Systems, Measurement, and Control 104(3), 1982, pages 205 to 211 (method 3)
  3. Bruno Siciliano and Oussama Khatib (editors), Springer Handbook of Robotics, second edition, Springer, 2016, Chapter 3, Dynamics, by Roy Featherstone and David E. Orin
  4. Kevin M. Lynch and Frank C. Park, Modern Robotics, Mechanics, Planning, and Control, Cambridge University Press, 2017, Chapter 8, Section 8.5 (forward dynamics of open chains)

Where this leads

About this page

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

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