Skip to content

Part 3: Examples built on ReDySim

The robots of Part 1 run with one command on a model file. The examples on this page are different: they are written in Python on top of ReDySim, because the task needs more than a model file can say (several systems in one simulation, forces between them, constraints, a control law of your own). Each is a script in the examples/ folder of the download, with its data in a folder of the same name; this page shows the whole example: what it does, the code, and what it prints and draws.

To run one, start it from any folder, for example python examples/cooperative_manipulation.py. A copy of the scripts is also installed with the package, so the Runner finds them after a normal pip install; redysim-floating --copy-examples my_examples writes them into a new folder of your own, to edit and build on. It needs nothing but the package (Jupyter is not needed); the figures open in windows, and the script ends when you close them. Besides the plots of the results, each script plays an animation of the motion (the pictures on this page are stills of it). The Runner starts them too: pick one in the Example script box at the bottom of its side bar and press Run script; the Example tab then shows what the script does and the output it prints.

What runs where. The compiled kernel of the package does the dynamics (the calls to sys_ode, for_kine and the like). Everything you write on top of it, the controller, the inverse kinematics, the contact or grasp forces, the stiff solver from SciPy and the code that joins them, runs in Python and takes almost all of the time: in a profile of these examples the kernel took under two per cent. They show how to build on the package; they are not fast simulators. The planar example takes a few seconds, the spatial one 20 to 40 seconds and the two with five robots 30 seconds and a minute on a quiet machine, and longer when the machine is busy.

Two satellites carry a payload

Two free-floating satellites, each with a three-link arm, capture the ends of a free bar and carry it 0.6 m sideways. No body is fixed to the world: each force the arms exert on the bar makes the satellites recoil, and the arms have to correct it. The three bodies are separate floating-base models of the package, simulated together in one derivative function. Nothing in the package is changed; the only coupling is a grasp model written in the example.

The steps are those of any cooperative task:

  1. One model file per kind of body. A satellite is a free base (800 kg) with three arm links of 0.7 m and 8 kg; the payload is a model of a base alone (100 kg, 1 m long, its centre of mass at the origin of its frame). The same satellite file is used twice. Gravity and ground are off.
  2. One case per body. Each body keeps its own six-dimensional base and its joints; they are not joined in one kinematic tree, which would need a closed loop.
  3. One derivative function. It takes the kinematics of the three bodies from for_kine, evaluates the two grasp wrenches, turns each into the wrench array of its body with link_wrench (the opposite wrench for the payload) and calls sys_ode. The integration has two segments, with the grasps created at the end of the first.
  4. A grasp model as the only coupling, and a controller for the arms.

The code on this page is the script examples/cooperative_manipulation.py of the download.

import logging
import os
from dataclasses import dataclass

import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp

import redysim_floating as rf

logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/cooperative_manipulation"    # the data of the example (next to the script in the download)
HAND = 4                                             # the link whose tip is the hand

The models

The two model files are in the data folder of the example. The satellite's body is a rod from −1 to 1 m along its x axis, and the arm (shoulder, elbow, wrist) is attached at its front end and moves in the x–y plane.

satellite = rf.load_model(os.path.join(DATA, "satellite_arm.yaml"))[0]
payload = rf.load_model(os.path.join(DATA, "payload_bar.yaml"))[0]
bodies = [satellite, satellite, payload]            # the left satellite, the right satellite, the bar
sizes = [2 * (r.n + 5) + 2 for r in bodies]         # the state of a body: qb, q, dqb, dq and two energies
offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(int)
print(f"satellite: {satellite.n} links, {sum(satellite.m):.0f} kg;  payload: {payload.n} link, {payload.m[0]:.0f} kg")

D = 3.0                                              # each satellite is 3 m from the origin, on the x axis
base_pose0 = [(np.array([-D, 0.0]), 0.0), (np.array([D, 0.0]), np.pi)]       # position and heading
bar_ends = [np.array([payload.alt[0] - payload.al[0], 0.0]), np.array([payload.alt[0], 0.0])]
hand_angles = (0.0, np.pi)                           # the hands point along the bar, towards each other

Output:

satellite: 4 links, 824 kg;  payload: 1 link, 100 kg

The task and the joint references

Each hand moves from a stand-off pose to one end of the bar, holds, and later carries the bar 0.6 m in y (the bar is a free body: the carry only happens because the grasps hold it). The hand's path is a sequence of waypoints at rest, joined by cycloidal moves. The inverse kinematics of the planar arm gives the joint angles at the start (the closed form is in arm_ik).

def wrap(q):
    return np.pi - (np.pi - np.asarray(q, dtype=float)) % (2.0 * np.pi)


def direction(angle):
    return np.array([np.cos(angle), np.sin(angle)])


def arm_ik(robot, base_xy, base_angle, hand_xy, hand_angle, elbow=1):
    """The three joint angles that put the hand at ``hand_xy`` pointing along ``hand_angle`` (absolute
    angles in the x-y plane) for a base at ``base_xy`` turned by ``base_angle``; ``elbow`` is +1 or -1."""
    offset, upper, fore, hand = robot.a[1], robot.a[2], robot.a[3], robot.alt[3]
    shoulder = np.asarray(base_xy, dtype=float) + offset * direction(base_angle)
    wrist = np.asarray(hand_xy, dtype=float) - hand * direction(hand_angle)
    d = np.linalg.norm(wrist - shoulder)
    if not abs(upper - fore) <= d <= upper + fore:
        raise ValueError(f"the wrist is {d:.3f} m from the shoulder, out of reach")
    gamma = np.arccos((upper**2 + d**2 - fore**2) / (2.0 * upper * d))
    theta1 = np.arctan2(*(wrist - shoulder)[::-1]) - elbow * gamma
    elbow_xy = shoulder + upper * direction(theta1)
    theta2 = np.arctan2(*(wrist - elbow_xy)[::-1])
    return wrap([theta1 - base_angle, theta2 - theta1, hand_angle - theta2])


def cycloidal(t, t0, t1):
    """A smooth rise from 0 to 1 between ``t0`` and ``t1``, at rest at both ends: ``(s, ds/dt)``."""
    if t <= t0:
        return 0.0, 0.0
    if t >= t1:
        return 1.0, 0.0
    tau = (t - t0) / (t1 - t0)
    return tau - np.sin(2.0 * np.pi * tau) / (2.0 * np.pi), (1.0 - np.cos(2.0 * np.pi * tau)) / (t1 - t0)


class Waypoints:
    """Positions through waypoints, at rest at each, cycloidal in between; called with a time it returns
    ``(x, dx)``."""

    def __init__(self, times, positions):
        self.times, self.positions = list(times), [np.asarray(p, dtype=float) for p in positions]

    def __call__(self, t):
        x, dx = self.positions[0].copy(), np.zeros_like(self.positions[0])
        for k in range(len(self.times) - 1):
            s, ds = cycloidal(t, self.times[k], self.times[k + 1])
            step = self.positions[k + 1] - self.positions[k]
            x, dx = x + s * step, dx + ds * step
        return x, dx


STANDOFF, CARRY = (0.8, 0.9), (0.0, 0.6)             # the hands start 0.8 m out and 0.9 m up; the carry in x, y
T_APPROACH, T_CAPTURE, T_CARRY, T_END = 4.0, 5.0, (5.5, 9.5), 11.0


def hand_targets():
    """The task of each hand, [x, y, angle] against time: from the stand-off pose to the bar end, a hold,
    and the carrying move."""
    out = []
    for k in range(2):
        sign = -1.0 if k == 0 else 1.0
        start = np.array([*(bar_ends[k] + [sign * STANDOFF[0], STANDOFF[1]]), hand_angles[k]])
        grasp = np.array([*bar_ends[k], hand_angles[k]])
        carry = np.array([*(grasp[:2] + CARRY), grasp[2]])
        out.append(Waypoints([0.0, T_APPROACH, T_CARRY[0], T_CARRY[1]], [start, grasp, grasp, carry]))
    return out


ELBOW = (1, -1)                                      # the arm configuration of each satellite
tasks = hand_targets()
q_start = [arm_ik(satellite, *base_pose0[k], tasks[k](0.0)[0][:2], hand_angles[k], ELBOW[k]) for k in range(2)]
print("initial joint angles (rad):", [np.round(q, 3).tolist() for q in q_start])

Output:

initial joint angles (rad): [[0.698, 1.745, -2.443], [-0.698, -1.745, 2.443]]

The controller

Each arm is driven in task space by a PD law on the measured pose of its hand (position and orientation in the inertial frame): \(\tau = J^\top (K_p e + K_d \dot e)\). Because it uses the measured pose, the recoil of the free satellite is corrected by feedback. The controller does not know about the payload.

KP, KD = (6000.0, 3000.0), (1500.0, 600.0)           # position (N/m), orientation (N m/rad); damping (N s/m, N m s/rad)


def controller(task):
    """``torque(t, robot, qb, dqb, q, dq)``: PD on the measured hand pose, mapped to the joints by the
    transpose of the hand Jacobian (a planar arm: the joint axes are along z)."""
    kp = np.array([KP[0], KP[0], KP[1]])
    kd = np.array([KD[0], KD[0], KD[1]])

    def torque(t, robot, qb, dqb, q, dq):
        kin = rf.for_kine(robot, qb, dqb, q, dq)
        hand, Q = kin.tip[HAND - 1], kin.Q[HAND - 1]
        x = np.array([hand[0], hand[1], np.arctan2(Q[1, 0], Q[0, 0])])
        v = np.array([*kin.vtip[HAND - 1][:2], (Q @ kin.tt[HAND - 1])[2]])
        xd, vd = task(t)
        e = xd - x
        e[2] = wrap(e[2])
        J = np.ones((3, 3))
        for j in range(3):
            r = hand - kin.origin[1 + j]
            J[0, j], J[1, j] = -r[1], r[0]
        return np.zeros(6), J.T @ (kp * e + kd * (vd - v))
    return torque

The grasp: the only coupling

Contact is not modelled. At the capture time the hand's pose in the frame of the payload is recorded and becomes the rest pose of a six-dimensional spring-damper: a force on the position error and a moment on the orientation error, each with damping on the relative velocity. Capturing at the present pose means the grasp starts without force, and its stiffness is then ramped up smoothly over 0.5 s. The wrench acts on the arm link at the hand, and the opposite wrench at the same point on the payload, so the coupling conserves the total linear and angular momentum exactly.

