Module contents
Lesson 6 of 33Core 110 min

Simulating robots: MuJoCo and Gymnasium

Describe a robot and scene in MJCF, study contacts and integration, and wrap a manipulation simulation in the Gymnasium API for reproducible episode collection.

After this lesson you can

  • Write an MJCF model with bodies, joints, actuators, sensors and cameras and debug it with a viewer.
  • Explain MuJoCo's soft contact model and how solref and solimp affect penetration and stiffness.
  • Choose timestep and integrator based on stability and cost, and verify simulation determinism.
  • Implement a Gymnasium environment with image and proprioceptive observations, distinguishing termination and truncation.
  • Collect data with vectorized environments and measure throughput in steps per second.

Before you start

A lab that fits on a computer

Before collecting robot demonstrations, we need a world where we can define what it sees and does, test contact and reset. A simulator does not remove the difference from the physical world: it allows hypotheses to be studied and errors found before spending data or real-machine time. Here we build a scene and a pushing environment that could serve as a basis for learning from demonstrations.

The paper by Todorov, Erez and Tassa (2012) introduces MuJoCo as an engine for model-based control; Towers and colleagues (2024) describe the Gymnasium interface. For time limits, Pardo and colleagues (2018) distinguish a task’s own horizon from a training cutoff.

InteractiveHow far does the box sink?
Initial impulse →
  • Height
  • Horizontal displacement
0.40
0.01
500
5
0.30
Shown time (s)0.40
Maximum penetration (m)0.109
IntegrationFinite
A 1 kg mass falls and slides on a table in a spring-damper model. This is an explicit analogy, not MuJoCo's contact implementation.
InteractiveIntegrators and stiff springs
  • Semi-implicit
  • Implicit
  • RK4
Show
100
0.05
h ω0.50
Semi-implicit, hω < 2Stable
RK4, hω ≤ 2√2Stable
Normalized energy of a 1 kg oscillator for four integrators. Change stiffness and step size; curves stop when E/E₀ exceeds 100.
InteractiveAn episode timeline
reset: s₀step: s₁step: s₂end: s₃next call
End
Autoreset
3
terminatedfalse
truncatedtrue
Returned observationfinal observation s₃
Compare termination and truncation and see what Gymnasium returns under each vectorized reset mode.

From file to state

An MJCF model is XML describing the tree of bodies, joints, geometries, actuators, sensors and cameras. A geometry can serve collision, visualization or both; its mass, friction and parameters must be interpreted in the model’s units. MuJoCo compiles the file into mjModel, containing parameters and structure. Each mjData contains the state and results of one trajectory: positions qpos, velocities qvel, controls, contacts and sensors. Multiple trajectories can share an immutable model, but require separate states.

At each mj_step, the engine computes kinematics, detects contacts, evaluates forces and constraints, obtains generalized accelerations and integrates the state. Free joints use quaternions for orientation, so nq and nv may differ; velocities should not be added directly to every component of qpos. The viewer helps check scale, joints, collisions and cameras; an attractive image alone does not validate physics.

A useful debugging sequence starts without control: check that the robot does not pass through the table and that blocks fall toward it. Then apply a small action and check joint signs and limits. Finally compare a site position with the camera and with the state the policy will read. If the end effector looks correct in the image but its site is in another frame, IK may move it in an unexpected direction. Actuators also have their own interface: a desired position, velocity and torque do not mean the same thing even if input vectors have the same length.

Contact and timestep

MuJoCo soft contact relaxes strict rigid-contact complementarity and formulates constraint resolution as convex optimization. It is not literally an independent spring per point: inertias and constraints are coupled. solref configures reference dynamics, usually through a time constant and damping ratio; solimp adjusts constraint impedance by distance. The official guide explains formats, limits and parameter mixing. Change one at a time and measure penetration, forces and stability; friction and geometry also change the result.

The first figure illustrates only a point mass: below the table, N=max⁡(0,−ky−dy˙)N=\max(0,-ky-d\dot y); horizontal friction is limited by μN\mu N. The fall starts at 0.3 m with horizontal velocity 1 m/s and uses semi-implicit Euler integration. Its “unstable” readout means height exceeded 10 m or became non-finite; it does not diagnose MuJoCo. Penetration is not necessarily a failure: it is part of this soft model. An excessively large step can nevertheless create spurious energy.

