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 MjData field 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: object

A MuJoCo model plus everything needed to run, record, and render it.

Models can be given as file paths (MJCF or URDF), XML strings, or Builder objects. 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) – MjData field 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) – MjData fields to record. "all" records every numeric field. Defaults to mujoco_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 controller on every call.

Raises:
  • ValueError – If no model is given or a parameter is out of range.

  • TypeError – If controller_kwargs are given without a controller.

data_lock

Held by the launch() viewer while it steps data.

reload()[source]

Rebuild the model and data from xml.

Returns:

The simulation, for method chaining.

Return type:

Self

property model: MjModel

The underlying MjModel (read-only).

property data: MjData

The live MjData for the current step (read-only).

Use captured_data for the recorded history of a run.

property keyframe: int | None

Model keyframe to reset to before every run, or None.

property captured_data: dict[str, ndarray | list[ndarray]]

Data recorded by the last run(), keyed by MjData field.

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 duration: float

Simulated time in seconds.

property fps: float

Rendered frames per simulated second.

property resolution: tuple[int, int]

Render size (width, height) in pixels.

property initial_conditions: dict[str, Any]

MjData field values applied before every run.

property controller: Callable[..., None] | None

Control callback f(model, data, **controller_kwargs), or None.

property ts: float

Physics timestep in seconds.

property data_rate: int

Data captures per simulated second.

property gravity: ndarray

Gravity vector (x, y, z).

run(*, render=False, camera=None)[source]

Simulate for duration seconds from a fresh reset.

Data is recorded data_rate times per second into captured_data. With render=True, frames are rendered offscreen fps times per second into frames.

Parameters:
  • render (bool) – Render frames while simulating.

  • camera (str | None) – Camera name to render from. Defaults to the free camera.

Returns:

The simulation, for method chaining.

Raises:

SimulationError – If stepping or rendering fails, or a viewer is open.

Return type:

Self

launch(show_menu=True)[source]

Open an interactive viewer window in a background thread.

Physics runs in real time against the live data, calling controller every step. Hold data_lock while changing data from another thread. Close the window, or press ESC or Q, to stop. Leaving a with 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:
  • title (str | None) – Title shown above the playback.

  • frame_idx (int | tuple[int, int] | None) – A frame index or (start, stop) range.

  • time_idx (float | tuple[float, float] | None) – A time or (start, stop) range in seconds.

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:
  • title (str) – Output path. The extension picks the format (.mp4, .gif, …).

  • frame_idx (int | tuple[int, int] | None) – A frame index or (start, stop) range.

  • time_idx (float | tuple[float, float] | None) – A time or (start, stop) range in seconds.

Returns:

Absolute path of the written file.

Raises:

ValueError – If no frames were rendered or the indices are invalid.

Return type:

str

t2f(t)[source]

Convert a time in seconds to a frame index.

Return type:

int

f2t(frame)[source]

Convert a frame index to a time in seconds.

Return type:

float

body_data(body_name, data_name=None)[source]

Captured per-body data for one body.

Per-body fields are MjData arrays indexed by body, such as xpos, xquat and cvel. Only captured fields are available.

Parameters:
  • body_name (str) – Name of the body.

  • data_name (str | None) – Field to return. If omitted, returns every captured per-body field.

Returns:

An array of shape (captures, *field_shape) for data_name, or a dict of them keyed by field.

Raises:

ValueError – If the body or field is unknown, or nothing was captured.

Return type:

dict[str, ndarray] | ndarray

name2id(name, obj_type=None)[source]

Look up an object’s id by name.

Parameters:
  • name (str) – Object name.

  • obj_type (str | mjtObj | None) – Object type, e.g. "body", "joint" or a mujoco.mjtObj. If omitted, returns the first match across all types.

Returns:

The object’s id.

Raises:

ValueError – If no object has that name.

Return type:

int

id2name(obj_id, obj_type)[source]

Look up an object’s name by id.

Parameters:
  • obj_id (int) – Object id.

  • obj_type (str | mjtObj) – Object type, e.g. "body", "joint" or a mujoco.mjtObj.

Returns:

The object’s name.

Raises:

ValueError – If there is no named object with that id.

Return type:

str

to_yaml(name='Model')[source]

Write captured_data to a YAML file.

Parameters:

name (str) – Output path. .yml is appended if missing.

Raises:

ValueError – If nothing was captured or the file cannot be written.