Files
UniversalTrain-ai/tests/test_template_foot_sites.py
chenlin ceca51b0d8
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
Improve generic robot onboarding, walking controls and end-effector interaction
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.
2026-11-06 10:54:58 +08:00

158 lines
7.9 KiB
Python

"""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