MuJoCo Python: Simulation, Sensors & Math
[!TIP]
Official MuJoCo documentation (doc/*.rst): Read short chapters like
../../programming/simulation.rst
(.. _Simulation:) and ../../overview.rst directly
when in a MuJoCo checkout; for large reference files like
../../python.rst (.. _PyStructs:, .. _PyNamed:,
.. _PyBatch:, .. _PySysid:),
../../modeling.rst (.. _CTuning:),
../../computation/index.rst (.. _Pipeline:,
.. _geIntegrators:, .. _geChoosingTimestepIntegrator:),
../../XMLreference.rst, and
../../APIreference/functions.rst, grep
the literal .. _Label: anchor. Outside a checkout, the same doc/*.rst tree
ships offline in pip install mujoco at
pathlib.Path(mujoco.__file__).parent / 'doc'; otherwise fetch
https://mujoco.readthedocs.io/en/latest/<path>.html (or /en/stable/ for
released pages; functions.rst renders inside
APIreference/APIfunctions.html, and Sphinx anchors lowercase the label,
e.g. .. _PyBatch: → #pybatch) and browse repo paths (../../../,
python/*.ipynb) under
https://github.com/google-deepmind/mujoco/tree/main/.
Related skills:
- mujoco-spec-editing — Procedural model
editing and composing scenes with
MjSpec.
- mujoco-deformables — Deformable
<flexcomp>,
<flex>, and <skin> modeling (rods, cloth, and 3D FEM soft bodies).
- mujoco-rendering — Offscreen image rendering,
cameras, depth, and segmentation.
- mujoco-accelerated — GPU/TPU physics simulation
with MJX (JAX) and MJWarp (CUDA).
- mujoco-parity — Cross-engine physics parity
comparison against MJWarp and MJX.
- mujoco-studio — Interactive viewers, Studio viewer
apps, and plugin architecture.
[!CAUTION]
- NEVER use
mj_name2id, model.name2id, or raw integer indexing
(e.g., data.qpos[0], data.xpos[body_id]) to look up elements by name.
Always use named access (data.body('name').xpos) or bind()
instead.
- Do not use dm_control / PyMJCF lookup patterns.
model.find('body', 'name'), .find_body(), and physics.named do not exist in
MuJoCo 3.x. Use direct accessors: .body('name'), .geom('name') etc. on
MjSpec, MjModel, and MjData.
1. Compilation Lifecycle: MjSpec → MjModel → MjData
MuJoCo models follow a three-stage lifecycle:
MjSpec ──spec.compile()──▶ MjModel ──MjData(model)──▶ MjData
│ │ │
│ (mutable blueprint) │ (compiled, mostly frozen) │ (simulation state)
│ │ │
└── spec.recompile(m, d) ─────┴────────────────────────────┘
MjSpec: Mutable data structure defining the simulation elements and
hierarchy.
MjModel: Compiled, optimized physics model containing constant and
precomputed parameters. Structural changes require recompilation.
MjData: Dynamic simulation state (positions, velocities, forces,
contacts, diagnostic buffers).
Python Lifecycle
import mujoco
# 1. Build or load spec
spec = mujoco.MjSpec()
body = spec.worldbody.add_body(name='pendulum', pos=[0, 0, 1])
body.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1])
body.add_joint(name='hinge', type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 1, 0])
# 2. Compile to model and instantiate data
model = spec.compile()
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
# 3. Dynamic recompilation (preserves existing state)
body2 = spec.worldbody.add_body(name='ball2', pos=[1, 0, 1])
body2.add_geom(size=[0.1])
body2.add_freejoint()
model, data = spec.recompile(model, data) # Always reassign return values
C++ Lifecycle
#include <mujoco/mujoco.h>
// 1. Create or load spec (or: mj_parseXML(filename, nullptr, error, sizeof(error)))
mjSpec* spec = mj_makeSpec();
mjsBody* world = mjs_findBody(spec, "world");
mjsBody* body = mjs_addBody(world, nullptr);
mjsGeom* geom = mjs_addGeom(body, nullptr);
geom->type = mjGEOM_SPHERE;
geom->size[0] = 0.1;
// 2. Compile to model and create data
mjModel* model = mj_compile(spec, nullptr);
if (!model) {
printf("%s\n", mjs_getError(spec));
}
mjData* data = mj_makeData(model);
// 3. Step or evaluate
mj_forward(model, data);
// 4. Clean up allocated resources
mj_deleteData(data);
mj_deleteModel(model);
mj_deleteSpec(spec);
Loading and Serializing
# Direct model loading from file or string
model = mujoco.MjModel.from_xml_path('model.xml')
model = mujoco.MjModel.from_xml_string(xml_str)
model = mujoco.MjModel.from_binary_path('model.mjb') # Precompiled binary format
# Loading mutable spec from file or string
spec = mujoco.MjSpec.from_file('model.xml')
spec = mujoco.MjSpec.from_string(xml_str)
# Serialization
xml_string = spec.to_xml()
spec.encode('model.xml', model)
[!CAUTION]
mujoco.load_model_from_path does not exist in MuJoCo 3.x. Use
mujoco.MjModel.from_xml_path(path) or mujoco.MjSpec.from_file(path). For
ready-to-run models, check ../../../model/ (humanoid/humanoid.xml,
tendon_arm/arm26.xml, car/car.xml), ../../../test/engine/testdata/, and
MuJoCo Menagerie (models.rst, .. _Menagerie:).
2. Accessing State: Named Access & bind()
1. Named Access (on MjModel and MjData)
In Python, access elements by calling the element-type accessor with the element
name:
# Reading state
torso_pos = data.body('torso').xpos # NumPy view (3,)
knee_angle = data.joint('knee').qpos # Shape depends on joint type
ball_size = model.geom('ball').size # NumPy view (3,)
# Writing controls and state
data.actuator('motor').ctrl = 1.0 # Writable view
data.joint('knee').qpos = 0.5
Supported element accessors: body, geom, joint (alias jnt), site,
camera (alias cam), light, mesh, skin, texture (alias tex),
material (alias mat), pair, equality (alias eq), tendon (alias
ten), actuator, sensor, numeric, text, tuple, keyframe (alias
key).
[!WARNING]
Named access returns views, not copies. In a simulation loop, modifying
the simulation changes the array in-place. If logging or storing history,
always call .copy():
# ❌ WRONG — all history items will point to the same final state
history.append(data.body('torso').xpos)
# ✅ RIGHT — records distinct coordinates
history.append(data.body('torso').xpos.copy())
2. bind() (Bridges MjSpec elements → MjModel / MjData)
When building models programmatically with MjSpec, use bind() to map spec
element handles directly to compiled data:
geom = spec.worldbody.add_geom(name='ball', size=[0.1])
joint = spec.worldbody.add_joint(name='hinge', type=mujoco.mjtJoint.mjJNT_HINGE)
model = spec.compile()
data = mujoco.MjData(model)
# Read through bind
radius = model.bind(geom).size[0]
ball_pos = data.bind(geom).xpos
# Write through bind — always use .set()
data.bind(joint).set('qpos', 0.5)
# Bind lists of spec elements in batch
joints = [spec.joint('j1'), spec.joint('j2')]
joint_angles = data.bind(joints).qpos
3. Simulation Stepping & Execution Pipeline
Stepping Pipeline (mj_step vs mj_step1 / mj_step2)
mj_step(model, data): Advances the simulation by one timestep
(model.opt.timestep). It computes kinematics, forces, collision constraints,
accelerations, and numerical integration in one full pass.
- Split Stepping (
mj_step1 + mj_step2): Used when custom controller
forces or external computations depend on the current kinematic state:
# 1. Advance position kinematics and sensor computations
mujoco.mj_step1(model, data)
# 2. Apply control torques or external forces based on current kinematics
data.ctrl[:] = compute_feedback_control(data.qpos, data.qvel)
data.qfrc_applied[:] = compute_external_forces(data)
# 3. Complete dynamic acceleration and integration
mujoco.mj_step2(model, data)
Sensor and Kinematic Initialization (mj_forward)
Before reading sensors or positions at time zero, call mj_forward() instead of
mj_step(). mj_forward evaluates kinematics and sensor outputs from the
current state without advancing simulation time:
# ✅ RIGHT — initialize sensors and kinematics at t=0
mujoco.mj_forward(model, data)
initial_obs = data.sensordata.copy()
# Advance physics
for _ in range(num_steps):
mujoco.mj_step(model, data)
Keyframe Resets & Restoring State
Use keyframes to reset configurations reliably:
# Python: reset to named keyframe
key_id = model.key('home').id
mujoco.mj_resetDataKeyframe(model, data, key_id)
mujoco.mj_forward(model, data) # Recompute kinematics and sensors
In C++:
int key_id = mj_name2id(m, mjOBJ_KEY, "home");
if (key_id >= 0) {
mj_resetDataKeyframe(m, d, key_id);
mj_forward(m, d);
}
Integrators & Numerical Stability
Configured via model.opt.integrator (full equations and timestep/integrator
selection notes in computation/index.rst,
.. _geIntegrators: and .. _geChoosingTimestepIntegrator:,
modeling.rst, .. _CTuningGlobal:, and
XMLreference.rst, .. _option-integrator:):
mjINT_IMPLICITFAST (recommended): Velocity-implicit (damping, kv,
fluid drag, free-body gyroscopic forces) via symmetric Cholesky at ~Euler
cost.
mjINT_IMPLICIT: Adds asymmetric Coriolis/centripetal velocity derivatives
(LU factorization) for rapidly spinning multi-link chains.
mjINT_EULER (legacy default): Semi-implicit Euler; implicit in joint
damping only.
mjINT_RK4: 4th-order Runge-Kutta (4 evaluations/step) for smooth,
energy-conserving systems.
mjINT_DISCRETE (candidate replacement in trial): Also implicit in
position (stiff springs, position servos kp, <flex> <elasticity>,
and their coupling with contacts; implicit/implicitfast are
velocity-implicit only — see
mujoco-deformables).
4. Contact & Force Sensing: Declarative Sensors
Why data.contact Should NOT Be Used for Observations
data.contact is a variable-length buffer that changes size and ordering every
timestep based on active collision pairs:
# ❌ WRONG — variable size and non-deterministic order break ML policies
for c in data.contact:
if c.geom1 == target_id:
force = ...
Declarative Contact Sensors
<contact> sensors (see XMLreference.rst,
.. _sensor-contact:) declaratively filter contacts, reduce them to a fixed
number of slots, and write deterministic vectors directly into data.sensordata:
<sensor>
<!-- Detect contacts between gripper and object: fixed 3 slots -->
<contact name="grip_contact"
body1="gripper" body2="object"
num="3" data="found force normal"
reduce="maxforce"/>
<!-- Net wrench on an entire body -->
<contact name="object_net"
body1="object"
data="force torque"
reduce="netforce"/>
</sensor>
Reading contact sensors in Python:
contact_data = data.sensor('grip_contact').data # Always fixed length
Touch Sensors for Scalar Normal Force
For scalar surface contact forces (e.g., fingertips), use touch sensors
(XMLreference.rst, .. _sensor-touch:) attached to a
site. Make sure the site is large enough to encompass the geom:
site = body.add_site(name='fingertip', pos=[0, 0, 0.05], size=[0.02])
spec.add_sensor(
name='touch_sensor',
type=mujoco.mjtSensor.mjSENS_TOUCH,
objname=site.name,
objtype=mujoco.mjtObj.mjOBJ_SITE,
)
5. Spatial Mathematics (mju_ Library)
MuJoCo provides an optimized spatial mathematics library under the mju_
namespace in both C++ and Python.
[!IMPORTANT]
MuJoCo quaternions are scalar-first: [w, x, y, z]. SciPy and ROS use
scalar-last: [x, y, z, w]. Swizzle components when converting:
# MuJoCo -> SciPy/ROS
scipy_quat = mj_quat[[1, 2, 3, 0]]
# SciPy/ROS -> MuJoCo
mj_quat = scipy_quat[[3, 0, 1, 2]]
Quaternion Operations
res = np.zeros(3)
mujoco.mju_rotVecQuat(res, vec, quat) # Rotate vector by quaternion
quat = np.zeros(4)
mujoco.mju_mat2Quat(quat, mat9) # Flat (9,) rotation matrix → quaternion
mujoco.mju_quat2Mat(mat9, quat) # Quaternion → flat (9,) matrix
mujoco.mju_axisAngle2Quat(quat, axis, angle) # Axis-angle → quaternion
mujoco.mju_euler2Quat(quat, euler, 'xyz') # Euler angles → quaternion
mujoco.mju_mulQuat(res_q, q1, q2) # Compose quaternions (q1 * q2)
mujoco.mju_negQuat(res_q, quat) # Quaternion conjugate (inverse)
mujoco.mju_quatZ2Vec(quat, vec) # Quaternion rotating Z-axis to vector
Pose Operations
# Compose poses (pos1/quat1 then pos2/quat2)
mujoco.mju_mulPose(pos_res, quat_res, pos1, quat1, pos2, quat2)
# Invert pose
mujoco.mju_negPose(pos_res, quat_res, pos, quat)
# Transform 3D point by pose
mujoco.mju_trnVecPose(res, pos, quat, vec)
6. Energy & Diagnostics
MuJoCo can continuously compute total mechanical energy to diagnose simulation
stability:
# Enable energy monitoring
model.opt.enableflags |= mujoco.mjtEnableBit.mjENBL_ENERGY
mujoco.mj_step(model, data)
potential_energy = data.energy[0]
kinetic_energy = data.energy[1]
total_energy = potential_energy + kinetic_energy
In passive, unforced, undamped systems, total_energy must remain constant.
Growing energy indicates numerical integration instability (requiring smaller
timesteps, or implicitfast if large damping or other velocity-dependent forces
are the cause). Before stiffening contacts to mask instability, inspect the
paused model at t = 0 in Studio/simulate for initial penetrations,
visual/collision geom mismatches, concave collision meshes replaced by convex
hulls (.. _coChecking:), implausible CAD/URDF inertia boxes, and degree/radian
mismatches (compiler/angle defaults to "degree"). For priority-ordered
speed-fidelity tuning, diagnosing divergence, non-SI unit mistakes
(millimeter/gram meshes), island sleeping, speculative CCD, or fluid drag, read
modeling.rst (.. _CTuning:, .. _CTuningDefaults:,
.. _CTuningGlobal:, .. _CTuningModel:),
overview.rst (.. _Clarifications:, .. _Divergence:,
.. _Units:, .. _Soft:),
computation/index.rst (.. _Solver:,
.. _Sleeping:), programming/simulation.rst
(.. _siSleep:), computation/speculative.rst,
and computation/fluid.rst.
7. CPU Batching (mujoco.batch & mujoco.rollout), Optimization & Backends
Stateful Multi-Threaded CPU Batching (mujoco.batch.Batch)
For vectorized RL stepping, closed-loop controllers, subset resets, and
per-simulation domain randomization on CPU across a native C++ thread pool (GIL
released, bit-identical to serial MjData stepping, and supporting all CPU
solvers/plugins), use mujoco.batch.Batch (python.rst,
.. _PyBatch:, wrapping C mjb_* in
APIreference/functions.rst,
.. _Batchedsimulation:):
from mujoco import batch
# Pass persistent=True if the model uses sleep, IPC, or stateful plugins
b = batch.Batch(model, nsim=1024, nthread=8)
qpos, ctrl, xpos = b.bind('qpos'), b.bind('ctrl'), b.bind('xpos')
# Named views slice (nsim, ...) and expand per-sim model fields
hinge_qpos = b.joint('hinge').qpos # (1024, 1)
b.body('pendulum').mass = per_sim_masses # Domain randomization
b.set_const() # Recompute derived model constants
for _ in range(1000):
ctrl[:] = policy(qpos, xpos)
b.step() # Or b.step(ids=active_ids)
Stateless Trajectory Rollouts, Optimization & System ID
- Open-loop trajectory rollouts (
mujoco.rollout): When rolling out fixed
control sequences (nbatch, nstep, ncontrol) from initial_state in one
call, use mujoco.rollout.rollout (python.rst,
.. _PyRollout:, and python/rollout.ipynb) or b.rollout(...).
- Finite-difference derivatives & LQR (
mjd_transitionFD): Compute
linearized $A, B, C, D$ transition matrices with mujoco.mjd_transitionFD
(APIreference/functions.rst,
.. _Derivatives-api:, and python/LQR.ipynb).
- Nonlinear least-squares & System ID (
mujoco.minimize, mujoco.sysid):
Use mujoco.minimize.least_squares (python.rst,
.. _PyMinimize:, and python/least_squares.ipynb) for box-constrained QP
optimization (mju_boxQP), and mujoco.sysid (pip install mujoco[sysid];
see python.rst, .. _PySysid:,
modeling.rst, .. _CTuningSysid:,
python/mujoco/sysid/README.md, and python/mujoco/sysid/sysid.ipynb) for
fitting inertias, friction/damping, actuator gains, and delays to hardware
logs over batched rollouts.
Compute Backend Comparison
| Feature |
C++ Engine (Default) |
MJX (JAX) |
MJWarp (CUDA) |
| Import |
import mujoco (mujoco.batch, mujoco.rollout) |
from mujoco import mjx |
import mujoco_warp as mjw |
| Primary Use |
Real-time control, interactive tools, CPU batch RL/MPC, full solver support |
Differentiable physics, large batch RL |
High-throughput batch rollouts |
| Hardware |
CPU (single or multi-threaded) |
GPU / TPU |
NVIDIA GPU |
| Precision |
float64 (or float32 with -DmjUSESINGLE / --@mujoco//:single_precision) |
float32 |
float32 |
| Solvers |
Newton, CG, PGS, noslip |
Newton, CG |
Newton, CG |
| Plugins |
All plugins |
Not supported |
SDF only |
For GPU and TPU execution patterns (and RL frameworks like mujoco_playground
and mjlab), refer to mujoco-accelerated; for
cross-engine physics comparison, refer to mujoco-parity.
8. Common Gotchas & Best Practices
- Computed fields are read-only: Fields like
data.xpos, data.xmat, and
data.xquat are output buffers. Never assign to them directly; change
inputs (data.qpos, data.ctrl) and call mj_forward() or mj_step().
- Duplicate names are forbidden: Spec element names must be unique within
each element type.
- Orientation keywords are mutually exclusive: When adding geoms, bodies,
or sites, provide only one of
quat, euler, axisangle, xyaxes, or
zaxis.
- Euler sequences: Lowercase characters denote intrinsic rotations
(
'xyz'), uppercase denote extrinsic rotations ('XYZ').
- Coordinate convention: +Z is up, gravity is
[0, 0, -9.81].
- Repeating controls with
nstep: Calling mj_step(model, data, nstep=N)
repeats the current control across N steps. For dynamic feedback control,
step one timestep at a time.
9. Key References
Documentation
- Python Bindings Reference (
.. _PyNotebook:,
.. _PyStructs:, .. _PyNamed:, .. _PyModelEdit:, .. _PyMJCF:,
.. _PyRollout:, .. _PyBatch:, .. _PyMinimize:, .. _PySysid:)
- Model Tuning & Pitfalls (
.. _CTuning:,
.. _CTuningDefaults:, .. _CTuningGlobal:, .. _CTuningModel:,
.. _CTuningSysid:) and Overview
(.. _Clarifications:, .. _Divergence:, .. _Units:,
.. _SurprisingCollisions:, .. _Soft:)
- Simulation Loop, Batching & Sleeping
(
.. _siSimulation:, .. _siStateControl:, .. _siForward:,
.. _siBatch:, .. _siDiagnostics:, .. _siSleep:)
- Computation, Solvers & Integrators
(
.. _geIntegrators:, .. _geChoosingTimestepIntegrator:, .. _geState:,
.. _Solver:, .. _Sleeping:, .. _Pipeline:),
Speculative CCD, and
Fluid Dynamics
- MuJoCo Menagerie Robot Gallery (
.. _Menagerie:) and
MJCF Sensor & Option Reference
(.. _sensor-contact:, .. _sensor-touch:, .. _option-flag:,
.. _keyframe:)
- C API Function Reference
(
.. _Mainsimulation:, .. _Batchedsimulation:, .. _Derivatives-api:,
.. _Quaternions:, .. _Poses:; rendered online inside
APIfunctions.rst) and
C API Types & Structs (.. _mjModel:,
.. _mjData:, .. _mjtState:)
Notebooks, Models & Ecosystem
- In-repo notebooks:
python/tutorial.ipynb, python/mjspec.ipynb,
python/rollout.ipynb, python/LQR.ipynb, python/least_squares.ipynb,
and python/mujoco/sysid/sysid.ipynb
- Source & models:
Python Bindings Tests,
Built-in Showcase Models,
C++ Samples (
.. _Sample:), and
C API Header
- Downstream control & RL repos:
MuJoCo MPC (
mujoco_mpc),
dm_control,
MuJoCo Playground,
and mjlab
1---2name: mujoco-python3description: >-4 MuJoCo Python (`import mujoco`) simulation lifecycle (MjSpec, MjModel, MjData),5 stepping (mj_step, mj_step1, mj_step2, mj_forward), named access (data.body,6 model.geom), bind(), multi-threaded CPU batch simulation (mujoco.batch.Batch,7 mujoco.rollout), optimization and system ID (mujoco.minimize, mujoco.sysid,8 mjd_transitionFD), contact/touch sensors, sensordata, keyframe resets,9 integrators, mju_ spatial math (quaternions, poses), and energy diagnostics.10 Use only for MuJoCo Python physics simulation, MjModel/MjData state access,11 MuJoCo CPU batching, stepping loops, and MuJoCo sensors/sysid. Don't use for12 custom non-MuJoCo Python/NumPy/C++ ODE or rigid-body simulators, custom13 finite-difference sysid, or general spatial math without `mujoco`, nor for14 spec editing (mujoco-spec-editing), deformable flex/cloth/cable modeling15 (mujoco-deformables), rendering (mujoco-rendering), GPU/TPU16 (mujoco-accelerated), parity (mujoco-parity), or GUI/viewers (mujoco-gui,17 mujoco-studio).18metadata:19 source: https://skillmd.com/skills/google-deepmind/mujoco-python20---2122# MuJoCo Python: Simulation, Sensors & Math2324> [!TIP]25>26> **Official MuJoCo documentation (`doc/*.rst`):** Read short chapters like27> [`../../programming/simulation.rst`](../../programming/simulation.rst)28> (`.. _Simulation:`) and [`../../overview.rst`](../../overview.rst) directly29> when in a MuJoCo checkout; for large reference files like30> [`../../python.rst`](../../python.rst) (`.. _PyStructs:`, `.. _PyNamed:`,31> `.. _PyBatch:`, `.. _PySysid:`),32> [`../../modeling.rst`](../../modeling.rst) (`.. _CTuning:`),33> [`../../computation/index.rst`](../../computation/index.rst) (`.. _Pipeline:`,34> `.. _geIntegrators:`, `.. _geChoosingTimestepIntegrator:`),35> [`../../XMLreference.rst`](../../XMLreference.rst), and36> [`../../APIreference/functions.rst`](../../APIreference/functions.rst), grep37> the literal `.. _Label:` anchor. Outside a checkout, the same `doc/*.rst` tree38> ships offline in `pip install mujoco` at39> `pathlib.Path(mujoco.__file__).parent / 'doc'`; otherwise fetch40> `https://mujoco.readthedocs.io/en/latest/<path>.html` (or `/en/stable/` for41> released pages; `functions.rst` renders inside42> `APIreference/APIfunctions.html`, and Sphinx anchors lowercase the label,43> e.g. `.. _PyBatch:` → `#pybatch`) and browse repo paths (`../../../`,44> `python/*.ipynb`) under45> `https://github.com/google-deepmind/mujoco/tree/main/`.46>47> **Related skills:**48>49> - [mujoco-spec-editing](../spec_editing/SKILL.md) — Procedural model50> editing and composing scenes with `MjSpec`.51> - [mujoco-deformables](../deformables/SKILL.md) — Deformable `<flexcomp>`,52> `<flex>`, and `<skin>` modeling (rods, cloth, and 3D FEM soft bodies).53> - [mujoco-rendering](../rendering/SKILL.md) — Offscreen image rendering,54> cameras, depth, and segmentation.55> - [mujoco-accelerated](../accelerated/SKILL.md) — GPU/TPU physics simulation56> with MJX (JAX) and MJWarp (CUDA).57> - [mujoco-parity](../parity/SKILL.md) — Cross-engine physics parity58> comparison against MJWarp and MJX.59> - [mujoco-studio](../studio/SKILL.md) — Interactive viewers, Studio viewer60> apps, and plugin architecture.6162> [!CAUTION]63>64> - **NEVER use `mj_name2id`, `model.name2id`, or raw integer indexing**65> (e.g., `data.qpos[0]`, `data.xpos[body_id]`) to look up elements by name.66> Always use **named access** (`data.body('name').xpos`) or **`bind()`**67> instead.68> - **Do not use dm_control / PyMJCF lookup patterns.** `model.find('body',69> 'name')`, `.find_body()`, and `physics.named` do **not exist** in70> MuJoCo 3.x. Use direct accessors: `.body('name')`, `.geom('name')` etc. on71> `MjSpec`, `MjModel`, and `MjData`.7273## 1. Compilation Lifecycle: MjSpec → MjModel → MjData7475MuJoCo models follow a three-stage lifecycle:7677```text78MjSpec ──spec.compile()──▶ MjModel ──MjData(model)──▶ MjData79 │ │ │80 │ (mutable blueprint) │ (compiled, mostly frozen) │ (simulation state)81 │ │ │82 └── spec.recompile(m, d) ─────┴────────────────────────────┘83```84851. **`MjSpec`**: Mutable data structure defining the simulation elements and86 hierarchy.872. **`MjModel`**: Compiled, optimized physics model containing constant and88 precomputed parameters. Structural changes require recompilation.893. **`MjData`**: Dynamic simulation state (positions, velocities, forces,90 contacts, diagnostic buffers).9192### Python Lifecycle9394```python95import mujoco9697# 1. Build or load spec98spec = mujoco.MjSpec()99body = spec.worldbody.add_body(name='pendulum', pos=[0, 0, 1])100body.add_geom(type=mujoco.mjtGeom.mjGEOM_SPHERE, size=[0.1])101body.add_joint(name='hinge', type=mujoco.mjtJoint.mjJNT_HINGE, axis=[0, 1, 0])102103# 2. Compile to model and instantiate data104model = spec.compile()105data = mujoco.MjData(model)106mujoco.mj_forward(model, data)107108# 3. Dynamic recompilation (preserves existing state)109body2 = spec.worldbody.add_body(name='ball2', pos=[1, 0, 1])110body2.add_geom(size=[0.1])111body2.add_freejoint()112model, data = spec.recompile(model, data) # Always reassign return values113```114115### C++ Lifecycle116117```cpp118#include <mujoco/mujoco.h>119120// 1. Create or load spec (or: mj_parseXML(filename, nullptr, error, sizeof(error)))121mjSpec* spec = mj_makeSpec();122mjsBody* world = mjs_findBody(spec, "world");123mjsBody* body = mjs_addBody(world, nullptr);124mjsGeom* geom = mjs_addGeom(body, nullptr);125geom->type = mjGEOM_SPHERE;126geom->size[0] = 0.1;127128// 2. Compile to model and create data129mjModel* model = mj_compile(spec, nullptr);130if (!model) {131 printf("%s\n", mjs_getError(spec));132}133mjData* data = mj_makeData(model);134135// 3. Step or evaluate136mj_forward(model, data);137138// 4. Clean up allocated resources139mj_deleteData(data);140mj_deleteModel(model);141mj_deleteSpec(spec);142```143144### Loading and Serializing145146```python147# Direct model loading from file or string148model = mujoco.MjModel.from_xml_path('model.xml')149model = mujoco.MjModel.from_xml_string(xml_str)150model = mujoco.MjModel.from_binary_path('model.mjb') # Precompiled binary format151152# Loading mutable spec from file or string153spec = mujoco.MjSpec.from_file('model.xml')154spec = mujoco.MjSpec.from_string(xml_str)155156# Serialization157xml_string = spec.to_xml()158spec.encode('model.xml', model)159```160161> [!CAUTION]162>163> `mujoco.load_model_from_path` does **not exist** in MuJoCo 3.x. Use164> `mujoco.MjModel.from_xml_path(path)` or `mujoco.MjSpec.from_file(path)`. For165> ready-to-run models, check `../../../model/` (`humanoid/humanoid.xml`,166> `tendon_arm/arm26.xml`, `car/car.xml`), `../../../test/engine/testdata/`, and167> MuJoCo Menagerie ([models.rst](../../models.rst), `.. _Menagerie:`).168169## 2. Accessing State: Named Access & bind()170171### 1. Named Access (on `MjModel` and `MjData`)172173In Python, access elements by calling the element-type accessor with the element174name:175176```python177# Reading state178torso_pos = data.body('torso').xpos # NumPy view (3,)179knee_angle = data.joint('knee').qpos # Shape depends on joint type180ball_size = model.geom('ball').size # NumPy view (3,)181182# Writing controls and state183data.actuator('motor').ctrl = 1.0 # Writable view184data.joint('knee').qpos = 0.5185```186187Supported element accessors: `body`, `geom`, `joint` (alias `jnt`), `site`,188`camera` (alias `cam`), `light`, `mesh`, `skin`, `texture` (alias `tex`),189`material` (alias `mat`), `pair`, `equality` (alias `eq`), `tendon` (alias190`ten`), `actuator`, `sensor`, `numeric`, `text`, `tuple`, `keyframe` (alias191`key`).192193> [!WARNING]194>195> **Named access returns views, not copies.** In a simulation loop, modifying196> the simulation changes the array in-place. If logging or storing history,197> **always call `.copy()`**:198>199> ```python200> # ❌ WRONG — all history items will point to the same final state201> history.append(data.body('torso').xpos)202>203> # ✅ RIGHT — records distinct coordinates204> history.append(data.body('torso').xpos.copy())205> ```206207### 2. `bind()` (Bridges `MjSpec` elements → `MjModel` / `MjData`)208209When building models programmatically with `MjSpec`, use `bind()` to map spec210element handles directly to compiled data:211212```python213geom = spec.worldbody.add_geom(name='ball', size=[0.1])214joint = spec.worldbody.add_joint(name='hinge', type=mujoco.mjtJoint.mjJNT_HINGE)215model = spec.compile()216data = mujoco.MjData(model)217218# Read through bind219radius = model.bind(geom).size[0]220ball_pos = data.bind(geom).xpos221222# Write through bind — always use .set()223data.bind(joint).set('qpos', 0.5)224225# Bind lists of spec elements in batch226joints = [spec.joint('j1'), spec.joint('j2')]227joint_angles = data.bind(joints).qpos228```229230## 3. Simulation Stepping & Execution Pipeline231232### Stepping Pipeline (`mj_step` vs `mj_step1` / `mj_step2`)233234- **`mj_step(model, data)`**: Advances the simulation by one timestep235 (`model.opt.timestep`). It computes kinematics, forces, collision constraints,236 accelerations, and numerical integration in one full pass.237- **Split Stepping (`mj_step1` + `mj_step2`)**: Used when custom controller238 forces or external computations depend on the current kinematic state:239240```python241# 1. Advance position kinematics and sensor computations242mujoco.mj_step1(model, data)243244# 2. Apply control torques or external forces based on current kinematics245data.ctrl[:] = compute_feedback_control(data.qpos, data.qvel)246data.qfrc_applied[:] = compute_external_forces(data)247248# 3. Complete dynamic acceleration and integration249mujoco.mj_step2(model, data)250```251252### Sensor and Kinematic Initialization (`mj_forward`)253254Before reading sensors or positions at time zero, call `mj_forward()` instead of255`mj_step()`. `mj_forward` evaluates kinematics and sensor outputs from the256current state **without advancing simulation time**:257258```python259# ✅ RIGHT — initialize sensors and kinematics at t=0260mujoco.mj_forward(model, data)261initial_obs = data.sensordata.copy()262263# Advance physics264for _ in range(num_steps):265 mujoco.mj_step(model, data)266```267268### Keyframe Resets & Restoring State269270Use keyframes to reset configurations reliably:271272```python273# Python: reset to named keyframe274key_id = model.key('home').id275mujoco.mj_resetDataKeyframe(model, data, key_id)276mujoco.mj_forward(model, data) # Recompute kinematics and sensors277```278279In C++:280```cpp281int key_id = mj_name2id(m, mjOBJ_KEY, "home");282if (key_id >= 0) {283 mj_resetDataKeyframe(m, d, key_id);284 mj_forward(m, d);285}286```287288### Integrators & Numerical Stability289290Configured via `model.opt.integrator` (full equations and timestep/integrator291selection notes in [computation/index.rst](../../computation/index.rst),292`.. _geIntegrators:` and `.. _geChoosingTimestepIntegrator:`,293[modeling.rst](../../modeling.rst), `.. _CTuningGlobal:`, and294[XMLreference.rst](../../XMLreference.rst), `.. _option-integrator:`):295296- `mjINT_IMPLICITFAST` (**recommended**): Velocity-implicit (damping, `kv`,297 fluid drag, free-body gyroscopic forces) via symmetric Cholesky at ~Euler298 cost.299- `mjINT_IMPLICIT`: Adds asymmetric Coriolis/centripetal velocity derivatives300 (LU factorization) for rapidly spinning multi-link chains.301- `mjINT_EULER` (legacy default): Semi-implicit Euler; implicit in joint302 damping only.303- `mjINT_RK4`: 4th-order Runge-Kutta (4 evaluations/step) for smooth,304 energy-conserving systems.305- `mjINT_DISCRETE` (candidate replacement in trial): Also implicit in306 *position* (stiff springs, position servos `kp`, `<flex>` `<elasticity>`,307 and their coupling with contacts; `implicit`/`implicitfast` are308 velocity-implicit only — see309 [`mujoco-deformables`](../deformables/SKILL.md)).310311## 4. Contact & Force Sensing: Declarative Sensors312313### Why `data.contact` Should NOT Be Used for Observations314315`data.contact` is a variable-length buffer that changes size and ordering every316timestep based on active collision pairs:317318```python319# ❌ WRONG — variable size and non-deterministic order break ML policies320for c in data.contact:321 if c.geom1 == target_id:322 force = ...323```324325### Declarative Contact Sensors326327`<contact>` sensors (see [XMLreference.rst](../../XMLreference.rst),328`.. _sensor-contact:`) declaratively filter contacts, reduce them to a fixed329number of slots, and write deterministic vectors directly into `data.sensordata`:330331```xml332<sensor>333 <!-- Detect contacts between gripper and object: fixed 3 slots -->334 <contact name="grip_contact"335 body1="gripper" body2="object"336 num="3" data="found force normal"337 reduce="maxforce"/>338339 <!-- Net wrench on an entire body -->340 <contact name="object_net"341 body1="object"342 data="force torque"343 reduce="netforce"/>344</sensor>345```346347Reading contact sensors in Python:348```python349contact_data = data.sensor('grip_contact').data # Always fixed length350```351352### Touch Sensors for Scalar Normal Force353354For scalar surface contact forces (e.g., fingertips), use `touch` sensors355([XMLreference.rst](../../XMLreference.rst), `.. _sensor-touch:`) attached to a356site. Make sure the site is large enough to encompass the geom:357358```python359site = body.add_site(name='fingertip', pos=[0, 0, 0.05], size=[0.02])360spec.add_sensor(361 name='touch_sensor',362 type=mujoco.mjtSensor.mjSENS_TOUCH,363 objname=site.name,364 objtype=mujoco.mjtObj.mjOBJ_SITE,365)366```367368## 5. Spatial Mathematics (mju_ Library)369370MuJoCo provides an optimized spatial mathematics library under the `mju_`371namespace in both C++ and Python.372373> [!IMPORTANT]374>375> MuJoCo quaternions are **scalar-first**: `[w, x, y, z]`. SciPy and ROS use376> **scalar-last**: `[x, y, z, w]`. Swizzle components when converting:377>378> ```python379> # MuJoCo -> SciPy/ROS380> scipy_quat = mj_quat[[1, 2, 3, 0]]381>382> # SciPy/ROS -> MuJoCo383> mj_quat = scipy_quat[[3, 0, 1, 2]]384> ```385386### Quaternion Operations387388```python389res = np.zeros(3)390mujoco.mju_rotVecQuat(res, vec, quat) # Rotate vector by quaternion391392quat = np.zeros(4)393mujoco.mju_mat2Quat(quat, mat9) # Flat (9,) rotation matrix → quaternion394mujoco.mju_quat2Mat(mat9, quat) # Quaternion → flat (9,) matrix395mujoco.mju_axisAngle2Quat(quat, axis, angle) # Axis-angle → quaternion396mujoco.mju_euler2Quat(quat, euler, 'xyz') # Euler angles → quaternion397mujoco.mju_mulQuat(res_q, q1, q2) # Compose quaternions (q1 * q2)398mujoco.mju_negQuat(res_q, quat) # Quaternion conjugate (inverse)399mujoco.mju_quatZ2Vec(quat, vec) # Quaternion rotating Z-axis to vector400```401402### Pose Operations403404```python405# Compose poses (pos1/quat1 then pos2/quat2)406mujoco.mju_mulPose(pos_res, quat_res, pos1, quat1, pos2, quat2)407408# Invert pose409mujoco.mju_negPose(pos_res, quat_res, pos, quat)410411# Transform 3D point by pose412mujoco.mju_trnVecPose(res, pos, quat, vec)413```414415## 6. Energy & Diagnostics416417MuJoCo can continuously compute total mechanical energy to diagnose simulation418stability:419420```python421# Enable energy monitoring422model.opt.enableflags |= mujoco.mjtEnableBit.mjENBL_ENERGY423424mujoco.mj_step(model, data)425potential_energy = data.energy[0]426kinetic_energy = data.energy[1]427total_energy = potential_energy + kinetic_energy428```429430In passive, unforced, undamped systems, `total_energy` must remain constant.431Growing energy indicates numerical integration instability (requiring smaller432timesteps, or `implicitfast` if large damping or other velocity-dependent forces433are the cause). Before stiffening contacts to mask instability, inspect the434paused model at `t = 0` in Studio/`simulate` for initial penetrations,435visual/collision geom mismatches, concave collision meshes replaced by convex436hulls (`.. _coChecking:`), implausible CAD/URDF inertia boxes, and degree/radian437mismatches (`compiler/angle` defaults to `"degree"`). For priority-ordered438speed-fidelity tuning, diagnosing divergence, non-SI unit mistakes439(millimeter/gram meshes), island sleeping, speculative CCD, or fluid drag, read440[modeling.rst](../../modeling.rst) (`.. _CTuning:`, `.. _CTuningDefaults:`,441`.. _CTuningGlobal:`, `.. _CTuningModel:`),442[overview.rst](../../overview.rst) (`.. _Clarifications:`, `.. _Divergence:`,443`.. _Units:`, `.. _Soft:`),444[computation/index.rst](../../computation/index.rst) (`.. _Solver:`,445`.. _Sleeping:`), [programming/simulation.rst](../../programming/simulation.rst)446(`.. _siSleep:`), [computation/speculative.rst](../../computation/speculative.rst),447and [computation/fluid.rst](../../computation/fluid.rst).448449## 7. CPU Batching (`mujoco.batch` & `mujoco.rollout`), Optimization & Backends450451### Stateful Multi-Threaded CPU Batching (`mujoco.batch.Batch`)452453For vectorized RL stepping, closed-loop controllers, subset resets, and454per-simulation domain randomization on CPU across a native C++ thread pool (GIL455released, bit-identical to serial `MjData` stepping, and supporting all CPU456solvers/plugins), use `mujoco.batch.Batch` ([python.rst](../../python.rst),457`.. _PyBatch:`, wrapping C `mjb_*` in458[APIreference/functions.rst](../../APIreference/functions.rst),459`.. _Batchedsimulation:`):460461```python462from mujoco import batch463464# Pass persistent=True if the model uses sleep, IPC, or stateful plugins465b = batch.Batch(model, nsim=1024, nthread=8)466qpos, ctrl, xpos = b.bind('qpos'), b.bind('ctrl'), b.bind('xpos')467468# Named views slice (nsim, ...) and expand per-sim model fields469hinge_qpos = b.joint('hinge').qpos # (1024, 1)470b.body('pendulum').mass = per_sim_masses # Domain randomization471b.set_const() # Recompute derived model constants472473for _ in range(1000):474 ctrl[:] = policy(qpos, xpos)475 b.step() # Or b.step(ids=active_ids)476```477478### Stateless Trajectory Rollouts, Optimization & System ID479480- **Open-loop trajectory rollouts (`mujoco.rollout`)**: When rolling out fixed481 control sequences `(nbatch, nstep, ncontrol)` from `initial_state` in one482 call, use `mujoco.rollout.rollout` ([python.rst](../../python.rst),483 `.. _PyRollout:`, and `python/rollout.ipynb`) or `b.rollout(...)`.484- **Finite-difference derivatives & LQR (`mjd_transitionFD`)**: Compute485 linearized $A, B, C, D$ transition matrices with `mujoco.mjd_transitionFD`486 ([APIreference/functions.rst](../../APIreference/functions.rst),487 `.. _Derivatives-api:`, and `python/LQR.ipynb`).488- **Nonlinear least-squares & System ID (`mujoco.minimize`, `mujoco.sysid`)**:489 Use `mujoco.minimize.least_squares` ([python.rst](../../python.rst),490 `.. _PyMinimize:`, and `python/least_squares.ipynb`) for box-constrained QP491 optimization (`mju_boxQP`), and `mujoco.sysid` (`pip install mujoco[sysid]`;492 see [python.rst](../../python.rst), `.. _PySysid:`,493 [modeling.rst](../../modeling.rst), `.. _CTuningSysid:`,494 `python/mujoco/sysid/README.md`, and `python/mujoco/sysid/sysid.ipynb`) for495 fitting inertias, friction/damping, actuator gains, and delays to hardware496 logs over batched rollouts.497498### Compute Backend Comparison499500| Feature | C++ Engine (Default) | MJX (JAX) | MJWarp (CUDA) |501| :--- | :--- | :--- | :--- |502| **Import** | `import mujoco` (`mujoco.batch`, `mujoco.rollout`) | `from mujoco import mjx` | `import mujoco_warp as mjw` |503| **Primary Use** | Real-time control, interactive tools, CPU batch RL/MPC, full solver support | Differentiable physics, large batch RL | High-throughput batch rollouts |504| **Hardware** | CPU (single or multi-threaded) | GPU / TPU | NVIDIA GPU |505| **Precision** | float64 (or float32 with `-DmjUSESINGLE` / `--@mujoco//:single_precision`) | float32 | float32 |506| **Solvers** | Newton, CG, PGS, noslip | Newton, CG | Newton, CG |507| **Plugins** | All plugins | Not supported | SDF only |508509For GPU and TPU execution patterns (and RL frameworks like `mujoco_playground`510and `mjlab`), refer to [`mujoco-accelerated`](../accelerated/SKILL.md); for511cross-engine physics comparison, refer to [`mujoco-parity`](../parity/SKILL.md).512513## 8. Common Gotchas & Best Practices5145151. **Computed fields are read-only**: Fields like `data.xpos`, `data.xmat`, and516 `data.xquat` are output buffers. Never assign to them directly; change517 inputs (`data.qpos`, `data.ctrl`) and call `mj_forward()` or `mj_step()`.5182. **Duplicate names are forbidden**: Spec element names must be unique within519 each element type.5203. **Orientation keywords are mutually exclusive**: When adding geoms, bodies,521 or sites, provide only one of `quat`, `euler`, `axisangle`, `xyaxes`, or522 `zaxis`.5234. **Euler sequences**: Lowercase characters denote intrinsic rotations524 (`'xyz'`), uppercase denote extrinsic rotations (`'XYZ'`).5255. **Coordinate convention**: +Z is up, gravity is `[0, 0, -9.81]`.5266. **Repeating controls with `nstep`**: Calling `mj_step(model, data, nstep=N)`527 repeats the current control across `N` steps. For dynamic feedback control,528 step one timestep at a time.529530## 9. Key References531532### Documentation533534- [Python Bindings Reference](../../python.rst) (`.. _PyNotebook:`,535 `.. _PyStructs:`, `.. _PyNamed:`, `.. _PyModelEdit:`, `.. _PyMJCF:`,536 `.. _PyRollout:`, `.. _PyBatch:`, `.. _PyMinimize:`, `.. _PySysid:`)537- [Model Tuning & Pitfalls](../../modeling.rst) (`.. _CTuning:`,538 `.. _CTuningDefaults:`, `.. _CTuningGlobal:`, `.. _CTuningModel:`,539 `.. _CTuningSysid:`) and [Overview](../../overview.rst)540 (`.. _Clarifications:`, `.. _Divergence:`, `.. _Units:`,541 `.. _SurprisingCollisions:`, `.. _Soft:`)542- [Simulation Loop, Batching & Sleeping](../../programming/simulation.rst)543 (`.. _siSimulation:`, `.. _siStateControl:`, `.. _siForward:`,544 `.. _siBatch:`, `.. _siDiagnostics:`, `.. _siSleep:`)545- [Computation, Solvers & Integrators](../../computation/index.rst)546 (`.. _geIntegrators:`, `.. _geChoosingTimestepIntegrator:`, `.. _geState:`,547 `.. _Solver:`, `.. _Sleeping:`, `.. _Pipeline:`),548 [Speculative CCD](../../computation/speculative.rst), and549 [Fluid Dynamics](../../computation/fluid.rst)550- [MuJoCo Menagerie Robot Gallery](../../models.rst) (`.. _Menagerie:`) and551 [MJCF Sensor & Option Reference](../../XMLreference.rst)552 (`.. _sensor-contact:`, `.. _sensor-touch:`, `.. _option-flag:`,553 `.. _keyframe:`)554- [C API Function Reference](../../APIreference/functions.rst)555 (`.. _Mainsimulation:`, `.. _Batchedsimulation:`, `.. _Derivatives-api:`,556 `.. _Quaternions:`, `.. _Poses:`; rendered online inside557 [`APIfunctions.rst`](../../APIreference/APIfunctions.rst)) and558 [C API Types & Structs](../../APIreference/APItypes.rst) (`.. _mjModel:`,559 `.. _mjData:`, `.. _mjtState:`)560561### Notebooks, Models & Ecosystem562563- **In-repo notebooks**: `python/tutorial.ipynb`, `python/mjspec.ipynb`,564 `python/rollout.ipynb`, `python/LQR.ipynb`, `python/least_squares.ipynb`,565 and `python/mujoco/sysid/sysid.ipynb`566- **Source & models**:567 [Python Bindings Tests](../../../python/mujoco/bindings_test.py),568 [Built-in Showcase Models](../../../model/humanoid/humanoid.xml),569 [C++ Samples](../../programming/samples.rst) (`.. _Sample:`), and570 [C API Header](../../../include/mujoco/mujoco.h)571- **Downstream control & RL repos**:572 [MuJoCo MPC (`mujoco_mpc`)](https://github.com/google-deepmind/mujoco_mpc),573 [`dm_control`](https://github.com/google-deepmind/dm_control),574 [MuJoCo Playground](https://github.com/google-deepmind/mujoco_playground),575 and [`mjlab`](https://github.com/mujocolab/mjlab)