myosuite.core.model_builder
Composable MJCF model builder using MuJoCo 3’s MjSpec API.
Warning
Experimental API — subject to change.
ModelBuilder is under active development and does not yet replicate all
features of the official MyoChallenge environment XML files. For production
training or evaluation against a challenge benchmark, load the environment
directly via its registered Gymnasium ID (e.g. make_env("myoChallengeBaodingP2-v1"))
or instantiate the environment class directly.
ModelBuilder is a lazy recipe — it records fragment attachments, prop bodies,
and MjSpec transforms without compiling until build() is called.
Current limitations
The following scene features are not supported natively and require an
apply_transform() escape hatch (or direct XML loading):
Tendons and spatial constraints (e.g. Baoding tracking tendons)
Sites (tracking markers, sensor attachment points)
Mocap bodies (static goal bins, opponent dummy, goal posts)
Non-freejoint object kinematics (slide/hinge joints on manipulated objects)
Multi-geom composite bodies (e.g. 12-capsule + 3-box die)
Cube-map / grid-layout textures (e.g. soccer ball, die faces)
Aerodynamic fluid coefficients (
fluidcoefon ping-pong ball)Mirrored body assembly (left arm in TableTennis)
Heightfield terrain (RunTrack, ChaseTag)
Contact filtering / exclusion pairs
Keyframes (initial pose snapshots)
Sensors (force, touch, accelerometer, …)
Alternatives
Direct XML loading — the recommended approach for full challenge parity:
import mujoco model = mujoco.MjModel.from_xml_path("path/to/scene.xml")
Gymnasium entry points — load a fully-configured challenge env:
from myosuite import make_env env = make_env("myoChallengeBaodingP2-v1")
apply_transform escape hatch — extend ModelBuilder scenes with any MjSpec feature not covered above:
def add_tendons(spec: mujoco.MjSpec) -> mujoco.MjSpec: # ... direct spec manipulation ... return spec model, spec = ModelBuilder().attach_fragment("hand").apply_transform(add_tendons).build()
Attributes
Classes
Composable MJCF model builder. |
|
Statistics of a |
Functions
|
Decorator to register a named model recipe. |
|
Let recipe name build its |
|
Return a registered recipe function by name. |
Return the names of all registered model recipes. |
|
|
Memoize a deterministic |
Drop the specs of every |
|
|
Build a model from a named recipe. |
Module Contents
- myosuite.core.model_builder.logger
- myosuite.core.model_builder.model_recipe(name)
Decorator to register a named model recipe.
- Parameters:
name (str) – Recipe identifier used in TaskConfig.model.
- Return type:
Example
>>> @model_recipe("elbow_standard") ... def _elbow(b): ... return b.attach_fragment("elbow")
- myosuite.core.model_builder.register_spec_recipe(name, spec_fn)
Let recipe name build its
MjSpecwith spec_fn instead of aModelBuilder.For models compiled outside the builder (MuscleMimic full body); the name must be registered with
model_recipe()too, so it is listed.- Parameters:
name (str)
spec_fn (collections.abc.Callable[[], mujoco.MjSpec])
- Return type:
None
- myosuite.core.model_builder.get_recipe(name)
Return a registered recipe function by name.
- class myosuite.core.model_builder.ModelBuilder
Composable MJCF model builder.
Warning
Experimental. See module docstring for the full list of unsupported scene features and recommended alternatives for production use.
Records fragment attachments and transform functions lazily. Every call to
build_spec()composes a fresh spec, whichbuild()compiles (nothing is cached here, since callers mutate the returned model and spec), and never modifies the seed or attached specs, so a builder can be built repeatedly.Positioning
Use
place_fragment()to attach a body-part at an explicit position and orientation in the scene. Useadd_free_body()to add a free-floating prop (sphere, box, cylinder, …) at a given pose. Useadd_mesh_body()to add a free-floating body with a mesh and optional texture. For anything else,apply_transform()gives direct access to the compiledmujoco.MjSpec.Examples
>>> # Attach elbow at origin (default) >>> model, spec = ModelBuilder().attach_fragment("elbow").build()
>>> # Place hand 0.5 m above the origin, rotated 90° around Z >>> import numpy as np >>> model, spec = ( ... ModelBuilder() ... .place_fragment("hand", pos=[0, 0, 0.5], quat=[0.707, 0, 0, 0.707]) ... .build() ... )
>>> # Add a red sphere prop at (0.3, 0, 0.1) >>> model, spec = ( ... ModelBuilder() ... .attach_fragment("hand") ... .add_free_body("target_ball", pos=[0.3, 0, 0.1], ... geom_type=mujoco.mjtGeom.mjGEOM_SPHERE, ... geom_size=[0.02, 0, 0], rgba=[1, 0, 0, 1]) ... .build() ... )
>>> # Add a mesh object with texture >>> model, spec = ( ... ModelBuilder() ... .attach_fragment("hand") ... .add_mesh_body("ball", mesh_file="/path/to/ball.obj", ... pos=[0.3, 0, 0.1], texture_file="/path/to/ball.png") ... .build() ... )
- classmethod from_xml_file(path)
Create a builder seeded from an existing MJCF XML file.
Use this when the model cannot be expressed as a composition of registered fragments — e.g. when loading a complete monolithic XML and then applying surgical spec mutations via
apply_transform().Chaining example:
model, spec = ( ModelBuilder.from_xml_file("myoarm.xml") .apply_transform(edit_fn_arm_reaching) .build() )
- Parameters:
path (str | pathlib.Path) – Absolute or relative path to the MJCF XML file.
- Returns:
A new
ModelBuilderinstance with path as its seed.- Return type:
- classmethod from_xml_string(xml, *, include=None)
Create a builder seeded from an in-memory MJCF string.
- Parameters:
- Returns:
A new
ModelBuilderinstance with the string as its seed.- Return type:
- classmethod from_spec(spec)
Create a builder seeded from a pre-built
MjSpec.- Parameters:
spec (mujoco.MjSpec) – Fully constructed MuJoCo model specification.
- Returns:
A new
ModelBuilderinstance with spec as its seed.- Return type:
- attach_fragment(name, parent='worldbody')
Append a body-part XML fragment at the parent body’s origin.
To control placement, use
place_fragment()instead.- Parameters:
- Returns:
Self, for method chaining.
- Return type:
- attach_spec(spec, name='<inline>', parent='worldbody')
Attach a pre-built MjSpec fragment directly, bypassing file resolution.
Use this when the fragment is composed programmatically rather than loaded from a static XML file — for example, a hand pruned from the full arm via
myo_sim.build.compose.build_right_hand_from_arm_spec().- Parameters:
- Returns:
Self, for method chaining.
- Return type:
Example
>>> from myo_sim.build.compose import build_right_hand_from_arm_spec >>> model, spec = ModelBuilder().attach_spec( ... build_right_hand_from_arm_spec(), name="hand" ... ).build()
- attach_kinematics(name, parent='worldbody')
Attach the kinematics-only component of a body part (Issue #75 API).
Resolves to
kinematics/<name>/body.xmlin the myo_sim Issue #75 directory layout (bodies, joints, and global sites only — no muscles or tendons). Falls back transparently to the full<name>fragment when the new structure is not yet present in the submodule.- Parameters:
- Returns:
Self, for method chaining.
- Return type:
- attach_part(name, parent='worldbody')
Attach the actuation component of a body part (Issue #75 API).
Resolves to
parts/<name>/muscles.xmlin the myo_sim Issue #75 directory layout (muscles, tendons, wrapping surfaces, and local sites). Falls back transparently to the full<name>fragment when the new structure is not yet present in the submodule.- Parameters:
- Returns:
Self, for method chaining.
- Return type:
- place_fragment(name, pos=(0.0, 0.0, 0.0), quat=(1.0, 0.0, 0.0, 0.0), parent='worldbody')
Attach a fragment at an explicit position and orientation.
The position and quaternion are relative to the parent body frame. The quaternion is in MJCF convention:
[w, x, y, z].- Parameters:
name (str) – Fragment identifier (same as
attach_fragment()).pos (_FloatVec3) – 3-vector
[x, y, z]offset from the parent origin (metres).quat (_FloatVec4) – 4-vector
[w, x, y, z]orientation quaternion.parent (str) – Name of the parent body to attach to.
- Returns:
Self, for method chaining.
- Return type:
Example
>>> import numpy as np >>> builder = ( ... ModelBuilder() ... .place_fragment("elbow", pos=[0, 0, 0]) ... .place_fragment("hand", pos=[0, 0, -0.35], parent="elbow_distal") ... )
- add_free_body(name, pos=(0.0, 0.0, 0.0), quat=(1.0, 0.0, 0.0, 0.0), geom_type=mujoco.mjtGeom.mjGEOM_SPHERE, geom_size=(0.02, 0.0, 0.0), rgba=(0.8, 0.8, 0.2, 1.0), mass=None, condim=3)
Add a free-floating prop body (sphere, box, cylinder, …) to the scene.
The body gets a freejoint so it is fully unconstrained at episode start. Set its initial position at runtime via
data.qpos[joint_addr:joint_addr+7].- Parameters:
name (str) – Unique body name (also used as geom name and freejoint name).
pos (_FloatVec3) – Initial world-frame position
[x, y, z](metres).quat (_FloatVec4) – Initial orientation quaternion
[w, x, y, z].geom_type (int) – MuJoCo geom type constant (default: sphere). Use
mujoco.mjtGeom.mjGEOM_BOX,mujoco.mjtGeom.mjGEOM_CYLINDER, etc.geom_size (_FloatVec3) – Geom size parameters — meaning depends on geom_type: sphere
[radius, 0, 0]; box[half-x, half-y, half-z]; cylinder[radius, half-height, 0].rgba (_FloatVec4) – Colour and opacity
[r, g, b, a].mass (float | None) – Body mass in kg.
Nonelets MuJoCo infer from density.condim (int) – Contact dimensionality (1, 3, 4, or 6). Use 4 for objects that require torsional friction (e.g. rolling balls).
- Returns:
Self, for method chaining.
- Return type:
Example
>>> import mujoco >>> builder = ( ... ModelBuilder() ... .attach_fragment("hand") ... .add_free_body("red_ball", pos=[0.3, 0.0, 0.1], ... geom_type=mujoco.mjtGeom.mjGEOM_SPHERE, ... geom_size=[0.02, 0, 0], rgba=[1, 0, 0, 1], ... mass=0.0027, condim=4) ... .add_free_body("blue_box", pos=[0.0, 0.2, 0.05], ... geom_type=mujoco.mjtGeom.mjGEOM_BOX, ... geom_size=[0.03, 0.03, 0.03], rgba=[0, 0, 1, 1]) ... )
- add_mesh_body(name, mesh_file, pos=(0.0, 0.0, 0.0), quat=(1.0, 0.0, 0.0, 0.0), scale=(1.0, 1.0, 1.0), texture_file=None, rgba=(0.8, 0.8, 0.8, 1.0), material_shininess=0.5, material_specular=0.3)
Add a free-floating body with a mesh geom and optional texture.
The mesh file is loaded from disk at build time. If texture_file is provided, a texture + material are created and applied to the geom; otherwise rgba is used as a flat colour.
- Parameters:
name (str) – Unique body name (also used as a prefix for the mesh, texture, material, and freejoint names).
mesh_file (str | pathlib.Path) – Path to the
.obj(or other MuJoCo-supported) mesh file.pos (_FloatVec3) – Initial world-frame position
[x, y, z](metres).quat (_FloatVec4) – Initial orientation quaternion
[w, x, y, z].scale (_FloatVec3) – Mesh scale factors
[sx, sy, sz]applied at load time.texture_file (str | pathlib.Path | None) – Optional path to a texture image (PNG, JPG, …). When
None, the geom is rendered with rgba only.rgba (_FloatVec4) – Flat colour and opacity
[r, g, b, a]. Used as the geom colour when no texture is provided, or as the material base colour when a texture is provided.material_shininess (float) – Shininess of the generated material (0–1).
material_specular (float) – Specular intensity of the generated material (0–1).
- Returns:
Self, for method chaining.
- Raises:
FileNotFoundError – If mesh_file or texture_file does not exist.
- Return type:
Example
>>> builder = ( ... ModelBuilder() ... .attach_fragment("hand") ... .add_mesh_body( ... "ping_pong_ball", ... mesh_file="/path/to/ball.obj", ... pos=[0.3, 0.0, 0.1], ... texture_file="/path/to/ball.png", ... ) ... )
- apply_transform(fn)
Register an arbitrary MjSpec transform.
- Parameters:
fn (collections.abc.Callable[[mujoco.MjSpec], mujoco.MjSpec]) – Callable that receives and returns a MjSpec.
- Returns:
Self, for method chaining.
- Return type:
- set_timestep(dt)
Set the simulation timestep.
Applied after all transforms, so it overrides the seed XML’s
<option timestep>.- Parameters:
dt (float) – Simulation timestep in seconds.
- Returns:
Self, for method chaining.
- Return type:
- disable_cylinder_contacts()
Disable contacts on cylindrical geoms (reduces simulation stiffness).
Applied after all transforms: every cylinder geom of the built model gets
contype = conaffinity = 0.- Returns:
Self, for method chaining.
- Return type:
- apply_sarcopenia(force_scale=0.5)
Scale muscle peak forces to simulate sarcopenia.
- Parameters:
force_scale (float) – Fraction of original peak force to retain (0–1).
- Returns:
Self, for method chaining.
- Return type:
- build()
Compose a fresh spec (see
build_spec()) and compile it into a MjModel.- Returns:
Tuple of (MjModel, MjSpec). The spec is new on every call (a copy for
from_spec()seeds).- Raises:
FileNotFoundError – If a fragment XML cannot be resolved.
KeyError – If a named parent body does not exist in the spec.
- Return type:
tuple[mujoco.MjModel, mujoco.MjSpec]
- build_spec()
Compose a fresh spec from the seed, fragments, props, transforms and options.
- Returns:
The uncompiled MjSpec, new on every call.
- Raises:
FileNotFoundError – If a fragment XML cannot be resolved.
KeyError – If a named parent body does not exist in the spec.
- Return type:
mujoco.MjSpec
- myosuite.core.model_builder.list_recipes()
Return the names of all registered model recipes.
Example
>>> from myosuite.core.model_builder import list_recipes >>> "elbow_standard" in list_recipes() True
- class myosuite.core.model_builder.SpecCacheInfo
Bases:
NamedTupleStatistics of a
cached_spec()builder (currsize: specs kept).
- myosuite.core.model_builder.cached_spec(maxsize=32, min_uses=2)
Memoize a deterministic
MjSpecbuilder.The builder’s arguments must capture every input that changes the spec it builds. A spec is kept from the min_uses-th build of its arguments on, so with the default of 2 a process that builds a model once (e.g. a vector-env worker making one env) keeps nothing, and one that builds it repeatedly (tests, in-process vector envs, train and eval envs) builds it twice. Every call returns a private spec that callers may edit and compile freely: the fresh build until the spec is kept, a
mujoco.MjSpec.copy()after. The cache is process-local; calls with unhashable arguments build without it, and setting the environment variableMYOSUITE_SPEC_CACHE=0disables it.- Parameters:
- Returns:
Decorator; the wrapped builder exposes
cache_infoandcache_clear.- Return type:
collections.abc.Callable[[collections.abc.Callable[…, mujoco.MjSpec]], collections.abc.Callable[…, mujoco.MjSpec]]
Example
>>> @cached_spec() ... def _scene(path: str) -> mujoco.MjSpec: ... return mujoco.MjSpec.from_file(path)
- myosuite.core.model_builder.clear_spec_caches()
Drop the specs of every
cached_spec()builder, freeing their memory.- Return type:
None
- myosuite.core.model_builder.build_from_recipe(name, edit_fn=None, **kwargs)
Build a model from a named recipe.
From its second build in a process (same recipe, edit, working directory and kwargs), the spec is kept and every call compiles a private copy of it (see
cached_spec()).- Parameters:
name (str) – Recipe name registered via @model_recipe.
edit_fn (collections.abc.Callable[[mujoco.MjSpec], None] | None) – In-place edit of the compiled recipe spec, e.g. the
edit_fnkwarg of an env; built and cached with the recipe.**kwargs (Any) – Unused; reserved for future recipe parameterisation.
- Returns:
Tuple of (MjModel, MjSpec).
- Return type:
tuple[mujoco.MjModel, mujoco.MjSpec]
Example
>>> model, spec = build_from_recipe("elbow_standard")