Skip to content

The first exam for code agents in the physical world: frozen robot tasks from many benchmark suites, each answered with a program and verified in a separate sandbox. Runs on Harbor.

31.7 KB
Raw Blame
"""Self-collision (bodies/README.md "自碰撞"; real limits B0): a real arm cannot pass through its own body, so the
simulated one cannot either. One declaration per robot (body.toml [self_collision]) says which parts of the robot
touch which; this module turns it into MuJoCo contact pairs, counts the contacts during play, and checks the
declaration against the model.

What collides (body.toml [self_collision], the rules below):
  parts     every body of the robot belongs to a part by a regular expression on its name (without the robot's
            prefix / suffix): an arm (`left_arm`, `right_arm`; a single arm: `arm`) or `body` (torso, waist, head,
            pelvis, legs, the base and its wheels, a pedestal). A body that matches nothing inherits its parent's part;
            one hanging below an arm without matching is the arm's TOOL (the hand on the wrist mount: paddle, racket,
            epee). The bodies a fixed-base arm stands on (its pedestal, gantry carriage, rail cart: the ancestors of the
            robot's matched bodies) are `body`.
  rules     every arm geom x every body geom (arm_body; legs count as body here); left arm x right arm, tools
            included (arm_arm); a tool x the links of its own arm (tool_own_arm); with same_arm = true also link x
            link of the same arm (a single arm such as the Franka, whose links fold onto each other). Legs (parts
            `left_leg`, `right_leg`): leg_leg = true, left leg x right leg; same_leg = true, link x link of one leg
            (shin x foot). ignore_geoms (a regular expression on geom names) leaves out sensing volumes.
  excluded  automatically: two geoms of one rigid group (bodies welded together: a link, its mount and its tool) and
            of two rigid groups joined by one joint (a link and its parent: the joint's housing overlaps by design,
            MuJoCo's own parent filter); by declaration: [[self_collision.exclude]] entries (two body-name patterns
            and a reason), for hulls that overlap at a joint housing one link further away. Every exclusion is
            written down with its reason; the check below fails an exclusion that matches nothing.

How: explicit MuJoCo <pair>s (named <tag>_<i>, tag = the robot's prefix + "selfcol" + suffix), so the robot's
geoms keep their contype / conaffinity (the library's robots: contype 4 / conaffinity 0, they never touch each
other or a second robot) and a pair adds exactly one tested geom pair; the contact parameters are MuJoCo's defaults
(condim 3, friction 1) with a stiff solref (SOLREF: rigid shells). The contacts
block the motion physically, as the real robot's shell does; the servo is not told (a real controller is not
either: the arm stalls against itself, its PD torque rises to the torque limit).

What is recorded (Monitor, fed by every rig.apply): self-collision events (a pair coming into contact; a bouncing
contact is one event), the time in contact, the peak normal force, its peak 10 ms mean and the impulse, per pair;
events whose 10 ms mean force exceeds the declared threshold ([self_collision] warn_force_n) are counted as
warnings. Recorded only: no penalty (the sports decide; see README).

    from bodies import selfcollision as SC
    plan = SC.plan(template_root, decl["self_collision"], prefix="A_")        # stdlib only: pairs + exclusions
    SC.add_pairs(scene_root, plan)                                             # <contact><pair .../></contact>
    mon = SC.Monitor(model, plan.tag, warn_force_n=30.0); mon.update(d) per physics step; mon.summary()
    python -m bodies.selfcollision check [robot ...]                          # needs mujoco (CI installs it)
    python -m bodies.selfcollision pairs ROBOT                                # the enabled and excluded pairs
    python -m bodies.selfcollision scene sports/SPORT                         # a sport's scenes: write the pairs

The planning part (plan, add_pairs, scene_block) is stdlib only; Monitor and check import numpy / mujoco.
"""
from __future__ import annotations

import re
import sys
import xml.etree.ElementTree as ET
from dataclasses import dataclass, field
from pathlib import Path

HERE = Path(__file__).resolve().parent
MARK_BEGIN = "<!-- self-collision: generated by bodies/selfcollision.py (scene_block), do not edit -->"
MARK_END = "<!-- /self-collision -->"