To separate causes, hold friction fixed and increase stiffness; then reduce the step. Higher stiffness creates more force for a given penetration, but fast motion needs temporal resolution. Increasing damping can reduce bounces, although a damper discretized with a large step can also introduce instability. The figure limits friction to the impulse needed to stop sliding in one step; it models neither box rotation nor torsional friction. In an actual MuJoCo scene, repeat the experiment with its parameters while observing contacts and forces rather than transferring the teaching spring value.

Timestep stability depends on the fastest dynamics. For mx¨+kx=0m\ddot x+kx=0, ω=k/m\omega=\sqrt{k/m}. Semi-implicit Euler is stable for the ideal oscillator when hω<2h\omega<2; explicit Euler grows for any positive step, while implicit Euler dissipates energy. For RK4 the imaginary axis remains in the stability region up to hω=22h\omega=2\sqrt 2. In the second figure m=1m=1, x0=1x_0=1, v0=0v_0=0 and E/E0E/E_0 is plotted. Stability does not guarantee accuracy. An action at 10 Hz and physics at 2 ms require 50 substeps; changing hh without changing that count alters control frequency.

Determinism means repeating the same calculation under the same conditions: version, platform, initial state, actions and generator. Reset the whole mjData and seed randomization. Equality on one machine does not guarantee identity across platforms or physical fidelity. Measure physics steps and rendering separately: drawing every substep may dominate time.

For a fair integrator comparison use identical initial state, physical duration and contact parameters, and measure both error and time. A smaller step increases evaluations per simulated second; an implicit method may be stable with larger steps but introduce dissipation and require work per step. With contact, regime changes and solver tolerances make the oscillator formula a guide, not a universal guarantee. Repeat with h/2h/2 and compare the trajectory and forces of interest: if they change much, resolution is not yet sufficient for that question.

Episodes and value

The Gymnasium API defines action and observation spaces. reset(seed=...) returns observation and information; step(action) returns observation, reward, terminated, truncated and information. The environment initializes its generator with super().reset(seed=seed) and uses self.np_random for randomization. Image and proprioceptive observations must fit their declared spaces and correspond to the same instant.

