Skip to content

10. Writing your own task

The ten tasks of the package are Python classes. A task of your own is one more: a subclass of redysim_rl.Task with four methods. The environment, the action modes, the batching over many robots, the Stable-Baselines3 adapter and the evaluation all stay the package's own.

This page builds one: bring the tip of the three-link arm to a goal height and hold it still there. The tip may end anywhere along the horizontal, so many poses solve it. The complete file, with training and a test on new goals, is examples/custom_task.py.

The four methods

A task works on all the robots of the environment at once: every array has one row per robot.

Method When What it does
bind(ctx) once, when the environment is built learns the robot (links, gravity, the number of joints) and sets obs_dim, the length of the observation
reset_envs(idx, rng, options) when the robots idx start an episode draws their goals (with rng, so a seed repeats them) and returns their start state (q, dq)
observation() after every step what the policy sees, (robots, obs_dim)
reward(action) after every step (reward, terminated, info), one value per robot

ctx gives the state and the robot: ctx.q, ctx.dq (joint positions and velocities, one row per robot), ctx.act (the actuated joints), ctx.n (joints), ctx.n_envs (robots), ctx.robots (the redysim.Robot of each) and ctx.backend.points(links, points), the position and velocity of points fixed on links.

The task

from typing import ClassVar

import numpy as np

from redysim_rl import Task


class HoldHeight(Task):
    """Bring the tip of the last link to a goal height (along the way up) and hold it still.

    Observation ``[q, dq, h_goal - h, v_tip]`` (the actuated joints, the height error, the tip
    velocity). Reward, term by term: ``-w_height |h_goal - h|``, ``-w_still |v_tip|^2``,
    ``-w_act |a|^2`` and ``bonus`` while the tip is within ``tol`` of the height and slower than
    ``tol_speed``. A robot succeeds when it is there at the end of the episode.
    """

    # optional: what the GUI shows (each has a plain default)
    default_action_mode = "impedance"
    LABELS: ClassVar[dict] = {"w_height": "Height error (m)", "w_still": "Tip speed penalty",
              "w_act": "Action size penalty", "bonus": "Bonus while held at the height",
              "tol": "At the height within (m)", "tol_speed": "Still: tip slower than (m/s)",
              "height_range": "Goals within (m of the shoulder height)",
              "init_noise": "Start pose noise (rad)"}
    FORMULAS: ClassVar[dict] = {"w_height": "-w |h_goal - h|", "w_still": "-w |v_tip|^2",
                                "w_act": "-w |a|^2", "bonus": "+w while within tol and slow"}
    SUCCESS = "the tip within tol of the goal height and slower than tol_speed at the end"

    def __init__(self, height_range=0.5, init_noise=0.1, tol=0.02, tol_speed=0.05,
                 w_height=1.0, w_still=0.1, w_act=0.001, bonus=1.0):
        self.height_range, self.init_noise = height_range, init_noise
        self.tol, self.tol_speed = tol, tol_speed
        self.w_height, self.w_still, self.w_act, self.bonus = w_height, w_still, w_act, bonus

    # 1. bind: the environment is built; learn the robot and say how long the observation is
    def bind(self, ctx):
        super().bind(ctx)                          # sets self.ctx and self.n_act
        robot = ctx.robots[0]
        self.tip_link = ctx.n                      # the last link
        self.tip = np.asarray(robot.tip_vectors()[ctx.n - 1], dtype=float).reshape(1, 3)
        g = np.asarray(robot.g, dtype=float)
        self.up = -g / np.linalg.norm(g)           # the way up: against gravity
        self.goal = np.zeros(ctx.n_envs)           # one goal height per robot
        self.obs_dim = 2 * self.n_act + 1 + 3

    def _tip(self):
        """Position and velocity of the tip of every robot, ``(N, 3)`` each."""
        pos, vel = self.ctx.backend.points([self.tip_link], self.tip)
        return pos[:, 0], vel[:, 0]

    # 2. reset_envs: new goals and start states for the robots ``idx`` (an episode begins)
    def reset_envs(self, idx, rng, options=None):
        k, n = len(idx), self.ctx.n
        if options and "goal" in options:          # fixed goals, for tests: one per robot
            self.goal[idx] = np.asarray(options["goal"], dtype=float)[idx]
        else:
            self.goal[idx] = rng.uniform(-self.height_range, self.height_range, k)
        q = np.zeros((k, n))
        q[:, self.ctx.act] = rng.uniform(-self.init_noise, self.init_noise, (k, self.n_act))
        return q, np.zeros((k, n))                 # start near the zero pose, at rest

    # 3. observation: what the policy sees, one row per robot
    def observation(self):
        c = self.ctx
        pos, vel = self._tip()
        error = self.goal - pos @ self.up
        return np.concatenate([c.q[:, c.act], c.dq[:, c.act], error[:, None], vel], axis=1)

    # 4. reward: (reward, terminated, info), one value per robot
    def reward(self, action):
        pos, vel = self._tip()
        error = np.abs(self.goal - pos @ self.up)
        speed = np.linalg.norm(vel, axis=1)
        success = (error < self.tol) & (speed < self.tol_speed)
        terms = {"height": -self.w_height * error,
                 "still": -self.w_still * speed ** 2,
                 "action": -self.w_act * np.sum(np.asarray(action) ** 2, axis=1),
                 "bonus": self.bonus * success}
        info = {"distance": error, "tip_speed": speed, "is_success": success,
                **{f"term_{name}": value for name, value in terms.items()}}
        terminated = np.zeros(len(error), dtype=bool)   # the episode runs to its time limit
        return sum(terms.values()), terminated, info

    # optional: the curves of the Episode tab, each with its tolerance (NaN: none)
    def measures(self, info):
        return [("height error (m)", info["distance"], self.tol),
                ("tip speed (m/s)", info["tip_speed"], self.tol_speed)]