@dataclass(frozen=True)
class GraspGains:
    stiffness: float = 1.0e4        # N/m
    damping: float = 2.0e3          # N s/m
    rot_stiffness: float = 1.0e3    # N m/rad
    rot_damping: float = 1.8e2      # N m s/rad
    ramp: float = 0.5               # s: the grasp builds up smoothly after capture


@dataclass(frozen=True)
class Grasp:
    link: int                       # the arm link that holds, 1-based
    point: np.ndarray               # the hand's position in the frame of the payload at capture
    rotation: np.ndarray            # the orientation of the arm link in the frame of the payload
    t_capture: float
    gains: GraspGains


def rotation_vector(R):
    angle = np.arccos(np.clip((np.trace(R) - 1.0) / 2.0, -1.0, 1.0))
    axis = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]])
    return 0.5 * axis if angle < 1e-9 else angle / (2.0 * np.sin(angle)) * axis


def capture(arm_kin, link, payload_kin, t, gains=GraspGains()):
    """Tie the hand (the tip of ``link``) to the payload at their present poses."""
    Rp, op = payload_kin.Q[0], payload_kin.origin[0]
    return Grasp(link, Rp.T @ (arm_kin.tip[link - 1] - op), Rp.T @ arm_kin.Q[link - 1], t, gains)


def build_up(grasp, t):
    s = np.clip((t - grasp.t_capture) / grasp.gains.ramp, 0.0, 1.0)
    return float(s * s * (3.0 - 2.0 * s))


def grasp_wrench(grasp, arm_kin, payload_kin, t):
    """``(force, moment, point)`` on the arm link, inertial frame; the payload gets the opposite force and
    moment at the same point."""
    g, i = grasp.gains, grasp.link - 1
    Rp, op = payload_kin.Q[0], payload_kin.origin[0]
    hand = arm_kin.tip[i]
    r = Rp @ grasp.point                                   # the grasp point, from the payload origin
    omega_payload = Rp @ payload_kin.tt[0]
    velocity_error = arm_kin.vtip[i] - (payload_kin.vcom[0] + np.cross(omega_payload, r))
    force = -g.stiffness * (hand - (op + r)) - g.damping * velocity_error
    orientation_error = rotation_vector(arm_kin.Q[i] @ (Rp @ grasp.rotation).T)
    moment = (-g.rot_stiffness * orientation_error
              - g.rot_damping * (arm_kin.Q[i] @ arm_kin.tt[i] - omega_payload))
    s = build_up(grasp, t)
    return s * force, s * moment, hand

The coupled simulation

One case per body (the satellites with their controller, the payload with no torques). The derivative function stacks the three states; before capture there are no grasps, and after it the grasp wrenches are turned into the fext arrays of the arm link and of the payload with link_wrench. A stiff solver from SciPy (BDF) integrates the two segments.

cases = []
for k in range(2):
    xy, angle = base_pose0[k]
    cases.append(rf.ForDynCase(robot=satellite, qb0=[xy[0], xy[1], 0.0, angle, 0.0, 0.0], q0=q_start[k],
                               dqb0=np.zeros(6), dq0=np.zeros(3), torque=controller(tasks[k])))
cases.append(rf.ForDynCase(robot=payload, qb0=np.zeros(6), q0=[], dqb0=np.zeros(6), dq0=[]))


def parts(y):
    return [y[offsets[k]:offsets[k + 1]] for k in range(3)]


def kinematics_of(y):
    out = []
    for case, p in zip(cases, parts(y), strict=True):
        n = case.robot.n
        out.append(rf.for_kine(case.robot, p[:6], p[5 + n:11 + n], p[6:5 + n], p[11 + n:10 + 2 * n]))
    return out


def derivative(grasps):
    def rhs(t, y):
        p = parts(y)
        fext = [None, None, None]
        if grasps:
            kin = kinematics_of(y)
            pay = np.zeros((1, 6))
            for k in range(2):
                f, m, point = grasp_wrench(grasps[k], kin[k], kin[2], t)
                fext[k] = rf.link_wrench(satellite, p[k][:6], p[k][6:9], HAND, force=f, moment=m, point=point)
                rf.link_wrench(payload, p[2][:6], [], 1, force=-f, moment=-m, point=point, out=pay)
            fext[2] = pay
        return np.concatenate([rf.sys_ode(cases[k], t, p[k], fext[k])[0] for k in range(3)])
    return rhs


STEP = 0.05
y0 = np.concatenate([c.y0 for c in cases])
grid = np.arange(0.0, T_END + 0.5 * STEP, STEP)
first = solve_ivp(derivative([]), (0.0, T_CAPTURE), y0, method="BDF", rtol=1e-8, atol=1e-10,
                  t_eval=grid[grid <= T_CAPTURE + 1e-9])
kin_c = kinematics_of(first.y[:, -1])
grasps = [capture(kin_c[k], HAND, kin_c[2], T_CAPTURE) for k in range(2)]     # the grasps close here
second = solve_ivp(derivative(grasps), (T_CAPTURE, T_END), first.y[:, -1], method="BDF", rtol=1e-8,
                   atol=1e-10, t_eval=grid[grid >= T_CAPTURE - 1e-9])
t = np.concatenate([first.t, second.t[1:]])
Y = np.concatenate([first.y.T, second.y.T[1:]])
print(f"{len(t)} saved states, {first.nfev + second.nfev} derivative evaluations")

Output:

221 saved states, 2468 derivative evaluations

What happened

The numbers worth looking at after a run: how close the hands were to the bar at capture, how far the bar was carried, the recoil of the satellites, the forces in the grasps and the total momentum. Nothing acts on the three bodies from outside, so the total linear and angular momentum stay at zero: their drift is the integration error, a direct check of the coupling.

def states(k):
    n = bodies[k].n
    y = Y[:, offsets[k]:offsets[k + 1]]
    return y[:, :6], y[:, 6:5 + n], y[:, 5 + n:11 + n], y[:, 11 + n:10 + 2 * n]


kin = [[rf.for_kine(bodies[k], *s) for s in zip(*[states(k)[i] for i in (0, 2, 1, 3)], strict=True)]
       for k in range(3)]                                  # for_kine(robot, qb, dqb, q, dq) at every saved time
ic, ie = int(np.argmin(abs(t - T_CAPTURE))), len(t) - 1

# the grasp forces on the payload (zero before capture)
force, moment = np.zeros((len(t), 2, 3)), np.zeros((len(t), 2, 3))
for i, ti in enumerate(t):
    for k in range(2):
        f, m, _ = grasp_wrench(grasps[k], kin[k][i], kin[2][i], ti)
        force[i, k], moment[i, k] = -f, -m
axis = np.array([kin[1][i].tip[HAND - 1] - kin[0][i].tip[HAND - 1] for i in range(len(t))])
axis /= np.linalg.norm(axis, axis=1, keepdims=True)
squeeze = 0.5 * np.einsum("ij,ij->i", force[:, 0] - force[:, 1], axis)
net = force.sum(axis=1)

# the total momentum of the three bodies about the origin
P, H = np.zeros((len(t), 3)), np.zeros((len(t), 3))
for k, robot in enumerate(bodies):
    for i, kk in enumerate(kin[k]):
        for j in range(robot.n):
            m = robot.m[j]
            P[i] += m * kk.vcom[j]
            H[i] += kk.Q[j] @ (robot.com_inertia(j) @ kk.tt[j]) + m * np.cross(kk.com[j], kk.vcom[j])

pay = kin[2]
gap = [np.linalg.norm(kin[k][ic].tip[HAND - 1] - end) for k, end in enumerate((pay[ic].start[0], pay[ic].tip[0]))]
shift = (pay[ie].origin[0] - pay[ic].origin[0])[:2]
recoil = [np.linalg.norm(states(k)[0][ie, :2] - states(k)[0][0, :2]) for k in range(2)]
turn = [states(k)[0][ie, 3] - states(k)[0][0, 3] for k in range(2)]
print(f"hands from the bar ends at capture: {gap[0]:.1e} m and {gap[1]:.1e} m")
print(f"the bar moved {shift[1]:.6f} m in y (0.6 asked), {shift[0]:.1e} m in x, and ends at rest "
      f"({np.linalg.norm(pay[ie].vcom[0]):.1e} m/s)")
print(f"each satellite recoiled by {recoil[0] * 100:.1f} and {recoil[1] * 100:.1f} cm and turned by "
      f"{turn[0]:.2f} and {turn[1]:.2f} rad")
print(f"peak net force on the payload {np.linalg.norm(net, axis=1).max():.1f} N, peak squeeze between the hands "
      f"{np.abs(squeeze).max():.2f} N")
print(f"momentum (should be zero): linear {np.abs(P).max():.1e} N s, angular {np.abs(H).max():.1e} N m s")

Output:

hands from the bar ends at capture: 4.7e-06 m and 4.7e-06 m
the bar moved 0.600004 m in y (0.6 asked), 6.5e-16 m in x, and ends at rest (6.0e-07 m/s)
each satellite recoiled by 2.9 and 2.9 cm and turned by -0.07 and 0.07 rad
peak net force on the payload 24.4 N, peak squeeze between the hands 0.75 N
momentum (should be zero): linear 6.5e-07 N s, angular 1.2e-10 N m s
fig, ax = plt.subplots(2, 2, figsize=(10, 6))
origin = np.array([kk.origin[0] for kk in pay])
ax[0, 0].plot(t, origin[:, 0] - origin[0, 0], label="x")
ax[0, 0].plot(t, origin[:, 1] - origin[0, 1], label="y")
ax[0, 0].set(xlabel="time (s)", ylabel="payload shift (m)", title="the bar is carried 0.6 m")
ax[0, 0].legend()
ax[0, 1].plot(t, np.linalg.norm(net, axis=1), label="net force on the payload")
ax[0, 1].plot(t, squeeze, label="squeeze between the hands")
ax[0, 1].set(xlabel="time (s)", ylabel="grasp (N)", title="the arms do not fight")
ax[0, 1].legend()
for k, name in enumerate(("left", "right")):
    ax[1, 0].plot(t, np.linalg.norm(states(k)[0][:, :2] - states(k)[0][0, :2], axis=1), label=f"{name} satellite")
ax[1, 0].set(xlabel="time (s)", ylabel="recoil of the satellites (m)", title="the satellites recoil")
ax[1, 0].legend()
ax[1, 1].semilogy(t, np.maximum(np.abs(P).max(axis=1), 1e-16), label="linear (N s)")
ax[1, 1].semilogy(t, np.maximum(np.abs(H).max(axis=1), 1e-16), label="angular (N m s)")
ax[1, 1].set(xlabel="time (s)", ylabel="total momentum", title="momentum stays at zero")
ax[1, 1].legend()
for a in ax.ravel():
    a.axvline(T_CAPTURE, ls=":", color="gray")
