State, actions, and sensors
This page describes direct CPU simulation using MujocoModel. Use the
First Robot tutorial for the complete control loop and live
viewer. Gymnasium observations and actions have their own layouts and
semantics, described in Environments.
Read the simulation state
A MujocoModel provides the compiled model as robot.model and the current
simulation data as robot.data. The compiled model determines all array
sizes and ordering.
| Field | Shape | Contents |
|---|---|---|
data.time |
Scalar | Simulated time in seconds. |
data.qpos |
(model.nq,) |
Generalized positions in compiled joint order. Slide joints use meters and hinge joints use radians. A free joint stores XYZ translation followed by a quaternion in WXYZ order. |
data.qvel |
(model.nv,) |
Generalized velocities in compiled degree-of-freedom order. Slide and hinge velocities use m/s and rad/s, respectively. A free joint stores three linear and three angular components. |
data.act |
(model.na,) |
Internal state of actuators with dynamics. For the generated integrated-velocity tendon actuators, the activation is the target tendon length in meters. |
data.ctrl |
(model.nu,) |
Current actuator inputs in compiled actuator order, including internal connector commands when present. |
Read time, qpos, qvel, and act together before computing an action.
Use .copy() to keep array values for a snapshot or log, since MuJoCo
updates its arrays in place. nq and nv can differ because a quaternion
uses four position entries and three angular velocity entries. Access a joint's
slice by name with data.joint(joint_name).qpos or .qvel. List the names
with [model.joint(i).name for i in range(model.njnt)].
For Cartesian positions, robot.get_node_position_matrix() returns one XYZ
row in meters per name in robot.node_names. The corresponding
robot.get_node_linear_velocity_matrix() has the same row order and shape
(len(robot.node_names), 3). Use
data.site(site_name).xpos.copy() to read a specific site's world position,
or robot.get_edge_length_dict() to read tendon lengths by name. In realistic
models, shared logical nodes can have multiple physical instances. See
Model Modes for that geometry.
Derived values such as Cartesian positions and sensors come from MuJoCo's
forward computation. Call mujoco.mj_forward(model, data) after editing state
arrays or when you need derived values evaluated at the newly integrated
state. This call updates the derived quantities without advancing time.
Apply one action vector
Build a one-dimensional NumPy array with shape
(len(robot.external_actuator_names),). Entry i goes to
robot.external_actuator_names[i], whose index in the full MuJoCo control
array is robot.external_actuator_ids[i]. For generated tendon actuators the
input is a target length rate in m/s. A positive command increases the
target length, a negative command decreases it, and zero holds the current
target. The actual tendon length responds through the servo and physics.
With robot, model, and data from the tutorial, one step looks like this:
# Hold every tendon target for this step. Replace these values with your commands.
action = np.zeros(len(robot.external_actuator_names), dtype=float)
limits = robot.get_external_ctrlrange() # (number of external actuators, 2)
robot.set_external_ctrl(np.clip(action, limits[:, 0], limits[:, 1]))
# Update internal connector hinge targets separately, then apply all controls.
robot.apply_angle_bisector_control()
mujoco.mj_step(model, data)
set_external_ctrl() writes just the external entries of data.ctrl. The
bisector controller writes internal hinge commands for realistic models.
robot.get_external_ctrl() reads the external command vector back in the same
order. For Gymnasium, use env.action_space.shape, the action space bounds,
and the selected environment's action semantics.
Read accelerometers
Realistic triangle models include a three-axis accelerometer at each generated
node site by default. Abstract models and routed models generated by the
package have no built-in accelerometers. Pass accelerometer_config=None to
omit sensors from a realistic triangle model, or pass an
AccelerometerConfig to configure fields such as the name prefix or delay.
import mujoco
import numpy as np
from mujoco_truss_gen import MujocoModel, get_mujoco_spec
robot = MujocoModel(get_mujoco_spec("octahedron", realistic=True))
model, data = robot.model, robot.data
# Collect all accelerometer names in compiled sensor order.
sensor_names = [
model.sensor(i).name
for i in range(model.nsensor)
if model.sensor_type[i] == mujoco.mjtSensor.mjSENS_ACCELEROMETER
]
# Run the forward computation so the readings match the current state.
mujoco.mj_forward(model, data)
acceleration = np.stack([data.sensor(name).data for name in sensor_names])
print(sensor_names[0], acceleration[0])
print(acceleration.shape)
The matrix has shape (number of accelerometers, 3). The realistic
octahedron above has 12 readings, one for each generated node site. Row i contains the
local X, Y, and Z readings in m/s² for sensor_names[i]. The sensor reports
proper acceleration, so a stationary sensor can register gravity's effect.
The axes follow the sensor's site frame. The default names are
accel_<site_name>, including suffixes for cloned node sites. Discover the
names from the compiled model so the code also works with a custom prefix.
If you configure a sensor delay, the reported sample follows that delay.
For a single reading to keep, use data.sensor(name).data.copy().
MuJoCo accelerometer reference
data.sensordata is the flat buffer of shape (model.nsensordata,) containing
all sensors. Use the named accessor or slice that buffer using
model.sensor_adr[i] as the start and model.sensor_dim[i] as the length.
Check whether the sensor list is empty before stacking readings if your
script accepts models without accelerometers.