Termination describes a final state of the problem, such as success or failure. Truncation is an external cutoff, such as a time limit on a continuing task. If the horizon is part of the problem and remaining time is included in the state, reaching that horizon can be termination. At an external cutoff, the value target uses r+γV(s′)r+\gamma V(s') with the actual final observation; at a terminal state it uses rr. Always treating truncation as terminal removes that term and biases the estimate.

For example, if the last step gives zero reward, γ=0.9\gamma=0.9 and the final state has estimated value 5, the external-truncation target is 4.5. Replacing it with zero treats a trajectory that merely stopped being observed as definitive failure. At the same time, reset does break the temporal sequence: an advantage or return must not propagate through the first state of the next episode. The flag stopping calculation between episodes and the flag cancelling bootstrap serve different roles.

Environment design fixes what the policy observes, the signal it controls, frequency, reward, success and initial distribution. If reward or success depends on something invisible, the problem may be partially observable. In the lab below, block position and goal are supplied as privileged state to a programmed expert; a policy receiving only RGB and proprioception would need to infer them or receive an observable goal. The action is horizontal Cartesian velocity; damped differential inverse kinematics converts it to joint velocities held for 50 substeps.

Vectorized environments batch observations and actions from independent copies. Recent Gymnasium versions have three autoreset modes. In NEXT_STEP, the final step returns the final observation and the next call resets, ignores the action and must be excluded from the buffer. In SAME_STEP, reset occurs in the same step and the final observation is in info["final_obs"]; in DISABLED, reset uses an explicit mask. Consult the autoreset documentation for your installed version: older versions used different keys and behaviour. The figure shows the first two modes.

A wrapper modifies the interface without necessarily changing the simulator: it can limit duration, normalize an action or stack images. Order matters. For example, if images are stacked before automatic reset, prevent the new episode’s stack from retaining frames from the previous one. To parallelize, each copy needs its own state and distinct seeds; more processes can increase throughput or reduce it through communication and rendering. Count valid transitions and episodes, not just calls to step, because NEXT_STEP reset steps are not policy transitions.

Local lab: block world

Install mujoco and NumPy in the local environment. The code downloads the Panda from MuJoCo Menagerie at a pinned revision if absent; it respects ORYON_PANDA_DIR or uses oryon-panda-model under the working directory. It adds a table, three free blocks, two cameras and a wrist force sensor. The sensor measures interaction between bodies in its frame, not directly a block’s normal force. Printed speed is a local measurement without rendering; compare the cameras afterwards. An interactive viewer can be opened after import mujoco.viewer with mujoco.viewer.launch(model, d1) in a local graphical session.

[ ]Compile and check a Panda sceneLocal GPU
import os, urllib.request, xml.etree.ElementTree as ET, time
from pathlib import Path
import numpy as np, mujoco
root=Path(os.environ.get('ORYON_PANDA_DIR',str(Path.cwd()/'oryon-panda-model')));root.mkdir(parents=True,exist_ok=True)
base='https://raw.githubusercontent.com/google-deepmind/mujoco_menagerie/822c2d8f877dd166c5b7d3c9f7e3c3b6589473b7/franka_emika_panda/'
xml=root/'panda.xml'
if not xml.exists():urllib.request.urlretrieve(base+'panda.xml',xml)
tree=ET.parse(xml)
for mesh in tree.findall('.//asset/mesh'):
    filename=mesh.get('file')
    if filename:
        dest=root/'assets'/filename;dest.parent.mkdir(parents=True,exist_ok=True)
        if not dest.exists():urllib.request.urlretrieve(base+'assets/'+filename,dest)
key=tree.find('keyframe');tree.getroot().remove(key)
world=tree.find('worldbody');hand=tree.find(".//body[@name='hand']")
ET.SubElement(hand,'site',{'name':'wrist_sensor','size':'.005','pos':'0 0 .05'})
sensor=ET.SubElement(tree.getroot(),'sensor');ET.SubElement(sensor,'force',{'name':'wrist_force','site':'wrist_sensor'})
ET.SubElement(world,'light',{'pos':'0 0 2'})
ET.SubElement(world,'geom',{'name':'table','type':'box','pos':'.5 0 .15','size':'.35 .35 .15'})
for i in range(3):
    b=ET.SubElement(world,'body',{'name':f'cube{i}','pos':f'0.7 {-.2+i*.2} .33'})
    ET.SubElement(b,'freejoint');ET.SubElement(b,'geom',{'type':'box','size':'.03 .03 .03','mass':'.1','rgba':'.8 .3 .2 1'})
ET.SubElement(world,'camera',{'name':'overhead','pos':'.5 0 1.5','xyaxes':'1 0 0 0 1 0'})
ET.SubElement(world,'camera',{'name':'side','pos':'1.5 0 .6','xyaxes':'0 1 0 -.3 0 .954'})
path=root/'panda_blocks.xml';tree.write(path,encoding='utf-8',xml_declaration=True)
model=mujoco.MjModel.from_xml_path(str(path))
def rollout(seed,steps=500):
    data=mujoco.MjData(model);rng=np.random.default_rng(seed);data.qpos[:9]=[0,0,0,-1.57079,0,1.57079,-.7853,.04,.04];data.ctrl[:]=[0,0,0,-1.57079,0,1.57079,-.7853,255]
    data.qpos[9:30:7]+=rng.uniform(-.01,.01,3)
    start=time.perf_counter();trace=[]
    for _ in range(steps):
        mujoco.mj_step(model,data);trace.append(np.r_[data.qpos,data.qvel])
    return data,(time.perf_counter()-start),np.array(trace)
d1,elapsed,trace1=rollout(42);d2,_,trace2=rollout(42)
print('trayectorias idénticas:',np.array_equal(trace1,trace2),'pasos/s (incluye registro):',round(500/elapsed),'fuerza muñeca:',d1.sensordata)
r=mujoco.Renderer(model,120,160)
for camera in ('overhead','side'):
    r.update_scene(d1,camera=camera);frame=r.render().copy();print(camera,frame.shape,'rango RGB:',frame.min(),frame.max())
r.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Offscreen rendering requires a compatible OpenGL context. Compare two trajectories with the same seed and observe how performance changes with hardware; the result is not a universal figure. The scene illustrates setup and measurement; it does not claim the Panda manipulated the cubes.

Local lab: push and collect episodes

Also install Gymnasium 1.1 or later. This self-contained environment uses a pusher with two prismatic joints to keep the task and its Jacobian readable; it is not the Panda from the first lab. task contains privileged block position and goal, proprio contains joint position and velocity, and rgb is a 64×64 overhead camera. The goal is not drawn in the image: it is supplied in task. The expert uses that privileged state to check the task, not to measure a visual policy.

[ ]Implement PushBlockEnv and validate its APILocal GPU
import os, time
import numpy as np
import gymnasium as gym
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
import mujoco

XML='''<mujoco model="push"><option timestep="0.002"/><worldbody>
<light pos="0 0 2"/><camera name="top" pos="0 0 .5" xyaxes="1 0 0 0 1 0"/>
<geom name="table" type="plane" size="1 1 .1" friction="1 .005 .0001"/>
<body name="pusher" pos="-.15 0 .025"><joint name="px" type="slide" axis="1 0 0" damping="5"/><joint name="py" type="slide" axis="0 1 0" damping="5"/><geom type="sphere" size=".015" mass="1" rgba=".2 .4 .8 1"/><site name="tip" size=".005"/></body>
<body name="block" pos="0 0 .025"><freejoint name="blockjoint"/><geom type="box" size=".025 .025 .025" mass=".1" rgba=".8 .3 .2 1"/></body>
</worldbody><actuator><velocity joint="px" kv="100" ctrlrange="-.2 .2"/><velocity joint="py" kv="100" ctrlrange="-.2 .2"/></actuator></mujoco>'''
class PushBlockEnv(gym.Env):
    metadata={'render_modes':['rgb_array'], 'render_fps':10}
    def __init__(self,render_mode='rgb_array',max_steps=100):
        self.model=mujoco.MjModel.from_xml_string(XML);self.data=mujoco.MjData(self.model);self.render_mode=render_mode;self.max_steps=max_steps;self.renderer=None
        self.action_space=spaces.Box(-1.,1.,shape=(2,),dtype=np.float32)
        self.observation_space=spaces.Dict({'rgb':spaces.Box(0,255,(64,64,3),dtype=np.uint8),'proprio':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32),'task':spaces.Box(-np.inf,np.inf,(4,),dtype=np.float32)})
        self.tip=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_SITE,'tip');self.block=mujoco.mj_name2id(self.model,mujoco.mjtObj.mjOBJ_BODY,'block')
        self.goal=np.array([.15,0.]);self.count=0
    def _obs(self):
        if self.renderer is None:self.renderer=mujoco.Renderer(self.model,64,64)
        self.renderer.update_scene(self.data,camera='top');img=self.renderer.render().copy()
        return {'rgb':img,'proprio':np.r_[self.data.qpos[:2],self.data.qvel[:2]].astype(np.float32),'task':np.r_[self.data.xpos[self.block,:2],self.goal].astype(np.float32)}
    def reset(self,*,seed=None,options=None):
        super().reset(seed=seed);mujoco.mj_resetData(self.model,self.data);self.data.qpos[3]=self.np_random.uniform(-.015,.015);self.count=0;mujoco.mj_forward(self.model,self.data)
        return self._obs(),{}
    def step(self,action):
        a=np.clip(np.asarray(action,dtype=np.float32),-1,1);mujoco.mj_forward(self.model,self.data)
        jp=np.zeros((3,self.model.nv));jr=np.zeros_like(jp);mujoco.mj_jacSite(self.model,self.data,jp,jr,self.tip)
        desired=.2*a;J=jp[:2,:2];[email protected]([email protected]+1e-4*np.eye(2),desired)
        self.data.ctrl[:]=np.clip(vel,-.2,.2)
        for _ in range(50):mujoco.mj_step(self.model,self.data)
        mujoco.mj_forward(self.model,self.data)
        self.count+=1;distance=np.linalg.norm(self.data.xpos[self.block,:2]-self.goal);terminated=bool(distance<.035);truncated=bool(self.count>=self.max_steps and not terminated)
        return self._obs(),float(-distance),terminated,truncated,{'distance':float(distance),'success':terminated}
    def render(self):return self._obs()['rgb']
    def close(self):
        if self.renderer is not None:self.renderer.close();self.renderer=None