fig.tight_layout()

What the motion looks like

The satellites (body and arm), the bar and the path of its centre at the start, at capture and at the end of the carry, with earlier poses lighter. The script plays the same drawing as an animation instead.

def satellite_line(k, i):
    kk = kin[k][i]
    return np.array([kk.start[0], kk.tip[0], *kk.origin[1:HAND], kk.tip[HAND - 1]])[:, :2]


def bar_line(i):
    return np.array([pay[i].start[0], pay[i].tip[0]])[:, :2]
fig, ax = plt.subplots(figsize=(9, 2.6))
path = np.array([kk.origin[0][:2] for kk in pay])
ax.plot(*path.T, color="tab:orange", lw=1.2)
shown = [0, ic, ie]
for n, i in enumerate(shown):
    last = n == len(shown) - 1
    for k in range(2):
        ax.plot(*satellite_line(k, i).T, color="0.15" if last else "0.7", lw=2 if last else 1.2,
                marker="o", ms=3 if last else 0)
    ax.plot(*bar_line(i).T, color="tab:green" if last else "#a6dcc8", lw=4 if last else 2.5)
ax.set_aspect("equal")
ax.set(xlabel="x (m)", ylabel="y (m)", title="start, capture and the end of the carry")
fig.tight_layout()

What to try

  • A different carry: change CARRY (for instance (0.3, 0.5)) and run again; the hand targets follow.
  • A softer grasp: reduce stiffness and rot_stiffness in GraspGains and watch the squeeze and the hand–bar error grow. A very stiff grasp makes the equations stiff for an explicit solver.
  • Lighter satellites: reduce the mass of link 1 in satellite_arm.yaml. A light satellite turns so much under the reaction of the arm that the arm reaches its straight-elbow singularity and the control is lost.
  • A three-dimensional version: the same structure works with seven-joint arms and a six-dimensional controller; the base attitude is then held by an ideal moment.

The pattern is the one for any coupled system on the package: one model and one case per body, a force law between them written outside the package, the opposite wrenches at the same point, and one derivative function.

Two satellites carry a cube in three dimensions

The spatial version of the cooperative task: two free-floating satellites, each with a seven-joint arm, hold a free 160 kg cube by the centres of two opposite faces and carry it 0.6 m sideways and 0.3 m up while turning it by 30° about the vertical axis. It has the structure of the planar example (separate floating-base models, one derivative function, a spring-damper grasp as the only coupling) and adds what a three-dimensional task needs:

  • the attitude of every base is given by Euler parameters (a unit quaternion), so there is no singularity, and the base state has 7 position and attitude values and 6 rates;
  • a six-dimensional task-space controller on the measured hand pose (position and orientation), with a null-space joint PD towards a planned joint path that uses the seventh joint's freedom;
  • an ideal attitude moment on each satellite that holds its initial attitude (the arms' reaction would otherwise turn the satellites);
  • a hand that is a point fixed in the last link, not its tip.

It runs in about 20 s on a quiet machine and several times longer on a busy one (the grasp is stiff, so the solver takes many small steps). Nothing in the package is changed.

The code on this page is the script examples/cooperative_manipulation_spatial.py of the download.

import json
import logging
import os
import warnings
from dataclasses import dataclass, field

import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d.art3d import Line3DCollection
from scipy.integrate import solve_ivp

import redysim_floating as rf

logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/cooperative_manipulation_spatial"    # the data of the example

The models

The satellite is a free base (a 1000 kg cube) with a seven-joint arm; the payload is a free cube of 160 kg and 0.8 m edge, a model of a base alone with its centre of mass at the origin of its frame. The arm's joint values are those of the MuJoCo model it came from plus the angle offsets in q0 of the hand file, and the hand is a point fixed in the last link (hand_in_link_8), 0.1 m from its origin.

satellite = rf.load_model("satellite_arm7.yaml")[0]
payload = rf.load_model(os.path.join(DATA, "payload_cube.yaml"))[0]
hand_file = json.load(open(os.path.join(DATA, "satellite_arm7_hand.json")))
HAND_POINT = np.array(hand_file["hand_in_link_8"])                      # the hand, in the frame of the last link
Q_HOME = np.radians([0, -150, 0, 150, 0, -150, 0.0]) + np.array(hand_file["q0"])
N = satellite.n                                                         # links: the base and seven arm links
bodies = [satellite, satellite, payload]
sizes = [2 * r.n + 13 for r in bodies]                                  # a state: qb (7), q, dqb (6), dq, 2 energies
offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(int)
print(f"satellite: {N} links, {sum(satellite.m):.0f} kg;  payload: {payload.m[0]:.0f} kg")

Output:

satellite: 8 links, 1025 kg;  payload: 160 kg

Rotations and the hand

Small helpers: a rotation about z, the conversions between a unit quaternion and a rotation matrix, the rotation vector of a rotation matrix (the orientation error), the 6 × 7 Jacobian of the hand with the base held, and the hand's position, velocity and the link's rotation and angular velocity in the inertial frame from for_kine.

def rz(a):
    c, s = np.cos(a), np.sin(a)
    return np.array([[c, -s, 0], [s, c, 0], [0, 0, 1.0]])


def quat_to_rot(q):
    w, x, y, z = q / np.linalg.norm(q)
    return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
                     [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
                     [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]])


def rotation_vector(R):
    """Axis times angle of a rotation matrix (also near 0 and near pi)."""
    angle = np.arccos(np.clip((np.trace(R) - 1.0) / 2.0, -1.0, 1.0))
    axis = np.array([R[2, 1] - R[1, 2], R[0, 2] - R[2, 0], R[1, 0] - R[0, 1]])
    if angle < 1e-9:
        return 0.5 * axis
    if np.pi - angle < 1e-6:
        _, v = np.linalg.eigh((R + R.T) / 2 - np.eye(3) * (np.trace(R) - 1) / 2)
        u = v[:, -1]
        return angle * (u if u @ axis >= 0 else -u)
    return angle / (2.0 * np.sin(angle)) * axis


def hand_state(kin, link=N, offset=HAND_POINT):
    """Hand position, velocity, link rotation and angular velocity (inertial frame) from ``for_kine``."""
    j = link - 1
    Q = np.asarray(kin.Q[j])
    p = np.asarray(kin.origin[j]) + Q @ offset
    w = Q @ np.asarray(kin.tt[j])
    v = np.asarray(kin.vcom[j]) + np.cross(w, p - np.asarray(kin.com[j]))
    return p, v, Q, w


def arm_jacobian(kin, p):
    """6 x 7 Jacobian [v; w] of the point ``p`` of the last link in the inertial frame, with the base held
    (joint k turns about the z axis of link k + 1)."""
    J = np.zeros((6, N - 1))
    for k in range(1, N):
        z = np.asarray(kin.Q[k])[:, 2]
        J[:3, k - 1] = np.cross(z, p - np.asarray(kin.origin[k]))
        J[3:, k - 1] = z
    return J

The task

Each hand moves from a stand-off pose to the centre of one face of the cube, holds, and later carries the face with the cube: a shift of (0, 0.6, 0.3) m and a turn of 30° about the vertical axis (HandTask, cycloidal moves at rest at both ends). The satellites sit at x = ∓2.2 m with their arms facing the cube, which is at the origin 0.6 m up. ik is a damped least-squares inverse kinematics that uses the null space to stay near a home posture; plan solves it along the whole task to give a planned joint path for the null-space posture term.

@dataclass
class Scenario:
    """The numbers of the task (lengths in m, angles in rad, times in s)."""
    base_distance: float = 2.2
    height: float = 0.6                  # the cube centre's height
    half_edge: float = 0.4
    standoff: tuple = (0.6, 0.0)         # the hands start this far out along x and up
    carry: tuple = (0.0, 0.6, 0.3)       # shift of the cube while it is carried
    turn: float = np.pi / 6              # turn of the cube about the vertical axis
    t_approach: float = 4.0
    t_capture: float = 5.0
    t_carry: tuple = (5.5, 9.5)
    t_end: float = 11.0
    step: float = 0.05                   # spacing of the saved states
    kp: tuple = (4000.0, 1000.0)         # hand PD: position (N/m), orientation (N m/rad)
    kd: tuple = (1500.0, 150.0)          # N s/m, N m s/rad
    posture_wn: float = 6.0              # null-space joint PD towards the planned path: natural frequency (rad/s)
    posture_zeta: float = 1.0            # and damping ratio; gains = joint inertia * wn^2
    plan_step: float = 0.1               # spacing of the planned joint path (s)
    att_kp: float = 3000.0               # base attitude PD: an ideal moment holds each base's initial attitude
    att_kd: float = 1500.0               # N m/rad, N m s/rad


SC = Scenario()
INERTIA = np.array([13.849, 14.814, 2.969, 3.116, 0.0351, 0.0770, 0.0202])     # joint inertias at the reference pose

# satellite 0 on the -x side with its arm pointing to +x (yaw pi); satellite 1 on the +x side (yaw 0)
base_pose0 = [(np.array([-SC.base_distance, 0.0, 0.0]), np.pi), (np.array([SC.base_distance, 0.0, 0.0]), 0.0)]
centre = np.array([0.0, 0.0, SC.height])


def base_state(k):
    xyz, yaw = base_pose0[k]
    return np.concatenate([xyz, [np.cos(yaw / 2), 0, 0, np.sin(yaw / 2)]])     # position and Euler parameters


class HandTask:
    """Desired pose of a hand against time: stand-off -> face centre, hold, then the carry."""

    def __init__(self, start, face, R):
        self.start, self.face, self.R = start, face, R

    @staticmethod
    def _cyc(t, t0, t1):
        if t <= t0:
            return 0.0, 0.0
        if t >= t1:
            return 1.0, 0.0
        tau = (t - t0) / (t1 - t0)
        return tau - np.sin(2 * np.pi * tau) / (2 * np.pi), (1 - np.cos(2 * np.pi * tau)) / (t1 - t0)

    def __call__(self, t):
        s, ds = self._cyc(t, 0.0, SC.t_approach)
        p = self.start + s * (self.face - self.start)
        v = ds * (self.face - self.start)
        s2, ds2 = self._cyc(t, *SC.t_carry)
        Rt = rz(s2 * SC.turn)
        rel = self.face - centre
        if not (s2 == 0.0 and ds2 == 0.0 and t < SC.t_carry[1]):
            p = centre + s2 * np.asarray(SC.carry) + Rt @ rel
        if t >= SC.t_carry[0]:
            w = np.array([0.0, 0.0, ds2 * SC.turn])
            v = ds2 * np.asarray(SC.carry) + np.cross(w, Rt @ rel)
        else:
            w = np.zeros(3)
        return p, Rt @ self.R, v, w


