Skip to content

utils

Color

Bases: StrEnum

Contains color aliases and converters to go between the various color formats. The color values are defined by the standard Tailwind CSS color theme.

MuJoCo uses a normalized rgba (all color channels clamped between 0 and 1). This enum defines with hex values, but they can be easily transformed with the provided methods (for example: Color.WHITE.rgba).

rgba property

Python
rgba: Vec4

Returns the normalized RGBA array for MuJoCo.

with_alpha

Python
with_alpha(alpha: float) -> Vec4

Returns the color with a custom transparency level.

Source code in src/mujoco_mojo/utils/color.py
Python
def with_alpha(self, alpha: float) -> Vec4:
    """Returns the color with a custom transparency level."""
    return Color.hex_to_rgba(self.value, alpha=alpha)

hex_to_rgba classmethod

Python
hex_to_rgba(hex_str: str, alpha: float = 1.0) -> Vec4

Converts '#RRGGBB' or 'RRGGBB' to normalized [0, 1] RGBA.

Source code in src/mujoco_mojo/utils/color.py
Python
@classmethod
def hex_to_rgba(cls, hex_str: str, alpha: float = 1.0) -> Vec4:
    """Converts '#RRGGBB' or 'RRGGBB' to normalized [0, 1] RGBA."""
    hex_str = hex_str.lstrip("#")
    # Convert hex to integers using bit-shifting
    lv = len(hex_str)
    if lv == 6:
        rgb = tuple(int(hex_str[i : i + 2], 16) for i in (0, 2, 4))
    else:
        raise ValueError(f"Invalid hex color: {hex_str}. Expected 6 characters.")

    return np.array([*(np.array(rgb) / 255.0), alpha])

rgba255_to_rgba classmethod

Python
rgba255_to_rgba(rgba255: Vec4) -> Vec4

Converts [0-255, 0-255, 0-255, 0-1] to normalized [0, 1] RGBA.

Source code in src/mujoco_mojo/utils/color.py
Python
@classmethod
def rgba255_to_rgba(cls, rgba255: Vec4) -> Vec4:
    """Converts [0-255, 0-255, 0-255, 0-1] to normalized [0, 1] RGBA."""
    res = np.array(rgba255, dtype=float)
    res[:3] /= 255.0
    return res

rgba_to_hex classmethod

Python
rgba_to_hex(rgba: Vec4) -> str

Converts normalized RGBA to '#RRGGBB' (alpha is discarded).

Source code in src/mujoco_mojo/utils/color.py
Python
@classmethod
def rgba_to_hex(cls, rgba: Vec4) -> str:
    """Converts normalized RGBA to '#RRGGBB' (alpha is discarded)."""
    rgba = np.asarray(rgba, dtype=float)
    r, g, b = (int(v) for v in rgba[:3] * 255)
    return f"#{r:02x}{g:02x}{b:02x}"

rgba_to_rgba255 classmethod

Python
rgba_to_rgba255(rgba: Vec4) -> Vec4

Converts normalized RGBA to [0-255, 0-255, 0-255, 0-1].

Source code in src/mujoco_mojo/utils/color.py
Python
@classmethod
def rgba_to_rgba255(cls, rgba: Vec4) -> Vec4:
    """Converts normalized RGBA to [0-255, 0-255, 0-255, 0-1]."""
    res = np.array(rgba, dtype=float)
    res[:3] *= 255.0
    return res

parse classmethod

Python
parse(v: Any) -> str | None

Normalizes arbitrary color input: None/"" -> None (hidden/unset), a member name (case-insensitive) -> its canonical uppercase name, a #rrggbb hex code -> its canonical member name if that exact hex matches one, otherwise its uppercase hex form. Anything else raises ValueError.