# check it: build an environment of 64 arms and take one step
import redysim_rl

env = redysim_rl.RedysimVectorEnv(HoldHeight(), num_envs=64, action_mode="impedance")
obs, _ = env.reset(seed=0)
print(obs.shape)                                # (64, 10): q, dq (3 each), the height error, v_tip
obs, reward, terminated, truncated, info = env.step(np.zeros((64, 9)))
print(sorted(k for k in info if k.startswith("term_")))

Train it

Any action mode works: the task sees only the state. Train it like a bundled task, passing the task object instead of a name:

from stable_baselines3 import PPO
from redysim_rl.wrappers import make_sb3

venv = make_sb3(HoldHeight(), num_envs=64, action_mode="impedance")
model = PPO("MlpPolicy", venv, n_steps=64, batch_size=1024, gamma=0.98,
            policy_kwargs={"log_std_init": -1.0}, device="cpu", seed=0)
model.learn(total_timesteps=10_000)             # a few seconds; 1_000_000 for a real run

python examples/custom_task.py does the whole run and compares it with doing nothing, on 256 goals the policy has not seen:

do nothing:  success 4.7 %, height error 0.2667 m
trained:     success 87.1 %, height error 0.0098 m

That is one run of 1 000 000 steps (64 arms, 4 cores, about two minutes), one seed, no tuning: the task learns with the settings of the bundled reach tasks.

What the info has to carry

  • is_success: whether each robot meets the goal now. The success rate is its value at the last step of the episode, so write the same test as the bonus.
  • distance: the error the evaluation reports (here the height error).
  • term_<name>: the reward split into terms that add up to the reward. They are optional, but they show which term decides the return; give each term a weight so that it can be switched off.
  • anything else you want to look at (here tip_speed).

terminated ends the episode of a robot early (a goal reached and done, a crash). The time limit is the environment's: max_episode_steps, 200 steps of 0.02 s unless the task or the call sets it.

Settings a task can give

Class attributes set what the environment builds when the call does not say:

Attribute Default Meaning
default_robot the three-link arm a function that returns the robot, or the name or path of a model file
default_action_mode "torque" the action mode
default_dt, default_substeps 0.02 s, 2 the control step and the physics steps in it
default_max_steps 200 the length of an episode
default_tau_limit 20 the joint force limit
default_q_limits, default_dq_limits ±3 rad, 10 rad/s joint position and speed limits

The call overrides them, for example your own arm from its model file: RedysimVectorEnv(HoldHeight(), robot="/path/to/my_arm.yaml", num_envs=64).

A task for a robot with a moving base (the space robot, a wheeled robot, a legged one) sets family = "floating" and returns the base state too from reset_envs: (q, dq, (qb, dqb)). The tasks in floating.py, wheeled.py and legged.py show how.

Tips

  • Put the error in the observation (here h_goal - h): a policy learns much faster when it sees what it has to make zero.
  • Keep the terms on similar scales at the start and give the effort terms (w_act, w_still) small weights; a large penalty on moving teaches the robot to stay where it is.
  • Compare with doing nothing (a zero action) on the same goals: some goals are met by luck (here goals near the start height), and the trained policy has to beat that.
  • Draw the goals and start states from rng only, so that env.reset(seed=...) repeats them.

In the GUI and in run files

A run file names the class and its file:

task: HoldHeight
task_file: custom_task.py        # relative to the run file, or an absolute path, or a module name
reward: {w_still: 0.2}           # the numbers of the class's __init__

Open it with Open run file, or press Load... beside the Task box and pick the Python file (a file with several tasks asks which one). Everything else is the GUI as for a bundled task: the Reward tab, the run card, New run, Continue, the replay, the checkpoints, the Episode tab and Compare runs. When the GUI starts it offers again every task of your own that has runs in the runs folder (it loads their files). The run folder keeps a copy of the file as task_source.py, so a run still shows the code it was trained with after you change the file.

The GUI takes what it shows from the class; all of these are optional:

In the class What the GUI makes of it Without it
numbers among the arguments of __init__ the rows of the Reward tab: w_* and bonus are weights that can be switched off, the others settings (whole numbers: counts) no rows
LABELS, FORMULAS (dicts) the name of each row and what it computes the argument names
OBS, OBS_HELP, and an obs argument the signals of the Observation card, ticked on and off one fixed signal, all
ROBOTS the robots offered for the task default_robot if it is a name, else three_link
MODES, default_action_mode the action modes offered, and the first one torque, PD target and impedance
default_dt, default_max_steps the step time and the max episode length 0.02 s, 200 steps
SUCCESS, ENDS the lines Success and Ends of the run card general words
measures(info) the top plots of the Episode tab: [(label, values, tolerance)] info["distance"] with tol
a goal that is a point, goal of shape (robots, 3) drawn in the replay no goal drawn
goal_angle of shape (robots,) the goal rotation, a short line through the goal point none
replay_point() the point whose path the replay draws, (robots, 3) the tip of the last link
default_target_range PD targets within this many radians of the home pose ±π

The class of the example has LABELS, FORMULAS, SUCCESS, default_action_mode and measures, so the GUI shows the height error and the tip speed, each with its tolerance, in the Episode tab.

For a robot with closed loops, read the class of the bundled task platform_reach, redysim_rl/platform.py: the triangle of the 3-RRR parallel robot to a goal point and angle, with PD targets on its three motors, goals made by turning the motors and closing the loops in small steps (so the mechanism keeps its assembly), and default_target_range, replay_point and measures. The replay draws a robot with branches or loops link by link: each leg as a bar from its pivot on the ground, and the platform, which holds three or more joints, as a plate.

A run file can run code

A run file with a task_file runs that Python file when it is opened. Open only run files whose task file you trust, as you would a script. The window also runs the task file of every run in the runs folder when it lists them, before you open any: do not copy a runs folder from someone you do not trust into yours.