tasks = []
for k in range(2):
    sign = -1.0 if k == 0 else 1.0                          # the face this hand holds: x = sign * half_edge
    face = centre + np.array([sign * SC.half_edge, 0, 0])
    start = face + np.array([sign * SC.standoff[0], 0, SC.standoff[1]])
    zc = np.array([sign, 0.0, 0.0])                         # the hand's z axis points away from the cube
    xc = np.array([0.0, 0.0, 1.0])
    tasks.append(HandTask(start, face, np.column_stack([xc, np.cross(zc, xc), zc])))


def ik(k, p, R, q0=None, iters=3000):
    """Joint angles that put the hand of satellite ``k`` at pose (p, R): damped least squares, and the null space
    used to stay near the home posture."""
    q = (Q_HOME if q0 is None else q0).copy()
    qb = base_state(k)
    for _ in range(iters):
        kin = rf.for_kine(satellite, qb, np.zeros(6), q, np.zeros(N - 1))
        hp, _, Q, _ = hand_state(kin)
        e = np.concatenate([p - hp, rotation_vector(R @ Q.T)])
        if np.abs(e).max() < 1e-9:
            return q
        J = arm_jacobian(kin, hp)
        q = q + J.T @ np.linalg.inv(J @ J.T + 1e-6 * np.eye(6)) @ e \
            + (np.eye(N - 1) - np.linalg.pinv(J) @ J) @ (0.2 * (Q_HOME - q))
    raise RuntimeError(f"the inverse kinematics of satellite {k} did not converge")


def plan(k):
    """The planned joint path of satellite ``k``: the inverse kinematics along the hand task on a grid, each
    solution started from the last; returned as tables ``(t, q, dq)``."""
    t = np.arange(0.0, SC.t_carry[1] + SC.plan_step, SC.plan_step)
    q = [ik(k, *tasks[k](0.0)[:2])]
    for tt in t[1:]:
        q.append(ik(k, *tasks[k](tt)[:2], q0=q[-1]))
    q = np.array(q)
    return t, q, np.gradient(q, t, axis=0)


q_start = [ik(k, *tasks[k](0.0)[:2]) for k in range(2)]
plans = [plan(k) for k in range(2)]
print("joint angles at the start (deg), satellite 0:", np.round(np.degrees(q_start[0])).astype(int).tolist())

Output:

joint angles at the start (deg), satellite 0: [-43, 93, 40, 327, 147, 69, -60]

The controller

Each arm is driven in task space by a six-dimensional PD law on the measured hand pose (position and orientation in the inertial frame), mapped to the joints by the transpose of the hand Jacobian, \(\tau = J^\top (K_p e + K_d \dot e)\). The arm has seven joints for six task coordinates, so a PD law on the joints towards the planned path acts in the null space of the Jacobian only. The base is not driven by the arm, but an ideal moment (tub) holds its attitude: it is the rotation vector of the attitude error, in the inertial frame.

def controller(task, k):
    """``torque(t, robot, qb, dqb, q, dq) -> (tub, tau)`` of satellite ``k``."""
    kp = np.array([SC.kp[0]] * 3 + [SC.kp[1]] * 3)
    kd = np.array([SC.kd[0]] * 3 + [SC.kd[1]] * 3)
    tp, qp, dqp = plans[k]
    R_att = quat_to_rot(base_state(k)[3:])
    kq, dq_gain = INERTIA * SC.posture_wn**2, 2 * SC.posture_zeta * INERTIA * SC.posture_wn

    def torque(t, robot, qb, dqb, q, dq):
        kin = rf.for_kine(robot, qb, dqb, q, dq)
        p, v, Q, w = hand_state(kin)
        pd, Rd, vd, wd = task(t)
        e = np.concatenate([pd - p, rotation_vector(Rd @ Q.T)])
        de = np.concatenate([vd - v, wd - w])
        J = arm_jacobian(kin, p)
        tau = J.T @ (kp * e + kd * de)
        qr = np.array([np.interp(t, tp, qp[:, j]) for j in range(N - 1)])
        dqr = np.array([np.interp(t, tp, dqp[:, j]) for j in range(N - 1)]) if t < tp[-1] else np.zeros(N - 1)
        tau += (np.eye(N - 1) - np.linalg.pinv(J) @ J) @ (kq * (qr - q) + dq_gain * (dqr - dq))
        tub = np.zeros(6)                                    # attitude control of the base: a moment, inertial frame
        tub[3:] = SC.att_kp * rotation_vector(R_att @ quat_to_rot(qb[3:7]).T) - SC.att_kd * np.asarray(dqb)[3:6]
        return tub, tau
    return torque

The grasp

As in the planar example, at the capture time the hand's pose in the frame of the cube is recorded and becomes the rest pose of a six-dimensional spring-damper, ramped up smoothly over 0.5 s; the wrench acts on the last arm link at the hand and the opposite wrench at the same point on the cube, so the coupling conserves the total linear and angular momentum. Here the hand is a point fixed in the last link, not its tip.

@dataclass(frozen=True)
class GraspGains:
    stiffness: float = 2.0e4        # N/m
    damping: float = 4.0e3          # N s/m
    rot_stiffness: float = 1.0e3    # N m/rad
    rot_damping: float = 1.0e2      # N m s/rad
    ramp: float = 0.5               # s


@dataclass(frozen=True)
class Grasp:
    point: np.ndarray               # the hand in the payload frame at capture
    rotation: np.ndarray            # the link's orientation in the payload frame at capture
    t_capture: float
    gains: GraspGains


def capture(arm_kin, payload_kin, t, gains=GraspGains()):
    p, _, Q, _ = hand_state(arm_kin)
    Rp, op = np.asarray(payload_kin.Q[0]), np.asarray(payload_kin.origin[0])
    return Grasp(Rp.T @ (p - op), Rp.T @ Q, t, gains)


def build_up(grasp, t):
    s = np.clip((t - grasp.t_capture) / grasp.gains.ramp, 0.0, 1.0)
    return float(s * s * (3.0 - 2.0 * s))


def grasp_wrench(grasp, arm_kin, payload_kin, t):
    """``(force, moment, point)`` on the arm link, inertial frame; the payload gets the opposite."""
    g = grasp.gains
    Rp, op = np.asarray(payload_kin.Q[0]), np.asarray(payload_kin.origin[0])
    hand, vh, Q, w = hand_state(arm_kin)
    r = Rp @ grasp.point
    wp = Rp @ np.asarray(payload_kin.tt[0])
    verr = vh - (np.asarray(payload_kin.vcom[0]) + np.cross(wp, r))
    force = -g.stiffness * (hand - (op + r)) - g.damping * verr
    moment = -g.rot_stiffness * rotation_vector(Q @ (Rp @ grasp.rotation).T) - g.rot_damping * (w - wp)
    s = build_up(grasp, t)
    return s * force, s * moment, hand

The coupled simulation

The same structure as the planar example: one case per body (the satellites with their controller and attitude moment, the cube with no torques), one derivative function that evaluates the grasp wrenches, turns them into the fext arrays with link_wrench and calls sys_ode, and two segments of a stiff solver (BDF) with the grasps created at the end of the first. The base state has seven values (position and Euler parameters), so the slices of the stacked state differ from the planar case.

cases = [rf.ForDynCase(robot=satellite, qb0=base_state(k), q0=q_start[k], dqb0=np.zeros(6), dq0=np.zeros(N - 1),
                       torque=controller(tasks[k], k)) for k in range(2)]
cases.append(rf.ForDynCase(robot=payload, qb0=np.array([*centre, 1.0, 0, 0, 0]), q0=[], dqb0=np.zeros(6), dq0=[]))


def parts(y):
    return [y[offsets[k]:offsets[k + 1]] for k in range(3)]


def kinematics_of(y):
    out = []
    for case, p in zip(cases, parts(y), strict=True):
        m = case.robot.n
        out.append(rf.for_kine(case.robot, p[:7], p[6 + m:12 + m], p[7:6 + m], p[12 + m:11 + 2 * m]))
    return out


def derivative(grasps):
    def rhs(t, y):
        p = parts(y)
        fext = [None, None, None]
        if grasps:
            kin = kinematics_of(y)
            pay = np.zeros((1, 6))
            for k in range(2):
                f, m, point = grasp_wrench(grasps[k], kin[k], kin[2], t)
                fext[k] = rf.link_wrench(satellite, p[k][:7], p[k][7:6 + N], N, force=f, moment=m, point=point)
                rf.link_wrench(payload, p[2][:7], [], 1, force=-f, moment=-m, point=point, out=pay)
            fext[2] = pay
        return np.concatenate([rf.sys_ode(cases[k], t, p[k], fext[k])[0] for k in range(3)])
    return rhs


RTOL, ATOL = 1e-6, 1e-8
y0 = np.concatenate([c.y0 for c in cases])
grid = np.arange(0.0, SC.t_end + 0.5 * SC.step, SC.step)
first = solve_ivp(derivative([]), (0.0, SC.t_capture), y0, method="BDF", rtol=RTOL, atol=ATOL,
                  t_eval=grid[grid <= SC.t_capture + 1e-9])
kin_c = kinematics_of(first.y[:, -1])
grasps = [capture(kin_c[k], kin_c[2], SC.t_capture) for k in range(2)]            # the grasps close here
gap = [float(np.linalg.norm(hand_state(kin_c[k])[0] - (centre + np.array([(-1.0, 1.0)[k] * SC.half_edge, 0, 0]))))
       for k in range(2)]
second = solve_ivp(derivative(grasps), (SC.t_capture, SC.t_end), first.y[:, -1], method="BDF", rtol=RTOL,
                   atol=ATOL, t_eval=grid[grid >= SC.t_capture - 1e-9])
t = np.concatenate([first.t, second.t[1:]])
Y = np.concatenate([first.y.T, second.y.T[1:]])
print(f"{len(t)} saved states, {first.nfev + second.nfev} derivative evaluations")

Output:

221 saved states, 7513 derivative evaluations

What happened

The cube should end 0.6 m sideways and 0.3 m up from where it was captured, turned by 30° about the vertical axis; the satellites should stay near where they started with their attitude held; and every joint should stay inside its limits (those of the source model). The interesting numbers are the errors, which are those of the whole chain: planner, controller, grasp and integration.

