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/kinova_pick_and_lift.py. A copy of the scripts is also installed with the package, so the Runner finds them after a normal pip install; redysim --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 pick and lift takes about 5 to 10 seconds on a quiet machine, and longer when the machine is busy.
Pick and lift: an arm, a gripper and a cube¶
A Kinova Gen3 Lite arm with its two-finger gripper picks up a 6 cm cube and lifts it. This is a coupled
system built on the package without changing it. The cube is part of the redysim robot: a second chain
of six joints, which starts at the fixed base like the arm does and carries the cube. The package integrates
arm, gripper and cube as one system; only the contact forces are written in the example, and they enter the
robot as external wrenches (fext) on the finger links and on the cube.
Why this works: the base is fixed, so two chains from it do not influence each other except through the
forces between their links. The generalized inertia matrix of the whole robot is block diagonal, and
parent: 0 can be given to any number of links. A body that moves freely, like this cube, is therefore a
chain of three prismatic and three revolute joints, and nothing about its dynamics has to be written here.
Three things in this example go beyond a model file:
- The gripper has constraints. One finger joint is driven; the three others follow it
(
q_follower = c0 + c1 q_driven). A model file cannot express that, so the robot is built in Python as a closed-loop system with the three linear constraints (ForDynCase.jacobian). - The contacts are written here. They are penalty point contacts: a vertex of a finger pad that is inside
the cube is pushed out along the nearest face with
k depth - c v_nand a regularized Coulomb friction. - The solver needs a looser absolute tolerance on the cube's coordinates (see the end of the simulation section), or it takes many times longer.
The cube's orientation is three revolute angles, so it has a singularity (the middle angle at plus or minus 90 degrees). This task never comes near it; a cube that tumbles freely would.
It is a teaching example, not a fast simulator: one 3.6 s task takes a few seconds to half a minute depending on the machine, against tens of milliseconds for a compiled contact solver such as MuJoCo's. Not modelled: contact between the palm, the proximal finger links or the arm and the cube, and the grasp is tuned to this cube size.
The code on this page is the script examples/kinova_pick_and_lift.py of the download.
import json
import logging
import os
import time
import matplotlib.pyplot as plt
import numpy as np
import yaml
from scipy.integrate import solve_ivp
from redysim import Robot
from redysim.kinematics.forward import for_kine, link_frames
from redysim.model.cases import ForDynCase
from redysim.model.modelfile import robot_from_dict
from redysim.simulation.fordyn import sys_ode
logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/kinova_pick_and_lift" # the data of the example (next to the script in the download)
The robot with its gripper¶
gripper.yaml has ten joints: the six arm joints, then the bottom and tip joints of the right finger, then of
the left finger. In the real gripper only right_finger_bottom is driven; the other three follow it:
(0-based joint numbers, MuJoCo's joint values). These are three constant linear constraints \(J q = c\), which the
package's closed-loop interface takes: the robot has closed_loop=True and dof=7, and the case gives the
constraint Jacobian (constant, so its derivative is zero). The joint values of the file are those of
MuJoCo plus Q0, the DH angle offsets in fordyn.q0.
DOC = yaml.safe_load(open(os.path.join(DATA, "gripper.yaml")))
Q0 = np.array(DOC["fordyn"]["q0"]) # MuJoCo coordinates + Q0 = ReDySim coordinates
N, DOF, DRIVER = 10, 7, 6 # joints, free joints, the driven finger joint
FOLLOWERS = [(7, 0.149, -0.676), (8, 0.0, -1.0), (9, 0.149, -0.676)] # (joint, c0, c1)
J = np.zeros((len(FOLLOWERS), N)) # J q = const: q_f - c1 q_driven = c0
for row, (f, c0, c1) in enumerate(FOLLOWERS):
J[row, f], J[row, DRIVER] = 1.0, -c1
DJ = np.zeros_like(J)
ARMATURE = 0.01 # kg m^2 added about every joint axis (rotor inertia)
links = [dict(link, inertia=list(link["inertia"])) for link in DOC["links"]]
for f, _, _ in FOLLOWERS:
links[f]["actuated"] = False # the followers have no motor of their own
for link in links:
link["inertia"][2] += ARMATURE # the link z axis is the joint axis
ROBOT = Robot.from_links(links, [0.0, 0.0, 0.0], closed_loop=True, dof=DOF,
name="Kinova Gen3 Lite with gripper") # gravity acts on the cube only
print(ROBOT.name, "|", N, "joints,", DOF, "free")
def constraints(q, dq):
return J, DJ # as ForDynCase(jacobian=...) expects
def gripper_q(q):
"""The driven finger joint in MuJoCo coordinates."""
return q[DRIVER] - Q0[DRIVER]
Output:
The task: waypoints and control¶
The arm follows four poses (hover, above the cube, grasp, lift) with a cycloidal path between them, and the
gripper closes at 1.5 s. The arm poses were found once by task-space inverse kinematics for a tool
position above the cube; they are data in pick_data.json, with the vertices of the two finger-pad boxes
(computed from the MuJoCo model's collision boxes, in the frame of their links).
The arm is a PD law on each joint with damping, and the gripper's driven joint a velocity law.
DATA_JSON = json.load(open(os.path.join(DATA, "pick_data.json")))
WAYPOINT = {k: np.array(v) for k, v in DATA_JSON["arm_q_mujoco"].items()}
CUBE_START = np.array(DATA_JSON["object_position"])
OPEN_Q, CLOSE_Q = 0.8, 0.05 # the driven finger: open and closed
T_CLOSE, T_LIFT, T_END = 1.5, 2.4, 3.6
MOVES = [(0.0, 0.6, "ready_hover", "above_object"), (0.6, 1.4, "above_object", "grasp"),
(T_LIFT, T_LIFT + 0.8, "grasp", "lift")]
KP, KV, DAMP, KG = 50.0, 5.0, 0.5, 1.0 # arm PD, joint damping, gripper speed gain
def arm_reference(t):
q = WAYPOINT["ready_hover"]
for t0, t1, a, b in MOVES:
if t >= t1:
q = WAYPOINT[b]
elif t > t0:
s = (t - t0) / (t1 - t0)
s = s - np.sin(2 * np.pi * s) / (2 * np.pi) # cycloidal
q = WAYPOINT[a] + s * (WAYPOINT[b] - WAYPOINT[a])
return q
def gripper_command(t, q_driven):
target = OPEN_Q if t < T_CLOSE else CLOSE_Q
return min(1.0, max(-1.0, 3.0 * (target - q_driven)))
def torque(t, tf, rb, q, dq):
tau = np.zeros(N)
tau[:6] = KP * (arm_reference(t) + Q0[:6] - q[:6]) - (KV + DAMP) * dq[:6]
tau[DRIVER] = KG * (gripper_command(t, gripper_q(q)) - dq[DRIVER]) - DAMP * dq[DRIVER]
tau[7:] = -DAMP * dq[7:]
return tau
CASE = ForDynCase(robot=ROBOT, q0=np.zeros(N), dq0=np.zeros(N), ti=0.0, tf=T_END, incr=0.02,
jacobian=constraints, torque=torque)
The cube and the contacts¶
The cube is a rigid body of 50 g (its motion comes from the chain below). Gravity acts on it; the arm has none here, as the MuJoCo model compensates it. Three kinds of contact:
- Pad vertices against the cube. The eight vertices of each distal finger pad's box. A vertex inside the
cube is pushed out along the nearest face with
k depth - c v_n(k = 2400N/m,c = 5N s/m) and a regularized Coulomb friction (mu = 1). - Cube edges against the pads. Points along the cube's twelve edges against each pad's box, pushed out through the pad's face. The pads are tilted a few degrees against the cube's faces, so the cube's edge reaches a pad face before a pad vertex reaches the cube; without this the edge goes through the pad.
- The cube's corners against the table (the plane \(z = 0\)), by the same law.
Each force on a finger link is turned into a wrench about the link origin in the link frame and passed to the
robot as fext; the opposite force and moment go to the cube.
CUBE_DOC = yaml.safe_load(open(os.path.join(DATA, "cube.yaml")))
MASS = CUBE_DOC["links"][-1]["mass"] # the cube: 50 g (its inertia is isotropic)
INERTIA = CUBE_DOC["links"][-1]["inertia"][0]
HALF = CUBE_DOC["side"] / 2 # 6 cm cube
if not np.isclose(INERTIA, MASS * CUBE_DOC["side"] ** 2 / 6):
raise ValueError("cube.yaml: the inertia of the cube must be mass * side^2 / 6")
GRAV = np.array([0.0, 0.0, -9.81])
MU, KN, CN, VS = 1.0, 2.4e3, 5.0, 1e-3 # friction, point stiffness and damping, regularization speed
EDGE_SAMPLES, EDGE_REF = 9, 0.01 # points per cube edge; m of edge carried by one stiffness
PADS = {7: "right distal pad", 9: "left distal pad"} # 0-based link
PTS = {int(k): np.array(v) for k, v in DATA_JSON["pad_vertices_link_frame"].items()}
ANCESTORS = []
for i in range(N):
chain, k = [], i
while k >= 0:
chain.append(k)
k = ROBOT.bt[k] - 1
ANCESTORS.append(chain)
def pad_boxes():
"""Each pad's box in its link frame: centre, unit axes (columns) and half edges, from its 8 vertices."""
out = {}
for link, pts in PTS.items():
v = pts.reshape(2, 2, 2, 3)
edges = np.array([v[1, 0, 0] - v[0, 0, 0], v[0, 1, 0] - v[0, 0, 0], v[0, 0, 1] - v[0, 0, 0]])
half = np.linalg.norm(edges, axis=1) / 2
out[link] = (pts.mean(axis=0), (edges / (2 * half[:, None])).T, half)
return out
BOXES = pad_boxes()
def cube_edge_points():
"""Points on the cube's twelve edges (cube frame) and the stiffness weight of each."""
c = np.array([[a, b, d] for a in (-1, 1) for b in (-1, 1) for d in (-1, 1)], float)
pts, w = [], []
spacing = 2 * HALF / (EDGE_SAMPLES - 1)
for i in range(8): # the corners
pts.append(c[i] * HALF)
w.append(1.5 * spacing / EDGE_REF)
for i in range(8): # along the edges
for j in range(i + 1, 8):
if np.abs(c[i] - c[j]).sum() == 2:
for k in range(1, EDGE_SAMPLES - 1):
f = k / (EDGE_SAMPLES - 1)
pts.append((c[i] * (1 - f) + c[j] * f) * HALF)
w.append(spacing / EDGE_REF)
return np.array(pts), np.array(w)
EDGE_PTS, EDGE_W = cube_edge_points()
def cross(a, b):
"""Cross product of 3-vectors (one of them may be a single vector, the other a row per point); written out
because `np.cross` spends most of its time on argument handling."""
out = np.empty(np.broadcast(a, b).shape)
out[..., 0] = a[..., 1] * b[..., 2] - a[..., 2] * b[..., 1]
out[..., 1] = a[..., 2] * b[..., 0] - a[..., 0] * b[..., 2]
out[..., 2] = a[..., 0] * b[..., 1] - a[..., 1] * b[..., 0]
return out
def point_force(Fn, n, vrel):
"""Normal force ``Fn`` along ``n`` and regularized Coulomb friction against the relative velocity."""
vt = vrel - np.einsum("ij,ij->i", vrel, n)[:, None] * n
return Fn[:, None] * n - MU * Fn[:, None] * vt / np.sqrt((vt ** 2).sum(axis=1) + VS ** 2)[:, None]
def contacts(q, dq, op, oR, ov, ow):
"""Contact forces at the arm state ``q, dq`` and the cube state (position, rotation matrix, velocity,
angular velocity): the wrenches on the links ``(N, 6)``, the force and moment on the cube, and what is
in contact (points and total normal force, per pad and for the table)."""
Q, org = link_frames(ROBOT, q)
fext = np.zeros((N, 6))
F_cube, M_cube = np.zeros(3), np.zeros(3)
info = {}
axes = Q[:, :, 2] # the joint axes
spin = axes * dq[:, None] # dq_j z_j
def velocity_of_link_points(link, P):
"""Velocity of world points fixed on a link: sum over its ancestors of dq_j z_j x (P - o_j)."""
ids = ANCESTORS[link]
return cross(spin[ids].sum(axis=0), P) - cross(spin[ids], org[ids]).sum(axis=0)
def add_on_link(link, P, F): # a force F at world points P acting on the link
fext[link, :3] += Q[link].T @ cross(P - org[link], F).sum(axis=0)
fext[link, 3:] += Q[link].T @ F.sum(axis=0)
# 1. the vertices of each pad against the cube
for link, pts in PTS.items():
P = org[link] + pts @ Q[link].T
pl = (P - op) @ oR # in the cube frame
dist = HALF - np.abs(pl) # distance to each face plane
inside = (dist > 0).all(axis=1)
info[PADS[link]] = (0, 0.0)
if not inside.any():
continue
idx = np.arange(len(P))
kmin = np.argmin(dist, axis=1) # the nearest face
nloc = np.zeros_like(P)
nloc[idx, kmin] = np.sign(pl[idx, kmin])
n = nloc @ oR.T # outward normal, world
vrel = velocity_of_link_points(link, P) - (ov + cross(ow, P - op))
vn = np.einsum("ij,ij->i", vrel, n)
Fn = np.where(inside, np.maximum(0.0, KN * dist[idx, kmin] - CN * vn), 0.0)
F = point_force(Fn, n, vrel)
F[~inside] = 0.0
add_on_link(link, P, F)
F_cube -= F.sum(axis=0)
M_cube -= cross(P - op, F).sum(axis=0)
info[PADS[link]] = (int((Fn > 0).sum()), float(Fn.sum()))
# 2. points of the cube's edges against the pad boxes
rc = EDGE_PTS @ oR.T
Pc, Vc = op + rc, ov + cross(ow, rc)
for link, (centre, U, half) in BOXES.items():
s = ((Pc - org[link]) @ Q[link] - centre) @ U # in the box frame
dist = half - np.abs(s)
inside = (dist > 0).all(axis=1)
if not inside.any():
continue
idx = np.arange(len(Pc))
kmin = np.ones(len(Pc), dtype=int) # out through the pad's face (its thin axis)
n = (U[:, kmin].T * np.sign(s[idx, kmin])[:, None]) @ Q[link].T
vrel = Vc - velocity_of_link_points(link, Pc)
vn = np.einsum("ij,ij->i", vrel, n)
Fn = np.where(inside, np.maximum(0.0, EDGE_W * (KN * dist[idx, kmin] - CN * vn)), 0.0)
Fc = point_force(Fn, n, vrel)
Fc[~inside] = 0.0
F_cube += Fc.sum(axis=0)
M_cube += cross(Pc - op, Fc).sum(axis=0)
add_on_link(link, Pc, -Fc)
count, total = info[PADS[link]]
info[PADS[link]] = (count + int((Fn > 0).sum()), total + float(Fn.sum()))
# 3. the cube's corners against the table
r = HALF * np.array([[a, b, c] for a in (-1, 1) for b in (-1, 1) for c in (-1, 1)]) @ oR.T
P, V = op + r, ov + cross(ow, r)
depth = -P[:, 2]
on = depth > 0
if on.any():
Fn = np.where(on, np.maximum(0.0, KN * depth - CN * V[:, 2]), 0.0)
vt = V[:, :2]
Ft = -MU * Fn[:, None] * vt / np.sqrt((vt ** 2).sum(axis=1) + VS ** 2)[:, None]
F = np.column_stack([Ft, Fn])
F_cube += F.sum(axis=0)
M_cube += cross(r, F).sum(axis=0)
info["table"] = (int(on.sum()), float(Fn.sum()))
return fext, F_cube, M_cube, info
The cube as a chain of six joints¶
The cube hangs from the fixed base on three prismatic joints (they carry it to any position) and three
revolute joints (they turn it to any orientation). This chain is the second model file of the example,
cube.yaml: the five links before the cube have no mass, the last link is the cube,
with its origin at its centre. Its DH parameters phi and alp, in quarter turns, are chosen so that
- the three prismatic axes are the world axes z, -y and x, and the three revolute axes are x, y and z;
- the frames of the six links multiply to the identity, so with all six joint values zero the cube sits at the origin, upright.
The links of the file are numbered from 1 with parent 0 the fixed base; here they are put after the ten links
of the arm and gripper. The joints are marked actuated only because the package counts them that way (dof
is the number of actuated joints); they get zero force. The three finger constraints get zero columns for the
new joints.
NC = len(CUBE_DOC["links"])
JOINTS = [link["joint"] for link in CUBE_DOC["links"]] # P P P R R R
chain_links = [dict(link, link=link["link"] + N, parent=link["parent"] + N if link["parent"] else 0)
for link in CUBE_DOC["links"]]
ROBOT_ALL = Robot.from_links(links + chain_links, [0.0, 0.0, 0.0], closed_loop=True, dof=DOF + NC,
name="Kinova Gen3 Lite with gripper and cube")
NT = N + NC # joints of the whole robot
JT = np.zeros((len(FOLLOWERS), NT))
JT[:, :N] = J
def constraints_all(q, dq):
return JT, np.zeros_like(JT)
def torque_all(t, tf, rb, q, dq):
return np.concatenate([torque(t, tf, rb, q[:N], dq[:N]), np.zeros(NC)]) # the cube joints have no motor
CASE_ALL = ForDynCase(robot=ROBOT_ALL, q0=np.zeros(NT), dq0=np.zeros(NT), ti=0.0, tf=T_END, incr=0.02,
jacobian=constraints_all, torque=torque_all)
# the axes of the chain at the zero configuration: they do not depend on the joint values
Q_ZERO, _ = link_frames(ROBOT_ALL, np.zeros(NT))
SLIDE_AXES = np.array([Q_ZERO[N + k][:, 2] for k in range(3)])
def cube_state(q, dq):
"""Position, rotation matrix, velocity and angular velocity of the cube from the whole robot's ``q, dq``."""
Q, org = link_frames(ROBOT_ALL, q)
p = org[-1]
v, w = np.zeros(3), np.zeros(3)
for k, joint in enumerate(JOINTS):
z, qd = Q[N + k][:, 2], dq[N + k]
if joint == "P":
v += qd * z
else:
w += qd * z
v += qd * cross(z, p - org[N + k])
return p, Q[-1], v, w
The simulation¶
The package integrates the robot with sys_ode(case, t, y, fext=fext), where y is q, dq and an energy
entry. The only work left to the example is to turn the cube's state into the contact forces and back: the
contacts give the force F and moment M on the cube, and the wrench on the last link is
[R^T M; R^T (F + m g)] (moment about the link origin, which is the cube's centre, and force, both in the link
frame). The arm has no gravity here (the MuJoCo model compensates it), so the weight of the cube is added to its
wrench.
SciPy's BDF integrates the whole state. The absolute tolerance matters: the cube's coordinates are
positions and angles of order 0.1 and their velocities, and the contacts are springs that sink about 4 mm
(9 N against 2400 N/m), so an error of a micrometre is of no consequence. With atol = 1e-6 on the cube
joints the run takes a few seconds; with 1e-8 everywhere it takes several times as long for the same
trajectory.
NA = 2 * NT + 1 # the state: q, dq, energy
def rhs(t, y):
q, dq = y[:NT], y[NT:2 * NT]
p, R, v, w = cube_state(q, dq)
fext_arm, F, M, _ = contacts(q[:N], dq[:N], p, R, v, w)
fext = np.zeros((NT, 6))
fext[:N] = fext_arm
fext[-1, :3] = R.T @ M
fext[-1, 3:] = R.T @ (F + MASS * GRAV)
return sys_ode(CASE_ALL, t, y, fext=fext)[0]
# the robot starts at the hover pose with the gripper open; the prismatic joints carry the cube to the table
q_start = np.concatenate([WAYPOINT["ready_hover"], [OPEN_Q], [0.0] * 3]) # MuJoCo coordinates
q_start[7:] = [0.149 - 0.676 * OPEN_Q, -OPEN_Q, 0.149 - 0.676 * OPEN_Q] # the followers
q0 = np.zeros(NT)
q0[:N] = q_start + Q0
q0[N:N + 3] = SLIDE_AXES @ CUBE_START
y0 = np.concatenate([q0, np.zeros(NT), [0.0]])
atol = np.full(NA, 1e-8)
atol[N:NT] = atol[NT + N:2 * NT] = 1e-6 # the cube's joints and velocities
t0 = time.perf_counter()
sol = solve_ivp(rhs, (0.0, T_END), y0, method="BDF", t_eval=np.arange(0.0, T_END + 1e-9, 0.02),
rtol=1e-5, atol=atol, max_step=0.005)
print(f"{sol.message} {sol.nfev} derivative evaluations, {time.perf_counter() - t0:.1f} s")
t = sol.t
states = [cube_state(sol.y[:NT, k], sol.y[NT:2 * NT, k]) for k in range(len(t))]
cube = np.array([s[0] for s in states])
grip = np.array([gripper_q(sol.y[:N, k]) for k in range(len(t))])
info = [contacts(sol.y[:N, k], sol.y[NT:NT + N, k], *states[k])[3] for k in range(len(t))]
force = {name: np.array([i[name][1] for i in info]) for name in PADS.values()}
fig, ax = plt.subplots(1, 3, figsize=(10, 3.2))
ax[0].plot(t, cube[:, 2] * 1e3)
ax[0].set(xlabel="time (s)", ylabel="cube height (mm)", title="the cube is lifted")
ax[1].plot(t, grip, color="tab:orange")
ax[1].axvline(T_CLOSE, ls=":", color="gray")
ax[1].set(xlabel="time (s)", ylabel="driven finger joint (rad)", title="the gripper closes")
for name, f in force.items():
ax[2].plot(t, f, label=name)
ax[2].set(xlabel="time (s)", ylabel="pad normal force (N)", title="the grip")
ax[2].legend()
fig.tight_layout()
print(f"cube height: start {cube[0, 2] * 1e3:.1f} mm, end {cube[-1, 2] * 1e3:.1f} mm; "
f"drift in the table plane {np.linalg.norm(cube[-1, :2] - cube[0, :2]) * 1e3:.1f} mm")
print("pad normal forces at the end (N):", {k: round(float(v[-1]), 2) for k, v in force.items()})
Output:
The solver successfully reached the end of the integration interval. 3560 derivative evaluations, 2.9 s
cube height: start 29.8 mm, end 217.5 mm; drift in the table plane 0.7 mm
pad normal forces at the end (N): {'right distal pad': 8.92, 'left distal pad': 8.92}

The gripper starts to close at 1.5 s but takes until about 2.3 s to reach the cube, where the pads begin to press;
the arm starts to lift at 2.4 s and the cube is 5 mm above the table at 2.7 s. The cube overshoots its final height by about 1 cm at 3.3 s as the arm's PD law settles. The two pads press with the same
force, about 8.9 N each. To check that the contacts do the lifting and not an artefact, switch friction off
(MU = 0.0) or keep the gripper open (CLOSE_Q = OPEN_Q) and run the example again: the cube then stays on
the table (29.9 mm, as it started).
What the motion looks like¶
Side views (the arm's plane) at four instants, from the joint values of the simulation: the arm and the two fingers as lines through their joints, the cube as a square. The script plays the same drawing as an animation instead.
def skeleton(q):
"""The arm and both fingers as line segments (x, z), through the link origins and ends."""
so, sc, _, _, st = for_kine(ROBOT, q, np.zeros(N))
lines = [np.column_stack([np.zeros(3), so[:, 0]])]
for i in range(ROBOT.n):
kids = ROBOT.children(i + 1)
for end in ([so[:, c - 1] for c in kids] or [st[:, i]]):
lines.append(np.column_stack([so[:, i], end]))
return lines
instants = [0.0, 1.4, 2.4, 3.6]
fig, axes = plt.subplots(1, 4, figsize=(11, 3.6), sharey=True)
for ax, ts in zip(axes, instants):
k = int(np.argmin(abs(t - ts)))
for line in skeleton(sol.y[:N, k]):
ax.plot(line[0], line[2], color="0.15", lw=1.8)
c = cube[k]
ax.add_patch(plt.Rectangle((c[0] - HALF, c[2] - HALF), 2 * HALF, 2 * HALF, fc="tab:orange", ec="k", zorder=3))
ax.axhline(0, color="0.5")
ax.set(title=f"t = {ts:.1f} s", xlim=(-0.05, 0.55), ylim=(-0.03, 0.6), xlabel="x (m)")
ax.set_aspect("equal")
axes[0].set_ylabel("z (m)")
fig.tight_layout()

What to try¶
- A heavier or larger cube: change
MASSandHALF(the pad tilt is fitted to this size, so a very different cube needs different waypoints). - A slippery grasp:
MU = 0.1and watch the cube slip out of the fingers. - Softer contacts: a smaller
KNlets the pads sink further into the cube. -
A different controller: replace
torqueand keep everything else; the contact forces are the same. -
A looser or tighter tolerance: change
atolfor the cube's joints and see how the run time and the cube's path change.
The pattern: a body that moves freely is a chain from the fixed base (three prismatic and three revolute joints), the force law between the bodies is written in the example, and the package integrates everything.
Grasp: a jaw gripper and a box on a six-link arm¶
A six-link Kinova Gen3 Lite arm, which has no gripper of its own, picks up a 6 cm, 50 g box with a two-finger
jaw gripper. Neither the gripper nor the box is in the arm's model file. They come from one grasp file,
grasp.yaml, which attach_grasp plugs onto link 6 of the arm. The file holds everything about the grasp, so
you change the gripper, the box or the task by editing the file, not code:
- the gripper, from its sizes: two prismatic fingers that slide along the tool's y axis and hang along z, each with a pad on its inner face;
- the box, from its size and mass: it hangs from the fixed base on a chain of six joints (three prismatic, three revolute), so the package integrates it together with the arm;
- the constraint that makes the two fingers close together;
- the contact: a penalty law with friction between the pads and the box, and between the box and the table. No other link of the arm touches the box;
- the task: where the box is, the heights of the approach, the closing time and the control gains.
What the example writes is only the plots; the model, the contact forces, the inverse kinematics of the arm's poses and the simulation are the package's.
The code on this page is the script examples/jaw_gripper_grasp.py of the download.
import logging
import os
import matplotlib.pyplot as plt
import numpy as np
import yaml
from redysim import Robot, attach_grasp, load_grasp_model, load_model
from redysim.kinematics.forward import link_frames
logging.disable(logging.INFO)
plt.rcParams.update({"figure.figsize": (7, 3.6), "axes.grid": True, "lines.linewidth": 1.6})
DATA = "../../examples/jaw_gripper_grasp" # the grasp file (next to the script in the download)
The arm¶
The arm is the bundled model kinova_gen3lite.yaml: six revolute joints and no gripper. Its weight is taken as
compensated (as the real arm's controller does), so the gravity of the model is set to zero; the box keeps its
weight. The joint values the model starts from (case.q0) are used as the first guess of the inverse
kinematics below.
arm, case, _ = load_model("kinova_gen3lite.yaml")
arm = Robot.from_links(arm.to_links("grouped"), [0.0, 0.0, 0.0], name=arm.name)
print(arm.name, "|", arm.n, "joints, no gripper")
Output:
The grasp file¶
grasp.yaml is a plain YAML file with these sections. Each fact is written once: the sizes give the inertias,
the pad boxes and the contact points, the DH angles give the joint directions, the stroke gives the finger
travel, and the start pose gives the starting joint values. The package checks the file when it loads it and
names the field that is wrong (a pad that is too thin, a gripper that cannot open around the box).
FILE = os.path.join(DATA, "grasp.yaml")
spec = yaml.safe_load(open(FILE))
print("sections :", ", ".join(spec))
gripper = {k: v for k, v in spec["gripper"].items() if k != "joints"}
print("gripper :", gripper)
print("box :", spec["object"]["size"], "m,", spec["object"]["mass"], "kg, starts at",
spec["object"]["start"]["position"])
print("contact :", spec["contact"])
print("fingers :", spec["constraints"])
Output:
sections : name, mount, gripper, object, constraints, joint_dynamics, table, contact, task
gripper : {'type': 'parallel_jaw', 'finger_length': 0.06, 'finger_width': 0.02, 'finger_thickness': 0.01, 'stroke': 0.06, 'finger_mass': 0.1, 'pad': {'length': 0.04, 'thickness': 0.01}}
box : [0.06, 0.06, 0.06] m, 0.05 kg, starts at [0.35, 0.0, 0.03]
contact : {'k': 2400.0, 'c': 5.0, 'mu': 1.0, 'friction_speed': 0.001, 'pad_points': 'vertices', 'edge_samples': 9, 'edge_ref': 0.01}
fingers : [{'follower': 'finger_2', 'driver': 'finger_1', 'c0': 0.0, 'c1': 1.0}]
Plugging it onto link 6¶
attach_grasp(arm, file, link=6) adds two finger links as children of link 6 and the six joints of the box.
The result holds the whole robot: the six arm joints, the two fingers (joints 6 and 7, counting from 0) and the
box (joints 8 to 13). The fingers are tied by the constraint q_finger_2 = q_finger_1, so the robot is a
closed-loop system with 13 free joints.
grasp = attach_grasp(arm, FILE, link=6)
robot = grasp.robot
print(robot.n, "joints,", robot.dof, "free; fingers", grasp.finger, "; box:", robot.n - grasp.n_base - 2, "joints")
print("joint types:", "".join("R" if r == 1 else "P" for r in robot.r))
print("constraint matrix J (J q = 0):", grasp.constraint_matrix.astype(int).tolist())
Output:
14 joints, 13 free; fingers (6, 7) ; box: 6 joints
joint types: RRRRRRPPPPPRRR
constraint matrix J (J q = 0): [[0, 0, 0, 0, 0, 0, -1, 1, 0, 0, 0, 0, 0, 0]]
The poses of the arm¶
The file gives the box position and how the gripper approaches it: the tool points down, and the rail of the
gripper is put at the box centre plus the offset of the pad centre plus a height. plan finds the arm's joint
values for each height by inverse kinematics (least squares from several starts, taking the solution nearest the
previous pose so that the path is smooth). Joint limits are not enforced by the package, so look at the values.
poses = grasp.plan(q_guess=case.q0[:6])
for name, q in poses.items():
print(f"{name:6s}", np.round(q, 3))
Output:
ready [-0.135 1.192 2.879 3.142 4.596 3.007]
above [-0.135 0.837 3.271 3.142 3.849 3.007]
grasp [-0.135 0.567 3.24 3.142 3.61 3.007]
lift [-0.135 0.986 3.225 3.142 4.044 3.007]
The simulation¶
simulate integrates the whole system with SciPy's BDF: the arm follows its poses along cycloidal paths under a
PD law, the gripper closes at 1.5 s and the arm lifts at 2.4 s. The contact forces go into the dynamics as
external wrenches on the finger links and on the box. The box's six joints get a looser absolute tolerance
(atol_object in the file); with the tight one the same run takes several times longer. The same case also
runs with run_fordyn(grasp.case(...)).
result = grasp.simulate(q_base=poses["ready"], torque=grasp.controller(poses))
t, box = result.t, result.box
print(f"{result.nfev} derivative evaluations, {result.seconds:.1f} s")
print(f"box height: start {box[0, 2] * 1e3:.1f} mm, end {box[-1, 2] * 1e3:.1f} mm, "
f"peak {box[:, 2].max() * 1e3:.1f} mm; drift in the table plane "
f"{np.linalg.norm(box[-1, :2] - box[0, :2]) * 1e3:.1f} mm")
print("pad normal forces at the end (N):", {k: round(float(v[-1]), 2) for k, v in result.pad_force.items()})
Output:
5506 derivative evaluations, 5.7 s
box height: start 30.0 mm, end 181.5 mm, peak 191.3 mm; drift in the table plane 4.3 mm
pad normal forces at the end (N): {'finger_1': 1.5, 'finger_2': 1.5}
Results¶
The gripper starts to close at 1.5 s and the pads touch the box at 1.56 s, because the arm has already placed
the open gripper around it. The impact gives a brief spike of about 5 N on each pad; then the command to the
driven finger, which is saturated, settles the two pads at half of drive_force each (1.5 N). The arm starts
to lift at 2.4 s and the box follows it. The box overshoots its final height as the arm's PD law settles. With
friction switched off (mu: 0.0 in the file) or with the gripper kept open the box stays on the table, so the
contacts do the lifting.
fig, ax = plt.subplots(1, 3, figsize=(10, 3.2))
ax[0].plot(t, box[:, 2] * 1e3)
ax[0].set(xlabel="time (s)", ylabel="box height (mm)", title="the box is lifted")
ax[1].plot(t, result.q[6] * 1e3, color="tab:orange")
ax[1].axvline(spec["task"]["gripper"]["close_at"], ls=":", color="gray")
ax[1].set(xlabel="time (s)", ylabel="finger position (mm)", title="the gripper closes")
for name, force in result.pad_force.items():
ax[2].plot(t, force, label=name)
ax[2].set(xlabel="time (s)", ylabel="pad normal force (N)", title="the grip")
ax[2].legend()
fig.tight_layout()

What the motion looks like¶
Side views (x and z) at four instants, from the joint values of the simulation: the arm as a line through its link origins, the two fingers as a line along the tool's z axis, and the box as a square. The script plays the same drawing as an animation instead.
half = np.asarray(spec["object"]["size"]) / 2
length = spec["gripper"]["finger_length"]
def skeleton(q):
"""The arm through its link origins, and the fingers from the rail along the tool z axis."""
Q, org = link_frames(robot, q)
arm_line = np.vstack([[0.0, 0.0, 0.0], org[:6]])
finger = np.vstack([org[5], org[5] + length * Q[5][:, 2]])
return arm_line, finger
instants = [0.0, 1.4, 2.4, 3.6]
fig, axes = plt.subplots(1, 4, figsize=(11, 3.6), sharey=True)
for ax, ts in zip(axes, instants):
k = int(np.argmin(abs(t - ts)))
arm_line, finger = skeleton(result.q[:, k])
ax.plot(arm_line[:, 0], arm_line[:, 2], color="0.15", lw=1.8)
ax.plot(finger[:, 0], finger[:, 2], color="tab:blue", lw=3)
c = box[k]
ax.add_patch(plt.Rectangle((c[0] - half[0], c[2] - half[2]), 2 * half[0], 2 * half[2],
fc="tab:orange", ec="k", zorder=3))
ax.axhline(0, color="0.5")
ax.set(title=f"t = {ts:.1f} s", xlim=(-0.1, 0.6), ylim=(-0.03, 0.7), xlabel="x (m)")
ax.set_aspect("equal")
axes[0].set_ylabel("z (m)")
fig.tight_layout()

The same in your own robot file¶
Instead of calling attach_grasp, a robot can carry the gripper in its own yaml file. grasp.yaml is general
and shared, and holds all the grasping parameters (the gripper, the box and where it is, the contact, the task).
Each robot's file says only where the gripper plugs on (link) and whether the weight of the arm is
compensated (gravity). kinova_with_gripper.yaml is the arm's file with that one section added.
load_grasp_model reads it and gives the same Grasp as above. A robot that needs other values, for example
a box elsewhere within its reach, points at its own copy of the grasp file.
FILE_OWN = os.path.join(DATA, "kinova_with_gripper.yaml")
text = open(FILE_OWN).read()
print(text[text.index("grasp:"):])
own = load_grasp_model(FILE_OWN)
print("loaded:", own.robot.n, "joints; the same robot as above:", own.robot.n == robot.n,
"; box starts at", own.spec["object"]["start"]["position"])
Output:
grasp:
file: grasp.yaml
link: 6
gravity: compensated # the controller compensates the weight of the arm; the box keeps its weight
loaded: 14 joints; the same robot as above: True ; box starts at [0.35, 0.0, 0.03]
What to try¶
- A different box: change
object.sizeandobject.massingrasp.yaml(the inertia follows from them). The opening must stay larger than the box, and the poses are found again for the new position. - A different gripper: change
finger_length,stroke, the pad size or the opening (startof the finger joints). The file is checked when it loads, and tells you what does not fit. - A slippery grasp:
contact.mu: 0.1and the box is no longer lifted (with 0.3 it still is): the friction of two pads at 1.5 N has to carry its weight. - Softer contacts: a smaller
contact.klets the pads sink further into the box. - Another arm: copy
kinova_with_gripper.yaml, replace the links with your own robot's and setlinkfor it: any open-loop fixed-base robot should take the samegrasp.yaml, with the box position and the approach heights in your copy of the file adjusted to its reach. Only the Kinova arm has been tried.
Not supported yet: a gripper with a rotation in its mount, a gripper that is not a plain two-finger jaw (for example the Kinova gripper of the pick-and-lift example, with its three couplings), and a box that is not a box. The package does not enforce joint limits, and the three revolute joints of the box have a singularity at plus or minus 90 degrees in their middle angle, which this task never approaches.