# ------------------------------------------------------------------------------------------------ the model's tree
def _defaults(root: ET.Element) -> dict[str, dict]:
    """class name -> the geom attributes the class gives (nested defaults inherit), "main" for the top level."""
    table: dict[str, dict] = {"main": {}}

    def walk(el, inherited, name):
        attrs = dict(inherited)
        g = el.find("geom")
        if g is not None:
            attrs.update(g.attrib)
        table[name] = attrs
        for ch in el.findall("default"):
            walk(ch, attrs, ch.get("class"))

    for top in root.findall("default"):
        if top.get("class") in (None, "main"):
            walk(top, table["main"], "main")
        else:                                  # a section of classes appended at the top level
            walk(top, table["main"], top.get("class"))
    return table


def _resolved(geom: ET.Element, cls: str, table: dict) -> dict:
    out = dict(table.get(cls, table["main"]))
    out.update(geom.attrib)
    return out


def is_collision_geom(attrs: dict) -> bool:
    """The default selection: a geom MuJoCo would collide (contype or conaffinity non-zero; defaults are 1)."""
    return int(attrs.get("contype", "1")) != 0 or int(attrs.get("conaffinity", "1")) != 0


def is_physical_geom(attrs: dict) -> bool:
    """A geom that is part of the robot's physical shape: a collision geom, or one with mass (the Franka scenes' arm
    meshes are drawn and simulated but switched out of MuJoCo's contacts with contype 0); not a massless drawing."""
    zero = lambda k: attrs.get(k) is not None and float(attrs[k]) == 0.0
    return is_collision_geom(attrs) or not (zero("mass") or zero("density"))


SELECT = {"collision": is_collision_geom, "physical": is_physical_geom}


@dataclass
class Plan:
    tag: str                                   # pair names: <tag>_<i>
    pairs: list = field(default_factory=list)  # (geom1, geom2, body1, body2, rule)
    excluded: list = field(default_factory=list)   # (body1, body2, reason)
    parts: dict = field(default_factory=dict)  # body name -> (part, is_tool)
    unused_exclusions: list = field(default_factory=list)

    def summary(self) -> dict:
        rules: dict[str, int] = {}
        for p in self.pairs:
            rules[p[4]] = rules.get(p[4], 0) + 1
        return {"tag": self.tag, "pairs": len(self.pairs), "by_rule": rules, "excluded_body_pairs": len(self.excluded)}