LO = np.radians([-170, -160, -170, -160, -170, -160, -170.0])            # joint limits of the source model
HI = np.radians([170, 100, 170, 160, 170, 160, 170.0])
DH_OFFSET = np.array([0, np.pi, np.pi, np.pi, np.pi, np.pi, 0])           # the DH angle offsets of the joints

cube = Y[:, offsets[2]:offsets[3]]
ic = int(np.argmin(abs(t - SC.t_capture)))
shift = cube[-1, :3] - cube[ic, :3]
turn = float(np.degrees(2 * np.arctan2(cube[-1, 6], cube[-1, 3])))
print(f"hands from the face centres at capture: {gap[0]:.1e} m and {gap[1]:.1e} m")
print("the cube moved by", np.round(shift, 6), "m (asked 0, 0.6, 0.3); errors",
      np.round(1e6 * np.abs(shift - np.array(SC.carry)), 1), "micrometres")
print(f"the cube turned by {turn:.4f} degrees (asked 30)")

att_error, att_moment = [], []
for k in range(2):
    b = Y[:, offsets[k]:offsets[k + 1]]
    R0 = quat_to_rot(base_state(k)[3:])
    att_error.append(np.array([np.linalg.norm(rotation_vector(R0 @ quat_to_rot(r[3:7]).T)) for r in b]))
    att_moment.append(np.array([np.linalg.norm(SC.att_kp * rotation_vector(R0 @ quat_to_rot(r[3:7]).T)
                                               - SC.att_kd * r[17:20]) for r in b]))
    qm = (b[:, 7:6 + N] - DH_OFFSET + np.pi) % (2 * np.pi) - np.pi                # MuJoCo coordinates, in (-pi, pi]
    margin = np.degrees(np.minimum(qm - LO, HI - qm).min())
    print(f"satellite {k}: moved {np.linalg.norm(b[-1, :3] - b[0, :3]):.3f} m, attitude error at most "
          f"{np.degrees(att_error[k].max()):.2f} deg, peak attitude moment {att_moment[k].max():.0f} N m, "
          f"smallest joint-limit margin {margin:.1f} deg")

Output:

hands from the face centres at capture: 1.2e-05 m and 1.2e-05 m
the cube moved by [1.00000e-06 6.00013e-01 3.00008e-01] m (asked 0, 0.6, 0.3); errors [ 1.  12.6  8.2] micrometres
the cube turned by 29.9996 degrees (asked 30)
satellite 0: moved 0.050 m, attitude error at most 0.71 deg, peak attitude moment 47 N m, smallest joint-limit margin 12.5 deg
satellite 1: moved 0.070 m, attitude error at most 0.88 deg, peak attitude moment 58 N m, smallest joint-limit margin 12.5 deg
fig, ax = plt.subplots(1, 3, figsize=(11, 3.2))
for i, name in enumerate(("x", "y", "z")):
    ax[0].plot(t, cube[:, i] - cube[ic, i], label=name)
ax[0].set(xlabel="time (s)", ylabel="cube shift (m)", title="the cube is carried")
ax[0].legend()
for k in range(2):
    ax[1].plot(t, np.degrees(att_error[k]), label=f"satellite {k}")
    ax[2].plot(t, att_moment[k], label=f"satellite {k}")
ax[1].set(xlabel="time (s)", ylabel="attitude error (deg)", title="the attitude is held")
ax[2].set(xlabel="time (s)", ylabel="attitude moment (N m)", title="the moment that holds it")
ax[1].legend()
for a in ax:
    a.axvline(SC.t_capture, ls=":", color="gray")
fig.tight_layout()

Without the attitude moment the satellites would turn under the reaction of the arms, and the arms would be driven towards their joint limits; the moment is ideal (no saturation, no wheel momentum), so a real servicer would need reaction wheels, control-moment gyros or thrusters that can supply it.

What the end of the carry looks like

The two satellites (the cubes at their bases), the arms as lines through their joints, and the carried cube, at the end of the carry. The satellites' bases are cubes of 1.2 m edge. The script plays the same drawing as an animation instead.

def box_edges(centre, R, half):
    corners = np.array([[a, b, c] for a in (-1, 1) for b in (-1, 1) for c in (-1, 1)]) * half
    pts = centre + corners @ R.T
    pairs = [(i, j) for i in range(8) for j in range(i + 1, 8) if np.abs(corners[i] - corners[j]).sum() == 2 * half]
    return [pts[[i, j]] for i, j in pairs]
k_end = int(np.argmin(abs(t - 9.5)))
kins = kinematics_of(Y[k_end])
fig = plt.figure(figsize=(9, 5))
ax = fig.add_subplot(projection="3d")
colors = ["tab:blue", "tab:red"]
for k in range(2):
    kk = kins[k]
    ax.add_collection3d(Line3DCollection(box_edges(np.asarray(kk.origin[0]), np.asarray(kk.Q[0]), 0.6),
                                         colors=colors[k], linewidths=1))
    chain = np.array([np.asarray(kk.origin[i]) for i in range(1, N)] + [hand_state(kk)[0]])
    ax.plot(*chain.T, color="0.15", lw=4.5, solid_capstyle="round")
    ax.plot(*chain.T, color=colors[k], lw=2.5, solid_capstyle="round")
    ax.scatter(*chain[-1], color="k", s=30)
kc = kins[2]
ax.add_collection3d(Line3DCollection(box_edges(np.asarray(kc.origin[0]), np.asarray(kc.Q[0]), 0.4),
                                     colors="tab:green", linewidths=2))
ax.plot(*cube[:k_end + 1, :3].T, color="tab:green", ls=":")
ax.set(xlim=(-2.9, 2.9), ylim=(-1.5, 1.5), zlim=(-0.7, 1.7), xlabel="x (m)", ylabel="y (m)", zlabel="z (m)")
ax.set_box_aspect((5.8, 3.0, 2.4), zoom=1.25)
ax.view_init(elev=22, azim=-62)
fig.tight_layout()

What to try

  • A different carry or turn: change carry and turn in Scenario. The inverse kinematics has to find a posture for every point of the path; it raises an error if one is out of reach.
  • Without the attitude moment: set att_kp and att_kd to zero and watch the satellites turn and the arms approach their joint limits.
  • A softer grasp: reduce the grasp stiffness. A stiffer one makes the equations stiff for an explicit solver, and the light wrist (a hand link of 0.02 kg m²) limits what an explicit step can take.
  • Tighter tolerances: RTOL and ATOL set the integration error; the run time grows quickly.

The pattern is that of the planar example and of any coupled system on the package: one model and one case per body, a force law between them written outside the package, the opposite wrenches at the same point, and one derivative function; the three-dimensional task changes the controller and the state, not the structure.

Five robots carry a plate

Five differential-drive robots of the size of a Pioneer 3-DX carry a plate of 25 kg. The plate lies on them like a tray on five waiters, and the robots drive together, 3 m forward and 1.5 m to the side while the plate turns by 60°. No robot is attached to the world: each is a separate floating-base model of the package with its own wheels, and the plate is a sixth one. All six are simulated together in one derivative function. Nothing in the package is changed; the only coupling is a mount model written in the example, the same pattern as in the satellite examples, here with wheels and gravity.

The steps are those of any cooperative task:

  1. One model file per kind of body. The robot is the pioneer model of the package (a chassis, two driven wheels and a caster, with the soft tyre force of the wheels: section); the plate is a base alone (25 kg, centre of mass at the origin of its frame). The same robot file is used five times.
  2. One case per body. Each body keeps its own six-dimensional base and its joints; they are not joined in one kinematic tree, which would need closed loops.
  3. One derivative function. It takes the kinematics of the six bodies from for_kine, evaluates the five mount forces, turns each into the wrench array of its body with link_wrench (the opposite force for the plate) and calls sys_ode.
  4. A mount model as the only coupling, and a controller for each robot.

A differential-drive robot cannot move sideways, so five of them cannot hold a rigid plate rigidly. The mount is therefore a ball joint with a spring: a point of the plate is tied to a point on top of the chassis by a three-dimensional spring-damper, which carries the weight and pulls sideways but does not stop the robot from turning under it. The controller of each robot drives that point, which can go anywhere on the ground, instead of the robot's centre, which cannot.

The code on this page is the script examples/cooperative_transport.py of the download.

import logging
import os

import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp

import redysim_floating as rf
from redysim_floating.control.vehicle import wheel_pair

logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/cooperative_transport"       # the data of the example (next to the script in the download)

The models

The two model files are in the data folder of the example. The robot is a copy of pioneer.yaml of the package (a chassis of 9 kg, two wheels of 16.5 cm diameter 33 cm apart, a ball caster under the rear; the ground is the plane y = 0, y is up and the chassis points along its x axis). The plate is a model of a base alone, 25 kg, with the inertia of a disc of 0.75 m radius. Five points of the plate on a circle of 0.75 m, 72° apart, rest on the robots.

robot = rf.load_model(os.path.join(DATA, "pioneer.yaml"))[0]
plate = rf.load_model(os.path.join(DATA, "payload_plate.yaml"))[0]
N = 5                                                # the number of robots
bodies = [robot] * N + [plate]
sizes = [2 * (b.n + 5) + 2 for b in bodies]          # the state of a body: qb, q, dqb, dq and two energies
offsets = np.concatenate([[0], np.cumsum(sizes)]).astype(int)

RING, THICK = 0.75, 0.02                             # the mount points of the plate: a circle of 0.75 m, 2 cm under its centre
angles = 2.0 * np.pi * np.arange(N) / N
r_plate = np.array([[RING * np.cos(a), -THICK, RING * np.sin(a)] for a in angles])     # in the frame of the plate
E, TOP, AXLE = -0.10, 0.2225, 0.0809                 # the mount on the chassis: 10 cm behind the axle (towards the caster), on top
r_robot = np.array([E, TOP, 0.0])                    # in the frame of the chassis; the axle is 0.0809 m above the ground
print(f"robot: {sum(robot.m):.1f} kg, {robot.n - 1} wheels;  plate: {plate.m[0]:.0f} kg;  {N} robots carry {plate.m[0] / N:.0f} kg each")

Output:

robot: 10.0 kg, 2 wheels;  plate: 25 kg;  5 robots carry 5 kg each

The task and the controller

The plate moves in the plane of the ground. Its pose (position and heading) goes from rest to rest in 9 s along a cycloidal path, so that its motion starts and ends smoothly. The path of each robot's mount point follows from the plate's: the point of the plate that it holds, carried along. The heading of the robots is not part of the task; they find their own.

