Sim Module¶
Run MuJoCo simulations, capture per-step data, and render frames.
The Simulation class wraps model loading, stepping, data capture,
offscreen rendering, and an interactive viewer behind a single object.
Example
>>> import mujoco_toolbox as mjtb
>>> sim = mjtb.Simulation("robot.xml", duration=5, data_rate=50).run()
>>> sim.captured_data["qpos"].shape # (steps, nq)
- mujoco_toolbox.sim.CaptureSpec: TypeAlias = 'Iterable[str] | str | Callable[..., Any]'¶
an iterable of
MjDatafield names, or"all".- Type:
Fields to capture
- class mujoco_toolbox.sim.Simulation(*xml_args, duration=10, data_rate=100, fps=30, resolution=None, initial_conditions=None, keyframe=None, controller=None, meshdir='meshes/', capture=None, ts=None, gravity=None, **controller_kwargs)[source]¶
Bases:
objectA MuJoCo model plus everything needed to run, record, and render it.
Models can be given as file paths (MJCF or URDF), XML strings, or
Builderobjects. Several inputs are merged into one model.Example
>>> sim = Simulation("robot.urdf", meshdir="meshes/", duration=5) >>> sim.run(render=True).save("robot.mp4") >>> sim.captured_data["qpos"]
- Parameters:
*xml_args (str | Builder) – Model sources to load and merge.
duration (float) – Simulated time in seconds.
data_rate (int) – Data captures per simulated second.
fps (float) – Rendered frames per simulated second.
resolution (tuple[int, int] | None) – Render size
(width, height)in pixels. Defaults to the model’s<visual><global offwidth offheight>or(400, 300).initial_conditions (dict[str, Any] | None) –
MjDatafield values applied before every run, e.g.{"qpos": [...]}.keyframe (int | None) – Model keyframe to reset to before every run.
controller (Callable[..., None] | None) – Control callback
f(model, data, **controller_kwargs)called every step.meshdir (str) – Mesh directory for URDF models.
capture (CaptureSpec | None) –
MjDatafields to record."all"records every numeric field. Defaults tomujoco_toolbox.CAPTURE_PARAMETERS.ts (float | None) – Physics timestep in seconds. Defaults to the model’s timestep.
gravity (Iterable[float] | None) – Gravity vector. Defaults to the model’s gravity.
**controller_kwargs (object) – Passed to
controlleron every call.
- Raises:
ValueError – If no model is given or a parameter is out of range.
TypeError – If
controller_kwargsare given without a controller.
- reload()[source]¶
Rebuild the model and data from
xml.- Returns:
The simulation, for method chaining.
- Return type:
- property model: MjModel¶
The underlying
MjModel(read-only).
- property data: MjData¶
The live
MjDatafor the current step (read-only).Use
captured_datafor the recorded history of a run.
- property captured_data: dict[str, ndarray | list[ndarray]]¶
Data recorded by the last
run(), keyed byMjDatafield.Each value is an array of shape
(captures, *field_shape). Fields whose size changes between steps (e.g.efc_*) are lists of arrays.- Raises:
ValueError – If the simulation has not been run.
- property frames: ndarray¶
Frames rendered by the last
run(), shape(n, height, width, 3).- Raises:
AttributeError – If no frames were rendered.
- property controller: Callable[..., None] | None¶
Control callback
f(model, data, **controller_kwargs), orNone.
- run(*, render=False, camera=None)[source]¶
Simulate for
durationseconds from a fresh reset.Data is recorded
data_ratetimes per second intocaptured_data. Withrender=True, frames are rendered offscreenfpstimes per second intoframes.- Parameters:
- Returns:
The simulation, for method chaining.
- Raises:
SimulationError – If stepping or rendering fails, or a viewer is open.
- Return type:
- launch(show_menu=True)[source]¶
Open an interactive viewer window in a background thread.
Physics runs in real time against the live
data, callingcontrollerevery step. Holddata_lockwhile changingdatafrom another thread. Close the window, or press ESC or Q, to stop. Leaving awith Simulation(...)block waits for the window to close and re-raises viewer errors.- Parameters:
show_menu (bool) – Show the viewer’s side panels.
- Returns:
A future that completes when the window closes;
result()re-raises viewer errors.- Raises:
SimulationError – If a viewer is already open.
- Return type:
Future[None]
- show(title=None, *, frame_idx=None, time_idx=None)[source]¶
Play rendered frames in a window, or inline in Jupyter.
- Parameters:
- Returns:
An inline HTML animation in Jupyter, otherwise
None.- Raises:
ValueError – If no frames were rendered or the indices are invalid.
- Return type:
HTML | None
- save(title='output.gif', *, frame_idx=None, time_idx=None)[source]¶
Write rendered frames to a video or GIF.
- Parameters:
- Returns:
Absolute path of the written file.
- Raises:
ValueError – If no frames were rendered or the indices are invalid.
- Return type:
- body_data(body_name, data_name=None)[source]¶
Captured per-body data for one body.
Per-body fields are
MjDataarrays indexed by body, such asxpos,xquatandcvel. Only captured fields are available.- Parameters:
- Returns:
An array of shape
(captures, *field_shape)fordata_name, or a dict of them keyed by field.- Raises:
ValueError – If the body or field is unknown, or nothing was captured.
- Return type:
- name2id(name, obj_type=None)[source]¶
Look up an object’s id by name.
- Parameters:
- Returns:
The object’s id.
- Raises:
ValueError – If no object has that name.
- Return type:
- id2name(obj_id, obj_type)[source]¶
Look up an object’s name by id.
- Parameters:
- Returns:
The object’s name.
- Raises:
ValueError – If there is no named object with that id.
- Return type:
- to_yaml(name='Model')[source]¶
Write
captured_datato a YAML file.- Parameters:
name (str) – Output path.
.ymlis appended if missing.- Raises:
ValueError – If nothing was captured or the file cannot be written.