def plan(root: ET.Element, decl: dict, prefix: str = "", suffix: str = "", world_geoms=(), select=None,
         name_unnamed: bool = True) -> Plan:
    """The self-collision pairs of one robot in an MJCF tree (a body's template or a whole scene). decl: body.toml
    [self_collision]. prefix / suffix: what the robot's names carry in this tree ("A_", "_b"). world_geoms: geoms of
    the worldbody that belong to the robot's body (a pedestal drawn in the world). select(attrs) -> bool picks the
    geoms that take part (default: the collision geoms). Unnamed selected geoms get a name (<body>_sc<k>), since a
    <pair> names its geoms."""
    select = select or is_collision_geom
    table = _defaults(root)
    wb = root.find("worldbody")
    norm = lambda n: n[len(prefix):len(n) - len(suffix) if suffix else None] \
        if n and n.startswith(prefix) and n.endswith(suffix) else None
    parts_re = {k: re.compile(v) for k, v in decl["parts"].items()}

    def match(n):
        if n is None:
            return None
        for k, rx in parts_re.items():
            if rx.fullmatch(n):
                return k
        return None

    # walk the tree: parent, weld group (bodies without a joint are welded to their parent), class, part
    info = {}                                   # body element -> dict

    def walk(el, parent, weld_parent_group, cls, inherited):
        for b in el.findall("body"):
            name = b.get("name")
            n = norm(name)
            jointed = b.find("joint") is not None or b.find("freejoint") is not None
            weld = b if jointed else weld_parent_group
            c = b.get("childclass") or cls
            m = match(n)
            if m is not None:
                part, tool = m, False
            elif inherited is not None:
                part, tool = inherited[0], inherited[0] != "body"
            else:
                part, tool = None, False
            info[b] = dict(name=name, norm=n, parent=parent, weld=weld, cls=c, part=part, tool=tool or (
                inherited is not None and inherited[1]))
            walk(b, b, weld, c, (part, info[b]["tool"]) if part is not None else None)

    walk(wb, None, "world", "main", None)
    robot = [b for b, i in info.items() if i["part"] is not None]
    if not robot:
        raise ValueError(f"no body of the robot (prefix {prefix!r}, suffix {suffix!r}) in the tree")
    # the bodies the robot stands on (ancestors of its matched bodies, not matched themselves): its body
    for b in robot:
        p = info[b]["parent"]
        while p is not None and info[p]["part"] is None:
            info[p]["part"], info[p]["tool"] = "body", False
            p = info[p]["parent"]
    weld_parent = {}
    for b, i in info.items():
        w = i["weld"]
        if w != "world" and w not in weld_parent:
            pb = info[w]["parent"]
            weld_parent[w] = info[pb]["weld"] if pb is not None else "world"

    def adjacent(wa, wb_):
        return wa is wb_ or weld_parent.get(wa) is wb_ or weld_parent.get(wb_) is wa

    # the geoms that take part (not those of [self_collision] ignore_geoms: sensing volumes, e.g. a kick's strike box)
    ignore = re.compile(decl["ignore_geoms"]) if decl.get("ignore_geoms") else None
    kind = lambda p: "arm" if p.endswith("arm") else "leg" if p.endswith("leg") else "body"
    geoms = []                                  # (name, body element or None for the world, part, tool, weld)
    for b, i in info.items():
        if i["part"] is None:
            continue
        k = 0
        for g in b.findall("geom"):
            attrs = _resolved(g, g.get("class") or i["cls"], table)
            if not select(attrs):
                continue
            if ignore is not None and g.get("name") is not None and ignore.fullmatch(norm(g.get("name")) or ""):
                continue
            if g.get("name") is None:
                if not name_unnamed:
                    raise ValueError(f"an unnamed collision geom in body {i['name']}")
                g.set("name", f"{i['name']}_sc{k}")
                k += 1
            geoms.append((g.get("name"), b, i["part"], i["tool"], i["weld"]))
    for gname in world_geoms:
        g = next((x for x in wb.findall("geom") if x.get("name") == gname), None)
        if g is None:
            raise ValueError(f"world geom {gname!r} not found")
        geoms.append((gname, None, "body", False, "world"))
    # exclusions by declaration
    ex = [(re.compile(e["bodies"][0]), re.compile(e["bodies"][1]), e["reason"]) for e in decl.get("exclude", [])]
    used = [False] * len(ex)
    bn = lambda b: "world" if b is None else info[b]["norm"] or info[b]["name"]
    rules = decl.get("rules", {})
    out = Plan(tag=f"{prefix}selfcol{suffix}",
               parts={info[b]["name"]: (i["part"], i["tool"]) for b, i in info.items() if i["part"] is not None})
    seen_ex = set()
    for x in range(len(geoms)):
        for y in range(x + 1, len(geoms)):
            g1, b1, p1, t1, w1 = geoms[x]
            g2, b2, p2, t2, w2 = geoms[y]
            if b1 is b2 and b1 is not None:
                continue
            k1, k2 = kind(p1), kind(p2)
            if k1 == "arm" and k2 == "arm":
                if p1 != p2:
                    rule = "arm_arm"
                elif t1 != t2:
                    rule = "tool_own_arm"
                elif not t1 and rules.get("same_arm", False):
                    rule = "same_arm"
                else:
                    continue
            elif k1 == "arm" or k2 == "arm":           # an arm (or its tool) with the body or a leg
                rule = "tool_body" if (t1 or t2) else "arm_body"
            elif k1 == "leg" and k2 == "leg":
                rule = "leg_leg" if p1 != p2 else "same_leg"
                if not rules.get(rule, False):
                    continue
            else:                                       # body x body, leg x body: not tested
                continue
            if not rules.get(rule if rule != "tool_body" else "arm_body", True):
                continue
            if adjacent(w1, w2):
                key = tuple(sorted((bn(b1), bn(b2))))
                if key not in seen_ex:
                    seen_ex.add(key)
                    out.excluded.append((*key, "AUTO: one rigid group, or two joined by one joint (the joint's "
                                                "housing; MuJoCo's parent filter)"))
                continue
            n1, n2 = bn(b1), bn(b2)
            hit = None
            for k, (ra, rb, why) in enumerate(ex):
                if (ra.fullmatch(n1) and rb.fullmatch(n2)) or (ra.fullmatch(n2) and rb.fullmatch(n1)):
                    hit = k
                    break
            if hit is not None:
                used[hit] = True
                key = tuple(sorted((n1, n2)))
                if key not in seen_ex:
                    seen_ex.add(key)
                    out.excluded.append((*key, ex[hit][2]))
                continue
            out.pairs.append((g1, g2, n1, n2, rule))
    out.unused_exclusions = [decl["exclude"][k]["bodies"] for k in range(len(ex)) if not used[k]]
    return out


