Files
chenlin c32df70326
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
release: v0.1 generic robot training and application platform
2026-11-05 11:05:01 +08:00

163 lines
6.3 KiB
Python

"""Acceptance coverage for controllers that expose body velocity commands."""
from __future__ import annotations
from collections.abc import Mapping
import mujoco
import numpy as np
from mjrl.controllers.model import joint_actuators, joint_ids, vector
from mjrl.controllers.wheels import WHEEL_AXES, wheel_mixer
from .layout import COMMAND_ORDER
def _active_ranges(ranges: Mapping, axes) -> set[str]:
active = set()
for axis in axes:
if axis not in ranges:
continue
lo, hi = vector(ranges[axis], 2, f"command_ranges.{axis}")
if lo < hi:
active.add(axis)
return active
def _rotation(frames: Mapping) -> np.ndarray:
quat = vector(frames["base"]["quaternion_world_wxyz"], 4, "base quaternion")
rotation = np.empty(9)
mujoco.mju_quat2Mat(rotation, quat)
return rotation.reshape(3, 3)
def _wheel_command(probe: Mapping, inverse: np.ndarray, actuators: np.ndarray) -> np.ndarray:
# Ignore the initial state. Later samples carry saturated wheel commands
# from explicit input, keys or a pad, including the keyboard ramp.
commands = [
inverse @ np.asarray(sample["ctrl"])[actuators]
for sample in probe["samples"]
if sample["physics_step"] > 0
]
if not commands:
return np.zeros(3)
values = np.stack(commands)
return values[np.argmax(abs(values), axis=0), np.arange(3)]
def _isolated(command, axes, required):
# Recovering twist from wheel rates can leave roundoff on zero axes.
moving = [
(axis, name, value) for axis, (name, value) in enumerate(zip(axes, command, strict=True))
if name in required and abs(value) > 1e-10
]
return moving[0] if len(moving) == 1 else None
def _body_window_proves(probe: Mapping, axis: int, command: float, *, exact: bool) -> bool:
metrics = probe.get("velocity_evaluation", {}).get("metrics", {})
stem = "base_angular_velocity" if axis == 2 else "base_velocity"
unit = "rad_s" if axis == 2 else "m_s"
for quantity in ("mean", "tracking_mae"):
metric = metrics.get(f"{stem}_{quantity}_{unit}")
if not metric or metric["passed"] is not True:
continue
target = metric["expected"][axis]
tolerance = metric["tolerance"][axis]
passive = metric["actuation_disabled_observed"]
if (
tolerance is None
or passive is None
or abs(target) <= tolerance
or target * command <= 0
or (exact and not np.isclose(target, command, rtol=1e-6, atol=0))
):
continue
if quantity == "tracking_mae":
if metric["observed"][axis] <= tolerance < passive[axis]:
return True
elif abs(metric["observed"][axis] - target) <= tolerance < abs(passive[axis] - target):
return True
return False
def _wheel_endpoint_proves(report: Mapping, probe: Mapping, axis: int, command: float) -> bool:
names = (
("base_angular_velocity_rad_s",)
if axis == 2 else ("base_displacement_m", "base_velocity_m_s")
)
metrics = probe.get("endpoint_response", {}).get("metrics", {})
for name in names:
metric = metrics.get(name)
if not metric or metric["passed"] is not True or metric.get("actuation_disabled_observed") is None:
continue
frames = report["frames"] if name == "base_displacement_m" else probe["final_frames"]
direction = _rotation(frames)[:, axis]
target, observed, passive = (
float(direction @ vector(metric[field], 3, f"{name}.{field}"))
for field in ("expected", "observed", "actuation_disabled_observed")
)
tolerance = metric["tolerance"]
if (
abs(target) > tolerance
and target * command > 0
and abs(observed - target) <= tolerance < abs(passive - target)
):
return True
return False
def missing_mobility_axes(model, config: Mapping, report: Mapping, layout: Mapping | None = None):
"""Find enabled axes without a commanded and causally measured body response."""
kind = config.get("kind")
if kind == "rl_onnx":
observation = layout["observation"]
if not any(term["name"] in {"commands", "velocity_commands"} for term in observation["terms"]):
return []
order = observation.get("command_order", COMMAND_ORDER)
required = _active_ranges(layout.get("command_ranges", {}).get("twist", {}), order)
covered = set()
for probe in report["probes"]:
command = probe["inputs"].get("command", {})
isolated = _isolated([command.get(name, 0) for name in COMMAND_ORDER], COMMAND_ORDER, required)
if isolated is not None:
axis, name, value = isolated
if _body_window_proves(probe, axis, value, exact=True):
covered.add(name)
return sorted(required - covered)
if kind not in {"differential", "omni"}:
return []
names, matrix, _ = wheel_mixer(config)
ranges = config.get("command_ranges", {})
enabled = _active_ranges(ranges, WHEEL_AXES) | (set(WHEEL_AXES) - ranges.keys())
required = {
axis for axis, column in zip(WHEEL_AXES, matrix.T, strict=True)
if axis in enabled and np.any(column)
}
groups = joint_actuators(model, joint_ids(model, names))
if any(len(group) != 1 for group in groups):
raise ValueError("mobility evidence needs one named actuator for each wheel")
actuators = np.array([group[0] for group in groups])
inverse = np.linalg.pinv(matrix)
covered = set()
for probe in report["probes"]:
command = _wheel_command(probe, inverse, actuators)
isolated = _isolated(command, WHEEL_AXES, required)
if isolated is not None:
axis, name, value = isolated
if (
_body_window_proves(probe, axis, value, exact=False)
or _wheel_endpoint_proves(report, probe, axis, value)
):
covered.add(name)
return sorted(required - covered)
def mobility_error(kind: str, missing: list[str]) -> str:
probes = "body-frame velocity window" if kind == "rl_onnx" else "body-motion"
return (
f"{kind} requires measured nonzero {probes} response in separate probes for "
f"{', '.join(missing)}. Command one enabled axis at a time."
)