Each robot is driven by a point-tracking law. Its mount point is at a distance \(e\) = −0.1 m from the axle along the chassis, and the velocity of that point is \(\dot{m} = v f + e\,\omega\, g\) with \(f\) the forward direction of the chassis and \(g\) the direction to its left. This can be solved for the forward speed \(v\) and the turn rate \(\omega\) that give the point any wished velocity \(u\): \(v = u\cdot f\), \(\omega = u\cdot g / e\). The wished velocity is the velocity of the point on the plate plus a feedback on the measured position of the point, so that the formation is corrected by feedback. The wheel speeds follow from \(v\) and \(\omega\), and a limited torque proportional to their error drives each wheel, as in the diff_drive controller of the package. The controller does not know about the plate or the other robots.

Since the point is behind the axle, the law makes the robot tow the point: the stable direction is the one in which the rear of the robot (the caster) leads, so the robots start turned round, and carry the plate on their back half, over the axle and the caster.

def rot(psi):                                        # the plane of the ground (x, z) turned by the heading psi
    c, s = np.cos(psi), np.sin(psi)
    return np.array([[c, s], [-s, c]]), np.array([[-s, c], [-c, -s]])      # the matrix and its derivative


def cycloidal(t, t0, t1):
    """A smooth rise from 0 to 1 between ``t0`` and ``t1``, at rest at both ends: ``(s, ds/dt)``."""
    if t <= t0:
        return 0.0, 0.0
    if t >= t1:
        return 1.0, 0.0
    tau = (t - t0) / (t1 - t0)
    return tau - np.sin(2.0 * np.pi * tau) / (2.0 * np.pi), (1.0 - np.cos(2.0 * np.pi * tau)) / (t1 - t0)


GOAL, TURN = np.array([3.0, -1.5]), np.deg2rad(60.0)     # the plate moves 3 m in x and 1.5 m in z and turns by 60 degrees about y
T_MOVE, T_END = (1.0, 10.0), 12.0


def plate_task(t):
    """The wished pose of the plate against time: position (x, z), heading, and their rates."""
    s, ds = cycloidal(t, *T_MOVE)
    return GOAL * s, GOAL * ds, TURN * s, TURN * ds


def point_task(k, t):
    """The wished position and velocity of the mount point of robot ``k`` on the ground (x, z)."""
    p, dp, psi, dpsi = plate_task(t)
    R, dR = rot(psi)
    r = r_plate[k][[0, 2]]
    return p + R @ r, dp + dpsi * (dR @ r)


KP, KD, TAU_MAX = 4.0, 3.0, 3.0                      # position gain (1/s), wheel speed gain (N m s/rad), wheel torque limit (N m)
RADIUS, TRACK = wheel_pair(robot, 3, 2)               # the wheel radius and the distance between the wheels: read from the model


def controller(k):
    """``torque(t, robot, qb, dqb, q, dq)`` of robot ``k``: drive its mount point along its path."""
    def torque(t, robot, qb, dqb, q, dq):
        kin = rf.for_kine(robot, qb, dqb, q, dq)
        Q = kin.Q[0]
        f = np.array([Q[0, 0], Q[2, 0]])             # the forward direction of the chassis on the ground
        g = np.array([f[1], -f[0]])                  # ... and the direction to its left
        point = (kin.origin[0] + Q @ r_robot)[[0, 2]]
        wished, speed = point_task(k, t)
        u = speed + KP * (wished - point)            # the velocity the point is to have
        v, w = u @ f, (u @ g) / E                    # the forward speed and the turn rate that give it
        tu = np.zeros(2)                             # the wheel torques: link 2 is the right wheel, link 3 the left
        tu[1] = np.clip(KD * ((v - 0.5 * w * TRACK) / RADIUS - dq[1]), -TAU_MAX, TAU_MAX)
        tu[0] = np.clip(KD * ((v + 0.5 * w * TRACK) / RADIUS - dq[0]), -TAU_MAX, TAU_MAX)
        return np.zeros(6), tu
    return torque

The mount: the only coupling

At each robot the mount ties a point of the plate to a point on top of the chassis with a spring-damper in three dimensions: \(F = -k\,(m_\mathrm{robot} - m_\mathrm{plate}) - c\,(\dot m_\mathrm{robot} - \dot m_\mathrm{plate})\). It carries a fifth of the weight (about 49 N, a sag of 2.5 mm) and pulls the plate along. The force acts on the chassis at the mount point, and the opposite force acts at the same point on the plate, so the coupling conserves linear and angular momentum between the bodies. It has no moment: the robot is free to turn under the plate.

STIFFNESS, DAMPING = 2.0e4, 4.0e2                    # N/m and N s/m, of each mount


def point_of(kin, local):
    """Position and velocity, in the inertial frame, of the point ``local`` of the first link of a body."""
    Q = kin.Q[0]
    r = Q @ local
    return kin.origin[0] + r, kin.vstart[0] + np.cross(Q @ kin.tt[0], r)


def mounts(kin):
    """``(force on the robot, point on the robot, point on the plate)`` for each of the five mounts."""
    out = []
    for k in range(N):
        a, va = point_of(kin[k], r_robot)
        b, vb = point_of(kin[N], r_plate[k])
        out.append((-STIFFNESS * (a - b) - DAMPING * (va - vb), a, b))
    return out

The coupled simulation

One case per body: the robots with their controller (the initial pose has the mount points under the plate, the robots turned round), the plate with no torques. The derivative function stacks the six states, turns the mount forces into the fext arrays of the chassis and of the plate with link_wrench, and calls sys_ode for each body. A stiff solver from SciPy (BDF) integrates, because the tyres and the mounts are stiff.

cases = []
for k in range(N):
    forward = np.array([np.cos(np.pi), -np.sin(np.pi)])      # the robots start turned round: their rear is towards the motion
    axle = r_plate[k][[0, 2]] - E * forward                  # the mount point is E along the chassis from the axle
    cases.append(rf.ForDynCase(robot=robot, qb0=[axle[0], AXLE, axle[1], 0.0, 0.0, np.pi], q0=[0.0, 0.0],
                               dqb0=np.zeros(6), dq0=np.zeros(2), torque=controller(k)))
cases.append(rf.ForDynCase(robot=plate, qb0=[0.0, AXLE + TOP + THICK, 0.0, 0.0, 0.0, 0.0], q0=[],
                           dqb0=np.zeros(6), dq0=[]))


def parts(y):
    return [y[offsets[k]:offsets[k + 1]] for k in range(N + 1)]


def kinematics_of(y):
    out = []
    for case, p in zip(cases, parts(y), strict=True):
        n = case.robot.n
        out.append(rf.for_kine(case.robot, p[:6], p[5 + n:11 + n], p[6:5 + n], p[11 + n:10 + 2 * n]))
    return out


def derivative(t, y):
    p = parts(y)
    kin = kinematics_of(y)
    fext = [None] * (N + 1)
    on_plate = np.zeros((1, 6))
    for k, (force, a, b) in enumerate(mounts(kin)):
        fext[k] = rf.link_wrench(robot, p[k][:6], p[k][6:8], 1, force=force, point=a)
        rf.link_wrench(plate, p[N][:6], [], 1, force=-force, point=b, out=on_plate)
    fext[N] = on_plate
    return np.concatenate([rf.sys_ode(cases[k], t, p[k], fext[k])[0] for k in range(N + 1)])


STEP = 0.05
y0 = np.concatenate([c.y0 for c in cases])
solution = solve_ivp(derivative, (0.0, T_END), y0, method="BDF", rtol=1e-5, atol=1e-7,
                     t_eval=np.arange(0.0, T_END + 0.5 * STEP, STEP))
t, Y = solution.t, solution.y.T
print(f"{len(t)} saved states, {solution.nfev} derivative evaluations")

Output:

241 saved states, 4274 derivative evaluations

What happened

After the run: how close the plate came to the wished pose, how well each robot held its place, the forces in the mounts (their vertical sum must be the weight of the plate when it is at rest), and how far apart the robots stayed (a robot is 0.45 m long, and the model has no contact between robots, so they must not meet).

def states(k):
    n = bodies[k].n
    y = Y[:, offsets[k]:offsets[k + 1]]
    return y[:, :6], y[:, 6:5 + n], y[:, 5 + n:11 + n], y[:, 11 + n:10 + 2 * n]


kin = [[rf.for_kine(bodies[k], *s) for s in zip(*[states(k)[i] for i in (0, 2, 1, 3)], strict=True)]
       for k in range(N + 1)]                            # for_kine(robot, qb, dqb, q, dq) at every saved time

force = np.zeros((len(t), N, 3))                         # the mount forces on the plate (reaction of those on the robots)
error = np.zeros((len(t), N))                            # the distance of each mount point from its wished place
for i, ti in enumerate(t):
    step_kin = [kin[k][i] for k in range(N + 1)]
    for k, (f, a, _) in enumerate(mounts(step_kin)):
        force[i, k] = -f
        error[i, k] = np.linalg.norm(a[[0, 2]] - point_task(k, ti)[0])

plate_qb = states(N)[0]
wished = np.array([plate_task(ti)[0] for ti in t])
heading = np.array([plate_task(ti)[2] for ti in t])
position_error = np.linalg.norm(plate_qb[:, [0, 2]] - wished, axis=1)
axles = np.array([[kin[k][i].origin[0][[0, 2]] for k in range(N)] for i in range(len(t))])
gaps = np.min([[np.linalg.norm(axles[i, a] - axles[i, b]) for a in range(N) for b in range(a + 1, N)]
               for i in range(len(t))], axis=1)
weight = plate.m[0] * 9.81
rest = len(t) - 1

print(f"the plate ends at ({plate_qb[rest, 0]:.4f}, {plate_qb[rest, 2]:.4f}) m, asked ({GOAL[0]}, {GOAL[1]}); "
      f"turned by {np.rad2deg(plate_qb[rest, 5]):.2f} degrees, asked {np.rad2deg(TURN):.0f}")
print(f"the plate is at most {position_error.max() * 100:.1f} cm from its wished position, "
      f"{np.rad2deg(np.abs(plate_qb[:, 5] - heading).max()):.1f} degrees from its wished heading")
print(f"the plate sags by {1e3 * (plate_qb[0, 1] - plate_qb[:, 1].min()):.1f} mm and ends level (tilt {np.rad2deg(np.abs(plate_qb[rest, 3:5]).max()):.3f} degrees)")
print(f"each mount point is at most {error.max() * 100:.1f} cm from its wished place; at the end {error[rest].max() * 1e3:.1f} mm")
print(f"the mount forces add up to {force[rest].sum(axis=0)[1]:.1f} N upwards at the end (the weight is {weight:.1f} N)")
print(f"the strongest mount force is {np.linalg.norm(force, axis=2).max():.0f} N; the robots stay at least {gaps.min():.2f} m apart")