def is_tag(name: str | None, tag: str) -> bool:
    """A pair name of this robot: <tag>_<i> exactly (robot A's tag "selfcol" must not take robot B's "selfcol_b_3")."""
    return bool(name) and re.fullmatch(re.escape(tag) + r"_\d+", name) is not None


def info(p: Plan | None) -> dict:
    """What a body's mount() returns about its self-collision (p None: switched off)."""
    if p is None:
        return {"selfcol_tag": None, "selfcol_pairs": 0, "selfcol_unused": [], "selfcol_plan": None}
    return {"selfcol_tag": p.tag, "selfcol_pairs": len(p.pairs), "selfcol_unused": p.unused_exclusions,
            "selfcol_plan": p}


SOLREF = "0.005 1"      # stiff (5 ms, critically damped): the shells are rigid; MuJoCo's default 0.02 lets a servo
                        # pushing at its torque limit sink an arm 2 cm into the body (conformance 9)


def pair_elements(p: Plan) -> list[ET.Element]:
    return [ET.Element("pair", name=f"{p.tag}_{i}", geom1=g1, geom2=g2, solref=SOLREF)
            for i, (g1, g2, *_r) in enumerate(p.pairs)]


def add_pairs(scene: ET.Element, p: Plan) -> int:
    """Append the plan's pairs to the scene's <contact> (created if missing). Returns the number of pairs."""
    con = scene.find("contact")
    if con is None:
        con = ET.SubElement(scene, "contact")
    for el in pair_elements(p):
        con.append(el)
    return len(p.pairs)


def scene_block(plans: list[Plan], indent: str = "    ") -> str:
    """The pairs of fixed scenes (a sport's MJCF file) as text between the generated-block markers."""
    lines = [indent + MARK_BEGIN]
    for p in plans:
        for el in pair_elements(p):
            lines.append(indent + ET.tostring(el, encoding="unicode"))
    lines.append(indent + MARK_END)
    return "\n".join(lines)


def put_scene_block(text: str, block: str) -> str:
    """Insert (or replace) the generated block in an MJCF text: inside <contact> (created before </mujoco>)."""
    if MARK_BEGIN in text:
        a = text.index(MARK_BEGIN)
        a = text.rfind("\n", 0, a) + 1
        b = text.index(MARK_END) + len(MARK_END)
        return text[:a] + block.lstrip("\n") + text[b:]
    i = text.rfind("</contact>")
    if i >= 0:
        i = text.rfind("\n", 0, i) + 1                 # the start of the </contact> line
        return text[:i] + block + "\n" + text[i:]
    j = text.rfind("</mujoco>")
    return text[:j] + "  <contact>\n" + block + "\n  </contact>\n" + text[j:]


