|
| 1 | +"""Regression: ContactData returns a per-env (num_envs,) tensor on raw MuJoCo. |
| 2 | +
|
| 3 | +The raw-MuJoCo branch built ``has_contact = np.zeros(num_envs)`` but, on a |
| 4 | +detected contact, rebound the name to a bare ``True`` — so ``torch.tensor(True)`` |
| 5 | +returned a 0-d scalar, while the MJX branch returns shape ``(num_env,)``. Same |
| 6 | +query, divergent output shape across backends. This pins the (num_envs,) shape |
| 7 | +in both the contact-present and contact-absent cases, with a stub handler (no |
| 8 | +mujoco/jax/GPU needed). |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +from types import SimpleNamespace |
| 14 | + |
| 15 | +import pytest |
| 16 | +import torch |
| 17 | + |
| 18 | + |
| 19 | +def _mujoco_stub(contacts): |
| 20 | + """A handler whose module looks like the raw-MuJoCo backend.""" |
| 21 | + stub_cls = type("StubMujocoHandler", (), {}) |
| 22 | + stub_cls.__module__ = "metasim.sim.mujoco.stub" # selects the raw-MuJoCo branch |
| 23 | + h = stub_cls() |
| 24 | + h.num_envs = 1 |
| 25 | + h.device = "cpu" |
| 26 | + h.data = SimpleNamespace(ncon=len(contacts), contact=contacts) |
| 27 | + return h |
| 28 | + |
| 29 | + |
| 30 | +def _query(handler): |
| 31 | + from roboverse_pack.queries.contact import ContactData |
| 32 | + |
| 33 | + q = ContactData("geom_a", "geom_b") |
| 34 | + q._geom1_id = 10 |
| 35 | + q._geom2_id = 20 |
| 36 | + q.handler = handler # bypass bind_handler (which needs a real mj model) |
| 37 | + return q |
| 38 | + |
| 39 | + |
| 40 | +@pytest.mark.general |
| 41 | +def test_contact_present_returns_per_env_tensor(): |
| 42 | + contacts = [SimpleNamespace(geom1=10, geom2=20, dist=0.0)] # matching pair, in contact |
| 43 | + out = _query(_mujoco_stub(contacts))() |
| 44 | + assert out.shape == (1,), f"expected (num_envs,) = (1,), got {tuple(out.shape)}" |
| 45 | + assert out.dtype == torch.float32 |
| 46 | + assert out[0] == 1.0 |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.general |
| 50 | +def test_contact_absent_returns_per_env_tensor(): |
| 51 | + out = _query(_mujoco_stub([]))() # no contacts |
| 52 | + assert out.shape == (1,) |
| 53 | + assert out[0] == 0.0 |
0 commit comments