MuJoCo Physics Simulator
MuJoCo (Multi-Joint dynamics with Contact) is a physics engine developed by Google DeepMind, used for research and development in robotics, biomechanics, and other areas. The Python bindings allow programmatic interaction with models, simulation, and data. It releases frequently, with minor version updates typically every few weeks to months.
Warnings
- breaking The official `mujoco` Python package (maintained by Google DeepMind) replaced the community-developed `mujoco_py`. `mujoco_py` is deprecated, unmaintained, and should not be used in new projects.
- breaking MuJoCo 3.0.0 introduced a substantial redesign of the Python Bindings API. Code written for pre-3.0 versions will likely break, especially regarding `mjx` (JAX integration) and `mjcf` (model construction) utilities.
- gotcha The `mujoco` Python package itself does not include a visualizer. To render simulations, you typically need to install an additional library like `mujoco_viewer` or integrate with `dm_control`.
- gotcha The `mujoco` Python package officially requires Python 3.10 or newer. Installing with older Python versions may lead to errors or unexpected behavior due to incompatibility with the pre-compiled binaries.
Install
-
pip install mujoco
Imports
- mujoco
import mujoco
- MjModel
import mujoco model = mujoco.MjModel.from_xml_string(...)
- MjData
import mujoco data = mujoco.MjData(model)
- mj_step
import mujoco mujoco.mj_step(model, data)
Quickstart
import mujoco
import numpy as np
# Create a simple XML model string for a sphere on a plane
xml_string = """
<mujoco model="sphere_drop">
<worldbody>
<geom name="floor" type="plane" size="0 0 0.1" material="grid"/>
<body name="sphere" pos="0 0 1">
<geom name="ball" type="sphere" size="0.1" material="sphere_mat"/>
</body>
</worldbody>
<asset>
<texture type="2d" name="grid" builtin="checker" width="512" height="512" rgb1="0.1 0.2 0.3" rgb2="0.2 0.3 0.4" mark="edge" markrgb="0.8 0.8 0.8"/>
<material name="grid" texture="grid" texrepeat="1 1" texuniform="true"/>
<material name="sphere_mat" rgba="0.7 0 0 1"/>
</asset>
</mujoco>
"""
# Load the model and create data
model = mujoco.MjModel.from_xml_string(xml_string)
data = mujoco.MjData(model)
# Simulate for 100 steps
print(f"Initial sphere position: {data.qpos[2]:.3f}") # Assuming Z is the 3rd element of qpos
for i in range(100):
mujoco.mj_step(model, data)
print(f"Final sphere position: {data.qpos[2]:.3f}")