def sport_scenes(sport_dir: Path) -> list[tuple[Path, list[Plan]]]:
    """The scenes of a sport that carries a library arm in its own scene (sport.toml [self_collision]: body, and
    [[self_collision.scenes]]: scene, robots = [{prefix, suffix, world_geoms}], geoms = "collision" | "physical")
    with their plans (stdlib only)."""
    import tomllib
    st = tomllib.loads((sport_dir / "sport.toml").read_text())
    sc = st.get("self_collision") or {}
    decl = tomllib.loads((HERE / sc["body"] / "body.toml").read_text())["self_collision"]
    out = []
    for e in sc.get("scenes", []):
        f = sport_dir / e["scene"]
        root = ET.fromstring(f.read_text())
        plans = [plan(root, decl, prefix=r.get("prefix", ""), suffix=r.get("suffix", ""),
                      world_geoms=r.get("world_geoms", ()), select=SELECT[e.get("geoms", "collision")],
                      name_unnamed=False) for r in e["robots"]]
        out.append((f, plans))
    return out


def write_sport_scenes(sport_dir: Path) -> list[str]:
    """Write (or refresh) the generated pair blocks of a sport's scenes. Returns what it did."""
    done = []
    for f, plans in sport_scenes(sport_dir):
        text = f.read_text()
        new = put_scene_block(text, scene_block(plans))
        if new != text:
            f.write_text(new)
        done.append(f"{f}: {sum(len(p.pairs) for p in plans)} pairs" + ("" if new != text else " (unchanged)"))
    return done


def scene_pairs(text: str) -> list[tuple[str, str, str]]:
    """The (name, geom1, geom2) of the generated block of an MJCF text (stdlib: for the static CI check)."""
    if MARK_BEGIN not in text:
        return []
    blk = text[text.index(MARK_BEGIN):text.index(MARK_END)]
    return re.findall(r'<pair name="([^"]+)" geom1="([^"]+)" geom2="([^"]+)"', blk)


