> For the complete documentation index, see [llms.txt](https://doc.ancorasir.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://doc.ancorasir.com/2026spring/robot-description-basics/class-03-mujoco-for-robots.md).

# Class 03: MuJoCo for Robots

Contact makes robot simulation difficult. Free motion follows smooth rigid-body dynamics, but contact introduces unilateral constraints, friction, impacts, changing contact sets, and numerical stiffness. Humanoid locomotion compounds all of these: many bodies may contact at once, the base is unactuated, and small force errors can become large balance errors.

This chapter develops the contact problem from rigid complementarity to MuJoCo's convex soft-constraint model. It then connects the mathematics to `solref` and `solimp` in MJCF and finishes with a reproducible foot-drop experiment in Python.

> **Learning objectives.** By the end of this class, you should be able to write the unilateral contact conditions, explain why frictional hard-contact models are challenging, interpret MuJoCo's formulation through Gauss's principle of least constraint, tune `solref` and `solimp` systematically, and inspect contact forces from the Python API.

### Contents

1. [Why contact is the hard part](#id-1.-why-contact-is-the-hard-part)
2. [Rigid unilateral contact and complementarity](#id-2.-rigid-unilateral-contact-and-complementarity)
3. [Why strict frictional contact is difficult](#id-3.-why-strict-frictional-contact-is-difficult)
4. [MuJoCo's soft convex contact model](#id-4.-mujocos-soft-convex-contact-model)
5. [Gauss's principle and the optimization view](#id-5.-gausss-principle-and-the-optimization-view)
6. [From mathematics to MJCF parameters](#id-6.-from-mathematics-to-mjcf-parameters)
7. [Lab: drop a foot and inspect contact forces](#id-7.-lab-drop-a-foot-and-inspect-contact-forces)
8. [A disciplined tuning workflow](#id-8.-a-disciplined-tuning-workflow)
9. [What the model does and does not guarantee](#id-9.-what-the-model-does-and-does-not-guarantee)
10. [Review questions](#id-10.-review-questions)
11. [References and further reading](#id-11.-references-and-further-reading)

***

### 1. Why contact is the hard part

Away from contact, an articulated system can be written

$$
\mathbf M(q)\dot v + \mathbf c(q,v) = \tau,
$$

where $$q$$ is configuration, $$v$$ is generalized velocity, $$\mathbf M$$ is the joint-space inertia matrix, $$\mathbf c$$ contains bias forces, and $$\tau$$ collects applied forces.

The unconstrained acceleration is

$$
\dot v\_{\text{unc}}
\= \mathbf M(q)^{-1}\big(\tau-\mathbf c(q,v)\big).
$$

Contact changes the equation to

$$
\mathbf M(q)\dot v + \mathbf c(q,v)
\= \tau + \mathbf J(q)^\top f,
$$

where $$\mathbf J$$ maps generalized motion into constraint coordinates and $$f$$ contains contact and other constraint forces.

The difficult part is not inserting $$\mathbf J^\top f$$. It is determining $$f$$ while respecting:

* non-penetration;
* repulsive normal force;
* friction-cone bounds;
* changing contact sets;
* equality constraints, joint limits, and tendon limits;
* finite computation time and numerical precision.

In a humanoid, the result must also remain consistent across feet, hands, knees, objects, and the floating base.

***

### 2. Rigid unilateral contact and complementarity

#### 2.1 Signed gap and normal force

Let $$\phi(q)$$ be the signed normal gap between two candidate contact surfaces:

* $$\phi(q)>0$$: separated;
* $$\phi(q)=0$$: touching;
* $$\phi(q)<0$$: interpenetrating.

Let $$\lambda\_n$$ be the normal contact force. Ideal rigid unilateral contact is expressed by the Signorini conditions,

$$
\phi(q)\ge 0,
\qquad
\lambda\_n\ge 0,
\qquad
\phi(q)\lambda\_n=0.
$$

The first inequality forbids penetration. The second allows contact to push but not pull. The product condition says that a positive normal force is possible only at zero gap, while separated bodies have zero normal force.

<figure><img src="/files/rDOLg1snu8o4W1iKsXGT" alt=""><figcaption></figcaption></figure>

*Figure 1. In the ideal hard-contact model, gap and normal force cannot both be positive.*

This is a **complementarity** condition: at least one of the paired variables must be zero. It naturally represents the switching between separated and contacting modes without requiring a separate equation for each mode.

#### 2.2 Acceleration-space form

For active constraints, acceleration in constraint coordinates is

$$
a\_c = \mathbf J\dot v + \dot{\mathbf J}v.
$$

Substitute the equations of motion:

$$
a\_c
\= \underbrace{\mathbf J\mathbf M^{-1}(\tau-\mathbf c)+\dot{\mathbf J}v}\_{a\_u}

* \underbrace{\mathbf J\mathbf M^{-1}\mathbf J^\top}\_{\mathbf A} f.
  $$

Here:

* $$a\_u$$ is unconstrained acceleration in constraint space;
* $$\mathbf A$$ is inverse inertia in constraint space;
* $$f$$ is the force selected by the contact solver.

This projected equation makes contact coupling visible. A force at one foot can alter acceleration at the other foot because the two constraints share generalized coordinates through $$\mathbf M^{-1}$$.

#### 2.3 Friction cones

For a conventional three-dimensional point contact, tangential force is bounded by Coulomb friction,

$$
\lVert f\_t\rVert\_2 \le \mu f\_n,
\qquad f\_n\ge 0.
$$

The admissible forces form a cone. Some solvers use the elliptic cone directly; others approximate it by a pyramid to obtain linear inequalities. MuJoCo supports both elliptic and pyramidal friction cones, depending on solver and model settings.

Contact dimensionality matters. A frictionless point needs only the normal direction. A regular frictional contact adds two tangential directions. Additional dimensions can model torsional and rolling friction.

***

### 3. Why strict frictional contact is difficult

#### 3.1 Hard contact is an idealization

Perfect rigidity creates discontinuous mode changes: force appears at the instant gap becomes zero, while penetration is forbidden. Real feet, floors, soles, skins, and structures deform. The deformation may be tiny relative to robot size but significant for contact force and numerical conditioning.

#### 3.2 Painlevé-type inconsistency and indeterminacy

Rigid bodies with Coulomb friction can admit configurations in which the classical continuous-time model has no solution or multiple solutions. This family of difficulties is associated with the Painlevé paradox. The problem is not simply a bad implementation; it can arise from the assumptions of perfectly rigid contact and idealized friction.

#### 3.3 Frictional complementarity is computationally hard

Frictional LCP/NCP formulations are difficult in the worst case. Practical engines therefore use approximations, iterative methods, warm starts, regularization, or velocity-stepping schemes. “NP-hard” is a worst-case complexity statement, not proof that every robot contact problem is slow, but it explains why solver design and approximation matter.

#### 3.4 Early termination has physical symptoms

An iterative solver must stop after finite work. Poor convergence may appear as:

* visible contact jitter;
* artificial energy injection;
* slow constraint drift;
* excessive slip;
* dependence on body ordering or solver iterations;
* different results after a small change in time step.

These symptoms should not automatically be “fixed” with more damping. First determine whether the model, contact geometry, time step, and solver are internally consistent.

***

### 4. MuJoCo's soft convex contact model

MuJoCo takes a different modeling position: both hard complementarity and soft convex contact are approximations to physical reality. It drops strict complementarity in frictional contact, permits controlled softness, and formulates constraint resolution as a convex optimization problem.

<figure><img src="/files/h54rrAD9OOAHUt2S66ef" alt=""><figcaption></figcaption></figure>

*Figure 2. Softness regularizes contact and makes the constraint model tunable to different materials and tasks.*

Three distinctions are important.

1. **Soft does not mean unconstrained.** Contact forces still lie in admissible sets such as friction cones.
2. **The model is not merely a standalone spring force.** Applied force, inertia, coupling, and all active constraints participate in one solve.
3. **Penetration is a modeled deformation coordinate.** Small residuals allow finite stiffness and damping, rather than an infinitely rigid interface.

The model's optimization structure supports a unique inverse-dynamics solution for finite softness and provides efficient forward solvers. This is valuable for control, estimation, system identification, and optimization in contact-rich systems.

***

### 5. Gauss's principle and the optimization view

#### 5.1 Least change from unconstrained acceleration

Gauss's principle of least constraint states, in a basic equality-constrained form, that the constrained acceleration is the feasible acceleration closest to the unconstrained one in the mass metric:

$$
\dot v
\= \arg\min\_x
\left\lVert x-\dot v\_{\text{unc}}\right\rVert\_{\mathbf M}^2
\quad \text{subject to}\quad
\mathbf Jx=a\_r,
$$

where

$$
\lVert z\rVert\_{\mathbf M}^2=z^\top\mathbf M z
$$

and $$a\_r$$ is a reference acceleration in constraint space.

<figure><img src="/files/ERxyKLqkp3Wb23le7sPv" alt=""><figcaption></figcaption></figure>

*Figure 3. Inertia determines how deviations from unconstrained acceleration are measured.*

This gives an intuitive picture: constraints alter the motion only as much as necessary, with “as much” measured in a physically meaningful metric.

#### 5.2 Contact-space coupling

The contact acceleration relation

$$
a\_c = a\_u + \mathbf A f,
\qquad
\mathbf A=\mathbf J\mathbf M^{-1}\mathbf J^\top
$$

projects Newton's law into constraint coordinates.

<figure><img src="/files/eHAm3d9Uf6cwepDpZ8sk" alt=""><figcaption></figcaption></figure>

*Figure 4. The contact Jacobian connects generalized motion to normal, frictional, and other constraint directions.*

The matrix $$\mathbf A$$ is positive semidefinite and describes how constraint forces produce constraint accelerations. Off-diagonal terms encode coupling among contacts.

#### 5.3 Adding softness

MuJoCo introduces a positive diagonal regularizer $$\mathbf R$$ and a reference acceleration $$a\_r$$. In the official formulation, the dual forward-contact problem can be written

$$
f
\= \arg\min\_{\lambda\in\Omega}
\frac{1}{2}\lambda^\top(\mathbf A+\mathbf R)\lambda

* \lambda^\top(a\_u-a\_r),
  $$

where $$\Omega$$ is the admissible set for equality, friction-loss, limit, and contact forces. For contact rows, it includes the selected friction cone.

Because $$\mathbf R$$ is positive definite by construction, the quadratic objective is strictly convex. The exact solver path depends on the friction cone and solver choices, but the optimization problem has a well-defined global minimizer.

The reference acceleration has spring-damper form for each scalar constraint,

$$
(a\_r)\_i = -b\_i(\mathbf Jv)\_i-k\_i r\_i,
$$

where $$r\_i$$ is the constraint residual, $$b\_i$$ is damping, and $$k\_i$$ is stiffness. For friction directions without a position residual, the reference is damping-only.

<figure><img src="/files/g5RZaVKwkfuwMXMA8s7N" alt=""><figcaption></figcaption></figure>

*Figure 5. The lecture's acceleration-space picture emphasizes the combination of inertial motion and regularized contact; MuJoCo's documentation gives the full primal and dual forms.*

#### 5.4 Hard and soft limits

The regularizer interpolates between unconstrained and reference accelerations. MuJoCo defines an impedance $$0\<d<1$$ and computes, conceptually,

$$
R\_{ii}=\frac{1-d\_i}{d\_i}\widehat A\_{ii}.
$$

Thus:

* $$d\rightarrow 1$$ gives a stronger, phenomenologically harder constraint and smaller $$R$$;
* $$d\rightarrow 0$$ gives a weaker constraint and larger $$R$$.

The exact hard limit $$R=0$$ is not allowed by the soft model, but constraints can be made practically stiff. This direction is worth remembering because “large penalty” intuition can otherwise lead to the wrong interpretation of $$R$$.

#### 5.5 Why optimization and control benefit

The convex formulation offers:

* a single coupled solution for active constraints;
* a unique inverse for finite softness;
* efficient Newton, conjugate-gradient, and projected Gauss-Seidel solver options;
* analytical structure useful in inverse dynamics and optimization;
* tunable contact profiles for different materials.

It does not make the entire simulator globally smooth. Collision detection, contact activation, discrete model changes, and some geometry transitions can still introduce nonsmooth behavior. The useful claim is narrower: the soft constraint model and its reduced cost have strong convexity and differentiability properties that hard step-like contact lacks.

***

### 6. From mathematics to MJCF parameters

MuJoCo exposes constraint behavior primarily through `solref` and `solimp`. They can be specified in defaults and overridden for individual geoms or constraints.

#### 6.1 `solref`: reference acceleration dynamics

With two positive values,

```xml
solref="timeconst dampratio"
```

the parameters describe an approximate second-order response:

* `timeconst` controls how quickly constraint error is corrected;
* `dampratio` controls damping relative to critical damping.

Smaller time constants generally produce stiffer, faster contact but demand more from the time step and solver. A damping ratio near `1` is a sensible starting point for non-oscillatory response.

<figure><img src="/files/QwJ8BaZI6KZa8mIRcl8b" alt=""><figcaption></figcaption></figure>

*Figure 6. The spring-damper analogy is useful for tuning trends. The effective physical stiffness also depends on impedance and constraint-space inertia, so the displayed scalar conversion should not be treated as a universal material constant.*

Negative `solref` values select a direct stiffness-damping format in the official modeling syntax. Do not mix the two interpretations.

#### 6.2 `solimp`: position-dependent impedance

```xml
solimp="d0 d_width width midpoint power"
```

defines how impedance varies with constraint violation. Conceptually:

* `d0` is impedance near zero residual;
* `d_width` is impedance at the specified `width`;
* `midpoint` and `power` shape the smooth interpolation.

<figure><img src="/files/3QmyURdDuA4b5qF2oQ5T" alt=""><figcaption></figcaption></figure>

*Figure 7. Position-dependent impedance can make initial contact compliant and increase constraint strength as deformation increases.*

Impedance values are clamped inside the open interval $$(0,1)$$. Values closer to one produce stronger constraints. The `width` is expressed in the relevant residual units - meters for a normal contact distance.

#### 6.3 Friction and contact dimension

For a geom,

```xml
friction="sliding torsional rolling"
```

sets friction coefficients used when contacts are combined. `condim` selects the number of active contact-force dimensions:

* `1`: normal force only;
* `3`: normal plus two tangential directions;
* `4`: add torsional friction;
* `6`: add two rolling-friction directions.

Use extra dimensions only when the physical question requires them. They change both the model's behavior and the solver's work.

#### 6.4 Time step and integrator are part of contact tuning

A contact model cannot be tuned independently of numerical integration. If constraint correction is much faster than the simulation time step, the discrete system may be poorly resolved. When contact is unstable, test a smaller time step before changing many physical parameters at once.

***

### 7. Lab: drop a foot and inspect contact forces

The following experiment isolates a single body and a single plane. That simplicity is deliberate: it makes penetration, rebound, and contact force easy to interpret before the same parameters are used on a humanoid.

#### 7.1 MJCF model

```xml
<mujoco model="humanoid_foot_contact_tuning">
  <option timestep="0.002"
          integrator="implicitfast"
          gravity="0 0 -9.81"/>

  <default>
    <geom solref="0.015 1.0"
          solimp="0.9 0.99 0.001 0.5 2"
          friction="1.0 0.05 0.0001"/>
  </default>

  <worldbody>
    <geom name="floor"
          type="plane"
          size="5 5 0.1"
          rgba="0.8 0.9 0.8 1"/>

    <body name="right_foot" pos="0 0 0.5">
      <freejoint name="foot_root"/>
      <geom name="foot_geometry"
            type="box"
            size="0.12 0.06 0.02"
            mass="1.5"
            condim="4"
            rgba="0.8 0.2 0.2 1"/>
    </body>
  </worldbody>
</mujoco>
```

<figure><img src="/files/yORY7b8LbkG3Q5eUgxmB" alt=""><figcaption></figcaption></figure>

*Figure 8. A minimal model isolates the variables involved in contact tuning.*

The `freejoint` contributes six velocity degrees of freedom and seven position coordinates because orientation is stored as a quaternion. The foot begins 0.5 m above the world origin. Its half-height is 0.02 m, so contact should occur when the body center approaches that height.

#### 7.2 Python evaluation script

Save the XML as `foot_drop.xml`, install the official `mujoco` Python package, and run:

```python
from pathlib import Path

import mujoco
import numpy as np


model = mujoco.MjModel.from_xml_path(str(Path("foot_drop.xml")))
data = mujoco.MjData(model)

print(
    f"{'time':>7}  {'z':>9}  {'normal':>12}  "
    f"{'tangent':>12}  {'contacts':>8}"
)

while data.time < 0.7:
    mujoco.mj_step(model, data)

    normal_force = 0.0
    tangential_force = 0.0

    for contact_id in range(data.ncon):
        wrench = np.zeros(6, dtype=np.float64)
        mujoco.mj_contactForce(model, data, contact_id, wrench)
        normal_force += wrench[0]
        tangential_force += np.linalg.norm(wrench[1:3])

    if int(round(data.time / model.opt.timestep)) % 10 == 0:
        print(
            f"{data.time:7.3f}  {data.qpos[2]:9.5f}  "
            f"{normal_force:12.4f}  {tangential_force:12.4f}  "
            f"{data.ncon:8d}"
        )
```

<figure><img src="/files/tm7jBmonZZl1dpTgLvcY" alt=""><figcaption></figcaption></figure>

*Figure 9. Contact forces are returned in the contact frame; the first component is normal force and subsequent active components depend on `condim`.*

#### 7.3 What to measure

Do not judge tuning only from whether the animation “looks stable.” Record quantitative signals:

* maximum penetration;
* peak normal force;
* time from first contact to rest;
* rebound height;
* steady-state body height;
* residual vertical velocity;
* solver iterations and convergence statistics;
* sensitivity to time step.

For this vertical, centered drop, tangential force should remain near zero. A large tangential force suggests asymmetry, rotation, or a modeling mistake.

#### 7.4 Controlled experiments

Change one factor at a time.

1. **Time constant sweep:** try `0.03`, `0.015`, and `0.0075` with constant damping ratio.
2. **Damping sweep:** compare underdamped, near-critical, and overdamped values.
3. **Impedance sweep:** vary `d0` and `d_width` while keeping the same width.
4. **Drop-height sweep:** test whether parameters remain stable at larger impact velocity.
5. **Time-step sweep:** halve the step and see whether conclusions remain similar.
6. **Mass sweep:** check whether the contact profile remains acceptable for a heavier body.

Plot force and penetration against time. The “best” parameters depend on the real material, task bandwidth, and acceptable computation cost.

***

### 8. A disciplined tuning workflow

#### Step 1: validate geometry and mass

Confirm body size, contact orientation, mass, inertia, and initial pose. Tuning cannot repair a foot that begins inside the floor or has a 1000× unit error.

#### Step 2: choose the simplest relevant contact

Start with `condim="1"` for a normal drop if friction is not yet under study. Add tangential, torsional, or rolling dimensions deliberately.

#### Step 3: establish a stable numerical baseline

Use a conservative time step, a suitable integrator, and sufficient solver iterations. Save this baseline before optimizing speed.

#### Step 4: tune correction speed and damping

Adjust `solref` to obtain acceptable penetration and decay without oscillation. Avoid extremely small time constants as a first response to every visible deformation.

#### Step 5: shape impedance with depth

Use `solimp` when the interface should be compliant at initial contact and stronger under larger deformation. Keep the width meaningful relative to geometry and measurement resolution.

#### Step 6: tune friction from targeted tests

Use incline, pull, or sliding tests instead of guessing coefficients from locomotion behavior. Friction should be identified separately from normal compliance when possible.

#### Step 7: scale up gradually

Move from one body to one foot, double support, a passive humanoid drop, and only then closed-loop locomotion. At each stage, preserve plots and parameter versions.

#### Step 8: validate against hardware

Compare force-time curves, deflection, rebound, and settling with real measurements. Contact tuning is a system-identification problem, not a visual styling exercise.

***

### 9. What the model does and does not guarantee

MuJoCo provides a precise and powerful contact model, but simulation remains a model.

#### The formulation gives you

* generalized-coordinate rigid-body dynamics;
* coupled optimization-based constraint forces;
* elliptic or pyramidal friction cones;
* tunable soft constraints;
* multiple forward solvers and analytical inverse structure;
* a model suitable for fast control and learning experiments.

#### It does not automatically give you

* correct geometry, mass, inertia, or actuator data;
* material parameters identified from hardware;
* deformation history, plasticity, tearing, or arbitrary continuum mechanics;
* guaranteed sim-to-real transfer;
* immunity to a poor time step, bad scaling, or under-converged solve;
* global smoothness through every contact creation or collision-geometry change.

The simulator's mathematical quality and the modeler's physical discipline are complementary. A robust solver applied to an incorrect robot or scene still produces the wrong experiment.

#### Key takeaways

1. Contact is unilateral and friction-limited; equality equations alone are insufficient.
2. Strict complementarity is elegant but creates modeling and computational difficulty for frictional rigid contact.
3. MuJoCo uses a convex soft-constraint formulation related to a generalized Gauss principle.
4. `solref` sets reference-response dynamics; `solimp` shapes constraint impedance.
5. Contact parameters, time step, solver, geometry, and mass must be tuned as one numerical-physical system.
6. Always validate with isolated experiments and quantitative signals before training a humanoid policy.

***

### 10. Review questions

1. What physical meanings do the three Signorini conditions encode?
2. Derive $$a\_c=a\_u+\mathbf A f$$ from the generalized equations of motion.
3. Why can two simultaneous contacts be coupled even if their geometries do not touch each other?
4. What modeling assumptions contribute to the Painlevé paradox?
5. In MuJoCo's formulation, what roles are played by $$\mathbf A$$, $$\mathbf R$$, and $$a\_r$$?
6. Why does $$d\rightarrow1$$ correspond to a stronger constraint?
7. How would you distinguish underdamped contact from insufficient solver convergence?
8. Design an experiment to identify foot-ground friction independently of normal compliance.
9. Why should a contact parameter set be retested after changing the simulation time step?

***

### 11. References and further reading

* MuJoCo documentation, [Computation](https://mujoco.readthedocs.io/en/latest/computation/) - soft contact model, primal/dual problems, solvers, and constraint parameters.
* MuJoCo documentation, [Modeling](https://mujoco.readthedocs.io/en/stable/modeling.html) - `solref`, `solimp`, friction, and modeling practice.
* MuJoCo documentation, [XML reference](https://mujoco.readthedocs.io/en/stable/XMLreference.html).
* Emanuel Todorov, [*Analytically-Invertible Dynamics with Contacts and Constraints: Theory and Implementation in MuJoCo*](https://doi.org/10.1109/ICRA.2014.6907751), ICRA 2014.
* David E. Stewart and Jeffrey C. Trinkle, [*An Implicit Time-Stepping Scheme for Rigid Body Dynamics with Inelastic Collisions and Coulomb Friction*](https://doi.org/10.1002/\(SICI\)1097-0207\(19960715\)39:15%3C2673::AID-NME972%3E3.0.CO;2-I), 1996.
* Google DeepMind, [MuJoCo source and tutorials](https://github.com/google-deepmind/mujoco).

***


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://doc.ancorasir.com/2026spring/robot-description-basics/class-03-mujoco-for-robots.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