Output:

the plate ends at (3.0000, -1.5000) m, asked (3.0, -1.5); turned by 60.00 degrees, asked 60
the plate is at most 0.3 cm from its wished position, 0.0 degrees from its wished heading
the plate sags by 2.5 mm and ends level (tilt 0.000 degrees)
each mount point is at most 0.3 cm from its wished place; at the end 0.0 mm
the mount forces add up to 245.3 N upwards at the end (the weight is 245.2 N)
the strongest mount force is 57 N; the robots stay at least 0.87 m apart
fig, ax = plt.subplots(2, 2, figsize=(10, 6))
ax[0, 0].plot(t, plate_qb[:, 0], label="x")
ax[0, 0].plot(t, plate_qb[:, 2], label="z")
ax[0, 0].plot(t, plate_qb[:, 5], label="heading (rad)")
ax[0, 0].set(xlabel="time (s)", ylabel="plate pose (m, rad)", title="the plate goes 3 m, 1.5 m and turns 60 degrees")
ax[0, 0].legend()
ax[0, 1].plot(t, 100 * position_error, label="plate (cm)")
for k in range(N):
    ax[0, 1].plot(t, 100 * error[:, k], lw=1.0, label=f"mount {k + 1}" if k < 2 else None)
ax[0, 1].set(xlabel="time (s)", ylabel="distance from the wished place (cm)", title="the robots hold their places")
ax[0, 1].legend()
for k in range(N):
    ax[1, 0].plot(t, np.linalg.norm(force[:, k], axis=1), label=f"robot {k + 1}")
ax[1, 0].axhline(weight / N, color="gray", ls=":")
ax[1, 0].set(xlabel="time (s)", ylabel="mount force (N)", title="the mounts share the weight (dotted: a fifth)")
ax[1, 0].legend(ncol=2, fontsize=8)
ax[1, 1].plot(t, force.sum(axis=1)[:, 1], label="vertical, sum of the five")
ax[1, 1].axhline(weight, color="gray", ls=":", label="weight of the plate")
ax[1, 1].plot(t, gaps * 100, label="smallest gap between robots (cm)")
ax[1, 1].set(xlabel="time (s)", ylabel="N, cm", title="the weight is carried; the robots do not meet")
ax[1, 1].legend(fontsize=8)
for a in ax.ravel():
    a.axvspan(*T_MOVE, color="0.93", zorder=0)
fig.tight_layout()

What the motion looks like

A view from above at five moments (the last is the end): the five robots (their chassis and wheels) and the plate (a circle through the five mount points), with earlier poses lighter, and the path of the centre of the plate. The script plays the same drawing as an animation instead.

def robot_outline(i, k):
    Q, o = kin[k][i].Q[0], kin[k][i].origin[0]
    corners = np.array([[0.2225, -0.2], [0.2225, 0.2], [-0.2225, 0.2], [-0.2225, -0.2], [0.2225, -0.2]])
    pts = np.array([o + Q @ np.array([x, 0.0, z]) for x, z in corners])
    return pts[:, [0, 2]], np.array([o, o + Q @ np.array([0.3, 0.0, 0.0])])[:, [0, 2]]
shown = [int(np.argmin(abs(t - s))) for s in (0.0, 2.5, 4.5, 6.5, T_END)]
fig, ax = plt.subplots(figsize=(9, 5))
ax.plot(*plate_qb[:, [0, 2]].T, color="tab:orange", lw=1.2)
circle = np.linspace(0.0, 2.0 * np.pi, 100)
for n, i in enumerate(shown):
    last = n == len(shown) - 1
    light = 0.35 + 0.65 * n / (len(shown) - 1)
    c = plate_qb[i, [0, 2]]
    R2, _ = rot(plate_qb[i, 5])
    ring = np.array([c + R2 @ (RING * np.array([np.cos(a), np.sin(a)])) for a in circle])
    ax.plot(*ring.T, color="tab:green" if last else "#a6dcc8", lw=2.5 if last else 1.5)
    for k in range(N):
        box, nose = robot_outline(i, k)
        ax.plot(*box.T, color="0.15" if last else str(1 - light * 0.8), lw=1.5)
        ax.plot(*nose.T, color="tab:red" if last else "#f0b8b0", lw=1.2)     # the front of the chassis
ax.set_aspect("equal")
ax.invert_yaxis()                                        # z is to the right of the robot: keep x to the right and z down
ax.set(xlabel="x (m)", ylabel="z (m)", title="five robots carry the plate (red: the front of the robots)")
fig.tight_layout()

What to try

  • A different task: change GOAL and TURN (for instance (2.0, 2.0) and 180°) and run again; the paths of the mount points follow. With a large turn the robots on the inside of the curve are slow and the outer ones fast.
  • Fewer or more robots: change N; the mount points are spread evenly on the circle.
  • A heavier plate: raise the mass in payload_plate.yaml. The load of a mount is behind the axle, over the caster side of the chassis, which is why the robots do not tip; keep E negative.
  • A softer mount: reduce STIFFNESS and the plate lags more behind the robots.
  • Another path: replace plate_task by any smooth pose against time; the robots do not need to know the future, only where their own point should be now and how fast it moves.

The pattern is the one for any coupled system on the package: one model and one case per body, a force law between them written outside the package, the opposite forces at the same point, and one derivative function.

Five robots in formation

Five differential-drive robots of the size of a Pioneer 3-DX start side by side in a line, and drive into a pentagon that then moves 4 m and turns by 90°. The line is numbered from one end and the slots of the pentagon are given so that the robots have to swap places: their paths cross in the first seconds, and the robots push against each other, which the controllers do not know about. Nothing is attached to anything and there is no plate: the only coupling between the five bodies is a soft contact between robots written in the example.

Each robot is a separate floating-base model of the package, with its own wheels and tyres, and the five are simulated together in one derivative function. Nothing in the package is changed. The steps are those of any multi-robot simulation:

  1. One model file for the kind of robot (the pioneer model of the package), used five times.
  2. One case per robot, each with its own initial pose and its own controller.
  3. One derivative function. It takes the kinematics of the five robots from for_kine, evaluates the contacts, turns each into the wrench array of the two robots with link_wrench and calls sys_ode for each robot.
  4. A contact model as the only coupling, and a controller for each robot.

This is the same pattern as the five robots that carry a plate (cooperative_transport); there the coupling is a mount that carries a load, here it is a contact that keeps robots apart.

The code on this page is the script examples/multi_robot.py of the download.

import logging
import os

import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp

import redysim_floating as rf
from redysim_floating.control.vehicle import wheel_pair

logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/multi_robot"                  # the data of the example (next to the script in the download)

The model and the task

The model file is a copy of pioneer.yaml of the package (a chassis of 9 kg, two wheels of 16.5 cm diameter 33 cm apart, a ball caster under the rear; the ground is the plane y = 0, y is up, and the chassis points along its x axis).

The robots start in a line along z, 0.8 m apart, all pointing along x, with their control points (below) on the line. The task of a robot is the path of its control point, a point 15 cm ahead of the axle: the point of a differential-drive robot can follow any path on the ground, the centre of the axle cannot move sideways. The paths are those of a formation: the centre of the formation moves 4 m along x while it turns by 90°, and each robot's slot goes, in the first 4 s, from its place in the line to its place in a pentagon of 1 m radius. The slot is SLOTS[k]: robot k goes to the pentagon corner of that number, and the numbers are reversed, so that the robot at one end of the line goes to the other side of the pentagon.

robot = rf.load_model(os.path.join(DATA, "pioneer.yaml"))[0]
N = 5                                                # the number of robots
sizes = 2 * (robot.n + 5) + 2                        # the state of a body: qb, q, dqb, dq and two energies
offsets = sizes * np.arange(N + 1)
AXLE, E = 0.0809, 0.15                               # the height of the axle; the control point is E ahead of it
RADIUS, TRACK = wheel_pair(robot, 3, 2)               # the wheel radius and the distance between the wheels: read from the model

line = np.array([[0.0, 0.8 * (k - 2)] for k in range(N)])                      # the start: a line along z, (x, z)
corner = 2.0 * np.pi * np.arange(N) / N
pentagon = np.array([[np.cos(a), np.sin(a)] for a in corner])                   # the formation: a pentagon of 1 m radius
SLOTS = [4, 3, 2, 1, 0]                                                         # the corner of the pentagon of each robot


def cycloidal(t, t0, t1):
    """A smooth rise from 0 to 1 between ``t0`` and ``t1``, at rest at both ends: ``(s, ds/dt)``."""
    if t <= t0:
        return 0.0, 0.0
    if t >= t1:
        return 1.0, 0.0
    tau = (t - t0) / (t1 - t0)
    return tau - np.sin(2.0 * np.pi * tau) / (2.0 * np.pi), (1.0 - np.cos(2.0 * np.pi * tau)) / (t1 - t0)


def rotation(psi):                                   # the plane of the ground (x, z) turned by psi, and its derivative
    c, s = np.cos(psi), np.sin(psi)
    return np.array([[c, s], [-s, c]]), np.array([[-s, c], [-c, -s]])


T_FORM, T_MOVE, T_END = (0.0, 4.0), (3.0, 11.0), 13.0
GOAL, TURN = np.array([4.0, 0.0]), np.deg2rad(90.0)  # the centre of the formation moves 4 m in x and turns by 90 degrees


def point_task(k, t):
    """The wished position and velocity of the control point of robot ``k`` (x, z)."""
    a, da = cycloidal(t, *T_FORM)                    # the formation closes from the line
    b, db = cycloidal(t, *T_MOVE)                    # ... and moves
    slot = (1 - a) * line[k] + a * pentagon[SLOTS[k]]
    dslot = da * (pentagon[SLOTS[k]] - line[k])
    R, dR = rotation(TURN * b)
    centre = GOAL * b
    return centre + R @ slot, GOAL * db + TURN * db * (dR @ slot) + R @ dslot

The controller

Each robot is driven by a point-tracking law. Its control point is at a distance \(e\) = 0.15 m ahead of the axle along the chassis, and the velocity of that point is \(\dot{m} = v f + e\,\omega\, g\) with \(f\) the forward direction of the chassis and \(g\) the direction to its left. This can be solved for the forward speed \(v\) and the turn rate \(\omega\) that give the point any wished velocity \(u\): \(v = u\cdot f\), \(\omega = u\cdot g / e\). The wished velocity is the velocity of the path plus a feedback on the measured position of the point. The wheel speeds follow from \(v\) and \(\omega\), and a limited torque proportional to their error drives each wheel, as in the diff_drive controller of the package. A controller knows nothing about the other robots.