# ------------------------------------------------------------------------------------------------ during play
class Monitor:
    """Self-collision contacts of one robot (its pairs: names <tag>_<i>), fed once per physics step (rig.apply, or
    the sport's loop). An event is a pair coming into contact (after more than GAP_S out of contact: a bouncing
    contact is one event); per event its peak normal force and its peak 10 ms mean force (FORCE_WINDOW_S: what a
    real robot's collision detection, which filters its external-force estimate, would see; an impact's
    instantaneous peak depends on the contact stiffness). An event whose 10 ms mean force exceeds warn_force_n is a
    warning. Also the time in contact, the impulse, the deepest penetration. Nothing it does changes the simulation."""

    GAP_S = 0.02
    FORCE_WINDOW_S = 0.01

    def __init__(self, model, tag: str, warn_force_n: float | None = None):
        import numpy as np
        import mujoco as mj
        self.m = model                           # no module attributes: a sport may pickle its simulator with it
        self.tag, self.warn = tag, warn_force_n
        ng = model.ngeom
        keys, names = [], {}
        gn = lambda g: mj.mj_id2name(model, mj.mjtObj.mjOBJ_GEOM, g)
        for i in range(model.npair):
            if is_tag(mj.mj_id2name(model, mj.mjtObj.mjOBJ_PAIR, i), tag):
                a, b = int(model.pair_geom1[i]), int(model.pair_geom2[i])
                k = min(a, b) * ng + max(a, b)
                keys.append(k)
                names[k] = (gn(a), gn(b))
        self.keys = np.array(sorted(keys), dtype=np.int64)
        self.names = names
        self.dt = float(model.opt.timestep)
        self.gap = max(1, int(round(self.GAP_S / self.dt)))
        self.win = max(1, int(round(self.FORCE_WINDOW_S / self.dt)))
        self._f = np.zeros(6)
        self.reset()

    @property
    def npairs(self):
        return int(self.keys.size)

    def reset(self):
        self.t = 0
        self.open: dict[int, dict] = {}          # pair key -> the running event
        self.events = 0
        self.warnings = 0
        self.steps_in_contact = 0
        self.peak_force = 0.0
        self.peak_force_10ms = 0.0
        self.max_depth = 0.0
        self.impulse = 0.0
        self.first_t = None
        self.by_pair: dict[int, list] = {}       # key -> [events, peak force, peak 10 ms mean force]

    def update(self, d):
        """One physics step: the contacts MuJoCo found in the last step (d.contact, d.efc_force)."""
        self.t += 1
        n = d.ncon
        if self.keys.size == 0 or (n == 0 and not self.open):
            return
        import numpy as np
        import mujoco as mj
        now: dict[int, float] = {}
        if n:
            g = d.contact.geom[:n]
            k = np.minimum(g[:, 0], g[:, 1]).astype(np.int64) * self.m.ngeom + np.maximum(g[:, 0], g[:, 1])
            for i in np.nonzero(np.isin(k, self.keys))[0]:
                mj.mj_contactForce(self.m, d, int(i), self._f)
                f = abs(float(self._f[0]))
                kk = int(k[i])
                now[kk] = now.get(kk, 0.0) + f
                self.impulse += f * self.dt
                self.max_depth = max(self.max_depth, -float(d.contact.dist[i]))
        for kk in now:
            if kk not in self.open:
                self.events += 1
                if self.first_t is None:
                    self.first_t = self.t
                self.by_pair.setdefault(kk, [0, 0.0, 0.0])[0] += 1
                self.open[kk] = {"w": [0.0] * self.win, "i": 0, "s": 0.0, "peak": 0.0, "avg": 0.0, "last": self.t}
        for kk in list(self.open):
            ev = self.open[kk]
            f = now.get(kk, 0.0)
            w, i = ev["w"], ev["i"]
            ev["s"] += f - w[i]
            w[i] = f
            ev["i"] = (i + 1) % self.win
            if f > 0.0:
                ev["last"] = self.t
                ev["peak"] = max(ev["peak"], f)
            ev["avg"] = max(ev["avg"], ev["s"] / self.win)
            bp = self.by_pair[kk]
            bp[1], bp[2] = max(bp[1], ev["peak"]), max(bp[2], ev["avg"])
            self.peak_force = max(self.peak_force, ev["peak"])
            self.peak_force_10ms = max(self.peak_force_10ms, ev["avg"])
            if self.t - ev["last"] > self.gap:      # out of contact for longer than the gap: the event is over
                self._close(kk)
        if now:
            self.steps_in_contact += 1

    def _close(self, kk):
        ev = self.open.pop(kk)
        if self.warn is not None and ev["avg"] > self.warn:
            self.warnings += 1

    def summary(self, top: int = 5) -> dict:
        """What a match record carries (JSON-safe)."""
        open_warn = sum(1 for ev in self.open.values() if self.warn is not None and ev["avg"] > self.warn)
        worst = sorted(self.by_pair.items(), key=lambda kv: -kv[1][2])[:top]
        return {"pairs": self.npairs, "events": self.events, "warnings": self.warnings + open_warn,
                "warn_force_n": self.warn, "time_in_contact_s": round(self.steps_in_contact * self.dt, 4),
                "peak_force_n": round(self.peak_force, 3), "peak_force_10ms_n": round(self.peak_force_10ms, 3),
                "impulse_ns": round(self.impulse, 5), "max_depth_m": round(self.max_depth, 5),
                "first_step": self.first_t,
                "worst_pairs": [{"geoms": list(self.names[k]), "events": v[0], "peak_force_n": round(v[1], 3),
                                 "peak_force_10ms_n": round(v[2], 3)} for k, v in worst]}


def monitors(model, tags: dict, body: str) -> dict:
    """One Monitor per seat ({seat: pair tag}) for a sport whose scene carries the library arm `body` (its
    body.toml [self_collision] warn_force_n): for the sports' own simulators (sport.toml [self_collision])."""
    import tomllib
    warn = tomllib.loads((HERE / body / "body.toml").read_text())["self_collision"].get("warn_force_n")
    return {seat: Monitor(model, tag, warn) for seat, tag in tags.items()}