def expert(obs):
    p=obs['proprio'];tip=np.array([-.15,0])+p[:2];block=obs['task'][:2];goal=obs['task'][2:];direction=goal-block;direction/=max(np.linalg.norm(direction),1e-8);behind=block-.045*direction
    target=behind if np.linalg.norm(tip-behind)>.025 and tip[0]<block[0]-.02 else goal
    return np.clip(6*(target-tip),-1,1).astype(np.float32)
env=PushBlockEnv();check_env(env,skip_render_check=True)
obs,_=env.reset(seed=1);start=time.perf_counter()
for i in range(100):
    obs,r,done,cut,info=env.step(expert(obs))
    if done or cut:break
print('episode',i+1,info,'seconds',time.perf_counter()-start)
env.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Reward is negative distance to the goal; success and time limit are returned separately. For training, decide how to represent the goal to the policy, evaluate contacts and positions outside the workspace, and record seeds and version. The checker tests the interface; it does not certify that the task is correct or safe.

[ ]Collect one thousand vectorized episodesLocal GPU
import gymnasium as gym
import numpy as np, time
from gymnasium.vector import AutoresetMode
envs=gym.vector.SyncVectorEnv([lambda:PushBlockEnv() for _ in range(4)],autoreset_mode=AutoresetMode.NEXT_STEP)
obs,_=envs.reset(seed=123);episodes=[];active=[[] for _ in range(4)]
resetting=np.zeros(4,dtype=bool);calls=0;start=time.perf_counter()
while len(episodes)<1000:
    actions=np.stack([expert({k:v[i] for k,v in obs.items()}) for i in range(4)])
    next_obs,reward,term,trunc,infos=envs.step(actions);calls+=1
    for i in range(4):
        if resetting[i]: continue  # NEXT_STEP: solo reinicio, acción ignorada
        transition={'obs':{k:v[i].copy() for k,v in obs.items()},'action':actions[i].copy(),
                    'reward':float(reward[i]),'terminated':bool(term[i]),'truncated':bool(trunc[i])}
        active[i].append(transition)
        if term[i] or trunc[i]:
            episodes.append({'steps':active[i], 'final_obs':{k:v[i].copy() for k,v in next_obs.items()}})
            active[i]=[]
    resetting=np.logical_or(term,trunc);obs=next_obs
