Skip to main content

Lab 01-01: Setting Up Your MuJoCo Environment

Objectives​

  • Install MuJoCo and verify the installation
  • Load and visualize a simple robot model
  • Understand the MuJoCo simulation loop
  • Run your first physics simulation

Materials​

TypeNameVersionTier
softwarePython3.10+required
softwareMuJoCo3.0+required
softwareNumPy1.24+required
datahumanoid.xmlincludedrequired

Prerequisites​

  • Basic Python programming knowledge
  • Familiarity with command line operations

Instructions​

Step 1: Install MuJoCo​

MuJoCo is now free and open-source. Install it using pip:

# In your terminal or Jupyter notebook
!pip install mujoco

Verification: Run the following to verify installation:

import mujoco
print(f"MuJoCo version: {mujoco.__version__}")

Expected: Version 3.0.0 or higher displayed without errors.

Step 2: Load Your First Model​

MuJoCo uses XML files to define robot models. Let's load the built-in humanoid:

import mujoco
import numpy as np

# Load the humanoid model (built into MuJoCo)
model = mujoco.MjModel.from_xml_path(
mujoco.util.get_resource_path("humanoid/humanoid.xml")
)
data = mujoco.MjData(model)

# Examine model properties
print(f"Number of bodies: {model.nbody}")
print(f"Number of joints: {model.njnt}")
print(f"Number of actuators: {model.nu}")
print(f"Degrees of freedom: {model.nv}")

Verification: You should see output similar to:

Number of bodies: 14
Number of joints: 18
Number of actuators: 21
Degrees of freedom: 27

Troubleshooting: If you get a file not found error, ensure MuJoCo is properly installed.

Step 3: Understand the Simulation Loop​

MuJoCo simulations advance through discrete timesteps:

# Get simulation parameters
print(f"Timestep: {model.opt.timestep} seconds")
print(f"Simulation will run at {1/model.opt.timestep:.0f} Hz")

# Reset simulation to initial state
mujoco.mj_resetData(model, data)

# Run simulation for 1 second
simulation_time = 1.0
steps = int(simulation_time / model.opt.timestep)

for i in range(steps):
# Step the simulation forward
mujoco.mj_step(model, data)

```python
```python
if i % 100 == 0:
        print(f"Time: {data.time:.3f}s, Height: {data.qpos[2]:.3f}m")

Verification: The humanoid should fall under gravity. Height should decrease from ~1.3m toward 0. Expected: You see the height decreasing as simulation time increases.

Step 4: Visualize the Simulation​

Launch the interactive viewer to see your robot:

import mujoco.viewer

# Launch passive viewer (non-blocking)
with mujoco.viewer.launch_passive(model, data) as viewer:
# Run simulation with visualization
while viewer.is_running():
mujoco.mj_step(model, data)
viewer.sync()

Verification: A window should open showing the humanoid model. Expected: You can rotate the view with mouse, see the robot fall, and close the window.

Step 5: Apply Control Inputs​

Let's prevent the humanoid from falling by applying joint torques:

# Reset simulation
mujoco.mj_resetData(model, data)

# Simple standing controller - apply torques to maintain position
def simple_controller(model, data):
"""Apply proportional control to maintain initial pose."""
kp = 100 # Proportional gain

# Target is initial joint positions (all zeros for this model)
target = np.zeros(model.nu)

# Current joint positions (skip free joint - first 7 elements)
current = data.qpos[7:7+model.nu]

# Apply proportional control
data.ctrl[:] = kp * (target - current)

# Run with controller
with mujoco.viewer.launch_passive(model, data) as viewer:
```python
```python
while viewer.is_running() and data.time < 5.0:
        simple_controller(model, data)
mujoco.mj_step(model, data)
viewer.sync()

Verification: The humanoid should attempt to maintain its pose rather than immediately collapsing. Expected: While not perfect, the robot should show some resistance to falling.

Expected Outcomes​

By completing this lab, you should:

  1. Have a working MuJoCo installation
  2. Understand how to load and inspect robot models
  3. Know the basic simulation loop structure
  4. Be able to visualize simulations
  5. Understand how control inputs affect robot behavior

Rubric​

CriterionPointsExcellentSatisfactoryNeeds Improvement
Installation20MuJoCo installed, version verifiedInstalled with minor issuesUnable to install
Model Loading20All properties correctly displayedModel loads with warningsCannot load model
Simulation Loop25Loop runs correctly, understands timestepLoop runs but unclear on timingLoop fails
Visualization20Viewer works, can interact with sceneViewer opens but limited interactionViewer fails
Controller15Controller implemented and explainedController works but not understoodController fails

Total Points: 100

Extensions​

For additional challenge:

  1. Modify the humanoid: Edit the XML to change mass or joint limits
  2. Data logging: Record joint positions over time and plot them
  3. Different models: Load other MuJoCo models (ant, cheetah, etc.)

Common Errors​

ErrorCauseFix
ModuleNotFoundError: mujocoMuJoCo not installedRun pip install mujoco
GLFWErrorDisplay issuesSet MUJOCO_GL=egl environment variable
FileNotFoundErrorModel path wrongUse mujoco.util.get_resource_path()