# ------------------------------------------------------------------------------------------------ the check
def rig_sampler(rig, m, rest_qpos):
    """Random legal poses of a library robot: the controlled vector u (lift, waist, the hand arm) uniform inside the
    rig's ranges (rig.LO / rig.HI; the base and the walking command at rest), the other arm's joints uniform inside
    their MJCF ranges; a legged robot's legs uniform in their ranges (its pelvis where it stands); the base at rest."""
    import numpy as np
    o = getattr(rig, "o", 0)
    other = rig.qadr[-7:]
    jr = {int(m.jnt_qposadr[j]): m.jnt_range[j] for j in range(m.njnt)}
    lo_o = np.array([jr[int(a)][0] for a in other])
    hi_o = np.array([jr[int(a)][1] for a in other])
    legs = rig.lqadr if not getattr(rig, "fixed_base", True) else []   # a legged robot's legs: uniform too
    lo_l = np.array([jr[int(a)][0] for a in legs])
    hi_l = np.array([jr[int(a)][1] for a in legs])

    def sample(rng):
        u = np.array(rig.rest, float)
        u[3:] = rng.uniform(rig.LO[3:], rig.HI[3:])
        q = rest_qpos.copy()
        t = rig.joint_targets(u)
        q[rig.qadr[o:]] = t[o:]
        q[other] = rng.uniform(lo_o, hi_o)
        if len(legs):
            q[legs] = rng.uniform(lo_l, hi_l)
        return q
    return sample


def check_model(m, tag, rest_qpos, sample, n_random=200, seed=0, structural=0.95, tol=1e-4):
    """The static self-collision check of one compiled model: (problems, report). At rest_qpos no pair of `tag`
    penetrates (more than tol); over n_random random legal poses (sample(rng) -> qpos) no pair penetrates in more
    than `structural` of them (a mount overlap: exclude it with a reason)."""
    import numpy as np
    import mujoco as mj
    d = mj.MjData(m)
    pairs = [i for i in range(m.npair) if is_tag(mj.mj_id2name(m, mj.mjtObj.mjOBJ_PAIR, i), tag)]
    gname = lambda g: mj.mj_id2name(m, mj.mjtObj.mjOBJ_GEOM, int(g))
    dist = lambda i, cut: mj.mj_geomDistance(m, d, int(m.pair_geom1[i]), int(m.pair_geom2[i]), cut, None)
    probs = []
    d.qpos[:] = rest_qpos
    mj.mj_kinematics(m, d)
    rest_pen, closest = [], (None, 1.0)
    for i in pairs:
        x = dist(i, 0.05)
        if x < closest[1]:
            closest = ((gname(m.pair_geom1[i]), gname(m.pair_geom2[i])), x)
        if x < -tol:
            rest_pen.append((gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), round(float(x), 4)))
    for a, b, x in rest_pen:
        probs.append(f"at rest {a} x {b} penetrate by {-x * 100:.2f} cm (fix the rest pose or exclude the pair "
                     "with a reason)")
    rng = np.random.default_rng(seed)
    cnt = np.zeros(len(pairs), int)
    any_hit = 0
    for _ in range(n_random):
        d.qpos[:] = sample(rng)
        mj.mj_kinematics(m, d)
        hit = False
        for k, i in enumerate(pairs):
            if dist(i, 0.01) < -tol:
                cnt[k] += 1
                hit = True
        any_hit += hit
    for k, i in enumerate(pairs):
        if cnt[k] > structural * n_random:
            probs.append(f"{gname(m.pair_geom1[i])} x {gname(m.pair_geom2[i])} penetrate in {cnt[k]} of {n_random} "
                         "random legal poses: a structural overlap (exclude it with a reason)")
    report = {"pairs": len(pairs), "rest_penetrating": rest_pen,
              "rest_closest": [list(closest[0] or ()), round(float(closest[1]), 4)],
              "random_poses": n_random, "random_poses_with_self_contact": int(any_hit),
              "most_frequent": sorted(([gname(m.pair_geom1[i]), gname(m.pair_geom2[i]), int(cnt[k])]
                                       for k, i in enumerate(pairs) if cnt[k]), key=lambda x: -x[2])[:5]}
    return probs, report


def configurations():
    """The hands a library robot is checked with: none, then every hand of bodies/hands/hands.toml on the right
    wrist, with its status (a "ready" hand fails the check, a "draft" hand only warns)."""
    import tomllib
    hands = tomllib.loads((HERE / "hands" / "hands.toml").read_text())
    return [(None, "ready")] + [(h, v.get("status", "draft")) for h, v in hands.items()]