elapsed=time.perf_counter()-start
success=sum(ep['steps'][-1]['terminated'] for ep in episodes)
print('episodios',len(episodes),'éxitos',success,'llamadas',calls,'pasos vectoriales/s',round(calls/elapsed,1),'llamadas individuales/s (incluye resets)',round(4*calls/elapsed,1))
envs.close()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

The rate includes resets and observation rendering and depends on the computer. episodes retains observations, actions, rewards, flags and final observation for each complete episode. In NEXT_STEP the reset call is excluded; the last valid state is taken before reset. Storing images uses memory: for large collections, write episodes incrementally to storage and record version, seeds and spaces. SyncVectorEnv groups copies in one process and does not promise parallel speedup; compare another configuration before drawing performance conclusions.

Practice

Quiz
An external limit interrupts a continuing task after 200 steps. What happens if it is treated as terminal when estimating value?
Numeric
For k=10⁴ N/m and mass 0.1 kg, what is the strict upper bound on h in seconds for semi-implicit Euler?
Quiz
For demonstrations at 10 Hz, what trade-off does a Cartesian velocity action present?
Code
Complete Reach.step: the action increments position, reward is minus distance to 1, it terminates at distance below 0.1 and truncates at ten steps if not terminated. The solution must pass Gymnasium's checker.
import numpy as np
import gymnasium as gym
from gymnasium import spaces
class Reach(gym.Env):
  def __init__(self):
      self.action_space=spaces.Box(-.1,.1,(1,),dtype=np.float32)
      self.observation_space=spaces.Box(-np.inf,np.inf,(1,),dtype=np.float32)
  def reset(self,*,seed=None,options=None):
      super().reset(seed=seed); self.x=0.; self.n=0
      return np.array([self.x],dtype=np.float32),{}
  def step(self,action):
      pass
Shift+Enter to run
Code
Implement a Stack wrapper that stacks the last k frames and preserves proprioception. On reset fill the stack with copies of the first frame; on step shift and add the new one. The environment returns a dictionary with rgb and proprio. Declare the new observation_space.
import gymnasium as gym
from gymnasium import spaces
import numpy as np
from collections import deque
class Stack(gym.Wrapper):
  def __init__(self,env,k):
      super().__init__(env)
      # Construye observation_space y memoria.
  def reset(self,**kwargs):
      pass
  def step(self,action):
      pass
Shift+Enter to run
Key idea
A reproducible environment specifies physics, observation, action and episode ending; a correct interface is as necessary as a stable simulation.