KP, KD, TAU_MAX = 4.0, 3.0, 3.0                      # position gain (1/s), wheel speed gain (N m s/rad), wheel torque limit (N m)


def controller(k):
    """``torque(t, robot, qb, dqb, q, dq)`` of robot ``k``: drive its control point along its path."""
    def torque(t, robot, qb, dqb, q, dq):
        Q = rf.for_kine(robot, qb, dqb, q, dq).Q[0]
        f = np.array([Q[0, 0], Q[2, 0]])             # the forward direction of the chassis on the ground
        g = np.array([f[1], -f[0]])                  # ... and the direction to its left
        point = np.array([qb[0], qb[2]]) + E * f
        wished, speed = point_task(k, t)
        u = speed + KP * (wished - point)            # the velocity the point is to have
        v, w = u @ f, (u @ g) / E                    # the forward speed and the turn rate that give it
        tu = np.zeros(2)                             # the wheel torques: link 2 is the right wheel, link 3 the left
        tu[1] = np.clip(KD * ((v - 0.5 * w * TRACK) / RADIUS - dq[1]), -TAU_MAX, TAU_MAX)
        tu[0] = np.clip(KD * ((v + 0.5 * w * TRACK) / RADIUS - dq[0]), -TAU_MAX, TAU_MAX)
        return np.zeros(6), tu
    return torque

The contact: the only coupling

A robot is taken as a disc of 0.25 m radius around its axle. When the centres of two discs are closer than 0.5 m, a spring-damper pushes them apart along the line between the centres: \(F = (k\,\delta - c\,\dot\delta)\) with \(\delta\) the overlap and \(\dot\delta\) its rate, and \(F\) is not allowed to pull. The force acts on the chassis of each robot at the origin of its frame (at the height of the axle), and the two forces are equal and opposite, so the contact conserves momentum. There is no friction between the robots, and the discs are only an approximation of the chassis.

REACH, STIFFNESS, DAMPING = 0.25, 3.0e3, 60.0        # radius of the disc (m), N/m and N s/m of the contact


def contacts(kin):
    """The contact force on every robot (x, y, z), and the number of the pairs that touch."""
    force, touching = np.zeros((N, 3)), 0
    for a in range(N):
        for b in range(a + 1, N):
            d = kin[a].origin[0] - kin[b].origin[0]
            d[1] = 0.0                               # the contact acts on the ground
            dist = np.linalg.norm(d)
            if dist >= 2.0 * REACH or dist < 1e-9:
                continue
            n = d / dist
            closing = (kin[a].vstart[0] - kin[b].vstart[0]) @ n
            f = max(STIFFNESS * (2.0 * REACH - dist) - DAMPING * closing, 0.0) * n
            force[a] += f
            force[b] -= f
            touching += 1
    return force, touching

The coupled simulation

One case per robot, each with its controller. The derivative function stacks the five states, turns the contact forces into the fext arrays with link_wrench, and calls sys_ode for each robot. A stiff solver from SciPy (BDF) integrates, because the tyres are stiff.

cases = [rf.ForDynCase(robot=robot, qb0=[line[k, 0] - E, AXLE, line[k, 1], 0.0, 0.0, 0.0], q0=[0.0, 0.0],
                       dqb0=np.zeros(6), dq0=np.zeros(2), torque=controller(k)) for k in range(N)]


def parts(y):
    return [y[offsets[k]:offsets[k + 1]] for k in range(N)]


def kinematics_of(y):
    return [rf.for_kine(robot, p[:6], p[10:16], p[6:8], p[16:18]) for p in parts(y)]


def derivative(t, y):
    p = parts(y)
    force, _ = contacts(kinematics_of(y))
    return np.concatenate([rf.sys_ode(cases[k], t, p[k],
                                      rf.link_wrench(robot, p[k][:6], p[k][6:8], 1, force=force[k]))[0]
                           for k in range(N)])


STEP = 0.05
y0 = np.concatenate([c.y0 for c in cases])
solution = solve_ivp(derivative, (0.0, T_END), y0, method="BDF", rtol=1e-5, atol=1e-7,
                     t_eval=np.arange(0.0, T_END + 0.5 * STEP, STEP))
t, Y = solution.t, solution.y.T
print(f"{len(t)} saved states, {solution.nfev} derivative evaluations")

Output:

261 saved states, 5713 derivative evaluations

What happened

After the run: how well each control point followed its path, how close the robots came to each other and for how long they touched, how large the contact forces were, and where the formation ended.

def states(k):
    y = Y[:, offsets[k]:offsets[k + 1]]
    return y[:, :6], y[:, 6:8], y[:, 10:16], y[:, 16:18]


kin = [[rf.for_kine(robot, *s) for s in zip(*[states(k)[i] for i in (0, 2, 1, 3)], strict=True)] for k in range(N)]
force = np.zeros((len(t), N, 3))
touching = np.zeros(len(t), dtype=int)
error = np.zeros((len(t), N))                            # the distance of each control point from its path
gap = np.zeros(len(t))                                   # the smallest distance between two axles
for i, ti in enumerate(t):
    step_kin = [kin[k][i] for k in range(N)]
    force[i], touching[i] = contacts(step_kin)
    for k in range(N):
        Q = step_kin[k].Q[0]
        point = step_kin[k].origin[0][[0, 2]] + E * np.array([Q[0, 0], Q[2, 0]])
        error[i, k] = np.linalg.norm(point - point_task(k, ti)[0])
    gap[i] = min(np.linalg.norm(step_kin[a].origin[0] - step_kin[b].origin[0]) for a in range(N) for b in range(a + 1, N))
peak = np.linalg.norm(force, axis=2).max(axis=1)
meet = np.flatnonzero(touching)

print(f"the control points are at most {error.max() * 100:.1f} cm from their paths, and {error[-1].max() * 1e3:.1f} mm at the end")
print(f"the robots touched during {len(meet) * STEP:.2f} s (from t = {t[meet[0]]:.2f} s to {t[meet[-1]]:.2f} s); "
      f"the strongest contact force is {peak.max():.0f} N" if len(meet) else "the robots never touched")
print(f"the smallest distance between two axles is {gap.min():.3f} m (the discs touch at {2 * REACH:.2f} m)")
centre = np.mean([kin[k][-1].origin[0][[0, 2]] + E * kin[k][-1].Q[0][[0, 2], 0] for k in range(N)], axis=0)
print(f"the centre of the control points ends at ({centre[0]:.3f}, {centre[1]:.3f}) m, asked ({GOAL[0]}, {GOAL[1]})")

Output:

the control points are at most 3.5 cm from their paths, and 0.0 mm at the end
the robots touched during 0.60 s (from t = 1.65 s to 2.20 s); the strongest contact force is 66 N
the smallest distance between two axles is 0.443 m (the discs touch at 0.50 m)
the centre of the control points ends at (4.000, -0.000) m, asked (4.0, 0.0)
fig, ax = plt.subplots(2, 2, figsize=(10, 6))
for k in range(N):
    ax[0, 0].plot(t, 100 * error[:, k], label=f"robot {k + 1}")
ax[0, 0].set(xlabel="time (s)", ylabel="distance from the path (cm)", title="the control points follow their paths")
ax[0, 0].legend(ncol=2, fontsize=8)
ax[0, 1].plot(t, gap * 100)
ax[0, 1].axhline(100 * 2 * REACH, color="gray", ls=":")
ax[0, 1].set(xlabel="time (s)", ylabel="smallest distance between axles (cm)", title="the robots touch (dotted: contact)")
ax[1, 0].plot(t, peak)
ax[1, 0].set(xlabel="time (s)", ylabel="largest contact force (N)", title="the contact force")
for k in range(N):
    ax[1, 1].plot(*states(k)[0][:, [0, 2]].T, label=f"robot {k + 1}")
ax[1, 1].set(xlabel="x (m)", ylabel="z (m)", title="the paths of the axles")
ax[1, 1].invert_yaxis()
ax[1, 1].legend(ncol=2, fontsize=8)
for a in ax.ravel()[:3]:
    a.axvspan(*T_FORM, color="0.93", zorder=0)
fig.tight_layout()

What the motion looks like

A view from above at five moments (the last is the end): the five robots (their chassis, numbered) with the front of each marked, earlier poses lighter. The script plays the same drawing as an animation instead.

def outline(i, k):
    Q, o = kin[k][i].Q[0], kin[k][i].origin[0]
    corners = np.array([[0.2225, -0.2], [0.2225, 0.2], [-0.2225, 0.2], [-0.2225, -0.2], [0.2225, -0.2]])
    box = np.array([o + Q @ np.array([x, 0.0, z]) for x, z in corners])[:, [0, 2]]
    return box, np.array([o, o + Q @ np.array([0.3, 0.0, 0.0])])[:, [0, 2]]
shown = [int(np.argmin(abs(t - s))) for s in (0.0, 1.5, 3.0, 6.5, T_END)]
fig, ax = plt.subplots(figsize=(9, 5))
colors = plt.cm.tab10(np.arange(N))
for n, i in enumerate(shown):
    last = n == len(shown) - 1
    for k in range(N):
        box, nose = outline(i, k)
        ax.plot(*box.T, color=colors[k], alpha=1.0 if last else 0.25 + 0.15 * n, lw=1.6)
        ax.plot(*nose.T, color="k", alpha=1.0 if last else 0.3, lw=1.0)
        if last:
            ax.annotate(str(k + 1), box[:4].mean(axis=0), ha="center", va="center", fontsize=9)
ax.set_aspect("equal")
ax.invert_yaxis()                                        # z is to the right of the robot: keep x to the right and z down
ax.set(xlabel="x (m)", ylabel="z (m)", title="five robots swap places and form a pentagon")
fig.tight_layout()

What to try

  • No swap: change SLOTS to [0, 1, 2, 3, 4]; the paths no longer cross and the contacts stay away.
  • A tighter formation: shrink the pentagon (the unit radius in pentagon); below about 0.45 m the neighbours in the pentagon touch each other even at rest.
  • A stiffer contact: raise STIFFNESS; the robots bounce off each other harder, and a much stiffer contact needs a smaller tolerance of the solver.
  • More robots: change N and line; the pentagon becomes an N-gon.
  • A different task: replace point_task by any path against time. The controller needs only where its point should be now and how fast it moves.

The pattern is the one for any coupled system on the package: one model and one case per body, a force law between them written outside the package, the opposite forces on both bodies, and one derivative function.