def compiled(B, hand, other_hand=None, **kw):
    """One library robot (prefix A_) alone in an empty world: (model, info)."""
    import mujoco as mj
    root = ET.Element("mujoco", model="selfcol_check")
    ET.SubElement(root, "compiler", angle="radian", autolimits="true")
    ET.SubElement(root, "option", timestep="0.001")
    for sec in ("default", "asset", "worldbody"):
        ET.SubElement(root, sec)
    if other_hand:
        kw["other_hand"] = other_hand
    info = B.mount(root, "A_", (0.0, 0.0, 0.0), 0.0, hand=hand, **kw)
    return mj.MjModel.from_xml_string(ET.tostring(root, encoding="unicode")), info


def check_body(name, n_random=200) -> tuple[list, list, dict]:
    """(failures, warnings, report) of one library robot: its declaration is used (no unused exclusion), and in
    every configuration the model passes check_model at the rest pose and over random legal poses."""
    import mujoco as mj
    sys.path.insert(0, str(HERE.parent))
    from bodies import load_body
    B = load_body(name)
    fails, warns, rep = [], [], {}
    unused = None
    for hand, status in configurations():
        m, info = compiled(B, hand)
        d = mj.MjData(m)
        rig = B.rig(m, "A_", hand=hand)
        rig.place(d, rig.rest)
        q0 = d.qpos.copy()
        probs, r = check_model(m, info["selfcol_tag"], q0, rig_sampler(rig, m, q0), n_random=n_random)
        rep[hand or "none"] = r
        u = set(map(tuple, info["selfcol_unused"]))
        unused = u if unused is None else unused & u          # unused with every hand
        for p in probs:
            (fails if status == "ready" else warns).append(f"{name} hand={hand or 'none'}: {p}")
        if r["pairs"] == 0:
            fails.append(f"{name} hand={hand or 'none'}: no self-collision pair")
    for u in sorted(unused or ()):
        fails.append(f"{name}: exclusion {list(u)} matches no geom pair (remove it)")
    return fails, warns, rep


def main(argv=None):
    import argparse
    import json
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("cmd", choices=["check", "pairs", "scene"])
    ap.add_argument("robots", nargs="*")
    ap.add_argument("--random", type=int, default=200)
    ap.add_argument("--json")
    a = ap.parse_args(argv)
    sys.path.insert(0, str(HERE.parent))
    from bodies import BODIES
    if a.cmd == "scene":                      # robots = sport directories: write their scenes' generated blocks
        for sd in a.robots:
            for line in write_sport_scenes(Path(sd)):
                print(line)
        return 0
    robots = a.robots or list(BODIES)
    if a.cmd == "pairs":
        from bodies import load_body
        for r in robots:
            B = load_body(r)
            root = ET.Element("mujoco")
            for sec in ("default", "asset", "worldbody"):
                ET.SubElement(root, sec)
            p = B.mount(root, "", (0.0, 0.0, 0.0), 0.0, hand="paddle")["selfcol_plan"]
            print(f"== {r}: {p.summary()}")
            for x in p.pairs:
                print(f"   pair  {x[4]:13s} {x[2]} / {x[0]}  x  {x[3]} / {x[1]}")
            for x in p.excluded:
                print(f"   excl  {x[0]} x {x[1]}: {x[2]}")
        return 0
    allf, out = [], {}
    for r in robots:
        f, w, rep = check_body(r, a.random)
        out[r] = {"failures": f, "warnings": w, "report": rep}
        for x in w:
            print("WARN [self-collision]", x)
        for x in f:
            print("FAIL [self-collision]", x)
        print(f"self-collision {r}: " + ", ".join(f"{h}: {v['pairs']} pairs, {v['random_poses_with_self_contact']}/"
                                                  f"{v['random_poses']} random poses in contact"
                                                  for h, v in rep.items()) + ("" if f else "; ok"))
        allf += f
    if a.json:
        Path(a.json).write_text(json.dumps(out, indent=1))
    return 1 if allf else 0


if __name__ == "__main__":
    sys.exit(main())