Usage

Example Script

Bare minimum to run MuJoCo simulation and display result

import mujoco_toolbox as mjtb

mjtb.Simulation("path/to/your/xml").run(render=True).save()

Data Capture

run() records MjData fields at data_rate captures per second. Each field is an array of shape (captures, *field_shape).

import mujoco_toolbox as mjtb

sim = mjtb.Simulation("path/to/xml", duration=5, data_rate=100, capture={"time", "qpos", "xpos"}).run()
sim.captured_data["qpos"]  # (500, nq)
sim.body_data("arm", "xpos")  # (500, 3)

Omit capture to use mjtb.CAPTURE_PARAMETERS, or pass capture="all" to record every numeric field.

Controllers

Pre-Made Controllers

The following controllers are available out-of-the-box:

  • sin

  • cos

  • step

  • random

  • real_time (recommended controller for digital twins)

You can import them as follows:

import mujoco_toolbox.controllers as ctrl

Custom


def foo(model: MjModel, data: MjData,**kwargs):
    # Perform logic based on model/data objects
    # ie. PID Controller

Extra keyword arguments to Simulation are passed to the controller on every step:

mjtb.Simulation("path/to/xml", controller=mjtb.sin, amplitude=0.5, frequency=2).run()

Instantiating a Digital Twin

import mujoco_toolbox as mjtb
from mujoco_toolbox.controllers import real_time

with mjtb.Simulation("path/to/xml", controller=real_time) as digitaltwin:
    viewer = digitaltwin.launch(show_menu=False)  # Open the simulation window
    while not viewer.done():  # until the window is closed (or ESC/Q)
        with digitaltwin.data_lock:
            digitaltwin.controller(digitaltwin.model, digitaltwin.data, {"mjdata_kwargs": value})

See MjData objects here

File Support

XML / MJCF (Native)

import mujoco_toolbox as mjtb

mjtb.Simulation("path/to/xml").show()
UR5/Vention

URDF

import mujoco_toolbox as mjtb

mjtb.Simulation("path/to/urdf", meshdir="path/to/mesh/files").show()  # supports *.stl or *.obj
UR5

Merging Capabilities

Supports full <mujoco>...</mujoco> and <robot>...</robot> structure as well as complete sub-tree structures.

import mujoco_toolbox as mjtb

# Merges: XML & URDF Files, XML & URDF Strings, Sub Tree Structures
mjtb.Simulation("path/to/xml_1", string_xml_var, ..., "path/to/xml_n").show()

⚠️ WARNING
Duplicate sub-tree items with the same name will cause MuJoCo to throw a FatalError.

Humanoid in Box