Improve generic robot onboarding, walking controls and end-effector interaction
Checks / Layout, translation and Colab checks (push) Has been cancelled
Checks / Ruff (push) Has been cancelled
Checks / Framework tests (native backend, CPU) (push) Has been cancelled
Checks / Portable Rust controller (push) Has been cancelled

Default humanoid intake to command-following gait and support bounded Cartesian target dragging for arms. Carry model and actuator semantics through calibration, native verification and packaging. Document reusable intake decisions and cover them with regression tests.
This commit is contained in:
2026-11-06 10:54:58 +08:00
parent d5e9004f6c
commit ceca51b0d8
88 changed files with 5572 additions and 619 deletions
+3 -18
View File
@@ -5,16 +5,9 @@ description: Translate a built bundle's manual.en.json into Chinese as manual.zh
# The bundle's manual, in Chinese
`scripts/deploy.py` writes `manual.en.json` into every bundle (both native
`mjrl-robot-app/1` bundles and legacy `kk-policy-bundle/1` bundles): each pad
control and each key the bundle reads, what it does in each mode, how each mode
is reached and left, and every mode switch. It is generated from the
controller's own account of its controls, so it cannot disagree with the
bindings. The pad and the keyboard are separate paths and the manual lists them
apart: in each mode `controls` is the pad and `keys` the keyboard, and each
switch says which `device` it is on. The Chinese version is a translation of
it, and this skill is how it is made: the build cannot write natural Chinese,
and a person or an agent can.
Translate the generated English manual of the actual native or legacy bundle.
Keep keyboard, pad and mode switches distinct; translate only the entries this
build supplies.
## Steps
@@ -88,11 +81,3 @@ A mode's custom control descriptions from its `controls.yaml` are translated
like any other text (for example, `drives the elbow joint target` becomes
`驱动肘关节目标位置`). Each mode lists only the controls bound in that mode, so
translate what is there and add nothing.
## Why a separate step
The English is the build's and the Chinese is a translation of it, never the
other way round: a manual written in Chinese first would have no generator to
hold it to the bindings. `--translate` is what keeps the two the same manual in
two languages -- it compares every identifier -- and it is also why a bundle
built without an agent still ships the English one.
+30 -29
View File
@@ -1,34 +1,35 @@
---
name: controls
description: Configure operator keys, pad bindings, releases, or legacy FSM mode switches using the shared control vocabulary and schema.
description: Configure and verify operator inputs, releases and mode bindings against a controller's supported physical commands.
---
# Bind operator input
# Bind physical commands to inputs
Read [Controls](../../../docs/CONTROLS.md). Use
`python -m controller --vocabulary` as the source of device names.
For the locked locomotion templates, generate the ordered body-frame
velocity binding in the robot's asset directory:
```bash
python .claude/skills/controls/scripts/write_controls.py --task <robot_id>
```
Use `--profile differential` for `wheeled_biped`. W/S drive forward and
backward and A/D turn left and right. The keyboard leaves lateral motion
unbound. The required Lx pad channel stays in the layout and has zero range.
The default `omni` profile keeps A/D for lateral motion and J/L for turning.
Use `--out` to specify another destination file. Keep all three velocity
channels in order. Use `--bind AXIS=SOURCE+` or `--bind AXIS=SOURCE-` for
named changes and `--release BUTTON` when specified. Point `robot_spec.py`
at this file.
For deterministic modes, generate the binding with `onboard.py setup-tier2`.
Validate the final YAML with `controller.controls.load_controls`. Exercise
both ends of the active axes and release on the selected model. Repeat native
verification after changing bindings that a portable app will package.
A legacy FSM mode switch belongs in the deployment manifest. Check it against
the mode's operator bindings and validate the legacy bundle. Native app mode
selection uses `--app-mode`.
1. Identify the named command, frame, unit, order, sign, rest value and release
behavior for each supported input. Choose the profile from actual kinematics;
preserve disabled channels if required by the target schema. The
[controls reference](../../../docs/CONTROLS.md) owns device vocabulary,
keyboard layouts, generators and schema validation.
For humanoid walking, bind W/S to forward/reverse body velocity and A/D to
left/right yaw. Verify signed translation and rotation independently and
check forward plus turn. For an arm with IK, exercise the viewer drag on
the tool target, measure the achieved tool point, and check where it holds
when the mouse is released.
2. Set each input's extrema from measured deployment capability. A held key
can reach the full configured value; a positive-direction test does not
validate a symmetric range. Preserve training ranges separately if supplied.
3. Validate the bindings and exercise held input, required signs, idle/release
and promised combinations on the actual controller. Measure physical motion
as well as input values. Compare the complete return-to-rest transition with
its settled endpoint. An abrupt release can reach the effort limit even when
the final position and steady effort pass. Sample applied effort on every physics
step, including the first step after the target changes. Record peak, time at
the bound and time to settle from both endpoints. If the jump causes
clipping, test a named slider `target_rate_limits` entry on the affected
axis with the same gains, effort limits and commands. Verify that one
release tick followed by idle reaches rest as reliably as holding release.
For legacy mode-switch conflicts follow the
[bundler's diagnostic](../deploy/SKILL.md#input-conflicts).
4. Hand the exact bindings, supported range and probe results to
[deploy](../deploy/SKILL.md). If a binding changes, repeat the affected
responses before releasing the changed archive.
@@ -8,6 +8,8 @@ import re
import sys
from pathlib import Path
import yaml
REPO = Path(__file__).resolve().parents[4]
sys.path.insert(0, str(REPO))
@@ -35,17 +37,7 @@ DEFAULT_BINDING = {
"ang_vel_z": ("Rx", -1),
}
#: The keyboard: command axis -> (the keys towards its positive direction, the
#: keys away from it). W S and the arrows walk forward and back, A D and the
#: arrows step left and right (the arrows asked for on 2026-09-28), J L turn --
#: the layout as the
#: user decided it on 2026-09-29. Two keys on one direction are summed while
#: both are held. Letting go of the keys is taking your hands off; there is no
#: key for it (`centre`, retired 2026-09-27).
#:
#: Every letter is also one of MuJoCo's viewer shortcuts -- W flips the scene to
#: wireframe -- and that was accepted for a keyboard laid out for the hands; the
#: dictionary's `_keys_note` has the table.
# Explicit omnidirectional layout, retained for existing operator profiles.
KEYS_FOR = {
"lin_vel_x": (("key_w", "key_up"), ("key_s", "key_down")),
"lin_vel_y": (("key_a", "key_left"), ("key_d", "key_right")),
@@ -99,7 +91,12 @@ def check(name: str, kind: str, allowed) -> None:
def keyboard_for(axes: list[str], profile: str) -> dict[str, KeyDirections | None]:
"""Check each selected keystroke against the dictionary."""
mapping = DIFFERENTIAL_KEYS if profile == "differential" else KEYS_FOR
if profile == "walking":
preset = REPO / "rl/mjrl/controllers/walking.yaml"
bindings = yaml.safe_load(preset.read_text(encoding="utf-8"))["devices"]["keyboard"]["axes"]
mapping = {axis: (tuple(keys["+"]), tuple(keys["-"])) for axis, keys in bindings.items()}
else:
mapping = DIFFERENTIAL_KEYS if profile == "differential" else KEYS_FOR
out = {}
for axis in axes:
directions = mapping[axis]
@@ -220,8 +217,8 @@ def main() -> int:
ap = argparse.ArgumentParser(prog="write_controls.py", description=__doc__.splitlines()[0])
ap.add_argument("--task", required=True, help="robot id, e.g. sample_biped")
ap.add_argument(
"--profile", choices=("omni", "differential"), default="omni",
help="keyboard profile. Use differential for the wheeled-biped template",
"--profile", choices=("walking", "omni", "differential"),
help="keyboard profile (defaults to the registered family, or walking for a new task)",
)
ap.add_argument("--axes", default=",".join(AXIS_MEANING),
help="command axes in order (default: all three)")
@@ -237,6 +234,12 @@ def main() -> int:
if re.fullmatch(r"[a-z][a-z0-9_]*", args.task) is None:
ap.error("--task must be a lowercase robot id")
if args.profile is None:
from tasks.robot_spec import read_robot_spec
registered = REPO / "tasks" / args.task / "robot_spec.py"
family = read_robot_spec(registered).family if registered.is_file() else "biped"
args.profile = {"biped": "walking", "wheeled_biped": "differential"}.get(family, "omni")
axes = [a.strip() for a in args.axes.split(",") if a.strip()]
if args.profile == "differential" and axes != list(AXIS_MEANING):
ap.error("the differential profile requires all three command axes in template order")
+45 -47
View File
@@ -1,66 +1,64 @@
---
name: deploy
description: Export, verify and package a robot controller as a native MuJoCo .app or a supported legacy board/web bundle. Use for deployment contracts, ONNX/RKNN conversion, runtime parity, bundle creation, or an explicitly requested hardware deployment.
description: Verify and package a native MuJoCo application or a supported legacy board/web bundle; diagnose runtime fidelity and final archive failures.
---
# Verified application packaging
# Package the verified capability
Read [deploy/README.md](../../../deploy/README.md) and
[deploy/BUNDLE.md](../../../deploy/BUNDLE.md). A directory containing an ONNX file
is an export, not an accepted application.
Use the [acceptance procedure](../../../docs/ROBOT_ONBOARDING_LESSONS.md) for
claim status and the [deploy guide](../../../deploy/README.md) and
[bundle format](../../../deploy/BUNDLE.md) for build commands and contracts.
## Native application
1. Identify the robot ID, normalized MJCF and control mode. Use the onboarding
skill for source assets. Do not infer a home pose or motor mapping from order.
2. For a trained or adapted policy, inspect its `layout.json`, numerical parity
report and source provenance. Preserve wire/observation/action named orders,
term histories, transforms, rates and gain semantics.
3. Write explicit native physical-response probes and run `onboard.py verify`.
Require both physics and control acceptance for a controlled capability.
Changing tolerances solely to turn a failure green is not acceptance.
4. Run `deploy.py --robot <id> --model <normalized.xml> --control
<controller.json> --controls <controls.yaml> --verification <report.json>
--bundle <output-parent>`. Add `--policy <export>` for an ONNX mode.
Geometry-only display omits controller/verification and claims `model_viewer`.
5. Replay the emitted app and run `deploy.py --check-reference <app>`. Record
actual measured results and supported runtime, including missing capabilities.
6. Follow [bundle-manual](../bundle-manual/SKILL.md) to add the Chinese manual
through `deploy.py --translate`; report the resulting archive path.
1. Select the declared host and mode. A native app needs host Python and its
declared dependencies. A geometry-only app claims `model_viewer`; a
controlled app needs passing native physics and command probes for its exact
model, controller and [bindings](../controls/SKILL.md). For a policy include
the actor, layout, parity evidence and provenance. Carry any requested
[motion-quality result](../train/SKILL.md) forward separately.
2. If source replay works but export diverges, compare the first differing
state: observations/history, action, target and effort, then next model
state. Check runtime versions and serialized geometry/physics. Preserve
suitable numeric assets; repeated serialization can change contact
trajectories. Different mesh frames can represent the same transformed
geometry: compare the quantities the claim actually requires.
If compiled mass, inertia or center of mass changes, locate the first
affected body and trace which geoms contribute under its inherited defaults.
An omitted zero mass or density can make a collision mesh contribute inertia.
Compare compiled values before and after relocation, including fixed links.
3. Build using the verified inputs. Include imported licenses and distinguish
synthetic fixtures in the robot ID and attribution. Add the
[translated manual](../bundle-manual/SKILL.md) before final validation.
4. Run the **final archive** outside the source checkout with the declared
dependencies, check its reference trajectories (`deploy.py --check-reference`)
and replay the claimed inputs for a finite duration. For a multi-stage task,
include a reference at a discriminating intermediate state, such as the
object's position during an unsupported hold. Replay the complete default
mode and any operator mode used to demonstrate the task. Record the archive hash,
host, measured response and limitations. If those bytes change, reassess
affected checks and identify the artifact actually delivered.
The portable native runtime needs host Python and declared dependencies. It is
not a browser or board executable. Do not mark an unsupported host as available.
## Legacy board or web target
## Legacy Rust board/web application
1. Export the checkpoint through `scripts/export.py`. Refuse contracts the target
reader does not implement; native hybrid position/velocity contracts are not
legacy scalar-action contracts.
2. Choose explicit export paths, cascade and switches in `deploy/manifests.json`
or repeated `--mode` arguments. The generic repository defines no default robot.
Use the [controls skill](../controls/SKILL.md) for binding changes.
3. For a real board, run the read-only preflight script with the explicitly supplied
`--host` and machine configuration. Check software ABI, DDS/QoS and named motor
order before a build or transfer. No address is inferred.
4. Build through `scripts/deploy.py`. Its default legacy path performs RKNN
conversion, cross-builds, contract checks and reference generation. Follow
`deploy/convert/README.md` and `deploy/fsm/README.md` for toolchains.
5. `--allow-incomplete` is a development build with recorded omissions. Do not
describe one as board-ready. Add its Chinese manual before handoff too.
6. Hardware operation is separate from building. When explicitly authorized,
run the board controller's `--dry-run` then `--check-reference` before the
operational command with the machine's configuration. Stop on mismatch.
Use only contracts the target reader implements; a native hybrid position and
velocity layout cannot be assumed to work with a scalar-action reader. Supply
the export paths, modes and switches explicitly. For a board, use the
[read-only preflight](scripts/check_board.py) with the supplied host and machine
configuration; check ABI, DDS/QoS and named motor order. A skipped preflight
check is not a pass. Cross-build and check the references for the selected target.
Include the translated manual; an `--allow-incomplete` build is developmental.
Operating hardware requires separate authorization and a passing board dry run
and reference check.
## Input conflicts
A mode's controls and the FSM's switches share a vocabulary and must not consume
one input twice. The legacy reader reports:
The legacy bundler checks the combination of mode inputs and FSM switches. On
```
switches on the pad's ... controls use too: one press would do both.
Pick another control, or say with `from` that the switch is not pressed in
```
Change the binding or explicitly restrict the switch's source modes. Do not remove
validation or widen a contract to hide the conflict. Unknown observation terms,
joint names, unsupported versions and missing trajectory companions fail closed.
change the binding or restrict the switch's source modes, then validate the
bundle again. Do not widen the schema or suppress the collision.
+25 -23
View File
@@ -5,29 +5,31 @@ description: Register a new legged robot for training by generating a data-only
# Register a robot
Read [Usage](../../../docs/USAGE.md#robot-specification) for the schema.
Select `biped`, `quadruped`, `wheeled_biped`, or `multipod` using inspected
model facts and control intent. Reuse the exact model that passed the
stance checks. Keep robot assets and optional controls outside `tasks/`.
Apply the [diagnosis and closeout loop](../../../docs/ROBOT_ONBOARDING_LESSONS.md).
Read the [robot specification schema](../../../docs/USAGE.md#robot-specification).
```bash
python scripts/onboard.py scaffold-tier3 --config robot.json --calibration calibration.json
python scripts/train.py --list
python scripts/train.py --task <robot_id> --dry-run
python -m pytest tests/test_registry.py tests/test_template_lock.py -q
```
1. Select a supported family from inspected physical topology and intended
control using the specification schema. Reuse the exact
model and dependencies that passed stance checks. Automatic family guesses
require review; a missing family is a template design issue, not a reason to
mislabel the robot.
2. Prepare only physical data: model/controls paths, named home values and base
height, gains, effort limits, action scales, supports and any wheel joints.
Keep assets and controls outside `tasks/`. Record source evidence or measured
calibration for values; do not infer missing policy semantics from this data.
3. Include [operator bindings](../controls/SKILL.md) for humanoid walking by
default. Resolve a custom controls path relative to its configuration.
4. Write one literal `tasks/<robot_id>/robot_spec.py`. Routine onboarding must
not modify the registry, entry points, template files or lock. New behavior,
rewards or a new family requires an explicit shared-template revision with
its own justification and validation. Do not hide behavior in the spec.
5. Verify discovery, resolved configuration and template integrity, then hand
off to [train](../train/SKILL.md) for a backend smoke. Discovery establishes
registration only.
The scaffold writes `tasks/<robot_id>/robot_spec.py`. It carries the model and
controls paths, home joint values and base height, gains and effort limits,
action scales, and contact names. With `--calibration`, the JSON supplies the
robot ID, family, model path, action scales, and any optional contacts,
controls, or wheel joint specifications not supplied by the report.
## Execution aids
For operator input, apply the [controls skill](../controls/SKILL.md) before
scaffolding and set `controls_path` in the scaffold JSON relative to that
file. Use `--profile differential` when generating bindings for
`wheeled_biped`.
Onboarding must not modify the template files, the registry source, the
entry points, or the lock. The only generated Python file is the literal
robot specification. If the asset requires a new family or behavior, treat
it as an explicit template revision.
`onboard.py scaffold-tier3 --config <config> --calibration <report>` writes the
specification. Review its output instead of relying on generation alone.
`train.py --list` and `--task <id> --dry-run` check discovery and resolution;
`tests/test_registry.py` and `tests/test_template_lock.py` check their contracts.
+35 -23
View File
@@ -1,30 +1,42 @@
---
name: onboard-asset
description: Inspect a new robot URDF, MJCF, mesh, or project directory, normalize it for MuJoCo, and select a viewer, existing policy, deterministic control, or legged training route.
description: Inspect a robot model and its dependencies, establish supported capabilities, and route an intake to viewing, policy adaptation, deterministic control or training.
---
# Onboard a robot asset
# Inspect and route an asset
Read [Workflow](../../../docs/WORKFLOWS.md) and [Hardware](../../../docs/HARDWARE.md).
Use the [common acceptance and closeout procedure](../../../docs/ROBOT_ONBOARDING_LESSONS.md).
The intake output is a selected model, an inventory of evidence and a supported
next step, including any blocker.
1. Run `python scripts/onboard.py inspect <source> --report <new-report.json>`.
Pass `--profile`, `--mesh-root`, `--policy`, or `--metadata` when supplied.
Review the selected model, missing dependencies, model checks, declared
control intent, and recommended tier. Resolve ambiguous inputs explicitly.
Keep candidate training configs associated with the actor that used them.
A Tier 1 recommendation with `needs_metadata` goes to
[tier1-adapt](../tier1-adapt/SKILL.md) for extraction and review.
2. Preserve the source and record the exact model selected. For URDF, MJCF,
or a standalone mesh, run `build-mjcf` with a new `--output` path. A
directory works when it contains one model, or one mesh if there is no model. Add
`--floating-base` only when the robot requires a free root. If generating
visual fallback collisions, record the approximation and inspect the result.
3. Check compilation and inspect joint names, units, axes, limits, inertias,
collision geometry, and frames. For a viewer use `scripts/deploy.py --robot
<id> --model <xml>` and run a finite headless replay.
4. Route an existing policy to [tier1-adapt](../tier1-adapt/SKILL.md),
deterministic control to [tier2-control](../tier2-control/SKILL.md), and
explicit legged training to [tier3-train](../tier3-train/SKILL.md).
1. Inventory the supplied assets, dependencies, licenses, actor, configurations
and reference results. Identify which belong together. A keyframe, gain or
physics timestep is model evidence; none establishes a policy's home, order,
action scales or decision rate. Label a synthetic actor as a test fixture.
2. Trace model includes to find the scene, articulated root, ground and contact
definitions. When several unnamed collision shapes make up one sole, identify
the supporting body and aggregate its floor contacts. Count physical feet
and measure their loads after settling. Explicit contact pairs can remain active with zero collision
masks. Review physical chains rather than counting mesh names or trusting
an automatic family guess. In manipulation scenes, an independent payload
adds another top-level body. Inspect the arm on its own to establish its
capabilities, then verify the complete scene with the robot root and scene
reset key selected explicitly. Check the free object's initial pose as well
as the robot pose. Inspect units, frames, inertias, axes and limits
using the [model requirements](../../../docs/HARDWARE.md).
3. Preserve the source. Reuse suitable compiled MJCF; convert to a separate
asset only if needed. Declare approximated collisions and add a floating
root only if the intended mechanism requires one.
4. Choose the [intake route](../../../docs/WORKFLOWS.md) justified by user
intent and available evidence. A working viewer can be delivered as such.
Default a humanoid intake to command-following walking. Reuse a matching
walking policy via [adaptation](../tier1-adapt/SKILL.md) or prepare the
floating-base biped for [training](../tier3-train/SKILL.md). Keep walking
open until measured gait passes. Honor an explicit narrower request. For
an arm, inspect the controllable chain and tool point for interactive
[end-effector control](../tier2-control/SKILL.md).
If the requested capability is blocked, record the missing prerequisite
and close out that claim; a different capability is a separate result.
A viewer pass establishes that the model loads. Carry separate measured
physics and command evidence into every controlled mode.
See [Onboard](../../../docs/USAGE.md#onboard) for inspection and conversion
tools. Model-only inspection does not require policy extraction.
+22 -154
View File
@@ -1,161 +1,29 @@
---
name: setup-env
description: Set up, verify or repair the mjrl-lab development environment on Linux, Windows or macOS, with or without an NVIDIA GPU -- the Python environment and the Rust toolchain the controller (deploy/fsm) builds with. Detects the machine, picks the right torch build, finds which of cargo, the wasm target, wasm-bindgen and CycloneDDS are missing, installs, and verifies Python and optional legacy targets. Use this whenever someone is getting this repository running on a new machine, onboarding, or hitting environment trouble: "ModuleNotFoundError: No module named 'mjlab'", torch not seeing the GPU, warp reporting only ['cpu'], a registered robot missing from `--list`, mujoco version conflicts, `cargo` not found, `idlc not found`, a wasm-bindgen version mismatch, the controller's tests skipping, or a suspicion that the wrong Python or the wrong checkout is being used. Reach for it before hand-rolling pip or cargo commands, because the failures here are quiet -- an environment that imports everything and trains happily can still be running another checkout's code or ignoring the GPU entirely, and a test suite on a machine without cargo is green because it skipped the controller.
description: Establish or diagnose this checkout's Python environment, simulation backend or optional legacy controller build toolchain.
---
# Setting up mjrl-lab
# Verify the environment used by the task
The reference procedure is [`docs/AGENT_SETUP.md`](../../../docs/AGENT_SETUP.md) — about 600 lines,
written to be read by an agent, with the full platform tables and a catalogue of known failures.
**This skill does not restate it.** It sequences it, automates the two parts worth automating,
and knows when to stop and read.
Use [docs/AGENT_SETUP.md](../../../docs/AGENT_SETUP.md) for platform-specific
installation, versions and failure remedies.
Two scripts carry the weight. Both are plain standard-library Python and run without this skill,
so an agent that cannot load skills can still use them:
1. Identify the interpreter, checkout, OS, device and intended target. Verify an
existing isolated environment before replacing it. Install this repository
editable in the intended interpreter; confirm that vendored libraries import
from this checkout. A different checkout can import and run successfully.
Keep incompatible simulator environments separate.
2. Test the capability that will actually run: device enumeration for Warp,
the batch rollout interface for native MuJoCo, or registry discovery for a
missing task. A GPU banner, version string or successful import alone can
pass when the intended capability is unusable.
3. Only for the corresponding legacy target, verify the Rust target builds,
the wasm tool matches the lockfile, or the device binary links and loads
with the target ABI. Skipped controller tests do not establish readiness.
4. Smoke-test the selected path with a registered task, or a viewer example
for a model-only request. Report the measured result and untested targets.
| Script | Interpreter | Answers |
|---|---|---|
| `scripts/detect.py` | whatever the machine already has | what this machine is, and the exact commands that follow from it |
| `scripts/gates.py` | the environment's own | whether the environment actually works, and what to fix |
## The shape of the problem
Almost everything here fails **quietly**. Installing a cu126 torch on a Blackwell card succeeds
and dies later inside CUDA. An editable install pointing at a stale checkout imports cleanly and
runs somebody else's code. A `pip` into the wrong interpreter reports success and changes
nothing. A machine without cargo runs the test suite green, because the tests that build the
controller skip. None of these announce themselves, and all of them surface much later as
something that looks unrelated.
That is why this measures before deciding and verifies after acting, rather than running a
sequence of commands and trusting that silence means success.
## Procedure
### 1. Measure, before deciding anything
```bash
python3 .claude/skills/setup-env/scripts/detect.py
```
Run it with the machine's existing interpreter — establishing whether that interpreter is usable
at all is part of what it answers. It reports OS, architecture, Python version, GPU and compute
capability, any environment that already exists, which parts of the controller's toolchain are
already here, and it ends with the exact command sequence for this machine.
Read its output before continuing. In particular:
- **Python out of range** (needs 3.10–3.13): install a compliant interpreter *first*. Installing
dependencies on an old one produces failures much later that read as unrelated.
- **An environment already exists**: go to step 3 and verify it. The common case after the first
run is not a bare machine but a broken environment, and building a second one hides the fault
rather than fixing it.
### 2. Install
Follow the commands `detect.py` printed. They are section 1 of the reference doc with the
branches already resolved for this machine; consult the doc when something does not match — the
Debian `ensurepip` split, the Windows execution policy, and the MSVC prerequisite each have a
paragraph there.
Only one step genuinely branches: **which torch wheel**. `detect.py` chose it from the measured
compute capability, and its reasoning is on the `torch_plan` function if you need to check it.
Before any `pip`, confirm the interpreter is the intended one:
```bash
python -c "import sys; print(sys.prefix)"
```
It must be the environment you just made. Pip reports success regardless of where it installs, so
this is the cheapest place to catch a mistake that otherwise surfaces three steps later.
`pip install -e .` is not optional and is not a convenience: the vendored `mjlab` and `rsl_rl`
live under `rl/`, which is not on `sys.path`. That editable install *is* the mechanism that makes
them importable.
**The legacy controller toolchain is required for its browser and board targets** — sections 2.1 and 2.2
of the reference doc. It is additive rather than per-checkout, so `detect.py` prints only the
steps this machine is missing, and "nothing missing" is a normal answer on a second checkout.
Two of its parts are easy to get subtly wrong:
- **wasm-bindgen's version comes from `deploy/fsm/Cargo.lock`**, exactly — not from
`Cargo.toml`'s `"0.2"`, a range every 0.2.x satisfies and `cargo install --version` refuses.
Take the command `detect.py` printed; `scripts/deploy.py` refuses any other version.
- **CycloneDDS is a source build** (11.0.1, the soname the board carries) and needs
`sudo ldconfig` after installing into `/usr/local`. It is not needed for `deploy.py`, but once
cargo exists `tests/test_deploy_sources.py` stops skipping and fails without it.
- **Rockchip's NPU header is per checkout, not per machine.** `bash
deploy/fsm/vendor/rknpu2/fetch.sh` puts it in the repository, git-ignored because its licence
is Rockchip's. `detect.py` prints that step whenever it is missing, a second checkout included.
### 3. Verify
```bash
.venv/bin/python .claude/skills/setup-env/scripts/gates.py --python-only
```
Use `--python-only` for Python onboarding, training, and native apps. Omit it to verify the legacy controller toolchain as well. The exit code counts failures. Each prints what it measured and, on failure, the
remedy and where the long form lives:
- **A — warp device enumeration.** On a GPU machine `cuda:0` must appear in the device list.
`wp.init()` also prints a banner naming the card; that banner appears even when CUDA is
unusable, so the list is the criterion and the banner is not.
- **B — native MuJoCo's batch interface.** `native:cpu` is built on `mujoco.rollout`, so
importing `mujoco` is not sufficient evidence.
- **C — the vendored copies are this checkout's.** Stricter than the doc's version, which only
rules out `site-packages`. An editable install left pointing at an older copy of the repository
satisfies that and still executes another checkout's code — measured on a training machine on
2026-09-04, where `tasks` came from the current repository and `mjlab` from a snapshot three
days stale. Everything imported; the seam being edited simply was not the seam being run.
- **D — the task registry.** Loads no simulation dependencies, so it passes even where the GPU is
broken. A failure here is a packaging problem, not a simulation one — which is worth knowing
before looking in the wrong place.
- **E — the Rust toolchain builds the legacy controller's host targets.** `cargo check` of the
browser's wasm and of the legacy `play --app` extension (`kk-policy-bundle/1`), and the
wasm-bindgen CLI against `Cargo.lock`. (Native `mjrl-robot-app/1` bundles run in pure Python.)
It builds rather than reading versions, because a missing target or linker passes `cargo --version`.
- **F — the device build links and loads.** `cargo test --lib -- --list` with the default
features: CycloneDDS, libclang, Rockchip's NPU header and a `libddsc` the loader finds. `--list` runs the binary
without running a test, so a failing crate test is not reported as an environment fault.
E and F take about 30 s together, cold, on the i9-14900KF with the crates already downloaded; a
first run also downloads them.
Do not proceed past a failure. Each remedy is printed; the long forms are section 6 of the
reference doc.
### 4. Smoke test
With the relevant gates green, smoke-test the backend you intend to use.
Choose a registered robot from `scripts/train.py --list`. If the registry is
empty, use the model viewer example in the root README.
```bash
python scripts/train.py --task <robot_id> --backend warp --device cuda --num_envs 4 --max-iterations 1 --headless
python scripts/train.py --task <robot_id> --backend native --device cpu --num_envs 4 --max-iterations 1 --headless
```
Check the backend in the run banner and confirm the PPO update completes.
## When something fails
Work from the measurement, not from the symptom. `detect.py` and `gates.py` both print what they
observed, and the reference doc's section 6 is indexed by the exact error text — search it for the
message rather than reasoning from the traceback, because several of these have causes that the
traceback does not mention (the `njmax` overflow, the wandb `start_method` rejection, and
`select_gpus` raising `IndexError` are all in that class).
Two rules survive every platform, and both are in section 7 of the doc:
- **Never `pip install mjlab` or `rsl-rl-lib`.** They exist as modifiable copies under `rl/`.
A PyPI copy in the same environment shadows them ambiguously and is very hard to notice.
- **Never install into an existing Isaac Lab environment.** mjlab needs `mujoco~=3.11`, Isaac Lab
ships 3.10, and they break each other.
## Reporting back
Say which branch the machine took, which gates passed, and what the smoke test measured. If a
gate was skipped or a step was worked around, say so plainly — an environment reported as ready
when one gate was quietly skipped is worse than one reported as broken, because the next failure
will be attributed to the code instead of the setup.
[Host detection](scripts/detect.py) and [environment checks](scripts/gates.py)
automate these measurements; run checks with the target interpreter. Use
`--python-only` for Python/native work. On failure use the measured mismatch
to select the remedy, then repeat the failed check.
+39 -37
View File
@@ -5,43 +5,45 @@ description: Recover explicit policy semantics from upstream training configs or
# Adapt an existing policy
1. Use [onboard-asset](../onboard-asset/SKILL.md) to identify the matching
model, actor and training configs. Treat a Tier 1 recommendation with
`needs_metadata` as a request to recover policy semantics.
2. If the source supplies a complete `mjrl-policy-adapter/1` document, use it
directly. Otherwise extract evidence from the matched config files.
Apply the [diagnosis and closeout loop](../../../docs/ROBOT_ONBOARDING_LESSONS.md).
An adapter graph match, source-policy quality and deployed motion are separate
claims with separate evidence.
```bash
python scripts/onboard.py extract-tier1 env.yaml agent.yaml --model robot.xml \
--output metadata-draft
```
1. Identify the matching actor, model and source runtime/configuration. Without
the actor, original-policy adaptation is blocked; continue supported asset
work through [onboarding](../onboard-asset/SKILL.md). Config filenames are not
a contract: recover semantics from matching declarative data, source code or
the live source managers. Static extraction cannot resolve arbitrary imports,
inheritance or expressions. Record unresolved fields instead of guessing.
2. Establish the complete named contract: observation terms, units, frames,
ordering, normalization, clipping and history; actor inputs/outputs; raw
action order, physical target scales, home, limits, gains and control rate.
Joint inventories, default-angle dictionaries, compiled order and tensor
widths each establish different facts. Verify actual interpreter, module
paths, dependency versions and physics settings when replaying a reference.
3. Review extracted provenance, conflicts and missing fields against that
evidence. Keep model facts distinct from learned-policy semantics. A complete
`mjrl-policy-adapter/1` document can be used directly; extraction drafts need
reviewed overrides and a ready manifest before automatic adaptation.
4. Choose only a transformation the target runtime supports. For zero-scale
held channels with raw previous-action observations, baking scales into actor
outputs loses history. Preserve the full raw output/history and explicit
per-channel scales when supported; never divide by zero or invent history.
A zero residual scale can still command a powered position hold.
5. Verify observation construction and history over multiple steps and resets,
then actor/normalizer outputs, physical target and servo response, and native
trajectories. Match the source order of target transforms and effort limits;
use out-of-range actions to distinguish clipping orders. Prove any version compatibility rewrite by semantic
and response comparisons. Refuse unsupported contracts or unresolved fields.
6. Measure requested command responses on the adapted model. Hand the exact
actor, layout, provenance, parity results and measured limitations to
[deploy](../deploy/SKILL.md) if packaging is requested.
Review `metadata.json` and the provenance, conflicts, `missing_fields` and
`unresolved` entries in `manifest.json`. An incomplete extraction writes
the draft and exits 1. Python inputs are read as static syntax only.
Resolve unknown imports, inheritance or expressions from source evidence
and record the confirmed values in a JSON or YAML overrides file. The
actor's observation and action definitions establish channel order.
A joint-name inventory, a dictionary of default angles, MuJoCo joint order
and graph widths each establish different facts.
3. Rerun extraction with `--overrides reviewed.json --output metadata-ready`.
Require `ready: true` in the manifest. Review ordered observation terms,
history, joint and action order, home pose, scaling, gains, limits and rate.
Run the adapter with the exact model.
## Execution aids
```bash
python scripts/onboard.py adapt-tier1 actor.onnx --metadata metadata-ready/metadata.json \
--model robot.xml --output policy --report adapter-report.json
```
After review, `--config env.yaml --config agent.yaml --overrides reviewed.json`
can replace `--metadata` and run the same extraction during adaptation.
4. Review the adapter parity result and layout against the supplied semantics.
Build a verification config for the ONNX controller with `kind: rl_onnx`,
its relative `policy` and `layout` paths, and the robot root when needed.
Run native command probes with meaningful expected motion and tolerances.
5. Package a compatible controlled mode only with passing verification for
those files. Use [deploy](../deploy/SKILL.md) and replay the resulting app.
A graph comparison verifies the transformation. Native command response
establishes how the adapted controller moves that model.
Use `onboard.py extract-tier1` for supported config formats, reviewed overrides
for source-confirmed values, and `adapt-tier1` for implemented transformations.
An incomplete extraction writes a draft and exits 1. See [extraction](../../../docs/CONTROLLER_SETUP.md#extract-metadata-from-upstream-configs)
and [Usage](../../../docs/USAGE.md) for syntax. A source contract outside the
helper's scope needs an explicitly supported runtime route, not a fabricated
ready manifest.
+56 -22
View File
@@ -5,27 +5,61 @@ description: Set up a deterministic native MuJoCo controller for a complete robo
# Set up deterministic control
1. Inspect the model with [onboard-asset](../onboard-asset/SKILL.md).
Choose a controller from the actual kinematics and intended motion.
Confirm joint axes and limits, actuator semantics, effort, and rates.
2. Declare a JSON controller config with its `kind`. Use
`joint_sliders` for named position joints, `ik` for a
named chain and end-effector site or body, `differential` or `omni` for
measured wheel geometry, and `trajectory` or `cpg` for explicit motions.
The `direct` API can inspect authored actuator inputs, but a packaged
`model_viewer` must have `actuators: []` and carries no control claim. Choose
one of the verified control kinds above for a controlled application.
3. Run setup to a fresh path.
Apply the [diagnosis and closeout loop](../../../docs/ROBOT_ONBOARDING_LESSONS.md)
after [asset inspection](../onboard-asset/SKILL.md).
```bash
python scripts/onboard.py setup-tier2 --model robot.xml --config setup.json --output control
```
1. Define the intended motion, conditions and expected physical response. Choose
control from inspected kinematics: named position joints, an IK chain and
end-effector, measured wheel geometry, or an explicit trajectory/CPG. For
an interactive arm, offer a draggable Cartesian target at a verified tool
point. Establish its reachable workspace, keep the gripper independent and
exercise mouse selection, translation and release in the packaged viewer.
Verify that a click from the startup view selects the target when a payload
or the tool overlaps it. A scripted Cartesian command bypasses picking. A model
viewer carries no control claim and must have `actuators: []`; the direct API
can inspect authored inputs but does not make a packaged viewer controlled.
2. Establish named joint/actuator mapping, axis signs, units, target semantics,
limits, effort and rate. Distinguish authored parameters from newly chosen
controller values. Passive joint damping and servo `kd` are separate; avoid
adding the same damping twice. When normalizing a position servo, compare
its compiled target-limited flag, target range and effort range before and
after. A continuous hinge can have a bounded servo input. Convert that
interval through the transmission and intersect applicable joint travel.
Set the joint near each target edge and command just beyond it. Compare
applied effort below the force cap, where a lost clamp is observable.
Record the initial state and the selected keyframe if one is available.
3. Preserve the intended mounting, gravity and contacts. Probe the initial
state, joint margins, drift and effort headroom before increasing amplitude;
check a grounded stance only if the task depends on it.
A plausible keyframe or stable hold does not establish dynamic capability.
If an authored rest pose fails a limit-margin check, measure the margin in
joint units and as a fraction of travel. When the task allows an interior
rest, test it on the source model, then use it for both reset and operator
release. For tasks that require an end stop, test that contact explicitly.
Diagnose insufficient authority, clipping, sign errors or contact problems
before changing gains; do not invent physical parameters to pass a probe.
4. Write the supported controller configuration and
[operator bindings](../controls/SKILL.md). Declare the command envelope as a
controller choice, with evidence for its usable range. Keep generated assets
separate from source files.
5. Compare commanded and measured motion in task coordinates. If the direction
is wrong, bypass the binding with a named target to distinguish input mapping
from transmission or frame errors. For an operation on an object, measure the
object outcome as well as actuator travel. For a load test, record the compiled
payload mass, free degrees of freedom and initial support. During a hold,
measure object clearance, contact forces on the intended gripper surfaces,
absence of external support and object drift in the gripper frame across the
full interval. After opening, check that support transfers back and the
gripper can withdraw. Repeat the same arm motion with the grasp disabled to
distinguish carrying from incidental support. Review physics and
control results separately and repeat affected probes after edits.
6. If packaging is requested, hand the tested model, controller, bindings
and native probe results to [deploy](../deploy/SKILL.md).
Use the resulting `robot.xml` and `controller.json`. Inspect the optional
`controls.yaml` with the [controls skill](../controls/SKILL.md).
4. Run `onboard.py verify` with a probe JSON that references the generated
controller and controls and declares expected measured responses. Use
[Tutorial](../../../docs/TUTORIAL.md) for a runnable joint-slider example.
Read both the physics and control stages and repeat after any relevant edit.
5. Package with the exact evidence and replay the app with finite steps.
Report observed responses, limits, and any failing probe.
## Execution aids
Use `onboard.py setup-tier2` to generate a supported controller and `verify` to
measure it. Inspect model parameters directly or through `model_evidence` when
useful; policy extraction is not required. Schemas and a runnable joint-slider
example are in [Usage](../../../docs/USAGE.md) and
[Tutorial](../../../docs/TUTORIAL.md).
+31 -22
View File
@@ -3,26 +3,35 @@ name: tier3-train
description: Calibrate a floating-base biped, quadruped, wheeled biped, or multipod for locked-template locomotion training, then scaffold and run measured replay.
---
# Calibrate and train a legged robot
# Calibrate and prepare locomotion training
1. Run [onboard-asset](../onboard-asset/SKILL.md). Establish the family, named
supports, single floating root, explicit locomotion intent, and joint
control semantics. Wheeled bipeds require named unlimited wheel hinges.
2. Prepare stance JSON with the seed pose, named supports, optional height
adjustments, and measured effort limits. Run
`python scripts/onboard.py calibrate --model robot.xml --config stance.json
--report calibration.json`. Inspect the measured contact loads, drift,
limits, effort headroom, and complete report before using it.
3. Follow [new-task](../new-task/SKILL.md) to generate the literal robot spec.
Supply explicit action scales and reuse the passing report for the same
XML and compiled dependencies. If operator input is requested, generate
bindings before scaffolding and set `controls_path` in the scaffold JSON.
Use `--profile differential` for a wheeled biped so A/D command yaw.
Keep robot-specific changes in data.
4. Follow [train](../train/SKILL.md). Verify discovery and a backend smoke
before allocating a learning run. Measure the selected checkpoint on
trained ranges with the required command and observation-noise setting.
5. If packaging is requested, export with `--native-layout` and verify the
exported model, controller and bindings. The native layout supports the
wheeled-biped template's hybrid position and velocity targets. Follow
[deploy](../deploy/SKILL.md) for the selected runtime.
Apply the [diagnosis and closeout loop](../../../docs/ROBOT_ONBOARDING_LESSONS.md).
Walking is the default training objective for humanoid intake. Include forward
and reverse speeds, turns in both directions, and a stop in the command
envelope. Select usable magnitudes from measured gait and tracking results.
1. Establish the inspected family, named supports, single floating root and joint
control semantics through [onboarding](../onboard-asset/SKILL.md). Wheeled
bipeds require named unlimited wheel hinges. Confirm that a supported locked
template represents the intended motion before creating a task.
2. Prepare a separate training asset only as needed. The template owns terrain
and calibrated reset state: remove source ground, source reset keyframes and
any `size.nkey` allocation hint together. Review terrain collision masks and
replacement floor pairs while retaining intended self-contact pairs. Check
that new ground does not inherit disabled robot collision defaults.
3. Calibrate a grounded stance using measured contact loads, drift, joint limits
and effort headroom. Separate passive damping from servo damping and preserve
source-backed physical limits. Test the chosen pose rather than treating an
authored keyframe or a successful static hold as a dynamic gait solution.
4. Establish physical action authority by named channel: raw actor value to
target, target clipping, applied effort and achievable excursion. Choose
scales with physical units and record their origin. Zero position residual
scale retains powered home hold; velocity scales must be positive and some
locomotion authority must remain active. Do not copy another robot's gains,
posture or action scales merely because its training worked.
5. Pass the matching calibration evidence, exact model and scales to
[task registration](../new-task/SKILL.md), then the registered task to
[training and measured replay](../train/SKILL.md).
Use `onboard.py calibrate` to record stance evidence. See
[Usage](../../../docs/USAGE.md#onboard) for the calibration inputs.
+41 -32
View File
@@ -1,38 +1,47 @@
---
name: train
description: Train or resume a locomotion policy through a locked template, validate backend and run size, replay the checkpoint, and report measured results.
description: Train or resume a locomotion task, diagnose stationary or poor-quality motion, and select a checkpoint using measured replay.
---
# Train and measure
# Train and evaluate locomotion
1. Confirm the robot appears in `scripts/train.py --list`. Use
[new-task](../new-task/SKILL.md) when the robot still needs registration.
Run `.claude/skills/setup-env/scripts/detect.py` and verify the environment
with the [setup skill](../setup-env/SKILL.md) when needed.
2. Resolve with `--dry-run`. Use `native:cpu` for the CPU path or `warp:cuda`
for a supported CUDA installation. A small environment count and one
iteration exercise the path. Choose the learning run size from the
backend's available memory and measured throughput. If Warp reports an
overflow, raise `--warp-max-constraints N` for per-world constraints or
`--warp-max-contacts N` for the shared contact pool and rerun the smoke.
Use positive integers. Training saves the selected and effective capacities
in `warp-allocation.json` beside the checkpoints. Warp resume, replay, and
export use that record with the current task or scene capacity floor.
Explicit flags override the saved setting and floor.
3. Run `scripts/train.py --task <robot_id>` with the chosen backend, device
and environment count. Use `--headless` for unattended runs. Watch
tracking rewards, episode lengths, termination counts, action spread,
and curriculum level. Use `--resume` for the latest run or
`--checkpoint <path>` for a specific one. On resume, an iteration override
counts additional iterations.
4. Run `scripts/play.py --task <robot_id> --checkpoint <path> --headless
--steps <count> --speed 0 --measure`. Use `--checkpoint-command-ranges`
for the saved curriculum range. For a fixed command inside that range,
add `--command <vx> <vy> <yaw_rate> --evaluation-out <json>`. Match replay
physics to training and report the observation noise setting.
5. Report the checkpoint, backend, environment count, iteration count,
evaluation command and duration, measured tracking, and resets. Describe
a one-iteration smoke as an execution check. Record when replay was not
run or results are unavailable.
Start with a [registered, calibrated task](../new-task/SKILL.md) and the
[claim and evidence to collect](../../../docs/ROBOT_ONBOARDING_LESSONS.md).
Use [Train and replay](../../../docs/USAGE.md#train-and-replay) for commands,
checkpoint selection and backend capacity settings.
See the [tutorial](../../../docs/TUTORIAL.md) for the end-to-end sequence.
1. **Establish a comparable baseline.** Record the task, checkpoint, backend,
physics/control rates, noise setting, evaluation commands and duration.
Check that the named observations, history, normalization, home and action
mapping still mean the same thing before resuming. If incompatible, keep
the old recipe and treat the new one as a separate experiment. Attribute a
reference adaptation, warm start or from-scratch run accurately.
2. **Run a bounded pilot.** Resolve the task, smoke-test the selected backend
and size the run from available memory and throughput. An overflow needs a
corrected allocation and a new smoke. A completed update proves execution.
Use headless measurement for unattended replay; plotting must not open a GUI.
3. **If commands produce little movement**, trace a named channel from raw
action through the target transform, limits and applied effort to measured
joint and body motion. Scale is in target units per policy unit, not a
clipping bound. Check contact/reset feasibility before attributing the
result to learning. Compare held and active channels separately.
4. **If the task pays for the wrong behavior**, compare reward per unit time
for the failure and an attempted improvement at the same command. Include
per-event terms, timestep, unused axes and penalties on channels without
physical authority. A partial budget suggests an experiment; it does not
establish a cause. Test the predicted improvement in a bounded ablation
before spending more iterations. If using a frozen teacher, verify matched
pre-action observations and masks across resets, frozen normalization, and
learner-only replay.
5. **Select by measured behavior.** Compare commanded and actual responses,
resets and effort across the claimed conditions. For stepping gaits, measure
complete swings per limb and environment, timing, clearance, coordination
and joint excursions. Exclude events crossing a reset or window boundary;
retain chatter. Measure slip at the contact point and effort fast enough to
observe clipping, or label a proxy and its limits. Use appropriate measures
for rolling or other motion. Derive thresholds from the task and a comparable
reference, never from a different robot's accepted checkpoint.
Report whether to continue, reject or hand off the selected checkpoint, with
the measurements behind that decision. If export is requested, pass the recipe,
contract, tested envelope and open quality issues to [deploy](../deploy/SKILL.md).
+8 -2
View File
@@ -32,10 +32,16 @@ Read an applicable `SKILL.md` in full before starting the work.
| [new-task](.claude/skills/new-task/SKILL.md) | Create the data-only robot specification and verify discovery. |
| [train](.claude/skills/train/SKILL.md) | Run or resume training and report measured replay results. |
| [controls](.claude/skills/controls/SKILL.md) | Bind keys and pad controls using the shared vocabulary. |
| [deploy](.claude/skills/deploy/SKILL.md) | Export and package policies for the supported host. |
| [deploy](.claude/skills/deploy/SKILL.md) | Verify and package a viewer, deterministic controller or policy for the supported host. |
| [bundle-manual](.claude/skills/bundle-manual/SKILL.md) | Translate the built application's operator manual. |
Every new skill belongs in this table. The template directories carry their own
lock instructions. Onboarding writes one literal `robot_spec.py` per robot and
lock instructions. Tier 3 registration writes one literal `robot_spec.py` per robot and
keeps the calibrated asset, controller, reports, and controls outside the locked
templates.
## Maintain skills after every robot intake
Every new intake, including failed or blocked work, ends with the
[case report and skill review](docs/ROBOT_ONBOARDING_LESSONS.md#required-closeout-for-every-new-robot).
Apply any transferable correction to the owning skill before handoff.
+3
View File
@@ -4,6 +4,9 @@ The project is a generic robotics onboarding, simulation, and training platform.
Choose an intake route in [Workflow](docs/WORKFLOWS.md). Use
[Usage](docs/USAGE.md) for commands and [Contributing](CONTRIBUTING.md) for layout.
Apply the mandatory [per-robot skill maintenance rule](AGENTS.md#maintain-skills-after-every-robot-intake)
to every intake.
## Checks
Run from the repository root with the editable install active.
+73 -3
View File
@@ -34,6 +34,23 @@ the number of substeps. Set gains and effort limits for your model. The bench
defaults are `kp: 40`, `kd: 4`, and `effort_limit: 30` for position and CPG
controllers, or `kv: 5` and `effort_limit: 30` for velocity actuators.
For `ik`, `joint_sliders`, `trajectory`, and `cpg`, each of `kp`, `kd`, and
`effort_limit` accepts either one scalar or a map covering every name in `joints`
exactly. Maps are resolved by name, independently of actuator order. Values must
be finite; `kp` and `effort_limit` must be positive and `kd` nonnegative. For
example, `"kp": {"hip": 70, "shoulder": 30}` gives those two controlled joints
different stiffnesses. Missing or extra names and positional arrays are rejected.
Normalization intersects the requested effort with the source actuator force
limits, pure motor input limits, and joint actuator-force limits. Source force
and motor input bounds are converted through the authored gear before creating
unit-gear actuators. Position and velocity target ranges are not effort limits.
The resulting model retains the effective bounds even when the configuration
requests a larger effort. Each joint must retain effort authority in both
directions. CPG clips its computed effort to the smaller magnitude of the two
effective bounds; position servos retain the asymmetric bounds when present.
| `kind` | Required inputs | Output |
|---|---|---|
| `ik` | `joints`. Provide `site`, or select `end_effector_body` and optional `end_effector_offset` in its local frame | Position targets from damped least-squares IK |
@@ -51,9 +68,12 @@ of the other verified kinds. A viewer never advances robot dynamics.
A new IK site defaults to `mjrl_ee`. If `end_effector_body` is omitted, setup follows
the chain from the last named joint to its unique leaf. A branching chain needs an
explicit endpoint. Setup places a collision-free target sphere on a `mocap=true`
body named `mjrl_target` unless a different `mocap_body` is configured. Drag that
sphere in the MuJoCo viewer, or send `target_x`, `target_y`, and `target_z` as
world-space offsets from its starting position. IK solves for the site position.
body named `mjrl_target` unless a different `mocap_body` is configured. A generated
marker starts at the tool point in the verified reset pose. An existing mocap
target keeps its authored origin unless `start_target_at_site` is set. Use
the [viewer drag controls](CONTROLS.md#deterministic-controller-controls), or
send `target_x`, `target_y`, and `target_z` as world-space offsets from the
starting position. Both paths use the configured axis bounds. IK solves for the site position.
The solver leaves other joints and the simulated position untouched.
Joint sliders accept a partial map of joint names to targets and hold other
@@ -61,6 +81,25 @@ targets. The MuJoCo viewer's Control panel can also set these targets directly.
The generated controls bind the first four axes unless `operator_axes` selects
another subset. `command_ranges` can narrow command travel per axis.
Set `"target_rate_limits": {"elbow": 0.5}` to limit the speed of selected
slider targets. Give a positive finite maximum in rad/s for each hinge or m/s
for each slide. Unlisted joints take the requested target immediately. At each
controller tick a limited target moves toward the requested position by at most
the configured rate times elapsed simulation time. A single named command,
viewer slider edit, or release-button tap latches the destination until it is
reached or replaced. Reset starts from the actual joint positions. Measure the
resulting effort and settling time under the intended load when choosing rates.
For a calibrated slider pose, supply `home` as a finite map covering exactly
`joints`, with each value inside both its physical limits and declared command
range. Without `home`, the operator rest uses the model reference pose, clipped
to the joint limits. `home` sets the operator rest and release targets; it does
not move the simulated robot on reset. Reset holds the actual supplied joint
positions. Supply the calibrated initial `pose` and base position to verification
so the packaged application starts from that verified state. Escape or the pad's
release button restores only operator-bound joints to `home`, preserving targets
on unbound joints such as supporting legs.
Trajectory files use `schema: "mjrl-trajectory/1"`, `joint_order`, strictly
increasing `time_s` from zero, and one `q` row per timestamp. Positions interpolate
linearly in time and hold at the last keyframe. Set `loop: true` for a loop whose
@@ -301,3 +340,34 @@ and 0.00304 rad/s in final joint velocities. The policy failed separate forward
and yaw tracking probes. It finished at −0.00148 m/s for a 0.08 m/s request
and 0.02854 rad/s for a 0.15 rad/s request. This smoke establishes execution
and export parity on the fixture.
### Explicit sensor frames and calibrated motors
The default base observations use the authored root body frame. An upstream
policy may instead observe an IMU site's angular velocity while keeping gravity
in the root frame. Declare only the overridden terms in `observation.frames`:
```json
{"observation": {
"terms": [{"name": "base_ang_vel"}, {"name": "projected_gravity"}],
"frames": {"base_ang_vel": {"kind": "site", "name": "imu"}}
}}
```
Frames apply to `base_ang_vel`, `base_lin_vel` and `projected_gravity`; each must
name an observed term and an existing `body` or `site`. Local velocities use that
frame's origin. These contracts use `mjrl-native-layout/1` to prevent a legacy
reader from silently applying different sensor semantics.
For an actor trained with a calibrated BAM motor, install the optional `bam`
extra under Python 3.12. In the top-level `motor_model` block, set `kind` to
`bam` and provide the calibrated `motor_name`, `model`, firmware gain `kp`,
supply voltage `vin`, current limit `max_current`, supply resistance
`vin_drop_resistance` and minimum voltage `vin_min` from the training setup.
This opt-in law requires position targets and replaces the ordinary PD effort
calculation. `motor_model.kp` is a firmware gain, distinct from the export's
`control.kp`. The declared effort limit still bounds output. BAM updates
load-dependent friction and damping at every physics tick, resets independently
for each probe, and updates passive friction with actuation disabled for the
counterfactual. Native bundles pin `better-actuator-models==1.0.2` and declare its
Python `>=3.12,<3.13` requirement. The original actor is not retrained.
+16 -7
View File
@@ -18,13 +18,18 @@ The generated command is `twist` feeding `velocity_commands`. Its axes are
`lin_vel_x`, `lin_vel_y`, and `ang_vel_z`, in that order. Pad deflections
scale to the command range, with separate positive and negative ends.
Keyboard keys bind directly to an axis direction and ramp while held.
The default `omni` profile uses W/S for forward and backward, A/D for
lateral movement, and J/L for turning. Use `--profile differential` for
the wheeled-biped template. W/S still drive forward and backward, A/D turn,
and the arrow keys mirror WASD. On the pad, Ly drives forward and backward
and Rx turns. The lateral channel stays in the three-axis layout. It is
unbound on the keyboard, and the template gives the required Lx pad
binding a zero command range.
For a registered task the generator selects a layout by family. Bipeds and
as-yet unregistered robots default to `walking`; other legged families use
`omni`, except wheeled bipeds which use `differential`. An explicit
`--profile` overrides that choice.
The `walking` layout uses W/S for forward/reverse and A/D for
left/right yaw. The arrow keys mirror WASD. J/L request left/right lateral
motion on policies that support it. The pad uses Ly for forward speed, Lx
for lateral speed and Rx for yaw. Holding W+A combines forward and left turn.
The explicit `omni` layout keeps A/D for lateral motion and J/L for yaw.
Use `--profile differential` for a wheeled biped; its lateral axis is
unbound on the keyboard and has a zero command range in the template.
Use `--bind AXIS=SOURCE+` or `--bind AXIS=SOURCE-` for explicit signs and
`--release BUTTON` for the pad release. Review the direction of motion and
@@ -39,6 +44,10 @@ joint sliders or targets can be addressed through the programmatic controller.
Run native verification with the exact controller and controls paths. After
changing bindings, generate a fresh report before packaging.
For end-effector IK, double-click the tool target marker, then hold Ctrl
and drag with the right mouse button. Add Shift to change the translation
plane. Release the button to hold the selected target.
## Shared schema
The schema describes a list of command terms and the bindings for both
+12 -6
View File
@@ -1,6 +1,6 @@
# 操作控制
<!-- tracks: CONTROLS.md @ sha256:bc51703abef90b63 -->
<!-- tracks: CONTROLS.md @ sha256:42ec9ffccdd8a735 -->
`controller/vocabulary.json` 定义键盘和手柄的控制名称。
`python -m controller --vocabulary` 可显示词表。
@@ -17,11 +17,14 @@ python .claude/skills/controls/scripts/write_controls.py --task my_robot \
命令 `twist` 送到 `velocity_commands`,轴顺序为 `lin_vel_x`、
`lin_vel_y`、`ang_vel_z`。摇杆的正负两侧分别按命令范围缩放。
键盘直接绑定方向,按住时逐渐增大。默认 `omni` 配置用 W/S 控制前后、
A/D 控制横移、J/L 控制转向。轮足双足模板使用 `--profile differential`。
此时 W/S 仍控制前后,A/D 控制转向,方向键与 WASD 对应。
手柄的 Ly 控制前后,Rx 控制转向。三轴布局仍保留横向通道,键盘不绑定此轴,
模板将格式要求的手柄 Lx 绑定的命令范围设为零。
已注册任务按形态选择布局。双足人形和暂未注册的机器人默认用 `walking`,轮足
双足用 `differential`,其余足式任务用 `omni`。可用 `--profile` 显式指定。
按键按住时,命令逐渐增大。`walking` 布局用 W/S 控制前进和后退,
A/D 控制左转和右转,方向键与 WASD 对应。支持侧移的策略还可以用 J/L 左右侧移。
手柄的 Ly、Lx 和 Rx 分别控制前后、侧移和转向。按住 W+A 可边前进边左转。
显式选择 `omni` 可使用 A/D 侧移、J/L 转向的布局。轮足双足使用
`--profile differential`,其横向轴无键盘绑定,模板中的横向速度范围为零。
用 `--bind AXIS=SOURCE+` 或 `--bind AXIS=SOURCE-` 指定符号,
用 `--release BUTTON` 设置手柄释放键。在仿真检查方向和释放动作,
@@ -33,6 +36,9 @@ A/D 控制横移、J/L 控制转向。轮足双足模板使用 `--profile differ
`operator_axes` 最多选四个轴,其余关节滑块或目标可通过程序接口控制。
打包前验证实际使用的控制器和绑定。修改后重新生成报告。
在末端控制模式下,双击末端的目标标记,按住 Ctrl 并用鼠标右键拖动。
同时按住 Shift 可切换拖动平面,松开鼠标后保持当前位置目标。
## 共享格式
命令列表声明名称、输出位置、坐标系、有序的轴和满幅缩放规则。每个轴有单位与
+59
View File
@@ -0,0 +1,59 @@
# Robot onboarding: diagnosis and skill maintenance
Start with the requested capability and operating conditions. Use the
[route table](WORKFLOWS.md) to select the applicable [stage skills](../AGENTS.md#skills).
A route recommendation is provisional until its required inputs are confirmed.
## Establish the claim before choosing tools
Derive observable pass criteria from the request and available evidence before
choosing a candidate. Use the rows relevant to the request:
| Claim | Evidence |
|---|---|
| The model loads | Resolve dependencies; inspect the compiled topology, units and frames. |
| The physical model supports the task | Check the intended initial state, constraints, joint margins and loads. Measure ground contact and stance only where relevant. |
| Commands work | Compare requested and measured physical responses across the claimed range, including rest or transitions where meaningful. |
| Motion has the requested quality | Pick measures suited to the mechanism and task; inspect individual components as well as the aggregate. Retain representative replay. |
| An export is faithful | Compare source and target behavior at matched inputs and states, then compare trajectories on the declared runtime. |
| The package works | Run the final archive with its actual dependencies and controls on its supported host. |
| Motion meets a subjective requirement | Present representative evidence and record the user's verdict separately. |
Record each relevant claim as **passed, failed or untested**; mark a potentially
confusing but inapplicable check **not applicable** and say why. Keep partial
passes when the overall request fails. A missing required probe is a coverage
gap; it is not a measured failure of that probe.
## Diagnose one layer at a time
1. Reproduce the first failing claim. Identify the exact inputs, runtime,
conditions and measurement; distinguish source facts, chosen values and
unknowns. Preserve the baseline and source provenance.
2. Trace the relevant path from input to outcome. For example, if a control
moves the wrong way, compare device input, commanded target and measured
movement before tuning gains. If only an export fails, compare it against
the working source at the first step where they differ. Skip stages the
route does not use.
3. State a possible cause, a check that distinguishes it from an alternative,
the predicted result and what decision each outcome would support. Prefer
a shared instrument when it measures the right quantity; otherwise inspect
source data or design a bounded probe. No robot-specific helper is required.
4. Change the smallest justified factor. Repeat the failed check under the
same conditions and check previously working behavior affected by the edit.
Tie results to the applicable artifacts and settings (hashes where available).
Report the margin for borderline passes. Leave the cause open if the evidence
does not distinguish it; do not relax a criterion after seeing the result.
## Required closeout for every new robot
Put one review in the robot's case report at completion or when blocked:
| Record | What to enter |
|---|---|
| Scope and evidence | Requested capability, source and missing inputs, applicable gate outcomes, artifacts, conditions and limits. |
| Diagnosis | Symptom → measurement → cause or uncertainty → change → retest result, or the next distinguishing test. |
| Skill decision | Name the owning skill. Add or correct the reusable decision there; if covered, identify the existing rule the case confirmed. Keep robot names, values, paths and experiments in the case report. |
| Validation | Record what was checked. For a changed decision, try a different mechanism or missing-input case without relying on the original helper. Verify links and skill metadata. |
Review even if no candidate passed. This review does not authorize additional
training, deployment or hardware operation.
+27 -5
View File
@@ -77,9 +77,12 @@ and provenance fields written by the CLI.
The calibrated scaffold config names `robot_id`, `family`, `model_path`, and
`action_scales` keyed by calibrated position-joint name. It can also name
`controls_path`, `velocity_joints`, `penalized_contact_geoms`, and
`controls_path`, `velocity_joints`, `foot_sites`, `penalized_contact_geoms`, and
`termination_contact_geoms`. Model and controls paths resolve relative to the
input JSON. The calibration must match the model XML and compiled dependencies.
Optional `posture_stds` is an exact-name map covering every calibrated position
joint with a positive finite value. Scaffolding writes these values into each
joint's `posture_std` and consumes the top-level map; omitting it uses `0.35`.
Without `--calibration`, give a full `RobotSpec` from verified model facts.
This example shows the file shape:
@@ -110,14 +113,27 @@ for quadruped, and five for multipod. A wheeled biped also needs at least two
named unlimited wheel hinges in `velocity_joints`, with `kp: 0`, positive
`kd`, an effort limit, and a velocity action scale.
Optional `posture_std` on each joint is its positive finite posture allowance
in radians, defaulting to `0.35`. It supplies calibration data for the template's
speed-dependent pose term, not a reward weight. Different joints can declare
different allowances without adding robot-specific logic to the template.
Optional `foot_sites` lists one unique, nonempty, unqualified MuJoCo site name
per named foot support, in the same order as `foot_geoms` or `foot_bodies`.
These sites provide authored measurement locations for foot-clearance terms.
The default empty list preserves existing specifications without sites. A
nonempty list must match the support count; use actual sites in the robot model.
Full `RobotSpec` input and literal scaffolding preserve both fields.
Scaffolding writes only `tasks/<robot_id>/robot_spec.py` in the task tree.
The robot ID is the task ID. Family values are `biped`, `quadruped`,
`wheeled_biped`, and `multipod`. The controls file for a locomotion policy
uses the body-frame `twist` term feeding `velocity_commands`, with
`lin_vel_x`, `lin_vel_y`, and `ang_vel_z` in that order. For operator input,
generate the [bindings](CONTROLS.md#training-template-controls) before
scaffolding and set `controls_path` in the input JSON. Choose
`--profile differential` for a wheeled biped to use A/D for yaw.
`lin_vel_x`, `lin_vel_y`, and `ang_vel_z` in that order. A new biped defaults to W/S for forward/reverse and A/D for left/right
yaw. To supply a custom layout, set `controls_path` in the input JSON. See
the [control profiles](CONTROLS.md#training-template-controls) for wheeled
and omnidirectional layouts.
## Train and replay
@@ -141,6 +157,12 @@ and the environment count. A Warp buffer overflow stops the run before it
uses the affected observations. For example, the G1 flat setup uses
`--warp-max-constraints 300`.
EPA horizon overflow is a separate convex-collision scratch-buffer limit;
increasing contact or constraint pools does not enlarge it. The checked Warp
backend reserves at least 128 horizon entries before capturing simulation graphs
(MuJoCo Warp 3.11 defaults to 24), preserves larger upstream buffers, and records
the effective size. It still stops on every reported overflow.
A Warp run saves selected and effective capacities in `warp-allocation.json`
beside its checkpoints. Warp resume, replay, and export read this file when
present. Explicit flags take precedence. Otherwise, the larger of the saved
+23 -5
View File
@@ -1,6 +1,6 @@
# 命令手册
<!-- tracks: USAGE.md @ sha256:3f15279c7bd4459d -->
<!-- tracks: USAGE.md @ sha256:39a53b186c3a2171 -->
用 Python 3.10–3.13 建立环境并执行 `python -m pip install -e ".[dev]"`。
平台配置见[环境准备](AGENT_SETUP.zh.md)。可编辑安装负责连接两个包根目录。
@@ -69,9 +69,11 @@ extraction = extract_policy_metadata(
### 机器人规格
使用标定时,配置提供 `robot_id`、`family`、`model_path` 和按位置关节名称
索引的 `action_scales`。可选 `controls_path`、`velocity_joints`、
索引的 `action_scales`。可选 `controls_path`、`velocity_joints`、`foot_sites`、
`penalized_contact_geoms` 和 `termination_contact_geoms`。模型及控制路径
相对输入 JSON 解析。标定报告须对应实际 XML 和编译依赖。
可选 `posture_stds` 须按名称精确覆盖所有标定的位置关节,每个值均为有限正数。
生成规格时,数值写入各关节的 `posture_std`,顶层映射随之移除;省略时使用 `0.35`。
不传 `--calibration` 时,可根据已验证的模型参数提供完整 `RobotSpec`,格式示例如下:
@@ -98,12 +100,23 @@ extraction = extract_policy_metadata(
多足至少五个。轮足双足还需在 `velocity_joints` 中提供至少两个不限位转动关节,设置 `kp: 0`、
正 `kd`、力矩上限和轮速动作尺度。
每个关节可选 `posture_std`,表示以弧度为单位的姿态容许尺度,须为有限正数,默认
`0.35`。它为模板中随速度变化的姿态项提供标定数据,不是奖励权重。各关节可设置
不同尺度,无需在模板中加入特定机器人的判断逻辑。
可选 `foot_sites` 为每个命名足部支撑指定一个 MuJoCo site,顺序须与 `foot_geoms`
或 `foot_bodies` 一致。名称须唯一、非空且不带实体路径前缀。这些 site 提供抬脚净空项
的模型测量位置。默认空列表兼容不含 site 的现有规格;非空列表的长度须等于支撑数量,
且应引用机器人模型中实际存在的 site。完整 `RobotSpec` 输入及生成的字面量规格都会
保留这两个字段。
仅生成 `tasks/<robot_id>/robot_spec.py`,任务 ID 等于机器人 ID。
形态取值为 `biped`、`quadruped`、`wheeled_biped`、`multipod`。
运动策略的控制文件按顺序提供 `lin_vel_x`、`lin_vel_y`、`ang_vel_z`,
由机体系 `twist` 命令送入 `velocity_commands`。若需要操作输入,在生成规格前先生成
[操作绑定](CONTROLS.zh.md#训练模板),并在输入 JSON 中设置 `controls_path`。
轮足双足应选择 `--profile differential`,让 A/D 控制转向。
由机体系 `twist` 命令送入 `velocity_commands`。新接入的双足人形默认用 W/S 前进和后退,
A/D 左转和右转。可在输入 JSON 的 `controls_path` 指定自定义布局。轮足与全向布局见
[操作绑定](CONTROLS.zh.md#训练模板)。
## 训练与回放
@@ -123,6 +136,11 @@ Warp 的约束和接触容量可用正整数参数 `--warp-max-constraints N`
总容量由每环境设置和环境数决定。缓冲区溢出时,程序会在使用受影响的观测前停止。
例如,G1 平地任务使用 `--warp-max-constraints 300`。
EPA horizon 溢出属于凸体碰撞求解的独立临时缓冲区限制,增加接触或约束容量
不会扩大这个缓冲区。平台的 Warp 后端在捕获仿真执行图前,至少分配 128 个
horizon 条目(MuJoCo Warp 3.11 默认是 24),保留上游更大的容量,并记录
实际大小。所有溢出仍会使运行停止。
Warp 训练会在检查点旁的 `warp-allocation.json` 中记录所选容量和实际容量。
使用 Warp 续训、回放或导出时会读取该文件(如存在)。命令行参数优先,其次取已记录
容量与任务或场景要求中的较大值。若没有运行记录且未配置容量,则由 Warp 自动分配。
+35 -2
View File
@@ -4,6 +4,17 @@ The intake tier describes what the supplied inputs support. A robot can use a
lower tier for visualization or deterministic control even if it also qualifies
for policy adaptation or training.
For a humanoid, the default delivery goal is walking under operator control.
Use a compatible walking policy when available or calibrate and train the
biped. A standing or upper-body demonstration can verify an intermediate
capability. Accept walking after measuring forward and reverse travel, left
and right turns, stopping, and alternating support on the final policy.
For an interactive arm, use a measured end-effector point and a draggable
IK target. An explicit task request takes precedence over these defaults.
Use the [common diagnosis, verification and closeout procedure](ROBOT_ONBOARDING_LESSONS.md)
throughout the selected route.
| Route | Required inputs | Verification and output |
|---|---|---|
| Tier 0 · Model viewing | Mesh, URDF, or MJCF and its dependencies | Compiled MJCF and viewer app |
@@ -31,8 +42,10 @@ build) can recommend Tier 3 with `status: needs_profile` and
Review the candidates, declare the profile and control intent, resolve the
reported `prerequisites`, then calibrate. Missing URDF actuation/effort data
remains an explicit prerequisite, not an inferred motor specification. An
explicit profile takes precedence over automatic routing; policy adaptation
retains its existing priority. No directory watcher or automatic training is
explicit control intent takes precedence over the humanoid default. For the
default walking route, check that the candidate policy accepts both signs of
forward speed and yaw before choosing adaptation. A scene that includes a
floor may need its robot-only model before calibration. No directory watcher or automatic training is
started by inspection.
Select `--policy` and `--metadata` when the directory
@@ -47,6 +60,26 @@ once the model, actor selection and metadata have passed intake checks.
Resolve missing meshes and inertias, ambiguous model selection, incompatible
actuator semantics, and unresolved metadata before building an application.
## Assets without weights or training configs
A robot description can provide geometry, contact pairs, servo parameters and
keyframes without a learned controller. Select the scene wrapper explicitly
when it supplies the floor and contact pairs. For a reviewable evidence-only
extraction, run:
```bash
python scripts/onboard.py extract-tier1 --model scene.xml --output out/model-draft
```
This writes `metadata.json` and `manifest.json` and exits 1 because policy
semantics remain unknown. The manifest's `model_evidence` includes the compiled
model fingerprint, named joints, actuator parameters and keyframes; it never
fills policy channel orders, scales, observation history or rate from these
physical facts. Supply matching configs and an actor to resume Tier 1.
Meanwhile, Tier 0 or a measured Tier 2 controller can produce an application.
Synthetic actors are separate adapter test fixtures, never recovered weights
or evidence of learned locomotion.
## Normalize the model
Use MJCF directly when it compiles and has the required geometry, frames,
+3
View File
@@ -60,6 +60,8 @@ dependencies = [
[project.optional-dependencies]
dev = ["pytest", "ruff"]
# BAM 1.0.2 requires Python 3.12; requesting this extra on other hosts fails explicitly.
bam = ["better-actuator-models==1.0.2"]
[build-system]
requires = ["setuptools>=64"]
@@ -93,6 +95,7 @@ controller = ["vocabulary.json"]
# Native app builders and validators use these trusted resources in wheels.
# tests/test_app_schema.py checks them against the published files.
"mjrl.platform" = ["app.schema", "LICENSE"]
"mjrl.controllers" = ["walking.yaml"]
[tool.ruff]
line-length = 100
+43 -12
View File
@@ -20,7 +20,7 @@ import yaml
from controller.controls import controller_contract, load_controls
from .controllers.bindings import velocity_controls
from .controllers.bindings import velocity_controls, walking_controls
from .controllers.model import finite, joint_ids, vector
from .platform.graph import TORCHSCRIPT_SUFFIXES, read_embedded_onnx
from .platform.layout import COMMAND_ORDER, JOINT_TERMS, NATIVE_LAYOUT_SCHEMA, STANDARD_TERMS
@@ -102,6 +102,7 @@ def _metadata(source: Mapping | Path) -> Mapping:
"use_default_offset",
"controller",
"root_body",
"motor_model",
},
"policy metadata",
)
@@ -396,6 +397,7 @@ def _observations(
"normalization",
"inputs",
"command_order",
"frames",
},
"observation",
)
@@ -473,6 +475,15 @@ def _observations(
denominator = (std + epsilon).astype(np.float32)
elif normalization not in ("baked_into_onnx", "none"):
raise ValueError("Unknown observation.normalization")
frames = _object(doc.get("frames", {}), "observation.frames")
for name, frame in frames.items():
if name not in {"base_ang_vel", "base_lin_vel", "projected_gravity"} or name not in terms:
raise ValueError("Observation frames require a corresponding base vector term")
frame = _object(frame, f"observation.frames.{name}")
if set(frame) != {"kind", "name"} or frame["kind"] not in {"body", "site"}:
raise ValueError("Observation frames must name a body or site")
if not isinstance(frame["name"], str) or not frame["name"]:
raise ValueError("Observation frame name must be nonempty")
inputs = []
if "inputs" in doc:
for item in doc["inputs"]:
@@ -512,6 +523,7 @@ def _observations(
"history_order": "oldest_first",
"normalization": "baked_into_onnx",
"command_order": command_order,
**({"frames": dict(frames)} if frames else {}),
}, transform
@@ -570,7 +582,9 @@ def _prepare(metadata: Mapping | Path, model=None) -> tuple[dict, _Transform]:
raise ValueError(f"{term['name']}.joint_order must be a subset of obs_joint_order")
names = {term["name"] for term in terms}
native = (
"targets" in doc.get("action", {})
"motor_model" in doc
or bool(observation.get("frames"))
or "targets" in doc.get("action", {})
or bool(passive)
or any(default_vel.values())
or any(isinstance(gain, dict) for gain in control.values())
@@ -619,6 +633,18 @@ def _prepare(metadata: Mapping | Path, model=None) -> tuple[dict, _Transform]:
if not lo <= 0 <= hi:
raise ValueError(f"command_ranges.twist.{axis} must contain zero")
layout["command_ranges"]["twist"][axis] = [float(lo), float(hi)]
if "motor_model" in doc:
from .platform.motors import validate_motor_model
if velocity:
raise ValueError("BAM motor model requires position targets")
layout["motor_model"] = validate_motor_model(doc["motor_model"])
if model is not None:
for frame in observation.get("frames", {}).values():
kind = mujoco.mjtObj.mjOBJ_SITE if frame["kind"] == "site" else mujoco.mjtObj.mjOBJ_BODY
index = mujoco.mj_name2id(model, kind, frame["name"])
if index < 0 or (frame["kind"] == "body" and index == 0):
raise ValueError(f"Model has no observation frame {frame['name']!r}")
if "controller" in doc:
layout["controller"] = dict(_object(doc["controller"], "controller"))
return layout, transform
@@ -886,17 +912,22 @@ def adapt_policy(
layout["_adapter_validation"] = {"max_abs_error": error, "probes": 10}
if active_axes:
tmp_controls = temporary / controls_path.name
tmp_controls.write_text(
yaml.safe_dump(velocity_controls(active_axes), sort_keys=False), "utf-8"
)
generated = controller_contract(load_controls(tmp_controls), None)
supplied = layout.get("controller", generated)
if any(
supplied.get(key) != generated[key]
for key in ("schema", "command", "task", "devices")
):
supplied = layout.get("controller")
# Prefer the walking layout for new exports. Existing actor metadata
# may explicitly contract the earlier, equally valid velocity keys.
for make_controls in (walking_controls, velocity_controls):
tmp_controls.write_text(
yaml.safe_dump(make_controls(active_axes), sort_keys=False), "utf-8"
)
generated = controller_contract(load_controls(tmp_controls), None)
if supplied is None or all(
supplied.get(key) == generated[key]
for key in ("schema", "command", "task", "devices")
):
layout["controller"] = generated
break
else:
raise ValueError("Supplied controller metadata differs from generated controls")
layout["controller"] = generated
for path, value in ((layout_path, layout), (config_path, config)):
(temporary / path.name).write_text(
json.dumps(value, indent=2, allow_nan=False) + "\n", "utf-8"
+10 -1
View File
@@ -232,8 +232,17 @@ class _NativeData:
def __init__(self, buffers: dict[str, np.ndarray], num_envs: int) -> None:
object.__setattr__(self, "_np", buffers)
tensors = {k: torch.from_numpy(v) for k, v in buffers.items()}
# mjwarp exposes mat33 fields with two trailing matrix dimensions.
# Keep MuJoCo's flat NumPy buffers for gather/scatter, but give entity
# pose readers the same matrix layout as Warp. Reshape shares memory:
# future native forward calls still update already-held tensor views.
for name in ("xmat", "site_xmat", "geom_xmat"):
if name in tensors:
value = tensors[name]
tensors[name] = value.reshape(*value.shape[:-1], 3, 3)
object.__setattr__(
self, "_t", {k: torch.from_numpy(v) for k, v in buffers.items()}
self, "_t", tensors
)
# mjwarp's Data has nworld (the world count) and mjlab's entity, sensor
# and offscreen_renderer all read it. Native MjData has no such concept, so
+2
View File
@@ -67,4 +67,6 @@ def write_warp_allocation(run_dir: Path, sim) -> None:
"allocation": {field: getattr(sim.cfg, field) for field, _ in _FLAGS},
"effective": {"njmax": data.njmax, "naconmax": data.naconmax, "nworld": data.nworld},
}
if hasattr(sim, "epa_horizon_capacity"):
record["effective"]["epa_horizon"] = sim.epa_horizon_capacity
(run_dir / FILENAME).write_text(json.dumps(record, indent=2) + "\n")
+38 -2
View File
@@ -7,6 +7,31 @@ from mjlab.sim import Simulation
from mujoco_warp._src.types import OverflowType
# EPA stores its temporary horizon per convex pair, independently of the
# contact/constraint pools. MuJoCo Warp 3.11's 24 entries can exhaust during
# otherwise valid deep mesh contacts. The kernels bound writes by array shape.
EPA_HORIZON_CAPACITY = 128
def _ensure_epa_horizon_capacity() -> int:
"""Raise host scratch allocation before initialization and graph capture.
These module globals size host allocations, not Warp compile-time constants.
Leave installed files and collision algorithms untouched, and never reduce a
newer upstream capacity. Apply to rigid and flexible collision paths alike.
"""
from mujoco_warp._src import collision_convex, collision_flex
modules = (collision_convex, collision_flex)
capacities = [getattr(module, "MJ_MAX_EPAHORIZON", None) for module in modules]
if any(type(value) is not int or value <= 0 for value in capacities):
raise RuntimeError("Unsupported MuJoCo Warp EPA scratch allocator; update the platform compatibility shim.")
capacity = max(EPA_HORIZON_CAPACITY, *capacities)
for module in modules:
module.MJ_MAX_EPAHORIZON = capacity
return capacity
@wp.kernel(enable_backward=False)
def _collect_overflow(
flags: wp.array(dtype=int),
@@ -32,6 +57,7 @@ class CheckedWarpSimulation(Simulation):
"""Preserve sticky flags across resets and check once per observation."""
def __init__(self, *args, **kwargs):
self.epa_horizon_capacity = _ensure_epa_horizon_capacity()
super().__init__(*args, **kwargs)
self._overflow_report = wp.zeros(3, dtype=int, device=self.wp_device)
@@ -58,10 +84,20 @@ class CheckedWarpSimulation(Simulation):
if flags or constraints or contacts:
data = self.wp_data
kinds = OverflowType(flags).name if flags else "capacity counters"
advice = []
if flags & OverflowType.EPA_HORIZON:
advice.append(
f"EPA horizon scratch capacity: {self.epa_horizon_capacity} entries per convex pair. "
"This is independent of contact and constraint pools; increase the platform EPA horizon "
"capacity before graph capture and replay the failing collision."
)
if constraints or flags & (OverflowType.NEFC | OverflowType.NJMAX_NNZ):
advice.append("For constraint overflow increase --warp-max-constraints.")
if contacts or flags & (OverflowType.BROADPHASE | OverflowType.NARROWPHASE):
advice.append("For broadphase or narrowphase overflow increase --warp-max-contacts.")
raise RuntimeError(
f"Warp buffer overflow ({kinds}). "
f"Constraint capacity per world: {data.njmax}, demand above capacity: {constraints}. "
f"Shared contact capacity: {data.naconmax}, demand above capacity: {contacts}. "
"For constraint overflow increase --warp-max-constraints. "
"For broadphase or narrowphase overflow increase --warp-max-contacts."
+ " ".join(advice)
)
+16
View File
@@ -1,6 +1,11 @@
"""Generate operator documents for named native command axes."""
from dataclasses import dataclass
from pathlib import Path
import yaml
WALKING_CONTROLS = Path(__file__).with_name("walking.yaml")
@dataclass(frozen=True)
@@ -20,6 +25,17 @@ _VELOCITY = {
}
def walking_controls(axes) -> dict:
"""Bind exactly the body-velocity axes the policy can observe."""
layout = yaml.safe_load(WALKING_CONTROLS.read_text(encoding="utf-8"))
term = layout["command"][0]
by_name = {axis["name"]: axis for axis in term["axes"]}
term["axes"] = [by_name[name] for name in axes]
for device in layout["devices"].values():
device["axes"] = {name: device["axes"][name] for name in axes}
return layout
def velocity_controls(axes, *, differential: bool = False) -> dict:
bindings = {axis: _VELOCITY[axis] for axis in axes}
if differential and "ang_vel_z" in bindings:
+118 -10
View File
@@ -2,6 +2,7 @@
from __future__ import annotations
from collections.abc import Mapping
from dataclasses import dataclass
from numbers import Real
@@ -34,8 +35,10 @@ def joint_ids(model: mujoco.MjModel, names: list[str]) -> np.ndarray:
def joint_actuators(model: mujoco.MjModel, ids: np.ndarray) -> list[np.ndarray]:
# Both joint transmissions have the same length law for hinges and slides.
direct = np.isin(model.actuator_trntype, [_JOINT, mujoco.mjtTrn.mjTRN_JOINTINPARENT])
return [
np.flatnonzero((model.actuator_trntype == _JOINT) & (model.actuator_trnid[:, 0] == joint))
np.flatnonzero(direct & (model.actuator_trnid[:, 0] == joint))
for joint in ids
]
@@ -54,6 +57,60 @@ def vector(value, size: int, field: str) -> np.ndarray:
return np.array([finite(v, field) for v in value], dtype=np.float64)
def joint_values(value, names, field: str, *, positive=False, nonnegative=False) -> np.ndarray:
"""Expand a scalar or exact named map in controller joint order."""
if not isinstance(names, (list, tuple)) or not names or not all(
isinstance(name, str) and name for name in names
) or len(set(names)) != len(names):
raise ValueError("joints must be a nonempty list of unique names")
if isinstance(value, Mapping):
if set(value) != set(names):
raise ValueError(f"{field} must cover controlled joints exactly")
values = [finite(value[name], f"{field}.{name}", positive=positive) for name in names]
else:
values = [finite(value, field, positive=positive)] * len(names)
values = np.asarray(values, dtype=np.float64)
if nonnegative and np.any(values < 0):
raise ValueError(f"{field} must be nonnegative")
return values
def joint_effort_bounds(model, ids, effort) -> np.ndarray:
"""Intersect requested joint effort with authored actuator and joint bounds.
MuJoCo actuator force is before gear transmission; normalize it to joint
effort before replacing an actuator with a unit-gear servo.
"""
bounds = np.column_stack((-effort, effort))
for i, (joint, actuators) in enumerate(zip(ids, joint_actuators(model, ids), strict=True)):
if len(actuators) > 1:
raise ValueError("A controlled joint has multiple actuators")
if len(actuators):
aid = int(actuators[0])
gear = model.actuator_gear[aid]
if not np.isfinite(gear).all() or gear[0] == 0 or np.any(gear[1:] != 0):
raise ValueError("Cannot normalize a non-scalar or zero actuator gear")
if model.actuator_forcelimited[aid]:
low, high = np.sort(model.actuator_forcerange[aid] * gear[0])
bounds[i] = [max(bounds[i, 0], low), min(bounds[i, 1], high)]
# A motor's input is effort, whereas a position/velocity servo's
# ctrlrange is a target range and must never be treated as force.
if (model.actuator_ctrllimited[aid]
and model.actuator_dyntype[aid] == mujoco.mjtDyn.mjDYN_NONE
and model.actuator_gaintype[aid] == mujoco.mjtGain.mjGAIN_FIXED
and model.actuator_biastype[aid] == mujoco.mjtBias.mjBIAS_NONE):
low, high = np.sort(
model.actuator_ctrlrange[aid] * model.actuator_gainprm[aid, 0] * gear[0]
)
bounds[i] = [max(bounds[i, 0], low), min(bounds[i, 1], high)]
if model.jnt_actfrclimited[joint]:
low, high = model.jnt_actfrcrange[joint]
bounds[i] = [max(bounds[i, 0], low), min(bounds[i, 1], high)]
if not bounds[i, 0] < 0 < bounds[i, 1]:
raise ValueError("Controlled joint effort must permit both directions")
return bounds
@dataclass(frozen=True)
class JointControl:
names: tuple[str, ...]
@@ -115,19 +172,70 @@ class JointControl:
return cls(tuple(names), ctrl, model.jnt_qposadr[ids], model.jnt_dofadr[ids], lo, hi)
def _position_limits(model, joint, actuators):
"""Return unit-gear joint targets, respecting the source servo's length units."""
limits = model.jnt_range[joint] if model.jnt_limited[joint] else None
if not len(actuators):
return limits
aid = actuators[0]
if not (model.actuator_ctrllimited[aid] or model.actuator_actlimited[aid]):
return limits
bias_type = model.actuator_biastype[aid]
bias = model.actuator_biasprm[aid]
# Motors and velocity servos do not take position targets.
if bias_type == mujoco.mjtBias.mjBIAS_NONE or (
bias_type == mujoco.mjtBias.mjBIAS_AFFINE and bias[1] == 0
):
return limits
name = model.joint(joint).name
gain = model.actuator_gainprm[aid, 0]
if not (
model.actuator_gaintype[aid] == mujoco.mjtGain.mjGAIN_FIXED
and bias_type == mujoco.mjtBias.mjBIAS_AFFINE
and gain > 0 and bias[0] == 0 and bias[1] == -gain and bias[2] <= 0
and model.actuator_dyntype[aid] in (
mujoco.mjtDyn.mjDYN_NONE, mujoco.mjtDyn.mjDYN_FILTER, mujoco.mjtDyn.mjDYN_FILTEREXACT,
)
and not model.actuator_actlimited[aid]
):
raise ValueError(
f"Cannot infer position target bounds for joint {name!r} "
"from its actuator law or activation limits"
)
# For a scalar joint the actuator length is gear * qpos. Sorting handles
# a reversed transmission, and works for both hinge and slide coordinates.
source = np.sort(model.actuator_ctrlrange[aid] / model.actuator_gear[aid, 0])
if not np.isfinite(source).all():
raise ValueError(f"Nonfinite position target bounds for joint {name!r}")
if limits is not None:
source = [max(limits[0], source[0]), min(limits[1], source[1])]
if source[0] >= source[1]:
raise ValueError(f"Actuator and joint position ranges do not overlap for {name!r}")
return source
def normalize_actuators(
spec: mujoco.MjSpec,
model: mujoco.MjModel,
names: list[str],
kind: str,
*,
kp: float,
kd: float,
effort: float,
kp: float | Mapping[str, float],
kd: float | Mapping[str, float],
effort: float | Mapping[str, float],
speed: float,
) -> None:
ids = joint_ids(model, names)
for joint, name, existing in zip(ids, names, joint_actuators(model, ids), strict=True):
gains = joint_values(kp, names, "kp", positive=kind == "position", nonnegative=True)
damping = joint_values(kd, names, "kd", positive=kind == "velocity", nonnegative=True)
efforts = joint_values(effort, names, "effort_limit", positive=True)
bounds = joint_effort_bounds(model, ids, efforts)
for index, (joint, name, existing) in enumerate(
zip(ids, names, joint_actuators(model, ids), strict=True)
):
if len(existing) > 1:
raise ValueError(f"Joint {name!r} has multiple actuators")
if len(existing):
@@ -140,14 +248,14 @@ def normalize_actuators(
actuator.delay = 0
if kind == "motor":
actuator.set_to_motor()
limits = [-effort, effort]
limits = bounds[index]
elif kind == "velocity":
actuator.set_to_velocity(kd)
actuator.set_to_velocity(damping[index])
limits = [-speed, speed]
else:
actuator.set_to_position(kp, kv=kd)
limits = model.jnt_range[joint] if model.jnt_limited[joint] else None
actuator.set_to_position(gains[index], kv=damping[index], timeconst=0)
limits = _position_limits(model, joint, existing)
actuator.ctrllimited = int(limits is not None)
actuator.ctrlrange = limits if limits is not None else [0, 0]
actuator.forcelimited = 1
actuator.forcerange = [-effort, effort]
actuator.forcerange = bounds[index]
+58 -9
View File
@@ -12,7 +12,7 @@ import numpy as np
from controller.controls import Controls, load_controls
from .input import OperatorInput
from .model import JointControl, finite, object_id, vector
from .model import JointControl, finite, joint_effort_bounds, joint_values, object_id, vector
from .motion import DampedLeastSquaresIK, Trajectory
from .wheels import WHEEL_AXES, mix_velocity, wheel_mixer
@@ -52,6 +52,9 @@ class Controller:
raise ValueError("control_hz must correspond to a whole number of physics steps")
self.command_axes: tuple[str, ...]
self.joints: JointControl | None = None
self._target_rates: np.ndarray | None = None
if "target_rate_limits" in config and self.kind != "joint_sliders":
raise ValueError("target_rate_limits requires joint_sliders")
self.controls: Controls | None = None
self.operator: OperatorInput | None = None
@@ -128,6 +131,9 @@ class Controller:
assert joints is not None
if self.kind == "ik":
self.ik = DampedLeastSquaresIK(self.model, joints, config)
self._start_at_site = config.get("start_target_at_site", False)
if type(self._start_at_site) is not bool:
raise ValueError("start_target_at_site must be boolean")
self.command_axes = IK_AXES
self._spans = [(-np.inf, np.inf, 0)] * 3
self._origin = self.model.body_pos[
@@ -136,6 +142,20 @@ class Controller:
elif self.kind == "joint_sliders":
self.command_axes = joints.names
self._home = np.clip(self.model.qpos0[joints.pos], joints.lo, joints.hi)
if "home" in config:
if not isinstance(config["home"], Mapping):
raise ValueError("home must map every controlled joint by name")
self._home = joint_values(config["home"], joints.names, "home")
if np.any(self._home < joints.lo) or np.any(self._home > joints.hi):
raise ValueError("home lies outside a controlled joint's position limits")
rates = config.get("target_rate_limits", {})
if not isinstance(rates, Mapping) or set(rates) - set(joints.names):
raise ValueError("target_rate_limits must map controlled joint names to rates")
if rates:
self._target_rates = np.array([
finite(rates[name], f"target_rate_limits.{name}", positive=True)
if name in rates else np.inf for name in joints.names
])
self._spans = list(zip(joints.lo, joints.hi, self._home, strict=True))
elif self.kind == "trajectory":
trajectory = config.get("trajectory")
@@ -168,11 +188,12 @@ class Controller:
self._centre + self._amplitude > joints.hi
):
raise ValueError("CPG excursion lies outside a joint's position limits")
self._kp = finite(config.get("kp", 40), "kp", positive=True)
self._kd = finite(config.get("kd", 4), "kd")
if self._kd < 0:
raise ValueError("kd must be nonnegative")
self._effort = finite(config.get("effort_limit", 30), "effort_limit", positive=True)
self._kp = joint_values(config.get("kp", 40), joints.names, "kp", positive=True)
self._kd = joint_values(config.get("kd", 4), joints.names, "kd", nonnegative=True)
requested = joint_values(config.get("effort_limit", 30), joints.names, "effort_limit", positive=True)
ids = self.model.dof_jntid[joints.vel]
bounds = joint_effort_bounds(self.model, ids, requested)
self._effort = np.minimum(-bounds[:, 0], bounds[:, 1])
self.command_axes = ("amplitude_scale",)
self._spans = [(0, 1, 1)]
@@ -188,11 +209,21 @@ class Controller:
self._time = float(data.time)
self._motion_time = 0.0
if self.kind == "ik":
self._origin = data.mocap_pos[self.ik.mocap].copy()
target = data.mocap_pos[self.ik.mocap]
if self._start_at_site:
mujoco.mj_kinematics(self.model, data)
target[:] = data.site_xpos[self.ik.site]
self._origin = target.copy()
spans = np.array([self.command_spans[axis][:2] for axis in IK_AXES])
self._target_low = self._origin + spans[:, 0]
self._target_high = self._origin + spans[:, 1]
elif self.kind == "joint_sliders":
data.ctrl[self.ctrl_ids] = np.clip(
data.qpos[self.joints.pos], self.joints.lo, self.joints.hi
)
if self._target_rates is not None:
self._applied = data.ctrl[self.ctrl_ids].copy()
self._requested = self._applied.copy()
if self.operator is not None:
self.operator.reset()
@@ -230,7 +261,13 @@ class Controller:
if self.kind in {"direct", "joint_sliders"}:
# The passive viewer's Control panel writes data.ctrl. Keep its
# slider values when there is no new keyboard, pad, or API target.
previous = dict(zip(self.command_axes, data.ctrl[self.ctrl_ids], strict=True))
previous_targets = data.ctrl[self.ctrl_ids]
if self._target_rates is not None:
# Viewer edits replace the pending goal only on the axes it changed.
previous_targets = np.where(
previous_targets != self._applied, previous_targets, self._requested
)
previous = dict(zip(self.command_axes, previous_targets, strict=True))
if use_operator and self.operator.releasing:
command = {
name: self.command_spans[name][2] for name in self.operator.controls.bindings
@@ -249,7 +286,10 @@ class Controller:
use_operator and (np.any(values) or self.operator.releasing)
):
data.mocap_pos[self.ik.mocap] = self._origin + values
output = self.ik.solve(data, data.mocap_pos[self.ik.mocap])
target = data.mocap_pos[self.ik.mocap]
# Native viewer drags write directly to mocap_pos, in world metres.
np.clip(target, self._target_low, self._target_high, out=target)
output = self.ik.solve(data, target)
elif self.kind == "trajectory":
self._motion_time += dt * values[0]
t = self._motion_time
@@ -266,6 +306,15 @@ class Controller:
effort = self._kp * (target - data.qpos[joints.pos])
effort += self._kd * (rate - data.qvel[joints.vel])
output = np.clip(effort, -self._effort, self._effort)
elif self._target_rates is not None:
self._requested = values
limited = np.isfinite(self._target_rates)
delta = self._target_rates[limited] * dt
output = values.copy()
output[limited] = np.clip(
values[limited], self._applied[limited] - delta, self._applied[limited] + delta
)
self._applied = output.copy()
else:
output = values
data.ctrl[self.ctrl_ids] = output
+8 -7
View File
@@ -18,7 +18,7 @@ from mjrl.onboarding._xml import checked_mjcf
from mjrl.onboarding.build import write_mjcf
from .bindings import AxisBinding, controls_document, velocity_controls
from .model import finite, normalize_actuators, object_id, vector
from .model import finite, joint_values, normalize_actuators, object_id, vector
from .runtime import WHEEL_KINDS, Controller, read_config
from .wheels import wheel_mixer
@@ -30,12 +30,12 @@ class ControllerSetup:
controls: Path | None
def _gains(config: Mapping) -> tuple[float, float, float]:
kp = finite(config.get("kp", 40), "kp", positive=True)
kd = finite(config.get("kd", 4), "kd")
if kd < 0:
raise ValueError("kd must be nonnegative")
effort = finite(config.get("effort_limit", 30), "effort_limit", positive=True)
def _gains(config: Mapping) -> tuple:
names = config.get("joints")
kp, kd, effort = config.get("kp", 40), config.get("kd", 4), config.get("effort_limit", 30)
joint_values(kp, names, "kp", positive=True)
joint_values(kd, names, "kd", nonnegative=True)
joint_values(effort, names, "effort_limit", positive=True)
return kp, kd, effort
@@ -64,6 +64,7 @@ def _prepare_ik(spec: mujoco.MjSpec, model: mujoco.MjModel, config: dict) -> Non
body.add_site(name=site, pos=offset, size=[0.012, 0, 0], rgba=[0.1, 0.8, 1, 1])
mocap = config.setdefault("mocap_body", "mjrl_target")
if spec.body(mocap) is None:
config.setdefault("start_target_at_site", True)
model = _compile_with_named_links(spec)
data = mujoco.MjData(model)
mujoco.mj_kinematics(model, data)
+28
View File
@@ -0,0 +1,28 @@
schema_version: 2
command:
- term: twist
feeds: velocity_commands
frame: body
axes:
- {name: lin_vel_x, unit: m/s, positive: forward}
- {name: lin_vel_y, unit: m/s, positive: left}
- {name: ang_vel_z, unit: rad/s, positive: counter-clockwise}
scaling: {rule: full_deflection_is_range_edge}
devices:
gamepad:
scheme: absolute
layout: xbox
deadzone: device_reported_rescaled
release_button: B
axes:
lin_vel_x: {source: Ly, sign: -1}
lin_vel_y: {source: Lx, sign: -1}
ang_vel_z: {source: Rx, sign: -1}
keyboard:
scheme: keys
full_after_s: 2.0
release: [key_escape]
axes:
lin_vel_x: {"+": [key_w, key_up], "-": [key_s, key_down]}
lin_vel_y: {"+": [key_j], "-": [key_l]}
ang_vel_z: {"+": [key_a, key_left], "-": [key_d, key_right]}
+5 -2
View File
@@ -12,6 +12,8 @@ import numpy as np
from mjlab.utils.spec import non_default_option_fields
from mjlab.utils.xml import fix_spec_xml, strip_buffer_textures
from .platform._serialization import spec_xml
def _asset_bytes(spec: mujoco.MjSpec, filename: str, tag: str) -> bytes:
directory = Path(spec.texturedir if tag == "texture" else spec.meshdir)
@@ -60,7 +62,7 @@ def write_native_model(env, output: Path, layout: dict) -> None:
setattr(spec.option, field, getattr(live.opt, field))
strip_buffer_textures(spec)
spec.compile()
xml = ET.fromstring(fix_spec_xml(spec.to_xml()))
xml = ET.fromstring(fix_spec_xml(spec_xml(spec)))
sources = {name: entity.spec for name, entity in env.scene.entities.items()}
_localize_assets(xml, spec, sources, output)
ET.indent(xml, space=" ")
@@ -87,7 +89,8 @@ def write_native_model(env, output: Path, layout: dict) -> None:
"geom_quat",
"actuator_forcerange",
):
# MjSpec's MJCF writer uses six significant digits.
# Preserve the existing contract checks even if high precision native
# serialization is unavailable. Lossy or reordered models must fail.
if not np.allclose(getattr(model, name), getattr(live, name), rtol=5e-6, atol=1e-9):
raise ValueError(f"Native model export changed {name}")
if not np.isclose(model.opt.timestep, layout["control"]["sim_dt"], rtol=0, atol=1e-12):
+32
View File
@@ -0,0 +1,32 @@
"""Discover project inputs without scanning installed dependencies and caches."""
from __future__ import annotations
import os
from pathlib import Path
_IGNORED_DIRECTORIES = {
".git", ".hg", ".svn", ".venv", "venv", ".tox", ".nox",
"__pycache__", ".cache", ".mypy_cache", ".pytest_cache", ".ruff_cache",
"node_modules", "site-packages", "dist-packages",
}
def project_files(source: Path) -> list[Path]:
"""Prune incidental directories, retaining training logs and exported assets.
The explicitly selected root is always searched. A virtual environment with
a custom name is recognized by its marker rather than by guessing names
such as ``env`` that may hold real robot configuration.
"""
files = []
for directory, children, names in os.walk(source, followlinks=False):
parent = Path(directory)
children[:] = [
name for name in children
if name not in _IGNORED_DIRECTORIES
and not (parent / name / "pyvenv.cfg").is_file()
]
files.extend(parent / name for name in names if (parent / name).is_file())
return sorted(files)
+16 -3
View File
@@ -152,16 +152,25 @@ def joint_margins(
return result
def collision_geom_ids(model: mujoco.MjModel) -> set[int]:
"""Include explicitly paired geoms even when their automatic masks are zero."""
enabled = set(np.flatnonzero(model.geom_contype | model.geom_conaffinity).tolist())
enabled.update(int(gid) for gid in model.pair_geom1)
enabled.update(int(gid) for gid in model.pair_geom2)
return enabled
def foot_geoms(model: mujoco.MjModel, raw: Any, bid: int) -> dict[str, int]:
if not isinstance(raw, list) or not raw or any(not isinstance(name, str) for name in raw):
raise ValueError("foot_geoms must be a nonempty list of named collision geoms")
if len(raw) != len(set(raw)):
raise ValueError("foot_geoms contains duplicate names")
result = {name: object_id(model, OBJ.mjOBJ_GEOM, name) for name in raw}
colliding = collision_geom_ids(model)
for name, gid in result.items():
if model.body_rootid[model.geom_bodyid[gid]] != bid:
raise ValueError(f"foot geom {name!r} is outside the robot root")
if not (model.geom_contype[gid] or model.geom_conaffinity[gid]):
if gid not in colliding:
raise ValueError(f"foot geom {name!r} is collision-disabled")
return result
@@ -181,6 +190,7 @@ def contact_groups(
if len(raw) != len(set(raw)):
raise ValueError("foot_bodies contains duplicate names")
result = {}
colliding = collision_geom_ids(model)
for name in raw:
body = object_id(model, OBJ.mjOBJ_BODY, name)
if model.body_rootid[body] != bid:
@@ -188,7 +198,7 @@ def contact_groups(
geoms = tuple(
gid
for gid in np.flatnonzero(model.geom_bodyid == body)
if model.geom_contype[gid] or model.geom_conaffinity[gid]
if gid in colliding
)
if not geoms:
raise ValueError(f"foot body {name!r} has no direct collision geometry")
@@ -234,7 +244,10 @@ def attach_calibration_ground(spec: mujoco.MjSpec, ground_geom: str | None) -> s
name = "onboarding_ground"
if spec.geom(name) is not None:
raise ValueError(f"{name!r} is already used")
spec.worldbody.add_geom(name=name, type=GEOM.mjGEOM_PLANE, size=[0.0, 0.0, 0.05])
spec.worldbody.add_geom(
name=name, type=GEOM.mjGEOM_PLANE, size=[0.0, 0.0, 0.05],
contype=1, conaffinity=1,
)
return name
+25 -6
View File
@@ -9,6 +9,7 @@ from pathlib import Path
from tempfile import NamedTemporaryFile
from typing import Any
from ._discovery import project_files
from ._report import atomic_write
from ._xml import _MODEL_EXTENSIONS, is_model_candidate, load_intake_mjcf, mesh_path, read_xml
@@ -173,9 +174,7 @@ def _select_source(source: Path, output: Path) -> Path:
if not source.is_dir():
return source
output = output.resolve()
files = sorted(
path for path in source.rglob("*") if path.is_file() and path.resolve() != output
)
files = [path for path in project_files(source) if path.resolve() != output]
candidates = [path for path in files if is_model_candidate(path)]
kind = "model"
if not candidates:
@@ -308,16 +307,19 @@ def write_mjcf(spec: Any, source: Path | str, output: Path | str, *, replace: bo
if source == output.resolve():
raise ValueError("output must differ from the source")
serializable = spec.copy()
from mjrl.platform._serialization import named_spec_tree, temporary_object_names
temporary_names = temporary_object_names(serializable)
# Compile a copy with fusion off for serialization. Otherwise the native
# writer can omit a fused child's original transform from the new XML.
fused = serializable.compiler.fusestatic
if fused:
original = spec.copy().compile()
original = serializable.copy().compile()
serializable.compiler.fusestatic = False
serializable.compile()
else:
original = serializable.compile()
xml = ET.fromstring(serializable.to_xml())
xml = named_spec_tree(serializable)
model_directory = Path(spec.modelfiledir or source.parent)
compiler = xml.find("compiler")
if compiler is None:
@@ -351,8 +353,25 @@ def write_mjcf(spec: Any, source: Path | str, output: Path | str, *, replace: bo
for field in ("nq", "nv", "nu", "nbody", "njnt", "ngeom"):
if getattr(original, field) != getattr(model, field):
raise ValueError(f"generated MJCF round-trip changed {field}")
geom_order = [model.geom(original.geom(gid).name).id for gid in range(original.ngeom)]
for field in ("body_mass", "body_inertia", "qpos0", "jnt_range", "geom_pos", "geom_quat"):
if not np.allclose(getattr(original, field), getattr(model, field), atol=1e-9, rtol=1e-5):
actual = getattr(model, field)
if field.startswith("geom_"):
actual = actual[geom_order]
if not np.allclose(getattr(original, field), actual, atol=1e-9, rtol=1e-5):
raise ValueError(f"generated MJCF round-trip changed {field}")
if temporary_names:
for element in xml.iter():
if element.tag in {"body", "geom"} and element.get("name") in temporary_names:
del element.attrib["name"]
result = ET.tostring(xml, encoding="unicode") + "\n"
# Removing unused temporary labels cannot change geometry or dynamics.
with NamedTemporaryFile(suffix=".xml", dir=output.parent, delete=False) as stream:
staging = Path(stream.name)
stream.write(result.encode("utf-8"))
try:
model = mujoco.MjModel.from_xml_path(str(staging))
finally:
staging.unlink(missing_ok=True)
atomic_write(output, result, replace=replace)
return model
+49 -19
View File
@@ -10,6 +10,7 @@ import yaml
from mjrl.platform.graph import SUPPORTED_POLICY_SUFFIXES
from ._discovery import project_files
from ._report import check, read_object
from ._xml import (
_MESH_EXTENSIONS,
@@ -19,7 +20,7 @@ from ._xml import (
read_xml,
)
from .build import urdf_spec
from .morphology import infer_morphology
from .morphology import infer_morphology, robot_root_ids
_POLICY_EXTENSIONS = SUPPORTED_POLICY_SUFFIXES | {".pth", ".ckpt", ".safetensors", ".tflite"}
_LEGGED_FAMILIES = {"biped", "quadruped", "wheeled_biped", "multipod"}
@@ -44,11 +45,7 @@ def _training_config_name(path: Path) -> bool:
def _inventory(source: Path) -> tuple[list[Path], list[Path], list[Path], list[Path], list[Path]]:
files = (
sorted(path for path in source.rglob("*") if path.is_file())
if source.is_dir()
else [source]
)
files = project_files(source) if source.is_dir() else [source]
models, weights, meshes, metadata, training_configs = [], [], [], [], []
for path in files:
extension = path.suffix.lower()
@@ -142,13 +139,16 @@ def _model_inventory(model: Any) -> dict[str, Any]:
}
for aid in range(model.nu)
]
from ._physics import collision_geom_ids
colliding = collision_geom_ids(model)
geoms = [
{
"name": model.geom(gid).name or None,
"id": gid,
"body_id": int(model.geom_bodyid[gid]),
"type": mujoco.mjtGeom(int(model.geom_type[gid])).name.removeprefix("mjGEOM_").lower(),
"collision_enabled": bool(model.geom_contype[gid] or model.geom_conaffinity[gid]),
"collision_enabled": gid in colliding,
}
for gid in range(model.ngeom)
]
@@ -259,7 +259,7 @@ def _completeness(
nonscalar = [
joint["name"] for joint in joints if joint["type"] not in {"free", "hinge", "slide"}
]
roots = [bid for bid in model["root_body_ids"] if not bodies[bid]["mocap"]]
roots = robot_root_ids(model)
return [
check("dynamic_dofs", model["dimensions"]["nv"] > 0, count=model["dimensions"]["nv"]),
check(
@@ -320,9 +320,10 @@ def _legged_evidence(model: dict[str, Any], profile: Mapping[str, Any]) -> dict[
and all(isinstance(name, str) and name in contacts for name in feet)
and len({contacts[name] for name in feet}) == len(feet) >= minimum
)
robot_only = model["root_body_ids"] == [root_id] and not model["world_geom_ids"]
roots = robot_root_ids(model)
robot_only = roots == [root_id] and not model["world_geom_ids"]
intent = profile.get("control_intent")
requested = intent in ("learned", "wasd", "retrain")
requested = intent in ("learned", "wasd", "retrain") or (family == "biped" and intent is None)
articulated = [joint for joint in model["joints"] if joint["type"] != "free"]
supported = bool(articulated) and all(
joint["type"] in {"hinge", "slide"} and joint["name"] for joint in articulated
@@ -349,6 +350,7 @@ def _legged_evidence(model: dict[str, Any], profile: Mapping[str, Any]) -> dict[
"explicit_core_legged_profile",
free_base and valid_feet and robot_only and supported and wheel_mapping and requested,
family=family,
base_body_is_root=root_id in roots,
floating_base=free_base,
valid_foot_contacts=valid_feet,
robot_only=robot_only,
@@ -391,6 +393,7 @@ def inspect_asset(
complete = False
legged = False
morphology = None
legged_check = {}
if len(models) == 1:
path = models[0]
try:
@@ -437,6 +440,7 @@ def inspect_asset(
metadata_extraction = extract_policy_metadata(sources, model=model)
metadata_doc = metadata_extraction["metadata"]
metadata_valid = False
walking_commands = False
metadata_issue = None
if metadata_extraction is not None and not metadata_extraction["ready"]:
metadata_issue = "upstream metadata needs review; see metadata_extraction"
@@ -447,11 +451,17 @@ def inspect_asset(
from mjrl.adapter import build_layout
try:
build_layout(metadata_doc, model=model)
layout = build_layout(metadata_doc, model=model)
except (TypeError, ValueError) as exc:
metadata_issue = str(exc)
else:
metadata_valid = True
twist = layout.get("command_ranges", {}).get("twist", {})
walking_commands = all(
lo < 0 < hi for lo, hi in (
twist.get("lin_vel_x", (0, 0)), twist.get("ang_vel_z", (0, 0))
)
)
checks.append(
check(
"policy_metadata_evidence",
@@ -487,7 +497,15 @@ def inspect_asset(
and intent in (None, "learned", "wasd", "retrain")
and (morphology["floating_base"] or evidence["format"] == "urdf")
)
if (3 in eligible or tier3_pending) and intent == "retrain":
# A humanoid's default objective survives a partial profile or a scene
# wrapper. Readiness still depends on the reviewed root, feet and model.
family = profile.get("family", morphology["family"] if morphology else None)
walking = family == "biped" and intent in (None, "learned", "wasd", "retrain")
if complete and intent == "deterministic":
tier = 2
elif complete and walking:
tier = 1 if 1 in eligible and walking_commands and intent != "retrain" else 3
elif (3 in eligible or tier3_pending) and intent == "retrain":
tier = 3
elif 1 in eligible or tier1_pending:
tier = 1
@@ -499,19 +517,28 @@ def inspect_asset(
tier = 0
route = {0: "build-mjcf", 1: "adapt-tier1", 2: "setup-tier2", 3: "scaffold-tier3"}[tier]
status = "ready"
if tier == 1 and (len(weights) != 1 or len(metadata) > 1):
if len(models) > 1:
status = "needs_selection"
elif tier == 1 and (len(weights) != 1 or len(metadata) > 1):
status = "needs_selection"
elif tier == 1 and not metadata_valid:
status = "needs_metadata"
elif tier == 3 and tier3_pending:
status = "needs_profile"
elif tier == 3 and not legged:
profile_ready = all(legged_check.get(key) for key in (
"base_body_is_root", "valid_foot_contacts", "supported_articulation",
"wheel_mapping", "learned_control_requested",
))
status = "needs_model" if profile_ready else "needs_profile"
prerequisites = []
if len(models) > 1:
prerequisites.append("select_model")
if tier == 3:
if tier3_pending:
prerequisites.append("confirm_morphology_and_control_intent")
if status == "needs_profile":
prerequisites.append("confirm_morphology_and_supports" if walking
else "confirm_morphology_and_control_intent")
if not morphology["floating_base"]:
prerequisites.append("build_floating_base_mjcf")
if evidence["world_geom_ids"]:
if evidence["world_geom_ids"] or len(robot_root_ids(evidence)) != 1:
prerequisites.append("extract_robot_only_model")
if not next(item["passed"] for item in checks if item["name"] == "actuation_coverage"):
prerequisites.append("supply_actuation_and_effort_limits")
@@ -531,11 +558,14 @@ def inspect_asset(
"morphology_candidates": morphology,
"checks": checks,
"recommendation": {
**({"objective": "walking"} if walking else {}),
"tier": tier,
"route": route,
"status": status,
"next_step": (
"review-profile" if tier == 3 and tier3_pending
"select-model" if len(models) > 1
else "review-profile" if status == "needs_profile"
else "prepare-training-model" if status == "needs_model"
else "extract-tier1" if tier == 1 and not metadata_valid else route
),
"prerequisites": prerequisites,
+88
View File
@@ -0,0 +1,88 @@
"""Compiled MJCF facts kept separate from unknown actor semantics."""
from __future__ import annotations
import mujoco
from ._physics import compiled_model_sha256
def model_evidence(model: mujoco.MjModel) -> dict:
"""Record named physical facts without inventing a policy contract.
Keyframes are authored poses, not evidence of a policy's default pose.
Physics timestep is not policy frequency; joint damping is not policy kd.
Raw actuator parameters retain transmission and force conventions.
"""
joints = []
for jid in range(model.njnt):
kind = mujoco.mjtJoint(int(model.jnt_type[jid]))
nq = {mujoco.mjtJoint.mjJNT_FREE: 7, mujoco.mjtJoint.mjJNT_BALL: 4}.get(kind, 1)
nv = {mujoco.mjtJoint.mjJNT_FREE: 6, mujoco.mjtJoint.mjJNT_BALL: 3}.get(kind, 1)
qadr, dadr = int(model.jnt_qposadr[jid]), int(model.jnt_dofadr[jid])
joints.append({
"name": model.joint(jid).name or None,
"type": kind.name.removeprefix("mjJNT_").lower(),
"body": model.body(int(model.jnt_bodyid[jid])).name,
"qpos_address": qadr, "dof_address": dadr,
"reference_qpos": model.qpos0[qadr:qadr + nq].tolist(),
"range": model.jnt_range[jid].tolist() if model.jnt_limited[jid] else None,
"damping": model.dof_damping[dadr:dadr + nv].tolist(),
"armature": model.dof_armature[dadr:dadr + nv].tolist(),
"actuator_force_range": (
model.jnt_actfrcrange[jid].tolist() if model.jnt_actfrclimited[jid] else None
),
})
actuators = []
for aid in range(model.nu):
transmission = mujoco.mjtTrn(int(model.actuator_trntype[aid]))
joint = None
if transmission in {mujoco.mjtTrn.mjTRN_JOINT, mujoco.mjtTrn.mjTRN_JOINTINPARENT}:
joint = model.joint(int(model.actuator_trnid[aid, 0])).name
actuators.append({
"name": model.actuator(aid).name or None,
"joint": joint,
"transmission": transmission.name.removeprefix("mjTRN_").lower(),
"target_ids": model.actuator_trnid[aid].tolist(),
"gear": model.actuator_gear[aid].tolist(),
"gain_type": mujoco.mjtGain(int(model.actuator_gaintype[aid])).name,
"bias_type": mujoco.mjtBias(int(model.actuator_biastype[aid])).name,
"dynamics_type": mujoco.mjtDyn(int(model.actuator_dyntype[aid])).name,
"gain_parameters": model.actuator_gainprm[aid].tolist(),
"bias_parameters": model.actuator_biasprm[aid].tolist(),
"dynamics_parameters": model.actuator_dynprm[aid].tolist(),
"control_range": (
model.actuator_ctrlrange[aid].tolist() if model.actuator_ctrllimited[aid] else None
),
"force_range": (
model.actuator_forcerange[aid].tolist() if model.actuator_forcelimited[aid] else None
),
})
return {
"schema": "mjrl.onboarding.model-evidence/1",
"compiled_model_sha256": compiled_model_sha256(model),
"dimensions": {"nq": model.nq, "nv": model.nv, "nu": model.nu},
"physics_timestep_s": float(model.opt.timestep),
"gravity_world_m_s2": model.opt.gravity.tolist(),
"joints": joints,
"actuators": actuators,
"keyframes": [{
"name": model.key(kid).name or None,
"qpos": model.key_qpos[kid].tolist(),
"qvel": model.key_qvel[kid].tolist(),
"ctrl": model.key_ctrl[kid].tolist(),
} for kid in range(model.nkey)],
"explicit_contact_pairs": [{
"geoms": [model.geom(int(gid)).name for gid in
(model.pair_geom1[pid], model.pair_geom2[pid])],
"condim": int(model.pair_dim[pid]),
"friction": model.pair_friction[pid].tolist(),
} for pid in range(model.npair)],
"limitations": [
"Compiled order does not establish actor observation or action order.",
"Keyframes and reference positions do not establish policy default_joint_pos.",
"Physics timestep does not establish policy control_hz or decimation.",
"Joint damping and actuator gains do not establish policy control gains.",
"No actor weights, observation history, normalization or action scale are recovered.",
],
}
+61 -2
View File
@@ -14,9 +14,63 @@ def _named(value: str | None, words: str) -> bool:
return bool(re.search(rf"(^|[^a-z])({words})([^a-z]|$)", text))
def _support_branches(
paths: dict[int, list[int]], by_body: dict[int, list],
) -> dict[int, int]:
"""Separate limbs below shared bodies without splitting a foot's contacts.
Start with root branches, then examine each support group's lowest common
ancestor. A deeper split requires at least two scalar joints on every
resulting distal chain: fixed contact bodies and single-joint toes do not
establish independent legs. Ambiguous short chains remain one candidate.
"""
result = {}
def partition(group: dict[int, list[int]], branch: int) -> None:
common = 0
for nodes in zip(*group.values()):
if len(set(nodes)) != 1:
break
common += 1
distal = {bid: path[common:] for bid, path in group.items()}
if len(group) == 1 or any(
sum(len(by_body.get(node, [])) for node in path) < 2
for path in distal.values()
):
result.update({bid: branch for bid in group})
return
children: dict[int, dict[int, list[int]]] = {}
for bid, path in distal.items():
children.setdefault(path[0], {})[bid] = group[bid]
for child, members in children.items():
partition(members, child)
roots: dict[int, dict[int, list[int]]] = {}
for bid, path in paths.items():
roots.setdefault(path[0], {})[bid] = path
for root, group in roots.items():
partition(group, root)
return result
def robot_root_ids(model: dict[str, Any]) -> list[int]:
"""Ignore empty static frame trees without hiding physical scene bodies."""
bodies = {body["id"]: body for body in model["bodies"]}
occupied = {joint["body_id"] for joint in model["joints"]}
occupied.update(geom["body_id"] for geom in model["geoms"])
occupied.update(body["id"] for body in bodies.values() if body["mass_kg"] > 0)
meaningful = set()
for bid in occupied:
while bid in bodies:
meaningful.add(bid)
bid = bodies[bid]["parent_id"]
return [bid for bid in model["root_body_ids"]
if bid in meaningful and not bodies[bid]["mocap"]]
def infer_morphology(model: dict[str, Any]) -> dict[str, Any]:
bodies = {body["id"]: body for body in model["bodies"]}
roots = [bid for bid in model["root_body_ids"] if not bodies[bid]["mocap"]]
roots = robot_root_ids(model)
base = roots[0] if len(roots) == 1 else None
joints = model["joints"]
scalar = [joint for joint in joints if joint["type"] in {"hinge", "slide"}]
@@ -32,6 +86,7 @@ def infer_morphology(model: dict[str, Any]) -> dict[str, Any]:
wheel_bodies = {joint["body_id"] for joint in wheels}
children = {body["parent_id"] for body in bodies.values()}
supports = []
support_paths = {}
terminal_chains = []
for bid, body in bodies.items():
if bid == base or bid in children:
@@ -61,6 +116,7 @@ def infer_morphology(model: dict[str, Any]) -> dict[str, Any]:
"velocity_dofs": sum(joint["velocity_dofs"] for joint in chain_joints),
})
if geoms and (foot or (leg and len(chain_joints) >= 2)):
support_paths[bid] = list(reversed(chain))
# Prefer explicitly named contact surfaces over wheel hubs/shells.
preferred = [geom for geom in geoms
if _named(geom["name"], "foot|feet|toe|sole|tire|wheel")]
@@ -69,7 +125,10 @@ def infer_morphology(model: dict[str, Any]) -> dict[str, Any]:
"geoms": [geom["name"] for geom in preferred or geoms if geom["name"]],
"wheel": wheel, "evidence": "named_support" if foot else "leg_chain",
})
# Multiple toes on one branch must not count as multiple legs.
# Limbs may share an articulated waist; distal contacts may share a foot.
support_branches = _support_branches(support_paths, by_body)
for support in supports:
support["branch_id"] = support_branches[support["body_id"]]
branches = {support["branch_id"] for support in supports}
count = len(branches)
wheel_count = sum(support["wheel"] for support in supports)
+12 -1
View File
@@ -70,6 +70,13 @@ def calibrated_spec_config(
action_scales = number_map(config.get("action_scales"), "action_scales")
if set(action_scales) != set(position_names):
raise ValueError("action_scales must cover exactly the calibrated position joints")
posture_stds = dict.fromkeys(position_names, 0.35)
if "posture_stds" in config:
posture_stds = number_map(config["posture_stds"], "posture_stds")
if set(posture_stds) != set(position_names):
raise ValueError("posture_stds must cover exactly the calibrated position joints")
if any(value <= 0 for value in posture_stds.values()):
raise ValueError("posture_stds must contain positive values")
values = []
for name in position_names:
measurement = measurements[name]
@@ -81,10 +88,11 @@ def calibrated_spec_config(
"name": name,
**{key: measurement[key] for key in fields},
"action_scale": action_scales[name],
"posture_std": posture_stds[name],
}
)
return {
**{key: value for key, value in config.items() if key != "action_scales"},
**{key: value for key, value in config.items() if key not in {"action_scales", "posture_stds"}},
"model_path": str(model_path),
"base_body": report.get("root_body"),
"base_height": float(position[2]),
@@ -106,6 +114,7 @@ def scaffold_task(
report supplies measured stance fields and must match the exact model.
The task directory defaults to the active `tasks` package.
"""
from mjrl.controllers.bindings import WALKING_CONTROLS
from tasks.robot_spec import RobotSpec, scaffold_robot_spec
from tasks.templates._locomotion import validate_robot_model
@@ -115,6 +124,8 @@ def scaffold_task(
if calibration is not None
else dict(config)
)
if data.get("family") == "biped":
data.setdefault("controls_path", str(WALKING_CONTROLS))
spec = RobotSpec.from_dict(data, base_dir=base)
checked_mjcf(spec.model_path)
validate_robot_model(spec)
+10 -4
View File
@@ -51,12 +51,12 @@ _TOP_FIELDS = {
"wire_joint_order", "obs_joint_order", "action_joint_order", "default_joint_pos",
"source_action_joint_order", "default_joint_vel", "passive_joints", "joint_limits",
"action_scale", "action", "command_ranges", "raw_action_clip", "use_default_offset",
"controller", "root_body",
"controller", "root_body", "motor_model",
}
_CONTROL_FIELDS = {"kp", "kd", "effort_limit", "control_hz"}
_OBSERVATION_FIELDS = {
"terms", "dim", "history_length", "source_term_order", "source_order",
"source_history_order", "normalization", "inputs", "command_order",
"source_history_order", "normalization", "inputs", "command_order", "frames",
}
_GAIN_FIELDS = {"control.kp", "control.kd", "control.effort_limit"}
_CONTROL_SECTIONS = {"control", "controller", "actuation", "actuator", "actuators", "gains"}
@@ -388,8 +388,8 @@ def extract_policy_metadata(
sources: Sequence[Path | str], *, overrides: Mapping | None = None, model=None
) -> dict:
"""Extract a canonical draft, with unresolved fields visible and provenance."""
if isinstance(sources, (str, Path)) or not sources:
raise ValueError("sources must be a nonempty sequence of config paths")
if isinstance(sources, (str, Path)) or (not sources and model is None):
raise ValueError("provide config paths or a model for an evidence-only draft")
if overrides is not None and not isinstance(overrides, Mapping):
raise ValueError("overrides must be a canonical metadata object")
@@ -655,8 +655,14 @@ def extract_policy_metadata(
except (AttributeError, KeyError, OverflowError, TypeError, ValueError) as error:
problem("metadata", {"source": "adapter", "path": ""}, str(error))
ready = False
evidence = None
if model is not None:
from .model_evidence import model_evidence
evidence = model_evidence(model)
return {
"schema": REPORT_SCHEMA,
"model_evidence": evidence,
"metadata": metadata,
"ready": ready,
"missing_fields": missing,
+10 -2
View File
@@ -24,6 +24,7 @@ from ._physics import (
OBJ,
base_frames,
compiled_model_sha256 as compiled_model_sha256,
collision_geom_ids,
contact_groups,
contact_loads,
finite,
@@ -504,8 +505,16 @@ def _run_probe(
disabled = model.opt.disableflags
try:
model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_ACTUATION
# Dynamic motor friction belongs to this passive rollout, not to the
# last active sample. Reset only controller state, preserving baseline.
reset_passive = getattr(controller, "reset_passive", None)
apply_passive = getattr(controller, "apply_passive", None)
if reset_passive is not None:
reset_passive(baseline)
mujoco.mj_forward(model, baseline)
for index in range(steps):
if apply_passive is not None:
apply_passive(baseline)
mujoco.mj_step(model, baseline)
mujoco.mj_forward(model, baseline)
if (
@@ -637,8 +646,7 @@ def verify(
mass = float(mj.body_subtreemass[root])
has_collision = any(
mj.body_rootid[mj.geom_bodyid[gid]] == root
and (mj.geom_contype[gid] or mj.geom_conaffinity[gid])
for gid in range(mj.ngeom)
for gid in collision_geom_ids(mj)
)
physics.append(
check(
+70
View File
@@ -0,0 +1,70 @@
"""Preserve floating point precision when the native XML writer supports it."""
from __future__ import annotations
import ctypes
import xml.etree.ElementTree as ET
from threading import RLock
_XML_LOCK = RLock()
def _precision_api():
import mujoco
# MuJoCo exposes these private hooks through its shared library, but not
# through Python. Keep the optional dependency isolated: older builds use
# their ordinary writer and callers' unchanged round-trip checks still apply.
try:
library = ctypes.CDLL(mujoco._specs.__file__)
get = library._mjPRIVATE__get_xml_precision
set_ = library._mjPRIVATE__set_xml_precision
except (OSError, AttributeError):
return None
get.argtypes, get.restype = [], ctypes.c_int
set_.argtypes, set_.restype = [ctypes.c_int], None
return get, set_
def spec_xml(spec) -> str:
"""Use double precision XML and restore native writer state even on error."""
api = _precision_api()
if api is None:
return spec.to_xml()
get, set_ = api
with _XML_LOCK:
previous = get()
try:
set_(17)
return spec.to_xml()
finally:
set_(previous)
def temporary_object_names(spec) -> set[str]:
"""Give anonymous bodies/geoms stable identities for round-trip checks."""
temporary_names = set()
used_names = {item.name for item in [*spec.bodies, *spec.geoms]}
for index, item in enumerate([*spec.bodies, *spec.geoms]):
if item is spec.worldbody or item.name:
continue
name = f"__mjrl_roundtrip_{index}"
while name in used_names:
name += "_"
item.name = name
temporary_names.add(name)
used_names.add(name)
return temporary_names
def named_spec_tree(spec) -> ET.Element:
"""Serialize a spec whose geoms have stable names for round-trip checks."""
root = ET.fromstring(spec_xml(spec))
# MuJoCo can elide both mass and density for a zero-mass geom when its
# class supplies both as zero. On reload it then acquires the built-in
# density. Use the effective spec mass, including class inheritance.
massless = {geom.name for geom in spec.geoms if geom.mass == 0}
if massless:
for element in root.iterfind("./worldbody//geom"):
if element.get("name") in massless:
element.set("mass", "0")
return root
+24 -4
View File
@@ -17,6 +17,13 @@ MODES = {"rl_onnx", "ik_mocap", "wheeled_velocity", "cpg_keyframe", "model_viewe
KIND_MODE = {"ik": "ik_mocap", "joint_sliders": "ik_mocap", "trajectory": "cpg_keyframe",
"cpg": "cpg_keyframe", "differential": "wheeled_velocity", "omni": "wheeled_velocity",
"direct": "model_viewer", "rl_onnx": "rl_onnx"}
IK_MOUSE_HELP = (
"Double-click the end-effector target marker to select it. Hold Ctrl and drag "
"with the right mouse button to move it. Hold Shift as well to change the "
"translation plane. Release the mouse to hold the target."
)
def _trusted_schema_bytes() -> bytes:
# The application also ships a published schema for readers. Validation
# always uses the copy shipped with this installed or portable runtime.
@@ -105,9 +112,11 @@ def _manual(root: Path, robot_id: str, modes: dict, default: str) -> dict:
"leave": "Close the viewer or stop replay.",
"keyboard": "This mode has no keyboard bindings.",
"controls": [], "keys": []}
contract = json.loads((root / mode["contract"]).read_text())
if contract.get("kind") == "ik":
item["summary"] = IK_MOUSE_HELP
if mode.get("controls"):
controls = load_controls(root / mode["controls"])
contract = json.loads((root / mode["contract"]).read_text())
if mode["control_mode"] == "rl_onnx":
layout = json.loads((root / mode["layout"]).read_text())
ranges = layout.get("command_ranges", {}).get("twist", {})
@@ -338,8 +347,19 @@ def _build_bundle(model: Path, output: Path, *, robot_id: str, modes: dict[str,
write_json(root / "manual.en.json", _manual(root, robot_id, mode_records, default_mode))
(root / "runtime").mkdir()
_runtime(root / "runtime/controller.pyz")
(root / "runtime/requirements.txt").write_text(
"mujoco~=3.11.0\nnumpy\nPyYAML\njsonschema\nonnx\nonnxruntime>=1.17\nimageio-ffmpeg\n")
requirements = "mujoco~=3.11.0\nnumpy\nPyYAML\njsonschema\nonnx\nonnxruntime>=1.17\nimageio-ffmpeg\n"
python_requirement = ">=3.10,<3.14"
for record in mode_records.values():
if record.get("layout"):
layout = json.loads((root / record["layout"]).read_text())
if "motor_model" in layout:
from .motors import BAM_PYTHON_REQUIREMENT, BAM_REQUIREMENT, validate_motor_model
validate_motor_model(layout["motor_model"])
requirements += BAM_REQUIREMENT + "\n"
python_requirement = BAM_PYTHON_REQUIREMENT
break
(root / "runtime/requirements.txt").write_text(requirements)
(root / "app.schema").write_bytes(_trusted_schema_bytes())
(root / "LICENSE").write_bytes(files(__package__).joinpath("LICENSE").read_bytes())
license_files = ["LICENSE"]
@@ -361,7 +381,7 @@ def _build_bundle(model: Path, output: Path, *, robot_id: str, modes: dict[str,
"controller": "controller.toml", "manuals": {"en": "manual.en.json"},
"reference": "reference.json", "verification": "verification.json" if reports else None,
"runtimes": {"native": {"file": "runtime/controller.pyz", "language": "python",
"python": ">=3.10,<3.14", "dependencies": "runtime/requirements.txt",
"python": python_requirement, "dependencies": "runtime/requirements.txt",
"platforms": ["linux", "windows", "macos"]}},
"capabilities": sorted({x["control_mode"] for x in mode_records.values()}),
"source": {"model_sha256": digest(model)}, "files": {}}
+44 -11
View File
@@ -16,16 +16,36 @@ def copy_model(source: Path, output: Path) -> dict[str, str]:
from mjrl.onboarding._xml import checked_mjcf
source, output = Path(source).resolve(), Path(output)
checked_mjcf(source)
before = mujoco.MjModel.from_xml_path(str(source))
authored = checked_mjcf(source)
from ._serialization import named_spec_tree, temporary_object_names
spec = mujoco.MjSpec.from_file(str(source))
# Compiling a fused spec mutates fixed-child geometry before serialization.
# Serialize the unfused tree and let the relocated model apply the original
# compiler setting, preserving both transforms and authored semantics.
fuse_static = spec.compiler.fusestatic
spec.compiler.fusestatic = False
spec.compile()
root = ET.fromstring(spec.to_xml())
authored_compiler = authored.find("compiler")
# An already flattened export needs only dependency relocation. Feeding it
# through MjSpec's writer recomposes mesh frames and renormalizes rotations,
# changing a few ulps that can split long contact-rich reference rollouts.
# Preserve its exact numeric attribute text, including inherited defaults.
direct = not any(element.tag in {"include", "model", "attach"}
for element in authored.iter()) and (
authored_compiler is None or not any(
authored_compiler.get(key) for key in ("assetdir", "meshdir", "texturedir", "strippath")
)
)
temporary_names = set()
if direct:
before = mujoco.MjModel.from_xml_path(str(source))
root = authored
fuse_static = spec.compiler.fusestatic
else:
temporary_names = temporary_object_names(spec)
before = spec.copy().compile()
# Compiling a fused spec mutates fixed-child geometry before serialization.
# Serialize the unfused tree and let the relocated model apply the original
# compiler setting, preserving both transforms and authored semantics.
fuse_static = spec.compiler.fusestatic
spec.compiler.fusestatic = False
spec.compile()
root = named_spec_tree(spec)
if root.find("extension") is not None:
raise ValueError("plugin models require an explicit packaged plugin runtime")
compiler = root.find("compiler")
@@ -57,7 +77,8 @@ def copy_model(source: Path, output: Path) -> dict[str, str]:
dependencies[str(path)] = relative
for key in ("assetdir", "meshdir", "texturedir"):
compiler.attrib.pop(key, None)
compiler.set("fusestatic", "true" if fuse_static else "false")
if not direct:
compiler.set("fusestatic", "true" if fuse_static else "false")
ET.indent(root)
ET.ElementTree(root).write(output, encoding="utf-8", xml_declaration=True)
after = mujoco.MjModel.from_xml_path(str(output))
@@ -65,6 +86,8 @@ def copy_model(source: Path, output: Path) -> dict[str, str]:
for field in ("nq", "nv", "nu", "nbody", "ngeom", "njnt"):
if getattr(before, field) != getattr(after, field):
raise ValueError(f"relocating model changed {field}")
geom_order = (list(range(before.ngeom)) if direct else
[after.geom(before.geom(gid).name).id for gid in range(before.ngeom)])
for field in (
"body_mass", "body_inertia", "body_pos", "body_quat", "body_ipos", "body_iquat",
"jnt_range", "jnt_pos", "jnt_axis", "jnt_stiffness", "qpos0",
@@ -74,8 +97,18 @@ def copy_model(source: Path, output: Path) -> dict[str, str]:
"actuator_gainprm", "actuator_biasprm", "actuator_dynprm",
"actuator_ctrlrange", "actuator_forcerange",
):
if not np.allclose(getattr(before, field), getattr(after, field), rtol=1e-7, atol=1e-10):
actual = getattr(after, field)
if field.startswith("geom_"):
actual = actual[geom_order]
if not np.allclose(getattr(before, field), actual, rtol=1e-7, atol=1e-10):
raise ValueError(f"relocating model changed {field}")
if direct and not np.array_equal(getattr(before, field), actual):
raise ValueError(f"relocating flattened model changed exact {field}")
if temporary_names:
for element in root.iter():
if element.tag in {"body", "geom"} and element.get("name") in temporary_names:
del element.attrib["name"]
ET.ElementTree(root).write(output, encoding="utf-8", xml_declaration=True)
return dependencies
+97
View File
@@ -0,0 +1,97 @@
"""Optional calibrated motor laws for native policy playback.
BAM owns the electrical and friction equations. Its constructor receives scratch
MuJoCo data because mj_setConst resets qpos; no live world is passed to it.
"""
from __future__ import annotations
from collections.abc import Mapping
from importlib.metadata import version
import re
import sys
import mujoco
import numpy as np
from mjrl.controllers.model import finite
BAM_VERSION = "1.0.2"
BAM_REQUIREMENT = f"better-actuator-models=={BAM_VERSION}"
BAM_PYTHON_REQUIREMENT = ">=3.12,<3.13"
def validate_motor_model(config: Mapping) -> dict:
fields = {
"kind", "motor_name", "model", "kp", "vin", "max_current",
"vin_drop_resistance", "vin_min",
}
if not isinstance(config, Mapping) or set(config) != fields or config.get("kind") != "bam":
raise ValueError(f"motor_model requires BAM fields {sorted(fields)}")
result = dict(config)
for field in ("motor_name", "model"):
if not isinstance(result[field], str) or not re.fullmatch(r"[a-zA-Z0-9_-]+", result[field]):
raise ValueError(f"motor_model.{field} must name a built-in BAM model")
for field in ("kp", "vin", "max_current", "vin_min"):
result[field] = finite(result[field], f"motor_model.{field}", positive=True)
result["vin_drop_resistance"] = finite(
result["vin_drop_resistance"], "motor_model.vin_drop_resistance"
)
if result["vin_drop_resistance"] < 0 or result["vin_min"] > result["vin"]:
raise ValueError("motor_model requires nonnegative resistance and vin_min <= vin")
return result
class BamMotorModel:
"""Apply a named BAM model once per physics tick, reset independently per run."""
def __init__(self, model, actuator_ids, effort, config):
config = validate_motor_model(config)
if sys.version_info[:2] != (3, 12):
raise ValueError(f"Native BAM playback requires Python {BAM_PYTHON_REQUIREMENT}")
if version("better-actuator-models") != BAM_VERSION:
raise ValueError(f"Native BAM playback requires {BAM_REQUIREMENT}")
from bam.model import load_model
from bam.mujoco import MujocoController
self.model = model
self.actuator_ids = np.asarray(actuator_ids)
self.effort = np.asarray(effort).copy()
self.dofs = model.jnt_dofadr[model.actuator_trnid[self.actuator_ids, 0]]
self.initial_friction = model.dof_frictionloss[self.dofs].copy()
self.initial_damping = model.dof_damping[self.dofs].copy()
motor = load_model(motor_name=config["motor_name"], model=config["model"])
for key in ("kp", "vin", "max_current"):
setattr(motor.actuator, key, config[key])
names = [model.actuator(int(index)).name for index in self.actuator_ids]
if any(not name for name in names):
raise ValueError("BAM requires named actuators")
self.controller = MujocoController(
motor, names, model, mujoco.MjData(model),
vin_drop_resistance=config["vin_drop_resistance"], vin_min=config["vin_min"],
)
self._applied_time = None
self._torque = np.zeros(len(names))
def reset(self, data, targets):
self.model.dof_frictionloss[self.dofs] = self.initial_friction
self.model.dof_damping[self.dofs] = self.initial_damping
controller = self.controller
controller.mujoco_data = data
controller.model.reset()
controller.last_ts = float(data.time)
controller.q_target = np.asarray(targets).copy()
self._applied_time = None
self._torque[:] = 0
data.ctrl[self.actuator_ids] = 0
def apply(self, data, targets):
# step() and the physics loop both call apply(). Evaluating BAM twice
# would update its state/friction twice for one physical sample.
if self._applied_time != float(data.time):
self.controller.mujoco_data = data
self.controller.q_target = np.asarray(targets).copy()
self.controller.update()
self._torque = np.clip(data.ctrl[self.actuator_ids], -self.effort, self.effort)
self._applied_time = float(data.time)
data.ctrl[self.actuator_ids] = self._torque
return data.ctrl.copy()
+7 -2
View File
@@ -9,7 +9,7 @@ import math
from pathlib import Path
import time
from .bundle import open_bundle, safe_path, write_json
from .bundle import IK_MOUSE_HELP, open_bundle, safe_path, write_json
class RobotApplication:
@@ -270,11 +270,16 @@ def play(
if headless:
viewer = None
else:
mouse_ik = app.config.get("kind") == "ik" and command is None
if mouse_ik:
print(f"[play] {IK_MOUSE_HELP}", flush=True)
viewer_keys.register(keys.report)
stack.callback(viewer_keys.unregister, keys.report)
viewer = stack.enter_context(
mujoco.viewer.launch_passive(
app.model, app.data, key_callback=viewer_keys.from_viewer
app.model, app.data, key_callback=viewer_keys.from_viewer,
# Keep the draggable marker visible in a narrow viewport.
show_left_ui=not mouse_ik, show_right_ui=not mouse_ik,
)
)
frames = []
+57 -1
View File
@@ -142,6 +142,32 @@ class OnnxController:
self.targets = self.home.copy()
self.velocity_targets = np.zeros_like(self.home)
self._configure_actuators(model)
self.motor_model = None
if "motor_model" in layout:
from .motors import BamMotorModel
if not self.native or np.any(self.velocity_axes):
raise ValueError("BAM requires native position actions")
self.motor_model = BamMotorModel(
model, self.actuators, self.effort[self.driven_idx], layout["motor_model"]
)
self.observation_frames = {}
frames = observation.get("frames", {})
if not isinstance(frames, Mapping) or set(frames) - names:
raise ValueError("Observation frames must name observed vector terms")
for term, frame in frames.items():
if term not in {"base_ang_vel", "base_lin_vel", "projected_gravity"}:
raise ValueError(f"{term} cannot declare an observation frame")
if not isinstance(frame, Mapping) or set(frame) != {"kind", "name"}:
raise ValueError("Observation frame requires kind and name")
kind = frame["kind"]
if kind not in {"body", "site"}:
raise ValueError("Observation frame kind must be body or site")
obj = mujoco.mjtObj.mjOBJ_BODY if kind == "body" else mujoco.mjtObj.mjOBJ_SITE
index = object_id(model, obj, frame["name"])
if kind == "body" and index == 0:
raise ValueError("Observation body frame must identify a robot body")
self.observation_frames[term] = (kind, index)
@staticmethod
def _tensor_name(tensor, width: int, which: str) -> str:
@@ -360,9 +386,28 @@ class OnnxController:
self.operator.reset()
for *_, history in self.terms:
history.clear()
self.apply(data)
if self.motor_model is None:
self.apply(data)
else:
self.motor_model.reset(data, self.targets[self.driven_idx])
mujoco.mj_forward(self.model, data)
def reset_passive(self, data) -> None:
"""Reset dynamic friction for an actuation-disabled counterfactual.
Preserve the supplied world state; policy state and targets from the
active rollout must not influence the passive comparison.
"""
if self.motor_model is not None:
self.motor_model.reset(data, data.qpos[self.qadr[self.driven_idx]])
def apply_passive(self, data) -> None:
if self.motor_model is not None:
if not self.model.opt.disableflags & mujoco.mjtDisableBit.mjDSBL_ACTUATION:
raise ValueError("Passive motor update requires disabled actuation")
self.motor_model.apply(data, data.qpos[self.qadr[self.driven_idx]])
data.ctrl[self.actuators] = 0
def observation(self, data, command):
mujoco.mj_forward(self.model, data)
values = {
@@ -383,6 +428,15 @@ class OnnxController:
values["projected_gravity"] = data.xmat[self.root_body].reshape(3, 3).T @ np.asarray(
[0.0, 0.0, -1.0]
)
for term, (kind, index) in self.observation_frames.items():
if term == "projected_gravity":
matrix = data.xmat[index] if kind == "body" else data.site_xmat[index]
values[term] = matrix.reshape(3, 3).T @ np.asarray([0.0, 0.0, -1.0])
else:
velocity = np.zeros(6)
obj = mujoco.mjtObj.mjOBJ_XBODY if kind == "body" else mujoco.mjtObj.mjOBJ_SITE
mujoco.mj_objectVelocity(self.model, data, obj, index, velocity, 1)
values[term] = velocity[:3] if term == "base_ang_vel" else velocity[3:]
parts = []
for name, indices, scale, clip, count, stride, history in self.terms:
frame = values[name]
@@ -446,6 +500,8 @@ class OnnxController:
def apply(self, data):
i = self.driven_idx
if self.motor_model is not None:
return self.motor_model.apply(data, self.targets[i])
torque = self.kp[i] * (self.targets[i] - data.qpos[self.qadr[i]])
torque += self.kd[i] * (self.velocity_targets[i] - data.qvel[self.vadr[i]])
data.ctrl[self.actuators] = np.clip(torque, -self.effort[i], self.effort[i])
+206
View File
@@ -0,0 +1,206 @@
"""Robot-independent stepping rewards for the biped recipe."""
from __future__ import annotations
import math
from typing import TYPE_CHECKING
import torch
from mjlab.tasks.velocity.mdp.rewards import feet_swing_height
if TYPE_CHECKING:
from mjlab.envs import ManagerBasedRlEnv
class ActiveActionRate:
"""Smooth policy channels that actually change physical targets.
Resolve the mask from each action term's runtime order, not RobotSpec
order. Zero-scale channels still exist in observations and retain their PD
home hold, but their raw policy variations cannot move a joint.
"""
def __init__(self, cfg, env: ManagerBasedRlEnv):
masks = []
for name in env.action_manager.active_terms:
term = env.action_manager.get_term(name)
scale = torch.as_tensor(term.scale, device=env.device)
if not torch.isfinite(scale).all():
raise ValueError("Action scales must be finite")
masks.append(torch.broadcast_to(scale != 0, term.raw_action.shape))
self.active = torch.cat(masks, dim=-1)
if self.active.shape != env.action_manager.action.shape:
raise ValueError("Physical action mask must match the policy action layout")
def __call__(self, env: ManagerBasedRlEnv) -> torch.Tensor:
delta = env.action_manager.action - env.action_manager.prev_action
return (delta.square() * self.active).sum(dim=-1)
def bounded_single_support(
env: ManagerBasedRlEnv, sensor_name: str, command_name: str,
) -> torch.Tensor:
"""Credit one-foot support during a commanded, bounded-duration swing.
Contact slots belong to a foot, not separate supports. Both feet in stance,
flight, and a foot held aloft beyond 0.4 seconds earn no credit. This is a
running reward rate; the reward manager supplies the control timestep.
"""
sensor = env.scene[sensor_name]
found = sensor.data.found
air_time = sensor.data.current_air_time
assert found is not None and air_time is not None
if air_time.ndim != 2 or found.shape[:2] != air_time.shape:
raise ValueError("support contact and airtime must share [environment, foot] axes")
touching = (found > 0).reshape(*air_time.shape, -1).any(dim=-1)
command = env.command_manager.get_command(command_name)
assert command is not None
moving = command[:, :2].norm(dim=-1) + command[:, 2].abs() > 0.05
one_support = touching.sum(dim=-1) == 1
swing = ((air_time > 0.05) & (air_time < 0.4)).any(dim=-1)
return (moving & one_support & swing).float()
class ResettableSwingHeight(feet_swing_height):
"""Keep the reference landing cost while clearing peaks on episode reset.
The vendored reward retains per-foot peaks but has no reset hook. Without
clearing selected rows, a terminated episode can affect its successor's
first landing. The inherited landing formula and timestep scaling stay
unchanged.
"""
def reset(self, env_ids: torch.Tensor | slice | None = None) -> None:
self.peak_heights[slice(None) if env_ids is None else env_ids] = 0.0
def command_relative_linear_tracking(
env: ManagerBasedRlEnv, command_name: str,
minimum_width: float = 0.1,
) -> torch.Tensor:
"""Keep low-speed tracking meaningful while allowing wider high-speed error."""
command = env.command_manager.get_command(command_name)
assert command is not None
actual = env.scene["robot"].data.root_link_lin_vel_b
speed = command[:, :2].norm(dim=-1)
width = (0.1 + 0.5 * speed).clamp(max=0.5)
width = torch.where(speed > 0.05, width.clamp(min=minimum_width), width)
error = (command[:, :2] - actual[:, :2]).square().sum(dim=-1) + actual[:, 2].square()
return torch.exp(-error / width.square())
def command_relative_angular_tracking(
env: ManagerBasedRlEnv, command_name: str,
minimum_width: float = 0.15,
) -> torch.Tensor:
"""Scale moving yaw tolerance while preserving the stationary noise floor."""
command = env.command_manager.get_command(command_name)
assert command is not None
actual = env.scene["robot"].data.root_link_ang_vel_b
# An additive floor made small nonzero turns too tolerant of undertracking.
# Clamping preserves the zero-yaw floor without adding it to moving turns.
width = (0.5 * command[:, 2].abs()).clamp(min=minimum_width, max=math.sqrt(0.5))
yaw_error = (command[:, 2] - actual[:, 2]).square() / width.square()
roll_pitch_error = actual[:, :2].square().sum(dim=-1) / 0.5
return torch.exp(-yaw_error - roll_pitch_error)
def translation_aware_angular_tracking(
env: ManagerBasedRlEnv, command_name: str,
linear_minimum_width: float = 0.1, translating_yaw_width: float = 0.15,
) -> torch.Tensor:
"""Reward the requested twist jointly when translation is commanded.
A robot standing still used to collect the entire heading reward while
ignoring forward commands. Retain a small heading floor during exploration,
and award the remainder in proportion to linear tracking. Pure turns and
idle commands retain their original yaw objective and noise tolerance.
"""
command = env.command_manager.get_command(command_name)
assert command is not None
turning = command_relative_angular_tracking(env, command_name)
translating = command[:, :2].norm(dim=-1) > 0.05
if translating_yaw_width != 0.15:
# Normal walking includes instantaneous pelvis heading oscillations.
# Relax only translating commands; pure-turn and idle accuracy retain
# their existing objective and still have separate native probes.
translating_heading = command_relative_angular_tracking(
env, command_name, minimum_width=translating_yaw_width,
)
turning = torch.where(translating, translating_heading, turning)
linear = command_relative_linear_tracking(env, command_name, minimum_width=linear_minimum_width)
multiplier = torch.where(translating, 0.2 + 0.8 * linear, torch.ones_like(linear))
return turning * multiplier
class CompletedSwingQuality:
"""Bounded height/duration cost for a swing observed from takeoff to landing.
Each foot must first be observed grounded after reset. Contact events that
never include an observed airborne sample, including reset-truncated swings,
incur no cost. Each completed event is divided by control dt so the reward
manager's integration leaves its magnitude independent of control rate.
"""
def __init__(self, cfg, env: ManagerBasedRlEnv):
for name in ("target_height", "target_swing_s"):
value = cfg.params[name]
if not math.isfinite(value) or value <= 0:
raise ValueError(f"{name} must be finite and positive")
minimum = cfg.params.get("minimum_motion_fraction", 1.0)
if not math.isfinite(minimum) or not 0 < minimum <= 1:
raise ValueError("minimum_motion_fraction must lie in (0, 1]")
count = env.scene[cfg.params["height_sensor_name"]].num_frames
self.peak_heights = torch.zeros((env.num_envs, count), device=env.device)
self.armed = torch.zeros_like(self.peak_heights, dtype=torch.bool)
self.in_swing = torch.zeros_like(self.armed)
def __call__(
self, env: ManagerBasedRlEnv, sensor_name: str, height_sensor_name: str,
target_height: float, target_swing_s: float, command_name: str,
command_threshold: float = 0.05,
minimum_motion_fraction: float = 1.0,
) -> torch.Tensor:
sensor = env.scene[sensor_name]
found, duration = sensor.data.found, sensor.data.last_air_time
assert found is not None and duration is not None
heights = env.scene[height_sensor_name].data.heights
if (heights.shape != self.peak_heights.shape or duration.shape != heights.shape
or found.shape[:2] != heights.shape):
raise ValueError("swing heights, airtime and contacts must share [environment, foot] axes")
touching = (found > 0).reshape(*heights.shape, -1).any(dim=-1)
taking_off = self.armed & ~touching & ~self.in_swing
self.in_swing |= taking_off
self.peak_heights = torch.where(taking_off, torch.zeros_like(heights), self.peak_heights)
self.peak_heights = torch.where(
self.in_swing & ~touching, torch.maximum(self.peak_heights, heights), self.peak_heights,
)
landed = self.in_swing & touching
height_cost = (self.peak_heights / target_height - 1).square().clamp(max=4.0)
duration_cost = (duration / target_swing_s - 1).square().clamp(max=4.0)
command = env.command_manager.get_command(command_name)
assert command is not None
moving = command[:, :2].norm(dim=-1) + command[:, 2].abs() > command_threshold
cost = ((height_cost + duration_cost) * landed).sum(dim=-1) / env.step_dt
if minimum_motion_fraction < 1.0:
# Preserve the small exploration cost while standing or initially
# moving. Apply the full quality cost once command progress exists.
# This adds no positive landing credit or cadence bonus.
data = env.scene["robot"].data
speed2 = command[:, :2].square().sum(dim=-1)
linear = (data.root_link_lin_vel_b[:, :2] * command[:, :2]).sum(dim=-1)
linear = linear / speed2.clamp(min=command_threshold ** 2)
angular = data.root_link_ang_vel_b[:, 2] * command[:, 2]
angular = angular / command[:, 2].square().clamp(min=command_threshold ** 2)
progress = torch.where(speed2 > command_threshold ** 2, linear, angular).clamp(0, 1)
cost *= minimum_motion_fraction + (1 - minimum_motion_fraction) * progress
self.peak_heights = torch.where(touching, torch.zeros_like(heights), self.peak_heights)
self.in_swing &= ~touching
self.armed |= touching
return cost * moving
def reset(self, env_ids: torch.Tensor | slice | None = None) -> None:
selection = slice(None) if env_ids is None else env_ids
self.peak_heights[selection] = 0.0
self.armed[selection] = False
self.in_swing[selection] = False
+67
View File
@@ -0,0 +1,67 @@
"""Training command distributions with explicit coverage of isolated axes."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import TYPE_CHECKING
import torch
from mjlab.tasks.velocity.mdp.velocity_command import UniformVelocityCommand, UniformVelocityCommandCfg
if TYPE_CHECKING:
from mjlab.envs import ManagerBasedRlEnv
@dataclass(kw_only=True)
class AxisBalancedVelocityCommandCfg(UniformVelocityCommandCfg):
"""Reserve a fraction of nonstanding commands for uniformly selected axes.
The remainder retains independent uniform sampling of all three axes.
Standing probability is inherited and independent of this conditional
fraction. Use this distribution for training, keeping replay's operator
command unchanged.
"""
isolated_axis_fraction: float = .3
def __post_init__(self):
super().__post_init__()
for name in ("isolated_axis_fraction", "rel_standing_envs", "init_velocity_prob"):
value = getattr(self, name)
if isinstance(value, bool) or not isinstance(value, (int, float)) or not math.isfinite(value) or not 0 <= value <= 1:
raise ValueError(f"{name} must be a finite fraction in [0, 1]")
if self.heading_command or self.ranges.heading is not None or self.rel_world_envs != 0 or self.rel_forward_envs != 0:
raise ValueError("Axis-balanced commands require body-frame sampling without heading, world, or forward modes")
for axis in ("lin_vel_x", "lin_vel_y", "ang_vel_z"):
bounds = getattr(self.ranges, axis)
if len(bounds) != 2 or any(isinstance(v, bool) or not isinstance(v, (int, float)) or not math.isfinite(v) for v in bounds) or not bounds[0] <= 0 <= bounds[1]:
raise ValueError(f"{axis} range must contain finite ordered bounds including zero")
def build(self, env: ManagerBasedRlEnv) -> AxisBalancedVelocityCommand:
return AxisBalancedVelocityCommand(self, env)
class AxisBalancedVelocityCommand(UniformVelocityCommand):
cfg: AxisBalancedVelocityCommandCfg
def __init__(self, cfg: AxisBalancedVelocityCommandCfg, env: ManagerBasedRlEnv):
cfg.__post_init__() # Also reject incompatible mutations made after config creation.
super().__init__(cfg, env)
def _resample_command(self, env_ids: torch.Tensor) -> None:
count = len(env_ids)
values = torch.empty((count, 3), device=self.device)
for column, axis in enumerate(("lin_vel_x", "lin_vel_y", "ang_vel_z")):
values[:, column].uniform_(*getattr(self.cfg.ranges, axis))
standing = torch.rand(count, device=self.device) < self.cfg.rel_standing_envs
isolated = (torch.rand(count, device=self.device) < self.cfg.isolated_axis_fraction) & ~standing
axes = torch.randint(3, (count,), device=self.device)
keep = ~isolated[:, None] | (torch.arange(3, device=self.device)[None, :] == axes[:, None])
values *= keep
self.vel_command_b[env_ids] = values
self.vel_command_w[env_ids] = values
self.is_standing_env[env_ids] = standing
self.is_heading_env[env_ids] = False
self.is_world_env[env_ids] = False
self.is_forward_env[env_ids] = False
+20 -14
View File
@@ -44,7 +44,8 @@ Nothing here is task-specific or robot-specific: the names come from the entity.
A live window is the right answer and is not always available: matplotlib needs
an interactive backend, which needs a GUI toolkit, and a training box reached
over SSH often has none. So this picks in order:
over SSH often has none. When an interactive view is explicitly requested,
this picks in order:
1. **a matplotlib window**, if an interactive backend imports -- three stacked
panels, one line per joint, a rolling window;
@@ -112,7 +113,7 @@ _BACKENDS = (
#: not enough to find out whether a window can open.
_PROBE = (
"import matplotlib;matplotlib.use({backend!r});"
"import matplotlib.pyplot as p;p.figure();p.close('all')"
"import matplotlib.pyplot as p;p.ioff();p.figure();p.close('all')"
)
@@ -157,7 +158,8 @@ class JointMonitor:
"""Collects and displays joint telemetry for one environment.
`update` is called once per control step from `play._loop`; `close` writes the
artifacts. Construction decides the display, so a failure to open a window
artifacts. An explicit `interactive=True` enables the live window.
Construction decides the display, so a failure to open a window
happens before the replay starts rather than a minute into it.
"""
@@ -171,6 +173,8 @@ class JointMonitor:
foot_names: "tuple[str, ...] | None" = None,
window_s: float = WINDOW_S,
refresh_hz: float = REFRESH_HZ,
*,
interactive: bool = False,
) -> None:
self.entity = entity
self.index = index
@@ -200,11 +204,11 @@ class JointMonitor:
self._fig = None
self._lines: dict[str, list] = {}
chosen = _interactive_backend()
chosen = _interactive_backend() if interactive else None
self._backend = None if chosen is None else chosen[0]
if chosen is not None:
self._open_window(*chosen)
else:
elif interactive:
print(
"[measure] no toolkit here can open a window, so the live view is "
"a table (`pip install PyQt5` in the venv is usually enough). The "
@@ -442,14 +446,13 @@ class JointMonitor:
def _write_png(self, path: Path) -> None:
"""The whole run, not the rolling window -- this is the artifact."""
import matplotlib
if self._fig is None:
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.backends.backend_agg import FigureCanvasAgg
from matplotlib.figure import Figure
count = 4 if self.foot_names else 3
fig, axes = plt.subplots(count, 1, sharex=True, figsize=(12, 3 * count))
fig = Figure(figsize=(12, 3 * count))
FigureCanvasAgg(fig)
axes = fig.subplots(count, 1, sharex=True)
panels = [
(axes[0], self._pos, "position [rad]", self.joint_names),
(axes[1], self._vel, "velocity [rad/s]", self.joint_names),
@@ -474,10 +477,12 @@ class JointMonitor:
fig.suptitle(title)
fig.tight_layout()
fig.savefig(path, dpi=120)
plt.close(fig)
def make_monitor(entity: Any, index: int, env, out_dir: Path) -> "JointMonitor | None":
def make_monitor(
entity: Any, index: int, env, out_dir: Path, *, interactive: bool = False,
) -> "JointMonitor | None":
"""Build a monitor for an entity, or None if it has no joints to measure.
The entity is passed in rather than found here: `play.py` already picks the
@@ -493,7 +498,8 @@ def make_monitor(entity: Any, index: int, env, out_dir: Path) -> "JointMonitor |
return None
unwrapped = getattr(env, "unwrapped", env)
sensor, names = _find_foot_sensor(unwrapped)
return JointMonitor(entity, index, unwrapped.step_dt, out_dir, sensor, names)
return JointMonitor(entity, index, unwrapped.step_dt, out_dir, sensor, names,
interactive=interactive)
def _find_foot_sensor(env) -> "tuple[Any, tuple[str, ...]]":
+2 -1
View File
@@ -58,7 +58,8 @@ def _parser() -> argparse.ArgumentParser:
setup.add_argument("--output", "--out", required=True, type=Path, help="output directory")
extract = commands.add_parser("extract-tier1", help="extract and review upstream policy metadata")
extract.add_argument("configs", nargs="+", type=Path, help="YAML, JSON or Python training configs")
extract.add_argument("configs", nargs="*", type=Path,
help="YAML, JSON or Python training configs; omit with --model for facts only")
extract.add_argument("--output", "--out", required=True, type=Path, help="new draft directory")
extract.add_argument("--model", type=Path, help="MJCF model for metadata validation")
extract.add_argument("--overrides", type=Path, help="reviewed JSON/YAML field overrides")
+2 -1
View File
@@ -511,7 +511,8 @@ def _run(spec, res, asset: Path | None, args) -> None:
from mjrl.viewer.monitor import make_monitor
out = (ckpt.parent if trained else Path.cwd()) / "measure"
monitor = make_monitor(*_watched(wrapped), wrapped, out)
monitor = make_monitor(*_watched(wrapped), wrapped, out,
interactive=not args.headless)
if monitor is None:
print("[measure] this scene has no entity with joints; nothing to measure")
+17 -6
View File
@@ -42,18 +42,22 @@ class JointSpec:
kp: float
kd: float
effort_limit: float
action_scale: float
action_scale: float # Zero holds a position actuator at its calibrated home.
home: float = 0.0
armature: float = 0.0
posture_std: float = 0.35
def __post_init__(self) -> None:
_names("joint", (self.name,))
_number(f"{self.name}.kp", self.kp, minimum=0.0)
_number(f"{self.name}.kd", self.kd, minimum=0.0)
_number(f"{self.name}.effort_limit", self.effort_limit, minimum=1e-12)
_number(f"{self.name}.action_scale", self.action_scale, minimum=1e-12)
_number(f"{self.name}.action_scale", self.action_scale, minimum=0.0)
_number(f"{self.name}.home", self.home)
_number(f"{self.name}.armature", self.armature, minimum=0.0)
_number(f"{self.name}.posture_std", self.posture_std, minimum=0.0)
if self.posture_std <= 0:
raise ValueError(f"{self.name}.posture_std must be positive")
@dataclass(frozen=True)
@@ -72,6 +76,7 @@ class RobotSpec:
foot_bodies: tuple[str, ...] = ()
penalized_contact_geoms: tuple[str, ...] = ()
termination_contact_geoms: tuple[str, ...] = ()
foot_sites: tuple[str, ...] = ()
def __post_init__(self) -> None:
if (
@@ -89,10 +94,14 @@ class RobotSpec:
raise ValueError("controls_path must be a Path or None")
_names("base_body", (self.base_body,))
_number("base_height", self.base_height, minimum=1e-12)
for key in ("foot_geoms", "foot_bodies", "penalized_contact_geoms", "termination_contact_geoms"):
if not isinstance(self.foot_sites, (list, tuple)):
raise ValueError("foot_sites must be a list or tuple of names")
for key in ("foot_geoms", "foot_bodies", "foot_sites", "penalized_contact_geoms", "termination_contact_geoms"):
_names(key, getattr(self, key))
if bool(self.foot_geoms) == bool(self.foot_bodies):
raise ValueError("declare either foot_geoms or foot_bodies")
if self.foot_sites and len(self.foot_sites) != len(self.foot_geoms or self.foot_bodies):
raise ValueError("foot_sites must have one site per named foot support")
min_contacts = {"biped": 2, "quadruped": 4, "wheeled_biped": 2, "multipod": 5}
if len(self.foot_geoms or self.foot_bodies) < min_contacts[self.family]:
raise ValueError(f"{self.family} requires at least {min_contacts[self.family]} supports")
@@ -102,11 +111,13 @@ class RobotSpec:
_names("position_joints and velocity_joints", tuple(j.name for j in self.joints))
if not self.position_joints or any(j.kp <= 0 for j in self.position_joints):
raise ValueError("position_joints must contain joints with kp > 0")
if not any(j.action_scale > 0 for j in self.joints):
raise ValueError("at least one joint must have a positive action_scale")
if self.family == "wheeled_biped":
if len(self.velocity_joints) < 2 or any(
j.kp != 0 or j.kd <= 0 for j in self.velocity_joints
j.kp != 0 or j.kd <= 0 or j.action_scale <= 0 for j in self.velocity_joints
):
raise ValueError("wheeled_biped requires at least two velocity joints with kp=0, kd>0")
raise ValueError("wheeled_biped requires at least two velocity joints with kp=0, kd>0, action_scale>0")
elif self.velocity_joints:
raise ValueError("velocity_joints are supported by wheeled_biped only")
@@ -121,7 +132,7 @@ class RobotSpec:
for key in ("model_path", "controls_path"):
if key in data and data[key] is not None:
data[key] = (base_dir / Path(data[key])).resolve()
for key in ("foot_geoms", "foot_bodies", "penalized_contact_geoms", "termination_contact_geoms"):
for key in ("foot_geoms", "foot_bodies", "foot_sites", "penalized_contact_geoms", "termination_contact_geoms"):
if key in data:
if not isinstance(data[key], (tuple, list)):
raise ValueError(f"{key} must be a list or tuple of names")
+4 -1
View File
@@ -7,7 +7,10 @@ _RECIPE = LocomotionRecipe(
command_ceiling=(0.7, 0.35, 0.8),
fall_angle_deg=55.0,
upright_weight=1.4,
air_time_weight=0.2,
air_time_weight=0.0,
# With posture and clearance costs, tiny commands favor standing. Train
# the full velocity range from the start.
command_fractions=(1.0,),
)
+142 -14
View File
@@ -25,7 +25,7 @@ from mjlab.managers import (
from mjlab.managers.scene_entity_config import SceneEntityCfg
from mjlab.rl import RslRlModelCfg, RslRlOnPolicyRunnerCfg
from mjlab.scene import SceneCfg
from mjlab.sensor import ContactMatch, ContactSensorCfg
from mjlab.sensor import ContactMatch, ContactSensorCfg, ObjRef, RingPatternCfg, TerrainHeightSensorCfg
from mjlab.sim import MujocoCfg, SimulationCfg
from mjlab.tasks.velocity import mdp as velocity_mdp
from mjlab.terrains import TerrainEntityCfg
@@ -34,6 +34,14 @@ from mjlab.viewer import ViewerConfig
from controller.controls import controller_contract, load_controls
from mjrl.tasks.curriculum import CommandRangeCurriculum
from mjrl.tasks.biped import (
ActiveActionRate,
CompletedSwingQuality,
bounded_single_support,
command_relative_linear_tracking,
translation_aware_angular_tracking,
)
from mjrl.tasks.commands import AxisBalancedVelocityCommandCfg
from mjrl.tasks.mdp import (
actuator_force,
base_roll_pitch_velocity,
@@ -63,6 +71,7 @@ class LocomotionRecipe:
fall_angle_deg: float
upright_weight: float
air_time_weight: float
command_fractions: tuple[float, ...] = _FRACTIONS
def _load_model(
@@ -91,9 +100,9 @@ def _load_model(
# The robot supplies geometry and dynamics. The calibrated spec supplies
# actuator gains and the home state, so remove the authored copies first.
for actuator in list(spec.actuators):
actuator.delete()
spec.delete(actuator)
for key in list(spec.keys):
key.delete()
spec.delete(key)
model = spec.compile()
joints = {joint.name: joint for joint in robot.joints}
@@ -118,7 +127,28 @@ def _load_model(
if missing := joints.keys() - homes.keys():
raise ValueError(f"{path}: missing calibrated joints {sorted(missing)}")
return spec, _contact_geoms(model, path, robot), homes
support_geoms = _contact_geoms(model, path, robot)
_ordered_foot_sites(model, robot)
return spec, support_geoms, homes
def _ordered_foot_sites(model: mujoco.MjModel, robot: RobotSpec) -> tuple[str, ...]:
"""Align sole markers to contact slots, which follow compiled model order."""
if not robot.foot_sites:
return ()
mode = mujoco.mjtObj.mjOBJ_BODY if robot.foot_bodies else mujoco.mjtObj.mjOBJ_GEOM
supports = robot.foot_bodies or robot.foot_geoms
ordered = []
for support, site_name in zip(supports, robot.foot_sites, strict=True):
support_id = mujoco.mj_name2id(model, mode, support)
site_id = mujoco.mj_name2id(model, mujoco.mjtObj.mjOBJ_SITE, site_name)
if site_id < 0:
raise ValueError(f"missing foot site {site_name!r}")
body_id = support_id if robot.foot_bodies else int(model.geom_bodyid[support_id])
if int(model.site_bodyid[site_id]) != body_id:
raise ValueError(f"foot site {site_name!r} must be on its support {support!r}")
ordered.append((support_id, site_name))
return tuple(name for _, name in sorted(ordered))
def _contact_geoms(model: mujoco.MjModel, path: Path, robot: RobotSpec) -> tuple[str, ...]:
@@ -155,7 +185,20 @@ def validate_robot_model(robot: RobotSpec, asset: Path | None = None) -> None:
def _entity_spec(path: Path, robot: RobotSpec) -> mujoco.MjSpec:
return _load_model(path, robot)[0]
spec = _load_model(path, robot)[0]
if robot.family == "biped" and robot.foot_sites:
# Terrain scans select group 0. Rendering groups do not alter contact
# masks; keep robot colliders out of terrain-only height measurements.
for geom in spec.geoms:
if geom.contype or geom.conaffinity:
geom.group = 3
elif geom.group == 0:
geom.group = 1
spec.add_sensor(
name="mjrl_root_angmom", type=mujoco.mjtSensor.mjSENS_SUBTREEANGMOM,
objtype=mujoco.mjtObj.mjOBJ_BODY, objname=robot.base_body,
)
return spec
def _patterns(names) -> tuple[str, ...]:
@@ -254,8 +297,11 @@ def _observations(robot: RobotSpec, play: bool):
def _commands(robot: RobotSpec, recipe: LocomotionRecipe, play: bool):
command_cls = velocity_mdp.UniformVelocityCommandCfg
fraction = 1.0 if play else _FRACTIONS[0]
command_cls = (
AxisBalancedVelocityCommandCfg if robot.family == "biped" and not play
else velocity_mdp.UniformVelocityCommandCfg
)
fraction = 1.0 if play else recipe.command_fractions[0]
x, y, yaw = (value * fraction for value in recipe.command_ceiling)
kwargs = {
"entity_name": "robot",
@@ -358,18 +404,21 @@ def _contact_penalty(env, sensor_name: str | None) -> torch.Tensor:
return _contact_hit(env, sensor_name).float()
def _contact_sensor(name: str, mode: str, patterns: tuple[str, ...], air_time: bool = False):
def _contact_sensor(
name: str, mode: str, patterns: tuple[str, ...], air_time: bool = False,
forces: bool = False,
):
return ContactSensorCfg(
name=name,
primary=ContactMatch(mode=mode, pattern=_patterns(patterns), entity="robot"),
secondary=ContactMatch(mode="body", pattern="terrain"),
fields=("found",),
fields=("found", "force") if forces else ("found",),
track_air_time=air_time,
reduce="maxforce",
reduce="netforce" if forces else "maxforce",
)
def _rewards(robot: RobotSpec, recipe: LocomotionRecipe):
def _rewards(robot: RobotSpec, recipe: LocomotionRecipe, foot_sites: tuple[str, ...] = ()):
leg_joints = _joint_selection(robot.position_joints)
rewards = {
"track_linear_velocity": RewardTermCfg(
@@ -422,6 +471,76 @@ def _rewards(robot: RobotSpec, recipe: LocomotionRecipe):
"command_name": _COMMAND, "command_threshold": 0.08,
},
)
if robot.family == "biped":
# Keep robot-specific homes and named posture tolerances in RobotSpec.
rewards["track_linear_velocity"].weight = 3.0
rewards["track_linear_velocity"].func = command_relative_linear_tracking
rewards["track_linear_velocity"].params = {"command_name": _COMMAND, "minimum_width": 0.35}
rewards["track_angular_velocity"] = RewardTermCfg(
# Keep pure-turn incentive, but do not award full heading credit
# to a stationary robot ignoring a simultaneous translation.
func=translation_aware_angular_tracking, weight=3.0,
params={"command_name": _COMMAND, "linear_minimum_width": 0.35,
"translating_yaw_width": 0.5},
)
rewards.pop("joint_home")
moving_std = {re.escape(joint.name): joint.posture_std for joint in robot.position_joints}
rewards["pose"] = RewardTermCfg(
func=velocity_mdp.variable_posture, weight=0.5,
params={
"asset_cfg": leg_joints, "command_name": _COMMAND,
"std_standing": {".*": 0.1},
"std_walking": moving_std, "std_running": moving_std.copy(),
"walking_threshold": 0.05, "running_threshold": 1.5,
},
)
# Smooth physical action channels; held joints must not dominate this
# budget while rapid hip/knee targets are filtered by passive damping.
rewards["action_rate"] = RewardTermCfg(func=ActiveActionRate, weight=-0.03)
# Natural-gait revision: raw squared torque disproportionately taxes
# high-effort hip/knee swing compared with low-effort ankle rocking.
# Preserve effort limits and native saturation gates; reduce this cost.
rewards["leg_torque"].weight = -1.0e-6
rewards.pop("swing_air_time", None)
rewards["single_support"] = RewardTermCfg(
func=bounded_single_support, weight=0.5,
params={"sensor_name": _SUPPORT_SENSOR, "command_name": _COMMAND},
)
if foot_sites:
# Sole height is relative to the actual terrain ray hit, not world Z.
sole_selection = SceneEntityCfg("robot", site_names=_patterns(foot_sites), preserve_order=True)
height = min(0.08, 0.1 * robot.base_height)
rewards.pop("support_slip")
rewards["foot_clearance"] = RewardTermCfg(
func=velocity_mdp.feet_clearance, weight=-2.0,
params={"target_height": height, "height_sensor_name": "sole_height",
"command_name": _COMMAND, "command_threshold": 0.05,
"asset_cfg": sole_selection},
)
rewards["swing_quality"] = RewardTermCfg(
# Integrated landing cost. Keep the initial exploration budget
# at .005, then strengthen quality with actual command progress.
func=CompletedSwingQuality, weight=-0.03,
params={"target_height": height, "height_sensor_name": "sole_height",
"sensor_name": _SUPPORT_SENSOR, "command_name": _COMMAND,
"command_threshold": 0.05,
"target_swing_s": 0.24 * math.sqrt(robot.base_height / 0.68),
"minimum_motion_fraction": 1.0 / 6.0},
)
rewards["foot_slip"] = RewardTermCfg(
func=velocity_mdp.feet_slip, weight=-0.1,
params={"sensor_name": _SUPPORT_SENSOR, "command_name": _COMMAND,
"command_threshold": 0.05, "asset_cfg": sole_selection},
)
rewards["soft_landing"] = RewardTermCfg(
func=velocity_mdp.soft_landing, weight=-1e-5,
params={"sensor_name": _SUPPORT_SENSOR, "command_name": _COMMAND,
"command_threshold": 0.05},
)
rewards["angular_momentum"] = RewardTermCfg(
func=velocity_mdp.angular_momentum_penalty, weight=-0.01,
params={"sensor_name": "robot/mjrl_root_angmom"},
)
return rewards
@@ -431,7 +550,8 @@ def env_cfg(
if robot.family != recipe.family:
raise ValueError(f"{recipe.family} template cannot use a {robot.family} robot spec")
path = asset or robot.model_path
_, support_geoms, homes = _load_model(path, robot)
spec, support_geoms, homes = _load_model(path, robot)
foot_sites = _ordered_foot_sites(spec.compile(), robot) if robot.family == "biped" else ()
commands, controls = _commands(robot, recipe, play)
sensors = [
_contact_sensor(
@@ -439,8 +559,16 @@ def env_cfg(
"body" if robot.foot_bodies else "geom",
robot.foot_bodies or robot.foot_geoms,
air_time=True,
forces=bool(foot_sites),
)
]
if foot_sites:
sensors.append(TerrainHeightSensorCfg(
name="sole_height",
frame=tuple(ObjRef(type="site", name=name, entity="robot") for name in foot_sites),
pattern=RingPatternCfg.single_ring(radius=0.025, num_samples=4),
max_distance=1.0, include_geom_groups=(0,), exclude_parent_body=True,
))
for name, geoms in (
(_PENALIZED_SENSOR, robot.penalized_contact_geoms),
(_TERMINATION_SENSOR, robot.termination_contact_geoms),
@@ -459,7 +587,7 @@ def env_cfg(
actions=_actions(robot),
commands=commands,
events=_events(robot, play, support_geoms),
rewards=_rewards(robot, recipe),
rewards=_rewards(robot, recipe, foot_sites),
terminations={
"time_out": TerminationTermCfg(func=mdp.time_out, time_out=True),
"undesired_contact": TerminationTermCfg(
@@ -476,7 +604,7 @@ def env_cfg(
"command": CurriculumTermCfg(
func=CommandRangeCurriculum,
params={
"fractions": _FRACTIONS, "ceilings": recipe.command_ceiling,
"fractions": recipe.command_fractions, "ceilings": recipe.command_ceiling,
"command_name": _COMMAND, "dwell_steps": 2400,
"min_steps": 200, "min_samples": 16, "gate_ratio": 0.4, "ema_alpha": 0.15,
},
+20
View File
@@ -177,6 +177,26 @@ def test_adapter_writes_valid_bindings_only_for_supported_command_ranges(tmp_pat
"layout": "layout.json",
}
# New metadata defaults to A/D yaw. An explicit pre-WASD contract
# regenerates its original keys and file bytes, including its ramp rate.
import yaml
from controller.controls import controller_contract
from mjrl.controllers.bindings import velocity_controls
assert "key_a" in controls.key_axes["ang_vel_z"].plus
previous = tmp_path / "controls.yaml"
previous.write_text(yaml.safe_dump(velocity_controls(tuple(controls.bindings)), sort_keys=False))
meta["controller"] = controller_contract(load_controls(previous), None)
restored = adapt_policy(source, meta, tmp_path / "previous")
assert restored.controls.read_bytes() == previous.read_bytes()
assert json.loads(restored.layout.read_text())["controller"] == meta["controller"]
assert load_controls(restored.controls).key_axes["ang_vel_z"].plus == ("key_j",)
meta["controller"]["devices"]["keyboard"]["full_after_s"] = 3.75
rejected = tmp_path / "mismatch"
with pytest.raises(ValueError, match="differs from generated controls"):
adapt_policy(source, meta, rejected)
assert not rejected.exists()
@pytest.mark.parametrize("observes_commands", [False, True])
def test_adapted_fixed_jit_runs_verified_native_application(tmp_path, observes_commands):
+80
View File
@@ -0,0 +1,80 @@
"""Calibrated actuator and sensor semantics survive metadata review/export."""
import copy
import json
import mujoco
import pytest
from mjrl.adapter import build_layout
from mjrl.onboarding.upstream import extract_policy_metadata
def metadata():
return {
"schema": "mjrl-policy-adapter/1",
"wire_joint_order": ["joint"], "obs_joint_order": ["joint"],
"action_joint_order": ["joint"], "default_joint_pos": {"joint": 0},
"joint_limits": {"joint": [-1, 1]}, "action_scale": 1,
"control": {"kp": 1, "kd": 0, "effort_limit": 0.64, "control_hz": 50},
"observation": {
"terms": [{"name": "base_ang_vel"}, {"name": "joint_pos"}],
"frames": {"base_ang_vel": {"kind": "site", "name": "imu"}},
},
"motor_model": {
"kind": "bam", "motor_name": "xl330", "model": "m6", "kp": 100,
"vin": 7.0, "max_current": 1.5, "vin_drop_resistance": 0.1, "vin_min": 6,
},
}
def test_calibrated_metadata_roundtrip(tmp_path):
doc = metadata()
source = tmp_path / "reviewed.json"
source.write_text(json.dumps(doc))
report = extract_policy_metadata([source])
assert report["ready"], report
assert report["metadata"] == doc
layout = build_layout(report["metadata"])
assert layout["_schema"] == "mjrl-native-layout/1"
assert layout["motor_model"] == doc["motor_model"]
assert layout["observation"]["frames"] == doc["observation"]["frames"]
assert layout["control"]["kp"] == 1 # BAM firmware gain stays separate.
assert layout["motor_model"]["kp"] == 100
@pytest.mark.parametrize("frames", [
{"actions": {"kind": "site", "name": "imu"}},
{"projected_gravity": {"kind": "site", "name": "imu"}},
{"base_ang_vel": {"kind": "sensor", "name": "imu"}},
{"base_ang_vel": {"kind": "site", "name": ""}},
{"base_ang_vel": {"kind": "site", "name": "imu", "ignored": 1}},
])
def test_unknown_or_unobserved_frames_fail_closed(frames):
doc = metadata()
doc["observation"]["frames"] = frames
with pytest.raises(ValueError, match="[Ff]rame"):
build_layout(doc)
def test_frame_must_exist_in_exact_model():
model = mujoco.MjModel.from_xml_string('''<mujoco><compiler angle="radian"/>
<worldbody><body><joint name="joint" range="-1 1"/>
<geom size=".1"/><site name="actual_imu"/></body></worldbody>
<actuator><motor joint="joint"/></actuator></mujoco>''')
doc = metadata()
with pytest.raises(ValueError, match="no observation frame"):
build_layout(doc, model=model)
doc["observation"]["frames"]["base_ang_vel"]["name"] = "actual_imu"
assert build_layout(doc, model=model)["observation"]["frames"]
def test_motor_metadata_rejects_unknown_keys_and_velocity_targets():
doc = metadata()
invalid = copy.deepcopy(doc)
invalid["motor_model"]["typo"] = 1
with pytest.raises(ValueError, match="BAM fields"):
build_layout(invalid)
doc["action"] = {"targets": {"joint": {"kind": "velocity", "offset": 0}}}
doc["control"]["kp"], doc["control"]["kd"] = 0, 1
with pytest.raises(ValueError, match="requires position targets"):
build_layout(doc)
+122
View File
@@ -0,0 +1,122 @@
"""Measure command populations and exercise inherited partial-reset lifecycle."""
from types import SimpleNamespace
import pytest
import torch
from mjrl.tasks.commands import AxisBalancedVelocityCommand, AxisBalancedVelocityCommandCfg
def _config(**kwargs):
return AxisBalancedVelocityCommandCfg(
entity_name="robot", resampling_time_range=(3., 7.),
ranges=AxisBalancedVelocityCommandCfg.Ranges((-.7, .7), (-.35, .35), (-.8, .8)),
**{"rel_standing_envs": .1, **kwargs},
)
def _term(count=30000, **kwargs):
zeros = torch.zeros(count, 3)
robot = SimpleNamespace(data=SimpleNamespace(root_link_lin_vel_b=zeros, root_link_ang_vel_b=zeros))
env = SimpleNamespace(num_envs=count, device="cpu", step_dt=.02, scene={"robot": robot})
return _config(**kwargs).build(env)
def test_population_has_balanced_isolated_axes_both_signs_standing_and_mixed_commands():
torch.manual_seed(1027)
term = _term()
assert isinstance(term, AxisBalancedVelocityCommand)
term.reset(torch.arange(term.num_envs))
term.compute(0.)
values = term.command
standing = term.is_standing_env
moving = ~standing
assert standing.float().mean().item() == pytest.approx(.1, abs=.012)
assert torch.count_nonzero(values[standing]) == 0
active_axes = (values != 0).sum(dim=1)
isolated = moving & (active_axes == 1)
assert isolated.sum().item() / moving.sum().item() == pytest.approx(.3, abs=.015)
assert ((active_axes[moving] == 1) | (active_axes[moving] == 3)).all()
assert (active_axes == 3).float().mean().item() == pytest.approx(.63, abs=.02)
for axis, maximum in enumerate((.7, .35, .8)):
assert (values[:, axis].abs() <= maximum).all()
chosen = isolated & (values[:, axis] != 0)
assert chosen.sum().item() / isolated.sum().item() == pytest.approx(1/3, abs=.025)
assert (values[chosen, axis] > 0).float().mean().item() == pytest.approx(.5, abs=.04)
assert values[chosen, axis].min() < -.9 * maximum
assert values[chosen, axis].max() > .9 * maximum
original = values.clone()
term.compute(.01)
torch.testing.assert_close(values, original, atol=0, rtol=0)
def test_isolation_keeps_original_sampled_axis_and_partial_reset_keeps_other_envs():
def sampled(fraction):
torch.manual_seed(29)
term = _term(256, isolated_axis_fraction=fraction, rel_standing_envs=0.)
term.reset(torch.arange(256))
term.compute(0.)
return term
mixed, isolated = sampled(0.), sampled(1.)
mask = isolated.command != 0
assert (mask.sum(dim=1) == 1).all()
assert (mixed.command != 0).all() # The control actually includes all axes.
torch.testing.assert_close(isolated.command[mask], mixed.command[mask], atol=0, rtol=0)
before = {name: getattr(isolated, name).clone() for name in
("vel_command_b", "vel_command_w", "time_left", "command_counter", "is_standing_env")}
ids = torch.tensor([1, 7, 19, 97])
untouched = torch.ones(256, dtype=torch.bool)
untouched[ids] = False
isolated.reset(ids)
isolated.compute(0., env_ids=ids)
for name, old in before.items():
torch.testing.assert_close(getattr(isolated, name)[untouched], old[untouched], atol=0, rtol=0)
assert not torch.equal(isolated.command[ids], before["vel_command_b"][ids])
assert (isolated.command_counter[ids] == 1).all()
assert ((isolated.time_left[ids] >= 3) & (isolated.time_left[ids] <= 7)).all()
@pytest.mark.parametrize("field", ["isolated_axis_fraction", "rel_standing_envs", "init_velocity_prob"])
@pytest.mark.parametrize("value", [-.1, 1.1, float("nan"), float("inf"), True, "0.3"])
def test_invalid_probabilities_fail(field, value):
with pytest.raises(ValueError, match=field):
_config(**{field: value})
@pytest.mark.parametrize("kwargs", [
{"heading_command": True}, {"rel_world_envs": .1}, {"rel_forward_envs": .1},
{"rel_world_envs": float("nan")},
])
def test_modes_that_overwrite_axes_are_rejected(kwargs):
with pytest.raises(ValueError):
_config(**kwargs)
@pytest.mark.parametrize("bounds", [(.1, .5), (-.5, -.1), (.5, -.5), (float("nan"), .5)])
def test_ranges_must_allow_zero_masking(bounds):
cfg = _config()
cfg.ranges.lin_vel_x = bounds
with pytest.raises(ValueError, match="lin_vel_x"):
cfg.build(None) # Validation precedes environment access.
def test_heading_range_and_mutated_mode_are_rejected():
cfg = _config()
cfg.ranges.heading = (-1., 1.)
with pytest.raises(ValueError, match="without heading"):
cfg.build(None)
cfg = _config()
cfg.rel_world_envs = .2
with pytest.raises(ValueError, match="body-frame"):
cfg.build(None)
def test_all_standing_stays_zero_with_isolation_enabled():
term = _term(16, rel_standing_envs=1., isolated_axis_fraction=1.)
term.reset(torch.arange(16))
term.compute(0.)
assert term.is_standing_env.all()
assert torch.count_nonzero(term.command) == 0
assert torch.count_nonzero(term.vel_command_w) == 0
+471
View File
@@ -0,0 +1,471 @@
"""Behavioral checks for biped support credit and episode-local swing peaks."""
from types import SimpleNamespace as NS
import pytest
import torch
from mjlab.sensor.terrain_height_sensor import TerrainHeightSensor
from mjlab.tasks.velocity.mdp.rewards import feet_swing_height
from mjrl.tasks.biped import (
ActiveActionRate,
CompletedSwingQuality,
ResettableSwingHeight,
bounded_single_support,
command_relative_angular_tracking,
command_relative_linear_tracking,
)
def test_action_smoothing_follows_runtime_scale_order_and_ignores_held_channels():
action = torch.tensor([[2., 999., 3.], [4., -999., 1.]])
previous = torch.tensor([[1., -999., 1.], [2., 999., -1.]])
terms = {'position': NS(scale=torch.tensor([[.2, 0.], [.2, 0.]]),
raw_action=action[:, :2]),
'velocity': NS(scale=.5, raw_action=action[:, 2:])}
manager = NS(active_terms=list(terms), get_term=terms.__getitem__,
action=action, prev_action=previous)
env = NS(action_manager=manager, device='cpu')
reward = ActiveActionRate(NS(), env)
torch.testing.assert_close(reward(env), torch.tensor([5., 8.]))
action[:, 0] += 2 # A real change on an active channel increases its cost.
torch.testing.assert_close(reward(env), torch.tensor([13., 20.]))
# Runtime history and the 3D action contract are unchanged by the reward.
assert previous[:, 1].tolist() == [-999., 999.]
assert action.shape == (2, 3)
@pytest.mark.parametrize("slots", [False, True])
def test_single_support_rejects_stance_flight_idle_and_unbounded_swing(slots):
found = torch.tensor([
[1, 1], [0, 0], [1, 0], [0, 1], [1, 0], [1, 0], [1, 0], [1, 0],
])
air = torch.tensor([
[0., 0.], [.2, .2], [0., .2], [.2, 0.], [0., .6], [0., .2],
[0., .05], [0., .4],
])
command = torch.tensor([[.2, 0., 0.]] * len(found))
command[3] = torch.tensor([0., 0., -.2]) # Turning also commands stepping.
command[5] = 0.
if slots:
# Two contact points on one foot must still count as one support.
found = torch.stack((found, found * 2), dim=-1)
env = NS(scene={"feet": NS(data=NS(found=found, current_air_time=air))},
command_manager=NS(get_command=lambda _: command))
assert bounded_single_support(env, "feet", "twist").tolist() == [
0., 0., 1., 1., 0., 0., 0., 0.,
]
command[:] = torch.tensor([.05, 0., 0.])
assert not bounded_single_support(env, "feet", "twist").any()
def test_single_support_rejects_mismatched_sensor_axes():
sensor = NS(data=NS(found=torch.ones(2, 3), current_air_time=torch.zeros(2, 2)))
with pytest.raises(ValueError, match="share"):
bounded_single_support(NS(scene={"feet": sensor}), "feet", "twist")
class _HeightSensor(TerrainHeightSensor):
"""Supply controlled terrain samples while exercising the real reward."""
def __init__(self, heights):
self.heights = heights
@property
def num_frames(self):
return self.heights.shape[1]
@property
def data(self):
return NS(heights=self.heights)
def _swing_env():
height = _HeightSensor(torch.tensor([[.12, .03], [.09, .06], [.06, .12]]))
contact = NS(data=NS(found=torch.zeros(3, 2)),
landed=torch.zeros(3, 2, dtype=torch.bool))
contact.compute_first_contact = lambda dt: contact.landed
env = NS(scene={"height": height, "feet": contact}, num_envs=3, device="cpu",
step_dt=.02, extras={"log": {}},
command_manager=NS(get_command=lambda _: torch.tensor([[.2, 0., 0.]] * 3)))
params = dict(sensor_name="feet", height_sensor_name="height", target_height=.06,
command_name="twist", command_threshold=.05)
return env, NS(params=params), params
def test_reset_discards_only_terminated_episode_peaks_and_changes_next_landing():
env, cfg, params = _swing_env()
reward = ResettableSwingHeight(cfg, env)
reference = feet_swing_height(cfg, env)
assert not reward(env, **params).any() # Flight accumulates, never pays a landing cost.
reference(env, **params)
before = reward.peak_heights.clone()
assert torch.all(before > 0)
reward.reset(torch.tensor([0, 2]))
torch.testing.assert_close(reward.peak_heights[1], before[1])
assert not reward.peak_heights[[0, 2]].any()
# The next episode swings to exactly the desired height. Unreset episodes
# keep their previous maximum; the reference control retains stale peaks.
env.scene["height"].heights[:] = .06
reward(env, **params)
reference(env, **params)
env.scene["feet"].data.found[:] = 1
env.scene["feet"].landed[:] = True
actual = reward(env, **params)
stale = reference(env, **params)
torch.testing.assert_close(actual, torch.tensor([0., .25, 0.]))
torch.testing.assert_close(stale, torch.tensor([1., .25, 1.]))
assert not reward.peak_heights.any() # Actual landings clear their feet.
@pytest.mark.parametrize("env_ids", [None, slice(None)])
@pytest.mark.parametrize("step_dt", [.01, .02])
def test_swing_height_full_reset_and_reference_rate_semantics(env_ids, step_dt):
env, cfg, params = _swing_env()
env.step_dt = step_dt
reward = ResettableSwingHeight(cfg, env)
reference = feet_swing_height(cfg, env)
reward(env, **params)
reference(env, **params)
env.scene["feet"].data.found[:] = 1
env.scene["feet"].landed[:] = True
actual = reward(env, **params)
torch.testing.assert_close(actual, reference(env, **params))
torch.testing.assert_close(actual, torch.tensor([1.25, .25, 1.]))
# The unscaled reference event cost is retained (no division by step_dt).
env.scene["feet"].data.found[:] = 0
env.scene["feet"].landed[:] = False
reward(env, **params)
assert reward.peak_heights.any()
reward.reset(env_ids)
assert not reward.peak_heights.any()
def _quality_env():
env, cfg, params = _swing_env()
params["target_swing_s"] = .18
env.scene["feet"].data.last_air_time = torch.full((3, 2), .18)
return env, CompletedSwingQuality(cfg, env), params
@pytest.mark.parametrize("step_dt", [.01, .02])
@pytest.mark.parametrize("slots", [False, True])
def test_completed_swing_cost_distinguishes_desired_short_and_outlier_events(step_dt, slots):
env, reward, params = _quality_env()
env.step_dt = step_dt
sensor = env.scene["feet"]
if slots:
sensor.data.found = sensor.data.found.unsqueeze(-1).repeat(1, 1, 2)
sensor.data.found[:] = 1
assert not reward(env, **params).any() # Initial stance arms every foot.
sensor.data.found[:, 0] = 0
env.scene["height"].heights[:, 0] = torch.tensor([.06, .012, .6])
assert not reward(env, **params).any()
sensor.data.last_air_time[:, 0] = torch.tensor([.18, .06, 1.8])
sensor.data.found[:] = 1
integrated = reward(env, **params) * step_dt
torch.testing.assert_close(integrated, torch.tensor([0., .8 ** 2 + (2 / 3) ** 2, 8.]))
assert not reward.peak_heights.any()
assert not reward.in_swing.any()
assert not reward(env, **params).any() # The event is never charged twice.
def test_initial_truncated_swing_and_unobserved_contact_chatter_are_ignored():
env, reward, params = _quality_env()
env.scene["height"].heights[:] = .6
assert not reward(env, **params).any() # Starts in flight; no observed takeoff.
assert not reward.peak_heights.any()
env.scene["feet"].data.found[:] = 1
env.scene["feet"].data.last_air_time[:] = .01
assert not reward(env, **params).any()
env.scene["feet"].landed[:] = True # Timer chatter without observed air.
assert not reward(env, **params).any()
assert reward.armed.all()
env.scene["feet"].data.found[:, 0] = 0
reward(env, **params)
env.scene["feet"].data.found[:, 0] = 1
assert (reward(env, **params) > 0).all() # A genuinely observed swing is detected.
@pytest.mark.parametrize('turn', [False, True])
def test_swing_quality_strengthens_with_command_progress_without_positive_bonus(turn):
env, reward, params = _quality_env()
params['minimum_motion_fraction'] = 1 / 6
linear, angular = torch.zeros(3, 3), torch.zeros(3, 3)
command = torch.zeros(3, 3)
command[:, 2 if turn else 0] = .2
(angular if turn else linear)[:, 2 if turn else 0] = torch.tensor([0., .1, .2])
env.scene['robot'] = NS(data=NS(root_link_lin_vel_b=linear, root_link_ang_vel_b=angular))
env.command_manager.get_command = lambda _: command
env.scene['feet'].data.found[:] = 1
assert not reward(env, **params).any()
env.scene['feet'].data.found[:, 0] = 0
env.scene['height'].heights[:, 0] = .012
assert not reward(env, **params).any()
env.scene['feet'].data.last_air_time[:, 0] = .06
env.scene['feet'].data.found[:] = 1
cost = reward(env, **params) * env.step_dt
full = .8 ** 2 + (2 / 3) ** 2
torch.testing.assert_close(cost, full * torch.tensor([1/6, 7/12, 1.]))
assert not reward(env, **params).any() # No repeated payment while grounded.
def test_completed_swing_idle_gate_does_not_leave_stale_event_state():
env, reward, params = _quality_env()
env.scene["feet"].data.found[:] = 1
reward(env, **params)
env.scene["feet"].data.found[:, 0] = 0
reward(env, **params)
env.scene["feet"].data.found[:] = 1
env.command_manager.get_command = lambda _: torch.zeros(3, 3)
assert not reward(env, **params).any()
assert not reward.in_swing.any()
env.command_manager.get_command = lambda _: torch.tensor([[0., 0., -.2]] * 3)
assert not reward(env, **params).any()
def test_completed_swing_reset_isolates_one_environment():
env, reward, params = _quality_env()
env.scene["feet"].data.found[:] = 1
reward(env, **params)
env.scene["height"].heights[:] = .012
env.scene["feet"].data.found[:, 0] = 0
reward(env, **params)
assert reward.in_swing[:, 0].all() and (reward.peak_heights[:, 0] > 0).all()
reward.reset(torch.tensor([1]))
assert not reward.armed[1].any() and not reward.in_swing[1].any()
assert not reward.peak_heights[1].any()
assert reward.in_swing[[0, 2], 0].all()
env.scene["feet"].data.found[:] = 1
torch.testing.assert_close(reward(env, **params) * env.step_dt, torch.tensor([.64, 0., .64]))
reward.reset()
assert not reward.armed.any() and not reward.in_swing.any() and not reward.peak_heights.any()
def test_low_command_tracking_has_material_gain_over_stationary_control(neutral_robot):
data = NS(root_link_lin_vel_b=torch.tensor([[0., 0., 0.], [0., .1, 0.], [0., .1, .1]]))
env = NS(scene={"robot": NS(data=data)},
command_manager=NS(get_command=lambda _: torch.tensor([[0., .1, 0.]] * 3)))
result = command_relative_linear_tracking(env, "twist")
expected = torch.exp(torch.tensor(-.1 ** 2 / .15 ** 2))
torch.testing.assert_close(result, torch.tensor([expected, 1., expected]))
assert 3 * (result[1] - result[0]) > .47
data.root_link_ang_vel_b = torch.tensor([[0., 0., 0.], [0., 0., .25], [0., 0., .25]])
env.command_manager.get_command = lambda _: torch.tensor([[0., 0., .25]] * 3)
result = command_relative_angular_tracking(env, "twist")
assert result[0].item() == pytest.approx(torch.exp(torch.tensor(-.25 ** 2 / .15 ** 2)).item())
assert result[1] == result[2] == 1.
from tasks.templates.Biped_Template.env_cfg import env_cfg
weight = env_cfg(neutral_robot).rewards["track_angular_velocity"].weight
# Reserve a material return margin for initiating a turn. The former
# weight fails this control, matching the measured low-yaw standing trap.
assert weight * (result[1] - result[0]) > 1.5
assert 1.5 * (result[1] - result[0]) < 1.5
def test_undertracking_turn_retains_incentive_without_tightening_idle_noise_floor():
command = torch.tensor([[0., 0., 0.], [0., 0., .25]])
actual = torch.tensor([[0., 0., .05], [0., 0., .14]])
env = NS(scene={"robot": NS(data=NS(root_link_ang_vel_b=actual))},
command_manager=NS(get_command=lambda _: command))
result = command_relative_angular_tracking(env, "twist")
assert result[0].item() == pytest.approx(torch.exp(torch.tensor(-(.05 / .15) ** 2)).item())
assert 3 * (1 - result[1]) > 1.2
additive_floor = torch.exp(torch.tensor(-((.25 - .14) / .275) ** 2))
assert 3 * (1 - additive_floor) < .5 # Former low-turn undertracking trap.
def test_roll_pitch_penalty_is_independent_of_yaw_command_and_tolerance_is_capped():
command = torch.tensor([[0., 0., 0.], [0., 0., .25], [0., 0., 2.]])
actual = torch.tensor([[.2, .3, 0.], [.2, .3, .25], [.2, .3, 2.]])
data = NS(root_link_ang_vel_b=actual, root_link_lin_vel_b=torch.zeros(3, 3))
env = NS(scene={"robot": NS(data=data)}, command_manager=NS(get_command=lambda _: command))
torch.testing.assert_close(command_relative_angular_tracking(env, "twist"),
torch.full((3,), torch.exp(torch.tensor(-.13 / .5))))
actual[2, 2] = 1.
assert command_relative_angular_tracking(env, "twist")[2].item() == pytest.approx(
torch.exp(torch.tensor(-1. / .5 - .13 / .5)).item(),
)
command[:] = torch.tensor([2., 0., 0.])
data.root_link_lin_vel_b[:] = torch.tensor([1.5, 0., 0.])
torch.testing.assert_close(command_relative_linear_tracking(env, "twist"),
torch.full((3,), torch.exp(torch.tensor(-1.))))
def test_biped_pilot_weights_leave_other_families_unchanged(neutral_robot):
from dataclasses import asdict
from importlib import import_module
from tasks.templates._locomotion import _rewards
from tasks.templates.Biped_Template.env_cfg import _RECIPE
rewards = _rewards(neutral_robot, _RECIPE, ('left_sole', 'right_sole'))
assert rewards['swing_quality'].func is CompletedSwingQuality
assert rewards['swing_quality'].weight == -.03
assert rewards['action_rate'].func is ActiveActionRate
assert rewards['action_rate'].weight == -.03
assert rewards['leg_torque'].weight == -1e-6
assert rewards['single_support'].weight == .5
for family, template in [('quadruped', 'Quadruped_Template'),
('multipod', 'Multipod_Template'),
('wheeled_biped', 'Wheeled_Biped_Template')]:
recipe = import_module(f'tasks.templates.{template}.env_cfg')._RECIPE
other_robot = NS(**{**asdict(neutral_robot), "family": family})
other_robot.position_joints = neutral_robot.position_joints
other = _rewards(other_robot, recipe)
assert other['action_rate'].weight == -.02
assert other['leg_torque'].weight == -1e-5
assert 'single_support' not in other
assert 'swing_quality' not in other
assert other['track_linear_velocity'].weight == 2.
assert other['joint_home'].weight == -.5
@pytest.mark.parametrize('step_dt', [.01, .02])
def test_small_completed_steps_do_not_consume_initial_forward_tracking_gain(
neutral_robot, step_dt,
):
"""Four imperfect real events must not erase the first tracking improvement.
This is a local reward-budget check, not a claim that a complete gait is
profitable: posture, action changes, effort, and impacts still carry their
configured costs and must be measured in native replay.
"""
from dataclasses import replace
from tasks.templates._locomotion import _rewards
from tasks.templates.Biped_Template.env_cfg import _RECIPE
# Use a synthetic tall biped to exercise height-dependent terms.
robot = replace(neutral_robot, base_height=1.0203419882368219)
rewards = _rewards(robot, _RECIPE, ('left_sole', 'right_sole'))
params = rewards['swing_quality'].params
found = torch.ones(1, 2)
air = torch.zeros(1, 2)
last_air = torch.zeros(1, 2)
height = NS(num_frames=2, data=NS(heights=torch.zeros(1, 2)))
sensor = NS(data=NS(found=found, current_air_time=air, last_air_time=last_air))
command = torch.tensor([[.7, 0., 0.]])
data = NS(root_link_lin_vel_b=torch.zeros(1, 3), root_link_ang_vel_b=torch.zeros(1, 3))
env = NS(scene={params['sensor_name']: sensor,
params['height_sensor_name']: height, 'robot': NS(data=data)},
command_manager=NS(get_command=lambda _: command),
num_envs=1, device='cpu', step_dt=step_dt)
quality = CompletedSwingQuality(rewards['swing_quality'], env)
assert quality(env, **params).item() == 0. # Observe stance before takeoff.
tracking = rewards['track_linear_velocity']
standing = tracking.func(env, **tracking.params).item()
data.root_link_lin_vel_b[:, 0] = .02
tracking_gain = tracking.weight * (tracking.func(env, **tracking.params).item() - standing)
assert tracking_gain == pytest.approx(.038963, abs=2e-6)
integrated_quality = 0.
integrated_support = 0.
nonzero_events = 0
starts = [round(t / step_dt) for t in [0., .24, .5, .74]]
swing_samples = round(.06 / step_dt)
for step in range(round(1. / step_dt)):
found[:] = 1
air[:] = 0
for event, start in enumerate(starts):
foot = event % 2
if start <= step < start + swing_samples:
found[:, foot] = 0
air[:, foot] = (step - start + 1) * step_dt
height.data.heights[:, foot] = .012
elif step == start + swing_samples:
last_air[:, foot] = .06
height.data.heights[:, foot] = 0.
cost = quality(env, **params).item() * step_dt
nonzero_events += int(cost > 0)
integrated_quality += cost
support = rewards['single_support']
integrated_support += support.func(env, **support.params).item() * step_dt
assert nonzero_events == 4 # Reject vacuous success from missing takeoffs.
expected_error = (.012 / params['target_height'] - 1) ** 2 \
+ (.06 / params['target_swing_s'] - 1) ** 2
fraction = params['minimum_motion_fraction'] + (1 - params['minimum_motion_fraction']) * .02 / .7
assert integrated_quality == pytest.approx(4 * expected_error * fraction, rel=1e-6)
new_cost = -rewards['swing_quality'].weight * integrated_quality
assert new_cost < tracking_gain
assert tracking_gain + rewards['single_support'].weight * integrated_support - new_cost > 0
# The previous recipe must fail the same budget on these same events.
assert tracking_gain + .3 * integrated_support - .05 * 4 * expected_error < 0
def test_translation_coupling_removes_standing_heading_credit_but_keeps_optimum(neutral_robot):
from mjrl.tasks.biped import translation_aware_angular_tracking
from tasks.templates.Biped_Template.env_cfg import env_cfg
command = torch.tensor([[.3, 0., 0.], [.3, 0., .25]])
data = NS(root_link_lin_vel_b=torch.tensor([[0., 0., 0.], [.3, 0., 0.]]),
root_link_ang_vel_b=torch.tensor([[0., 0., 0.], [0., 0., .25]]))
env = NS(scene={'robot': NS(data=data)}, command_manager=NS(get_command=lambda _: command))
angular = command_relative_angular_tracking(env, 'twist')
coupled = translation_aware_angular_tracking(env, 'twist')
assert 3 * angular[0].item() == pytest.approx(3.) # Previous standing windfall.
assert 3 * coupled[0].item() == pytest.approx(1.16862662, abs=1e-6)
assert coupled[1].item() == pytest.approx(1.) # Perfect full twist still earns 3/s.
term = env_cfg(neutral_robot).rewards['track_angular_velocity']
assert term.func is translation_aware_angular_tracking
def test_walking_tolerance_allows_pelvis_oscillation_but_keeps_pure_turn_and_idle(neutral_robot):
from tasks.templates.Biped_Template.env_cfg import env_cfg
cfg = env_cfg(neutral_robot)
command = torch.tensor([[.3, 0., 0.], [.3, 0., 0.], [0., 0., .4], [0., 0., 0.]])
data = NS(root_link_lin_vel_b=torch.tensor([[.3, 0., 0.], [0., 0., 0.],
[0., 0., 0.], [0., 0., 0.]]),
root_link_ang_vel_b=torch.tensor([[0., 0., .12], [0., 0., 0.],
[0., 0., 0.], [0., 0., .12]]))
env = NS(scene={'robot': NS(data=data)}, command_manager=NS(get_command=lambda _: command))
term = cfg.rewards['track_angular_velocity']
value = term.func(env, **term.params)
assert value[0].item() == pytest.approx(torch.exp(torch.tensor(-.12**2/.5**2)).item())
assert value[1].item() < .6 # Standing still does not receive full heading credit.
original = command_relative_angular_tracking(env, 'twist')
torch.testing.assert_close(value[2:], original[2:])
assert value[2].item() < .02 # Ignoring a pure .4 rad/s turn still loses nearly all credit.
data.root_link_lin_vel_b[2:, 0] = .1
linear = cfg.rewards['track_linear_velocity']
torch.testing.assert_close(linear.func(env, **linear.params)[2:],
command_relative_linear_tracking(env, 'twist')[2:])
assert term.weight == 3.
def test_translation_coupling_keeps_pure_turn_idle_and_threshold_behavior():
from mjrl.tasks.biped import translation_aware_angular_tracking
command = torch.tensor([[0., 0., .25], [0., 0., 0.], [.05, 0., .25]])
data = NS(root_link_lin_vel_b=torch.tensor([[.1, .1, .1]] * 3),
root_link_ang_vel_b=torch.tensor([[.02, .03, .14], [.02, .03, .05],
[.02, .03, .14]]))
env = NS(scene={'robot': NS(data=data)}, command_manager=NS(get_command=lambda _: command))
torch.testing.assert_close(translation_aware_angular_tracking(env, 'twist'),
command_relative_angular_tracking(env, 'twist'))
# Crossing the explicit translation threshold engages the joint objective.
command[2, 0] = .051
assert translation_aware_angular_tracking(env, 'twist')[2] \
< command_relative_angular_tracking(env, 'twist')[2]
def test_translation_coupling_rejects_wrong_yaw_lateral_backwards_and_vertical_motion():
from mjrl.tasks.biped import translation_aware_angular_tracking
command = torch.tensor([[.3, 0., .25]] * 6)
data = NS(root_link_lin_vel_b=torch.tensor([[.3, 0., 0.], [.3, 0., 0.],
[0., .3, 0.], [-.3, 0., 0.],
[.3, 0., .1], [0., 0., 0.]]),
root_link_ang_vel_b=torch.tensor([[0., 0., .25], [0., 0., 0.],
[0., 0., .25], [0., 0., .25],
[0., 0., .25], [0., 0., .25]]))
env = NS(scene={'robot': NS(data=data)}, command_manager=NS(get_command=lambda _: command))
result = translation_aware_angular_tracking(env, 'twist')
assert result[0].item() == pytest.approx(1.)
assert ((result[1:] > 0) & (result[1:] < 1)).all()
assert result[2] < result[5] # Matching speed in the wrong direction is worse than stillness.
assert result[3] < result[5]
torch.testing.assert_close(result, command_relative_angular_tracking(env, 'twist')
* (.2 + .8 * command_relative_linear_tracking(env, 'twist')))
+8 -1
View File
@@ -35,11 +35,18 @@ def test_training_range_matches_replay_at_each_checkpoint_level(neutral_robot):
def test_the_operator_reaches_each_trained_limit(neutral_robot):
train = env_cfg(neutral_robot)
replay = env_cfg(neutral_robot, play=True)
checkpoint = {"infos": {"curriculum": {"command": {"level": 1}}}}
params = train.curriculum["command"].params
level = len(params["fractions"]) - 1
checkpoint = {"infos": {"curriculum": {"command": {"level": level}}}}
report = configure_velocity_replay(replay, train, checkpoint)
command = replay.commands["twist"]
controls = command.controls
edges = spans(controls.command("twist"), command)
for axis, ceiling in zip(("lin_vel_x", "lin_vel_y", "ang_vel_z"), params["ceilings"], strict=True):
low, high = report["ranges"][axis]
cap = ceiling * params["fractions"][level]
assert (low, high) == pytest.approx((-cap, cap))
assert -ceiling <= low < high <= ceiling
for axis, (binding,) in controls.bindings.items():
values = dict.fromkeys(("Lx", "Ly", "Rx", "Ry", "LT", "RT"), 0.0)
values[binding.source] = binding.sign
+113
View File
@@ -0,0 +1,113 @@
"""Named heterogeneous servos retain physical limits and calibrated operator rest."""
import json
import numpy as np
import pytest
mujoco = pytest.importorskip("mujoco")
from mjrl.controllers import load_controller, setup_controller
XML = """<mujoco>
<compiler angle="radian"/>
<option timestep=".002" gravity="0 0 0" integrator="implicitfast"/>
<worldbody><body name="leg_body">
<joint name="leg" type="slide" axis="1 0 0" range="-.2 .2" actuatorfrcrange="-5 4"/>
<geom size=".02" mass="1" contype="0" conaffinity="0"/>
<body name="arm_body"><joint name="arm" type="slide" axis="0 1 0" range="-.2 .2" actuatorfrcrange="-3 5"/>
<geom size=".02" mass="1" contype="0" conaffinity="0"/>
</body></body></worldbody>
<actuator>
<motor name="arm_motor" joint="arm" gear="-2" forcerange="-4 3" ctrlrange="-1 2"/>
<position name="leg_servo" joint="leg" kp="10" ctrlrange="-.2 .2" forcerange="-8 12"/>
</actuator></mujoco>"""
GAINS = {"kp": {"arm": 30, "leg": 70}, "kd": {"arm": 3, "leg": 2},
"effort_limit": {"arm": 100, "leg": 6}}
def setup(tmp_path, **extra):
source = tmp_path / "source.xml"
source.write_text(XML)
config = {"kind": "joint_sliders", "joints": ["leg", "arm"], **GAINS, **extra}
result = setup_controller(source, config, tmp_path / "controller")
model = mujoco.MjModel.from_xml_path(str(result.model))
controller = load_controller(model, result.config, result.controls)
return result, model, controller
def test_named_servos_apply_gains_by_joint_and_do_not_enlarge_authored_effort(tmp_path):
result, model, controller = setup(tmp_path)
config = json.loads(result.config.read_text())
assert config["kp"] == GAINS["kp"]
assert config["kd"] == GAINS["kd"]
assert config["effort_limit"] == GAINS["effort_limit"]
# Actuator order arm,leg differs from controller order leg,arm.
np.testing.assert_array_equal(model.actuator_gainprm[:, 0], [30, 70])
np.testing.assert_array_equal(model.actuator_biasprm[:, 2], [-3, -2])
np.testing.assert_array_equal(model.actuator_gear[:, 0], [1, 1])
# Arm: motor control [-1,2] * gear -2, intersect joint [-3,5].
# Leg: requested +-6, source force [-8,12], intersect joint [-5,4].
np.testing.assert_array_equal(model.actuator_forcerange, [[-3, 2], [-5, 4]])
data = mujoco.MjData(model)
controller.reset(data)
controller.step(data, {"arm": .2, "leg": .2})
mujoco.mj_forward(model, data)
np.testing.assert_array_equal(data.actuator_force, [2, 4])
controller.step(data, {"arm": -.2, "leg": -.2})
mujoco.mj_forward(model, data)
np.testing.assert_array_equal(data.actuator_force, [-3, -5])
def test_cpg_uses_named_pd_gains_and_clips_to_preserved_effort(tmp_path):
_, model, controller = setup(
tmp_path, kind="cpg", frequency_hz=1, amplitude=[.1, .1], phase=[np.pi / 2] * 2,
)
data = mujoco.MjData(model)
controller.reset(data)
data.qpos[:] = [.09, .09]
data.qvel[:] = [.2, .1]
# leg: 70*.01 - 2*.2=.3; arm: 30*.01 - 3*.1=0.
np.testing.assert_allclose(controller.step(data), [0, .3], atol=1e-14)
data.qpos[:] = [-.1, -.1]
np.testing.assert_allclose(controller.step(data), [2, 4], atol=1e-14)
data.qpos[:] = [.2, .2]
np.testing.assert_allclose(controller.step(data), [-2, -4], atol=1e-14)
@pytest.mark.parametrize("release", [{"keys": {"key_escape"}}, {"pad": {"B": True}}])
def test_calibrated_home_releases_bound_arm_and_preserves_unbound_leg(tmp_path, release):
_, model, controller = setup(
tmp_path, home={"arm": -.08, "leg": .1}, operator_axes=["arm"],
command_ranges={"arm": [-.12, .04], "leg": [-.15, .15]},
)
data = mujoco.MjData(model)
data.qpos[:] = [.11, -.07]
controller.reset(data)
# Reset holds actual calibrated pose, rather than teleporting qpos to home.
np.testing.assert_array_equal(data.qpos, [.11, -.07])
np.testing.assert_array_equal(data.ctrl, [-.07, .11])
controller.step(data, {"arm": .03, "leg": .13})
controller.step(data, **release)
np.testing.assert_array_equal(data.ctrl, [-.08, .13])
assert controller.command_spans["arm"][2] == -.08
assert controller.command_spans["leg"][2] == .1
@pytest.mark.parametrize("field,value", [
("kp", {"arm": 30}), ("kp", {"arm": 30, "leg": 70, "extra": 1}),
("kd", {"arm": -1, "leg": 2}), ("kp", {"arm": 0, "leg": 2}),
("effort_limit", {"arm": float("nan"), "leg": 2}),
("effort_limit", {"arm": 0, "leg": 2}), ("kp", [30, 70]),
("home", {"arm": 0}), ("home", {"arm": 0, "leg": .3}),
("home", {"arm": float("inf"), "leg": .1}), ("home", [0, .1]),
])
def test_named_parameters_reject_missing_extra_invalid_or_positional_values(tmp_path, field, value):
with pytest.raises(ValueError):
setup(tmp_path, **{field: value})
assert not (tmp_path / "controller").exists()
def test_home_must_lie_in_declared_command_range(tmp_path):
with pytest.raises(ValueError, match="exceeds limits or excludes the rest"):
setup(tmp_path, home={"arm": -.08, "leg": .1}, command_ranges={"arm": [0, .1]})
+168 -20
View File
@@ -91,32 +91,62 @@ def test_mocap_ik_solves_named_site_and_tracks_without_editing_qpos(tmp_path):
assert setup.controls.is_file()
def test_application_idle_keyboard_preserves_mocap_drag(tmp_path):
def test_application_native_mouse_drag_tracks_and_respects_workspace(tmp_path):
from mjrl.platform.bundle import IK_MOUSE_HELP, _manual
from mjrl.platform.play import RobotApplication
setup, _, _, _ = _setup(tmp_path, _ARM, kind="ik", joints=["x", "y"])
app = RobotApplication(
setup.model.parent,
{
"model": "robot.xml",
"default_mode": "ik",
"modes": {
"ik": {
"control_mode": "ik_mocap",
"contract": "controller.json",
"controls": "controls.yaml",
}
},
},
setup, _, _, _ = _setup(
tmp_path, _ARM, kind="ik", joints=["x", "y"],
command_ranges={"target_x": [-0.02, 0.02], "target_y": [-0.03, 0.03]},
)
app.data.mocap_pos[0] = [0.08, -0.05, 0]
manifest = {
"model": "robot.xml",
"default_mode": "ik",
"modes": {"ik": {
"control_mode": "ik_mocap", "contract": "controller.json", "controls": "controls.yaml",
}},
}
app = RobotApplication(setup.model.parent, manifest)
manual = _manual(setup.model.parent, "arm", manifest["modes"], "ik")
assert manual["modes"][0]["summary"] == IK_MOUSE_HELP
model, data, ik = app.model, app.data, app.controller.ik
# A calibrated starting pose can differ from the model reference position.
data.qpos[:] = [0.03, 0.04]
app.controller.reset(data)
mujoco.mj_forward(model, data)
origin = data.site_xpos[ik.site].copy()
np.testing.assert_allclose(data.mocap_pos[ik.mocap], origin)
camera, opt = mujoco.MjvCamera(), mujoco.MjvOption()
camera.lookat, camera.distance = origin, 0.5
camera.azimuth, camera.elevation = 90, -90
scene = mujoco.MjvScene(model, maxgeom=32)
perturb = mujoco.MjvPerturb()
mujoco.mjv_updateScene(model, data, opt, perturb, camera, mujoco.mjtCatBit.mjCAT_ALL, scene)
# The same picking, right-drag and pose application calls as MuJoCo's
# passive viewer. Aim at the marker rim, clear of the tool geometry.
point = np.zeros(3)
ids = [np.full(1, -1, dtype=np.int32) for _ in range(3)]
body = mujoco.mjv_select(model, data, opt, 1.0, 0.555, 0.5, scene, point, *ids)
assert body == model.body("mjrl_target").id
perturb.select = body
perturb.localpos[:] = data.xmat[body].reshape(3, 3).T @ (point - data.xpos[body])
mujoco.mjv_initPerturb(model, data, scene, perturb)
perturb.active = mujoco.mjtPertBit.mjPERT_TRANSLATE
mujoco.mjv_movePerturb(
model, data, mujoco.mjtMouse.mjMOUSE_MOVE_H, 0.4, 0.15, scene, perturb
)
mujoco.mjv_applyPerturbPose(model, data, perturb, 0)
raw_offset = data.mocap_pos[ik.mocap] - origin
assert abs(raw_offset[0]) > 0.02
expected = origin + np.clip(raw_offset, [-0.02, -0.03, -0.2], [0.02, 0.03, 0.2])
for _ in range(55):
app.step(keys=())
np.testing.assert_allclose(
app.data.site_xpos[app.controller.ik.site], [0.08, -0.05, 0], atol=1e-4
)
np.testing.assert_allclose(data.mocap_pos[ik.mocap], expected)
np.testing.assert_allclose(data.site_xpos[ik.site], expected, atol=1e-4)
app.step(keys={"key_escape"})
np.testing.assert_equal(app.data.mocap_pos[0], [0, 0, 0])
np.testing.assert_allclose(data.mocap_pos[ik.mocap], origin)
def test_sliders_and_trajectory_apply_joint_limits_and_interpolate_by_name(tmp_path):
@@ -317,3 +347,121 @@ def test_omni_geometry_lateral_motion_and_uniform_saturation(tmp_path):
np.testing.assert_allclose(
controller.step(data, {"ang_vel_z": 1}), [1.3, -1.3, -1.3], atol=1e-10
)
def test_slider_rate_limit_persists_partial_targets_and_accepts_viewer_edits(tmp_path):
_, model, data, sliders = _setup(
tmp_path, _ARM, kind="joint_sliders", joints=["x", "y"], target_rate_limits={"x": 0.5}
)
# The model actuators are ordered y,x. An unlisted joint moves immediately.
np.testing.assert_allclose(sliders.step(data, {"x": 1, "y": -.06}), [-.06, 0])
data.time = .1
np.testing.assert_allclose(sliders.step(data, {"y": .1}), [.1, .05])
np.testing.assert_allclose(sliders.step(data), [.1, .05])
data.time = .2
np.testing.assert_allclose(sliders.step(data, keys=()), [.1, .1])
data.time = .5
np.testing.assert_allclose(sliders.step(data), [.1, .2])
data.ctrl[1] = -.1
data.time = .6
np.testing.assert_allclose(sliders.step(data, keys=()), [.1, .15])
data.time = 1.2
np.testing.assert_allclose(sliders.step(data), [.1, -.1])
mujoco.mj_resetData(model, data)
data.qpos[0] = -.02
np.testing.assert_allclose(sliders.step(data), [0, -.02])
data.time = .1
np.testing.assert_allclose(sliders.step(data), [0, -.02])
@pytest.mark.parametrize("release", [{"keys": {"key_escape"}}, {"pad": {"B": True}}])
@pytest.mark.parametrize("hold_release", [True, False])
def test_slider_rate_limited_operator_return_completes_after_tap_or_hold(
tmp_path, release, hold_release
):
_, _, data, sliders = _setup(
tmp_path, _ARM, kind="joint_sliders", joints=["x", "y"], home={"x": -.1, "y": 0},
operator_axes=["x"], target_rate_limits={"x": 0.5},
)
data.time = .5
np.testing.assert_allclose(sliders.step(data, pad={"Ly": -1}), [0, .2])
data.time = .52
np.testing.assert_allclose(sliders.step(data, **release), [0, .19])
data.time = .54
following = release if hold_release else {"keys": ()}
np.testing.assert_allclose(sliders.step(data, **following), [0, .18])
data.time = 1.2
np.testing.assert_allclose(sliders.step(data, **following), [0, -.1])
@pytest.mark.parametrize("limits", [None, 0.5, {"other": 1}, {"x": 0}, {"x": -1},
{"y": float("nan")}, {"y": True}])
def test_slider_rate_limits_validate_names_and_positive_finite_rates(tmp_path, limits):
with pytest.raises(ValueError, match="target_rate_limits"):
_setup(tmp_path, _ARM, kind="joint_sliders", joints=["x", "y"], target_rate_limits=limits)
def _servo_fixture(actuator, joint_range="", transmission="joint"):
return f"""<mujoco><compiler angle="radian"/><worldbody><body>
<joint name="axis" {joint_range}/><geom size=".02"/>
</body></worldbody><actuator><{actuator} {transmission}="axis"/></actuator></mujoco>"""
@pytest.mark.parametrize("actuator,joint_range,expected", [
('position ctrlrange="-3.141592 3.141592"', "", [-3.141592, 3.141592]),
('position gear="-2" ctrlrange="-.5 1.5"', "", [-.75, .25]),
('general gear="2" gainprm="3" biastype="affine" biasprm="0 -3 -1" ctrlrange="-.5 1.5"',
'range="-.5 .5"', [-.25, .5]),
('position timeconst=".02" ctrlrange="-.1 .2"', "", [-.1, .2]),
('position kp="10" inheritrange=".5"', 'range="-1 1"', [-.5, .5]),
])
def test_normalized_servo_preserves_length_target_in_joint_units(
tmp_path, actuator, joint_range, expected
):
_, model, data, controller = _setup(
tmp_path, _servo_fixture(actuator, joint_range), kind="joint_sliders", joints=["axis"]
)
assert model.actuator_ctrllimited[0]
np.testing.assert_array_equal(model.actuator_ctrlrange[0], expected)
for command, bound in zip([-10, 10], expected, strict=True):
np.testing.assert_array_equal(controller.step(data, {"axis": command}), [bound])
# A raw MuJoCo user can bypass the controller. At the target boundary
# the servo must also hold zero force for an out-of-range native input.
data.qpos[0] = bound
data.ctrl[0] = command
mujoco.mj_forward(model, data)
assert data.actuator_force[0] == pytest.approx(0, abs=1e-12)
@pytest.mark.parametrize("actuator", [
'motor ctrlrange="-.1 .1"', 'velocity ctrlrange="-.1 .1"',
'position ctrllimited="false" ctrlrange="-.1 .1"',
])
def test_non_position_inputs_and_disabled_limits_do_not_restrict_joint_targets(tmp_path, actuator):
_, model, data, controller = _setup(
tmp_path, _servo_fixture(actuator), kind="joint_sliders", joints=["axis"]
)
assert not model.actuator_ctrllimited[0]
np.testing.assert_array_equal(controller.step(data, {"axis": .5}), [.5])
@pytest.mark.parametrize("actuator,joint_range,error", [
('position gear="-2" ctrlrange="2 4"', 'range="0 1"', "do not overlap"),
('general biastype="affine" biasprm=".1 -3 -1" gainprm="3" ctrlrange="-1 1"', "",
"Cannot infer position target bounds"),
('intvelocity kp="3" actrange="-2 2" ctrlrange="-1 1"', "",
"Cannot infer position target bounds"),
])
def test_normalization_rejects_incompatible_position_bounds(tmp_path, actuator, joint_range, error):
with pytest.raises(ValueError, match=error):
_setup(tmp_path, _servo_fixture(actuator, joint_range), kind="joint_sliders", joints=["axis"])
assert not (tmp_path / "joint_sliders").exists()
def test_parent_frame_scalar_transmission_reuses_the_source_servo(tmp_path):
xml = _servo_fixture('position gear="-2" ctrlrange="-.2 .8"', transmission="jointinparent")
_, model, data, controller = _setup(tmp_path, xml, kind="joint_sliders", joints=["axis"])
assert model.nu == 1
np.testing.assert_array_equal(model.actuator_ctrlrange[0], [-.4, .1])
np.testing.assert_array_equal(controller.step(data, {"axis": 1}), [.1])
+37 -2
View File
@@ -111,8 +111,43 @@ def _generate_controls(path: Path, *options: str):
return load_controls(path)
def test_controls_writer_defaults_to_omni(tmp_path) -> None:
controls = _generate_controls(tmp_path / "omni.yaml")
def test_default_walking_controls_drive_training_and_native_policy(tmp_path) -> None:
import yaml
from mjrl.controllers.bindings import WALKING_CONTROLS, walking_controls
from mjrl.controllers.input import OperatorInput
from mjrl.tasks.operator import Operator, spans
full = load_controls(WALKING_CONTROLS)
names = [axis.name for axis in full.command("twist").axes]
edges = spans(full.command("twist"), _env_cfg().commands["twist"])
native_path = tmp_path / "adapted.yaml"
native_path.write_text(yaml.safe_dump(walking_controls(names)))
for controls in (full, _generate_controls(tmp_path / "generated.yaml"), load_controls(native_path)):
for keys, target in [
(("key_w",), [.6, 0, 0]), (("key_s",), [-.3, 0, 0]),
(("key_a",), [0, 0, .7]), (("key_d",), [0, 0, -.7]),
(("key_w", "key_a"), [.6, 0, .7]), (("key_w", "key_s"), [0, 0, 0]),
]:
clock = _Clock()
op = Operator(controls, listen=False, clock=clock)
op.attach("twist", edges)
for key in keys:
op.key(key, True)
native = OperatorInput(controls, edges)
native.read({}, keys, 0, 0)
clock.t = controls.full_after_s
assert op.command("twist") == pytest.approx(target)
values = native.read({}, keys, clock.t, clock.t)
assert [values[name] for name in names] == pytest.approx(target)
for key in keys:
op.key(key, False)
assert op.command("twist") == pytest.approx([0, 0, 0])
assert all(value == 0 for value in native.read({}, (), clock.t, 0).values())
@pytest.mark.parametrize("options", [("--profile", "omni"), ("--task", "multipod_example")])
def test_omni_controls_preserve_lateral_keys(tmp_path, options) -> None:
controls = _generate_controls(tmp_path / "omni.yaml", *options)
assert "key_a" in controls.key_axes["lin_vel_y"].plus
assert "key_d" in controls.key_axes["lin_vel_y"].minus
assert controls.key_axes["ang_vel_z"].plus == ("key_j",)
+3
View File
@@ -111,6 +111,9 @@ def built(neutral_robot):
with pytest.MonkeyPatch.context() as mp:
mp.delenv(LEVEL_ENV, raising=False)
cfg = env_cfg(neutral_robot)
# This fixture tests generic multi-rung resume, independently of the
# biped recipe's intentional full-range, single-rung training policy.
cfg.curriculum["command"].params["fractions"] = (.4, .7, 1.)
cfg.scene.num_envs = N_ENVS
env = ManagerBasedRlEnv(cfg, device="cpu")
wrapped = RslRlVecEnvWrapper(env)
+56
View File
@@ -0,0 +1,56 @@
"""A zero residual scale retains position control while removing policy authority."""
from dataclasses import replace
import pytest
import torch
def test_zero_scale_holds_home_without_disabling_the_actuator(neutral_robot):
from mjlab.envs import ManagerBasedRlEnv
from mjlab.sim import get_simulation_cls, set_simulation_cls
from mjrl.backend import native_sim
from mjrl.backend.resolve import resolve
from mjrl.backend.select import use_backend
from tasks.templates.Biped_Template.env_cfg import env_cfg
held = replace(neutral_robot.position_joints[0], action_scale=0.0)
robot = replace(neutral_robot, position_joints=(held, *neutral_robot.position_joints[1:]))
previous, threads = get_simulation_cls(), native_sim._DEFAULT_NTHREAD
env = None
try:
use_backend(resolve(backend='native', device='cpu', num_envs=1))
env = ManagerBasedRlEnv(env_cfg(robot, play=True), device='cpu')
action = env.action_manager.get_term('joint_pos')
action.process_actions(torch.tensor([[100.0, 1.0]]))
assert action._processed_actions[0, 0].item() == pytest.approx(held.home)
moving = robot.position_joints[1]
assert action._processed_actions[0, 1].item() == pytest.approx(moving.home + moving.action_scale)
# A held action is still a powered PD joint, not an omitted/passive DOF.
actuator = env.scene['robot'].actuators[0]
assert actuator.stiffness[0, 0].item() == pytest.approx(held.kp)
assert actuator.force_limit[0, 0].item() == pytest.approx(held.effort_limit)
action.process_actions(torch.tensor([[-100.0, -1.0]]))
assert action._processed_actions[0, 0].item() == pytest.approx(held.home)
assert action._processed_actions[0, 1].item() == pytest.approx(moving.home - moving.action_scale)
finally:
if env is not None:
env.close()
set_simulation_cls(previous)
native_sim._DEFAULT_NTHREAD = threads
def test_negative_and_entirely_held_locomotion_actions_are_rejected(neutral_robot):
with pytest.raises(ValueError, match='action_scale'):
replace(neutral_robot.position_joints[0], action_scale=-.1)
with pytest.raises(ValueError, match='at least one joint'):
replace(neutral_robot, position_joints=tuple(
replace(joint, action_scale=0.0) for joint in neutral_robot.position_joints))
def test_velocity_actuator_still_requires_nonzero_scale():
from pathlib import Path
from tasks.robot_spec import read_robot_spec
robot = read_robot_spec(Path(__file__).resolve().parents[1] / 'tasks/wheeled_biped_example/robot_spec.py')
with pytest.raises(ValueError, match='action_scale>0'):
replace(robot, velocity_joints=tuple(replace(joint, action_scale=0.0) for joint in robot.velocity_joints))
+117
View File
@@ -0,0 +1,117 @@
"""Reset discontinuities and contact chatter must remain visible in diagnostics."""
import numpy as np
import pytest
from tools.checks.diagnose_locomotion_policy import contact_events, summarize_samples
def _samples():
target = np.array([0., 0., 100., 0., 2., 2.]).reshape(6, 1, 1)
done = np.zeros((6, 1), dtype=bool)
done[2] = True
velocity = np.full((6, 1, 3), .2)
velocity[2] = 999.
reward = np.full((6, 1, 1), 1.)
reward[2] = 999.
root = np.zeros((6, 1, 3))
root[..., 2] = 1.1
root[2, :, 2] = .2
return dict(action=target.copy(), target=target, qpos=target.copy(), torque=target.copy(),
dones=done, contacts=np.ones((6, 1, 2), dtype=bool),
height=np.zeros((6, 1, 2)), velocity=velocity, rewards=reward,
root_height=root[..., 2], root_link_pos_w=root)
def test_reset_frames_are_excluded_but_real_target_jumps_remain():
sample = _samples()
sample['angular_velocity'] = np.full((6, 1, 3), .3)
sample['angular_velocity'][2] = 999.
result = summarize_samples(sample, .02, ['joint'], np.array([10.]), ['reward'],
np.array([.2, .2, 0.]))
assert result['valid_samples'] == 5 and result['excluded_reset_samples'] == 1
assert result['valid_target_difference_samples'] == 3
# The real 0->2 rad action transition remains; 0->100->0 reset edges vanish.
assert result['joints']['joint']['target_speed_rms_rad_s'] == pytest.approx(100 / np.sqrt(3))
assert result['joints']['joint']['qpos']['max'] == 2.
assert result['joints']['joint']['torque_saturation_fraction'] == 0.
assert result['reward_rate']['reward'] == 1.
assert result['mean_velocity'] == pytest.approx([.2, .2, .2])
assert result['mean_velocity_axes'] == ['vx', 'vy', 'vz']
assert result['mean_angular_velocity'] == pytest.approx([.3, .3, .3])
assert result['mean_yaw_tracking_error'] == pytest.approx(.3)
assert result['mean_height'] == pytest.approx(1.1)
assert result['root_height_m']['min'] == pytest.approx(1.1)
# A control without resets must detect the large real jump, not suppress it.
sample['dones'][:] = False
control = summarize_samples(sample, .02, ['joint'], np.array([10.]), ['reward'],
np.array([.2, .2, 0.]))
assert control['joints']['joint']['target_speed_rms_rad_s'] > 3000.
assert control['joints']['joint']['qpos']['max'] == 100.
assert control['joints']['joint']['torque_saturation_fraction'] > 0.
def test_stance_slip_ignores_swing_and_reset_samples():
sample = _samples()
sample['sole_velocity_w'] = np.zeros((6, 1, 2, 3))
sample['sole_velocity_w'][..., 0] = .03
sample['sole_velocity_w'][2] = 999. # Reset frame.
sample['contacts'][3, 0, 1] = False
sample['sole_velocity_w'][3, 0, 1] = 100. # Airborne foot.
result = summarize_samples(sample, .02, ['joint'], np.array([10.]), ['reward'],
np.array([.2, .2, 0.]))
assert result['stance_sole_horizontal_speed_m_s']['max'] == pytest.approx(.03)
assert result['joints']['joint']['qpos']['per_env_p95_p05_excursion_rad'] == [2.]
def test_reset_aborts_swings_and_same_foot_periods_do_not_bridge_episodes():
contacts = np.ones((14, 1, 2), dtype=bool)
contacts[[1, 2, 4, 5, 7, 8, 11, 12], 0, 0] = False
dones = np.zeros((14, 1), dtype=bool)
dones[5] = True
height = np.where(contacts, 0., .03)
result = contact_events(contacts, height, dones, .02)
assert result['completed_swings_per_env_foot'] == [[3, 0]]
summary = result['contact_event_summary']
assert summary['complete_event_count'] == 3
assert summary['airtime_s']['median'] == pytest.approx(.04)
assert summary['same_foot_landing_period_s']['min'] == pytest.approx(.08)
assert summary['same_foot_landing_period_s']['max'] == pytest.approx(.08)
assert summary['events_airtime_ge_0_1s_and_height_ge_0_02m'] == 0
@pytest.mark.parametrize('dt', [.01, .02])
def test_descriptive_threshold_does_not_change_existing_40ms_count(dt):
# One 40ms shallow event and one 120ms higher event; include leading and
# trailing truncated air phases, neither of which is a complete swing.
states = [False, True] + [False] * round(.04 / dt) + [True, True] \
+ [False] * round(.12 / dt) + [True, True, False]
contacts = np.ones((len(states), 1, 2), dtype=bool)
contacts[:, 0, 0] = states
heights = np.where(contacts, 0., .01)
start = 4 + round(.04 / dt)
heights[start:start + round(.12 / dt), 0, 0] = .03
result = contact_events(contacts, heights, np.zeros((len(states), 1), dtype=bool), dt)
assert result['completed_swings_per_env_foot'] == [[2, 0]]
summary = result['contact_event_summary']
assert summary['complete_event_count'] == 2
assert summary['airtime_s']['min'] == pytest.approx(.04)
assert summary['airtime_s']['max'] == pytest.approx(.12)
assert summary['events_airtime_ge_0_1s_and_height_ge_0_02m'] == 1
def test_one_frame_chatter_is_described_but_not_counted_as_40ms_swing():
contacts = np.ones((3, 1, 2), dtype=bool)
contacts[1, 0, 0] = False
result = contact_events(contacts, np.where(contacts, 0., .005),
np.zeros((3, 1), dtype=bool), .02)
assert result['completed_swings_per_env_foot'] == [[0, 0]]
assert result['contact_event_summary']['complete_event_count'] == 1
assert result['contact_event_summary']['airtime_s']['median'] == .02
assert result['contact_event_summary']['same_foot_landing_period_s'] is None
def test_no_usable_samples_fails_explicitly():
sample = _samples()
sample['dones'][:] = True
with pytest.raises(ValueError, match='No non-reset samples'):
summarize_samples(sample, .02, ['joint'], [10.], ['reward'], np.zeros(3))
+1 -1
View File
@@ -81,7 +81,7 @@ def test_training_only_randomization_and_wheel_exclusion(neutral_robot):
cfg = env_cfg(neutral_robot)
assert cfg.observations["actor"].history_length == 4
assert {"joint_home", "lin_vel_z", "ang_vel_xy", "support_slip", "missing_support"} <= cfg.rewards.keys()
assert {"pose", "single_support", "lin_vel_z", "ang_vel_xy", "support_slip", "missing_support"} <= cfg.rewards.keys()
assert {"base_density", "base_com", "pd_gains", "support_friction"} <= cfg.events.keys()
play = env_cfg(neutral_robot, play=True)
assert play.observations["actor"].history_length == 4
+47 -3
View File
@@ -116,9 +116,6 @@ def test_the_csv_header_still_describes_its_rows(tmp_path: Path) -> None:
monitor = JointMonitor(
_Entity(), 0, 0.01, tmp_path, sensor=_Feet(), foot_names=feet
)
# The window may or may not have opened depending on the machine; the csv is
# what this is about.
monitor._fig = None
for _ in range(4):
monitor.update()
monitor.close()
@@ -170,3 +167,50 @@ def test_a_bundle_is_a_directory_checkpoint_can_be_pointed_at(tmp_path) -> None:
(bare / "actor.onnx").write_bytes(b"")
with pytest.raises(FileNotFoundError):
find_checkpoint(str(bare), tmp_path)
def test_measurement_only_probes_gui_when_explicitly_interactive(tmp_path, monkeypatch):
from types import SimpleNamespace
from mjrl.viewer import monitor as module
events = []
def probe():
events.append('probe')
return 'QtAgg', {'QT_API': 'pyqt5'}
def open_window(self, backend, env):
events.append((backend, env))
monkeypatch.setattr(module, '_interactive_backend', probe)
monkeypatch.setattr(module.JointMonitor, '_open_window', open_window)
entity = SimpleNamespace(joint_names=('hip',), actuator_names=('hip',))
env = SimpleNamespace(step_dt=.01)
measurement = module.make_monitor(entity, 0, env, tmp_path)
assert measurement._fig is None
assert events == []
# Control proves the explicitly requested live view still probes and opens.
module.make_monitor(entity, 0, env, tmp_path, interactive=True)
assert events == ['probe', ('QtAgg', {'QT_API': 'pyqt5'})]
def test_saved_plot_uses_no_interactive_figure_even_with_live_window(tmp_path, monkeypatch):
from types import SimpleNamespace
from matplotlib import pyplot
from mjrl.viewer.monitor import JointMonitor
def unexpected(*args, **kwargs):
raise AssertionError('artifact export opened an interactive figure')
monkeypatch.setattr(pyplot, 'figure', unexpected)
monkeypatch.setattr(pyplot, 'subplots', unexpected)
measurement = JointMonitor(SimpleNamespace(joint_names=('hip',), actuator_names=('hip',)),
0, .01, tmp_path)
measurement._fig = object() # Existing live monitor must not affect export.
measurement._t = [0., .01]
measurement._pos = [[0.], [.1]]
measurement._vel = [[0.], [1.]]
measurement._tau = [[0.], [.5]]
png = tmp_path / 'measure.png'
measurement._write_png(png)
assert png.read_bytes().startswith(b'\x89PNG\r\n\x1a\n')
+189
View File
@@ -0,0 +1,189 @@
"""Fusion can reorder geoms; serialization must preserve poses at full precision."""
import xml.etree.ElementTree as ET
import numpy as np
import pytest
mujoco = pytest.importorskip('mujoco')
from mjrl.onboarding.build import write_mjcf
def _source(tmp_path):
(tmp_path / 'shape.obj').write_text('''v 0 0 0
v .1 0 0
v 0 .2 0
v 0 0 .3
f 1 3 2
f 1 2 4
f 1 4 3
f 2 3 4
''')
path = tmp_path / 'robot.xml'
path.write_text('''<mujoco><compiler fusestatic="true"/>
<asset><mesh name="shape" file="shape.obj"/></asset><worldbody>
<body name="base"><joint name="axis"/><geom size=".1"/>
<body name="fixed_a" pos=".1234567890123 .032123456789 .2"
quat=".998412345 .00123456789 .0423456789 .03123456789">
<geom name="first" type="mesh" mesh="shape"/>
<geom name="second" size=".03" pos=".01 .02 .03"/>
<body name="nested" pos=".0123456789 .02345678901 .03456789012">
<geom name="nested_geom" type="mesh" mesh="shape"/>
</body>
</body>
<body name="fixed_b" pos=".2 0 0"><geom name="last" size=".02"/></body>
</body></worldbody></mujoco>''')
return path
def test_fusion_order_and_mesh_poses_preserved(tmp_path, monkeypatch):
from mjrl.platform import _serialization
serialize = _serialization.spec_xml
def reordered(spec):
root = ET.fromstring(serialize(spec))
parent = root.find(".//body[@name='fixed_a']")
geoms = parent.findall('geom')
for geom in geoms:
parent.remove(geom)
for index, geom in enumerate(reversed(geoms)):
parent.insert(index, geom)
return ET.tostring(root, encoding='unicode')
monkeypatch.setattr(_serialization, 'spec_xml', reordered)
source = _source(tmp_path)
spec = mujoco.MjSpec.from_file(str(source))
original = mujoco.MjModel.from_xml_path(str(source))
copied = write_mjcf(spec, source, tmp_path / 'output' / 'robot.xml')
assert original.nbody == copied.nbody == 2
assert copied.geom(0).name == ''
assert '__mjrl_roundtrip_' not in (tmp_path / 'output' / 'robot.xml').read_text()
# Native fusion changes IDs after canonicalization; prove the test has a
# reordered geom and then verify each object by its actual identity.
assert original.geom('first').id != copied.geom('first').id
for name in ['first', 'nested_geom', 'last']:
a, b = original.geom(name).id, copied.geom(name).id
np.testing.assert_allclose(original.geom_pos[a], copied.geom_pos[b], atol=1e-12, rtol=0)
np.testing.assert_allclose(original.geom_quat[a], copied.geom_quat[b], atol=1e-12, rtol=0)
np.testing.assert_allclose(original.body_inertia, copied.body_inertia, atol=1e-9)
def test_roundtrip_still_rejects_transform_corruption(tmp_path, monkeypatch):
source = _source(tmp_path)
load = mujoco.MjModel.from_xml_path
def corrupted(path):
model = load(path)
model.geom_pos[model.geom('first').id, 0] += .01
return model
monkeypatch.setattr(mujoco.MjModel, 'from_xml_path', corrupted)
output = tmp_path / 'output' / 'robot.xml'
with pytest.raises(ValueError, match='round-trip changed geom_pos'):
write_mjcf(mujoco.MjSpec.from_file(str(source)), source, output)
assert not output.exists()
@pytest.mark.parametrize('raises', [False, True])
def test_precision_restored_on_success_and_error(raises):
from mjrl.platform._serialization import _precision_api, spec_xml
api = _precision_api()
if api is None:
pytest.skip('native writer precision hooks unavailable')
get, set_ = api
previous = get()
class Writer:
def to_xml(self):
assert get() == 17
if raises:
raise ValueError('writer error')
return '<mujoco/>'
try:
set_(9)
if raises:
with pytest.raises(ValueError, match='writer error'):
spec_xml(Writer())
else:
assert spec_xml(Writer()) == '<mujoco/>'
assert get() == 9
finally:
set_(previous)
def test_precision_fallback_without_native_hooks(monkeypatch):
from mjrl.platform import _serialization
monkeypatch.setattr(_serialization, '_precision_api', lambda: None)
class Writer:
def to_xml(self):
return '<mujoco/>'
assert _serialization.spec_xml(Writer()) == '<mujoco/>'
def test_packaged_copy_preserves_precision(tmp_path):
from mjrl.platform.model import copy_model
source = _source(tmp_path)
before = mujoco.MjModel.from_xml_path(str(source))
output = tmp_path / 'app' / 'robot.xml'
copy_model(source, output)
after = mujoco.MjModel.from_xml_path(str(output))
assert '__mjrl_roundtrip_' not in output.read_text()
for name in ['first', 'nested_geom', 'last']:
a, b = before.geom(name).id, after.geom(name).id
np.testing.assert_allclose(before.geom_pos[a], after.geom_pos[b], atol=1e-12, rtol=0)
np.testing.assert_allclose(before.geom_quat[a], after.geom_quat[b], atol=1e-12, rtol=0)
@pytest.mark.parametrize('packaged', [False, True])
def test_temporary_names_do_not_strip_other_object_names(tmp_path, packaged):
from mjrl.platform.model import copy_model
source = tmp_path / 'source.xml'
source.write_text('''<mujoco><worldbody><body><joint name="j"/>
<geom size=".1"/><site name="__mjrl_roundtrip_1" size=".01"/>
</body></worldbody><sensor><framepos name="p" objtype="site"
objname="__mjrl_roundtrip_1"/></sensor></mujoco>''')
output = tmp_path / 'result.xml'
if packaged:
copy_model(source, output)
else:
write_mjcf(mujoco.MjSpec.from_file(str(source)), source, output)
model = mujoco.MjModel.from_xml_path(str(output))
assert model.site('__mjrl_roundtrip_1').id == 0
assert model.body(1).name == ''
assert model.geom(0).name == ''
@pytest.mark.parametrize('packaged', [False, True])
def test_massless_collision_defaults_preserve_inferred_inertia(tmp_path, packaged):
from mjrl.platform.model import copy_model
# Include the body so packaging must flatten the spec. Both zero settings
# together trigger the native writer's elision of the collision default.
(tmp_path / 'body.xml').write_text('''<mujoco><body name="link">
<joint name="hinge"/><geom size=".1" mass="1.25"/>
<geom class="pad" size=".2" pos="0 .25 0"/>
<geom class="pad" size=".15" pos=".25 0 0" mass=".5"/>
</body></mujoco>''')
source = tmp_path / 'scene.xml'
source.write_text('''<mujoco><default><default class="collision">
<geom density="0" mass="0"/><default class="pad"/>
</default></default><worldbody><include file="body.xml"/></worldbody></mujoco>''')
before = mujoco.MjModel.from_xml_path(str(source))
assert before.body('link').mass.item() == 1.75
output = tmp_path / 'output' / 'robot.xml'
if packaged:
copy_model(source, output)
else:
write_mjcf(mujoco.MjSpec.from_file(str(source)), source, output)
after = mujoco.MjModel.from_xml_path(str(output))
for field in ('body_mass', 'body_inertia', 'body_ipos', 'body_iquat'):
np.testing.assert_array_equal(getattr(after, field), getattr(before, field))
assert all(after.geom(gid).name == '' for gid in range(after.ngeom))
+110
View File
@@ -0,0 +1,110 @@
"""Relocating flattened MJCF must preserve exact compiled dynamics and defaults."""
import xml.etree.ElementTree as ET
import numpy as np
import pytest
mujoco = pytest.importorskip('mujoco')
from mjrl.platform.model import copy_model, validate_contained_model
def _model(tmp_path):
(tmp_path / 'shape.obj').write_text('''v 0 0 0
v .1 0 0
v 0 .2 0
v 0 0 .3
f 1 3 2
f 1 2 4
f 1 4 3
f 2 3 4
''')
source = tmp_path / 'source.xml'
source.write_text('''<mujoco><compiler angle="radian"/>
<option timestep=".0025" integrator="implicitfast"/>
<default><default class="part"><geom friction=".812345678901234 .01 .001"/>
<joint damping=".123456789012345"/></default></default>
<asset><mesh name="shape" file="shape.obj"/></asset><worldbody>
<geom type="plane" size="2 2 .1"/>
<body name="robot" pos="0 0 .3" quat=".998412345 .00123456789 .0423456789 .03123456789">
<freejoint/><geom type="sphere" size=".1"/>
<geom name="visual" type="mesh" mesh="shape" contype="0" conaffinity="0"
quat=".912345678901 .001234567891 .234567891234 .123456789123"/>
<body name="arm" pos=".1234567890123 0 .05" childclass="part">
<joint name="hinge"/><geom name="hand" size=".04"/></body></body>
</worldbody><actuator><position joint="hinge" kp="10.1234567890123" kv="1"/>
</actuator></mujoco>''')
return source
def test_flattened_copy_keeps_exact_compiled_arrays_and_rollout(tmp_path, monkeypatch):
from mjrl.platform import _serialization
def unexpected(spec):
raise AssertionError('Flattened XML was unnecessarily reserialized')
monkeypatch.setattr(_serialization, 'spec_xml', unexpected)
source = _model(tmp_path)
output = tmp_path / 'app' / 'robot.xml'
copy_model(source, output)
before = mujoco.MjModel.from_xml_path(str(source))
after = mujoco.MjModel.from_xml_path(str(output))
for field in dir(before):
a, b = getattr(before, field), getattr(after, field)
# _sizes includes storage allocated for relocated path strings.
if field != "_sizes" and isinstance(a, np.ndarray) and np.issubdtype(a.dtype, np.number):
np.testing.assert_array_equal(a, b, err_msg=field)
# Numeric defaults and original anonymous objects survive, not just named geoms.
assert ET.parse(output).find('.//default[@class="part"]/geom').get('friction') \
== '.812345678901234 .01 .001'
assert before.geom(0).name == after.geom(0).name == ''
(tmp_path / 'shape.obj').unlink()
validate_contained_model(output.parent, output)
a, b = mujoco.MjData(before), mujoco.MjData(after)
for step in range(1000):
a.ctrl[:] = b.ctrl[:] = .2 * np.sin(step * .01)
mujoco.mj_step(before, a)
mujoco.mj_step(after, b)
np.testing.assert_array_equal(a.qpos, b.qpos)
np.testing.assert_array_equal(a.qvel, b.qvel)
def test_flattened_copy_still_rejects_sub_tolerance_geometry_change(tmp_path, monkeypatch):
source = _model(tmp_path)
output = tmp_path / 'app' / 'robot.xml'
load = mujoco.MjModel.from_xml_path
def changed(path):
model = load(path)
if str(path) == str(output):
model.geom_pos[0, 0] += 1e-12
return model
monkeypatch.setattr(mujoco.MjModel, 'from_xml_path', changed)
with pytest.raises(ValueError, match='flattened model changed exact geom_pos'):
copy_model(source, output)
def test_include_and_asset_directory_still_use_normalization(tmp_path):
source = _model(tmp_path)
xml = ET.parse(source)
asset = xml.find('./asset/mesh')
(tmp_path / 'assets').mkdir()
(tmp_path / 'shape.obj').rename(tmp_path / 'assets/shape.obj')
xml.find('compiler').set('meshdir', 'assets')
body = xml.find('./worldbody/body')
xml.find('worldbody').remove(body)
fragment = ET.Element('mujoco')
fragment.append(body)
ET.ElementTree(fragment).write(tmp_path / 'body.xml')
ET.SubElement(xml.find('worldbody'), 'include', file='body.xml')
xml.write(source)
assert asset.get('file') == 'shape.obj'
output = tmp_path / 'app' / 'robot.xml'
copy_model(source, output)
result = ET.parse(output)
assert result.find('.//include') is None
assert result.find('compiler').get('meshdir') is None
validate_contained_model(output.parent, output)
assert mujoco.MjModel.from_xml_path(str(source)).nq \
== mujoco.MjModel.from_xml_path(str(output)).nq
+81
View File
@@ -0,0 +1,81 @@
"""Model facts must never masquerade as recovered actor semantics."""
import json
import subprocess
import sys
from pathlib import Path
import mujoco
import pytest
from mjrl.onboarding.model_evidence import model_evidence
from mjrl.onboarding.upstream import extract_policy_metadata
_XML = """<mujoco><option timestep="0.005"/>
<worldbody><geom name="floor" type="plane" size="1 1 .1"/>
<body name="robot"><joint name="elbow" range="-60 60" damping="3"/>
<geom name="foot" size=".1" contype="0" conaffinity="0"/></body></worldbody>
<contact><pair geom1="floor" geom2="foot"/></contact>
<actuator><position name="servo" joint="elbow" kp="17" gear="2"
ctrlrange="-.5 .5" forcerange="-4 6"/></actuator>
<keyframe><key name="pose" qpos=".2" ctrl=".4"/></keyframe></mujoco>"""
def test_model_only_draft_keeps_semantics_unknown():
model = mujoco.MjModel.from_xml_string(_XML)
report = extract_policy_metadata([], model=model)
assert not report['ready']
assert report['metadata'] == {'schema': 'mjrl-policy-adapter/1'}
assert {'obs_joint_order', 'action_joint_order', 'control.control_hz',
'default_joint_pos', 'action_scale', 'observation.terms'} <= set(report['missing_fields'])
facts = report['model_evidence']
assert facts['physics_timestep_s'] == .005
assert facts['joints'][0]['damping'] == [3]
assert facts['actuators'][0]['gear'][0] == 2
assert facts['actuators'][0]['force_range'] == [-4, 6]
assert facts['actuators'][0]['control_range'] == [-.5, .5]
assert facts['keyframes'][0]['qpos'] == [.2]
assert facts['explicit_contact_pairs'][0]['geoms'] == ['floor', 'foot']
# The fingerprint must detect physical changes, not merely joint names.
model.dof_damping[0] = 4
assert model_evidence(model)['compiled_model_sha256'] != facts['compiled_model_sha256']
def test_no_sources_or_model_is_not_an_extraction():
with pytest.raises(ValueError, match='config paths or a model'):
extract_policy_metadata([])
def test_model_only_cli_persists_failed_draft(tmp_path):
model = tmp_path / 'robot.xml'
model.write_text(_XML)
output = tmp_path / 'draft'
result = subprocess.run(
[sys.executable, 'scripts/onboard.py', 'extract-tier1', '--model', str(model),
'--output', str(output)], cwd=Path(__file__).resolve().parents[1],
capture_output=True, text=True,
)
assert result.returncode == 1, result.stderr
manifest = json.loads((output / 'manifest.json').read_text())
assert manifest['ready'] is False
assert manifest['model_evidence']['dimensions']['nu'] == 1
assert json.loads((output / 'metadata.json').read_text()) == manifest['metadata']
assert not list(output.glob('*.onnx'))
def test_native_verification_accepts_explicit_pair_physics(tmp_path):
from mjrl.onboarding.verify import verify
model = tmp_path / 'robot.xml'
model.write_text(_XML)
config = {'root_body': 'robot', 'steps': 1,
'actuator_targets': {'servo': .4}, 'joint_positions': {'elbow': .2}}
report = verify(model, config)
dynamic = next(c for c in report['stages']['physics']['checks']
if c['name'] == 'dynamic_robot')
assert dynamic['passed'] and dynamic['has_collision']
model.write_text(_XML.replace('<contact><pair geom1="floor" geom2="foot"/></contact>', ''))
report = verify(model, config)
dynamic = next(c for c in report['stages']['physics']['checks']
if c['name'] == 'dynamic_robot')
assert not dynamic['passed'] and not dynamic['has_collision']
+84
View File
@@ -42,6 +42,32 @@ def test_explicit_control_intent_wins():
assert report["recommendation"]["tier"] == 2
def test_default_biped_objective_only_adapts_an_actor_that_observes_forward_and_turn(tmp_path, neutral_robot):
# Inspection validates metadata without executing any supplied actor graph.
actor = tmp_path / "actor.onnx"
actor.write_bytes(b"inventory only")
joints = [joint.name for joint in neutral_robot.position_joints]
axes = ["lin_vel_x", "ang_vel_z"]
metadata = {
"wire_joint_order": joints, "obs_joint_order": [], "action_joint_order": joints,
"default_joint_pos": dict.fromkeys(joints, 0.0), "action_scale": 1.0,
"control": {"kp": 10, "kd": 0.6, "effort_limit": 10, "control_hz": 50},
"observation": {"terms": [{"name": "commands"}], "command_order": axes},
"command_ranges": {"twist": {axis: [-0.5, 0.5] for axis in axes}},
}
profile = {"family": "biped", "base_body": neutral_robot.base_body,
"foot_geoms": list(neutral_robot.foot_geoms)}
def recommendation(intent=None):
selected = profile if intent is None else {**profile, "control_intent": intent}
return inspect_asset(neutral_robot.model_path, profile=selected, policy=actor,
policy_metadata=metadata)["recommendation"]
assert recommendation()["tier"] == 1
assert recommendation("retrain")["tier"] == 3
assert recommendation("deterministic")["tier"] == 2
metadata["command_ranges"]["twist"]["ang_vel_z"] = [0, 0]
assert recommendation()["tier"] == 3
def test_direct_drive_wheels_are_not_legs():
report = inspect_asset(ROOT / "assets/differential_drive/robot.xml")
assert report["morphology_candidates"]["family"] is None
@@ -92,3 +118,61 @@ def test_ambiguous_models_do_not_infer(tmp_path):
report = inspect_asset(tmp_path)
assert report["morphology_candidates"] is None
assert report["recommendation"]["tier"] == 0
assert report["recommendation"]["status"] == "needs_selection"
assert report["recommendation"]["next_step"] == "select-model"
assert report["recommendation"]["prerequisites"] == ["select_model"]
assert inspect_asset(tmp_path / "a.xml")["recommendation"]["status"] == "ready"
def _shared_support_model(path, *, limbs, contact_joints, shared_joint):
"""Use anonymous links so only distal topology can separate the limbs."""
branches = []
for limb in range(limbs):
contacts = ''.join(
f'<body name="sole_{limb}_{toe}" pos="{toe * .05} 0 0">'
+ (f'<joint name="digit_{limb}_{toe}"/>' if contact_joints else '')
+ f'<geom name="contact_{limb}_{toe}" size=".025"/></body>'
for toe in range(2)
)
branches.append(
f'<body name="segment_{limb}_a" pos="0 {limb * .2} -.1">'
f'<joint name="axis_{limb}_a"/><geom size=".04"/>'
f'<body name="segment_{limb}_b" pos="0 0 -.1">'
f'<joint name="axis_{limb}_b"/><geom size=".04"/>'
f'{contacts}</body></body>'
)
shared = '<joint name="shared_axis"/>' if shared_joint else ''
path.write_text(
'<mujoco><worldbody><body name="base"><freejoint/><geom size=".1"/>'
f'<body name="shared">{shared}<geom size=".05"/>'
+ ''.join(branches) + '</body></body></worldbody></mujoco>'
)
@pytest.mark.parametrize("shared_joint", [False, True])
@pytest.mark.parametrize("contact_joints", [False, True])
@pytest.mark.parametrize("limbs,family", [(2, "biped"), (4, "quadruped")])
def test_shared_ancestor_separates_distal_limbs_not_their_contacts(
tmp_path, shared_joint, contact_joints, limbs, family,
):
path = tmp_path / "shared.xml"
_shared_support_model(path, limbs=limbs, contact_joints=contact_joints,
shared_joint=shared_joint)
candidates = inspect_asset(path)["morphology_candidates"]
assert candidates["family"] == family
assert candidates["support_branch_count"] == limbs
assert len(candidates["supports"]) == 2 * limbs
for limb in range(limbs):
contacts = [support for support in candidates["supports"]
if support["body"].startswith(f"sole_{limb}_")]
assert len({support["branch_id"] for support in contacts}) == 1
@pytest.mark.parametrize("contact_joints", [False, True])
def test_single_limb_with_two_distal_contacts_is_not_a_biped(tmp_path, contact_joints):
path = tmp_path / "single.xml"
_shared_support_model(path, limbs=1, contact_joints=contact_joints, shared_joint=True)
candidates = inspect_asset(path)["morphology_candidates"]
assert len(candidates["supports"]) == 2
assert candidates["support_branch_count"] == 1
assert candidates["family"] is None
+286
View File
@@ -0,0 +1,286 @@
"""Calibrated motor parity and observation frames for imported real policies."""
import json
import numpy as np
import onnx
from onnx import TensorProto, helper
import pytest
mujoco = pytest.importorskip("mujoco")
pytest.importorskip("bam")
from bam.model import load_model
from bam.mujoco import MujocoController
from mjrl.platform.motors import BamMotorModel, validate_motor_model
from mjrl.platform.policy import OnnxController
CONFIG = {
"kind": "bam", "motor_name": "xl330", "model": "m6", "kp": 100,
"vin": 7.0, "max_current": 1.5, "vin_drop_resistance": 0.1, "vin_min": 6,
}
XML = """<mujoco>
<compiler angle="radian"/><option timestep=".002"/>
<worldbody><body name="base" pos="0 0 1"><freejoint/>
<geom size=".1" mass="1"/>
<site name="imu" quat=".5 -.5 -.5 .5" pos=".1 0 0"/>
<body pos=".2 0 0"><joint name="a" range="-2 2" damping=".041" frictionloss=".013"/>
<geom type="capsule" fromto="0 0 0 .1 0 0" size=".02" mass=".1"/></body>
<body pos="-.2 0 0"><joint name="b" range="-2 2" damping=".041" frictionloss=".013"/>
<geom type="capsule" fromto="0 0 0 -.1 0 0" size=".02" mass=".1"/></body>
</body></worldbody>
<actuator><motor name="motor_b" joint="b"/><motor name="motor_a" joint="a"/></actuator>
</mujoco>"""
def test_bam_matches_upstream_dynamics_and_repeated_reset():
model = mujoco.MjModel.from_xml_string(XML)
actual = mujoco.MjData(model)
actual.qpos[:3] = [.2, -.3, 1.1]
preserved = actual.qpos.copy()
bridge = BamMotorModel(model, [1, 0], [.6405, .6405], CONFIG)
np.testing.assert_array_equal(actual.qpos, preserved)
original = mujoco.MjModel.from_xml_string(XML)
expected = mujoco.MjData(original)
motor = load_model(motor_name="xl330", model="m6")
motor.actuator.kp = 100
motor.actuator.vin = 7.0
motor.actuator.max_current = 1.5
upstream = MujocoController(
motor, ["motor_a", "motor_b"], original, expected,
vin_drop_resistance=.1, vin_min=6,
)
traces = []
for _ in range(2):
mujoco.mj_resetData(model, actual)
actual.qpos[:] = preserved
bridge.reset(actual, [0, 0])
mujoco.mj_forward(model, actual)
trace = []
for tick in range(100):
target = [.65 * np.sin(tick * .1), -.2]
bridge.apply(actual, target)
first = actual.ctrl.copy()
bridge.apply(actual, [10, 10]) # Duplicate physics tick cannot consume state twice.
np.testing.assert_array_equal(actual.ctrl, first)
mujoco.mj_step(model, actual)
trace.append(np.r_[actual.qpos, actual.qvel, actual.ctrl])
traces.append(trace)
np.testing.assert_array_equal(traces[0], traces[1])
expected.qpos[:] = preserved
motor.reset()
upstream.last_ts = expected.time
mujoco.mj_forward(original, expected)
reference = []
for tick in range(100):
upstream.q_target = np.array([.65 * np.sin(tick * .1), -.2])
upstream.update()
expected.ctrl[:] = np.clip(expected.ctrl, -.6405, .6405)
mujoco.mj_step(original, expected)
reference.append(np.r_[expected.qpos, expected.qvel, expected.ctrl])
np.testing.assert_allclose(traces[0], reference, rtol=0, atol=1e-12)
assert np.max(np.abs(np.asarray(traces[0])[:, -2:])) > .1
assert not np.allclose(model.dof_frictionloss, .013)
@pytest.mark.parametrize("change", [
{"kind": "other"}, {"model": "../m6"}, {"vin": 0}, {"vin_min": 8},
{"max_current": float("inf")}, {"vin_drop_resistance": -1}, {"extra": 1},
])
def test_bam_rejects_invalid_configuration(change):
with pytest.raises(ValueError):
validate_motor_model({**CONFIG, **change})
def test_site_gyro_and_body_gravity_are_distinct_observation_frames(tmp_path):
graph = helper.make_graph(
[helper.make_node("Constant", [], ["actions"], value=helper.make_tensor(
"target", TensorProto.FLOAT, [1, 2], [0, 0]))],
"constant", [helper.make_tensor_value_info("obs", TensorProto.FLOAT, [1, 9])],
[helper.make_tensor_value_info("actions", TensorProto.FLOAT, [1, 2])],
)
proto = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)])
proto.ir_version = 9
onnx.save(proto, tmp_path / "actor.onnx")
layout = {
"_schema": "mjrl-native-layout/1", "wire_joint_order": ["a", "b"],
"obs_joint_order": ["a", "b"], "action_joint_order": ["a", "b"],
"default_joint_pos": {"a": 0, "b": 0}, "action_scale": {"a": 1, "b": 1},
"joint_limits": {"a": [-2, 2], "b": [-2, 2]},
"control": {"kp": 1, "kd": 0, "control_hz": 50, "effort_limit": .6405},
"action": {"dim": 2, "targets": {
"a": {"kind": "position", "offset": 0}, "b": {"kind": "position", "offset": 0}}},
"observation": {"dim": 9, "terms": [
{"name": "base_ang_vel", "dim": 3}, {"name": "projected_gravity", "dim": 3},
{"name": "base_lin_vel", "dim": 3}],
"frames": {"base_ang_vel": {"kind": "site", "name": "imu"},
"base_lin_vel": {"kind": "site", "name": "imu"}}},
"motor_model": CONFIG,
}
(tmp_path / "layout.json").write_text(json.dumps(layout))
model = mujoco.MjModel.from_xml_string(XML)
controller = OnnxController(model, {"layout": "layout.json", "policy": "actor.onnx"}, tmp_path)
data = mujoco.MjData(model)
controller.reset(data)
data.qvel[:6] = [.1, .2, .3, 1, 2, 3]
mujoco.mj_forward(model, data)
site_velocity = np.zeros(6)
mujoco.mj_objectVelocity(model, data, mujoco.mjtObj.mjOBJ_SITE, model.site("imu").id,
site_velocity, 1)
observation = controller.observation(data, {})[0]
np.testing.assert_allclose(observation[:3], site_velocity[:3], atol=1e-7)
np.testing.assert_allclose(observation[3:6], [0, 0, -1], atol=1e-7)
np.testing.assert_allclose(observation[6:], site_velocity[3:], atol=1e-7)
assert not np.allclose(observation[:3], data.qvel[3:6])
controller.step(data)
snapshot = data.ctrl.copy()
controller.apply(data)
np.testing.assert_array_equal(data.ctrl, snapshot)
def test_passive_verification_replays_dynamic_friction_independently():
from mjrl.onboarding.verify import _run_probe, _THRESHOLDS
from mjrl.platform.velocity import VelocityWindow
class Controller:
reset_passive = OnnxController.reset_passive
apply_passive = OnnxController.apply_passive
def __init__(self, model):
self.model = model
self.actuators = np.array([1, 0])
self.driven_idx = np.array([0, 1])
self.qadr = np.array([7, 8])
self.motor_model = BamMotorModel(model, self.actuators, [.6405, .6405], CONFIG)
self.target = np.zeros(2)
def reset(self, data):
self.motor_model.reset(data, data.qpos[self.qadr])
def step(self, data, command):
self.target[:] = command["target"]
self.apply(data)
def apply(self, data):
return self.motor_model.apply(data, self.target)
model = mujoco.MjModel.from_xml_string(XML)
controller = Controller(model)
initial = mujoco.MjData(model)
initial.qpos[-2:] = [.3, -.5]
initial.qvel[3:6] = [.5, -.3, 1]
initial.qvel[-2:] = [4, -3]
mujoco.mj_forward(model, initial)
original_qpos = initial.qpos.copy()
metric = "base_angular_velocity_mean_rad_s"
specs = {metric: {"target": [0, 0, 0], "tolerance": [1, 1, 1]}}
results = []
for command in (-1.5, 1.5):
_, _, measurements = _run_probe(
model, initial, 1, {"a": 1, "b": 2}, controller,
{"command": {"target": command}, "expect": specs}, _THRESHOLDS, None, {}, 250, 10,
)
results.append(measurements["velocity_evaluation"]["metrics"][metric])
np.testing.assert_array_equal(initial.qpos, original_qpos)
# Active commands genuinely differ; the counterfactual must not inherit
# their final load-dependent friction or motor state.
assert not np.allclose(results[0]["observed"], results[1]["observed"])
np.testing.assert_array_equal(
results[0]["actuation_disabled_observed"], results[1]["actuation_disabled_observed"]
)
original = mujoco.MjModel.from_xml_string(XML)
baseline = mujoco.MjData(original)
motor = load_model(motor_name="xl330", model="m6")
motor.actuator.kp, motor.actuator.vin, motor.actuator.max_current = 100, 7.0, 1.5
upstream = MujocoController(
motor, ["motor_a", "motor_b"], original, baseline,
vin_drop_resistance=.1, vin_min=6,
)
baseline.qpos[:] = initial.qpos
baseline.qvel[:] = initial.qvel
original.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_ACTUATION
mujoco.mj_forward(original, baseline)
window = VelocityWindow(1, 0, .5, specs)
for index in range(250):
upstream.q_target = baseline.qpos[upstream.qpos_indexes].copy()
upstream.update()
baseline.ctrl[:] = 0
mujoco.mj_step(original, baseline)
mujoco.mj_forward(original, baseline)
window.sample(original, baseline, (index + 1) * .002)
np.testing.assert_allclose(
results[0]["actuation_disabled_observed"], window.results()[metric]["observed"],
rtol=0, atol=1e-12,
)
# A frozen-friction control reproduces the old bug and must be distinguishable.
controller.reset_passive = None
controller.apply_passive = None
_, _, stale = _run_probe(
model, initial, 1, {"a": 1, "b": 2}, controller,
{"command": {"target": 1.5}, "expect": specs}, _THRESHOLDS, None, {}, 250, 10,
)
assert not np.allclose(
stale["velocity_evaluation"]["metrics"][metric]["actuation_disabled_observed"],
window.results()[metric]["observed"], atol=1e-5,
)
@pytest.mark.parametrize("python_version", [(3, 10), (3, 11), (3, 13)])
def test_bam_reports_unsupported_python_before_loading_motor(monkeypatch, python_version):
from types import SimpleNamespace
from mjrl.platform import motors
monkeypatch.setattr(motors, "sys", SimpleNamespace(version_info=python_version))
with pytest.raises(ValueError, match="requires Python >=3.12,<3.13"):
BamMotorModel(None, [], [], CONFIG)
def test_bam_bundle_declares_dependency_python_constraint(tmp_path):
from mjrl.adapter import adapt_policy
from mjrl.onboarding.verify import verify
from mjrl.platform.bundle import build_bundle, open_bundle
model_path = tmp_path / "robot.xml"
model_path.write_text(XML.replace("<freejoint/>", ""))
model = mujoco.MjModel.from_xml_path(str(model_path))
graph = helper.make_graph(
[helper.make_node("Constant", [], ["actions"], value=helper.make_tensor(
"target", TensorProto.FLOAT, [1, 2], [.4, -.4]))],
"constant", [helper.make_tensor_value_info("obs", TensorProto.FLOAT, [1, 2])],
[helper.make_tensor_value_info("actions", TensorProto.FLOAT, [1, 2])],
)
proto = helper.make_model(graph, opset_imports=[helper.make_opsetid("", 17)])
proto.ir_version = 9
onnx.save(proto, tmp_path / "source.onnx")
metadata = {
"wire_joint_order": ["a", "b"], "obs_joint_order": ["a", "b"],
"action_joint_order": ["a", "b"], "default_joint_pos": {"a": 0, "b": 0},
"action_scale": 1,
"control": {"kp": 1, "kd": 0, "control_hz": 50, "effort_limit": .6405},
"observation": {"terms": [{"name": "joint_pos"}]}, "motor_model": CONFIG,
}
result = adapt_policy(tmp_path / "source.onnx", metadata, tmp_path / "policy", model=model)
report = verify(model_path, {
"controller": str(result.config), "root_body": "base", "steps": 2000,
"probes": [{"command": {}, "joint_positions": {"a": .4, "b": -.4}}],
})
assert report["passed"], report
report_path = tmp_path / "verification.json"
report_path.write_text(json.dumps(report))
app = build_bundle(model_path, tmp_path / "bundle", robot_id="bench", modes={
"move": {"controller": result.config, "policy": result.actor,
"layout": result.layout, "verification": report_path},
})
with open_bundle(app) as (root, manifest):
assert manifest["runtimes"]["native"]["python"] == ">=3.12,<3.13"
assert "better-actuator-models==1.0.2" in (root / "runtime/requirements.txt").read_text()
viewer = build_bundle(model_path, tmp_path / "viewer", robot_id="bench", modes={
"view": {"control_mode": "model_viewer"},
})
with open_bundle(viewer) as (root, manifest):
assert manifest["runtimes"]["native"]["python"] == ">=3.10,<3.14"
assert "better-actuator-models" not in (root / "runtime/requirements.txt").read_text()
+91
View File
@@ -0,0 +1,91 @@
"""Native scene export preserves fine geometry rotations without wider tolerances."""
from types import SimpleNamespace as NS
import numpy as np
import pytest
mujoco = pytest.importorskip('mujoco')
# Initialize the entity package as a real training scene does; mjlab spec and
# actuator utilities otherwise have a vendored import-order cycle.
from mjlab.entity import Entity # noqa: F401
from mjrl.native_export import write_native_model
def _environment():
spec = mujoco.MjSpec.from_string('''<mujoco><option timestep=".003"/>
<asset><mesh name="shape" file="shape.obj"/></asset>
<worldbody><body name="robot" pos=".012345678901234 .02 .3">
<freejoint/><geom name="shell" type="mesh" mesh="shape"
quat=".912345678901 .001234567891 .234567891234 .123456789123"/>
<body name="limb" pos="0 0 .1"><joint name="hinge"/>
<geom name="limb_geom" type="capsule" size=".03 .2"
quat=".998765432109 .0000123456789 .032345678901 .012345678901"/>
</body></body></worldbody><actuator><motor joint="hinge"/></actuator>
</mujoco>''', assets={'shape.obj': b'''v 0 0 0
v .1 0 0
v 0 .2 0
v 0 0 .3
f 1 3 2
f 1 2 4
f 1 4 3
f 2 3 4
'''})
# Mesh-frame composition exposes cancellation that six-digit authored
# rotations cannot preserve, even with the existing relative tolerance.
probe = spec.compile()
inverse = np.empty(4)
mujoco.mju_negQuat(inverse, probe.mesh_quat[0])
target = np.array([.9, .3, .2, 1e-6])
target /= np.linalg.norm(target)
authored = np.empty(4)
mujoco.mju_mulQuat(authored, target, inverse)
spec.geom('shell').quat = authored
live = spec.compile()
class Scene:
entities = {}
def __init__(self):
self.spec = spec
def __getitem__(self, name):
assert name == 'robot'
return NS(indexing=NS(root_body_id=live.body('robot').id))
return NS(scene=Scene(), sim=NS(mj_model=live), cfg=NS(commands={}))
def test_native_export_retains_sub_six_digit_rotations(tmp_path):
env = _environment()
write_native_model(env, tmp_path, {'control': {'sim_dt': .003}})
copied = mujoco.MjModel.from_xml_path(str(tmp_path / 'robot.xml'))
np.testing.assert_allclose(copied.geom_quat, env.sim.mj_model.geom_quat, rtol=0, atol=1e-14)
np.testing.assert_allclose(copied.body_pos, env.sim.mj_model.body_pos, rtol=0, atol=1e-14)
assert (tmp_path / 'controller.json').is_file()
def test_native_export_rejects_actual_geometry_rotation_change(tmp_path):
env = _environment()
# Mutate only the live model: this is a real mismatch with the scene spec.
env.sim.mj_model.geom_quat[1] = [1., 0., 0., 0.]
with pytest.raises(ValueError, match='Native model export changed geom_quat'):
write_native_model(env, tmp_path, {'control': {'sim_dt': .003}})
assert not (tmp_path / 'controller.json').exists()
def test_six_digit_writer_control_demonstrates_original_failure(tmp_path, monkeypatch):
from mjrl.platform import _serialization
api = _serialization._precision_api()
if api is None:
pytest.skip('six digit control requires native precision hooks')
get, set_ = api
previous = get()
try:
set_(6)
monkeypatch.setattr('mjrl.native_export.spec_xml', lambda spec: spec.to_xml())
with pytest.raises(ValueError, match='Native model export changed geom_quat'):
write_native_model(_environment(), tmp_path, {'control': {'sim_dt': .003}})
finally:
set_(previous)
+96
View File
@@ -0,0 +1,96 @@
"""Native tensor matrix views must support entity poses without copying physics buffers."""
from dataclasses import replace
from xml.etree import ElementTree as ET
import numpy as np
import pytest
import torch
from mjrl.backend.native_sim import _NativeData
@pytest.mark.parametrize('name', ['xmat', 'site_xmat', 'geom_xmat'])
def test_native_matrix_view_shares_the_original_flat_buffer(name):
raw = np.arange(36, dtype=np.float32).reshape(2, 2, 9)
data = _NativeData({name: raw}, 2)
held = getattr(data, name)
assert held.shape == (2, 2, 3, 3)
assert data.numpy(name) is raw and raw.shape == (2, 2, 9)
raw[1, 0, 5] = 123.
assert held[1, 0, 1, 2].item() == 123.
held[0, 1, 2, 0] = 456.
assert raw[0, 1, 6] == 456.
# Attribute assignment also writes the original gather/scatter allocation.
setattr(data, name, torch.full_like(held, 7.))
np.testing.assert_array_equal(raw, np.full_like(raw, 7.))
def test_native_entity_site_and_geom_poses_match_rotated_mujoco_states(neutral_robot, tmp_path):
from mjlab.envs import ManagerBasedRlEnv
from mjlab.sim import get_simulation_cls, set_simulation_cls
from mjlab.utils.lab_api.math import matrix_from_quat
from mjrl.backend import native_sim
from mjrl.backend.resolve import resolve
from mjrl.backend.select import use_backend
from tasks.templates.Biped_Template.env_cfg import env_cfg
tree = ET.parse(neutral_robot.model_path)
base = tree.find(".//body[@name='base']")
ET.SubElement(base, 'site', name='offset_site', pos='.11 -.03 .06',
euler='.4 -.2 .3')
tree.find(".//geom[@name='trunk']").set('euler', '-.3 .2 -.1')
path = tmp_path / 'rotated.xml'
tree.write(path)
robot_spec = replace(neutral_robot, model_path=path)
saved_class, saved_threads = get_simulation_cls(), native_sim._DEFAULT_NTHREAD
env = None
try:
use_backend(resolve(backend='native', device='cpu', num_envs=2, cpu_threads=1))
cfg = env_cfg(robot_spec, play=True)
cfg.scene.num_envs = 2
env = ManagerBasedRlEnv(cfg, device='cpu')
robot, sim = env.scene['robot'], env.sim
site_views = sim.data.site_xmat # Keep a reference across native forwards.
old_site_matrices = site_views.clone()
for phase in (0., .25):
sim.data.qpos[:, :3] = torch.tensor([[.2, -.1, .7], [-.4, .3, .9]])
for world, angle in enumerate((.6 + phase, -.8 - phase)):
sim.data.qpos[world, 3:7] = torch.tensor(
[np.cos(angle / 2), 0., 0., np.sin(angle / 2)], dtype=torch.float32)
sim.data.qpos[world, 7:] = torch.tensor([.2 + phase, -.3])
sim.forward()
assert not torch.allclose(site_views, old_site_matrices)
old_site_matrices = site_views.clone()
for kind in ('site', 'geom'):
indices = getattr(robot.data.indexing, f'{kind}_ids').cpu().numpy()
poses = getattr(robot.data, f'{kind}_pose_w')
matrices = matrix_from_quat(poses[..., 3:]).cpu().numpy()
for world in range(2):
_, native = sim.env_mjdata(world)
np.testing.assert_allclose(
poses[world, :, :3].cpu().numpy(),
getattr(native, f'{kind}_xpos')[indices], atol=1e-6, rtol=0)
np.testing.assert_allclose(
matrices[world], getattr(native, f'{kind}_xmat')[indices].reshape(-1, 3, 3),
atol=1e-6, rtol=0)
# Distinct worlds and nonidentity matrices make order and
# orientation errors observable, not just a shape assertion.
assert not np.allclose(matrices[0], matrices[1])
assert not np.allclose(matrices[0], np.eye(3))
np.testing.assert_array_equal(
getattr(robot.data, f'{kind}_pos_w').cpu().numpy(), poses[..., :3].cpu().numpy())
# Raycast consumers keep accepting the same matrices via view.
assert sim.data.xmat[:, 1].view(-1, 3, 3).shape == (2, 3, 3)
# Regression control: restoring the old flattened tensor layout makes
# the public pose accessor reject the flattened rotation matrices.
sim.data._t['site_xmat'] = site_views.reshape(2, -1, 9)
with pytest.raises(torch.jit.Error, match='Invalid rotation matrix shape'):
_ = robot.data.site_pos_w
sim.data._t['site_xmat'] = site_views
finally:
if env is not None:
env.close()
set_simulation_cls(saved_class)
native_sim._DEFAULT_NTHREAD = saved_threads
+14 -3
View File
@@ -249,7 +249,7 @@ def test_existing_weights_need_complete_model_and_metadata(tmp_path: Path) -> No
]
def test_tier3_needs_explicit_legged_control_intent(tmp_path: Path) -> None:
def test_biped_defaults_to_learned_walking_and_requires_grounded_model_review(tmp_path: Path) -> None:
model = tmp_path / "robot.xml"
model.write_text(
"""
@@ -278,7 +278,9 @@ def test_tier3_needs_explicit_legged_control_intent(tmp_path: Path) -> None:
"base_body": "base",
"foot_geoms": ["left_contact", "right_contact"],
}
assert inspect_asset(model, profile=profile)["recommendation"]["tier"] == 2
default = inspect_asset(model, profile=profile)["recommendation"]
assert default["tier"] == 3 and default["objective"] == "walking"
assert 3 in default["eligible_tiers"]
explicit = {**profile, "control_intent": "wasd"}
legged = inspect_asset(model, profile=explicit)
assert legged["recommendation"]["tier"] == 3
@@ -287,7 +289,16 @@ def test_tier3_needs_explicit_legged_control_intent(tmp_path: Path) -> None:
)
assert not coverage["passed"] and coverage["missing"] == ["visual_link"]
invalid = {**explicit, "foot_geoms": ["left_contact", "missing_contact"]}
assert inspect_asset(model, profile=invalid)["recommendation"]["tier"] == 2
unresolved = inspect_asset(model, profile=invalid)["recommendation"]
assert unresolved["tier"] == 3 and unresolved["status"] == "needs_profile"
assert 3 not in unresolved["eligible_tiers"]
model.write_text(model.read_text().replace("<worldbody>", '<worldbody><geom type="plane" size="1 1 .1"/>'))
scene = inspect_asset(model, profile=profile)["recommendation"]
assert scene["tier"] == 3 and scene["status"] == "needs_model"
assert "extract_robot_only_model" in scene["prerequisites"]
assert 3 not in scene["eligible_tiers"]
opt_out = inspect_asset(model, profile={**profile, "control_intent": "deterministic"})
assert opt_out["recommendation"]["tier"] == 2
def test_mjcf_plugin_declarations_are_rejected_before_native_parse(tmp_path: Path) -> None:
+71
View File
@@ -0,0 +1,71 @@
"""Project intake excludes installed examples without hiding actual exports."""
from pathlib import Path
import pytest
pytest.importorskip("mujoco")
from mjrl.onboarding.build import build_mjcf
from mjrl.onboarding.inspect import inspect_asset
_MODEL = '<mujoco><worldbody><geom type="box" size=".1 .1 .1"/></worldbody></mujoco>'
def _write(root: Path, name: str, text: str) -> Path:
path = root / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text, encoding="utf-8")
return path
@pytest.mark.parametrize("incidental", [
".venv", "venv", ".git", "__pycache__", ".cache", ".pytest_cache",
"node_modules", "site-packages", "dist-packages", "custom-python",
])
def test_project_discovery_prunes_dependencies_for_inspect_and_build(tmp_path, incidental):
source = tmp_path / "project"
model = _write(source, "models/robot.xml", _MODEL)
config = _write(source, "logs/run/params/env.yaml", "sim: {dt: 0.005}\n")
actor = _write(source, "logs/run/exported/actor.onnx", "discovery must not load actors")
unrelated = source / incidental
if incidental == "custom-python":
_write(unrelated, "pyvenv.cfg", "home = /usr/bin\n")
_write(unrelated, "examples/robot.xml", _MODEL)
_write(unrelated, "examples/legged_robot_config.py", "class Config: pass\n")
_write(unrelated, "examples/actor.onnx", "unrelated installed policy")
_write(unrelated, "examples/mesh.obj", "unrelated installed mesh")
report = inspect_asset(source)
assert report["model_candidates"] == [str(model)]
assert report["training_config_candidates"] == [str(config)]
assert report["policy_candidates"] == [str(actor)]
assert report["mesh_candidates"] == []
# A dependency model used to make directory builds ambiguous as well.
output = tmp_path / "built.xml"
build_mjcf(source, output)
assert output.is_file()
def test_config_directories_and_explicit_dependency_paths_remain_selectable(tmp_path):
source = tmp_path / "project"
model = _write(source, ".venv/examples/robot.xml", _MODEL)
config = _write(source, "env/legged_robot_config.py", "class Config: pass\n")
hidden = _write(source, ".exports/env.yaml", "sim: {dt: 0.005}\n")
report = inspect_asset(source)
assert report["training_config_candidates"] == sorted([str(config), str(hidden)])
assert report["model_candidates"] == []
# Explicit selection overrides discovery exclusions, including selected roots.
assert inspect_asset(model)["model_candidates"] == [str(model)]
assert inspect_asset(model.parent)["model_candidates"] == [str(model)]
build_mjcf(model, tmp_path / "explicit.xml")
def test_discovery_still_reports_genuine_model_ambiguity(tmp_path):
first = _write(tmp_path, "models/first.xml", _MODEL)
second = _write(tmp_path, "exports/second.xml", _MODEL)
report = inspect_asset(tmp_path)
assert report["model_candidates"] == sorted([str(first), str(second)])
with pytest.raises(ValueError, match="multiple model candidates"):
build_mjcf(tmp_path, tmp_path / "built.xml")
@@ -0,0 +1,80 @@
"""Explicit pairs establish contact geometry; empty frames do not add robots."""
import pytest
mujoco = pytest.importorskip("mujoco")
from mjrl.onboarding._physics import contact_groups
from mjrl.onboarding.inspect import inspect_asset
def _model(*, pairs=True, extra='<body name="empty_frame"><body/></body>'):
contact = '<contact><pair geom1="floor" geom2="left_sole"/>' \
'<pair geom1="floor" geom2="right_sole"/></contact>' if pairs else ''
return f'''<mujoco><default><geom contype="0" conaffinity="0"/></default>
<worldbody><geom name="floor" type="plane" size="1 1 .1"/>
<body name="base"><freejoint/><geom size=".1"/>
<body name="left_foot"><joint name="left_hip"/>
<geom name="left_sole" size=".1"/></body>
<body name="right_foot"><joint name="right_hip"/>
<geom name="right_sole" size=".1"/>
<geom name="visual_only" size=".05"/></body></body>{extra}
</worldbody>{contact}</mujoco>'''
def test_explicit_pairs_enable_intake_and_contact_groups(tmp_path):
path = tmp_path / 'robot.xml'
path.write_text(_model())
report = inspect_asset(path)
geoms = {geom['name']: geom for geom in report['model']['geoms']}
assert geoms['left_sole']['collision_enabled']
assert not geoms['visual_only']['collision_enabled']
assert report['morphology_candidates']['family'] == 'biped'
assert report['morphology_candidates']['floating_base']
assert report['recommendation']['complete_model']
model = mujoco.MjModel.from_xml_path(str(path))
root = model.body('base').id
for selector, names in [('foot_geoms', ['left_sole', 'right_sole']),
('foot_bodies', ['left_foot', 'right_foot'])]:
kind, groups = contact_groups(model, {selector: names}, root)
assert kind == selector
assert set(groups) == set(names)
with pytest.raises(ValueError, match='collision-disabled'):
contact_groups(model, {'foot_geoms': ['visual_only']}, root)
def test_zero_masks_without_pairs_remain_disabled(tmp_path):
path = tmp_path / 'robot.xml'
path.write_text(_model(pairs=False))
report = inspect_asset(path)
assert not report['recommendation']['complete_model']
assert report['morphology_candidates']['family'] is None
model = mujoco.MjModel.from_xml_path(str(path))
for config in ({'foot_geoms': ['left_sole']}, {'foot_bodies': ['left_foot']}):
with pytest.raises(ValueError, match='collision-disabled|no direct collision'):
contact_groups(model, config, model.body('base').id)
@pytest.mark.parametrize('extra', [
'<body name="obstacle"><geom size=".1"/></body>',
'<body name="second_robot"><freejoint/><geom size=".1"/></body>',
])
def test_physical_extra_roots_still_require_selection(tmp_path, extra):
path = tmp_path / 'robot.xml'
path.write_text(_model(extra=extra))
report = inspect_asset(path)
assert report['morphology_candidates']['base_body'] is None
assert not next(item['passed'] for item in report['checks']
if item['name'] == 'single_robot_root')
def test_calibration_ground_does_not_inherit_collision_disabled_defaults():
from mjrl.onboarding._physics import attach_calibration_ground
spec = mujoco.MjSpec.from_string(_model(pairs=False))
name = attach_calibration_ground(spec, None)
model = spec.compile()
assert model.geom(name).contype[0] == 1
assert model.geom(name).conaffinity[0] == 1
# Authored masks remain untouched; only the generated terrain is enabled.
assert model.geom('floor').contype[0] == 0
assert model.geom('left_sole').conaffinity[0] == 0
+18
View File
@@ -140,6 +140,24 @@ def test_stance_checks_actual_support_and_effort(tmp_path: Path) -> None:
assert not failed_root.exists()
def test_biped_scaffold_inherits_walking_controls_unless_overridden(tmp_path, neutral_robot):
from dataclasses import asdict
from controller.controls import load_controls
from tasks.robot_spec import read_robot_spec
recipe = asdict(neutral_robot)
explicit = recipe.pop("controls_path")
for path_fields, expected in (({}, "key_a"), ({"controls_path": explicit}, "key_j"),
({"controls_path": None}, None)):
result = scaffold_task({**recipe, **path_fields}, base_dir=tmp_path,
tasks_root=tmp_path / str(expected))
path = read_robot_spec(Path(result["robot_spec"])).controls_path
if expected is None:
assert path is None
else:
assert expected in load_controls(path).key_axes["ang_vel_z"].plus
def test_verify_measures_real_actuated_response(arm: Path) -> None:
"""A well-shaped graph and finite controls can still drive a wrong target."""
config = {
+102
View File
@@ -0,0 +1,102 @@
"""Contact evidence cannot count stationary, chatter, or partial air phases."""
import mujoco
import pytest
from tools.checks.measure_policy_gait import (
ContactCycles,
SoleMeasurements,
foot_site_ids,
horizontal_ground_height,
)
def _sample(states, dt=.02):
tracker = ContactCycles()
for index, state in enumerate(states):
tracker.sample(state, index * dt)
return tracker.result(.04, 2)
def test_repeated_stance_swing_cycles_are_detected():
result = _sample([True] * 4 + [False] * 4 + [True] * 4 + [False] * 4 + [True] * 4)
assert result["passed"]
assert result["qualifying_swings"] == result["qualifying_stances"] == 2
assert result["takeoffs"] == result["landings"] == 2
def test_standing_and_contact_chatter_do_not_pass():
assert not _sample([True] * 100)["passed"]
chatter = _sample([True, False] * 100)
assert not chatter["passed"]
assert chatter["qualifying_swings"] == 0
def test_warmup_truncated_and_unlanded_swings_do_not_count():
result = _sample([False] * 5 + [True] * 5 + [False] * 5)
assert result["landings"] == 1
assert result["takeoffs"] == 1
assert result["completed_air_times_s"] == []
assert not result["passed"]
def test_stride_duration_measures_two_observed_landings():
result = _sample([False] * 3 + [True] * 4 + [False] * 4 + [True] * 4)
assert result["landing_to_landing_stride_times_s"] == pytest.approx([.16])
def test_sole_peaks_exclude_partial_swings_and_slip_uses_only_loaded_samples():
sole = SoleMeasurements()
sole.sample(False, .5, 20.) # Warmup-truncated flight must not set a peak.
sole.sample(True, 0., .1)
sole.sample(False, .02, 50.)
sole.sample(False, .07, 50.)
sole.sample(False, .04, 50.)
sole.sample(True, 0., .3)
sole.sample(False, .9, 50.) # An unfinished final swing is also excluded.
result = sole.result(.02)
assert result["completed_swing_peak_heights_m"] == [.07]
assert result["mean_completed_swing_peak_height_m"] == .07
assert result["contact_samples"] == 2
assert result["mean_contact_slip_speed_m_s"] == pytest.approx(.2)
assert result["rms_contact_slip_speed_m_s"] == pytest.approx((.05) ** .5)
assert result["integrated_contact_slip_distance_m"] == pytest.approx(.008)
def _sole_model(ground='type="plane" size="2 2 .1" pos="0 0 .2"'):
return mujoco.MjModel.from_xml_string(f"""
<mujoco><worldbody>
<geom name="ground" {ground}/>
<body name="left" pos="0 .2 .3"><site name="left_sole"/></body>
<body name="right" pos="0 -.2 .4"><site name="right_sole"/></body>
</worldbody></mujoco>
""")
def test_sole_mapping_checks_body_association_and_plane_height():
model = _sole_model()
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
ids = foot_site_ids(model, ["right", "left"], ["right_sole", "left_sole"])
height = horizontal_ground_height(model, data, model.geom("ground").id)
assert height == .2
assert data.site_xpos[ids["left"], 2] - height == pytest.approx(.1)
assert data.site_xpos[ids["right"], 2] - height == pytest.approx(.2)
with pytest.raises(ValueError, match="attached"):
foot_site_ids(model, ["right", "left"], ["left_sole", "right_sole"])
with pytest.raises(ValueError, match="one unique"):
foot_site_ids(model, ["right", "left"], ["right_sole", "right_sole"])
with pytest.raises(ValueError, match="one unique"):
foot_site_ids(model, ["right", "left"], ["right_sole"])
@pytest.mark.parametrize("ground", [
'type="box" size="2 2 .1"',
'type="plane" size="2 2 .1" euler="20 0 0"',
])
def test_sole_height_rejects_nonplane_and_tilted_ground(ground):
model = _sole_model(ground)
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
with pytest.raises(ValueError, match="plane"):
horizontal_ground_height(model, data, model.geom("ground").id)
+124
View File
@@ -0,0 +1,124 @@
"""Posture allowances and clearance sites are explicit, portable robot data."""
from dataclasses import asdict, replace
import hashlib
from pathlib import Path
import pytest
from tasks.robot_spec import JointSpec, RobotSpec, read_robot_spec, scaffold_robot_spec
@pytest.fixture
def spec(tmp_path):
model = tmp_path / "robot.xml"
model.write_text('<mujoco><worldbody><geom size=".1"/></worldbody></mujoco>')
return RobotSpec(
robot_id="schema_robot", family="biped", model_path=model,
base_body="base", base_height=.5, foot_geoms=("left_foot", "right_foot"),
position_joints=(JointSpec("left", 10, 1, 20, .1), JointSpec("right", 20, 2, 30, .2)),
)
def test_old_literals_keep_default_posture_allowance_and_no_sites(spec):
old = asdict(spec)
old.pop("foot_sites")
for joint in old["position_joints"]:
joint.pop("posture_std")
loaded = RobotSpec.from_dict(old, base_dir=Path.cwd())
assert loaded.foot_sites == ()
assert [joint.posture_std for joint in loaded.position_joints] == [.35, .35]
def test_named_posture_and_sites_survive_literal_scaffolding(spec, tmp_path):
enriched = replace(
spec, foot_sites=("left_clearance", "right_clearance"),
position_joints=(replace(spec.position_joints[0], posture_std=.15),
replace(spec.position_joints[1], posture_std=.7)),
)
document = asdict(enriched)
document["foot_sites"] = list(enriched.foot_sites)
loaded = RobotSpec.from_dict(document, base_dir=tmp_path)
assert loaded.foot_sites == enriched.foot_sites
path = scaffold_robot_spec(loaded, tasks_root=tmp_path / "tasks")
assert read_robot_spec(path) == enriched
assert read_robot_spec(path).position_joints[0].posture_std != .35
assert read_robot_spec(path).position_joints[1].posture_std != .35
@pytest.mark.parametrize("value", [0, -1, float("nan"), float("inf"), float("-inf"), True, ".2", None])
def test_posture_std_requires_positive_finite_numeric_values(value):
with pytest.raises(ValueError, match="posture_std"):
JointSpec("hip", 10, 1, 20, .1, posture_std=value)
@pytest.mark.parametrize("sites", [
("one",), ("one", "two", "three"), ("one", "one"), ("", "two"),
(" ", "two"), ("robot/left", "right"), (None, "right"), "lr", None,
])
def test_sites_reject_wrong_count_duplicates_bad_names_and_nonlists(spec, sites):
with pytest.raises(ValueError):
replace(spec, foot_sites=sites)
document = asdict(spec)
document["foot_sites"] = sites
with pytest.raises(ValueError):
RobotSpec.from_dict(document, base_dir=Path.cwd())
def test_site_count_uses_selected_body_supports(spec):
bodies = replace(spec, foot_geoms=(), foot_bodies=("left", "right", "rear"))
with pytest.raises(ValueError, match="one site per named foot support"):
replace(bodies, foot_sites=("left_site", "right_site"))
assert replace(bodies, foot_sites=("left_site", "right_site", "rear_site")).foot_sites[-1] == "rear_site"
@pytest.fixture
def calibrated_input(spec):
mujoco = pytest.importorskip("mujoco")
from mjrl.onboarding._physics import compiled_model_sha256
# Exercise the metadata writer with an exact model fingerprint, without
# conflating this schema fixture with a physical calibration claim.
config = {"robot_id": spec.robot_id, "family": spec.family,
"model_path": str(spec.model_path), "action_scales": {"left": .1, "right": .2},
"foot_sites": ["left_site", "right_site"]}
report = {
"schema": "mjrl.onboarding.calibrate/1", "passed": True,
"model_sha256": hashlib.sha256(spec.model_path.read_bytes()).hexdigest(),
"compiled_model_sha256": compiled_model_sha256(mujoco.MjModel.from_xml_path(str(spec.model_path))),
"base_position": [0, 0, .5], "base_quaternion": [1, 0, 0, 0],
"root_body": "base", "foot_geoms": ["left_foot", "right_foot"],
"joint_order": [joint.name for joint in spec.position_joints],
"joints": {joint.name: asdict(joint) for joint in spec.position_joints},
}
return config, report
def test_calibrated_scaffold_maps_allowances_by_name_and_consumes_input_map(calibrated_input):
from mjrl.onboarding.scaffold import calibrated_spec_config
config, report = calibrated_input
output = calibrated_spec_config(
{**config, "posture_stds": {"right": .6, "left": .15}}, report, base_dir=Path.cwd()
)
assert "posture_stds" not in output
assert "action_scales" not in output
spec = RobotSpec.from_dict(output, base_dir=Path.cwd())
assert [(joint.name, joint.posture_std) for joint in spec.position_joints] == [("left", .15), ("right", .6)]
assert spec.foot_sites == ("left_site", "right_site")
default = calibrated_spec_config(config, report, base_dir=Path.cwd())
assert [joint["posture_std"] for joint in default["position_joints"]] == [.35, .35]
@pytest.mark.parametrize("posture", [
{}, {"left": .2}, {"left": .2, "right": .3, "unknown": .4},
{"left": 0, "right": .3}, {"left": -1, "right": .3},
{"left": float("nan"), "right": .3}, {"left": float("inf"), "right": .3},
{"left": True, "right": .3}, [.2, .3], None,
])
def test_calibrated_scaffold_rejects_incomplete_extra_or_invalid_allowances(calibrated_input, posture):
from mjrl.onboarding.scaffold import calibrated_spec_config
config, report = calibrated_input
with pytest.raises(ValueError, match="posture_stds"):
calibrated_spec_config({**config, "posture_stds": posture}, report, base_dir=Path.cwd())
+61
View File
@@ -0,0 +1,61 @@
"""Authored controls are replaced by calibration using the supported MjSpec API."""
from dataclasses import replace
from xml.etree import ElementTree as ET
import numpy as np
import pytest
mujoco = pytest.importorskip("mujoco")
pytest.importorskip("mjlab")
from tasks.templates._locomotion import _load_model
from tasks.templates.Biped_Template.env_cfg import env_cfg
def test_authored_actuators_and_keys_are_replaced_without_modifying_source(neutral_robot, tmp_path):
source = ET.parse(neutral_robot.model_path)
actuators = ET.SubElement(source.getroot(), "actuator")
for index in range(2):
ET.SubElement(actuators, "position", name=f"authored_{index}", joint=f"leg_{index}",
kp="99", kv="9", forcerange="-90 90")
keys = ET.SubElement(source.getroot(), "keyframe")
for index in range(2):
ET.SubElement(keys, "key", name=f"authored_pose_{index}",
qpos="0 0 .4 1 0 0 0 .5 -.5", ctrl=".5 -.5")
path = tmp_path / "authored.xml"
source.write(path)
original_bytes = path.read_bytes()
authored = mujoco.MjModel.from_xml_path(str(path))
assert authored.nu == authored.nkey == 2 # Both removal loops must do work.
np.testing.assert_array_equal(authored.actuator_gainprm[:, 0], [99, 99])
joints = tuple(replace(joint, kp=11 + i, kd=.7 + i, effort_limit=8 + i,
home=.1 if i == 0 else -.2, armature=.01 + .01 * i)
for i, joint in enumerate(neutral_robot.position_joints))
robot = replace(neutral_robot, model_path=path, position_joints=joints)
spec, _, homes = _load_model(path, robot)
stripped = spec.compile()
assert stripped.nu == stripped.nkey == 0
assert homes == {joint.name: joint.home for joint in joints}
np.testing.assert_array_equal(stripped.body_mass, authored.body_mass)
np.testing.assert_array_equal(stripped.jnt_range, authored.jnt_range)
entity = env_cfg(robot).scene.entities["robot"].build()
calibrated = entity.spec.compile()
assert calibrated.nu == 2
assert calibrated.nkey == 1
assert calibrated.key(0).name == "init_state"
for index, (joint, actuator) in enumerate(zip(joints, entity.actuators, strict=True)):
assert actuator.cfg.stiffness == joint.kp
assert actuator.cfg.damping == joint.kd
assert actuator.cfg.effort_limit == joint.effort_limit
np.testing.assert_array_equal(calibrated.actuator_forcerange[index],
[-joint.effort_limit, joint.effort_limit])
jid = calibrated.joint(joint.name).id
assert calibrated.dof_armature[calibrated.jnt_dofadr[jid]] == joint.armature
assert calibrated.key("init_state").qpos[calibrated.jnt_qposadr[jid]] == joint.home
assert path.read_bytes() == original_bytes
reread = mujoco.MjModel.from_xml_path(str(path))
assert reread.nu == reread.nkey == 2
np.testing.assert_array_equal(reread.actuator_gainprm, authored.actuator_gainprm)
+71
View File
@@ -0,0 +1,71 @@
"""Biped training starts at full command coverage; other families keep staging."""
from importlib import import_module
from pathlib import Path
from types import SimpleNamespace
import pytest
import torch
from mjlab.tasks.velocity.mdp.velocity_command import UniformVelocityCommandCfg
from mjrl.tasks.commands import AxisBalancedVelocityCommand, AxisBalancedVelocityCommandCfg
from mjrl.tasks.operator import OperatorVelocityCommand, OperatorVelocityCommandCfg
from tasks.robot_spec import read_robot_spec
@pytest.mark.parametrize("template,ceilings", [
("Biped", (.7, .35, .8)),
("Quadruped", (1.1, .6, 1.)),
("Wheeled_Biped", (1.3, 0., 1.1)),
("Multipod", (.6, .45, .75)),
])
def test_family_training_command_ranges_and_curriculum(template, ceilings):
examples = (Path(__file__).resolve().parents[1] / "tasks").glob("*_example/robot_spec.py")
robot = next(spec for spec in map(read_robot_spec, examples) if spec.family == template.lower())
env_cfg = import_module(f"tasks.templates.{template}_Template.env_cfg").env_cfg
train, play = env_cfg(robot), env_cfg(robot, play=True)
assert type(train.commands["twist"]) is (
AxisBalancedVelocityCommandCfg if template == "Biped" else UniformVelocityCommandCfg
)
assert type(play.commands["twist"]) is OperatorVelocityCommandCfg
fractions = (1.,) if template == "Biped" else (.4, .7, 1.)
curriculum = train.curriculum["command"].params
assert curriculum["fractions"] == fractions
assert curriculum["ceilings"] == ceilings
assert play.curriculum == {}
for axis, ceiling in zip(("lin_vel_x", "lin_vel_y", "ang_vel_z"), ceilings, strict=True):
training = getattr(train.commands["twist"].ranges, axis)
playing = getattr(play.commands["twist"].ranges, axis)
assert playing == (-ceiling, ceiling)
assert training == (-ceiling * fractions[0], ceiling * fractions[0])
if template == "Biped":
assert training == playing
elif ceiling:
assert training != playing # Detect accidentally widening every family.
if template == "Biped":
assert "swing_air_time" not in train.rewards
assert "single_support" in train.rewards
@pytest.mark.parametrize("command", [(.2, -.1, .3), (0., 0., -.3), (0., 0., 0.)])
def test_biped_fixed_replay_bypasses_training_axis_mask_and_operator(neutral_robot, command):
from mjrl.replay import configure_velocity_replay
from tasks.templates.Biped_Template.env_cfg import env_cfg
train, play = env_cfg(neutral_robot), env_cfg(neutral_robot, play=True)
checkpoint = {"infos": {"curriculum": {"command": {"level": 0}}}}
report = configure_velocity_replay(play, train, checkpoint, command)
assert report["fixed_body_command"] == list(command)
assert train.commands["twist"].isolated_axis_fraction == .3
zeros = torch.zeros(2, 3)
env = SimpleNamespace(num_envs=2, device="cpu", step_dt=.02, scene={
"robot": SimpleNamespace(data=SimpleNamespace(root_link_lin_vel_b=zeros, root_link_ang_vel_b=zeros)),
})
term = play.commands["twist"].build(env)
assert not isinstance(term, (AxisBalancedVelocityCommand, OperatorVelocityCommand))
term.reset(torch.arange(2))
for _ in range(3):
term.compute(8.) # Exceeds maximum sample duration; exercise real resampling.
term.reset(torch.tensor([1]))
term.compute(0., env_ids=torch.tensor([1]))
torch.testing.assert_close(term.command, torch.tensor([command, command]), atol=0, rtol=0)
+157
View File
@@ -0,0 +1,157 @@
"""Foot-site data reaches ordered contact rewards and real native terrain scans."""
from dataclasses import replace
from xml.etree import ElementTree as ET
import numpy as np
import pytest
import torch
mujoco = pytest.importorskip("mujoco")
pytest.importorskip("mjlab")
from tasks.templates._locomotion import _entity_spec, _ordered_foot_sites
from tasks.templates.Biped_Template.env_cfg import env_cfg
@pytest.fixture
def site_robot(neutral_robot, tmp_path):
source = ET.parse(neutral_robot.model_path)
for i in range(2):
body = source.find(f".//body[@name='leg_body_{i}']")
ET.SubElement(body, "site", name=f"sole_{i}", pos="0 0 -.20", size=".002")
base = source.find(".//body[@name='base']")
# Attached to a different body from the site, so exclude_parent_body alone
# cannot prevent this robot collider from corrupting the terrain height.
ET.SubElement(base, "geom", name="robot_ray_blocker", type="box",
pos="0 .12 -.23", size=".05 .05 .005", mass="0")
path = tmp_path / "sites.xml"
source.write(path)
joints = tuple(replace(joint, posture_std=std)
for joint, std in zip(neutral_robot.position_joints, [.15, .55], strict=True))
return replace(neutral_robot, model_path=path, position_joints=joints,
foot_sites=("sole_1", "sole_0"), foot_geoms=("contact_1", "contact_0"))
@pytest.mark.parametrize("body_supports", [False, True])
def test_site_order_follows_compiled_support_order_and_requires_matching_body(site_robot, body_supports):
robot = site_robot
if body_supports:
robot = replace(robot, foot_geoms=(), foot_bodies=("leg_body_1", "leg_body_0"))
model = mujoco.MjModel.from_xml_path(str(robot.model_path))
assert _ordered_foot_sites(model, robot) == ("sole_0", "sole_1")
with pytest.raises(ValueError, match="must be on its support"):
_ordered_foot_sites(model, replace(robot, foot_sites=("sole_0", "sole_1")))
with pytest.raises(ValueError, match="missing foot site"):
_ordered_foot_sites(model, replace(robot, foot_sites=("missing", "sole_0")))
cfg = env_cfg(robot)
heights = next(sensor for sensor in cfg.scene.sensors if sensor.name == "sole_height")
assert tuple(frame.name for frame in heights.frame) == ("sole_0", "sole_1")
selection = cfg.rewards["foot_clearance"].params["asset_cfg"]
assert selection.site_names == ("sole_0", "sole_1") and selection.preserve_order
def _ray_from_first_site(spec):
spec.worldbody.add_geom(name="test_ground", type=mujoco.mjtGeom.mjGEOM_PLANE,
size=[10, 10, .1], group=0)
model = spec.compile()
data = mujoco.MjData(model)
mujoco.mj_forward(model, data)
site = model.site("sole_0").id
geom = np.array([-1], dtype=np.int32)
mujoco.mj_ray(model, data, data.site_xpos[site], np.array([0., 0., -1.]),
np.array([1, 0, 0, 0, 0, 0], dtype=np.uint8), 1,
int(model.site_bodyid[site]), geom)
assert geom[0] >= 0
return model.geom(int(geom[0])).name
@pytest.mark.parametrize("visual_only", [False, True])
def test_terrain_rays_exclude_other_robot_geometry_without_changing_collision_masks(site_robot, visual_only):
if visual_only:
source_xml = ET.parse(site_robot.model_path)
blocker = source_xml.find(".//geom[@name='robot_ray_blocker']")
blocker.set("contype", "0")
blocker.set("conaffinity", "0")
source_xml.write(site_robot.model_path)
original = site_robot.model_path.read_bytes()
source = mujoco.MjSpec.from_file(str(site_robot.model_path))
assert _ray_from_first_site(source.copy()) == "robot_ray_blocker" # Detection control.
isolated = _entity_spec(site_robot.model_path, site_robot)
assert _ray_from_first_site(isolated.copy()) == "test_ground"
before, after = source.compile(), isolated.compile()
colliding = (before.geom_contype | before.geom_conaffinity) != 0
assert np.all(before.geom_group[colliding] == 0)
assert np.all(after.geom_group[colliding] == 3)
blocker_id = before.geom("robot_ray_blocker").id
assert before.geom_group[blocker_id] == 0
assert after.geom_group[blocker_id] == (1 if visual_only else 3)
for field in ("geom_contype", "geom_conaffinity", "geom_friction", "geom_size", "geom_pos"):
np.testing.assert_array_equal(getattr(after, field), getattr(before, field))
assert site_robot.model_path.read_bytes() == original
def test_site_biped_config_has_force_terrain_posture_and_clearance_terms(site_robot, neutral_robot):
cfg = env_cfg(site_robot)
support = next(sensor for sensor in cfg.scene.sensors if sensor.name == "support_contacts")
assert set(support.fields) == {"found", "force"}
assert support.track_air_time and support.reduce == "netforce"
height = next(sensor for sensor in cfg.scene.sensors if sensor.name == "sole_height")
assert height.include_geom_groups == (0,)
assert {"pose", "single_support", "foot_clearance", "swing_quality", "foot_slip",
"soft_landing", "angular_momentum"} <= cfg.rewards.keys()
assert cfg.rewards["pose"].params["std_walking"] == {"leg_0": .15, "leg_1": .55}
plain = env_cfg(neutral_robot)
assert "pose" in plain.rewards and "single_support" in plain.rewards
assert "sole_height" not in {sensor.name for sensor in plain.scene.sensors}
assert "foot_clearance" not in plain.rewards and "swing_quality" not in plain.rewards
@pytest.mark.parametrize("with_sites", [True, False])
def test_native_two_environment_biped_terms_execute_and_reset_peaks(site_robot, neutral_robot, with_sites):
from mjlab.envs import ManagerBasedRlEnv
from mjlab.sim import get_simulation_cls, set_simulation_cls
from mjrl.backend import native_sim
from mjrl.backend.resolve import resolve
from mjrl.backend.select import use_backend
saved_cls, threads = get_simulation_cls(), native_sim._DEFAULT_NTHREAD
use_backend(resolve(backend="native", device="cpu", num_envs=2))
env = None
try:
cfg = env_cfg(site_robot if with_sites else neutral_robot, play=True)
cfg.scene.num_envs = 2
cfg.seed = 7
env = ManagerBasedRlEnv(cfg, device="cpu")
obs, _ = env.reset()
assert obs["actor"].shape[0] == 2
env.command_manager.get_command("twist")[:] = torch.tensor([.2, 0., 0.])
saw_contact_force = False
for _ in range(8):
obs, reward, _, _, _ = env.step(torch.full(env.action_space.shape, .3))
assert torch.isfinite(obs["actor"]).all() and torch.isfinite(reward).all()
if with_sites:
contact = env.scene["support_contacts"]
assert contact.primary_names == ["contact_0", "contact_1"]
assert contact.data.force is not None and torch.isfinite(contact.data.force).all()
saw_contact_force |= bool(contact.data.force.abs().max() > 0)
height = env.scene["sole_height"].data
assert height.heights.shape == (2, 2)
assert (height.distances >= 0).all()
torch.testing.assert_close(height.hit_pos_w[..., 2], torch.zeros_like(height.hit_pos_w[..., 2]), atol=1e-5, rtol=0)
torch.testing.assert_close(height.heights, height.frame_pos_w[..., 2], atol=1e-5, rtol=0)
if with_sites:
assert saw_contact_force
pose = env.reward_manager.get_term_cfg("pose").func
torch.testing.assert_close(pose.std_walking, torch.tensor([.15, .55]))
swing = env.reward_manager.get_term_cfg("swing_quality").func
swing.peak_heights[:] = torch.tensor([[.1, .2], [.3, .4]])
env._reset_idx(torch.tensor([0], dtype=torch.long))
torch.testing.assert_close(swing.peak_heights, torch.tensor([[0., 0.], [.3, .4]]))
env.reset()
assert torch.count_nonzero(swing.peak_heights) == 0
finally:
if env is not None:
env.close()
set_simulation_cls(saved_cls)
native_sim._DEFAULT_NTHREAD = threads
+7 -3
View File
@@ -78,6 +78,10 @@ LOCK = {
"56fcf2bf9e52204e02669bb10dd37c586f7d1b5b3160fbb5538ead6dde44a1bd",
"rl/mjrl/tasks/curriculum.py":
"e34c9dbf8a6ef7a93ad10d4b68687db128b527a3f8651bbdab619c36a20075d1",
"rl/mjrl/tasks/biped.py":
"f467a11b9ae5460c03632c10548cde5f24bcabf30ee8d21f1a7cdf7d045ad192",
"rl/mjrl/tasks/commands.py":
"d1bd60a38e7f4efd0ecfa8cd23212d0ad32eb8e8b67cb37aed93919915ba2f05",
"rl/mjrl/tasks/mdp.py":
"debf40561ec0a8b51deea56b2aa8fe8b3f3b24a07a2a119039a07cc0cb7678b1",
"rl/mjrl/tasks/operator.py":
@@ -89,13 +93,13 @@ LOCK = {
"tasks/registry.py":
"42285516f8365b21fc6b1a6b19dfa126cf3f7331cc8a3c00f855ffa51c4ec922",
"tasks/robot_spec.py":
"f0fc03fdc704e8fb1a2df618fe0c40224bb6c7812e514e6fc188b28c95acfcf5",
"bda823beaa1b0d9be11c0df70422acc0ff59a49b0ead6d8cb5eab6016a41730d",
"tasks/templates/Biped_Template/AGENTS.md":
"91a6778d0cffc055e3d076df147b9e064c332c19c2beb8fe697c9260c479ee4d",
"tasks/templates/Biped_Template/__init__.py":
"9dbf382a9f5d58076fc9c81310fd69881ec550f4b391e0548c14df891ddeb6ad",
"tasks/templates/Biped_Template/env_cfg.py":
"8cfc44c601ff9db329d5ff60783c89731a043f4389c183000224681904d7ce1b",
"5520fcee6194d9e8cb7c98a3cc940a41e85b07572dff1d83117ecf204626e181",
"tasks/templates/Multipod_Template/AGENTS.md":
"8f51e0807e2ce4749cf0541d3863adf7652eb70a0918617cfb311544be8b4783",
"tasks/templates/Multipod_Template/__init__.py":
@@ -117,7 +121,7 @@ LOCK = {
"tasks/templates/__init__.py":
"e426b202e0457053ae2948d9194cd80e0a3149ab2b972e94b2c81396f1f89797",
"tasks/templates/_locomotion.py":
"7e25c2985b77a6ed8dfb296745ecbe98ee23fc992127967319308d539958018f",
"0b1703e7dbdbb50f76712a87116e5e44627946265b0144308b399df3a008724b",
}
+13
View File
@@ -31,6 +31,19 @@ def test_saved_allocations_restore_and_respect_scene_and_cli(tmp_path):
assert (native.njmax, native.nconmax) == (None, None)
def test_effective_epa_scratch_capacity_is_recorded(tmp_path):
import json
sim = SimpleNamespace(
cfg=SimpleNamespace(njmax=64, nconmax=48),
wp_data=SimpleNamespace(njmax=64, naconmax=96, nworld=2),
epa_horizon_capacity=128,
)
write_warp_allocation(tmp_path, sim)
record = json.loads((tmp_path / FILENAME).read_text())
assert record["effective"]["epa_horizon"] == 128
def test_legacy_checkpoint_falls_back_and_invalid_record_fails(tmp_path):
checkpoint = tmp_path / "model_10.pt"
sim = SimpleNamespace(njmax=100, nconmax=80)
+90
View File
@@ -0,0 +1,90 @@
"""EPA scratch grows before graph capture; collision failures remain fatal."""
import numpy as np
import pytest
wp = pytest.importorskip("warp")
mujoco = pytest.importorskip("mujoco")
pytest.importorskip("mujoco_warp")
from mjlab.sim import SimulationCfg
from mjrl.backend.warp_sim import (
EPA_HORIZON_CAPACITY,
CheckedWarpSimulation,
_ensure_epa_horizon_capacity,
)
from mujoco_warp._src import collision_convex, collision_flex
from mujoco_warp._src.types import OverflowType
def test_epa_shim_preserves_larger_upstream_capacity_and_rejects_unknown_allocator(monkeypatch):
monkeypatch.setattr(collision_convex, "MJ_MAX_EPAHORIZON", 256)
monkeypatch.setattr(collision_flex, "MJ_MAX_EPAHORIZON", 24)
assert _ensure_epa_horizon_capacity() == 256
assert collision_flex.MJ_MAX_EPAHORIZON == 256
monkeypatch.delattr(collision_flex, "MJ_MAX_EPAHORIZON")
with pytest.raises(RuntimeError, match="Unsupported MuJoCo Warp EPA scratch allocator"):
_ensure_epa_horizon_capacity()
def test_epa_host_allocation_uses_capacity_and_overflow_stays_fatal(monkeypatch):
monkeypatch.setattr(collision_convex, "MJ_MAX_EPAHORIZON", 24)
monkeypatch.setattr(collision_flex, "MJ_MAX_EPAHORIZON", 24)
allocations = []
original_empty = wp.empty
def record_empty(*args, **kwargs):
allocations.append(kwargs.get("shape"))
return original_empty(*args, **kwargs)
monkeypatch.setattr(wp, "empty", record_empty)
model = mujoco.MjModel.from_xml_string("""<mujoco><worldbody>
<geom type="box" size=".1 .1 .1"/>
<body pos="0 0 .15"><freejoint/><geom type="box" size=".1 .1 .1"/></body>
</worldbody></mujoco>""")
sim = CheckedWarpSimulation(1, SimulationCfg(), model, "cpu")
assert sim.epa_horizon_capacity == EPA_HORIZON_CAPACITY == 128
assert collision_flex.MJ_MAX_EPAHORIZON == 128
sim.forward()
sim.sense()
assert (sim.wp_data.naccdmax, 128) in allocations
assert sim.wp_data.nacon.numpy()[0] > 0 # Contacts are still computed.
sim.wp_data.overflow.assign(np.array([int(OverflowType.EPA_HORIZON)], dtype=np.int32))
sim.reset() # Preserve an overflow even if environment reset clears its flag.
with pytest.raises(RuntimeError, match="EPA horizon scratch capacity: 128") as failure:
sim.sense()
assert "--warp-max-contacts" not in str(failure.value)
assert "--warp-max-constraints" not in str(failure.value)
def test_actual_epa_horizon_negative_control_and_enlarged_scratch_agree():
# Upstream 3.11.0's test_box_box_horizon regression exercises a 13-edge
# horizon. Reuse its public-distribution test harness, not a mock kernel.
from mujoco_warp import test_data
from mujoco_warp._src.collision_gjk_test import _geom_dist
with wp.ScopedDevice("cpu"):
_, _, model, data = test_data.fixture(xml="""<mujoco><worldbody>
<geom size=".025 .025 .025" type="box"/>
<geom size=".025 .025 .025" type="box"/>
</worldbody></mujoco>""")
geometry = dict(
pos1=wp.vec3(.065118454396725, -.125125020742416, .124963559210300),
mat1=wp.mat33(.996357858181000, .085266821086407, -.000942531623878,
-.085266284644604, .996358215808868, .000591202871874,
.000989508931525, -.000508683384396, .999999582767487),
pos2=wp.vec3(.065104484558105, -.124979749321938, .174992129206657),
mat2=wp.mat33(.996556758880615, -.082913912832737, -.000453041866422,
.082915119826794, .996536433696747, .006357696373016,
-.000075668765930, -.006373368669301, .999979794025421),
)
results = {}
for capacity in (5, 24, EPA_HORIZON_CAPACITY):
overflow = wp.zeros(1, dtype=int)
results[capacity] = _geom_dist(model, data, 0, 1, horizon_size=capacity,
warn_overflow=False, overflow_out=overflow, **geometry)
assert bool(int(overflow.numpy()[0]) & OverflowType.EPA_HORIZON) == (capacity == 5)
assert results[128][0] == pytest.approx(-.00011578822, abs=1e-6)
assert results[128][1] > 0
for expected, actual in zip(results[24], results[128], strict=True):
np.testing.assert_allclose(actual, expected, atol=1e-8, rtol=0)
+231
View File
@@ -0,0 +1,231 @@
#!/usr/bin/env python3
"""Measure a two-foot biped's actions, rewards and complete swings without a GUI."""
from __future__ import annotations
import argparse
from dataclasses import asdict
import json
from pathlib import Path
from types import SimpleNamespace
import numpy as np
import torch
import tasks
from mjrl.backend.select import use_backend
from mjrl.replay import configure_velocity_replay
def quantiles(values):
values = np.asarray(values, dtype=float)
if not values.size:
return None
return dict(zip(('min', 'p25', 'median', 'p75', 'max'),
np.quantile(values, [0., .25, .5, .75, 1.]).tolist()))
def contact_events(contacts, heights, dones, dt):
"""Describe observed full swings, never joining episodes across a reset."""
contacts, dones = np.asarray(contacts, dtype=bool), np.asarray(dones, dtype=bool)
events, periods = [], []
counts = np.zeros(contacts.shape[1:], dtype=int)
for env in range(contacts.shape[1]):
for foot in range(contacts.shape[2]):
armed, start, last_landing = False, None, None
for step in range(len(contacts)):
if dones[step, env]:
armed, start, last_landing = False, None, None
continue
if contacts[step, env, foot]:
if start is not None:
duration = (step - start) * dt
peak = float(np.max(heights[start:step, env, foot]))
events.append((duration, peak))
if duration >= .04 - 1e-10:
counts[env, foot] += 1
if last_landing is not None:
periods.append((step - last_landing) * dt)
last_landing = step
armed, start = True, None
elif armed and start is None:
start = step
duration = [event[0] for event in events]
peak = [event[1] for event in events]
return {
'completed_swings_per_env_foot': counts.tolist(),
'contact_event_summary': {
'complete_event_count': len(events),
'airtime_s': quantiles(duration), 'peak_height_m': quantiles(peak),
'same_foot_landing_period_s': quantiles(periods),
'events_airtime_ge_0_1s_and_height_ge_0_02m': sum(
air >= .1 - 1e-10 and height >= .02 for air, height in events),
'description': 'All observed grounded-airborne-grounded events, including chatter; '
'threshold counts are descriptive, not natural gait acceptance.',
},
}
def summarize_samples(sample, dt, names, limits, reward_names, command):
"""Exclude auto-reset frames and cross-reset differences from all summaries.
Environment step returns post-reset states but pre-reset terminal rewards.
Neither is treated as an aligned physical sample on a reset frame.
"""
valid = ~sample['dones'].astype(bool)
if not valid.any():
raise ValueError('No non-reset samples remain for policy diagnostics')
pairs = valid[1:] & valid[:-1]
joints = {}
for j, name in enumerate(names):
joints[name] = {key: {'min': float(sample[key][..., j][valid].min()),
'max': float(sample[key][..., j][valid].max()),
'std': float(sample[key][..., j][valid].std())}
for key in ('action', 'target', 'qpos', 'torque')}
speed = np.diff(sample['target'][..., j], axis=0)[pairs] / dt
joints[name]['target_speed_rms_rad_s'] = (
float(np.sqrt(np.mean(speed ** 2))) if speed.size else None)
joints[name]['torque_saturation_fraction'] = float(
(np.abs(sample['torque'][..., j][valid]) >= .99 * limits[j]).mean())
# Per-environment excursion excludes different episode/home offsets
# from masquerading as a larger physical joint motion.
for key in ('target', 'qpos'):
excursions = [np.diff(np.quantile(sample[key][:, e, j][valid[:, e]], [.05, .95]))[0]
for e in range(valid.shape[1]) if valid[:, e].any()]
joints[name][key]['per_env_p95_p05_excursion_rad'] = excursions
counts = sample['contacts'].sum(-1)[valid]
report = {
'valid_samples': int(valid.sum()), 'excluded_reset_samples': int((~valid).sum()),
'valid_target_difference_samples': int(pairs.sum()),
'mean_velocity': sample['velocity'][valid].mean(0).tolist(),
'mean_velocity_axes': ['vx', 'vy', 'vz'],
'mean_abs_xy_error': np.abs(sample['velocity'][valid][..., :2] - command[:2]).mean(0).tolist(),
'single_support_fraction': float((counts == 1).mean()),
'flight_fraction': float((counts == 0).mean()),
'double_support_fraction': float((counts == 2).mean()),
'max_sole_height': sample['height'][valid].max(0).tolist(),
'reward_rate': dict(zip(reward_names, sample['rewards'][valid].mean(0).tolist())),
'joints': joints,
**contact_events(sample['contacts'], sample['height'], sample['dones'], dt),
}
if 'root_height' in sample:
report['mean_height'] = float(sample['root_height'][valid].mean())
report['root_height_m'] = quantiles(sample['root_height'][valid])
report['mean_root_link_pos_w'] = sample['root_link_pos_w'][valid].mean(0).tolist()
if 'angular_velocity' in sample:
angular = sample['angular_velocity'][valid]
report['mean_angular_velocity'] = angular.mean(0).tolist()
report['mean_yaw_tracking_error'] = float(np.abs(angular[:, 2] - command[2]).mean())
if 'sole_velocity_w' in sample:
stance = sample['contacts'].astype(bool) & valid[..., None]
speeds = np.linalg.norm(sample['sole_velocity_w'][..., :2], axis=-1)
report['stance_sole_horizontal_speed_m_s'] = quantiles(speeds[stance])
return report
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--task', required=True)
parser.add_argument('--checkpoint', type=Path, required=True)
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--command', type=float, nargs=3, default=(.3, 0, 0))
parser.add_argument('--steps', type=int, default=750)
parser.add_argument('--num-envs', type=int, default=4)
args = parser.parse_args()
if args.steps < 10 or args.num_envs < 1 or not np.isfinite(args.command).all():
parser.error('Use at least 10 steps, positive environment count and finite commands')
# Tiny CPU replay batches should not spawn a large BLAS pool beside the
# native physics workers, especially when comparing several commands.
torch.set_num_threads(1)
torch.manual_seed(42)
np.random.seed(42)
use_backend(SimpleNamespace(backend='native', cpu_threads=4, strip_visual=True))
from mjlab.envs import ManagerBasedRlEnv
from mjlab.rl import RslRlVecEnvWrapper
from mjlab.rl.runner import MjlabOnPolicyRunner
cfg = tasks.load_env_cfg(args.task, play=True)
cfg.seed = 42
train_cfg = tasks.load_env_cfg(args.task)
saved = torch.load(args.checkpoint, map_location='cpu', weights_only=False)
configure_velocity_replay(cfg, train_cfg, saved, args.command)
for name, group in cfg.observations.items():
if name in train_cfg.observations:
group.enable_corruption = train_cfg.observations[name].enable_corruption
cfg.scene.num_envs = args.num_envs
env = ManagerBasedRlEnv(cfg=cfg, device='cpu')
try:
agent_cfg = tasks.load_agent_cfg(args.task)
wrapped = RslRlVecEnvWrapper(env, clip_actions=agent_cfg.clip_actions)
runner_cls = tasks.load_runner_cls(args.task) or MjlabOnPolicyRunner
runner = runner_cls(wrapped, asdict(agent_cfg), device='cpu')
runner.load(str(args.checkpoint), load_cfg={'actor': True}, strict=True, map_location='cpu')
policy = runner.get_inference_policy(device='cpu')
obs = wrapped.get_observations()
robot = env.scene['robot']
action_term = env.action_manager.get_term('joint_pos')
model = env.sim.mj_model
motor_ids = [next(i for i in range(model.nu)
if model.actuator_trnid[i, 0] == model.joint(f'robot/{name}').id)
for name in action_term._target_names]
if not np.allclose(model.actuator_gear[motor_ids, 0], 1.0):
raise ValueError('Diagnostic requires direct unit-gear joint motors')
limits = np.abs(model.actuator_forcerange[motor_ids]).max(axis=1)
sole_names = train_cfg.rewards['foot_clearance'].params['asset_cfg'].site_names
sole_ids, _ = robot.find_sites(sole_names, preserve_order=True)
records = {key: [] for key in (
'action', 'target', 'qpos', 'torque', 'rewards', 'velocity',
'contacts', 'height', 'dones', 'root_link_pos_w', 'root_height', 'angular_velocity',
'sole_position_w', 'sole_velocity_w',
)}
with torch.inference_mode():
for _ in range(args.steps):
actions = policy(obs)
obs, _, dones, _ = wrapped.step(actions)
sensor = env.scene['support_contacts'].data
touching = (sensor.found > 0).reshape(args.num_envs, 2, -1).any(-1)
values = {
'action': actions, 'target': action_term._processed_actions,
'qpos': robot.data.joint_pos[:, action_term._target_ids],
'torque': env.sim.data.actuator_force[:, motor_ids],
'rewards': env.reward_manager._step_reward,
'velocity': robot.data.root_link_lin_vel_b,
'angular_velocity': robot.data.root_link_ang_vel_b,
'contacts': touching, 'height': env.scene['sole_height'].data.heights,
'dones': dones, 'root_link_pos_w': robot.data.root_link_pos_w,
'root_height': robot.data.root_link_pos_w[:, 2] - env.scene.env_origins[:, 2],
'sole_position_w': robot.data.site_pos_w[:, sole_ids],
'sole_velocity_w': robot.data.site_lin_vel_w[:, sole_ids],
}
for key, value in values.items():
records[key].append(value.detach().cpu().numpy().copy())
arrays = {key: np.stack(value) for key, value in records.items()}
warmup = min(100, args.steps // 5)
sample = {key: value[warmup:] for key, value in arrays.items()}
report = {
'task': args.task, 'checkpoint': str(args.checkpoint.resolve()), 'seed': 42,
'backend': 'native', 'observation_noise': True, 'command': args.command,
'command_axes': ['vx', 'vy', 'yaw_rate'],
'num_envs': args.num_envs, 'seconds': args.steps * env.step_dt,
'warmup_seconds': warmup * env.step_dt,
'episode_resets': int(arrays['dones'].sum()),
'policy_dt_s': env.step_dt,
**summarize_samples(sample, env.step_dt, action_term._target_names, limits,
env.reward_manager.active_terms, np.asarray(args.command)),
'limitations': [
'Auto-reset frames and adjacent target differences are excluded from summaries.',
'Height is root Z above the environment origin; it assumes the flat terrain task.',
'Torque is sampled at policy rate; native verification samples every physics step.',
'Air phases >=40 ms are counted; ground-phase duration is not gated here.',
'Contact cycles and velocity alone do not establish natural gait or full control acceptance.',
],
}
args.out.parent.mkdir(parents=True, exist_ok=True)
args.out.write_text(json.dumps(report, indent=2, allow_nan=False) + '\n')
np.savez_compressed(args.out.with_suffix('.npz'), **arrays)
print(json.dumps({key: value for key, value in report.items() if key != 'joints'}, indent=2))
finally:
env.close()
if __name__ == '__main__':
main()
+362
View File
@@ -0,0 +1,362 @@
"""Supplement native verification with measured foot contact cycles and motion.
Defaults require two completed stance/swing cycles per foot after a 2 s warmup,
with each phase lasting at least 0.04 s. A contact requires 1 N normal load on
the named ground. Linear commands require 0.05 m net commanded-direction travel
and 0.02 m/s mean speed; yaw requires 0.1 rad turn and 0.05 rad/s mean yaw rate.
These are explicit stepping-evidence gates, not a replacement for native physics
and command acceptance. Unloading contacts does not by itself prove clearance.
Optional --foot-sites names, paired with --feet, add sole-marker height and
contact-slip measurements above a static horizontal plane. These descriptive
measurements do not add a naturalness pass/fail criterion.
"""
from __future__ import annotations
import argparse
from dataclasses import dataclass, field
import hashlib
import json
import math
from pathlib import Path
import mujoco
import numpy as np
from mjrl.onboarding._physics import contact_groups, contact_loads, object_id, root_body, warnings
from mjrl.platform.bundle import safe_path
from mjrl.platform.policy import OnnxController
@dataclass
class ContactCycles:
"""Count complete observed air phases; discard a warmup-truncated swing."""
touching: bool | None = None
since: float = 0.0
takeoff: float | None = None
takeoffs: int = 0
landings: int = 0
contact_samples: int = 0
samples: int = 0
air_times: list[float] = field(default_factory=list)
stance_times: list[float] = field(default_factory=list)
last_landing: float | None = None
stride_times: list[float] = field(default_factory=list)
def sample(self, touching: bool, elapsed: float) -> None:
self.samples += 1
self.contact_samples += int(touching)
if self.touching is None:
self.touching, self.since = touching, elapsed
elif touching != self.touching:
if touching:
self.landings += 1
if self.last_landing is not None:
self.stride_times.append(elapsed - self.last_landing)
self.last_landing = elapsed
if self.takeoff is not None:
self.air_times.append(elapsed - self.takeoff)
self.takeoff = None
else:
self.takeoffs += 1
self.stance_times.append(elapsed - self.since)
self.takeoff = elapsed
self.touching, self.since = touching, elapsed
def result(self, minimum_phase_s: float, minimum_cycles: int) -> dict:
swings = sum(t + 1e-9 >= minimum_phase_s for t in self.air_times)
stances = sum(t + 1e-9 >= minimum_phase_s for t in self.stance_times)
return {
"takeoffs": self.takeoffs, "landings": self.landings,
"completed_air_times_s": self.air_times,
"completed_stance_times_s": self.stance_times,
"landing_to_landing_stride_times_s": self.stride_times,
"qualifying_swings": swings, "qualifying_stances": stances,
"contact_fraction": self.contact_samples / self.samples if self.samples else None,
"passed": swings >= minimum_cycles and stances >= minimum_cycles,
}
@dataclass
class SoleMeasurements:
"""Measure complete swing peaks and slip during load-bearing samples."""
touching: bool | None = None
swing_peak: float | None = None
swing_peaks: list[float] = field(default_factory=list)
contact_samples: int = 0
contact_speed_sum: float = 0.0
contact_speed_squared_sum: float = 0.0
def sample(self, touching: bool, height: float, horizontal_speed: float) -> None:
if touching:
self.contact_samples += 1
self.contact_speed_sum += horizontal_speed
self.contact_speed_squared_sum += horizontal_speed ** 2
if self.touching is False and self.swing_peak is not None:
self.swing_peaks.append(self.swing_peak)
self.swing_peak = None
elif self.touching is True:
self.swing_peak = height
elif self.swing_peak is not None:
self.swing_peak = max(self.swing_peak, height)
self.touching = touching
def result(self, physics_dt: float) -> dict:
count = self.contact_samples
return {
"completed_swing_peak_heights_m": self.swing_peaks,
"mean_completed_swing_peak_height_m": (
sum(self.swing_peaks) / len(self.swing_peaks) if self.swing_peaks else None
),
"contact_samples": count,
"mean_contact_slip_speed_m_s": self.contact_speed_sum / count if count else None,
"rms_contact_slip_speed_m_s": (
math.sqrt(self.contact_speed_squared_sum / count) if count else None
),
"integrated_contact_slip_distance_m": self.contact_speed_sum * physics_dt,
}
def foot_site_ids(model: mujoco.MjModel, feet: list[str], sites: list[str]) -> dict[str, int]:
"""Require one unique marker attached directly to each named foot body."""
if len(sites) != len(feet) or len(set(sites)) != len(sites) or len(set(feet)) != len(feet):
raise ValueError("foot-sites must provide one unique site per unique foot body")
result = {}
for foot, site in zip(feet, sites, strict=True):
body_id = object_id(model, mujoco.mjtObj.mjOBJ_BODY, foot)
site_id = object_id(model, mujoco.mjtObj.mjOBJ_SITE, site)
if model.site_bodyid[site_id] != body_id:
raise ValueError(f"foot site {site!r} must be attached to foot body {foot!r}")
result[foot] = site_id
return result
def horizontal_ground_height(model: mujoco.MjModel, data: mujoco.MjData, ground: int) -> float:
"""Validate the restricted geometry used by sole-height measurements."""
if model.geom_type[ground] != mujoco.mjtGeom.mjGEOM_PLANE:
raise ValueError("foot-site height measurement requires a plane ground geom")
if model.body_weldid[model.geom_bodyid[ground]] != 0:
raise ValueError("foot-site height measurement requires a static ground plane")
normal = data.geom_xmat[ground].reshape(3, 3)[:, 2]
if not np.allclose(normal, (0., 0., 1.), atol=1e-8, rtol=0.):
raise ValueError("foot-site height measurement requires an upward horizontal ground plane")
return float(data.geom_xpos[ground, 2])
def _positive(value: str) -> float:
number = float(value)
if not math.isfinite(number) or number <= 0:
raise argparse.ArgumentTypeError("must be a finite positive number")
return number
def measure(args) -> dict:
directory = args.export.resolve(strict=True)
model_path = directory / "robot.xml"
config = json.loads((directory / "controller.json").read_text())
if config.get("kind") != "rl_onnx":
raise ValueError("export must contain an rl_onnx controller")
if args.warmup >= args.seconds or args.warmup < 0 or not math.isfinite(args.warmup):
raise ValueError("warmup must be finite and within [0, seconds)")
if len(args.feet) < 2 or args.min_cycles < 1:
raise ValueError("at least two foot bodies and one complete cycle are required")
if not np.isfinite(args.command).all():
raise ValueError("command must contain finite values")
model = mujoco.MjModel.from_xml_path(str(model_path))
forbidden = int(mujoco.mjtDisableBit.mjDSBL_CONTACT | mujoco.mjtDisableBit.mjDSBL_CONSTRAINT)
if model.opt.disableflags & forbidden:
raise ValueError("contact and constraints must be enabled")
model.opt.disableflags |= mujoco.mjtDisableBit.mjDSBL_AUTORESET
root = root_body(model, args.root)
ground = object_id(model, mujoco.mjtObj.mjOBJ_GEOM, args.ground)
if model.body_rootid[model.geom_bodyid[ground]] == root:
raise ValueError("ground must be outside the robot")
_, feet = contact_groups(model, {"foot_bodies": args.feet}, root)
site_names = getattr(args, "foot_sites", None)
sites = foot_site_ids(model, args.feet, site_names) if site_names is not None else {}
controller = OnnxController(model, {**config, "root_body": args.root}, directory)
ratio = 1.0 / (controller.control_hz * model.opt.timestep)
substeps = round(ratio)
if substeps < 1 or abs(ratio - substeps) > 1e-6:
raise ValueError("physics rate must be a whole multiple of policy control rate")
data = mujoco.MjData(model)
key = object_id(model, mujoco.mjtObj.mjOBJ_KEY, args.keyframe)
mujoco.mj_resetDataKeyframe(model, data, key)
controller.reset(data)
mujoco.mj_forward(model, data)
ground_height = horizontal_ground_height(model, data, ground) if sites else None
initial_position = data.xpos[root].copy()
states = {name: ContactCycles() for name in feet}
soles = {name: SoleMeasurements() for name in sites}
contact_events = []
sole_velocity = np.zeros(6)
command = dict(zip(("lin_vel_x", "lin_vel_y", "ang_vel_z"), args.command, strict=True))
velocity_sum = np.zeros(6)
motion = np.zeros(6)
samples = 0
peak_tilt = peak_drop = 0.0
peak_load = dict.fromkeys(feet, 0.0)
window_position = window_rotation = previous_yaw = None
yaw_change = 0.0
finite = True
completed = 0
steps = math.ceil(args.seconds / model.opt.timestep)
for index in range(steps):
if index % substeps == 0:
controller.step(data, command)
else:
controller.apply(data)
if not np.isfinite(data.ctrl).all():
finite = False
break
mujoco.mj_step(model, data)
completed = index + 1
if not all(np.isfinite(x).all() for x in (data.qpos, data.qvel, data.qacc)):
finite = False
break
# These derived poses/velocities and solved contacts belong to the
# pre-integration substep. Keep their matching timestamp; an extra
# mj_forward would alter solver warm starts and the replay trajectory.
rotation = data.xmat[root].reshape(3, 3)
peak_tilt = max(peak_tilt, float(np.arccos(np.clip(rotation[2, 2], -1, 1))))
peak_drop = max(peak_drop, float(initial_position[2] - data.xpos[root, 2]))
elapsed = index * model.opt.timestep
if elapsed + 1e-9 < args.warmup:
continue
yaw = math.atan2(rotation[1, 0], rotation[0, 0])
if window_position is None:
window_position = data.xpos[root].copy()
window_rotation = rotation.copy()
previous_yaw = yaw
yaw_change += math.atan2(math.sin(yaw - previous_yaw), math.cos(yaw - previous_yaw))
previous_yaw = yaw
loads, _ = contact_loads(model, data, root, ground)
landed, took_off = [], []
for name, geoms in feet.items():
load = sum(loads.get(gid, 0.0) for gid in geoms)
peak_load[name] = max(peak_load[name], load)
touching = load >= args.min_contact_force
previous_contact = states[name].touching
if previous_contact is not None and touching != previous_contact:
(landed if touching else took_off).append(name)
states[name].sample(touching, elapsed)
if name in sites:
site = sites[name]
mujoco.mj_objectVelocity(
model, data, mujoco.mjtObj.mjOBJ_SITE, site, sole_velocity, 0,
)
soles[name].sample(
touching, float(data.site_xpos[site, 2] - ground_height),
float(np.linalg.norm(sole_velocity[3:5])),
)
if landed or took_off:
contact_events.append({"time_s": elapsed, "landed": landed, "took_off": took_off})
mujoco.mj_objectVelocity(model, data, mujoco.mjtObj.mjOBJ_XBODY, root, motion, 1)
velocity_sum += motion
samples += 1
if not samples:
raise ValueError("simulation produced no evaluation samples")
mean = velocity_sum / samples
displacement = data.xpos[root] - window_position
local_displacement = window_rotation.T @ displacement
direction = np.array(args.command[:2], dtype=float)
speed = float(np.linalg.norm(direction))
motion_checks = {}
if speed > 0:
direction /= speed
motion_checks["commanded_linear_travel"] = {
"displacement_m": float(local_displacement[:2] @ direction),
"minimum_m": args.min_distance,
"mean_speed_m_s": float(mean[3:5] @ direction),
"minimum_m_s": args.min_speed,
"passed": bool(local_displacement[:2] @ direction >= args.min_distance
and mean[3:5] @ direction >= args.min_speed),
}
if args.command[2] != 0:
sign = math.copysign(1, args.command[2])
motion_checks["commanded_yaw_travel"] = {
"yaw_change_rad": yaw_change * sign, "minimum_rad": args.min_yaw_angle,
"mean_yaw_rate_rad_s": float(mean[2]) * sign,
"minimum_rad_s": args.min_yaw_rate,
"passed": yaw_change * sign >= args.min_yaw_angle
and float(mean[2]) * sign >= args.min_yaw_rate,
}
engine_warnings = warnings(data)
foot_results = {name: {**state.result(args.min_phase, args.min_cycles),
"peak_normal_load_n": peak_load[name]}
for name, state in states.items()}
for foot, sole in soles.items():
foot_results[foot]["sole_measurements"] = {
"site": model.site(sites[foot]).name, **sole.result(model.opt.timestep),
}
checks = {
"finite_completed_run": finite and completed == steps,
"no_engine_warnings": not engine_warnings,
"root_tilt": peak_tilt <= args.max_tilt,
"repeated_foot_cycles": all(result["passed"] for result in foot_results.values()),
"commanded_motion": bool(motion_checks) and all(c["passed"] for c in motion_checks.values()),
}
files = ["robot.xml", "controller.json", config["layout"], config["policy"]]
return {
"schema": "mjrl.policy-gait-diagnostic/1", "export": str(directory),
"source_sha256": {name: hashlib.sha256(safe_path(directory, name).read_bytes()).hexdigest()
for name in files},
"mujoco_version": mujoco.__version__, "backend": "native", "observation_noise": False,
"root_body": args.root, "ground_geom": args.ground, "keyframe": args.keyframe,
"command": command, "physics_dt_s": model.opt.timestep,
"control_hz": controller.control_hz, "completed_steps": completed,
"seconds": completed * model.opt.timestep, "evaluation_start_s": args.warmup,
"samples": samples, "minimum_cycles_per_foot": args.min_cycles,
"minimum_stance_and_swing_s": args.min_phase,
"minimum_contact_force_n": args.min_contact_force, "maximum_tilt_rad": args.max_tilt,
"feet": foot_results, "displacement_world_m": displacement.tolist(),
"contact_transition_sequence": contact_events,
"sole_height_ground_z_m": ground_height,
"displacement_initial_body_m": local_displacement.tolist(),
"mean_body_linear_velocity_m_s": mean[3:].tolist(),
"mean_body_angular_velocity_rad_s": mean[:3].tolist(),
"yaw_change_rad": yaw_change, "peak_tilt_rad": peak_tilt,
"peak_root_drop_m": peak_drop, "warnings": engine_warnings,
"motion_checks": motion_checks, "checks": checks,
"stepping_evidence_passed": all(checks.values()),
"limitations": ["Supplementary contact-cycle evidence; native verification remains required.",
"Contact unloading does not establish geometric foot clearance.",
"Optional site heights describe sole markers, not the lowest foot edge.",
"Slip and swing heights are descriptive; no naturalness threshold is imposed.",
"Combined turning commands use net travel in the initial body frame."],
}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("export", type=Path)
parser.add_argument("--root", required=True)
parser.add_argument("--feet", nargs="+", required=True)
parser.add_argument("--foot-sites", nargs="+",
help="optional sole sites, paired in the same order as --feet")
parser.add_argument("--ground", required=True)
parser.add_argument("--keyframe", default="init_state")
parser.add_argument("--seconds", type=_positive, default=12.0)
parser.add_argument("--warmup", type=float, default=2.0)
parser.add_argument("--command", nargs=3, type=float, required=True, metavar=("VX", "VY", "YAW"))
parser.add_argument("--min-cycles", type=int, default=2)
parser.add_argument("--min-phase", type=_positive, default=.04)
parser.add_argument("--min-contact-force", type=_positive, default=1.0)
parser.add_argument("--min-distance", type=_positive, default=.05)
parser.add_argument("--min-speed", type=_positive, default=.02)
parser.add_argument("--min-yaw-angle", type=_positive, default=.1)
parser.add_argument("--min-yaw-rate", type=_positive, default=.05)
parser.add_argument("--max-tilt", type=_positive, default=.7)
parser.add_argument("--report", type=Path, required=True)
args = parser.parse_args()
report = measure(args)
args.report.parent.mkdir(parents=True, exist_ok=True)
args.report.write_text(json.dumps(report, indent=2, allow_nan=False) + "\n")
print(json.dumps(report, allow_nan=False))
raise SystemExit(0 if report["stepping_evidence_passed"] else 1)
if __name__ == "__main__":
main()