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).
- User Guide Workflow Generate Script Assets and Materials
with_alpha
¶
hex_to_rgba
classmethod
¶
Converts '#RRGGBB' or 'RRGGBB' to normalized [0, 1] RGBA.
Source code in src/mujoco_mojo/utils/color.py
rgba255_to_rgba
classmethod
¶
Converts [0-255, 0-255, 0-255, 0-1] to normalized [0, 1] RGBA.
rgba_to_hex
classmethod
¶
Converts normalized RGBA to '#RRGGBB' (alpha is discarded).
Source code in src/mujoco_mojo/utils/color.py
rgba_to_rgba255
classmethod
¶
Converts normalized RGBA to [0-255, 0-255, 0-255, 0-1].
parse
classmethod
¶
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
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.
-
User Guide
- Features MojoDataFrame Selecting signals Reading a name
- Workflow Runtime Script Request-Based Telemetry
-
Reference
mujoco_mojoutils
category
instance-attribute
¶
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
¶
subgroups: tuple[_Part, ...] = ()
Folders under the category, e.g. ("box1", "xpos"). Empty parts are dropped; none may contain / or :.
attr
class-attribute
instance-attribute
¶
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
¶
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
¶
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
covers
¶
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
__contains__
¶
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
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.
- User Guide Features MojoDataFrame Plain Polars, plus a namespace
-
Reference
mujoco_mojoutils-
MojoDataFrame -
dataframe-
MojoDataFrame -
MojoNamespace-
change_frame -
convert_enums -
select -
select_actuator -
select_attribute -
select_body -
select_camera -
select_category -
select_channel -
select_custom -
select_equality -
select_flex -
select_geom -
select_joint -
select_light -
select_name -
select_path_part -
select_plugin -
select_requirement -
select_sensor -
select_site -
select_tendon -
with_filter_map -
with_filters -
with_unit_system
-
-
-
read_parquet
classmethod
¶
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.
- User Guide Features MojoDataFrame Loading telemetry
Source code in src/mujoco_mojo/utils/dataframe.py
read_column_metadata
classmethod
¶
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.
- User Guide Features MojoDataFrame Loading telemetry
Source code in src/mujoco_mojo/utils/dataframe.py
from_pl
classmethod
¶
from_pl(df: DataFrame) -> MojoDataFrame
Converts a standard Polars DataFrame into a MojoFrame for the static analyzer.
- User Guide Features MojoDataFrame Loading telemetry
from_dict
classmethod
¶
Creates a MojoFrame from a dictionary.
- User Guide Features MojoDataFrame Loading telemetry
Proximity
¶
Bases: MojoBaseModel
Provide high-precision triangle-level distance queries.
- User Guide Features Proximity Measuring a Pair
volume_1
instance-attribute
¶
First volume to perform proximity calculations for.
volume_2
instance-attribute
¶
Second volume to perform proximity calculations for.
dist_max
instance-attribute
¶
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
¶
algorithm: ProximityType = CONVEX_HULL
What algorithm should be used for the narrowphase test.
visualize
class-attribute
instance-attribute
¶
visualize: bool = True
Wheter or not to visualize this proximity in the MuJoCo viewer.
active
class-attribute
instance-attribute
¶
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
¶
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 ( |
Source code in src/mujoco_mojo/utils/proximity.py
get_convex_hull_proximity
¶
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 ( |
Raises:
| Type | Description |
|---|---|
TypeError
|
If either volume is a |
Source code in src/mujoco_mojo/utils/proximity.py
get_vertex_to_face_proximity
¶
Calculates the vertex to face distance using a multi-phase Bounding Volume Hierarchy (BVH) query.
Phases
- Broad Phase: Sphere-Sphere check (object level).
- Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
- 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 ( |
Source code in src/mujoco_mojo/utils/proximity.py
| Python | |
|---|---|
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
get_face_to_face_proximity
¶
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
- Broad Phase: Sphere-Sphere check (object level).
- Mid Phase: BVH Traversal (eliminating triangle groups). No exit here.
- 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 ( |
Source code in src/mujoco_mojo/utils/proximity.py
get_proximity
¶
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 ( |
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
request
¶
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
scalaris posted as a single value withattr=channel. - An
xyzis a cartesian vector without a magnitude component, posted as 3 values (x,y,z).fromtoposts onexyzfor each volume in the pair, undersubgroups=(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 |
['dist', 'prox_type']
|
Source code in src/mujoco_mojo/utils/proximity.py
| Python | |
|---|---|
493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 | |
MojoGenerator
¶
Bases: Protocol
Definition of a function that generates a MojoModel model instance.
-
Reference
mujoco_mojoutils
MojoObjective
¶
Bases: Protocol
Definition of a function that scores a completed Mojo simulation.
-
Reference
mujoco_mojoutils
MojoRunner
dataclass
¶
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(),
)
-
User Guide
- Examples Vertically Landed Rocket Runtime Behavior Running One Trial
- Workflow Running Jobs Running Jobs
args
class-attribute
instance-attribute
¶
Positional arguments passed to the generator, the runtime, and the objective.
kwargs
class-attribute
instance-attribute
¶
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
¶
slurm_trial_id: int | None
Returns the current SLURM task ID if running as part of an array job.
shared_argument_flags
¶
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
validate_kwargs
¶
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
run
¶
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
orchestrate_slurm
¶
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
execute_single_trial
¶
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
run_monte_carlo
¶
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 | |
|---|---|
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 | |
get_slurm_array_string
staticmethod
¶
Collapses [0, 1, 2, 5, 6] into '0-2,5-6' for SLURM.
Source code in src/mujoco_mojo/utils/runner.py
get_slurm_partitions
staticmethod
¶
Queries sinfo for available partitions and identifies the default.
Source code in src/mujoco_mojo/utils/runner.py
normalize_to_mb
staticmethod
¶
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
format_bytes
staticmethod
¶
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
get_slurm_node_mem_limit
staticmethod
¶
Finds the MINIMUM RealMemory limit, normalized to MB.
Source code in src/mujoco_mojo/utils/runner.py
get_slurm_cpu_limit
staticmethod
¶
Finds the minimum of the max allowed CPUs (CPUTot) among nodes in a partition.
Source code in src/mujoco_mojo/utils/runner.py
slurm_time_to_seconds
staticmethod
¶
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
get_slurm_time_limit
staticmethod
¶
Finds the MaxTime limit for a specific partition.
Source code in src/mujoco_mojo/utils/runner.py
get_max_array_size
staticmethod
¶
get_max_array_size() -> int
Queries the global SLURM configuration for MaxArraySize.
Source code in src/mujoco_mojo/utils/runner.py
slurm_mojo_command
staticmethod
¶
slurm_mojo_command() -> Path
The mujoco-mojo executable next to the running interpreter, which the compute nodes use to run each trial.
prepare_slurm_job
¶
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 |
Source code in src/mujoco_mojo/utils/runner.py
slurm_worker_command
¶
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
write_slurm_script
¶
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
submit_slurm_script
¶
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
slurm_limit_problems
¶
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
submit_slurm
¶
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 |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
- User Guide Workflow Running Jobs Running Jobs Execution Mode SLURM Mode (slurm) Submitting from Python
Source code in src/mujoco_mojo/utils/runner.py
| Python | |
|---|---|
1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 | |
orchestrate_slurm_monte_carlo
¶
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 | |
|---|---|
1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 | |
MojoRuntime
¶
Bases: Protocol
Definition of a function that executes a generated MojoModel model.
-
Reference
mujoco_mojoutils
MonteCarloConfig
¶
Bases: BaseConfig
-
Reference
mujoco_mojoutils
n_proc
class-attribute
instance-attribute
¶
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
¶
resume: bool = DEFAULT_RESUME
Whether to resume a study if the study already exists.
padding
class-attribute
instance-attribute
¶
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
¶
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
¶
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
-
Reference
mujoco_mojoutils
n_proc
class-attribute
instance-attribute
¶
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
¶
resume: bool = DEFAULT_RESUME
Whether to resume a study if the study already exists.
padding
class-attribute
instance-attribute
¶
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
¶
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
¶
n_trial: int = DEFAULT_OP_N_TRIAL
Number of trials to run.
study_name
class-attribute
instance-attribute
¶
study_name: str = DEFAULT_OP_STUDY_NAME
Unique identifier for the Optuna study.
direction
instance-attribute
¶
direction: Direction
Whether we want to find the lowest or highest objective value.
timeout
class-attribute
instance-attribute
¶
timeout: float | None = DEFAULT_OP_TIMEOUT
Stop the study after this many seconds, regardless of trial count.
storage
class-attribute
instance-attribute
¶
storage: str | None = DEFAULT_OP_STORAGE
Database URL (e.g., 'sqlite:///study.db') for multi-node persistence.
sampler
class-attribute
instance-attribute
¶
sampler: Sampler = DEFAULT_OP_SAMPLER
The search algorithm. TPE is generally best for noisy physics.
evals_per_trial
class-attribute
instance-attribute
¶
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
¶
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.
Trial
dataclass
¶
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.
base_dir
instance-attribute
¶
base_dir: Path
Root directory where all simulation trials are stored.
xml_name
instance-attribute
¶
xml_name: str
Filename for the generated MJCF XML (e.g., 'model.xml').
model_config_name
instance-attribute
¶
model_config_name: str | None
Filename for the serialized MojoModel configuration (e.g., 'config.json').
padding_style
instance-attribute
¶
padding_style: str
Format specifier for directory naming (e.g., '04d').
trial_dir
property
¶
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'.
model_config_path
property
¶
model_config_path: Path
The full path to the JSON configuration file for this trial.
named_value_path
property
¶
named_value_path: Path
The full path to the JSON NamedValue file for this trial.
run
¶
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 |
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 |
Source code in src/mujoco_mojo/utils/runner.py
| Python | |
|---|---|
521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 | |
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.
- User Guide Features MojoDataFrame
unit
class-attribute
instance-attribute
¶
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
¶
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
¶
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
¶
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
¶
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
¶
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__
¶
__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
__or__
¶
__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
from_enum
classmethod
¶
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.
- User Guide Workflow Runtime Script Request-Based Telemetry
Source code in src/mujoco_mojo/utils/signal_metadata.py
validated
classmethod
¶
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
unchecked
classmethod
¶
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
lenient
classmethod
¶
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
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.
VECTOR
class-attribute
instance-attribute
¶
Rotate only (velocities, forces, accelerations, momenta, directions).
QUATERNION
class-attribute
instance-attribute
¶
Compose: q' = q_b^-1 (x) q.
SCALAR
class-attribute
instance-attribute
¶
Unchanged by a frame change (energies, distances, angles, magnitudes, joint values).
metadata
property
¶
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
¶
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.