Returns a plain str, not a Color, since a caller (e.g. VisualizationSettings's color fields) may need to store an arbitrary hex with no matching member, not just a member name - not every valid return value corresponds to an actual enum member.

Source code in src/mujoco_mojo/utils/color.py
Python
@classmethod
def parse(cls, v: Any) -> str | None:
    """
    Normalizes arbitrary color input: `None`/`""` -> `None` (hidden/unset), a member name (case-insensitive) -> its canonical uppercase name, a `#rrggbb` hex code -> its canonical member name if that exact hex matches one, otherwise its uppercase hex form. Anything else raises `ValueError`.

    Returns a plain `str`, not a `Color`, since a caller (e.g. `VisualizationSettings`'s color fields) may need to store an arbitrary hex with no matching member, not just a member name - not every valid return value corresponds to an actual enum member.
    """
    if v is None or v == "":
        return None
    if not isinstance(v, str):
        msg = f"{v!r} is not a valid Color name or hex code."
        raise ValueError(msg)
    if _HEX_COLOR_RE.match(v):
        hex_upper: str = v.upper()
        return _HEX_TO_COLOR_NAME.get(hex_upper, hex_upper)
    upper: str = v.upper()
    if upper in cls.__members__:
        return upper
    msg = f"'{v}' is not a valid Color name (e.g. 'ROSE_500') or hex code (e.g. '#F43F5E')."
    raise ValueError(msg)

Column

Bases: BaseModel

One telemetry column: its name parts and its metadata. str(column) is the column name as it appears in the telemetry file.

category instance-attribute

Python
category: SignalCategory | _Part

Top-level category, e.g. Bodies (see SignalCategory for the built-in ones). Must not be empty or contain / or :.

subgroups class-attribute instance-attribute

Python
subgroups: tuple[_Part, ...] = ()

Folders under the category, e.g. ("box1", "xpos"). Empty parts are dropped; none may contain / or :.

attr class-attribute instance-attribute

Python
attr: _Part | None = Field(default=None)

The component or attribute name, e.g. x. An empty value is treated as unset; it may not contain / or :.

metadata class-attribute instance-attribute

Python
metadata: ColumnMetadata = Field(
    default_factory=ColumnMetadata
)

Metadata persisted for this column in the telemetry file's footer. Validated when the column is built (a plain dict is accepted), so the per-timestep merges that produce it can skip validation.

parse classmethod

Python
parse(
    name: str, metadata: ColumnMetadata | None = None
) -> Column

Splits a column name into its parts; the exact inverse of str(). Raises ValueError for a malformed name (an empty part).

Each distinct name is parsed once per process and then served from a cache, so parsing every column of a large frame repeatedly costs a dictionary lookup per name. The returned Column is shared, which is safe because it is frozen.

Source code in src/mujoco_mojo/utils/column.py
Python
@classmethod
def parse(cls, name: str, metadata: ColumnMetadata | None = None) -> Column:
    """
    Splits a column name into its parts; the exact inverse of `str()`. Raises `ValueError` for a malformed name (an empty part).

    Each distinct name is parsed once per process and then served from a cache, so parsing every column of a large frame repeatedly costs a dictionary lookup per name. The returned `Column` is shared, which is safe because it is frozen.
    """
    column = _parse(name)
    if metadata is None:
        return column
    return column.model_copy(
        update={"metadata": ColumnMetadata.validated(metadata)}
    )

covers

Python
covers(other: Column) -> bool

True if other is this column or lies beneath it: the same category, other's subgroups start with this column's subgroups, and this column's attr is unset or equal to other's. Metadata is ignored.

A partial column therefore selects a whole subtree: Column(category="Bodies", subgroups=("box1",)) covers Bodies/box1/xpos:x and Bodies/box1:ke_trans.

Source code in src/mujoco_mojo/utils/column.py
Python
def covers(self, other: Column) -> bool:
    """
    True if `other` is this column or lies beneath it: the same category, `other`'s subgroups start with this column's subgroups, and this column's `attr` is unset or equal to `other`'s. Metadata is ignored.

    A partial column therefore selects a whole subtree: `Column(category="Bodies", subgroups=("box1",))` covers `Bodies/box1/xpos:x` and `Bodies/box1:ke_trans`.
    """
    n = len(self.subgroups)
    return (
        other.category == self.category
        and other.subgroups[:n] == self.subgroups
        and (self.attr is None or self.attr == other.attr)
    )

__contains__

Python
__contains__(other: Self | str) -> bool

child in parent, the same test as parent.covers(child); a name string is parsed first, and a string outside the telemetry grammar is never contained. Equality is untouched, so ==, hashing, and x in [columns] keep meaning exact match.

Source code in src/mujoco_mojo/utils/column.py
Python
def __contains__(self, other: Self | str) -> bool:
    """`child in parent`, the same test as `parent.covers(child)`; a name string is parsed first, and a string outside the telemetry grammar is never contained. Equality is untouched, so `==`, hashing, and `x in [columns]` keep meaning exact match."""
    column = other
    if isinstance(other, str):
        try:
            column = _parse(other)
        except ValueError:
            return False
    return isinstance(column, Column) and self.covers(column)

MojoDataFrame

Bases: _MojoFrame

A Polars DataFrame of telemetry, with Mojo's loaders for reading it back from a telemetry.parquet file and the .mojo namespace (see MojoNamespace) for selecting signals, poses, units and reference frames.

Every Polars DataFrame has the namespace once mujoco_mojo is imported, and this class adds the loaders and type hints that keep the type through select, filter, with_columns and the rest.

read_parquet classmethod

Python
read_parquet(
    path: Path | str,
    columns: list[int] | list[str] | None = None,
    *args: Any,
    **kwargs: Any,
) -> MojoDataFrame

Loads a DataFrame containing only the specific telemetry columns requested.

Source code in src/mujoco_mojo/utils/dataframe.py
Python
@classmethod
def read_parquet(
    cls,
    path: Path | str,
    columns: list[int] | list[str] | None = None,
    *args: Any,
    **kwargs: Any,
) -> MojoDataFrame:
    """Loads a DataFrame containing only the specific telemetry columns requested."""
    return cls.from_pl(
        pl.read_parquet(source=path, columns=columns, *args, **kwargs)
    )

read_column_metadata classmethod

Python
read_column_metadata(
    path: Path | str,
) -> dict[str, ColumnMetadata]

Reads the per-column metadata from the parquet file footer written by SignalManager. Returns an empty dict if the file has no embedded metadata. An entry that fails validation (for example a unit written by another version) is still loaded, unvalidated, with a warning, so older files keep opening.

Source code in src/mujoco_mojo/utils/dataframe.py
Python
@classmethod
def read_column_metadata(cls, path: Path | str) -> dict[str, ColumnMetadata]:
    """Reads the per-column metadata from the parquet file footer written by `SignalManager`. Returns an empty dict if the file has no embedded metadata. An entry that fails validation (for example a unit written by another version) is still loaded, unvalidated, with a warning, so older files keep opening."""
    file_meta = pq.read_metadata(str(path)).metadata
    if not file_meta:
        return {}
    raw = file_meta.get(b"column_metadata")
    if raw is None:
        return {}
    return {
        col: ColumnMetadata.lenient(entry, where=f" for column '{col}'")
        for col, entry in json.loads(raw.decode()).items()
    }

from_pl classmethod

Python
from_pl(df: DataFrame) -> MojoDataFrame

Converts a standard Polars DataFrame into a MojoFrame for the static analyzer.

Source code in src/mujoco_mojo/utils/dataframe.py
Python
@classmethod
def from_pl(cls, df: pl.DataFrame) -> MojoDataFrame:
    """
    Converts a standard Polars DataFrame into a MojoFrame for the static analyzer.
    """
    return cast(MojoDataFrame, df)

from_dict classmethod

Python
from_dict(
    data: dict[str, Any], *args: Any, **kwargs: Any
) -> MojoDataFrame

Creates a MojoFrame from a dictionary.

Source code in src/mujoco_mojo/utils/dataframe.py
Python
@classmethod
def from_dict(
    cls, data: dict[str, Any], *args: Any, **kwargs: Any
) -> MojoDataFrame:
    """Creates a MojoFrame from a dictionary."""
    return cls.from_pl(pl.DataFrame(data=data, *args, **kwargs))

Proximity

Bases: MojoBaseModel

Provide high-precision triangle-level distance queries.

volume_1 instance-attribute

Python
volume_1: Proximityable

First volume to perform proximity calculations for.

volume_2 instance-attribute

Python
volume_2: Proximityable

Second volume to perform proximity calculations for.

dist_max instance-attribute

Python
dist_max: float

The 'cutoff' distance. If objects are further than this (as estimated by a sphere to sphere test), the sphere to sphere estimate will be returned and exit early.

algorithm class-attribute instance-attribute

Python
algorithm: ProximityType = CONVEX_HULL

What algorithm should be used for the narrowphase test.

visualize class-attribute instance-attribute

Python
visualize: bool = True

Wheter or not to visualize this proximity in the MuJoCo viewer.

active class-attribute instance-attribute

Python
active: bool = True

Whether this pair is being measured. An inactive pair is not drawn, logged or calculated, so a pair that no longer matters costs nothing. A direct call to get_proximity still works.

get_sphere_to_sphere_proximity

Python
get_sphere_to_sphere_proximity(
    state: MjState,
) -> tuple[float, Vec3, Vec3, bool]

Calculates the shortest distance between two volumes using their bounding spheres.

Parameters:

Name Type Description Default
state MjState

The paired MuJoCo model and data instance.

required

Returns:

Type Description
tuple[float, Vec3, Vec3, bool]

tuple[float, Vec3, Vec3, bool]: Unsigned (>= 0) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and if the estimated distance exceeds dist_max.

Source code in src/mujoco_mojo/utils/proximity.py
Python
def get_sphere_to_sphere_proximity(
    self,
    state: MjState,
) -> tuple[float, Vec3, Vec3, bool]:
    """
    Calculates the shortest distance between two volumes using their bounding spheres.

    Args:
        state: The paired MuJoCo model and data instance.

    Returns:
        tuple[float, Vec3, Vec3, bool]: Unsigned (`>= 0`) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and if the estimated distance exceeds dist_max.

    """
    # get world orientations and origins
    origin_volume_1 = self.volume_1.rt_pos(state)
    mat_volume_1 = self.volume_1.rt_xmat(state)

    origin_volume_2 = self.volume_2.rt_pos(state)
    mat_volume_2 = self.volume_2.rt_xmat(state)

    if np.isnan(self.volume_1._rad):
        self.volume_1._rad, self.volume_1._local_centroid = (
            self.volume_1.vertex_max_norm(state.model)
        )

    if np.isnan(self.volume_2._rad):
        self.volume_2._rad, self.volume_2._local_centroid = (
            self.volume_2.vertex_max_norm(state.model)
        )

    # shift centers to pre-calculated centroids
    pos_volume_1 = origin_volume_1 + (mat_volume_1 @ self.volume_1._local_centroid)
    pos_volume_2 = origin_volume_2 + (mat_volume_2 @ self.volume_2._local_centroid)

    rad_volume_1 = self.volume_1._rad
    rad_volume_2 = self.volume_2._rad

    vec_volume_1_to_volume_2 = pos_volume_2 - pos_volume_1
    d_centers = float(np.linalg.norm(vec_volume_1_to_volume_2))
    dist = d_centers - (rad_volume_1 + rad_volume_2)

    dist = max(0.0, dist)  # clip to zero
    exceeds_dist_max = dist > self.dist_max

    if d_centers > 1e-9:
        unit_vec = vec_volume_1_to_volume_2 / d_centers
        p1 = pos_volume_1 + (unit_vec * rad_volume_1)
        p2 = pos_volume_2 - (unit_vec * rad_volume_2)
    else:
        p1 = pos_volume_1
        p2 = pos_volume_2

    self.update_last(p1, p2, state)
    return dist, p1, p2, exceeds_dist_max

get_convex_hull_proximity

Python
get_convex_hull_proximity(
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]

Calculates the shortest distance between two volumes using their convex hull.

Parameters:

Name Type Description Default
state MjState

The paired MuJoCo model and data instance.

required

Returns:

Type Description
tuple[float, Vec3, Vec3, ProximityType]

tuple[float, Vec3, Vec3, ProximityType]: Unsigned (>= 0) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

Raises:

Type Description
TypeError

If either volume is a SiteMesh and the broadphase sphere-to-sphere check doesn't already resolve the query. The narrowphase below is MuJoCo's native mj_geomDistance, which only operates on geoms - it indexes mjModel's geom arrays by geom id, a completely separate namespace from a site's id. Use ProximityType.VERTEX_TO_FACE or FACE_TO_FACE instead, which compute distance via mojo's own trimesh-based BVH query rather than this native call.

Source code in src/mujoco_mojo/utils/proximity.py
Python
def get_convex_hull_proximity(
    self,
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]:
    """
    Calculates the shortest distance between two volumes using their convex hull.

    Args:
        state: The paired MuJoCo model and data instance.

    Returns:
        tuple[float, Vec3, Vec3, ProximityType]: Unsigned (`>= 0`) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

    Raises:
        TypeError: If either volume is a `SiteMesh` and the broadphase sphere-to-sphere check doesn't already resolve the query. The narrowphase below is MuJoCo's native `mj_geomDistance`, which only operates on geoms - it indexes `mjModel`'s geom arrays by geom id, a completely separate namespace from a site's id. Use `ProximityType.VERTEX_TO_FACE` or `FACE_TO_FACE` instead, which compute distance via mojo's own trimesh-based BVH query rather than this native call.

    """
    # ========== BROADPHASE ==========
    if self.volume_1._proximity_configured_for != ProximityType.CONVEX_HULL:
        self.volume_1.bake_proximity(state.model, ProximityType.CONVEX_HULL)

    if self.volume_2._proximity_configured_for != ProximityType.CONVEX_HULL:
        self.volume_2.bake_proximity(state.model, ProximityType.CONVEX_HULL)

    d_est, p1, p2, skip = self.get_sphere_to_sphere_proximity(state)

    if skip:
        return d_est, p1, p2, ProximityType.SPHERE_TO_SPHERE

    if isinstance(self.volume_1, SiteMesh) or isinstance(self.volume_2, SiteMesh):
        msg = "CONVEX_HULL proximity's narrowphase uses MuJoCo's native mj_geomDistance, which only supports geoms, not sites. Use ProximityType.VERTEX_TO_FACE or FACE_TO_FACE instead for a SiteMesh."
        logger.error(msg)
        raise TypeError(msg)

    # ========== NARROWPHASE ==========
    # temp buffer for MuJoCo's 6-element output [x1,y1,z1, x2,y2,z2]
    mj_fromto = np.zeros(6)
    min_dist = mujoco.mj_geomDistance(
        m=state.model,
        d=state.data,
        geom1=self.volume_1.get_id(state.model),
        geom2=self.volume_2.get_id(state.model),
        distmax=self.dist_max,
        fromto=mj_fromto,
    )

    min_dist = max(0.0, min_dist)  # clip from below to zero

    # past `distmax` MuJoCo returns `distmax` with the points zeroed, so keep the broadphase's points, which the broadphase already stored
    if min_dist >= self.dist_max:
        return min_dist, p1, p2, ProximityType.CONVEX_HULL

    p1 = mj_fromto[:3].copy()
    p2 = mj_fromto[3:6].copy()
    self.update_last(p1, p2, state)
    return min_dist, p1, p2, ProximityType.CONVEX_HULL

get_vertex_to_face_proximity

Python
get_vertex_to_face_proximity(
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]

Calculates the vertex to face distance using a multi-phase Bounding Volume Hierarchy (BVH) query.

Phases
  1. Broad Phase: Sphere-Sphere check (object level).
  2. Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
  3. Narrow Phase: Point-to-Face proximity.

Parameters:

Name Type Description Default
state MjState

The paired MuJoCo model and data instance.

required

Returns:

Type Description
tuple[float, Vec3, Vec3, ProximityType]

tuple[float, Vec3, Vec3, ProximityType]: Unsigned (>= 0) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

Source code in src/mujoco_mojo/utils/proximity.py
Python
def get_vertex_to_face_proximity(
    self,
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]:
    """
    Calculates the vertex to face distance using a multi-phase Bounding Volume Hierarchy (BVH) query.

    Phases:
        1. Broad Phase: Sphere-Sphere check (object level).
        2. Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
        3. Narrow Phase: Point-to-Face proximity.

    Args:
        state: The paired MuJoCo model and data instance.

    Returns:
        tuple[float, Vec3, Vec3, ProximityType]: Unsigned (`>= 0`) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

    """
    if self.volume_1._proximity_configured_for != ProximityType.VERTEX_TO_FACE:
        self.volume_1.bake_proximity(state.model, ProximityType.VERTEX_TO_FACE)

    if self.volume_2._proximity_configured_for != ProximityType.VERTEX_TO_FACE:
        self.volume_2.bake_proximity(state.model, ProximityType.VERTEX_TO_FACE)

    assert self.volume_1._baked_query and self.volume_2._baked_query
    assert (
        self.volume_2._local_verts is not None
        and self.volume_2._local_verts is not None
    )

    # ========== BROADPHASE: Sphere-Sphere check ==========
    # find center to center to center distance and return early if broad phase
    d_est, p1, p2, skip = self.get_sphere_to_sphere_proximity(state)
    if skip:
        return d_est, p1, p2, ProximityType.SPHERE_TO_SPHERE

    # ========== COORDINATE TRANSFORMATION ==========
    pos_volume_1 = self.volume_1.rt_pos(state)
    pos_volume_2 = self.volume_2.rt_pos(state)

    mat_volume_1 = self.volume_1.rt_xmat(state)  # already Mat3 (3x3)
    mat_volume_2 = self.volume_2.rt_xmat(state)
    rel_pos = pos_volume_2 - pos_volume_1

    # ========== NARROWPHASE A: Volume_1-Surface vs. Volume_2-Vertices ==========
    # trimesh uses a BVH internall here (Mid-phase) to find closest triangles
    # combine transforms from volume_1 to volume_2: V_local_volume_1 = R_volume_1.T @ (R_volume_2 @ V_local_volume_2 + p_volume_2 - p_volume_1)
    volume_2_v_in_volume_1 = (
        self.volume_2._local_verts @ mat_volume_2.T + rel_pos
    ) @ mat_volume_1
    pts_on_volume_1, dist_a, _ = self.volume_1._baked_query.on_surface(
        volume_2_v_in_volume_1
    )
    idx_a = np.argmin(dist_a)
    min_a = dist_a[idx_a]

    # ========== NARROWPHASE B: Volume_1-Vertices vs. Volume_2-Surface  ==========
    # transform volume_1 vertices into volume_2's local frame
    volume_1_v_in_volume_2 = (
        self.volume_1._local_verts @ mat_volume_1.T - rel_pos
    ) @ mat_volume_2
    pts_on_volume_2, dist_b, _ = self.volume_2._baked_query.on_surface(
        volume_1_v_in_volume_2
    )
    idx_b = np.argmin(dist_b)
    min_b = dist_b[idx_b]

    # ========== CLEANUP ==========
    # find global min
    if min_a < min_b:
        min_dist = float(min_a)
        p1 = (pts_on_volume_1[idx_a] @ mat_volume_1.T) + pos_volume_1
        p2 = (volume_2_v_in_volume_1[idx_a] @ mat_volume_1.T) + pos_volume_1

        self.update_last(p1, p2, state)
        return min_dist, p1, p2, ProximityType.VERTEX_TO_FACE
    else:
        min_dist = float(min_b)

        # pt_on_volume_2 was calculated in volume_2's local frame
        p2 = (pts_on_volume_2[idx_b] @ mat_volume_2.T) + pos_volume_2
        p1 = (volume_1_v_in_volume_2[idx_b] @ mat_volume_2.T) + pos_volume_2

        self.update_last(p1, p2, state)
        return min_dist, p1, p2, ProximityType.VERTEX_TO_FACE

get_face_to_face_proximity

Python
get_face_to_face_proximity(
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]

Calculates the face to face distance using a multi-phase Bounding Volume Hierarchy (BVH) query.

This is more accurate than the vertex to face method, but comes at higher computational cost.

Phases
  1. Broad Phase: Sphere-Sphere check (object level).
  2. Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
  3. Narrow Phase: Face-to-Face proximity.

Parameters:

Name Type Description Default
state MjState

The paired MuJoCo model and data instance.

required

Returns:

Type Description
tuple[float, Vec3, Vec3, ProximityType]

tuple[float, Vec3, Vec3, ProximityType]: Unsigned (>= 0) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

Source code in src/mujoco_mojo/utils/proximity.py
Python
def get_face_to_face_proximity(
    self,
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]:
    """
    Calculates the face to face distance using a multi-phase Bounding Volume Hierarchy (BVH) query.

    This is more accurate than the vertex to face method, but comes at higher computational cost.

    Phases:
        1. Broad Phase: Sphere-Sphere check (object level).
        2. Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
        3. Narrow Phase: Face-to-Face proximity.

    Args:
        state: The paired MuJoCo model and data instance.

    Returns:
        tuple[float, Vec3, Vec3, ProximityType]: Unsigned (`>= 0`) minimum distance from volume_1 to volume_2, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which phase the exit occurred in.

    """
    if self.volume_1._proximity_configured_for != ProximityType.FACE_TO_FACE:
        self.volume_1.bake_proximity(state.model, ProximityType.FACE_TO_FACE)

    if self.volume_2._proximity_configured_for != ProximityType.FACE_TO_FACE:
        self.volume_2.bake_proximity(state.model, ProximityType.FACE_TO_FACE)

    assert self.volume_1._baked_manager and self.volume_2._baked_manager

    # ========== BROADPHASE: Sphere-Sphere check ==========

    # find center to center to center distance and return early if broad phase
    d_est, p1, p2, skip = self.get_sphere_to_sphere_proximity(state)
    if skip:
        return d_est, p1, p2, ProximityType.SPHERE_TO_SPHERE

    # ========== NARROWPHASE ==========
    # set the other transformation relative to volume_1's local frame
    t_volume_1 = np.eye(4)
    t_volume_1[:3, :3] = self.volume_1.rt_xmat(state)
    t_volume_1[:3, 3] = self.volume_1.rt_pos(state)

    t_volume_2 = np.eye(4)
    t_volume_2[:3, :3] = self.volume_2.rt_xmat(state)
    t_volume_2[:3, 3] = self.volume_2.rt_pos(state)

    self.volume_1._baked_manager.set_transform(self.volume_1.name, t_volume_1)
    self.volume_2._baked_manager.set_transform(self.volume_2.name, t_volume_2)

    # CollisionManager returns distance and the two closest points
    result = self.volume_1._baked_manager.min_distance_other(
        self.volume_2._baked_manager, return_data=True
    )
    min_dist = float(result[0])
    min_dist = max(0.0, min_dist)  # clip to zero
    data = result[1]

    assert data
    p1 = data.point(self.volume_1.name)
    p2 = data.point(self.volume_2.name)

    self.update_last(p1, p2, state)
    return min_dist, p1, p2, ProximityType.FACE_TO_FACE

get_proximity

Python
get_proximity(
    state: MjState,
) -> tuple[float, Vec3, Vec3, ProximityType]

Calculates the shortest distance between two volumes using the specified proximity algorithm.

This is a general dispatcher method that routes to different proximity calculation algorithms based on the algorithm parameter. Each mode offers different tradeoffs between speed and precision:

Modes: - SPHERE_TO_SPHERE: Fastest. Uses bounding sphere distance only (broadphase). - CONVEX_HULL: Fast & accurate. Uses MuJoCo's convex hull-based distance (default). - VERTEX_TO_FACE: Accurate. Multi-phase BVH with vertex-to-surface queries. - FACE_TO_FACE: Most accurate but slowest. Full mesh-to-mesh distance calculation.

Phases (for non-sphere modes): 1. Broad Phase: Sphere-Sphere check (object level). 2. Narrow Phase: Algorithm-specific distance calculation.

Parameters:

Name Type Description Default
state MjState

The paired MuJoCo model and data instance.

required

Returns:

Type Description
float

tuple[float, ProximityType]: If fromto=False, returns the unsigned (>= 0) minimum distance and which algorithm produced the result.

Vec3

tuple[tuple[float, Vec3, Vec3], ProximityType]: If fromto=True, returns the minimum distance, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which algorithm produced the result.

The result is cached per-timestep (keyed on state.data.time), so calling this more than once during the same step (e.g. once from request()'s telemetry sampler and again from a user-defined runtime input/Load that reads the same Proximity instance) only pays for the underlying calculation once.

Source code in src/mujoco_mojo/utils/proximity.py
Python
def get_proximity(self, state: MjState) -> tuple[float, Vec3, Vec3, ProximityType]:
    """
    Calculates the shortest distance between two volumes using the specified proximity algorithm.

    This is a general dispatcher method that routes to different proximity calculation algorithms based on the `algorithm` parameter. Each mode offers different tradeoffs between speed and precision:

    **Modes:**
        - `SPHERE_TO_SPHERE`: Fastest. Uses bounding sphere distance only (broadphase).
        - `CONVEX_HULL`: Fast & accurate. Uses MuJoCo's convex hull-based distance (default).
        - `VERTEX_TO_FACE`: Accurate. Multi-phase BVH with vertex-to-surface queries.
        - `FACE_TO_FACE`: Most accurate but slowest. Full mesh-to-mesh distance calculation.

    **Phases (for non-sphere modes):**
        1. Broad Phase: Sphere-Sphere check (object level).
        2. Narrow Phase: Algorithm-specific distance calculation.

    Args:
        state: The paired MuJoCo model and data instance.

    Returns:
        tuple[float, ProximityType]: If fromto=False, returns the unsigned (`>= 0`) minimum distance and which algorithm produced the result.

        tuple[tuple[float, Vec3, Vec3], ProximityType]: If fromto=True, returns the minimum distance, world location of minimum distance on volume_1, world location of minimum distance on volume_2, and which algorithm produced the result.

    The result is cached per-timestep (keyed on `state.data.time`), so calling this more than once during the same step (e.g. once from `request()`'s telemetry sampler and again from a user-defined runtime input/Load that reads the same `Proximity` instance) only pays for the underlying calculation once.

    """
    is_cached = (
        self._last_prox_type is not None
        and not np.isnan(self._last_dist)
        and state.data.time == self._last_t
    )
    if is_cached:
        assert self._last_prox_type is not None  # narrows for the type checker
        return self._last_dist, self._last_p1, self._last_p2, self._last_prox_type

    match self.algorithm:
        case ProximityType.SPHERE_TO_SPHERE:
            d_est, p1, p2, _skip = self.get_sphere_to_sphere_proximity(state)
            result = (d_est, p1, p2, ProximityType.SPHERE_TO_SPHERE)
        case ProximityType.CONVEX_HULL:
            result = self.get_convex_hull_proximity(state)
        case ProximityType.VERTEX_TO_FACE:
            result = self.get_vertex_to_face_proximity(state)
        case ProximityType.FACE_TO_FACE:
            result = self.get_face_to_face_proximity(state)
        case _:
            msg = f"Method for {self.algorithm.name} not implemented."
            logger.error(msg)
            raise NotImplementedError(msg)

    # the configured algorithm's broadphase sphere-to-sphere check can exit early
    # (objects farther apart than dist_max), so the phase that actually produced
    # this result can flip between SPHERE_TO_SPHERE and the configured narrowphase
    # algorithm from one call to the next; surface that for performance debugging
    prox_type = result[3]
    if self._last_prox_type is not None and prox_type != self._last_prox_type:
        logger.debug(
            f"Proximity {self.pair_name} switched phase: "
            f"{self._last_prox_type.name} -> {prox_type.name} (t={state.data.time:.4f})"
        )
    self._last_prox_type = prox_type
    self._last_dist = result[0]
    # _last_t/_last_p1/_last_p2 were already set by update_last() inside whichever
    # method above produced `result`

    return result

request

Python
request(
    signal_manager: SignalManager | None = None,
    channels: list[Literal["dist", "fromto", "prox_type"]]
    | dict[
        Literal["dist", "fromto", "prox_type"],
        MetadataLike | None,
    ] = ["dist", "prox_type"],
) -> None

Registers specific channels for logging.

Channel Description Type
dist minimum distance between the volume pair, per the proximity algorithm scalar
fromto world coordinates of the nearest point on each volume xyz
prox_type the ProximityType used to compute dist and fromto, as an integer scalar

Each channel is posted under subgroups=(pair_name,), where pair_name is f"{volume_1.name}_to_{volume_2.name}".

  • A scalar is posted as a single value with attr=channel.
  • An xyz is a cartesian vector without a magnitude component, posted as 3 values (x, y, z). fromto posts one xyz for each volume in the pair, under subgroups=(pair_name, "fromto", volume_name).

Only the computations required by the requested channels are performed each timestep.

Each signal is tagged with built-in dimension/unit metadata for its channel (dist/fromto as a length, prox_type as dimensionless).

If signal_manager is omitted, the SignalManager of the active RuntimeManager with block is used. If that RuntimeManager has no SignalManager configured, this is a no-op.

Parameters:

Name Type Description Default
signal_manager SignalManager | None

The signal manager to register the sampler with.

None
channels list[Literal['dist', 'fromto', 'prox_type']] | dict[Literal['dist', 'fromto', 'prox_type'], MetadataLike | None]

The proximity data channels to log. Pass a list to select channels, or a dict mapping channel name to metadata overrides (or None) to select channels and attach per-channel metadata in one step.

['dist', 'prox_type']
Source code in src/mujoco_mojo/utils/proximity.py
Python
def request(
    self,
    signal_manager: SignalManager | None = None,
    channels: list[Literal["dist", "fromto", "prox_type"]]
    | dict[Literal["dist", "fromto", "prox_type"], MetadataLike | None] = [
        "dist",
        "prox_type",
    ],
) -> None:
    """
    Registers specific channels for logging.

    | Channel     | Description                                                            | Type   |
    |:------------|:-----------------------------------------------------------------------|:-------|
    | `dist`      | minimum distance between the volume pair, per the proximity algorithm  | scalar |
    | `fromto`    | world coordinates of the nearest point on each volume                  | xyz    |
    | `prox_type` | the `ProximityType` used to compute `dist` and `fromto`, as an integer | scalar |

    Each channel is posted under `subgroups=(pair_name,)`, where `pair_name` is `f"{volume_1.name}_to_{volume_2.name}"`.

    * A `scalar` is posted as a single value with `attr=channel`.
    * An `xyz` is a cartesian vector without a magnitude component, posted as 3 values (`x`, `y`, `z`). `fromto` posts one `xyz` for each volume in the pair, under `subgroups=(pair_name, "fromto", volume_name)`.

    Only the computations required by the requested channels are performed each timestep.

    Each signal is tagged with built-in `dimension`/`unit` metadata for its channel (`dist`/`fromto` as a length, `prox_type` as dimensionless).

    If `signal_manager` is omitted, the `SignalManager` of the active `RuntimeManager` `with` block is used. If that `RuntimeManager` has no `SignalManager` configured, this is a no-op.

    Args:
        signal_manager: The signal manager to register the sampler with.
        channels: The proximity data channels to log. Pass a list to select channels, or a dict mapping channel name to metadata overrides (or `None`) to select channels and attach per-channel metadata in one step.

    """
    from mujoco_mojo.runtime.signal_manager import resolve_signal_manager

    signal_manager = resolve_signal_manager(signal_manager)
    if signal_manager is None:
        return

    if isinstance(channels, dict):
        _meta = cast("MetadataOverrides", channels)
        channels = list(channels.keys())
    else:
        _meta = {}

    pair_name = self.pair_name
    _prox_attrs = {"dist", "fromto", "prox_type"}
    needs_proximity = bool(set(channels) & _prox_attrs)

    if needs_proximity:
        self._requested = True

    volume_names = (str(self.volume_1.name), str(self.volume_2.name))
    first, second = volume_names
    descriptions = {
        "dist": f"Minimum distance between volumes {first} and {second}",
        "prox_type": f"Proximity algorithm used to compute the distance between volumes {first} and {second}, as an integer code",
    }
    columns: dict[str, tuple[Column, ...]] = {}

    def merged(channel: str, state: MjState, description: str) -> ColumnMetadata:
        return merge_signal_metadata(
            _REQUEST_CHANNEL_METADATA.get(channel),
            channel,
            _meta,
            unit_system=state.us,
            description=description,
        )

    def channel_columns(channel: str, state: MjState) -> tuple[Column, ...]:
        # built on a channel's first sample (its metadata depends on the unit
        # system), then reused: this runs every timestep
        cols = columns.get(channel)
        if cols is None:
            if channel == "fromto":
                # one x/y/z point per volume in the pair
                cols = tuple(
                    col
                    for volume in volume_names
                    for col in fan_out(
                        SignalCategory.PROXIMITIES,
                        (pair_name, channel, volume),
                        "xyz",
                        merged(
                            channel,
                            state,
                            f"Position of the nearest point on volume {volume} of pair {pair_name}, in the world frame",
                        ),
                    )
                )
            else:
                cols = (
                    Column(
                        category=SignalCategory.PROXIMITIES,
                        subgroups=(pair_name,),
                        attr=channel,
                        metadata=merged(
                            channel, state, descriptions.get(channel, "")
                        ),
                    ),
                )
            columns[channel] = cols
        return cols

    def sample(state: MjState) -> None:
        if not self.active:
            return

        dist: float = np.nan
        p1: Vec3 = np.zeros(3)
        p2: Vec3 = np.zeros(3)
        prox_type = ProximityType.SPHERE_TO_SPHERE

        if needs_proximity:
            dist, p1, p2, prox_type = self.get_proximity(state)

        for channel in channels:
            match channel:
                case "dist":
                    (col,) = channel_columns(channel, state)
                    signal_manager.post(dist, col)
                case "fromto":
                    for v, col in zip(
                        (*p1, *p2), channel_columns(channel, state), strict=True
                    ):
                        signal_manager.post(float(v), col)
                case "prox_type":
                    (col,) = channel_columns(channel, state)
                    signal_manager.post(float(prox_type.value), col)
                case _:
                    continue

    signal_manager.register_sampler(sample)

MojoGenerator

Bases: Protocol

Definition of a function that generates a MojoModel model instance.

MojoObjective

Bases: Protocol

Definition of a function that scores a completed Mojo simulation.

MojoRunner dataclass

Python
MojoRunner(
    generator: MojoGenerator,
    generator_path: str | None = None,
    runtime: MojoRuntime | None = DEFAULT_RUNTIME,
    runtime_path: str | None = None,
    objective: MojoObjective | None = None,
    objective_path: str | None = None,
    seed: int | None = DEFAULT_SEED,
    workdir: Path = DEFAULT_WORKDIR,
    model_config_name: str
    | None = DEFAULT_MODEL_CONFIG_NAME,
    xml_name: str = DEFAULT_XML_NAME,
    config: MonteCarloConfig
    | OptimizerConfig = MonteCarloConfig(),
    args: list[Any] = list(),
    kwargs: dict[str, Any] = dict(),
)

args class-attribute instance-attribute

Python
args: list[Any] = field(default_factory=list)

Positional arguments passed to the generator, the runtime, and the objective.

kwargs class-attribute instance-attribute

Python
kwargs: dict[str, Any] = field(default_factory=dict)

Keyword arguments shared by the generator, the runtime, and the objective. Each receives only the ones it accepts (all of them if it takes **kwargs).

slurm_trial_id property

Python
slurm_trial_id: int | None

Returns the current SLURM task ID if running as part of an array job.

shared_argument_flags

Python
shared_argument_flags() -> str

The --arg and --kwarg options that hand this runner's arguments to another mujoco-mojo process, such as a SLURM worker.

Source code in src/mujoco_mojo/utils/runner.py
Python
def shared_argument_flags(self) -> str:
    """The `--arg` and `--kwarg` options that hand this runner's arguments to another `mujoco-mojo` process, such as a SLURM worker."""
    flags = [f'--arg "{a}"' for a in self.args]
    flags += [f'--kwarg "{k}={v}"' for k, v in self.kwargs.items()]
    return " ".join(flags)

validate_kwargs

Python
validate_kwargs() -> None

Raises ValueError if a keyword argument is accepted by none of the generator, the runtime, and the objective.

Each function is only given the keywords it accepts, so a misspelled one would otherwise be dropped silently. A function that takes **kwargs accepts everything, which turns the check off.

Source code in src/mujoco_mojo/utils/runner.py
Python
def validate_kwargs(self) -> None:
    """
    Raises `ValueError` if a keyword argument is accepted by none of the generator, the runtime, and the objective.

    Each function is only given the keywords it accepts, so a misspelled one would otherwise be dropped silently. A function that takes `**kwargs` accepts everything, which turns the check off.
    """
    targets: dict[str, tuple[Callable[..., Any], int]] = {
        "generator": (self.generator, GENERATOR_FIXED_ARGS)
    }
    if self.runtime is not None:
        targets["runtime"] = (self.runtime, RUNTIME_FIXED_ARGS)
    if self.objective is not None:
        targets["objective"] = (self.objective, OBJECTIVE_FIXED_ARGS)
    validate_shared_kwargs(self.kwargs, self.args, targets)

run

Python
run(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    execution_mode: ExecutionMode = LOCAL,
    trial_nums: list[int] | None = None,
) -> bool

Vectors a job to be either computed locally or to be orchestrated by SLURM.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    execution_mode: ExecutionMode = ExecutionMode.LOCAL,
    trial_nums: list[int] | None = None,
) -> bool:
    """Vectors a job to be either computed locally or to be orchestrated by SLURM."""
    self._prepare_run(clean_workdir, cleanup_delay)

    match execution_mode:
        case ExecutionMode.LOCAL:
            return self.run_local(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        case ExecutionMode.SLURM:
            return self.orchestrate_slurm(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        case _:
            msg = f"No run command has been configured for execution mode {execution_mode}"
            logger.error(msg)
            raise NotImplementedError(msg)

orchestrate_slurm

Python
orchestrate_slurm(
    global_overrides: NamedValueDict[NDArray],
    trial_nums: list[int] | None = None,
) -> bool

Generates an sbatch script and submits the job array to SLURM for a given config.

Source code in src/mujoco_mojo/utils/runner.py
Python
def orchestrate_slurm(
    self,
    global_overrides: NamedValueDict[NDArray],
    trial_nums: list[int] | None = None,
) -> bool:
    """Generates an sbatch script and submits the job array to SLURM for a given config."""
    (self.workdir / "logs").mkdir(exist_ok=True)

    from rich.console import Console

    Console().print(
        "[dim]Tip: set '[slurm]' entries in ~/.mujoco-mojo/settings.toml (or a project-local "
        "./.mujoco-mojo/settings.toml, via `mujoco-mojo settings set --project`) to auto-inject "
        "extra #SBATCH lines (prefix a key with 'sbatch.', e.g. 'sbatch.account') and/or "
        "environment variables (any other key) into the generated submission script.[/dim]"
    )

    if isinstance(self.config, MonteCarloConfig):
        try:
            had_fails = self.orchestrate_slurm_monte_carlo(
                global_overrides=global_overrides,
                trial_nums=trial_nums,
            )
        except (BdbQuit, KeyboardInterrupt):
            print("\n")
            logger.error("Aborted SLURM orchestration!")
            had_fails = True
    else:
        msg = f"A SLURM configuration for {self.config.__class__.__name__} has not been implemented."
        logger.error(msg)
        raise NotImplementedError(msg)
    return had_fails

execute_single_trial

Python
execute_single_trial(
    trial_num: int,
    seed: int | None,
    overrides_payload: dict[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]

Helper to package a Trial and run it.

The model and state are live in-process objects; callers that need to cross a ProcessPoolExecutor boundary (i.e. parallel MC) must use _execute_trial_subprocess instead, which drops the non-picklable objects before the result is serialized back.

Returns (mojo_model, trial_status, state).

Source code in src/mujoco_mojo/utils/runner.py
Python
def execute_single_trial(
    self, trial_num: int, seed: int | None, overrides_payload: dict[str, Any]
) -> tuple[MojoModel | None, TrialStatus, MjState | None]:
    """
    Helper to package a Trial and run it.

    The model and state are live in-process objects; callers that need to cross a ProcessPoolExecutor boundary (i.e. parallel MC) must use `_execute_trial_subprocess` instead, which drops the non-picklable objects before the result is serialized back.

    Returns `(mojo_model, trial_status, state)`.
    """
    overrides = NamedValueDict[NDArray].model_validate(overrides_payload)

    trial = Trial(
        trial_num=trial_num,
        base_dir=self.workdir,
        xml_name=self.xml_name,
        model_config_name=self.model_config_name,
        padding_style=self.config.padding_style,
    )

    mojo_model, trial_status, state = trial.run(
        generator=self.generator,
        runtime=self.runtime,
        seed=seed,
        overrides=overrides,
        args=self.args,
        kwargs=self.kwargs,
    )

    # write distribution tables from this process so they never need to
    # cross the pickle boundary; FileLock serializes concurrent workers,
    # and the inner exists() check ensures only the first one writes
    if mojo_model is not None and mojo_model.dists:
        stochas_dir = self.workdir / STOCHAS_DIR_NAME
        stochas_dir.mkdir(exist_ok=True)
        dists_json_path = stochas_dir / STOCHAS_DISTS_FNAME
        with FileLock(stochas_dir / ".dists.lock"):
            if not dists_json_path.exists():
                mojo_model.dists.to_tables(stochas_dir)
                tmp = stochas_dir / "dists.tmp.json"
                tmp.write_text(mojo_model.dists.model_dump_json(), encoding="utf-8")
                tmp.replace(dists_json_path)

    return mojo_model, trial_status, state

run_monte_carlo

Python
run_monte_carlo(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool

Orchestrates a Monte Carlo job.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run_monte_carlo(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool:
    """Orchestrates a Monte Carlo job."""
    if self.slurm_trial_id is not None:
        tn = self.slurm_trial_id
        logger.info(f"SLURM Worker detected. Executing Trial {tn}")
        _mojo_model, trial_status, _ = self.execute_single_trial(
            trial_num=tn,
            seed=self.seed,
            overrides_payload=global_overrides.model_dump(),
        )

        return trial_status.completion == Completion.ERROR

    job_trial_nums = trial_nums if trial_nums else self.config.trial_nums

    # initialize the status tracker
    status_tracker = JobStatus(
        workdir=self.workdir.resolve(),
        job_type=JobType.MONTE_CARLO,
        execution_mode=ExecutionMode.LOCAL,
        n_proc=self.config.n_proc,
        seed=self.seed,
        padding_style=self.config.padding_style,
        generator=MojoRunner.inspect_protocol(self.generator),
        runtime=MojoRunner.inspect_protocol(self.runtime),
        objective=MojoRunner.inspect_protocol(self.objective),
        args_used=describe_args(self.args),
        kwargs_used=describe_kwargs(self.kwargs),
        trial_nums=job_trial_nums,
    )

    # decide which trials to execute
    if self.config.resume:
        self._renumber_trial_folders(
            self.workdir.resolve(), self.config.padding_style
        )
        status_tracker.refresh_from_disk(n_proc=self.config.n_proc)
    status_tracker.dump_to_path(self.workdir / JOB_STATUS_FNAME)

    to_run = status_tracker.pending_trial_nums

    if not to_run:
        logger.info("All trials were already completed. Nothing to do.")
        return bool(status_tracker.unsuccessful_trial_nums)

    if self.config.is_parallel:
        logger.info(
            f"Running {len(to_run)} trials with {self.config.n_proc} processors. {status_tracker.n_done}/{self.config.n_trial} ({status_tracker.progress:.2%}) trials completed."
        )
        # needed for logging on Windows
        with multiprocessing.Manager() as m:
            log_queue = m.Queue()

            parent_log_level = logging.getLogger().getEffectiveLevel()
            listener = QueueListener(log_queue, *logging.getLogger().handlers)
            listener.start()

            executor = ProcessPoolExecutor(
                max_workers=self.config.n_proc,
                initializer=worker_init,
                initargs=(log_queue, parent_log_level),
            )
            try:
                future_to_tn = {
                    executor.submit(
                        self._execute_trial_subprocess,
                        tn,
                        self.seed,
                        global_overrides.model_dump(),
                    ): tn
                    for tn in to_run
                }
                for f in as_completed(future_to_tn):
                    tn = future_to_tn[f]
                    try:
                        trial_status = f.result()
                        status_tracker.update_trial(status=trial_status)
                    except (BdbQuit, KeyboardInterrupt):
                        # user is quitting from breakpoint() or CTRL+C
                        raise
                    except Exception as e:
                        logger.exception(f"Trial {tn} failed: {e}")
                        status_tracker.update_trial(
                            status=TrialStatus(
                                trial_num=tn, completion=Completion.ERROR
                            )
                        )
                    status_tracker.generate_report()
            except (BdbQuit, KeyboardInterrupt):
                # allows killing the job with one CTRL+C
                logger.warning("Interrupt recieved. Stopping all trials.")
                executor.shutdown(wait=False, cancel_futures=True)
                raise
            finally:
                listener.stop()
                executor.shutdown(wait=True)
    else:
        for tn in to_run:
            try:
                _, trial_status, _ = self.execute_single_trial(
                    trial_num=tn,
                    seed=self.seed,
                    overrides_payload=global_overrides.model_dump(),
                )
                status_tracker.update_trial(
                    status=trial_status,
                )
            except (BdbQuit, KeyboardInterrupt):
                # user is quitting from breakpoint() or CTRL+C
                raise
            except Exception as e:
                logger.exception(f"A trial failed with error: {e}")
                status_tracker.update_trial(
                    status=TrialStatus(trial_num=tn, completion=Completion.ERROR)
                )
            status_tracker.generate_report()

    status_tracker.generate_report(alert_generation=True)
    return bool(status_tracker.unsuccessful_trial_nums)

get_slurm_array_string staticmethod

Python
get_slurm_array_string(ids: list[int]) -> str

Collapses [0, 1, 2, 5, 6] into '0-2,5-6' for SLURM.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_array_string(ids: list[int]) -> str:
    """Collapses [0, 1, 2, 5, 6] into '0-2,5-6' for SLURM."""
    if not ids:
        return ""

    ranges = []
    # Identify groups of consecutive integers
    for _, group in itertools.groupby(
        enumerate(sorted(ids)), lambda x: x[1] - x[0]
    ):
        group = list(group)
        start = group[0][1]
        end = group[-1][1]
        if start == end:
            ranges.append(str(start))
        else:
            ranges.append(f"{start}-{end}")

    return ",".join(ranges)

get_slurm_partitions staticmethod

Python
get_slurm_partitions() -> tuple[list[str], str | None]

Queries sinfo for available partitions and identifies the default.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_partitions() -> tuple[list[str], str | None]:
    """Queries sinfo for available partitions and identifies the default."""
    try:
        result = subprocess.run(
            ["sinfo", "-h", "--format=%P"],
            capture_output=True,
            text=True,
            timeout=5,
        )
        if result.returncode == 0:
            raw_partitions = [
                p.strip() for p in result.stdout.splitlines() if p.strip()
            ]

            default_partition = None
            clean_partitions = []

            for p in raw_partitions:
                if p.endswith("*"):
                    name = p.replace("*", "")
                    default_partition = name
                    clean_partitions.append(name)
                else:
                    clean_partitions.append(p)

            return sorted(list(set(clean_partitions))), default_partition
    except Exception:
        pass
    return [], None

normalize_to_mb staticmethod

Python
normalize_to_mb(mem_str: str) -> int

Converts SLURM memory strings (e.g., '1000', '1G', '1024M', '125.9G') to integer MB, or 0 if the string isn't a recognizable size. See mujoco_mojo.utils.slurm.normalize_to_mb.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def normalize_to_mb(mem_str: str) -> int:
    """Converts SLURM memory strings (e.g., '1000', '1G', '1024M', '125.9G') to integer MB, or 0 if the string isn't a recognizable size. See `mujoco_mojo.utils.slurm.normalize_to_mb`."""
    return normalize_to_mb(mem_str)

format_bytes staticmethod

Python
format_bytes(mb_value: int) -> str

Scales MB back up to the most readable unit (G, T, etc.), with at most one decimal place. The value is rounded down, never up, so a limit shown to the user is never larger than the real limit; normalize_to_mb reads the result back.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def format_bytes(mb_value: int) -> str:
    """Scales MB back up to the most readable unit (G, T, etc.), with at most one decimal place. The value is rounded down, never up, so a limit shown to the user is never larger than the real limit; `normalize_to_mb` reads the result back."""
    units = ["M", "G", "T", "P"]
    value = float(mb_value)
    unit_index = 0

    # keep dividing by 1024 for as long as the next unit is reached
    while value >= 1024 and unit_index < len(units) - 1:
        value /= 1024
        unit_index += 1

    # floor to one decimal: rounding up could show more memory than the node has
    floored = math.floor(value * 10) / 10
    # if it's a whole number (like 1.0G), show it as 1G, otherwise one decimal place (like 1.5G)
    if floored.is_integer():
        return f"{int(floored)}{units[unit_index]}"
    return f"{floored:.1f}{units[unit_index]}"

get_slurm_node_mem_limit staticmethod

Python
get_slurm_node_mem_limit(partition_name: str) -> str

Finds the MINIMUM RealMemory limit, normalized to MB.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_node_mem_limit(partition_name: str) -> str:
    """Finds the MINIMUM RealMemory limit, normalized to MB."""
    try:
        # 1. Get nodes from partition
        part_info = subprocess.run(
            ["scontrol", "show", "partition", partition_name, "-o"],
            capture_output=True,
            text=True,
        ).stdout
        node_match = re.search(r"\bNodes=(\S+)", part_info)
        if not node_match:
            return "<UNKNOWN>"

        # 2. Get node info (can handle ranges like c[1-2])
        node_info = subprocess.run(
            ["scontrol", "show", "node", node_match.group(1), "-o"],
            capture_output=True,
            text=True,
        ).stdout

        # 3. Find all RealMemory values (capturing optional suffixes)
        # Regex captures digits and any trailing letters (like G or M)
        mem_matches = re.findall(r"\bRealMemory=(\d+(?:\.\d+)?[KMGTP]?)", node_info)
        if mem_matches:
            # Normalize every match to MB and find the lowest one
            min_mb = min(MojoRunner.normalize_to_mb(m) for m in mem_matches)
            return MojoRunner.format_bytes(min_mb)

    except Exception:
        pass

    return "<UNKNOWN>"

get_slurm_cpu_limit staticmethod

Python
get_slurm_cpu_limit(partition_name: str) -> str

Finds the minimum of the max allowed CPUs (CPUTot) among nodes in a partition.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_cpu_limit(partition_name: str) -> str:
    """Finds the minimum of the max allowed CPUs (CPUTot) among nodes in a partition."""
    try:
        # 1. Get the nodes in the partition
        part_cmd = ["scontrol", "show", "partition", partition_name, "-o"]
        part_info = subprocess.run(part_cmd, capture_output=True, text=True).stdout

        node_match = re.search(r"\bNodes=(\S+)", part_info)
        if not node_match:
            return "<UNKNOWN>"

        # 2. Get the node info
        node_cmd = ["scontrol", "show", "node", node_match.group(1), "-o"]
        nodes_info = subprocess.run(node_cmd, capture_output=True, text=True).stdout

        # 3. Find all CPUTot values (The total physical/logical CPUs on the node)
        cpu_values = re.findall(r"\bCPUTot=(\d+)", nodes_info)

        if cpu_values:
            # Find the minimum to ensure any node can handle the task
            return str(min(int(v) for v in cpu_values))

    except Exception:
        pass

    return "<UNKNOWN>"

slurm_time_to_seconds staticmethod

Python
slurm_time_to_seconds(time_str: str) -> int

Converts a SLURM time limit to total seconds, or -1 for UNLIMITED. See mujoco_mojo.utils.slurm.slurm_time_to_seconds.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def slurm_time_to_seconds(time_str: str) -> int:
    """Converts a SLURM time limit to total seconds, or -1 for `UNLIMITED`. See `mujoco_mojo.utils.slurm.slurm_time_to_seconds`."""
    return slurm_time_to_seconds(time_str)

get_slurm_time_limit staticmethod

Python
get_slurm_time_limit(partition_name: str) -> str

Finds the MaxTime limit for a specific partition.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_slurm_time_limit(partition_name: str) -> str:
    """Finds the MaxTime limit for a specific partition."""
    try:
        # Get partition info
        part_cmd = ["scontrol", "show", "partition", partition_name, "-o"]
        part_info = subprocess.run(part_cmd, capture_output=True, text=True).stdout

        # Look for MaxTime= followed by the time string (e.g., 1-00:00:00 or UNLIMITED)
        time_match = re.search(r"\bMaxTime=(\S+)", part_info)
        if time_match:
            return str(time_match.group(1))

    except Exception:
        pass

    return "<UNKNOWN>"

get_max_array_size staticmethod

Python
get_max_array_size() -> int

Queries the global SLURM configuration for MaxArraySize.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def get_max_array_size() -> int:
    """Queries the global SLURM configuration for MaxArraySize."""
    try:
        result = subprocess.run(
            ["scontrol", "show", "config"], capture_output=True, text=True
        ).stdout
        match = re.search(r"MaxArraySize=(\d+)", result)
        return int(match.group(1)) if match else 1001
    except Exception:
        return 1001

slurm_mojo_command staticmethod

Python
slurm_mojo_command() -> Path

The mujoco-mojo executable next to the running interpreter, which the compute nodes use to run each trial.

Source code in src/mujoco_mojo/utils/runner.py
Python
@staticmethod
def slurm_mojo_command() -> Path:
    """The `mujoco-mojo` executable next to the running interpreter, which the compute nodes use to run each trial."""
    return Path(sys.executable).parent.resolve() / "mujoco-mojo"

prepare_slurm_job

Python
prepare_slurm_job(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> SlurmJob | None

Sets up the workdir for a SLURM submission without asking anything.

Creates the logs folder, persists the global overrides for the workers, writes job_status.json, and works out which trials still need to run (honoring resume).

Returns:

Type Description
SlurmJob | None

The job, or None when every trial was already completed.

Source code in src/mujoco_mojo/utils/runner.py
Python
def prepare_slurm_job(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> SlurmJob | None:
    """
    Sets up the workdir for a SLURM submission without asking anything.

    Creates the logs folder, persists the global overrides for the workers, writes `job_status.json`, and works out which trials still need to run (honoring `resume`).

    Returns:
        The job, or `None` when every trial was already completed.

    """
    (self.workdir / "logs").mkdir(parents=True, exist_ok=True)

    # persist overrides so workers can access them
    overrides_path = self.workdir.resolve() / "global_overrides.json"
    has_overrides = len(global_overrides) > 0
    if has_overrides:
        logger.info(f"Persisting global overrides to {overrides_path}")
        overrides_path.write_text(global_overrides.model_dump_json())

    job_trial_nums = trial_nums if trial_nums else self.config.trial_nums
    status_tracker = JobStatus(
        workdir=self.workdir.resolve(),
        job_type=JobType.MONTE_CARLO,
        execution_mode=ExecutionMode.SLURM,
        n_proc=self.config.n_proc,
        seed=self.seed,
        padding_style=self.config.padding_style,
        generator=MojoRunner.inspect_protocol(self.generator),
        runtime=MojoRunner.inspect_protocol(self.runtime),
        objective=MojoRunner.inspect_protocol(self.objective),
        args_used=describe_args(self.args),
        kwargs_used=describe_kwargs(self.kwargs),
        trial_nums=job_trial_nums,
    )

    # decide which trials to execute
    if self.config.resume:
        self._renumber_trial_folders(
            self.workdir.resolve(), self.config.padding_style
        )
        status_tracker.refresh_from_disk(n_proc=self.config.n_proc)
    status_tracker.dump_to_path(self.workdir / JOB_STATUS_FNAME)

    to_run = status_tracker.pending_trial_nums
    if not to_run:
        logger.info("All trials were already completed. Nothing to do.")
        return None
    logger.info(f"{len(to_run)} trials were identified for running.")

    return SlurmJob(
        status=status_tracker,
        to_run=to_run,
        overrides_path=overrides_path,
        has_overrides=has_overrides,
    )

slurm_worker_command

Python
slurm_worker_command(job: SlurmJob) -> str

What each array task runs: one trial, picked by the array index, on a single process.

Source code in src/mujoco_mojo/utils/runner.py
Python
def slurm_worker_command(self, job: SlurmJob) -> str:
    """What each array task runs: one trial, picked by the array index, on a single process."""
    runtime_flag = f'--runtime "{self.runtime_path}"' if self.runtime_path else ""
    seed_flag = f"--seed {self.seed}" if self.seed is not None else ""
    overrides_flag = (
        f'--overrides "{job.overrides_path}"' if job.has_overrides else ""
    )
    return (
        f"{self.slurm_mojo_command()} run single "
        f'--generator "{self.generator_path}" '
        f"{runtime_flag} {seed_flag} {overrides_flag} "
        f'--workdir "{self.workdir.resolve()}" '
        f"{self.shared_argument_flags()} "
        f"--padding {self.config.padding_width} "  # name the trial folder like the orchestrator expects
        f"--trial-num $SLURM_ARRAY_TASK_ID "  # execute its own trial_num
        f"--execution-mode local "  # using local since slurm will just send us back to this method
        f"--n-proc 1"  # a worker only needs 1 process
    )

write_slurm_script

Python
write_slurm_script(
    job: SlurmJob, config: SlurmConfig, console: Console
) -> Path

Writes mujoco_mojo_submit.sh for job, adding the extra #SBATCH lines and environment variables from the settings files (and printing what they are).

Source code in src/mujoco_mojo/utils/runner.py
Python
def write_slurm_script(
    self, job: SlurmJob, config: SlurmConfig, console: Console
) -> Path:
    """Writes `mujoco_mojo_submit.sh` for `job`, adding the extra `#SBATCH` lines and environment variables from the settings files (and printing what they are)."""
    from mujoco_mojo.settings import MujocoMojoSettings

    slurm_settings = MujocoMojoSettings().slurm
    _print_slurm_extras(console, slurm_settings)

    script = build_submission_script(
        job_name=config.job_name or f"mojo-sim-{job.status.id}",
        array_range=self.get_slurm_array_string(job.to_run),
        workdir=self.workdir.resolve(),
        config=config,
        worker_command=self.slurm_worker_command(job),
        extra_sbatch_lines=slurm_settings.sbatch_lines(),
        extra_env_lines=slurm_settings.env_lines(),
    )
    script_path = (self.workdir / "mujoco_mojo_submit.sh").resolve()
    script_path.write_text(script, encoding="utf-8")
    logger.info(f"SLURM submission script written to {script_path}")
    return script_path

submit_slurm_script

Python
submit_slurm_script(
    job: SlurmJob, script_path: Path
) -> SlurmSubmission

Runs sbatch on the script and, once it is accepted, saves the SLURM job id in job_status.json so the job can be looked up (and watched) later.

Source code in src/mujoco_mojo/utils/runner.py
Python
def submit_slurm_script(self, job: SlurmJob, script_path: Path) -> SlurmSubmission:
    """Runs `sbatch` on the script and, once it is accepted, saves the SLURM job id in `job_status.json` so the job can be looked up (and watched) later."""
    logger.info(f"Submitting {len(job.to_run)} trials...")
    try:
        result = subprocess.run(
            ["sbatch", "--parsable", str(script_path)],
            capture_output=True,
            text=True,
        )
    except OSError as exc:
        return SlurmSubmission(script_path, message=f"Could not run sbatch: {exc}")
    if result.returncode != 0:
        return SlurmSubmission(
            script_path, message=(result.stderr or result.stdout).strip()
        )

    job_id = parse_job_id(result.stdout)
    job.status.slurm_job_id = job_id
    job.status.dump_to_path(self.workdir / JOB_STATUS_FNAME)
    return SlurmSubmission(
        script_path,
        submitted=True,
        job_id=job_id,
        message=f"Submitted batch job {job_id}"
        if job_id
        else result.stdout.strip(),
    )

slurm_limit_problems

Python
slurm_limit_problems(
    job: SlurmJob, config: SlurmConfig
) -> list[str]

Everything in the request that exceeds what the cluster reports (CPUs, memory, and time for the partition, and the array size). Limits SLURM cannot report are not checked.

Source code in src/mujoco_mojo/utils/runner.py
Python
def slurm_limit_problems(self, job: SlurmJob, config: SlurmConfig) -> list[str]:
    """Everything in the request that exceeds what the cluster reports (CPUs, memory, and time for the partition, and the array size). Limits SLURM cannot report are not checked."""
    partition = config.partition or ""
    checks = (
        cpu_problem(config.cpus_per_task, self.get_slurm_cpu_limit(partition)),
        mem_problem(config.mem, self.get_slurm_node_mem_limit(partition)),
        time_problem(config.time_limit, self.get_slurm_time_limit(partition)),
        array_problem(len(job.to_run), self.get_max_array_size()),
    )
    return [problem for problem in checks if problem is not None]

submit_slurm

Python
submit_slurm(
    config: SlurmConfig,
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    *,
    submit: bool = True,
    skip_checks: bool = False,
    console: Console | None = None,
) -> SlurmSubmission | None

Initializes a workdir and submits it to SLURM from a SlurmConfig, without asking anything.

Parameters:

Name Type Description Default
config SlurmConfig

The resources to request.

required
global_overrides NamedValueDict[NDArray]

Overrides persisted for the workers.

NamedValueDict[NDArray]()
trial_nums list[int] | None

Specific trials to run, instead of all of them.

None
clean_workdir bool

Wipe the workdir first.

False
cleanup_delay int

Seconds of countdown before wiping.

10
submit bool

Run sbatch. When False the workdir and script are written and nothing is submitted.

True
skip_checks bool

Submit even if the request exceeds a limit the cluster reports.

False
console Console | None

Where to print what happened.

None

Returns:

Type Description
SlurmSubmission | None

What was written and submitted, or None when every trial was already completed.

Raises:

Type Description
ValueError

If generator_path is not set (or runtime_path, when there is a runtime), or the request exceeds a cluster limit and skip_checks is not set.

Source code in src/mujoco_mojo/utils/runner.py
Python
def submit_slurm(
    self,
    config: SlurmConfig,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
    clean_workdir: bool = False,
    cleanup_delay: int = 10,
    *,
    submit: bool = True,
    skip_checks: bool = False,
    console: Console | None = None,
) -> SlurmSubmission | None:
    """
    Initializes a workdir and submits it to SLURM from a `SlurmConfig`, without asking anything.

    Args:
        config: The resources to request.
        global_overrides: Overrides persisted for the workers.
        trial_nums: Specific trials to run, instead of all of them.
        clean_workdir: Wipe the workdir first.
        cleanup_delay: Seconds of countdown before wiping.
        submit: Run `sbatch`. When `False` the workdir and script are written and nothing is submitted.
        skip_checks: Submit even if the request exceeds a limit the cluster reports.
        console: Where to print what happened.

    Returns:
        What was written and submitted, or `None` when every trial was already completed.

    Raises:
        ValueError: If `generator_path` is not set (or `runtime_path`, when there is a runtime), or the request exceeds a cluster limit and `skip_checks` is not set.

    """
    from rich.console import Console

    if not isinstance(self.config, MonteCarloConfig):
        msg = f"A SLURM configuration for {self.config.__class__.__name__} has not been implemented."
        logger.error(msg)
        raise NotImplementedError(msg)

    # the workers are separate `mujoco-mojo` processes that import each function by its dotted path
    missing = []
    if self.generator_path is None:
        missing.append("generator_path")
    if (
        self.runtime is not None
        and self.runtime is not DEFAULT_RUNTIME
        and self.runtime_path is None
    ):
        missing.append("runtime_path")
    if missing:
        msg = f"Set {' and '.join(missing)} (for example 'sim.generate') so the compute nodes can import the function."
        logger.error(msg)
        raise ValueError(msg)

    console = console or Console()
    self._prepare_run(clean_workdir, cleanup_delay)
    job = self.prepare_slurm_job(global_overrides, trial_nums)
    if job is None:
        console.print(
            "[green]All trials were already completed.[/] Nothing to submit."
        )
        return None

    if not skip_checks:
        problems = self.slurm_limit_problems(job, config)
        if problems:
            msg = (
                "The request exceeds what the cluster reports:\n  - "
                + "\n  - ".join(problems)
                + "\nChange the request, or skip these checks to submit anyway."
            )
            logger.error(msg)
            raise ValueError(msg)

    script_path = self.write_slurm_script(job, config, console)
    if not submit:
        console.print(
            f"\n[yellow]Nothing was submitted.[/] The workdir is ready; submit it with:\n[bold green]sbatch {script_path}[/]"
        )
        return SlurmSubmission(script_path)

    submission = self.submit_slurm_script(job, script_path)
    if submission.submitted:
        console.print(f"\n[bold green]Success![/] {submission.message}")
    else:
        logger.error(f"SLURM Submission Failed: {submission.message}")
    return submission

orchestrate_slurm_monte_carlo

Python
orchestrate_slurm_monte_carlo(
    global_overrides: NamedValueDict[
        NDArray
    ] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool

Orchestrates a Monte Carlo SLURM submission interactively.

Prompts for the resources (checking each against the partition's limits), collects them in a SlurmConfig, and then hands everything to the same code submit_slurm uses. Just before submitting it offers to keep watching the job, which keeps job_status.json and the runtime report current (see watch_job).

Source code in src/mujoco_mojo/utils/runner.py
Python
def orchestrate_slurm_monte_carlo(
    self,
    global_overrides: NamedValueDict[NDArray] = NamedValueDict[NDArray](),
    trial_nums: list[int] | None = None,
) -> bool:
    """
    Orchestrates a Monte Carlo SLURM submission interactively.

    Prompts for the resources (checking each against the partition's limits), collects them in a `SlurmConfig`, and then hands everything to the same code `submit_slurm` uses. Just before submitting it offers to keep watching the job, which keeps `job_status.json` and the runtime report current (see `watch_job`).
    """
    from rich.console import Console
    from rich.markup import escape
    from rich.prompt import Confirm, IntPrompt, Prompt

    console = Console()
    project_root = Path.cwd().resolve()

    job = self.prepare_slurm_job(global_overrides, trial_nums)
    if job is None:
        return False

    def proceed_despite(message: str, note: str = "") -> bool:
        console.print(f"\n[bold red]WARNING:[/] {message}")
        if note:
            console.print(f"[red]{note}[/]\n")
        return Confirm.ask("Do you want to proceed anyway?", default=False)

    # ask for sbatch settings with a bunch of console inputs with default values
    available_partitions, default_partition = self.get_slurm_partitions()

    console.print(
        "\n[bold cyan]MuJoCo Mojo Orchestrator: SLURM Resource Setup[/bold cyan]"
    )
    console.print(f"\t            [dim]Python:[/dim] {sys.executable}")
    console.print(f"\t              [dim]Root:[/dim] {project_root}")
    console.print(f"\t[dim]mujoco-mojo binary:[/dim] {self.slurm_mojo_command()}\n")

    # Standard colors only for Rich compatibility
    job_name = Prompt.ask(
        "  [white]Job Name[/]", default=f"mojo-sim-{job.status.id}"
    )
    if available_partitions:
        # Use the actual SLURM default if we found one, otherwise the first in list
        initial_default = (
            default_partition if default_partition else available_partitions[0]
        )

        partition = Prompt.ask(
            "  [white]Partition[/]",
            choices=available_partitions,
            default=initial_default,
        )
    else:
        partition = Prompt.ask(
            "  [white]Partition[/] [dim](optional)[/]", default=""
        )

    # === get partition limits ===
    cpu_limit = self.get_slurm_cpu_limit(partition)
    mem_limit = self.get_slurm_node_mem_limit(partition)
    time_limit_hint = self.get_slurm_time_limit(partition)

    # === get cpus per task ===
    cpus_per_task = max(
        1,
        IntPrompt.ask(
            f"  [white]CPUs per task[/] [dim](Node Limit: {cpu_limit})[/]",
            default=1,
        ),
    )
    if problem := cpu_problem(cpus_per_task, cpu_limit):
        if not proceed_despite(problem):
            return True

    # === get memory ===
    while True:
        mem_text = Prompt.ask(
            f"  [white]Memory per node[/] (e.g., 256M or 1.5G) [dim](Node Limit: {mem_limit})[/]",
            default="" if mem_limit == UNKNOWN_LIMIT else mem_limit,
        ).strip()
        if not mem_text or normalize_to_mb(mem_text) > 0:
            break
        console.print(
            f"[bold red]ERROR:[/] '{escape(mem_text)}' is not a memory size. "
            "Use a number with an optional unit, for example 512M or 1.5G."
        )
    mem = mem_text or None
    if problem := mem_problem(mem, mem_limit):
        if not proceed_despite(
            problem, "This job will likely be rejected by SLURM."
        ):
            return True

    # === get time ===
    while True:
        time_limit = Prompt.ask(
            f"  [white]Time limit[/] (e.g., 01:00:00 or 1-12:00:00) [dim](Partition Limit: {time_limit_hint})[/]",
            default="01:00:00",
        ).strip()
        try:
            slurm_time_to_seconds(time_limit)
            break
        except ValueError:
            console.print(
                f"[bold red]ERROR:[/] '{escape(time_limit)}' is not a SLURM time limit."
            )
    if problem := time_problem(time_limit, time_limit_hint):
        if not proceed_despite(problem):
            return True

    # === get concurrency throttle ===
    max_concurrent_text = Prompt.ask(
        "  [white]Max concurrent tasks[/] [dim](blank = no limit, let SLURM decide)[/]",
        default="",
    )
    if max_concurrent_text and not max_concurrent_text.isdigit():
        console.print(
            f"\n[bold red]WARNING:[/] '{escape(max_concurrent_text)}' is not a number. Ignoring."
        )
        max_concurrent_text = ""
    max_concurrent = (
        int(max_concurrent_text) if max_concurrent_text.strip("0") else None
    )

    # === the project root ===
    add_root_to_pythonpath = True
    if str(project_root) not in os.getenv("PYTHONPATH", ""):
        console.print(
            f"\n[yellow]Warning:[/] Project root [italic]{project_root}[/] is not in your PYTHONPATH."
        )
        add_root_to_pythonpath = Confirm.ask(
            "Should Mojo automatically include it in the SLURM submission?",
            default=True,
        )

    config = SlurmConfig(
        job_name=job_name,
        partition=partition or None,
        cpus_per_task=cpus_per_task,
        mem=mem,
        time_limit=time_limit,
        max_concurrent=max_concurrent,
        add_root_to_pythonpath=add_root_to_pythonpath,
        project_root=project_root,
    )

    if problem := array_problem(len(job.to_run), self.get_max_array_size()):
        console.print(f"\n[bold red]ERROR:[/] {problem}")
        if not Confirm.ask("Proceed anyway?", default=False):
            return True

    script_path = self.write_slurm_script(job, config, console)

    watch_cmd = (
        f'mujoco-mojo run watch-workdir --workdir "{self.workdir.resolve()}"'
    )

    # final submission
    if not Confirm.ask(
        f"\n[cyan]Submit {len(job.to_run)} trials to SLURM now?[/]", default=True
    ):
        # deferred submission; the status file already exists, so the watcher works
        # for a job submitted by hand too
        console.print(
            f"\n[yellow]Orchestration complete.[/] Submit manually with:\n[bold green]sbatch {script_path}[/]"
        )
        console.print(
            f"\n[dim]To keep the status file and runtime report current once it is running, run:[/] [green]{watch_cmd}[/]"
        )
        return False

    # asked now because the status file the watcher keeps current already exists
    watch = Confirm.ask(
        "Keep the job status and runtime report up to date until the job finishes?",
        default=True,
    )

    submission = self.submit_slurm_script(job, script_path)
    if not submission.submitted:
        logger.error(f"SLURM Submission Failed: {submission.message}")
        console.print(
            f"\n[bold red]SLURM submission failed:[/] {escape(submission.message)}"
        )
        return True

    job_id = submission.job_id or "UNKNOWN"
    console.print(f"\n[bold green]Success![/] {submission.message}")

    # === Monitoring Dashboard ===
    console.print("\n[bold cyan]Monitoring Status:[/bold cyan]")
    console.print(f"  - [white]Check status:[/]       [green]squeue -j {job_id}[/]")
    console.print(
        f"  - [white]Watch live:[/]         [green]watch -n 1 squeue -j {job_id}[/]"
    )
    console.print(
        f"  - [white]View first log:[/]     [green]tail -f {self.workdir.resolve()}/logs/trial_0.log[/]"
    )
    console.print(f"  - [white]Cancel all trials:[/]  [green]scancel {job_id}[/]")
    console.print(
        f"\n[dim]Logs are being written to: {self.workdir.resolve()}/logs/[/]"
    )

    if not watch:
        console.print(
            f"\n[dim]To keep the status file and runtime report current later, run:[/] [green]{watch_cmd}[/]"
        )
        return False

    try:
        watch_job(self.workdir, n_proc=max(1, self.config.n_proc), console=console)
    except KeyboardInterrupt:
        console.print(
            f"\n[yellow]Stopped watching.[/] The job keeps running. Resume with: [green]{watch_cmd}[/]"
        )
    return False

MojoRuntime

Bases: Protocol

Definition of a function that executes a generated MojoModel model.

MonteCarloConfig

Bases: BaseConfig

n_proc class-attribute instance-attribute

Python
n_proc: int = DEFAULT_N_PROC

Number of proccesses to allow.

This value is used to determine how many parallel jobs can be run. It is also used for the discovery of trial status. Using a value of 1 will result in the slowest runtime, but highest reliability.

Important

Be a good citizen. Use a reasonable number if you are working on a shared resource. You are a jerk if you use everything.

resume class-attribute instance-attribute

Python
resume: bool = DEFAULT_RESUME

Whether to resume a study if the study already exists.

padding class-attribute instance-attribute

Python
padding: int | None = Field(default=None, ge=1)

Zero-padding width of the trial folder names (for example 3 gives trial_007). When unset, the width is derived from n_trial so every trial in a job sorts consistently; set it when a process only knows about one trial of a larger job, such as a SLURM worker.

padding_style property

Python
padding_style: str

This dynamically defines the padding style for trial numbers. This is helpful to ensure the filesystem consistently sorts the trials.

Examples: - Suppose you n_trials is 2000 (and the nominal trial_num is 0) - This method would return 04d - Trial number 0 maps to 0000 - Trial number 123 maps to 0123 - Trial number 1999 will still map to 1999

n_trial class-attribute instance-attribute

Python
n_trial: int = DEFAULT_MC_N_TRIAL

Number of trials to run.

You are able to resume a previous job and modify the number of runs desired by changing this value. A job already in progress will not be dynamically stopped though if you change this value at runtime.

OptimizerConfig

Bases: BaseConfig

n_proc class-attribute instance-attribute

Python
n_proc: int = DEFAULT_N_PROC

Number of proccesses to allow.

This value is used to determine how many parallel jobs can be run. It is also used for the discovery of trial status. Using a value of 1 will result in the slowest runtime, but highest reliability.

Important

Be a good citizen. Use a reasonable number if you are working on a shared resource. You are a jerk if you use everything.

resume class-attribute instance-attribute

Python
resume: bool = DEFAULT_RESUME

Whether to resume a study if the study already exists.

padding class-attribute instance-attribute

Python
padding: int | None = Field(default=None, ge=1)

Zero-padding width of the trial folder names (for example 3 gives trial_007). When unset, the width is derived from n_trial so every trial in a job sorts consistently; set it when a process only knows about one trial of a larger job, such as a SLURM worker.

padding_style property

Python
padding_style: str

This dynamically defines the padding style for trial numbers. This is helpful to ensure the filesystem consistently sorts the trials.

Examples: - Suppose you n_trials is 2000 (and the nominal trial_num is 0) - This method would return 04d - Trial number 0 maps to 0000 - Trial number 123 maps to 0123 - Trial number 1999 will still map to 1999

n_trial class-attribute instance-attribute

Python
n_trial: int = DEFAULT_OP_N_TRIAL

Number of trials to run.

study_name class-attribute instance-attribute

Python
study_name: str = DEFAULT_OP_STUDY_NAME

Unique identifier for the Optuna study.

direction instance-attribute

Python
direction: Direction

Whether we want to find the lowest or highest objective value.

timeout class-attribute instance-attribute

Python
timeout: float | None = DEFAULT_OP_TIMEOUT

Stop the study after this many seconds, regardless of trial count.

storage class-attribute instance-attribute

Python
storage: str | None = DEFAULT_OP_STORAGE

Database URL (e.g., 'sqlite:///study.db') for multi-node persistence.

sampler class-attribute instance-attribute

Python
sampler: Sampler = DEFAULT_OP_SAMPLER

The search algorithm. TPE is generally best for noisy physics.

evals_per_trial class-attribute instance-attribute

Python
evals_per_trial: int = Field(
    default=DEFAULT_OP_EVALS_PER_TRIAL, ge=1
)

Number of times to run the sim with different seeds per trial. The average score is returned to Optuna.

Reduces 'lucky' trials in noisy physics.

refine_search_factor class-attribute instance-attribute

Python
refine_search_factor: float | None = Field(
    default=DEFAULT_OP_REFINE_SEARCH_FACTOR, gt=0, lt=1
)

If set (e.g., 0.5), and resume is True, the Runner will shrink the search space bounds by this factor around the current best trial to focus on local refinement.

Smaller values will more aggressively refine the search space.

prune_failed_trials class-attribute instance-attribute

Python
prune_failed_trials: bool = DEFAULT_OP_PRUNE_FAILED_TRIALS

Whether to immediately stop trials that violate physical constraints (e.g., Mujoco instability) to save compute time.

Trial dataclass

Python
Trial(
    trial_num: int,
    base_dir: Path,
    xml_name: str,
    model_config_name: str | None,
    padding_style: str,
)

Handles the lifecycle of a single simulation run.

The Trial object is responsible for the 'dirty work' of a Monte Carlo run: - Creating directories - Writing the MJCF XML - Saving the configuration snapshot - Triggering the physics runtime.

trial_num instance-attribute

Python
trial_num: int

Unique identifier for this trial iteration.

base_dir instance-attribute

Python
base_dir: Path

Root directory where all simulation trials are stored.

xml_name instance-attribute

Python
xml_name: str

Filename for the generated MJCF XML (e.g., 'model.xml').

model_config_name instance-attribute

Python
model_config_name: str | None

Filename for the serialized MojoModel configuration (e.g., 'config.json').

padding_style instance-attribute

Python
padding_style: str

Format specifier for directory naming (e.g., '04d').

trial_dir property

Python
trial_dir: Path

The absolute path to this trial's unique workspace.

Example

If base_dir is './sims' and trial_num is 7 with '03d' padding, this returns './sims/trial_007'.

xml_path property

Python
xml_path: Path

The full path to the MJCF XML file for this trial.

model_config_path property

Python
model_config_path: Path

The full path to the JSON configuration file for this trial.

named_value_path property

Python
named_value_path: Path

The full path to the JSON NamedValue file for this trial.

run

Python
run(
    generator: MojoGenerator,
    runtime: MojoRuntime | None,
    seed: int | None,
    overrides: NamedValueDict[NDArray],
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]

Executes the complete simulation pipeline for this trial.

This method coordinates three main phases: 1. Generation: Calls the user-provided generator to build a MojoModel model. 2. Persistence: Creates the workspace and writes the model/config to disk. 3. Execution: Triggers the physics runtime if one is provided.

Parameters:

Name Type Description Default
generator MojoGenerator

Function that returns a MojoModel instance.

required
runtime MojoRuntime | None

Optional function to run the simulation (MuJoCo).

required
seed int | None

Seed to use to define the trial.

required
overrides NamedValueDict[NDArray]

Key-value pairs that override random distributions.

required
args Sequence[Any]

Positional arguments passed to the generator and the runtime.

required
kwargs Mapping[str, Any]

Keyword arguments, each function receiving only the ones it accepts.

required

Returns:

Type Description
tuple[MojoModel | None, TrialStatus, MjState | None]

The MojoModel object for the trial or None if there was a failure prior to generating the MojoModel and the status of the trial.

Source code in src/mujoco_mojo/utils/runner.py
Python
def run(
    self,
    generator: MojoGenerator,
    runtime: MojoRuntime | None,
    seed: int | None,
    overrides: NamedValueDict[NDArray],
    args: Sequence[Any],
    kwargs: Mapping[str, Any],
) -> tuple[MojoModel | None, TrialStatus, MjState | None]:
    """
    Executes the complete simulation pipeline for this trial.

    This method coordinates three main phases:
    1.  **Generation**: Calls the user-provided generator to build a `MojoModel` model.
    2.  **Persistence**: Creates the workspace and writes the model/config to disk.
    3.  **Execution**: Triggers the physics runtime if one is provided.

    Args:
        generator: Function that returns a `MojoModel` instance.
        runtime: Optional function to run the simulation (MuJoCo).
        seed: Seed to use to define the trial.
        overrides: Key-value pairs that override random distributions.
        args: Positional arguments passed to the generator and the runtime.
        kwargs: Keyword arguments, each function receiving only the ones it accepts.

    Returns:
        The `MojoModel` object for the trial or None if there was a failure prior to generating the MojoModel and the status of the trial.

    """
    status = TrialStatus(trial_num=self.trial_num)
    status._path = self.trial_dir / TRIAL_STATUS_FNAME

    # set up a per-trial log file capturing everything logged during this trial
    self.trial_dir.mkdir(parents=True, exist_ok=True)
    trial_log_handler = get_trial_log_handler(self.trial_dir / "mojo.log")
    root_logger = logging.getLogger()
    root_logger.addHandler(trial_log_handler)

    with status.record_step(step_name="pending"):
        pass

    from mujoco_mojo.runtime.requirements_manager import RequirementSatisfied
    from mujoco_mojo.runtime.runtime_manager import SimulationStopped

    result = None
    state = None
    runtime_manager: RuntimeManager | None = None
    try:
        # 1. Generate
        with status.record_step(step_name="generating"):
            logger.info(f"Generating trial_num={self.trial_num}")
            mojo_model = (
                MojoModel()
                .with_overrides(overrides=overrides)
                .with_seed(seed=seed)
                .with_trial_num(self.trial_num)
            )
            mojo_model = generator(
                mojo_model,
                overrides,
                *args,
                **select_kwargs(generator, GENERATOR_FIXED_ARGS, args, kwargs),
            )
            mojo_model._trial_dir = self.trial_dir

            # 2. Setup Workspace & Save Metadata
            logger.info(f"Saving trial_num={self.trial_num} to {self.trial_dir}")

            # bundle assets, this remaps DepPath attributes to point to the shared asset dir
            rel_to_xml = Path(
                os.path.relpath(self.shared_asset_dir, self.trial_dir)
            )
            mojo_model.mjcf.bundle_assets(
                target_dir=self.shared_asset_dir, rel_to_xml=rel_to_xml
            )

            # save XML (with modified DepPath)
            if runtime is None:
                mojo_model.mjcf.write_xml(self.xml_path)
            if self.model_config_name:
                mojo_model.dump_to_path(self.model_config_path)
            self.named_value_path.write_text(mojo_model.named.model_dump_json())

        with status.record_step(step_name="solving"):
            # 3. Execute (if runtime provided)
            if runtime is not None:
                logger.info(f"Executing trial_num={self.trial_num} runtime")
                import mujoco_mojo.runtime as rt

                runtime_manager = rt.RuntimeManager(
                    signal_manager=rt.SignalManager(
                        export_path=self.trial_dir
                        / rt.SignalManager.default_output_name(),
                        unit_system=mojo_model.us,
                    )
                )
                runtime_manager._mojo_model = mojo_model
                state = mojo_model.mjcf.prep_for_sim(
                    self.xml_path, unit_system=mojo_model.us
                )
                result = runtime(
                    mojo_model,
                    runtime_manager,
                    state,
                    *args,
                    **select_kwargs(runtime, RUNTIME_FIXED_ARGS, args, kwargs),
                )
                status.requirements = runtime_manager.requirement_results
            else:
                logger.info(
                    f"No runtime definition was provided for trial_num={self.trial_num} so MuJoCo will not be run."
                )
                result = mojo_model
                state = None

        # serialize again in case new named values were added during the run
        if self.model_config_name:
            mojo_model.dump_to_path(self.model_config_path)
        self.named_value_path.write_text(mojo_model.named.model_dump_json())

        # clear unpicklable collision managers before returing to avoid multiprocessing serialization erros
        mojo_model.clear_unpickleable_data()

        status.step = "done"
        if status.requirements and not all(r.passed for r in status.requirements):
            status.completion = Completion.FAILURE
        else:
            status.completion = Completion.SUCCESS

    except (BdbQuit, KeyboardInterrupt):
        logger.warning("Quit command detected. Exiting execution...")
        raise
    except RequirementSatisfied:
        # a live requirement ended the trial early as a success: complete
        # normally, with the outcome decided by the requirement results
        status.step = "done"
        if runtime_manager is not None:
            status.requirements = runtime_manager.requirement_results
        if status.requirements and not all(r.passed for r in status.requirements):
            status.completion = Completion.FAILURE
        else:
            status.completion = Completion.SUCCESS
    except SimulationStopped:
        status.step = "done"
        status.completion = Completion.TERMINATED
        if runtime_manager is not None:
            status.requirements = runtime_manager.requirement_results
    except Exception as e:
        status.step = "done"
        status.completion = Completion.ERROR
        logger.exception(
            f"Trial {self.trial_num} failed with the following error: {e}"
        )
    finally:
        status.dump_to_path(status._path)
        root_logger.removeHandler(trial_log_handler)
        trial_log_handler.close()

    return result, status, state

ColumnMetadata

Bases: BaseModel

Metadata describing one telemetry column, stored per column in the parquet footer.

The declared fields are the ones mujoco-mojo understands and validates. Any other key is kept as-is (extra="allow"), so callers can attach their own labels. Unset fields (None or an empty string) are omitted when dumping, so the serialized form only carries what was actually tagged.

unit class-attribute instance-attribute

Python
unit: str | None = None

Concrete Pint unit string, e.g. meter / second. When dimension is also set, both must have the same dimensionality.

dimension class-attribute instance-attribute

Python
dimension: str | None = None

Pint dimension expression for the physical quantity, e.g. [length] / [time]. Tags the quantity without committing to a concrete unit, which is the right choice for built-in signals since the modeling unit system isn't knowable.

quantity class-attribute instance-attribute

Python
quantity: str | None = None

Free-form hint that separates quantities Pint cannot tell apart, e.g. torque versus energy.

transform_type class-attribute instance-attribute

Python
transform_type: TransformType | None = None

How this signal's grouped :x/:y/:z or :w/:x/:y/:z components transform under change_frame(). Only set it for channels that are grouped into such a family.

enumeration_map class-attribute instance-attribute

Python
enumeration_map: dict[str, int] | None = None

Labels for an integer-coded signal, mapping each label to its code, e.g. {"IDLE": 0, "RUNNING": 1}. The column still holds the codes (as floats, like all telemetry); convert_enums() swaps them for labels and the Dojo shows the labels on the plot. Codes must be unique. Build it from an enum class with ColumnMetadata.from_enum().

description class-attribute instance-attribute

Python
description: str = ''

Free-text explanation of what this column holds, e.g. Torque the PD controller commands at the elbow, before the actuator's gear ratio. It tells apart columns whose names look alike. An empty string means no description.

__hash__

Python
__hash__() -> int

Hashes the declared scalar fields only (equal objects still hash equal), so instances can key the per-timestep caches. enumeration_map is left out because a dict is not hashable; equality still compares it.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
def __hash__(self) -> int:
    """Hashes the declared scalar fields only (equal objects still hash equal), so instances can key the per-timestep caches. `enumeration_map` is left out because a dict is not hashable; equality still compares it."""
    return hash(
        (
            self.unit,
            self.dimension,
            self.quantity,
            self.transform_type,
            self.description,
        )
    )

__bool__

Python
__bool__() -> bool

False when nothing is set, so if metadata: skips empty metadata.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
def __bool__(self) -> bool:
    """False when nothing is set, so `if metadata:` skips empty metadata."""
    return bool(self._set_values())

__or__

Python
__or__(other: object) -> ColumnMetadata

Merges two metadata objects, with the right side winning where both set a value. Extras are kept. The result is not re-validated (both sides already were, or are validated where they are registered), which keeps per-timestep merges cheap.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
def __or__(self, other: object) -> ColumnMetadata:
    """Merges two metadata objects, with the right side winning where both set a value. Extras are kept. The result is not re-validated (both sides already were, or are validated where they are registered), which keeps per-timestep merges cheap."""
    if not isinstance(other, ColumnMetadata):
        return NotImplemented
    return self.model_copy(update=other._set_values())

from_enum classmethod

Python
from_enum(enum_cls: type[Enum]) -> ColumnMetadata

Builds the metadata for a signal that posts the integer values of enum_cls: an enumeration_map of every member's name to its value (iterating the class, so aliases are skipped), tagged dimensionless since a code has no unit. Raises TypeError if a member's value is not an integer, and ValueError if the class has no members.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
@classmethod
def from_enum(cls, enum_cls: type[Enum]) -> ColumnMetadata:
    """Builds the metadata for a signal that posts the integer values of `enum_cls`: an `enumeration_map` of every member's name to its value (iterating the class, so aliases are skipped), tagged dimensionless since a code has no unit. Raises `TypeError` if a member's value is not an integer, and `ValueError` if the class has no members."""
    mapping: dict[str, int] = {}
    for member in enum_cls:
        value = member.value
        if isinstance(value, bool) or not isinstance(value, int):
            raise TypeError(
                f"{enum_cls.__name__}.{member.name} has value {value!r}; an enumeration_map needs integer codes"
            )
        mapping[member.name] = int(value)
    if not mapping:
        raise ValueError(f"{enum_cls.__name__} has no members to map")
    return dimensionless_metadata() | cls(enumeration_map=mapping)

validated classmethod

Python
validated(value: MetadataLike) -> ColumnMetadata

Validates a metadata object or a plain dict (always, unlike model_validate on an instance), raising a ValidationError naming the bad field.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
@classmethod
def validated(cls, value: MetadataLike) -> ColumnMetadata:
    """Validates a metadata object or a plain dict (always, unlike `model_validate` on an instance), raising a `ValidationError` naming the bad field."""
    return cls.model_validate(
        value.model_dump() if isinstance(value, ColumnMetadata) else dict(value)
    )

unchecked classmethod

Python
unchecked(value: MetadataLike) -> ColumnMetadata

Wraps a plain dict without validating it, for per-timestep merges. The merged result is validated once, where the signal is registered.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
@classmethod
def unchecked(cls, value: MetadataLike) -> ColumnMetadata:
    """Wraps a plain dict without validating it, for per-timestep merges. The merged result is validated once, where the signal is registered."""
    return (
        value if isinstance(value, ColumnMetadata) else cls.model_construct(**value)
    )

lenient classmethod

Python
lenient(
    raw: Mapping[str, Any], *, where: str = ""
) -> ColumnMetadata

Validates raw, but falls back to loading it unvalidated (with a warning) if it is invalid, so files written by other versions still open.

Source code in src/mujoco_mojo/utils/signal_metadata.py
Python
@classmethod
def lenient(cls, raw: Mapping[str, Any], *, where: str = "") -> ColumnMetadata:
    """Validates `raw`, but falls back to loading it unvalidated (with a warning) if it is invalid, so files written by other versions still open."""
    try:
        return cls.validated(raw)
    except ValidationError as e:
        logger.warning(f"Loading invalid column metadata{where}: {e}")
        return cls.model_construct(**raw)

TransformType

Bases: StrEnum

How a signal must be re-expressed under MojoDataFrame.mojo.change_frame().

POINT, VECTOR, and QUATERNION tag channels grouped into a :x/:y/:z (or :w/:x/:y/:z) family (see rotatable_bases/quaternion_bases), which change_frame refuses to touch untagged. SCALAR says the value does not depend on the frame at all. A lone scalar column needs no tag to be left alone, so tagging it is optional and states the intent; the tag matters for a group whose columns happen to be named :x/:y/:z (or :w/:x/:y/:z) without being a vector, which it keeps out of any rotation.

POINT class-attribute instance-attribute

Python
POINT = 'point'

Translate then rotate (positions).

VECTOR class-attribute instance-attribute

Python
VECTOR = 'vector'

Rotate only (velocities, forces, accelerations, momenta, directions).

QUATERNION class-attribute instance-attribute

Python
QUATERNION = 'quaternion'

Compose: q' = q_b^-1 (x) q.

SCALAR class-attribute instance-attribute

Python
SCALAR = 'scalar'

Unchanged by a frame change (energies, distances, angles, magnitudes, joint values).

metadata property

Python
metadata: ColumnMetadata

Builds a ColumnMetadata carrying only this transform_type, tagging how a signal's grouped vector/quaternion components transform under MojoDataFrame.mojo.change_frame().

setup_logger

Python
setup_logger(
    level=INFO,
    terminal: bool = True,
    log_file: Path | str | None = Path("mojo.log"),
    max_bytes: int = 10 * 1024 * 1024,
    backup_count: int = 5,
) -> Logger

Shortcut to a sensible MuJoCo Mojo logger using Rich for the terminal.

Source code in src/mujoco_mojo/utils/log.py
Python
def setup_logger(
    level=logging.INFO,
    terminal: bool = True,
    log_file: Path | str | None = Path("mojo.log"),
    max_bytes: int = 10 * 1024 * 1024,  # 10MB
    backup_count: int = 5,
) -> logging.Logger:
    """Shortcut to a sensible MuJoCo Mojo logger using Rich for the terminal."""
    logger = logging.getLogger()
    logger.setLevel(level)

    # avoid double logging by preventing logs from being sent to the root logger
    logger.propagate = False

    if not terminal and log_file is None:
        return logger

    # clear existing handlers
    if logger.hasHandlers():
        logger.handlers.clear()

    # --- RICH HANDLER FOR TERMINAL ---
    if terminal:
        console = Console(theme=mojo_theme)
        rich_handler = RichHandler(
            console=console,
            show_time=True,
            log_time_format="[%Y-%m-%d %H:%M:%S]",
            show_path=True,
            enable_link_path=False,
            # highlighter=None,
            markup=True,  # allows color in the log message itself currently disabled in case an array is logged. Square brackets will break logging.
            rich_tracebacks=True,
        )
        rich_handler.addFilter(TerminalFilter())
        logger.addHandler(rich_handler)

    # --- PLAIN TEXT HANDLER ---
    if log_file is not None:
        log_file = Path(log_file)
        log_file.parent.mkdir(parents=True, exist_ok=True)

        file_format = (
            "%(asctime)s [%(levelname)s] %(pathname)s:%(lineno)d - %(message)s"
        )
        file_handler = RotatingFileHandler(
            log_file, maxBytes=max_bytes, backupCount=backup_count
        )
        file_handler.setFormatter(logging.Formatter(file_format))
        file_handler.addFilter(FileFilter())
        logger.addHandler(file_handler)

    return logger