playful / chess-sim /code /sim /validate_scene.py
Ali-Uraish's picture
Add files using upload-large-folder tool
33c14d6 verified
Raw History Blame Contribute Delete
11.3 kB
"""Check asset scale, grasp collision fit, labels, and five seconds of settling.
Runs headlessly with the base dependencies. Does not certify a manipulation policy.
"""
from __future__ import annotations
import hashlib
import json
import xml.etree.ElementTree as ET
from pathlib import Path
import mujoco
import numpy as np
HERE = Path(__file__).resolve().parent
ROOT = HERE / "assets" / "chess"
def triangles(path):
raw = path.read_bytes()
dtype = np.dtype([("normal", "<f4", 3), ("vertices", "<f4", (3, 3)), ("attribute", "<u2")])
return np.frombuffer(raw, dtype=dtype, offset=84)["vertices"].astype(float)
def cross_section_bounds(paths, z):
points = []
for path in paths:
tri = triangles(path)
for i, j in ((0, 1), (1, 2), (2, 0)):
a, b = tri[:, i], tri[:, j]
mask = ((a[:, 2] <= z) & (b[:, 2] > z)) | ((b[:, 2] <= z) & (a[:, 2] > z))
a, b = a[mask], b[mask]
points.append(a + (b - a) * ((z - a[:, 2]) / (b[:, 2] - a[:, 2]))[:, None])
xy = np.concatenate(points)[:, :2]
return np.array([xy.min(0), xy.max(0)])
def check_finger_hulls(hulls, tolerance=0.0003):
"""Slab hulls must match each finger's cross-sections where it touches pieces.
Samples keep 0.1 mm away from slab cuts: a cut at a step leaves a sliver the
thickness of the step search (0.05 mm) that straddles the step.
"""
from grasp_geometry import section_extent
arm = HERE / "assets" / "so101"
for part, info in hulls.items():
perm = [i for i in range(3) if i != info["axis"]] + [info["axis"]]
mesh = triangles(arm / info["source_file"])[:, :, perm]
hull = np.concatenate([triangles(arm / f) for f in info["collision"]])[:, :, perm]
lo, hi = info["grip_range_mm"]
heights = np.linspace(lo, hi, 400)
edges = np.array(info["slab_edges_mm"])
heights = heights[np.min(np.abs(heights[:, None] - edges[None]), axis=1) > 0.1] / 1000
worst = 0.0
for along in (np.array([1.0, 0.0]), np.array([0.0, 1.0])):
across = np.array([-along[1], along[0]])
a = section_extent(mesh, heights, along, across, 1.0)
b = section_extent(hull, heights, along, across, 1.0)
ok = ~np.isnan(a[0]) & ~np.isnan(b[0])
worst = max(worst, np.abs(a[0] - b[0])[ok].max(), np.abs(a[1] - b[1])[ok].max())
assert worst < tolerance, f"{part} finger hulls differ by {worst*1000:.3f} mm"
print(f"{part}: {len(info['collision'])} finger hulls, worst section error {worst*1000:.3f} mm")
def check_link_hulls(hulls, tolerance=0.00005):
"""Decomposed link hulls must contain every vertex of the part they replace.
Shapes smaller than the real part would let the expert plan moves that collide
on hardware, so the check is one-sided: the hulls may be larger, never smaller.
"""
arm = HERE / "assets" / "so101"
for part, info in hulls.items():
verts = triangles(arm / info["source_file"]).reshape(-1, 3) * info["scale"]
outside = np.full(len(verts), np.inf)
for f in info["collision"]:
tri = triangles(arm / f)
n = np.cross(tri[:, 1] - tri[:, 0], tri[:, 2] - tri[:, 0])
norm = np.linalg.norm(n, axis=1)
keep = norm > 1e-12
n = n[keep] / norm[keep, None]
c = np.einsum("ij,ij->i", n, tri[keep, 0])
outside = np.minimum(outside, (verts @ n.T - c).max(axis=1))
worst = max(outside.max(), 0.0)
assert worst < tolerance, f"{part} hulls miss the part by {worst*1000:.3f} mm"
print(f"{part}: {len(info['collision'])} hulls, {info['pieces_cm3']:.1f} cm3 "
f"(upstream hull {info['single_hull_cm3']:.1f}), cover the part to {worst*1000:.3f} mm")
def main():
# The scene may change appearance, but must preserve the supplied arm mechanics.
upstream = ET.parse(HERE / "assets/so101/so101_camera_upstream.xml").getroot()
patched = ET.parse(HERE / "assets/so101/so101.xml").getroot()
for tag in ("joint", "position", "inertial"):
assert [dict(e.attrib) for e in upstream.iter(tag)] == [dict(e.attrib) for e in patched.iter(tag)], tag
# The one declared change: listed parts' single collision hulls become several hulls
# in the same frame, class and material: finger slabs (prepare_gripper_assets.py) and
# link decompositions (prepare_arm_collision.py).
hulls = json.loads((HERE / "assets/so101/collision/manifest.json").read_text())["parts"]
expected_geoms, expected_meshes = [], [dict(e.attrib) for e in upstream.iter("mesh")]
for e in upstream.iter("geom"):
a = dict(e.attrib)
if a.get("class") == "collision" and a.get("mesh") in hulls:
files = hulls[a["mesh"]]["collision"]
expected_geoms += [{**a, "mesh": f"{a['mesh']}_col_{i}"} for i in range(len(files))]
expected_meshes += [{"name": f"{a['mesh']}_col_{i}", "file": f} for i, f in enumerate(files)]
else:
expected_geoms.append(a)
assert [dict(e.attrib) for e in patched.iter("geom")] == expected_geoms, "geom"
patched_meshes = [dict(e.attrib) for e in patched.iter("mesh")]
assert sorted(map(str, patched_meshes)) == sorted(map(str, expected_meshes)), "mesh"
for part, info in hulls.items():
assert hashlib.sha256((HERE / "assets/so101" / info["source_file"]).read_bytes()).hexdigest() == info["source_sha256"]
check_finger_hulls({k: v for k, v in hulls.items() if v["method"] == "slab"})
check_link_hulls({k: v for k, v in hulls.items() if v["method"] == "coacd"})
original_bodies = {e.get("name"): dict(e.attrib) for e in upstream.iter("body")}
for body in patched.iter("body"):
expected = original_bodies[body.get("name")].copy()
if body.get("name") == "base":
expected["pos"] = "0 0 0.06"
assert dict(body.attrib) == expected, body.get("name")
pieces = json.loads((ROOT / "manifest.json").read_text())["pieces"]
errors = []
for kind, p in pieces.items():
assert hashlib.sha256((ROOT / p["source_file"]).read_bytes()).hexdigest() == p["source_sha256"]
verts = triangles(ROOT / p["visual"]).reshape(-1, 3)
assert np.allclose([verts.min(0), verts.max(0)], p["bounds_m"], atol=1e-7), kind
assert np.max(np.ptp(verts[:, :2], axis=0)) < 0.025, f"{kind} exceeds square"
assert abs(verts[:, 2].min()) < 1e-7, f"{kind} not seated at origin"
visual = cross_section_bounds([ROOT / p["visual"]], p["grasp_z_m"])
contact = cross_section_bounds([ROOT / f for f in p["collision"]], p["grasp_z_m"])
error = float(np.abs(visual - contact).max())
assert error < 0.0002, f"{kind} collision surface differs by {error*1000:.3f} mm at grasp"
errors.append(error)
print(f"{kind}: {p['height_m']*1000:.2f} mm tall; grasp collision error {error*1000:.3f} mm")
m = mujoco.MjModel.from_xml_path(str(HERE / "chess_scene.xml"))
d = mujoco.MjData(m)
mujoco.mj_resetDataKeyframe(m, d, m.key("home").id)
mujoco.mj_forward(m, d)
table = m.geom("table")
assert table.type == mujoco.mjtGeom.mjGEOM_BOX
assert np.isclose(table.pos[2] + table.size[2], 0), "Table contact height changed"
assert not np.any(m.mat_reflectance), "Unexpected mirror material"
ids = [i for i in range(m.nbody) if m.body(i).name.startswith(("w_", "b_"))]
assert len(ids) == 32
for bid in ids:
name = m.body(bid).name
kind = name.split("_")[1]
p = pieces[kind]
assert m.jnt_type[m.body_jntadr[bid]] == mujoco.mjtJoint.mjJNT_FREE
assert np.isclose(m.body_mass[bid], p["mass_kg"])
assert np.isclose(m.site(name + "_grasp").pos[2], p["grasp_z_m"], atol=1e-7)
visual = m.geom(name + "_visual")
assert visual.contype == 0 and visual.conaffinity == 0 and visual.group == 2
collision_ids = np.flatnonzero((m.geom_bodyid == bid) & (m.geom_group == 3))
assert len(collision_ids) == p["collision_hulls"]
assert np.all(m.geom_contype[collision_ids] != 0)
for file in "abcdefgh":
for rank in range(1, 9):
assert m.site(f"sq_{file}{rank}").id >= 0
start = d.xpos[ids].copy()
for _ in range(round(5 / m.opt.timestep)):
mujoco.mj_step(m, d)
mujoco.mj_forward(m, d)
assert np.isfinite(d.qpos).all() and not d.warning.number.any()
drift = np.linalg.norm(d.xpos[ids, :2] - start[:, :2], axis=1).max()
tilt = np.degrees(np.arccos(np.clip(d.xmat[ids, 8], -1, 1))).max()
board_top = d.site_xpos[m.site("board_center").id, 2]
assert drift < 0.001, f"Piece drift {drift*1000:.3f} mm"
assert tilt < 2, f"Piece tilted {tilt:.2f} degrees"
assert np.max(np.abs(d.xpos[ids, 2] - board_top)) < 0.0005
touching = set()
for c in d.contact:
a, b = m.geom_bodyid[c.geom1], m.geom_bodyid[c.geom2]
if a == m.body("board").id:
touching.add(b)
if b == m.body("board").id:
touching.add(a)
assert set(ids) <= touching, "A piece is not supported by the board"
print(f"PASS: 32 supported pieces, 64 square sites, no physics warnings; "
f"5 s max drift {drift*1000:.3f} mm, max tilt {tilt:.3f} degrees.")
# Check frame coverage and line of sight in the actual parked pose. This does
# not imply visibility while the arm is executing a move.
for camera_name in ("overhead", "rover"):
cam = m.camera(camera_name)
eye = d.cam_xpos[cam.id]
rotation = d.cam_xmat[cam.id].reshape(3, 3)
tan_y = np.tan(np.radians(float(cam.fovy[0])) / 2)
mask = np.array([1, 1, 1, 0, 0, 0], dtype=np.uint8)
for file in "abcdefgh":
for rank in range(1, 9):
point = d.site_xpos[m.site(f"sq_{file}{rank}").id]
local = (point - eye) @ rotation
assert -local[2] > 0
assert abs(local[0] / local[2]) < tan_y * 4/3
assert abs(local[1] / local[2]) < tan_y
ray = point - eye
ray /= np.linalg.norm(ray)
hit = np.array([-1], dtype=np.int32)
mujoco.mj_ray(m, d, eye, ray, mask, 1, -1, hit)
assert hit[0] >= 0
body = m.body(m.geom_bodyid[hit[0]]).name
assert body == "board" or body.startswith(("w_", "b_")), f"{file}{rank} obscured by {body}"
rover_body = m.cam_bodyid[m.camera("rover").id]
assert m.body(m.body_parentid[rover_body]).name == "rover_deck"
# Include the board rim and space for tall pieces, not just square centers.
cid = m.camera("rover").id
rotation = d.cam_xmat[cid].reshape(3, 3)
tan_y = np.tan(np.radians(m.cam_fovy[cid]) / 2)
for x in (0.098, 0.322):
for y in (-0.112, 0.112):
for z in (0.008, 0.055):
local = (np.array([x, y, z]) - d.cam_xpos[cid]) @ rotation
assert local[2] < 0 and abs(local[0]/local[2]) < tan_y * 4/3
assert abs(local[1]/local[2]) < tan_y
print("PASS: SO-101 meshes, joints, actuators and inertials preserved; finite tabletop at z=0; "
"overhead and rover each frame 64/64 square centers unobstructed by the parked arm.")
if __name__ == "__main__":
main()