Appendix B: Using ReDySim from Python¶
This appendix is optional. Everything in the manual works without it. Use it when you want to run many simulations in a row, make your own graphs, or process the results.
You need a little Python: you should be able to save a text file ending in .py and run
it. The examples use the model file my_robot.yaml from section 2.1, which you can create with
B.1 Run a model file¶
Save this as run_arm.py in the same folder as my_robot.yaml:
import matplotlib.pyplot as plt
from redysim import load_model, run_fordyn
robot, fordyn_case, invdyn_case = load_model("my_robot.yaml")
res = run_fordyn(fordyn_case) # forward dynamics
res.plot() # joint motion, torque and energy plots
plt.show()
and run it with the environment active:
load_model returns three things: the robot, the forward-dynamics case (or None if the
file has no fordyn: part), and the inverse-dynamics case (or None). For inverse
dynamics use run_invdyn(invdyn_case) in the same way. The bundled examples can be
loaded by name, for example load_model("kuka.yaml"). A model file that uses your own Python
function (custom:, section 2.6 of the manual) must be loaded with
load_model("my_robot.yaml", allow_python=True).
To save the animation as a GIF, or the results as .dat files:
res.animate(save="arm.gif") # trace=True also draws the path of each end link's tip
res.save("results") # writes timevar.dat, statevar.dat, envar.dat in results/
B.2 The results¶
After res = run_fordyn(case), the results are NumPy arrays with one row per time step:
| name | contents | shape |
|---|---|---|
res.t |
times | (steps,) |
res.q |
joint positions | (steps, joints) |
res.dq |
joint velocities | (steps, joints) |
res.lam |
closed loops: Lagrange multipliers at the cut joints (an open loop has none) | (steps, constraints) |
res.energy |
potential, kinetic, actuator and total energy | (steps, 4) |
res.tip |
ground-frame position of the end effector: the tip of each last link, see res.tip_links |
(steps, links, 3) |
For inverse dynamics, inv = run_invdyn(case) gives inv.t, inv.q, inv.dq, inv.ddq
and the joint torques inv.tau. For a closed loop, inv.lam holds the forces at the cut
joints; forward dynamics gives the same quantity as res.lam.
Angles are in radians. To see degrees, use numpy.degrees(res.q).
You can also read the files from a run made with the command:
import numpy as np
t = np.loadtxt("output/fordyn/my_robot/timevar.dat")
y = np.loadtxt("output/fordyn/my_robot/statevar.dat") # positions, then velocities, ...
B.3 Your own graph¶
import matplotlib.pyplot as plt
import numpy as np
plt.figure()
plt.plot(res.t, np.degrees(res.q[:, 0]), label="joint 1")
plt.plot(res.t, np.degrees(res.q[:, 1]), label="joint 2")
plt.xlabel("time (s)")
plt.ylabel("angle (deg)")
plt.legend()
plt.grid(True)
plt.savefig("joints.png", dpi=150) # save a picture
plt.show()
B.4 Compare several designs¶
Change a parameter in a loop and plot every run on one graph. Here link 1's mass is varied:
import matplotlib.pyplot as plt
import numpy as np
from redysim import load_model, run_fordyn
plt.figure()
for m1 in (0.5, 1.0, 1.5):
robot, case, _ = load_model("my_robot.yaml") # a fresh copy for each run
robot.m = [m1, 0.4] # one mass per link
res = run_fordyn(case)
plt.plot(res.t, np.degrees(res.q[:, 0]), label=f"m1 = {m1} kg")
plt.xlabel("time (s)")
plt.ylabel("joint 1 angle (deg)")
plt.legend()
plt.show()
Two rules apply to the robot's arrays (robot.m, robot.a, ...):
- Replace the whole array:
robot.m = [1.0, 0.4]. Changing one element in place (robot.m[0] = 1.0) is not allowed and gives the errorassignment destination is read-only. - Give one value per link. The number of values must match the number of links.
In Python the arrays are called alp, a, b, th for the modified DH parameters, phi and
h for the branch angle and offset, and m for the masses (a model file calls the masses
mass).
B.5 Forces on a link, and several robots together¶
A constant force, or one that acts only for a time, can be written in the model file without Python
(external:, section 2.6 of the manual). The rest of this section is for forces that depend on the
state.
A force or moment from outside, such as a contact or a grasp, acts on one link. Describe it
with link_wrench, which gives an array with one row per link, and pass it to the dynamics:
from redysim import link_wrench, invdyn_tree
# 20 N along x (ground frame), applied at the point p of link 2
fext = link_wrench(robot, q, 2, force=[20, 0, 0], point=p)
tau = invdyn_tree(robot, q, dq, ddq, fext=fext) # the joints supply what is left
To get the joint accelerations for given joint forces in one call, use fordyn_tree (it
adds the Coriolis, gravity and external-wrench terms itself, and takes the same g and fext):
from redysim import fordyn_tree
ddq = fordyn_tree(robot, q, dq, tau, fext=fext) # = I(q)^-1 (tau - bias)
force and moment are in the ground frame; point is where the force acts, in ground
coordinates (default: the origin of the link). Give out=fext to add a second wrench to the
same array. To apply a force during a whole run, give the case a function
case.external(t, robot, q, dq) that returns such an array. The work of external forces is not
part of the energy balance of the result.
To simulate several robots together, join their states in one vector and call sys_ode for each
robot from one derivative function, with the forces that couple them. The robots affect each
other only through these forces. Here two arms are joined by a spring between their tips
(gravity is switched off, so that only the spring acts):
import matplotlib.pyplot as plt
import numpy as np
from scipy.integrate import solve_ivp
from redysim import for_kine, link_wrench, load_model, sys_ode
_, case_a, _ = load_model("two_link.yaml") # two identical arms ...
_, case_b, _ = load_model("two_link.yaml")
case_b.robot.base_pos = {1: (0.6, 0.2, 0.0)} # ... the second 0.6 m to the right and 0.2 m up
case_b.q0 = [np.pi, 0.0] # and pointing back at the first
case_a.robot.g = case_b.robot.g = [0.0, 0.0, 0.0] # no gravity: only the spring acts
ny = len(case_a.y0) # one state vector: q, dq, actuator energy
k, rest = 5.0, 0.3 # spring stiffness (N/m), length (m)
def tip(case, y): # the end of the last link, ground frame
n = case.robot.n
return for_kine(case.robot, y[:n], y[n:2 * n]).tip[:, n - 1]
def derivative(t, y):
ya, yb = y[:ny], y[ny:]
pa, pb = tip(case_a, ya), tip(case_b, yb)
f = k * (np.linalg.norm(pb - pa) - rest) * (pb - pa) / np.linalg.norm(pb - pa) # on arm A
wa = link_wrench(case_a.robot, ya[:2], 2, force=f, point=pa)
wb = link_wrench(case_b.robot, yb[:2], 2, force=-f, point=pb)
return np.concatenate([sys_ode(case_a, t, ya, wa)[0], sys_ode(case_b, t, yb, wb)[0]])
t = np.linspace(0, 3, 121)
sol = solve_ivp(derivative, (0, 3), np.concatenate([case_a.y0, case_b.y0]), t_eval=t, rtol=1e-8)
gap = [np.linalg.norm(tip(case_b, y[ny:]) - tip(case_a, y[:ny])) for y in sol.y.T]
plt.plot(t, gap)
plt.xlabel("time (s)")
plt.ylabel("distance between the tips (m)")
plt.show()
A grasp that is modelled as a stiff spring needs a small step or the BDF solver; a very stiff
spring slows the simulation. Robots with a free base, such as a payload that two arms hold, are
simulated with the floating-base package (redysim_floating), which has the same link_wrench
and sys_ode; its robots can be mixed with these in one derivative function.
B.6 Step a robot one control step at a time¶
run_fordyn simulates a whole run, with the control law written in the model file. When the
controller is your own Python code, such as a feedback law, a co-simulation with another program,
or a learned policy, use a Stepper. It advances the robot by one control step at a time and
holds the joint forces constant during the step, as a controller that samples at a fixed rate
does:
import matplotlib.pyplot as plt
import numpy as np
from redysim import Stepper, load_model
robot, _, _ = load_model("two_link.yaml")
st = Stepper(robot, dt=0.01, substeps=2, tau_limits=5.0) # forces limited to +-5 N m
st.reset([0.0, 0.0]) # at rest, both joints at 0
q_d = np.array([1.0, 0.5]) # where the joints should go
kp, kd = 10.0, 0.5
t, q = [0.0], [st.x[:2].copy()]
for _ in range(300):
q_now, dq_now = st.x[:2], st.x[2:]
st.step(kp * (q_d - q_now) - kd * dq_now) # a PD law, once per step
t.append(st.t)
q.append(st.x[:2].copy())
plt.plot(t, q)
plt.xlabel("time (s)")
plt.ylabel("joint angles (rad)")
plt.show()
st.x is the state [q; dq]. It is a read-only view of the stepper's own state, so copy it
(st.x.copy()) if you want to keep it. Joint 1 stops about 0.13 rad short of its target: a plain
PD law leaves an error under gravity.
The control step dt is divided into substeps equal steps of the fixed-step RK4 method, so the
cost of a step is always the same and the same inputs always give the same result. The gains must
suit the step: the links of two_link are light, so a stiff law (the kp: 49, kd: 14 of the model
file, which relies on an adaptive solver) is unstable at dt = 0.01. If the robot shakes or
blows up, lower kd or shorten dt.
| what | how |
|---|---|
| forces | st.step(tau): one value per joint, or one per actuated joint; joints that are not actuated receive none |
| external forces | st.step(tau, fext) with fext from link_wrench (section B.5), held constant over the step |
| start | st.reset(q) or st.reset(q, dq); time starts again at 0 |
| time | st.t |
| accelerations | st.ddq(x, tau) gives them for any state, without moving the robot |
| limits | q_limits=(lower, upper), dq_limits=b and tau_limits=b (a single b means the range -b to b; a tuple is (lower, upper)). A joint at its position limit stops there; the forces are clipped before the step |
| what happened | st.info: which joints hit a limit (q_hit, dq_hit, tau_clipped) |
| faster, less accurate | method="semi_implicit" |
| speed | a step is done in compiled code (a few microseconds for a small arm, tens for a long chain or a mechanism with loops) when the compiled kernels are installed; compiled=False runs the same calculation in Python, with the same results, three to fifty times slower |
A closed-loop robot works the same way, with its loop closure taken from the model file:
robot, case, _ = load_model("fourbar.yaml")
st = Stepper(robot, dt=0.01, substeps=2)
st.reset(case.q0, case.dq0) # closes the loop from the actuated joint
for _ in range(300):
st.step([0.0]) # the one actuated joint
print(st.info["loop_error"]) # how far the loop is open (m); about 1e-10 here
print(st.info["lam"]) # the constraint forces
A step cannot keep a closed loop exactly closed, so the stepper corrects it: reset closes the
starting pose, and after a step whose error is above project_tol (default 1e-9) the passive
joints are moved back onto the loop. stabilise=10 adds a feedback term that pulls the loop back
during the step; with project=False it keeps the error near 1e-6 on the four-bar. In a closed
loop, limits on the joint rates (dq_limits) clip each rate on its own and so break the loop's
velocity constraint, which the stepper then has to repair: use them with care.
Many robots at once¶
Learning a control policy needs many simulations at the same time. A BatchStepper holds N
independent copies of a robot and advances all of them by one control step per call, spread over
the cores of the computer:
import copy
import numpy as np
from redysim import BatchStepper, load_model
robot, case, _ = load_model("two_link.yaml")
rng = np.random.default_rng(0)
robots = [copy.deepcopy(robot) for _ in range(256)] # one robot per environment
for r in robots:
r.m = r.m * rng.uniform(0.8, 1.2, r.n) # each with its own link masses
batch = BatchStepper(robots, dt=0.01, substeps=2, tau_limits=5.0)
batch.reset(case.q0) # the same start in every environment
q_d = np.array([1.0, 0.5]) # the joint angles wanted
for _ in range(300):
q, dq = batch.x[:, :robot.n], batch.x[:, robot.n:]
batch.step(10.0 * (q_d - q) - 0.5 * dq) # tau: one row per environment
error = np.abs(batch.x[:, :robot.n] - q_d)
print(batch.x.shape, error.max(axis=0)) # joint 1 stops short, under gravity
batch.x has one row [q; dq] per environment and is read-only, like st.x. tau has one row
per environment (or one vector for all of them), with a value for every joint or for every
actuated joint. Robots of the same mechanism may have different parameters, such as masses and
lengths; a change made to robots[i] takes effect at the next batch.reset(...) of that
environment, or at once with batch.refresh(). The environments do not influence each other, and the
result does not depend on how many threads are used (threads=).
To start again only some of the environments, for example those that have finished an episode,
give mask (one true or false per environment): batch.reset(q0, mask=done). A mechanism with a
loop that cannot be closed at some pose does not stop the others: that environment keeps its
state and is marked in batch.info["failed"], which is the signal to reset it. The other entries
of batch.info are as for a single stepper, one row per environment (q_hit, dq_hit,
tau_clipped, and for a closed loop lam and loop_error). With the compiled kernels a
6-joint arm runs at about a million environment steps per second on a computer with 16 cores;
without them the same code runs, one environment after the other in Python, and much more slowly.
Where is the hand? Points of the robot¶
A control law or a learned policy usually needs the position of the tool, not only the joint
angles. st.points(links, pts) gives the position and the velocity, in the inertial frame, of
points fixed in links of the robot at its current state, and with jacobian=True also the linear
Jacobian, d position / d q:
import numpy as np
from redysim import BatchStepper, Stepper, load_model
robot, case, _ = load_model("kuka.yaml")
st = Stepper(robot, dt=0.01)
st.reset(case.q0)
tool = [robot.n] # the last link
point = [0.0, 0.0, 0.1] # 0.1 m along the z axis of that link's frame
pos, vel, J = st.points(tool, point, jacobian=True)
print("position (m):", pos[0].round(3))
print("Jacobian shape:", J.shape) # (points, 3, joints)
batch = BatchStepper(robot, dt=0.01, n_envs=256)
batch.reset(case.q0)
batch.step(np.zeros((256, robot.n)))
pos, vel = batch.points(tool, point) # the same point in every environment
print("batch positions:", pos.shape)
links are link numbers (1-based) and pts the points in the frames of those links: one point
for all of them, or one row per link. The results have one row per point, and for a batch one
more axis in front, for the environments. Without a stepper, redysim.point_motion(robot, q, dq,
links, pts) and redysim.point_jacobian(robot, q, links, pts) do the same for any joint values,
and redysim.link_motion(robot, q, dq) gives the orientation, origin, angular velocity and origin
velocity of every link. for_kine and link_frames are done by the same compiled code, in a few
microseconds.
B.7 Common problems¶
| problem | fix |
|---|---|
ModuleNotFoundError: No module named 'redysim' |
activate the environment first (section 1.1) |
FileNotFoundError: my_robot.yaml |
run the script from the folder that holds the file, or give the full path |
| no plot appears | add import matplotlib.pyplot as plt and plt.show() at the end |
ValueError: assignment destination is read-only |
assign a new array to the whole attribute, for example robot.m = [...] (section B.4) |
ValueError: assignment destination is read-only on st.x |
st.x is a read-only view; use st.reset(q, dq) to set the state, or st.x.copy() to keep it (section B.6) |
| a stepped robot shakes or blows up | the feedback gains are too stiff for the control step: lower kd or kp, or use a shorter dt (section B.6) |