551 lines
25 KiB
Python
551 lines
25 KiB
Python
"""Control parser and operator contracts exercised with neutral fixtures."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import re
|
|
import subprocess
|
|
import sys
|
|
from dataclasses import replace
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
pytest.importorskip("yaml")
|
|
|
|
from controller.controls import ( # noqa: E402
|
|
controller_contract,
|
|
load_controls,
|
|
)
|
|
|
|
FIXTURES = Path(__file__).parent / "fixtures" / "controls"
|
|
CONTROLS = load_controls(FIXTURES / "velocity.yaml")
|
|
POSTURE_SPEC = FIXTURES / "multi_command.yaml"
|
|
AUXILIARY_SPEC = FIXTURES / "auxiliary.yaml"
|
|
|
|
|
|
def _env_cfg():
|
|
twist = SimpleNamespace(ranges=SimpleNamespace(
|
|
lin_vel_x=(-0.3, 0.6), lin_vel_y=(-0.5, 0.5), ang_vel_z=(-0.7, 0.7),
|
|
))
|
|
posture = SimpleNamespace(
|
|
neutral_height=0.42,
|
|
ranges=SimpleNamespace(height=(0.30, 0.52), twist=0.6, pitch=0.25, roll=0.3),
|
|
moving=SimpleNamespace(twist=0.2, pitch=0.1, roll=(-0.1, 0.2)),
|
|
stand_threshold=0.06,
|
|
velocity_command="twist",
|
|
max_rate=0.5,
|
|
)
|
|
return SimpleNamespace(commands={"twist": twist, "posture": posture, "body_pose": posture})
|
|
|
|
|
|
def test_the_file_says_which_way_the_robot_walks() -> None:
|
|
"""The three directions, stated rather than inferred from a device convention."""
|
|
(twist,) = CONTROLS.commands
|
|
assert [a.positive for a in twist.axes] == ["forward", "left", "counter-clockwise"]
|
|
assert twist.frame == "body"
|
|
assert twist.feeds == "velocity_commands"
|
|
|
|
|
|
@pytest.mark.parametrize("axis", ["lin_vel_x", "lin_vel_y", "ang_vel_z"])
|
|
def test_the_mapping_reads_the_file_rather_than_agreeing_with_it(axis: str) -> None:
|
|
"""The control group.
|
|
|
|
Without this, every assertion about which way a stick drives passes against
|
|
a mapping that ignores the specification entirely and has the three signs
|
|
written into it -- which is the arrangement the file was introduced to end.
|
|
Flip a sign in the specification and the command must follow.
|
|
"""
|
|
from mjrl.tasks.operator import deflections
|
|
|
|
(b,) = CONTROLS.bindings[axis]
|
|
values = dict.fromkeys(("Lx", "Ly", "Rx", "Ry", "LT", "RT"), 0.0)
|
|
values[b.source] = 1.0
|
|
before = deflections(values, False, CONTROLS)[axis]
|
|
flipped = replace(CONTROLS, bindings={**CONTROLS.bindings, axis: (replace(b, sign=-b.sign),)})
|
|
after = deflections(values, False, flipped)[axis]
|
|
assert before == pytest.approx(-after)
|
|
assert before != 0.0
|
|
|
|
|
|
def test_the_keyboard_names_what_each_key_does() -> None:
|
|
"""Keystrokes are bound to directions of the file's axes by the
|
|
dictionary's names: W is forward, and every axis is reached both ways."""
|
|
assert "key_w" in CONTROLS.key_axes["lin_vel_x"].plus, "W is towards forward, the axis's +"
|
|
assert "key_s" in CONTROLS.key_axes["lin_vel_x"].minus
|
|
for axis, keys in CONTROLS.key_axes.items():
|
|
assert keys.unbound is None and keys.plus and keys.minus, axis
|
|
assert CONTROLS.key_release == ("key_escape",)
|
|
|
|
|
|
def test_the_locomotion_keyboard_reaches_both_ends_of_every_axis() -> None:
|
|
"""The keyboard alone drives each velocity axis to the edge of its range,
|
|
through the operator `play` uses: each "+" keystroke to the axis's top and
|
|
each "-" one to its bottom. A keyboard whose words and signs disagreed
|
|
would walk the robot backwards on W, with every screen plausible."""
|
|
pytest.importorskip("mjlab", reason="the env config needs mjlab installed")
|
|
from mjrl.tasks.operator import Operator, spans
|
|
|
|
cfg = _env_cfg()
|
|
edges = spans(CONTROLS.command("twist"), cfg.commands["twist"])
|
|
names = [a.name for a in CONTROLS.command("twist").axes]
|
|
for i, axis in enumerate(names):
|
|
for strokes, end in [(CONTROLS.key_axes[axis].plus, 1), (CONTROLS.key_axes[axis].minus, 0)]:
|
|
for stroke in strokes:
|
|
clock = _Clock()
|
|
op = Operator(CONTROLS, listen=False, clock=clock)
|
|
op.attach("twist", edges)
|
|
assert op.key(stroke, True), stroke
|
|
clock.t = CONTROLS.full_after_s
|
|
assert op.command("twist")[i] == pytest.approx(edges[axis][end]), stroke
|
|
|
|
|
|
def _generate_controls(path: Path, *options: str):
|
|
writer = Path(__file__).resolve().parents[1] / ".claude/skills/controls/scripts/write_controls.py"
|
|
subprocess.run(
|
|
[sys.executable, str(writer), "--task", "locomotion_fixture", "--out", str(path), *options],
|
|
check=True,
|
|
capture_output=True,
|
|
text=True,
|
|
)
|
|
return load_controls(path)
|
|
|
|
|
|
def test_controls_writer_defaults_to_omni(tmp_path) -> None:
|
|
controls = _generate_controls(tmp_path / "omni.yaml")
|
|
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",)
|
|
assert controls.key_axes["ang_vel_z"].minus == ("key_l",)
|
|
|
|
|
|
def test_differential_controls_drive_wheeled_template_forward_and_yaw(tmp_path, neutral_robot):
|
|
from xml.etree import ElementTree as ET
|
|
|
|
pytest.importorskip("mjlab")
|
|
from controller.xbox import GamepadState
|
|
from mjrl.controllers.input import OperatorInput
|
|
from mjrl.tasks.operator import Operator, spans
|
|
from tasks.robot_spec import JointSpec
|
|
from tasks.templates.Wheeled_Biped_Template.env_cfg import env_cfg
|
|
|
|
controls = _generate_controls(tmp_path / "wheel.yaml", "--profile", "differential")
|
|
twist = controls.command("twist")
|
|
assert [axis.name for axis in twist.axes] == ["lin_vel_x", "lin_vel_y", "ang_vel_z"]
|
|
assert controls.key_axes["lin_vel_y"].unbound
|
|
|
|
source = ET.parse(neutral_robot.model_path)
|
|
for index in range(2):
|
|
leg = source.find(f".//body[@name='leg_body_{index}']")
|
|
wheel = ET.SubElement(leg, "body", name=f"wheel_body_{index}", pos="0 0 -0.15")
|
|
ET.SubElement(wheel, "joint", name=f"wheel_{index}", axis="0 1 0")
|
|
ET.SubElement(wheel, "geom", size="0.02", mass="0.05")
|
|
model = tmp_path / "wheeled.xml"
|
|
source.write(model)
|
|
robot = replace(
|
|
neutral_robot,
|
|
family="wheeled_biped",
|
|
model_path=model,
|
|
controls_path=controls.source,
|
|
velocity_joints=tuple(JointSpec(f"wheel_{i}", 0, 1, 1, 4) for i in range(2)),
|
|
)
|
|
command_cfg = env_cfg(robot, play=True).commands["twist"]
|
|
edges = spans(twist, command_cfg)
|
|
x_lo, x_hi, _ = edges["lin_vel_x"]
|
|
yaw_lo, yaw_hi, _ = edges["ang_vel_z"]
|
|
assert x_lo < 0 < x_hi and yaw_lo < 0 < yaw_hi
|
|
assert edges["lin_vel_y"] == (0, 0, 0)
|
|
commands = {
|
|
"key_w": [x_hi, 0, 0],
|
|
"key_s": [x_lo, 0, 0],
|
|
"key_a": [0, 0, yaw_hi],
|
|
"key_d": [0, 0, yaw_lo],
|
|
}
|
|
for key, target in commands.items():
|
|
clock = _Clock()
|
|
operator = Operator(controls, listen=False, clock=clock)
|
|
operator.attach("twist", edges)
|
|
assert operator.key(key, True)
|
|
clock.t = controls.full_after_s
|
|
assert operator.command("twist") == pytest.approx(target)
|
|
native = OperatorInput(controls, edges)
|
|
native.read({}, (key,), 0, 0)
|
|
actual = native.read({}, (key,), clock.t, clock.t)
|
|
assert [actual[axis.name] for axis in twist.axes] == pytest.approx(target)
|
|
|
|
pad = SimpleNamespace(state=lambda: GamepadState(lx=-1, ly=-1, rx=-1))
|
|
operator = Operator(controls, pad, listen=False, clock=_Clock())
|
|
operator.attach("twist", edges)
|
|
assert operator.command("twist") == pytest.approx([x_hi, 0, yaw_hi])
|
|
native = OperatorInput(controls, edges)
|
|
actual = native.read({"Lx": -1, "Ly": -1, "Rx": -1}, (), 0, 0)
|
|
assert [actual[axis.name] for axis in twist.axes] == pytest.approx([x_hi, 0, yaw_hi])
|
|
|
|
|
|
def test_a_modifier_with_nothing_to_do_does_not_take_over(tmp_path) -> None:
|
|
"""A modifier that is a chord's and nothing on its own -- Shift, with the
|
|
twist put on Shift + J / L --
|
|
pressed alone leaves the command with the sampler, as the controller
|
|
does, which only takes over for a keystroke that acts. J pressed with it is
|
|
the twist, and takes over: the control group."""
|
|
pytest.importorskip("mjlab", reason="the env config needs mjlab installed")
|
|
import yaml
|
|
from mjrl.tasks.operator import Operator, spans
|
|
|
|
doc = _posture_doc()
|
|
_keys(doc)["twist"] = {"+": ["shift+key_j"], "-": ["shift+key_l"]}
|
|
spec = tmp_path / "controls.yaml"
|
|
spec.write_text(yaml.safe_dump(doc), "utf-8")
|
|
controls = load_controls(spec)
|
|
cfg = _env_cfg()
|
|
op = Operator(controls, listen=False, clock=_Clock())
|
|
for term in ("twist", "posture"):
|
|
op.attach(term, spans(controls.command(term), cfg.commands[term]))
|
|
assert op.key("key_left_shift", True), "Shift is a key the file reads"
|
|
assert op.command("twist") is None, "Shift alone took the command from the sampler"
|
|
op.key("key_j", True)
|
|
assert op.command("twist") is not None, "Shift + J did not take over"
|
|
assert not op.key("keypad_5", True), "a key the file does not read reports as such"
|
|
|
|
|
|
class _Clock:
|
|
"""Seconds, moved by the test: what a key's hold is measured by."""
|
|
|
|
def __init__(self) -> None:
|
|
self.t = 0.0
|
|
|
|
def __call__(self) -> float:
|
|
return self.t
|
|
|
|
|
|
def test_a_retired_schema_1_file_is_refused(tmp_path) -> None:
|
|
"""Schema 1 is gone, and a file still written in it says so by name rather
|
|
than being read as the nearest thing."""
|
|
old = tmp_path / "controls.yaml"
|
|
old.write_text("schema_version: 1\ncommand: {}\n", "utf-8")
|
|
with pytest.raises(ValueError, match="retired"):
|
|
load_controls(old)
|
|
|
|
|
|
def test_the_exported_block_is_the_file_and_says_which_revision() -> None:
|
|
pytest.importorskip("mjlab", reason="the env config needs mjlab installed")
|
|
|
|
block = controller_contract(CONTROLS, _env_cfg())
|
|
assert block["schema"] == "operator_controller/2"
|
|
assert block["source"]["sha256"] == CONTROLS.source_sha256
|
|
(twist,) = block["command"]
|
|
assert [a["positive"] for a in twist["axes"]] == ["forward", "left", "counter-clockwise"]
|
|
assert block["devices"]["gamepad"]["axes"] == CONTROLS.gamepad["axes"]
|
|
assert block["devices"]["keyboard"]["axes"] == CONTROLS.keyboard["axes"]
|
|
assert block["task"] == {}, "a task that keeps nothing says so"
|
|
|
|
|
|
def test_every_reader_reads_the_one_dictionary() -> None:
|
|
"""One list, three readers, and no copies.
|
|
|
|
It had a copy in each reader for a day: a Python table here, Rust consts in
|
|
`deploy/fsm`, and a prose block in a deploy manifest. Adding a word meant
|
|
remembering two other files, and forgetting one leaves a name that reads as
|
|
supported and is refused on build -- or, worse, the other way round.
|
|
|
|
So this checks the *wiring*, not the contents: that each reader resolves to
|
|
`controller/vocabulary.json` and none of them carries a list of its own.
|
|
"""
|
|
import re
|
|
|
|
from controller import vocabulary
|
|
from controller.controls import _AXES, _BUTTONS
|
|
|
|
root = Path(__file__).resolve().parents[1]
|
|
assert vocabulary.PATH == root / "controller/vocabulary.json"
|
|
|
|
# The task side holds no list; it is the dictionary's, verbatim.
|
|
assert tuple(_AXES) == vocabulary.axes()
|
|
assert _BUTTONS == frozenset(vocabulary.buttons())
|
|
|
|
# The crate embeds the same file rather than restating it. `include_str!`
|
|
# fixes the bytes at compile time, so a board carries no file and a browser
|
|
# needs no fetch, and there is still one source.
|
|
rs = (root / "deploy/fsm/src/vocabulary.rs").read_text("utf-8")
|
|
assert 'include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/../../controller/vocabulary.json"))' \
|
|
in rs.replace("\n", " ").replace(" ", ""), "the crate does not embed the dictionary"
|
|
assert not re.search(r'const PAD_BUTTONS: \[&str', rs), "the crate kept a list of its own"
|
|
|
|
# Control group: the parse is reading something, so the assertions above
|
|
# cannot pass by comparing two empty things.
|
|
assert len(vocabulary.buttons()) == 14 and len(vocabulary.axes()) == 6
|
|
|
|
|
|
def test_the_local_reader_reports_only_names_the_dictionary_knows() -> None:
|
|
"""`controller/` aligns a pad to the dictionary and stops there.
|
|
|
|
Its job is not to decide what a button means -- that belongs to a task --
|
|
so it must not have a spelling of its own either. `view` is the one name it
|
|
reports that the dictionary does not accept, and the dictionary says why
|
|
rather than leaving it looking like an oversight.
|
|
"""
|
|
from controller import vocabulary
|
|
from controller.xbox import BUTTONS
|
|
|
|
reported = set(BUTTONS.values())
|
|
accepted = set(vocabulary.buttons())
|
|
assert reported - accepted == set(vocabulary.absent()), \
|
|
"the reader reports a name the dictionary neither accepts nor explains"
|
|
assert "view" in vocabulary.absent()
|
|
|
|
|
|
def test_x_and_y_are_recorded_as_unresolved() -> None:
|
|
"""A recorded disagreement, not a passing check.
|
|
|
|
`controller/xbox.py` and the robot's pad service read evdev 307 and 308 the
|
|
other way round from each other. One is wrong about which physical button it
|
|
is, and only pressing it settles that. Nothing binds either today, so
|
|
nothing is broken while it stands.
|
|
|
|
This exists so the disagreement cannot be closed by somebody assuming. It
|
|
fails when the note leaves the dictionary, which is the moment to say
|
|
whether it was measured or guessed.
|
|
"""
|
|
from controller import vocabulary
|
|
from controller.xbox import BTN_NORTH, BTN_WEST
|
|
|
|
assert (BTN_NORTH, BTN_WEST) == (307, 308)
|
|
unresolved = {b["name"]: b.get("unresolved") for b in vocabulary.load()["buttons"]}
|
|
assert unresolved["X"] and "307" in unresolved["X"], "the X/Y question left the dictionary"
|
|
assert unresolved["Y"]
|
|
# And it is visible to anyone who asks, not only to a reader of the JSON.
|
|
assert "unresolved" in vocabulary.describe()
|
|
|
|
|
|
|
|
# ── The full case: two commands, one operator ────────────────────────────────
|
|
|
|
def test_the_contract_carries_numbers_a_robot_can_use() -> None:
|
|
"""The block `deploy/fsm` reads as `operator_controller/2`.
|
|
|
|
Each rest as a **number**: the file names a config field (`neutral_height`),
|
|
a robot has no config to look it up in, and a rest it could not resolve is
|
|
a height of zero -- a body on the floor.
|
|
|
|
"""
|
|
cfg = _env_cfg()
|
|
block = controller_contract(load_controls(POSTURE_SPEC), cfg)
|
|
assert block["schema"] == "operator_controller/2"
|
|
assert [c["term"] for c in block["command"]] == ["twist", "posture"]
|
|
assert block["source"]["sha256"] == load_controls(POSTURE_SPEC).source_sha256
|
|
height = next(a for a in block["command"][1]["axes"] if a["name"] == "height")
|
|
assert height["rest"] == pytest.approx(cfg.commands["posture"].neutral_height) and height["rest_from"] == "neutral_height"
|
|
# Moved, not placed: the robot integrates it from the number.
|
|
# The file's own number, carried over: the value is the task's to tune.
|
|
assert height["integrate_s"] == pytest.approx(load_controls(POSTURE_SPEC).integrating["height"])
|
|
assert "integrate_s" not in next(a for a in block["command"][1]["axes"] if a["name"] == "pitch")
|
|
|
|
# The control group: with no environment to read it from, the rest is
|
|
# refused rather than written as a name or left out.
|
|
with pytest.raises(ValueError, match="rests at `neutral_height`"):
|
|
controller_contract(load_controls(POSTURE_SPEC), None)
|
|
|
|
|
|
def _posture_doc() -> dict:
|
|
import yaml
|
|
|
|
return yaml.safe_load(POSTURE_SPEC.read_text("utf-8"))
|
|
|
|
|
|
def _pad(d: dict) -> dict:
|
|
return d["devices"]["gamepad"]
|
|
|
|
|
|
def _kb(d: dict) -> dict:
|
|
return d["devices"]["keyboard"]
|
|
|
|
|
|
def _keys(d: dict) -> dict:
|
|
return d["devices"]["keyboard"]["axes"]
|
|
|
|
|
|
def _axis(d: dict, name: str) -> dict:
|
|
return next(a for c in d["command"] for a in c["axes"] if a["name"] == name)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mutate, message",
|
|
[
|
|
(lambda d: d.__setitem__("command", d["command"][0]), "is a list"),
|
|
# Two bindings claiming the same stretch of one stick: one deflection
|
|
# would move both, and each alone looks right.
|
|
(lambda d: _pad(d)["axes"]["twist"].__setitem__("travel", [0.0, 0.6]), "both take Rx"),
|
|
# The same with a fall: the climb is the claim. The file as written
|
|
# falls over the turn's climb and loads, which is the control group.
|
|
(lambda d: _pad(d)["axes"]["twist"].__setitem__("travel", [0.0, 0.6, 0.6, 0.75]),
|
|
"both take Rx"),
|
|
(lambda d: _pad(d)["axes"]["twist"].__setitem__("travel", [0.0, 0.5, 0.4, 0.75]),
|
|
"travel"),
|
|
(lambda d: _pad(d)["axes"]["twist"].__setitem__("travel", [0.0, 0.5, 0.75]), "travel"),
|
|
(lambda d: _pad(d)["axes"]["pitch"].__setitem__("travel", [0.5, 0.5]), "travel"),
|
|
(lambda d: _pad(d)["axes"].pop("pitch"), "no control drives pitch"),
|
|
(lambda d: _pad(d)["axes"].__setitem__("yaw", {"source": "Ry", "sign": 1}),
|
|
"which no command has"),
|
|
(lambda d: _pad(d)["axes"]["height"].__setitem__("sign", 0), "must be 1 or -1"),
|
|
(lambda d: _pad(d)["axes"]["pitch"].__setitem__("source", "right_stick_y"),
|
|
"does not publish"),
|
|
(lambda d: _pad(d).pop("shift"), "declares no shift button"),
|
|
# `hold` is refused on purpose -- a rule from when the keyboard, through
|
|
# MuJoCo's viewer, saw presses only.
|
|
(lambda d: _pad(d)["shift"].__setitem__("gesture", "rise"), "a shift is"),
|
|
(lambda d: _pad(d)["shift"].__setitem__("gesture", "double_click"), "gestures are"),
|
|
(lambda d: _pad(d)["shift"].__setitem__("button", "B"),
|
|
"both the shift and the release"),
|
|
(lambda d: _pad(d)["shift"].__setitem__("button", "view"), "does not publish"),
|
|
(lambda d: _pad(d).__setitem__("scheme", "integrating"), "absolute"),
|
|
# The moved axis and the tap that puts it back: each must say a time,
|
|
# and a reset needs an axis to reset and a button of its own.
|
|
(lambda d: _axis(d, "height").__setitem__("integrate_s", 0), "integrate_s is 0"),
|
|
(lambda d: _axis(d, "height").__setitem__("integrate_s", True), "integrate_s is True"),
|
|
(lambda d: _axis(d, "height").pop("integrate_s"), "no axis has `integrate_s`"),
|
|
(lambda d: _pad(d).__setitem__("reset", "B"), "both the reset and the release"),
|
|
(lambda d: _pad(d).__setitem__("reset", "view"), "does not publish"),
|
|
# The keyboard: its scheme, and the notched keyboard's form, retired and
|
|
# refused by name ...
|
|
(lambda d: _kb(d).__setitem__("scheme", "integrating"), "implements `keys`"),
|
|
(lambda d: _kb(d).__setitem__("full_after_s", 0), "a positive number"),
|
|
(lambda d: _kb(d).__setitem__("full_after_s", True), "a positive number"),
|
|
(lambda d: _kb(d).__setitem__("step", 0.1), "notched keyboard retired"),
|
|
(lambda d: _kb(d).__setitem__("centre", "key_h"), "retired on 2026-09-27"),
|
|
# ... every axis on it or said to be off it, with a reason ...
|
|
(lambda d: _keys(d).pop("pitch"), "keyboard.axes leaves out pitch"),
|
|
(lambda d: _keys(d).__setitem__("pitch", {"unbound": " "}), "does not say why"),
|
|
(lambda d: _keys(d).__setitem__("yaw", {"+": ["key_1"], "-": ["key_2"]}), "which no command has"),
|
|
(lambda d: _keys(d).__setitem__("pitch", {"+": ["key_i"]}), "keyboard.axes.pitch is"),
|
|
(lambda d: _keys(d)["pitch"].__setitem__("+", []), "non-empty list of keystrokes"),
|
|
# ... each keystroke one, and one keystroke doing one thing ...
|
|
(lambda d: _keys(d)["pitch"].__setitem__("+", ["KeyI"]), "is not a key"),
|
|
(lambda d: _keys(d)["pitch"].__setitem__("+", ["hyper+key_i"]), "is not a key"),
|
|
(lambda d: _keys(d)["pitch"].__setitem__("+", ["key_w"]), "One keystroke would do both"),
|
|
(lambda d: _kb(d).__setitem__("release", ["key_i"]), "One keystroke would do both"),
|
|
# ... and a modifier held alone is not also the modifier of a chord.
|
|
(lambda d: (_keys(d).__setitem__("twist", {"+": ["shift+key_j"], "-": ["shift+key_l"]}),
|
|
_keys(d)["roll"].__setitem__("+", ["shift"])), "also modifies a key"),
|
|
(lambda d: _kb(d).pop("release"), "missing release"),
|
|
(lambda d: d["command"][1].__setitem__("term", "twist"), "listed twice"),
|
|
],
|
|
)
|
|
def test_a_malformed_specification_stops_the_import(mutate, message, tmp_path) -> None:
|
|
"""Each of these is a pad and a keyboard that disagree, or a control that
|
|
drives nothing, and none of them would raise anywhere else."""
|
|
import yaml
|
|
|
|
doc = _posture_doc()
|
|
mutate(doc)
|
|
path = tmp_path / "controls.yaml"
|
|
path.write_text(yaml.safe_dump(doc), "utf-8")
|
|
with pytest.raises((ValueError, KeyError), match=re.escape(message)):
|
|
load_controls(path)
|
|
|
|
|
|
def test_the_unmutated_round_trip_loads(tmp_path) -> None:
|
|
"""The control group for the parametrisation above: the same dump with no
|
|
mutation loads, so each failure there is the mutation's."""
|
|
import yaml
|
|
|
|
path = tmp_path / "controls.yaml"
|
|
path.write_text(yaml.safe_dump(_posture_doc()), "utf-8")
|
|
assert load_controls(path).bindings == load_controls(POSTURE_SPEC).bindings
|
|
|
|
|
|
def _auxiliary_doc() -> dict:
|
|
import yaml
|
|
|
|
return yaml.safe_load(AUXILIARY_SPEC.read_text("utf-8"))
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"mutate, message",
|
|
[
|
|
# Declared once, with what it is and does ...
|
|
(lambda d: d["task"]["tool_left"].__setitem__("kind", "grip"), "a task control is `amount`"),
|
|
(lambda d: d["task"]["tool_left"].__setitem__("does", " "), "does not say what it does"),
|
|
# ... and bound on each device by that name, every one and only those.
|
|
(lambda d: _pad(d)["task"].pop("tool_right"), "gamepad.task leaves out ['tool_right']"),
|
|
(lambda d: _kb(d)["task"].pop("preset_three"), "keyboard.task leaves out ['preset_three']"),
|
|
(lambda d: _pad(d)["task"].__setitem__("grip", "X"), "which the top-level `task:` does not declare"),
|
|
# A control a command reads, or the release, would do two things.
|
|
(lambda d: _pad(d)["task"].__setitem__("tool_left", "Rx"), "both the task's (tool_left) and a command's"),
|
|
(lambda d: _pad(d)["task"].__setitem__("tool_right", "LT"), "on two task controls"),
|
|
# A press on the d-pad, an amount on an axis.
|
|
(lambda d: _pad(d)["task"].__setitem__("preset_three", "A"), "a `press` goes on a d-pad"),
|
|
(lambda d: _pad(d)["task"].__setitem__("tool_left", "dpad_right"), "an `amount` goes on an axis"),
|
|
# The keyboard: the task's keys may be shared among its controls -- the
|
|
# two claws both on Space -- and with nothing else.
|
|
(lambda d: _kb(d)["task"].__setitem__("tool_left", ["key_w"]), "One keystroke would do both"),
|
|
(lambda d: _kb(d)["task"].__setitem__("tool_left", []), "non-empty list of keystrokes"),
|
|
(lambda d: _kb(d)["task"].__setitem__("preset_three", ["ctrl", "ctrl"]), "lists a keystroke twice"),
|
|
],
|
|
)
|
|
def test_a_control_the_task_cannot_keep_stops_the_import(mutate, message, tmp_path) -> None:
|
|
"""Refuse controls assigned twice or missing from either device."""
|
|
import yaml
|
|
|
|
doc = _auxiliary_doc()
|
|
mutate(doc)
|
|
path = tmp_path / "controls.yaml"
|
|
path.write_text(yaml.safe_dump(doc), "utf-8")
|
|
with pytest.raises((ValueError, KeyError), match=re.escape(message)):
|
|
load_controls(path)
|
|
|
|
|
|
def test_what_the_task_keeps_reaches_the_contract(tmp_path) -> None:
|
|
"""The robot has no `controls.yaml`; the contract's block is what its
|
|
controller reads the task's controls from, and what refuses a hook reading
|
|
one the task does not keep. So the block carries them, as the file says.
|
|
|
|
The control group is the unmutated dump, which loads with them -- so each
|
|
failure above is its mutation's -- and posture, which keeps none.
|
|
"""
|
|
import yaml
|
|
|
|
|
|
path = tmp_path / "controls.yaml"
|
|
path.write_text(yaml.safe_dump(_auxiliary_doc()), "utf-8")
|
|
kept = load_controls(path)
|
|
assert set(kept.task) == {"tool_left", "tool_right", "preset_one", "preset_two", "preset_three"}
|
|
assert load_controls(POSTURE_SPEC).task == {}
|
|
|
|
block = controller_contract(kept, _env_cfg())
|
|
assert block["task"] == {n: {"kind": t.kind, "does": t.does} for n, t in kept.task.items()}
|
|
assert block["devices"]["gamepad"]["task"] == kept.pad_task
|
|
assert block["devices"]["keyboard"]["task"] == {n: list(k) for n, k in kept.key_task.items()}
|
|
|
|
|
|
def test_a_key_written_twice_is_refused_rather_than_the_last_one_kept(tmp_path) -> None:
|
|
"""PyYAML keeps the last of two equal keys and says nothing.
|
|
|
|
So an axis written twice in the keyboard's `axes` is one set of keys
|
|
silently gone, and the completeness check cannot see it: the surviving line
|
|
may be the one that was meant. Written as text, because a dict cannot hold
|
|
the duplicate.
|
|
"""
|
|
text = POSTURE_SPEC.read_text("utf-8")
|
|
line = ' pitch: { "+": [key_i], "-": [key_k] }\n'
|
|
assert text.count(line) == 1
|
|
path = tmp_path / "controls.yaml"
|
|
path.write_text(text.replace(line, line + ' pitch: { "+": [key_k], "-": [key_i] }\n'))
|
|
with pytest.raises(ValueError, match="written twice"):
|
|
load_controls(path)
|
|
|
|
|
|
def test_the_contract_carries_the_bands_and_the_ramp_the_command_was_trained_under() -> None:
|
|
"""Bands and rate limits are serialized only for terms that declare them."""
|
|
cfg = _env_cfg()
|
|
blocks = {
|
|
command["term"]: command
|
|
for command in controller_contract(load_controls(POSTURE_SPEC), cfg)["command"]
|
|
}
|
|
assert blocks["posture"]["bands"] == {
|
|
"standing_below": 0.06,
|
|
"velocity_term": "twist",
|
|
"moving": {"twist": [-0.2, 0.2], "pitch": [-0.1, 0.1], "roll": [-0.1, 0.2]},
|
|
}
|
|
assert blocks["posture"]["max_rate"] == 0.5
|
|
assert "bands" not in blocks["twist"] and "max_rate" not in blocks["twist"]
|