Appendix B: Using Python (optional)¶
You do not need Python programming to use ReDySim. If you do write Python, everything the command line does is available as functions.
Run a robot and read the results¶
import redysim_floating as rf
from redysim_floating.examples import EXAMPLES
case = EXAMPLES["biped"].fordyn() # a ready-made robot; or rf.load_model("my_robot.yaml")[1]
case.tf = 1.0 # end time, seconds
res = rf.run_fordyn(case)
res.t # times
res.qb, res.dqb # body position and angles (x y z phi theta psi), rates
res.q, res.dq # joint values (angles or displacements) and rates
res.tau # joint torques applied
res.energy # potential, kinetic, actuator, total, ground
res.ground_force # force on both ends of every leg link
res.plot() # the plots of the command line
res.animate(save="biped.gif") # the animation (a planar robot flat, planar=False: 3-D)
res.animate(trace=True) # with the path of the trunk's centre of mass on the floor
res.save("my_results") # the .dat files
Inverse dynamics works the same way: rf.run_invdyn(EXAMPLES["quadruped"].invdyn()) gives
the joint torques in res.tu.
Dynamics and Jacobians¶
robot, fordyn_case, invdyn_case = rf.load_model("my_robot.yaml")
tu, ddqb, ground_power = rf.invdyn_float(robot, qb, dqb, q, dq, ddq) # torques for a motion
ddy, ground_power = rf.fordyn_float(robot, qb, dqb, q, dq, tub, tu) # motion for torques
g = rf.gjm(robot, q, ee=[3, 5]) # Jbe, Jme, GJM
gjm gives the Jacobians of the end of links 3 and 5: g.Jme (end-point motion per joint rate),
g.Jbe (per body motion) and g.GJM, the generalized Jacobian of a free-floating robot such
as space_robot. rf.stance_jacobian(...) does the same for feet planted on the ground.
Forces on a link¶
A constant force, or one that acts only for a time, can be written in the model file without Python
(external:, section 2.8 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 rf.link_wrench, which gives an array with one row per link (the base is row 0), and pass it
to the dynamics:
# 20 N along x (inertial frame), applied at the tip of link 3
tip = rf.for_kine(robot, qb, dqb, q, dq).tip[2]
fext = rf.link_wrench(robot, qb, q, 3, force=[20, 0, 0], point=tip)
ddy, ground_power = rf.fordyn_float(robot, qb, dqb, q, dq, tub, tu, fext)
tu, ddqb, ground_power = rf.invdyn_float(robot, qb, dqb, q, dq, ddq, fext)
force and moment are in the inertial frame; point is where the force acts (default: the
origin of the link). Give out=fext to add a second wrench to the same array. Inside the
program each row is [moment about the link origin; force] in the frame of the link, which
you can also fill in yourself. To apply a force during a whole run, give the case a function
case.external(t, robot, qb, dqb, q, dq) that returns such an array. The work of external
forces is not part of the energy balance of the result.
Several robots in one simulation¶
Every robot is a separate model, each with its own free base. You can simulate several together
(for example two space robots that hold one payload) by joining their states in one vector and
calling rf.sys_ode for each of them from one derivative function. The robots affect each other
only through the wrenches you pass in. The example below joins two bodies without joints (the
payload of section 2.8 of the manual) by a spring and draws both:
import numpy as np
from scipy.integrate import solve_ivp
import redysim_floating as rf
from redysim_floating.io.plotting import animate_many
robot, case_a, _ = rf.load_model("payload.yaml") # a body without joints
case_b = rf.load_model("payload.yaml")[1]
case_b.qb0, case_b.dqb0 = [2.0, 0, 0, 0, 0, 0], np.zeros(6)
k, rest = 400.0, 1.0 # spring stiffness (N/m), length (m)
ny = len(case_a.y0) # the length of one state vector
def derivative(t, y):
ya, yb = y[:ny], y[ny:]
f = k * ((yb[0] - ya[0]) - rest) # force on body A, along x
wa = rf.link_wrench(robot, ya[:6], [], 1, force=[f, 0, 0])
wb = rf.link_wrench(robot, yb[:6], [], 1, force=[-f, 0, 0])
return np.concatenate([rf.sys_ode(case_a, t, ya, wa)[0], rf.sys_ode(case_b, t, yb, wb)[0]])
t = np.linspace(0, 5, 101)
sol = solve_ivp(derivative, (0, 5), np.concatenate([case_a.y0, case_b.y0]), t_eval=t, rtol=1e-8)
def poses(offset): # the kinematics of one robot at all times
return [rf.for_kine(robot, sol.y[offset:offset + 6, i], sol.y[offset + 6:offset + 12, i], [], [])
for i in range(len(t))]
scene = rf.Scene(trunk=True, ground=False)
animate_many([(scene, poses(0)), (scene, poses(ny))], t,
ties=[((0, 1, "tip"), (1, 1, "start"))], save="two_bodies.gif")
animate_many takes one (scene, kinematics) pair per robot; ties are dashed lines between
a point of one robot and a point of another, here the spring. A grasp that is modelled as a
stiff spring needs a small step or the BDF solver; a very stiff spring slows the simulation.
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 torques constant during the step, as a controller that samples at a fixed rate does:
import numpy as np
import redysim_floating as rf
from redysim_floating.examples import EXAMPLES
case = EXAMPLES["space_robot"].fordyn()
robot = case.robot
st = rf.Stepper(robot, dt=0.01, substeps=2, tau_limits=200.0) # torques limited to +-200 N m
st.reset(case.qb0, case.q0) # at rest, joints at their start
q_d = np.array(case.q0) + 0.5 # where the joints should go
for _ in range(500):
st.step(200.0 * (q_d - st.q) - 40.0 * st.dq) # a PD law, once per step
print("joint error:", np.abs(st.q - q_d).max().round(4))
print("the body turned by", st.qb[3].round(3), "rad: nothing holds it")
The state st.x is [qb; q; dqb; dq]: the pose of the base (position and three Euler angles), the
joint values of the links 2 to n, and their rates. st.qb, st.q, st.dqb and st.dq are views
of its parts. They are read-only, like st.x: copy them to keep them. step(tu) takes the n - 1
joint torques; tub (default zero, an undriven base) and fext (external forces, as for
link_wrench) are optional. st.reset(qb, q, dqb, dq) sets the state, st.t is the time,
st.ddq(x, tu) gives the accelerations at any state without moving the robot, and st.info
tells what happened in the last step: which joints hit a limit (q_limits=, dq_limits=) and
which torques were clipped (tau_limits=, q_hit, dq_hit, tau_clipped), and the power of the
ground reactions (ground_power).
The control step dt is divided into substeps equal steps of the fixed-step RK4 method
(method="semi_implicit" is cheaper and less accurate), so a step always costs the same and the
same inputs always give the same result. Three things need care:
- The ground is a stiff spring. An explicit step needs a small enough sub-step
dt / substeps: 0.2 ms or less for the bundled biped (about 25 µs to agree with an accurate adaptive solver through the first impact), 1 ms for the quadruped and the hexapod. The gains of a feedback law must also suit the step, as for any sampled controller. - Euler angles have a singularity. A robot that tumbles, or lies down, can reach it (the angle
rates of the base then grow without bound). Give
euler_parameters=Truefor those: the base pose then has 7 values (position and a unit quaternion, kept normalised) anddqb[3:6]is the angular velocity in the inertial frame.rf.to_parameter_state(qb, dqb)converts a start state. - A step that diverges raises
FloatingPointError(a state that is not finite, or beyond 1e8) and leaves the state as it was.
The compiled kernels do the step in a few tens of microseconds for a
13-link robot; compiled=False runs the same calculation in Python, with the same results and
several times more slowly.
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
import redysim_floating as rf
from redysim_floating.examples import EXAMPLES
case = EXAMPLES["quadruped"].fordyn()
robot = case.robot
rng = np.random.default_rng(0)
robots = [copy.deepcopy(robot) for _ in range(64)] # one robot per environment
for r in robots:
r.m = r.m * rng.uniform(0.9, 1.1, r.n) # each with its own link masses
qb0, dqb0 = rf.to_parameter_state(case.qb0, case.dqb0) # position and quaternion
batch = rf.BatchStepper(robots, dt=0.002, substeps=4, euler_parameters=True)
batch.reset(qb0, case.q0, dqb0) # the same start in every one
for _ in range(250): # half a second without torque
batch.step(np.zeros((64, robot.n - 1))) # tu: one row per environment
height = batch.x[:, 1] # the trunk's height in each one
print(batch.x.shape, "trunk height", height.min().round(3), "to", height.max().round(3), "m")
print("failed:", int(batch.info["failed"].sum()))
batch.x has one row [qb; q; dqb; dq] per environment and is read-only. tu has one row per
environment (or one vector for all of them). Robots of the same mechanism may differ in their
parameters, such as masses, lengths and ground; 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(qb0, q0, mask=done). A step that
diverges in one environment 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. With the compiled kernels a
13-link robot runs at about 100 000 to 200 000 environment steps per second on a computer with
16 cores, depending on the sub-steps; without them the same code runs, one environment after the
other in Python, and much more slowly.
Where are the feet?¶
A control law or a learned policy usually needs the position of the feet or 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 velocity
Jacobian: velocity = J @ [dqb; dq], the columns for the six base rates and then the joint rates.
import numpy as np
import redysim_floating as rf
from redysim_floating.examples import EXAMPLES
case = EXAMPLES["quadruped"].fordyn()
robot = case.robot
st = rf.Stepper(robot, dt=0.002, substeps=2)
st.reset(case.qb0, case.q0)
feet = [4, 7, 10, 13] # the last link of each leg
tips = [[robot.alt[i - 1], 0.0, 0.0] for i in feet] # the tip of a link is at x = alt
pos, vel, J = st.points(feet, tips, jacobian=True)
print("the feet are on the ground:", bool(np.all(np.abs(pos[:, 1]) < 1e-6))) # y is up
print("Jacobian shape:", J.shape) # (points, 3, 6 + joints)
batch = rf.BatchStepper(robot, dt=0.002, substeps=2, n_envs=256)
batch.reset(case.qb0, case.q0)
batch.step(np.zeros((256, robot.n - 1)))
pos, vel = batch.points(feet, tips) # the same points in every environment
print("batch positions:", pos.shape)
links are link numbers (1-based, 1 is the base) 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, rf.point_motion(robot, qb, dqb, q,
dq, links, pts) and rf.point_jacobian(robot, qb, q, links, pts) do the same for any state, and
rf.for_kine, which gives the positions and velocities of every link, is done by the same compiled
code, in about 5 microseconds.