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.
Python ai-agentsbenchmarkcoding-agentsembodied-aievaluationharborllm-agentsrobot-learningroboticssimulation
"""The Embodied Olympics - Fun world: one Unitree G1 of the Embodied Olympics robot library (its g1-4: Menagerie's 29-joint G1, its real
joint, speed and torque limits, its motor torque-speed curves, its self-collision) in a sports venue, the action
layer every task shares, the hands' grip, and the stepping that the referee (referee.py) watches.
One control step is 10 ms = 10 physics steps of 1 ms (the robot library's). Everything that changes the world happens
in World.step(row): the row is a "sim row" (RAW_DIM floats), the action in the simulator's own space, and the list of
sim rows replays an episode bit-exactly in a fresh process. The agent's action types (ACTION_TYPES) are views of it.
Who drives the joints (row[0], the mode):
stand the platform holds the legs in the stance (the walking policy's default leg angles on the stand gains with
gravity support); the row's 17 waist and arm targets drive the upper body
walk Unitree's own walking policy drives the legs from the row's velocity command (vx, vy, wz; Embodied Olympics'
joint-group arbiter, the handover to the policy included); the row's waist and arm targets drive the rest
run Embodied Olympics' athletics running policy drives all 29 joints from the velocity command
run_arms the running policy drives the legs and the waist; the row's 14 arm targets drive the arms
joints the row drives all 29 joints: position targets, velocity targets, feed-forward torques and PD gains
(Unitree's LowCmd: tau = kp (q - q_meas) + kd (dq - dq_meas) + tau_ff), at 1 kHz
Every joint target is clipped into the joint's range and moves at most the joint's speed limit per step; every motor
torque goes through the robot library's output stage (torque-speed curve, torque limit).
"""
from __future__ import annotations
import hashlib
import importlib
import json
import math
import os
import re
import sys
import xml.etree.ElementTree as ET
import numpy as np
import mujoco
SIM_DIR = os.environ.get("RFO_SIM_DIR", "/opt/roboolympics")
for _p in (os.path.join(SIM_DIR, "athletics"), SIM_DIR):
if _p not in sys.path:
sys.path.insert(0, _p)
from bodies import load_body # noqa: E402
from bodies.control.arbiter import Arbiter # noqa: E402
from bodies.unitree_g1 import body as G1B # noqa: E402
import run_policy as RP # noqa: E402
from bodies.unitree_g1.agile import Agile # noqa: E402
from bodies.unitree_g1.falcon import Falcon # noqa: E402
from . import looks # noqa: E402
from . import realhand # noqa: E402
from .referee import Referee # noqa: E402
from .scene import Scene # noqa: E402
# The robots of the library a task may use (Task.robot): the Unitree G1 (1.32 m, 33 kg, 29 joints; a walking and a running
# policy) and the Unitree H1-2 (1.78 m, 67 kg, 27 joints; a walking policy; H2-class leg actuators, below), each
# with its real limits and motor curves.
ROBOTS = {
"unitree_g1": dict(title="Unitree G1", height_m=1.32, run=True, walkers=True,
source="MuJoCo Menagerie's unitree_g1 with Unitree's joint, speed and torque limits and motor "
"torque-speed curves"),
"unitree_h1": dict(title="Unitree H1-2", height_m=1.78, run=False, walkers=False,
source="the H1-2 body (Unitree's own h1_2 model, its joint ranges and speed limits) with Unitree "
"H2 / H2-X-class leg actuators from the H2's official URDF (hips and knees 360 N m, "
"ankle pitch 66.88 N m; curves of Unitree's M107 shape, 2.5 kW peak per joint) and "
"H2-class arm actuators from the same URDF (shoulder pitch 130 N m; shoulder roll and "
"yaw, elbow, forearm roll 60 N m; curves of Unitree's N7520 / N5020 shapes); the H1-2's "
"own torso (M107-15, 200 N m), ankle roll and wrist pitch / yaw (estimates)"),
}
BODY = load_body("unitree_g1")
ROBOT_REVISION = BODY.revision
CONTROL_DT = float(BODY.dt) # 10 ms (both robots)
SUB = int(BODY.substeps) # 10 physics steps of 1 ms
PHYS_DT = CONTROL_DT / SUB
HEAD_PITCH_RAD = 0.35 # the head camera's tilt below the horizon
JOINTS = list(G1B.LEGS) + list(G1B.TORSO) + [f"left_{j}_joint" for j in G1B.ARM] + [f"right_{j}_joint" for j in G1B.ARM]
NJ = len(JOINTS) # 29, the Unitree SDK order
LEGS, WAIST, ARMS, UPPER = slice(0, 12), slice(12, 15), slice(15, 29), slice(12, 29)
GROUP_NAMES = ("legs", "waist", "arms")
SIDES = ("left", "right")
# ------------------------------------------------------------------------------------------------ the sim row
MODES = ("stand", "walk", "run", "run_arms", "joints", "walk_falcon", "walk_agile")
STAND, WALK, RUN, RUN_ARMS, JOINT, WALK_FALCON, WALK_AGILE = range(7)
WALKERS = (WALK_FALCON, WALK_AGILE) # the G1's optional walking policies (FALCON, AGILE), from the robot library
R_MODE, R_CMD, R_Q, R_DQ, R_TAU, R_KP, R_KD, R_GRIP = (0, slice(1, 4), slice(4, 33), slice(33, 62), slice(62, 91),
slice(91, 120), slice(120, 149), slice(149, 151))
RAW_DIM = 151 # the G1's (the module-level layout names are the G1's; a world has its own: Layout)
class Layout:
"""A robot's joint groups and its sim row: [mode, vx, vy, wz, q, dq, tau, kp, kd (nj each), grip_left, grip_right].
The joints are in the robot's SDK order: left leg 6, right leg 6, waist (the G1: yaw, roll, pitch; the H1-2: one
torso yaw), left arm 7, right arm 7."""
def __init__(self, joints: list[str], n_waist: int):
nj = len(joints)
self.JOINTS, self.NJ, self.NW, self.NU = list(joints), nj, n_waist, nj - 12
self.LEGS, self.WAIST = slice(0, 12), slice(12, 12 + n_waist)
self.ARMS, self.UPPER = slice(12 + n_waist, nj), slice(12, nj)
self.R_Q, self.R_DQ, self.R_TAU, self.R_KP, self.R_KD = (slice(4 + i * nj, 4 + (i + 1) * nj) for i in range(5))
self.R_GRIP = slice(4 + 5 * nj, 6 + 5 * nj)
self.RAW_DIM = 6 + 5 * nj
RUN_CMD = np.array([[0.0, 5.0], [-0.12, 0.12], [-0.5, 0.5]]) # the running policy's command ranges
STAND_RATE = 1.5 # rad/s: how fast `stand` brings the legs to the stance
GRIP_REACH = 0.035 # m: a hand grips an object whose surface is this close to its palm
GRIP_SPEED = 6.0 # m/s: ... and that moves no faster than this relative to the palm
FALL_Z = 0.35 # m: the pelvis below this is down (tasks that allow it say so)
UNSTABLE = "the simulation became unstable" # the referee's reason when the physics diverges (an attempt's failure)
MAX_SPEED = 150.0 # m/s: the robot or a prop faster than this is a divergence too
# The robot's visible body where its collision model has no geometry: the H1-2's thighs and shins are four rods 4 cm
# thick and 20 cm long plus two 1 cm discs (up to 0.44 m of visible thigh outside any collision geom), its knees, hips
# and wrist motor housings have none; the G1's waist (yaw and roll links) and its shoulders' outer housings have none;
# the hands (the G1's rubber fist, the H1-2's Inspire fingers: up to 77 mm outside the palm pad) are looks only.
# A prop (a bar, a rope, a ball, a hurdle, an opponent) went through them. Each such visual mesh gets a shell: its
# convex hull, massless, that touches only the props (contype 0, conaffinity SHELL_BIT; every prop but the ground gets
# SHELL_BIT in its contype): not the floor or the ground, not the robot itself (self-collision, the feet on the ground
# and the walking policies unchanged). The hands' shells too (the fist, the fingers: props only); the palm pad stays
# the hand's model for holding.
# The feet keep their own (the sole and the strike box), the hand mounts theirs (the palm pad, the task's tool or the
# real hand, which replaces the fist / fingers); the torso's logo plate lies inside the torso's hull. A shell's contact
# is stiff, a rigid prop on the robot's aluminium shell: solref 0.004 s (4 physics steps; MuJoCo keeps timeconst >= 2
# timesteps stable), solimp 0.99 0.999 0.0005 (MuJoCo's default soft contact let a heavy bar sink 12-44 mm), and a
# solmix that makes them win against a prop of default priority; a prop with a priority of its own (a ball: its bounce,
# scene.py) keeps its own parameters.
# Source: the Embodied Olympics weightlifting fix (CHIGUI0/roboolympics PR #179 at f54e26a8, sports/weightlifting/
# venue.py `_shells` and BAR_CONTACT, MIT; library issue CHIGUI0/roboolympics #268): <= 3.2 mm at 190 kg.
# The robot's own collision geoms (the body hulls, the palm pads, the feet's strike boxes, a real hand's housing and
# fingers) get the same stiff contact (ROBOT_CONTACT) against props, mechanisms and fixtures (not the ground:
# GROUND_SOLMIX): with MuJoCo's default (solref 0.02 1, solimp 0.9 0.95 0.001) a rigid prop or a machine's part sank
# 20-75 mm into them (a stress test). Not the soles (contype 1: the G1's four sole
# spheres, the H1-2's sole hulls; SOLE_CONTACT, below) nor a geom with a priority of its own (the real hand's pads).
SHELL_BIT = 128 # a bit no family uses (they use 1-64)
SHELL_CONTACT = dict(solref="0.004 1", solimp="0.99 0.999 0.0005 0.5 2", solmix="1e+06")
ROBOT_CONTACT = SHELL_CONTACT
# The soles (SOLE_CONTACT) keep the robot model's own contact (MuJoCo's default; the G1's sole spheres priority 1):
# they sink 6 mm walking, 15 mm under FALCON, 54 mm stamping (random leg torques), the H1-2's 14 / 37 mm (114 mm in
# the stress test). Stiffer soles were measured (a stress test; solref 0.01 / 0.005 / 0.004,
# solimp 0.95-0.99 / 0.99-0.999, priority 1): every policy still does its job at every setting (G1: walk, FALCON and
# AGILE 10 m, turn 360 deg, run 50 m; H1-2: walk 10 m, turn 360 deg) and at 0.004 / 0.99-0.999 the soles sink 0.4 mm
# standing, 1.3 walking, 4.0 stamping, but open-loop controllers tuned on these soles (throws, kicks, serves,
# sets) then fail; the soles keep the model's own contact.
SOLE_CONTACT: dict | None = None
# The ground keeps its own contact with everything: the ground and the fixed surfaces one stands
# on (sc.ground, planes, height fields, fixed STANDABLE geoms: a beam, a platform, a vaulting table) of no priority
# get GROUND_SOLMIX, so that in a contact with any geom of no priority (the robot's stiffened geoms, a family's rigid
# prop) their own parameters (MuJoCo's default, or a mat's) win, as before the stiffening; a geom with a priority
# (a ball, a sole, a mat of priority 1) keeps winning as before.
GROUND_SOLMIX = "1e+12"
SHELL_SKIP_BODY = ("ankle_roll_link", "_mount") # no shell: the feet and the hand mounts (pads, tools, real hands)
SHELL_SKIP_MESH = ("logo",) # the logo plate (mesh name); the hands (the G1's fist, the
# H1-2's fingers) get shells like the rest (props only)
GRIPS = ["grip_left", "grip_right"]
VEL = ["vx", "vy", "wz"]
def walker_cmd(pol, cmd_max) -> tuple[np.ndarray, np.ndarray]:
"""The command range of an optional walking policy: its training range (FALCON: +-command_max; AGILE: command_min
to command_max) within the robot's own walking limits (cmd_max, [limits.walk])."""
cmd_max = np.asarray(cmd_max, float)
lo = getattr(pol, "cmd_min", -pol.cmd_max)
return np.maximum(np.asarray(lo, float)[:3], -cmd_max), np.minimum(np.asarray(pol.cmd_max, float)[:3], cmd_max)
def _shells(root: ET.Element, ground: set, skip: set = frozenset()) -> None:
"""The robot's shells (SHELL_BIT, above): one on every visual mesh of the robot that no collision geom of its own
body covers (the same mesh), named <body>_shell<i>; SHELL_BIT on the contype of every collidable geom outside the
robot but the ground (sc.ground, planes, height fields)."""
defaults: dict[str, dict] = {} # class -> its geom defaults (MuJoCo's inheritance)
def scan(el, name, inherited):
own = dict(inherited)
for g in el.findall("geom"):
own.update(g.attrib)
defaults[name] = own
for c in el.findall("default"):
scan(c, c.get("class"), own)
top = root.find("default")
if top is not None:
scan(top, "main", {})
def resolved(g, cls, key, dflt="1"):
return g.get(key, defaults.get(g.get("class") or cls, {}).get(key, dflt))
def robot(b): # the robot's links (not the hand mounts: pads, tools, real hands)
name = b.get("name") or ""
if name.endswith("_mount"):
return
gs = b.findall("geom")
vis = [g for g in gs if g.get("mesh") and ((g.get("class") or "").endswith("_visual")
or (g.get("contype") == "0" and g.get("conaffinity") == "0"))]
covered = {g.get("mesh") for g in gs if g.get("mesh") and g not in vis}
if not any(k in name for k in SHELL_SKIP_BODY) and name not in skip: # (skip: a real hand's fingers)
for i, g in enumerate(x for x in vis if x.get("mesh") not in covered
and not any(k in x.get("mesh") for k in SHELL_SKIP_MESH)):
sh = ET.SubElement(b, "geom", name=f"{name}_shell{i}", type="mesh", mesh=g.get("mesh"), contype="0",
conaffinity=str(SHELL_BIT), group="3", mass="0", rgba="0.3 0.6 0.9 0.35",
**SHELL_CONTACT)
for a in ("pos", "quat", "euler", "axisangle", "xyaxes", "zaxis"):
if g.get(a) is not None:
sh.set(a, g.get(a))
for c in b.findall("body"):
robot(c)
def props(el, cls, fixed=True):
for g in el.findall("geom"):
ct, ca = int(resolved(g, cls, "contype")), int(resolved(g, cls, "conaffinity"))
if (fixed and (ct or ca) and not int(resolved(g, cls, "priority", "0"))
and (g.get("name") in ground or resolved(g, cls, "type") in ("plane", "hfield")
or (ct & 1 and ca & 4 and not ca & 8))):
g.set("solmix", GROUND_SOLMIX) # the ground and the fixed surfaces one stands on (GROUND_SOLMIX)
if g.get("name") in ground or resolved(g, cls, "type") in ("plane", "hfield"):
continue
if ct or ca:
g.set("contype", str(ct | SHELL_BIT))
for c in el.findall("body"):
if c.get("name") != "pelvis":
moves = c.find("joint") is not None or c.find("freejoint") is not None
props(c, c.get("childclass") or cls, fixed and not moves)
def stiff(b, cls): # the robot's own collision geoms (ROBOT_CONTACT, SOLE_CONTACT)
cls = b.get("childclass") or cls
for g in b.findall("geom"):
ct = int(resolved(g, cls, "contype"))
if ct == 1: # a sole
for k, v in (SOLE_CONTACT or {}).items():
g.set(k, v)
elif ct and not int(resolved(g, cls, "priority", "0")) and "_shell" not in (g.get("name") or ""):
for k, v in ROBOT_CONTACT.items(): # (not look-only, shells, geoms with a priority of their own)
g.set(k, v)
for c in b.findall("body"):
stiff(c, cls)
wb = root.find("worldbody")
pelvis = next(b for b in wb.findall("body") if b.get("name") == "pelvis")
robot(pelvis)
props(wb, "main")
stiff(pelvis, pelvis.get("childclass") or "main")
# Self-collision. The robot library's own pairs (bodies/selfcollision.py: body.toml [self_collision], named
# selfcol_<i>) only cover the geoms that collide (contype 4): the G1's Menagerie hulls, the H1-2's thin thigh and shin
# rods. The visible body around them is the shells (above: the G1's waist and shoulder housings and its rubber fists,
# the H1-2's thighs, knees, hips, wrist housings and its Inspire fingers), and the hands are the palm pads, a task's
# tool or a real hand, added here after the library: none of them touched the robot itself. A limb went through the
# body: a shot-put stance with the thumb 2.3 cm inside the shoulder, a put 4.7 cm into it and the other hand
# 6.8 cm into the hip, a volleyball set with the hands 5.7-6.4 cm into each other, the H1-2's arms through each other,
# a flailing G1's knee 9 cm into its pelvis.
# Now every collision geom and every shell of the robot takes part (the shells are the visual meshes' convex hulls:
# the visible body), by the library's parts and rules (body.toml [self_collision]: arm x body (torso, pelvis, head,
# legs), left arm x right arm (hands, pads, tools and real hands included: hand x hand), left leg x right leg, shin x
# foot) and two more: a link x a link of the same arm (the library's same_arm, off for its own arms: a thumb into its
# own shoulder, a forearm folded into the upper arm) and a leg x the body (a knee into the pelvis, a thigh on the
# chest). A hand's own parts (a finger hand's thumb x its fingers) are the hand's (realhand.py). Excluded: two geoms of
# one rigid group or of two groups joined by one joint (the library's automatic exclusion: the joint's housing), the
# library's declared exclusions, HAND_CARRIER and SELF_EXCLUDE (below: hulls that overlap by construction two joints
# apart, measured at the rest pose and over random legal poses, each with its reason).
# The contact is the shells' stiff one (SHELL_CONTACT: the robot's rigid aluminium / plastic shell on itself; the
# library's 0.005 s on MuJoCo's default solimp let a servo at its torque limit sink a hand 1-2 cm into the body), on
# MuJoCo's default friction 1 (the library's choice for its pairs). One explicit <pair> per geom pair, so the
# robot's geoms keep their contype / conaffinity: props, the ground and the walking policies see the same robot.
SELF_PAIR = dict(condim="3", solref=SHELL_CONTACT["solref"], solimp=SHELL_CONTACT["solimp"])
# A hand (its pad, tool or real hand, the H1-2's fingers) and the wrist links that carry it: the hand's own business
# (its fingers close into the palm, whose hull is the wrist link's; a finger hand's own pairs, realhand.py); the
# hand against the rest of its own arm (a thumb into its shoulder) stays enabled.
HAND_CARRIER = re.compile(r"(left|right)_wrist_(roll|pitch|yaw)_link")
# SELF_EXCLUDE: measured: every enabled body pair at the rest pose, and over 100 random
# poses of only the joints between the two bodies (the rest at rest). Excluded are the pairs two joints apart whose
# hulls overlap in that sample (a housing round the joint between them: the convex hull fills the recess the other
# link turns in); every pair three or more joints apart stays (an upper arm into the chest is a real collision).
SELF_EXCLUDE = { # (body regex, body regex, reason); {s}: one side (left, right)
"unitree_g1": [
("torso_link", "{s}_shoulder_roll_link",
"shoulder housing (as the library's H1-2): the roll link's shell turns in the torso hull's shoulder recess, "
"40-48% of shoulder pitch x roll poses, up to 73 mm; the upper arm (yaw link) onwards stays enabled"),
("{s}_elbow_link", "{s}_wrist_pitch_link",
"wrist housing: the hulls meet round the wrist roll joint in 9% of its poses, at most 1.7 mm"),
("{s}_wrist_roll_link", "{s}_wrist_yaw_link",
"wrist housing: the hulls meet round the wrist pitch joint in 4-5% of its poses, at most 2.6 mm"),
("pelvis", "{s}_hip_roll_link",
"hip housing: the hulls meet round the hip pitch joint in 5-10% of its poses, up to 25 mm"),
],
"unitree_h1": [
("{s}_knee_link", "{s}_ankle_roll_link",
"ankle housing: the shin's shell reaches down round the ankle pitch joint into the sole's hull (25.7 mm at "
"rest, every ankle pose)"),
("pelvis", "{s}_hip_pitch_link",
"hip housing: the hulls meet round the hip yaw joint in 7-8% of its poses, up to 8 mm"),
("{s}_hip_yaw_link", "{s}_hip_roll_link",
"hip housing: the hulls meet round the hip pitch joint in 29-48% of its poses, up to 42 mm"),
("{s}_elbow_roll_link", "{s}_wrist_yaw_link",
"wrist housing: the hulls overlap round the wrist pitch joint (2.6-7.9 mm at rest, 95-100% of its poses)"),
],
}
def _self_collision(root: ET.Element, robot: str, decl: dict, keep=()) -> dict:
"""Replace the library's self-collision pairs by the full set (above). keep: pairs (geom1, geom2) a hand adds
itself (a finger hand's thumb x its fingers), left out here. Returns {"pairs": n, "excluded": [(b1, b2, why)]}."""
contact = root.find("contact")
if contact is None:
contact = ET.SubElement(root, "contact")
for p in list(contact.findall("pair")): # the library's pairs (all inside this set)
if re.fullmatch(r"selfcol_\d+", p.get("name") or ""):
contact.remove(p)
defaults: dict[str, dict] = {}
def scan(el, name, inherited):
own = dict(inherited)
for g in el.findall("geom"):
own.update(g.attrib)
defaults[name] = own
for c in el.findall("default"):
scan(c, c.get("class"), own)
top = root.find("default")
if top is not None:
scan(top, "main", {})
parts = {k: re.compile(v) for k, v in decl["parts"].items()}
ignore = re.compile(decl["ignore_geoms"]) if decl.get("ignore_geoms") else None
rules = dict(decl.get("rules", {}))
ex = [(re.compile(e["bodies"][0]), re.compile(e["bodies"][1]), e["reason"]) for e in decl.get("exclude", [])]
ex += [(re.compile(a.format(s=s)), re.compile(b.format(s=s)), why)
for a, b, why in SELF_EXCLUDE.get(robot, []) for s in SIDES]
wb = root.find("worldbody")
pelvis = next(b for b in wb.findall("body") if b.get("name") == "pelvis")
info: dict = {} # body name -> (part, hand, weld group, parent's weld group)
geoms: list = [] # (geom, body, part, hand, weld group)
def walk(b, cls, part, hand, weld, pweld):
name = b.get("name") or ""
cls = b.get("childclass") or cls
own = next((k for k, rx in parts.items() if rx.fullmatch(name)), None)
if own is not None:
part = own
# the hand: the wrist mount and all below it (pad, tool, real hand), the H1-2's Inspire fingers (L_*, R_*)
hand = hand or name.endswith("_mount") or name.startswith(("L_", "R_"))
if b.find("joint") is not None or b.find("freejoint") is not None:
pweld, weld = weld, name
info[name] = (part, hand, weld, pweld)
k = 0
for g in b.findall("geom"):
a = dict(defaults.get(g.get("class") or cls, {}))
a.update(g.attrib)
if int(a.get("contype", "1")) == 0 and int(a.get("conaffinity", "1")) == 0:
continue # a look
if g.get("name") is None:
g.set("name", f"{name}_sc{k}")
k += 1
if ignore is not None and ignore.fullmatch(g.get("name")):
continue # a sensing volume (the kick's strike boxes)
geoms.append((g.get("name"), name, part, hand, weld))
for c in b.findall("body"):
walk(c, cls, part, hand, weld, pweld)
walk(pelvis, pelvis.get("childclass") or "main", None, False, "world", None)
pw = {w: p for _, _, w, p in info.values()}
kind = lambda p: "arm" if p.endswith("arm") else "leg" if p.endswith("leg") else "body" # noqa: E731
keep = {tuple(sorted(k)) for k in keep}
excluded, seen, out = [], set(), []
for i in range(len(geoms)):
g1, b1, p1, t1, w1 = geoms[i]
for j in range(i + 1, len(geoms)):
g2, b2, p2, t2, w2 = geoms[j]
if b1 == b2 or p1 is None or p2 is None or tuple(sorted((g1, g2))) in keep:
continue
k1, k2 = kind(p1), kind(p2)
if k1 == "arm" and k2 == "arm":
if p1 == p2 and t1 and t2:
continue # one hand's parts: the hand's own pairs (realhand.py)
if p1 == p2 and t1 != t2 and HAND_CARRIER.fullmatch(b1 if t2 else b2):
continue # a hand x the wrist links that carry it (its palm's hull)
elif k1 == "leg" and k2 == "leg":
if not rules.get("leg_leg" if p1 != p2 else "same_leg", False):
continue
elif "arm" not in (k1, k2): # a leg x the body (pelvis, waist, torso); not body x body
if "leg" not in (k1, k2):
continue
if w1 == w2 or pw.get(w1) == w2 or pw.get(w2) == w1:
key = tuple(sorted((b1, b2)))
if key not in seen:
seen.add(key)
excluded.append((*key, "one rigid group, or two joined by one joint (the joint's housing)"))
continue
hit = next((why for ra, rb, why in ex if (ra.fullmatch(b1) and rb.fullmatch(b2))
or (ra.fullmatch(b2) and rb.fullmatch(b1))), None)
if hit is not None:
key = tuple(sorted((b1, b2)))
if key not in seen:
seen.add(key)
excluded.append((*key, hit))
continue
out.append((g1, g2))
for i, (g1, g2) in enumerate(out):
ET.SubElement(contact, "pair", name=f"selfcol_{i}", geom1=g1, geom2=g2, **SELF_PAIR)
return {"pairs": len(out), "excluded": excluded}
def _yaw(quat) -> float:
w, x, y, z = quat
return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))
# The motors' rotor inertia, friction and (the H1-2's hips, torso and knees) torque-speed curves from Unitree's own
# actuator data (no battery cap: Unitree publishes no discharge limit).
# Source for every number in UNITREE_ACTUATORS: unitree_rl_lab, source/unitree_rl_lab/unitree_rl_lab/assets/robots/
# unitree_actuators.py, commit 4960b84732b0c2ec593dccbfe963fda1bcd7b1e3 (S6 of the G1's body.toml, S8 of the H1-2's):
# per actuator class `armature` (rotor inertia x gear ratio^2, kg m^2), `Fs` (static friction, N m: MuJoCo
# frictionloss), `Fd` (dynamic friction, N m s/rad: MuJoCo damping) and the curve X1 / X2 (rad/s) / Y1 / Y2 (N m).
# Before: the models' own armature 0.01 on every joint and frictionloss 0.3 (G1) / 0.1 (H1-2), and for the H1-2 the
# library's estimated curves (Y1 = Y2 = the URDF effort, X1 = 0.6 X2).
# The G1: each joint's class is its body.toml [motors.assign] (unitree_rl_lab unitree.py UNITREE_G1_29DOF_CFG); the
# ankles and the waist roll / pitch are two N5020-16 in a parallel linkage: twice the inertia and the friction.
# The H1-2: Unitree publishes no H1-2 actuator table. Its hips, torso and knees are M107 motors (unitree_rl_lab
# unitree.py UNITREE_H1_CFG: actuator groups "M107-24-1" = the knees, "M107-24-2" = the hips and the torso), and the
# h1_2.urdf velocity limits (23 rad/s hips and torso, 14 rad/s knees) are 0.90 / 0.88 of the no-load speeds X2 of
# M107_15 (25.6) and M107_24 (16.0), the ratio of the G1's URDF velocities to its motors' X2 (0.88-0.92): the hips
# and the torso get M107_15, the knees M107_24 (its Y1 240 / Y2 292.5 N m are below the URDF effort 300 N m, which
# stays the hard cap). The H1-2's ankles and arms (no published class) keep the library's estimate and the model's
# armature and friction.
UNITREE_ACTUATORS = {
"N7520_14p3": dict(armature=0.01017752004, Fs=1.6, Fd=0.16),
"N7520_22p5": dict(armature=0.025101925, Fs=2.4, Fd=0.24),
"N5020_16": dict(armature=0.003609725, Fs=0.6, Fd=0.06),
"N5020_16_x2": dict(armature=2 * 0.003609725, Fs=2 * 0.6, Fd=2 * 0.06),
"W4010_25": dict(armature=0.00425, Fs=0.6, Fd=0.06),
"M107_15": dict(armature=0.063259741, Fs=0.0, Fd=0.0, X1=14.0, X2=25.6, Y1=150.0, Y2=182.8),
"M107_24": dict(armature=0.160478022, Fs=0.0, Fd=0.0, X1=8.8, X2=16.0, Y1=240.0, Y2=292.5),
}
H1_2_ACTUATORS = {"hip_yaw": "M107_15", "hip_pitch": "M107_15", "hip_roll": "M107_15", "torso": "M107_15",
"knee": "M107_24"}
def unitree_actuators(m, robot) -> None:
"""Unitree's armature, friction and curves (UNITREE_ACTUATORS) on the robot's joints and its output stage."""
a = robot.arb
keys = [a.bm.short(j) for j in a.JOINTS]
X1, X2, Y1, Y2 = (np.array(e, float) for e in a._env)
for i, k in enumerate(keys):
cls = a.D["motors"]["assign"][k] if robot.name == "unitree_g1" else H1_2_ACTUATORS.get(k)
if cls is None:
continue
c = UNITREE_ACTUATORS[cls]
v = a.vadr[i]
m.dof_armature[v] = c["armature"]
if c["Fs"] or c["Fd"]:
m.dof_frictionloss[v], m.dof_damping[v] = c["Fs"], c["Fd"]
if "X1" in c:
X1[i], X2[i] = c["X1"], c["X2"]
Y1[i], Y2[i] = min(c["Y1"], a.tau_max[i]), min(c["Y2"], a.tau_max[i])
if robot.name == "unitree_h1":
h2x_legs(m, robot, keys, X1, X2, Y1, Y2)
h2x_arms(m, robot, keys, X1, X2, Y1, Y2)
a._env = a.act.env = (X1, X2, Y1, Y2)
# The H1-2 body with Unitree H2 / H2-X-class leg actuators, from the H2's official URDF (the H2-X is
# shown with "high-torque joints"; Unitree publishes no H2 / H2-X motor data, so its legs are inferred from what is
# published). Torque limits (the hard cap, as the URDF effort is for every Unitree robot): Unitree's H2.urdf
# (unitreerobotics/unitree_ros robots/h2_description/H2.urdf, last commit 2026-07-08; unitree_mujoco h2_mujoco.xml has
# the same actuatorfrcrange): hip yaw / pitch / roll 360 N m, knee 360 N m, ankle pitch 66.88 N m (its ankle roll, 19
# N m, is weaker than the H1-2's 40: the H1-2's 40 N m stays); the H2 product page (unitree.com/H2): "max leg joint
# torque 360 N m". Torque-speed curve: none is published, so each hip and knee motor takes the measured shape of the
# M107 it replaces (UNITREE_ACTUATORS: M107_15 for the hips, M107_24 for the knee), scaled on both axes:
# torque: the curve's peak (its braking torque Y2) = the URDF effort 360 N m, Y1 = 360 / (Y2 / Y1 of the M107:
# 182.8 / 150 = 1.2187 hips, 292.5 / 240 = 1.2188 knee) = 295.4 N m driving (Unitree's G1 has the same order:
# knee Y1 111 < Y2 131 < URDF 139);
# speed: the corner X1 so that the peak driving power Y1 x X1 is H2X_CORNER_W, the no-load X2 = X1 x (X2 / X1 of the
# M107: 25.6 / 14.0 = 1.829 hips, 16.0 / 8.8 = 1.818 knee); with that shape the power along the falling side never
# exceeds the corner's.
# H2X_CORNER_W = 2.5 kW: the top of the sourced range of a real humanoid leg joint's peak power: Unitree's M107 curves
# 2.10 / 2.11 kW at the corner (150 x 14.0, 240 x 8.8), BIT's BHR8-J1 knee measured 1.5 kW in a 0.5 m box jump (arXiv
# 2506.12314, 2025); a flat 360 N m to the H2's URDF velocity of 20 rad/s would be 7.2 kW per joint. So: hips X1 8.46,
# X2 15.5 rad/s; knee X1 8.46, X2 15.4 rad/s (the M107_24 had 8.8 / 16.0). The ankle pitch: 66.88 N m driving and
# braking on the H1-2's own estimated speeds (body.toml [motors] ankle_pitch X1 6, X2 10 rad/s: 0.40 kW). Rotor inertia
# and friction stay the M107's (UNITREE_ACTUATORS), the ankles' the model's. The H1-2's own URDF speed limits (hips 23,
# knee 14, ankles 9 rad/s) still bound the joint targets.
H2X_CORNER_W = 2500.0
H2X_LEGS = { # joint key: (URDF effort N m, the M107 class whose shape it takes)
"hip_yaw": (360.0, "M107_15"), "hip_pitch": (360.0, "M107_15"), "hip_roll": (360.0, "M107_15"),
"knee": (360.0, "M107_24"), "ankle_pitch": (66.88, None),
}
def h2x_legs(m, robot, keys, X1, X2, Y1, Y2) -> None:
"""H2X_LEGS on the H1-2's legs: the torque limits everywhere the motor is clamped, and the curves (in place)."""
a = robot.arb
for i, k in enumerate(keys):
if k not in H2X_LEGS:
continue
eff, cls = H2X_LEGS[k]
if cls is None:
Y1[i] = Y2[i] = eff
else:
c = UNITREE_ACTUATORS[cls]
Y2[i] = eff
Y1[i] = eff / (c["Y2"] / c["Y1"])
X1[i] = H2X_CORNER_W / Y1[i]
X2[i] = X1[i] * (c["X2"] / c["X1"])
aid = int(a.aid[i])
jid = int(m.actuator_trnid[aid, 0])
m.actuator_ctrlrange[aid] = (-eff, eff)
if m.actuator_forcelimited[aid]:
m.actuator_forcerange[aid] = (-eff, eff)
if m.jnt_actfrclimited[jid]:
m.jnt_actfrcrange[jid] = (-eff, eff)
a.tau_max[i] = eff
a.act.tau_max[i] = eff
rig = robot.rig
if hasattr(rig, "laid") and hasattr(rig, "ltau"):
for n, la in enumerate(rig.laid):
if int(la) == aid:
rig.ltau[n] = eff
if hasattr(rig, "aid") and hasattr(rig, "tau_lim"):
for n, la in enumerate(rig.aid):
if int(la) == aid:
rig.tau_lim[n] = eff
# The H1-2's arms with Unitree H2-class arm actuators (the whole H1-2 H2-class). Torque limits from
# Unitree's H2.urdf (unitree_ros robots/h2_description/H2.urdf, 2026-07-08; unitree_mujoco h2_mujoco.xml the same):
# shoulder pitch 130 N m; shoulder roll, shoulder yaw, elbow, wrist roll 60 N m; wrist pitch and yaw 10 N m; waist yaw
# 120, roll / pitch 180 N m. Mapped onto the H1-2's joints (the same chain: shoulder pitch, roll, yaw, elbow, then the
# forearm's roll, the wrist's pitch and yaw): shoulder_pitch 130; shoulder_roll, shoulder_yaw, elbow_pitch and
# elbow_roll (the H2's wrist roll: the forearm's roll) 60. Never weaker than the H1-2: its wrist pitch / yaw (19 N m)
# stay, and its single torso joint (a yaw: h1_2.urdf axis 0 0 1) keeps its own 200 N m on the M107-15 curve (the
# H2's waist yaw is 120 N m).
# Curves: Unitree publishes none for the H2's arm motors, so each takes the measured shape of the Unitree motor class
# of its size (UNITREE_CURVES, unitree_rl_lab unitree_actuators.py, the G1's arm and hip motors): the shoulder pitch
# (130 N m) the N7520-14.3 shape, the 60 N m joints the N5020-16 shape: the braking peak Y2 = the URDF effort, Y1 =
# Y2 / (the class's Y2 / Y1), X2 = X1 x (the class's X2 / X1). X1 is the class's own corner power over the new Y1
# (N7520-14.3: 71 x 22.63 = 1.61 kW; N5020-16: 24.8 x 30.86 = 0.77 kW: the measured range of Unitree's arm-size
# motors), raised where needed so that no joint is weaker than the H1-2's at any speed (the forearm roll: 1.25 kW, the
# shoulder yaw and elbow 0.80 kW; below the N7520's 1.61 kW). Rotor inertia and friction: the class's
# (UNITREE_ACTUATORS). The H1-2's URDF speed limits (shoulder 9, upper arm 20, forearm 31.4 rad/s) still bound the
# joint targets. A smaller class than the legs' (2.5 kW): an arm joint of a humanoid is a smaller motor.
UNITREE_CURVES = { # unitree_rl_lab unitree_actuators.py (= the G1's body.toml [motors])
"N7520_14p3": dict(X1=22.63, X2=35.52, Y1=71.0, Y2=83.3),
"N5020_16": dict(X1=30.86, X2=40.13, Y1=24.8, Y2=31.9),
}
H2X_ARMS = { # joint key: (URDF effort N m, the Unitree class whose shape it takes)
"shoulder_pitch": (130.0, "N7520_14p3"), "shoulder_roll": (60.0, "N5020_16"), "shoulder_yaw": (60.0, "N5020_16"),
"elbow_pitch": (60.0, "N5020_16"), "elbow_roll": (60.0, "N5020_16"),
}
def _curve(w, X1, X2, Y1):
"""The driving torque limit of a curve at speeds w (elementwise)."""
return np.where(w < X1, Y1, np.clip(Y1 * (1.0 - (w - X1) / max(X2 - X1, 1e-9)), 0.0, None))
def h2x_arms(m, robot, keys, X1, X2, Y1, Y2) -> None:
"""H2X_ARMS on the H1-2's arms: the torque limits wherever the motor is clamped, the curves (in place), the class's
rotor inertia and friction. Each new curve is checked to be no weaker than the H1-2's at every speed."""
a = robot.arb
grid = np.linspace(0.0, 60.0, 6001)
for i, k in enumerate(keys):
if k not in H2X_ARMS:
continue
eff, cls = H2X_ARMS[k]
c, u = UNITREE_CURVES[cls], UNITREE_ACTUATORS[cls]
old = _curve(grid, X1[i], X2[i], Y1[i])
y2, y1 = eff, eff / (c["Y2"] / c["Y1"])
r = c["X2"] / c["X1"]
x1 = c["X1"] * c["Y1"] / y1 # the class's corner power at the new torque
while np.any(_curve(grid, x1, x1 * r, y1) < old - 1e-9):
x1 *= 1.001 # raised until no speed is weaker than the H1-2's
if y1 < Y1[i] or y2 < Y2[i] or eff < a.tau_max[i]:
raise ValueError(f"H2X_ARMS would weaken {k}")
X1[i], X2[i], Y1[i], Y2[i] = x1, x1 * r, y1, y2
v = a.vadr[i]
m.dof_armature[v] = u["armature"]
m.dof_frictionloss[v], m.dof_damping[v] = u["Fs"], u["Fd"]
aid = int(a.aid[i])
jid = int(m.actuator_trnid[aid, 0])
m.actuator_ctrlrange[aid] = (-eff, eff)
if m.actuator_forcelimited[aid]:
m.actuator_forcerange[aid] = (-eff, eff)
if m.jnt_actfrclimited[jid]:
m.jnt_actfrcrange[jid] = (-eff, eff)
a.tau_max[i] = eff
a.act.tau_max[i] = eff
rig = robot.rig
for ids, lim in (("aid", "tau_lim"), ("laid", "ltau")):
if hasattr(rig, ids) and hasattr(rig, lim):
for n, la in enumerate(getattr(rig, ids)):
if int(la) == aid:
getattr(rig, lim)[n] = eff
class Robot:
"""The mounted G1: the library rig and arbiter, addresses, limits, the body parts' geoms."""
def __init__(self, m, name: str = "unitree_g1"):
self.m, self.name, self.info = m, name, ROBOTS[name]
self.B = load_body(name)
self.bm = importlib.import_module(f"bodies.{name}.body")
self.stand_z = float(self.bm.STAND_Z)
self.rig = self.B.rig(m, "", hand=None)
self.arb = Arbiter(self.rig)
a = self.arb
self.L = Layout(list(a.JOINTS), len(a.GROUPS["waist"]))
unitree_actuators(m, self) # Unitree's rotor inertia, friction, H1-2 curves
self.has_run = bool(self.info["run"])
self.modes = {STAND, WALK, JOINT} | ({RUN, RUN_ARMS} if self.has_run else set())
# The G1's two optional walking policies (bodies/unitree_g1/falcon.py, agile.py: numpy ports of the released
# FALCON and WBC-AGILE G1 policies), stepped like the running policy: 50 Hz, their 12 leg targets on their
# own leg gains; the waist and the arms stay the row's, on the default gains. FALCON also gives its wrist
# residual (as torque on the wrists, as the library's rig does).
self.walkers = {}
if self.info.get("walkers"):
self.walkers = {WALK_FALCON: Falcon(self.B.decl), WALK_AGILE: Agile(self.B.decl)}
self.modes |= set(WALKERS)
self.qadr, self.vadr = a.qadr, a.vadr
self.fq, self.fv = self.rig.fqadr, self.rig.fvadr
self.lo, self.hi, self.speed, self.tau_max = a.lo.copy(), a.hi.copy(), a.speed.copy(), a.tau_max.copy()
self.kp_max, self.kd_max = a.kp_max.copy(), a.kd_max.copy()
self.stance = a.rest[:12].copy() # the walking policy's default leg angles
self.rest = a.rest.copy() # ... and the rest pose of the waist and the arms
# default gains of a `joints` row: the stand gains on the legs, the servo gains on the waist and the arms
self.kp0 = np.r_[a.stand_kp, a.servo_kp[12:]]
self.kd0 = np.r_[a.stand_kd, a.servo_kd[12:]]
if self.has_run:
self.run_kp, self.run_kd = np.minimum(RP.KP, a.kp_max), np.minimum(RP.KD, a.kd_max)
sid = lambda n: int(m.sensor_adr[m.sensor(n).id]) # noqa: E731
self.sens = {k: sid(k) for k in ("orientation_pelvis", "gyro_pelvis", "accelerometer_pelvis",
"orientation_torso", "gyro_torso", "accelerometer_torso")}
self.pelvis = m.body("pelvis").id
self.torso = m.body("torso_link").id
self.bodies = sorted(a.robot_bodies)
self.mount = {s: m.body(f"{s}_mount").id for s in SIDES}
self.palm = {s: m.site(f"{s}_palm").id for s in SIDES}
self.foot_site = {s: m.site(f"{s}_foot").id for s in SIDES}
self.head_site = m.site("head_center").id
self.mass = float(m.body_subtreemass[self.pelvis])
class World:
CONTROL_DT, PHYS_DT, SUB = CONTROL_DT, PHYS_DT, SUB
def __init__(self, task, instance: dict | None = None):
"""task: a rfo.task.TaskBase (the family's rules and venue). instance: the frozen instance (its parameters
override the task's defaults; None: the defaults)."""
self.task = task
if instance is not None:
task.configure(instance.get("params", {}))
self.robot_name = getattr(task, "robot", "unitree_g1")
if self.robot_name not in ROBOTS:
raise ValueError(f"unknown robot {self.robot_name!r}; one of {list(ROBOTS)}")
sc = Scene()
task.build(sc)
looks.dress(sc) # lights, materials: looks only (looks.py)
self.scene = sc
self.xml = self._assemble(sc)
self.m = mujoco.MjModel.from_xml_string(self.xml)
looks.paint(self.m)
# MuJoCo would reset the data by itself when the physics diverges (a bad acceleration); the referee's record
# and the grips would then belong to another world. No auto-reset: the step loop ends the attempt instead.
self.m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_AUTORESET)
self.d = mujoco.MjData(self.m)
m = self.m
self.robot = Robot(m, self.robot_name)
self.L = self.robot.L
self.runp = RP.RunPolicy()
self.real_hands = dict(sc.real_hands) # side -> "dex1" / "dex3" / "inspire": a real hand, no weld (realhand.py)
self.robot.real_hands = self.real_hands
self.grippables = {n: dict(v, body=m.body(n).id) for n, v in sc.grippables.items()}
self.welds = {(s, n): m.equality(f"grip_{s}_{n}").id for s in SIDES if s not in self.real_hands
for n in self.grippables}
self.free = {} # free bodies by name: (qpos adr, dof adr)
for j in range(m.njnt):
if m.jnt_type[j] == mujoco.mjtJoint.mjJNT_FREE and m.jnt_bodyid[j] != self.robot.pelvis:
self.free[m.body(int(m.jnt_bodyid[j])).name] = (int(m.jnt_qposadr[j]), int(m.jnt_dofadr[j]))
self._lin_dofs = np.array([self.robot.fv + i for i in range(3)]
+ [va + i for _, va in self.free.values() for i in range(3)])
self.cameras = ["head_left", "head_right"] + list(sc.cameras)
self._eq_data0 = m.eq_data.copy() # a grip writes its weld's pose into the model: reset restores it
self.tool_hands = set(sc.hand_tools) # a hand that carries a tool has no fist to grip with
self._renderers: dict = {}
self.hands = (realhand.make_hands(self, self.real_hands, getattr(sc, "real_hand_options", {}))
if self.real_hands else None)
self.ref = Referee(self)
self.reset()
# ------------------------------------------------------------------ the model
def _assemble(self, sc: Scene) -> str:
root = sc.root
x, y, yaw = self.task.start
load_body(self.robot_name).mount(root, "", (x, y, 0.0), yaw, hand=None, lod="standard",
head_pitch=HEAD_PITCH_RAD)
if self.robot_name == "unitree_h1": # the H1-2's sole is one convex hull: on a box or a mesh it would get
opt = root.find("option") # a single contact point and sink; multi-point contacts for it
if not any(f.get("multiccd") for f in opt.findall("flag")):
ET.SubElement(opt, "flag", multiccd="enable")
sens = root.find("sensor")
sites = {e.get("name") for e in root.iter("site")}
for where in ("pelvis", "torso"):
s = f"imu_in_{where}"
if s not in sites: # the H1-2 has one IMU site, "imu", in its torso
if where == "torso" and "imu" in sites:
s = "imu"
else:
link = next(b for b in root.iter("body") if b.get("name") == ("pelvis" if where == "pelvis" else "torso_link"))
ET.SubElement(link, "site", name=s, pos="0 0 0", size="0.01", group="5")
ET.SubElement(sens, "framequat", name=f"orientation_{where}", objtype="site", objname=s)
ET.SubElement(sens, "gyro", name=f"gyro_{where}", site=s)
ET.SubElement(sens, "accelerometer", name=f"accelerometer_{where}", site=s)
for side, kind in sc.real_hands.items():
if side not in SIDES or kind not in realhand.KINDS or side in sc.hand_tools:
raise ValueError(f"real_hands[{side!r}] = {kind!r}: a side, one of {realhand.KINDS}, and no hand tool there")
if realhand.HAND_ROBOT.get(kind, self.robot_name) != self.robot_name:
raise ValueError(f"real_hands[{side!r}] = {kind!r} is the {realhand.HAND_ROBOT[kind]}'s hand, not the "
f"{self.robot_name}'s")
hand_opts = dict(getattr(sc, "real_hand_options", {}) or {})
for side in hand_opts:
if sc.real_hands.get(side) not in realhand.FINGER_KINDS:
raise ValueError(f"real_hand_options[{side!r}]: only a finger hand (dex3, inspire) takes options")
self._inspire_palm: dict[str, str] = {}
hand_pairs: list[tuple[str, str]] = []
if sc.real_hands: # friction that holds: elliptic cones, stiff friction (realhand.py)
opt = root.find("option")
opt.set("cone", opt.get("cone", "elliptic"))
opt.set("impratio", opt.get("impratio", f"{realhand.IMPRATIO:g}"))
if set(sc.real_hands.values()) & set(realhand.FINGER_KINDS):
# the finger hands take the robot past 60 degrees of freedom, where MuJoCo's "auto" switches to its
# sparse Jacobians: on these trees (about 70 DoF) the dense ones step faster (the same equations)
opt.set("jacobian", opt.get("jacobian", "dense"))
for side in SIDES: # the hands: a palm pad (or the task's tool) on each wrist mount
mount = next(b for b in root.iter("body") if b.get("name") == f"{side}_mount")
real = side in sc.real_hands
kind = sc.real_hands.get(side)
ET.SubElement(mount, "site", name=f"{side}_palm", pos=(realhand.grasp_point_in_mount(mount, side, kind)
if kind in realhand.FINGER_KINDS else f"0 0 {realhand.CENTRE_Z:g}" if real else "0 0 0.045"),
size="0.008", group="4")
frag = sc.hand_tools.get(side)
if real: # the real hand (realhand.py): no pad, no weld
if kind == "dex1":
realhand.strip_hand(root, side, self.robot_name)
realhand.build(root, mount, side, self.robot_name)
else: # a finger hand: the G1's fist goes; the H1-2's fingers get joints
if kind == "dex3":
realhand.strip_hand(root, side, self.robot_name)
build = realhand.build_dex3 if kind == "dex3" else realhand.build_inspire
_geoms, pairs = build(root, mount, side, self.robot_name, hand_opts.get(side, {}))
hand_pairs += pairs
if kind == "inspire":
self._inspire_palm[side] = realhand.inspire_palm_geom(root, side)
continue
if frag:
for i, el in enumerate(ET.fromstring(f"<x>{frag}</x>")):
if el.tag == "geom" and el.get("name") is None:
el.set("name", f"{side}_tool_g{i}")
mount.append(el)
else:
ET.SubElement(mount, "geom", name=f"{side}_palm_pad", type="box", pos="0 0 0.05", size="0.022 0.04 0.05",
contype="4", conaffinity="0", mass="0", group="3", rgba="0.15 0.15 0.17 1",
friction="1.2 0.005 0.0001")
for name in sc.grippables:
sc.grip_weld(side, name)
_shells(root, set(sc.ground), {b for s in SIDES if sc.real_hands.get(s) == "inspire"
for b in realhand.inspire_bodies(s)})
# The robot's self-collision (SELF_PAIR, above): every hull, shell, palm pad, tool and real hand of the robot
# against the parts it can reach; a finger hand's thumb x its fingers are the hand's own pairs (realhand.py).
self.selfcol = _self_collision(root, self.robot_name, load_body(self.robot_name).decl["self_collision"],
keep=hand_pairs)
contact = root.find("contact")
for g1, g2 in hand_pairs: # a finger hand's thumb and its fingers (realhand.py's own)
ET.SubElement(contact, "pair", name=f"handcol_{g1}_{g2}", geom1=g1, geom2=g2, condim="3")
return ET.tostring(root, encoding="unicode")
# ------------------------------------------------------------------ episode
def reset(self) -> None:
m, d, r = self.m, self.d, self.robot
mujoco.mj_resetData(m, d)
x, y, yaw = self.task.start
r.rig.place(d, r.rig.rest, pos=(x, y, r.stand_z), yaw=yaw)
r.arb.reset(d)
self._hold_legs()
self.runp.reset()
self.k = 0 # control steps done
self.refused = 0 # joint plans the arbiter refused (the targets then stay)
self.unstable = False
self.mode = STAND
self.run_k = 0
self.run_tgt = r.arb.target()
for pol in r.walkers.values():
pol.reset()
self.walk_k = 0
self.walk_tgt = r.stance.copy()
self.wrist_ff = np.zeros(14)
self.cmd = np.zeros(3)
self.held = {s: None for s in SIDES} # side -> the name of the body its hand grips
self.grip_req = {s: False for s in SIDES}
d.eq_active[:] = m.eq_active0
m.eq_data[:] = self._eq_data0
self.last_raw: np.ndarray | None = None # the sim row in force (the last one executed)
self.pins: dict[str, np.ndarray] = {} # free bodies a task holds in place (a ball on a launcher)
if self.hands:
self.hands.reset()
self.task.reset(self)
d.time = 0.0
d.act[:] = 0
d.ctrl[:] = 0
d.qacc_warmstart[:] = 0
if self.hands:
self.hands.write_ctrl()
mujoco.mj_forward(m, d)
if self.hands:
self.hands.update_held()
self.ref.reset()
def _hold_legs(self) -> None:
"""The legs on the arbiter's hold (stand gains, gravity support) at the stance: how the robot stands at t = 0."""
a, d = self.robot.arb, self.d
L = a.GROUPS["legs"]
a.plans.pop("legs", None)
a.ho = a.settle = None
a.kicker = None
a.cmd_req = np.zeros(3)
a.cmd = np.zeros(3)
a.q_a[L] = a.q_b[L] = d.qpos[a.qadr[L]]
a._set_owner("legs", "hold", "stand")
@property
def t(self) -> float:
"""Seconds of the episode."""
return self.k * CONTROL_DT
@property
def done(self) -> bool:
return self.ref.done
@property
def success(self) -> bool:
return self.ref.success
# ------------------------------------------------------------------ one control step
def step(self, raw) -> bool:
"""One control step of a sim row. Returns True when the episode is over."""
if self.ref.done:
raise RuntimeError("the episode is over")
raw = np.asarray(raw, dtype=np.float64)
L = self.L
if raw.shape != (L.RAW_DIM,) or not np.all(np.isfinite(raw)):
raise ValueError(f"a sim row is {L.RAW_DIM} finite floats")
if raw[R_MODE] not in self.robot.modes: # checked before anything changes
raise ValueError(f"a sim row's first value is the mode, one of {sorted(self.robot.modes)} "
f"({', '.join(MODES[i] for i in sorted(self.robot.modes))})")
m, d, a = self.m, self.d, self.robot.arb
for name, pose in self.pins.items(): # a pinned body stays where the task put it
qa, va = self.free[name]
d.qpos[qa:qa + 7] = pose
d.qvel[va:va + 6] = 0.0
hands = self.hands
if hands: # a real hand's grip column is its closure command: kept in [0, 1]
raw = raw.copy() # (so the row in force, last_raw, holds what ran)
for i, s in enumerate(SIDES):
if s in self.real_hands:
raw[L.R_GRIP.start + i] = min(max(float(raw[L.R_GRIP.start + i]), 0.0), 1.0)
self.task.before_step(self)
self._grips(raw[L.R_GRIP] >= 0.5)
if hands:
hands.command(raw[L.R_GRIP]) # a real hand: the closure command (realhand.py)
self._control(raw)
a.begin_step(d)
won = self.ref.success
for j in range(1, SUB + 1):
a.apply(d, j)
if hands:
hands.substep()
mujoco.mj_step(m, d)
if (d.warning[mujoco.mjtWarning.mjWARN_BADQACC].number or not np.all(np.isfinite(d.qpos))
or float(np.abs(d.qvel[self._lin_dofs]).max()) > MAX_SPEED):
self.unstable = True # the physics diverged: the attempt ends here, as a failure
break
if hands:
hands.update_held()
self.ref.substep()
self.k += 1
self.last_raw = raw.copy()
if self.unstable:
self.ref.void(UNSTABLE, keep_success=won) # (also a success latched earlier in this control step)
self.ref.done = True
else:
self.ref.step()
return self.ref.done
def _plan(self, groups, Q, QD=None, TAU=None, kp=None, kd=None, rate=None) -> None:
"""One row of joint targets for `groups` through the arbiter's plan: clipped into the ranges and to one step
of the speed limits from where each group's target is (its measured position when it is taken over)."""
r, a, d = self.robot, self.robot.arb, self.d
ix = np.concatenate([a.GROUPS[g] for g in groups])
ref = a.q_b[ix].copy()
for g in groups:
if a.owner[g] not in ("plan", "hold"):
sel = np.isin(ix, a.GROUPS[g])
ref[sel] = d.qpos[a.qadr[ix[sel]]]
step = (r.speed[ix] if rate is None else np.minimum(r.speed[ix], rate)) * CONTROL_DT * 0.999
q = np.clip(np.asarray(Q, float), r.lo[ix] + 1e-6, r.hi[ix] - 1e-6)
q = np.clip(ref + np.clip(q - ref, -step, step), r.lo[ix] + 1e-6, r.hi[ix] - 1e-6) # (a joint the load pushed
# a little past its range comes back in at once)
a.last_plan_step = -10 ** 9 # the arbiter's one-plan-per-20-ms rule is for remote players
why = a.plan(d, list(groups), q[None, :], None if QD is None else np.asarray(QD, float)[None, :],
None if TAU is None else np.asarray(TAU, float)[None, :], kp, kd)
if why: # refused (a joint driven far past its range): nothing changes
self.refused += 1
def _control(self, raw) -> None:
r, a, d, L = self.robot, self.robot.arb, self.d, self.L
mode = int(raw[R_MODE])
if mode in (RUN, RUN_ARMS) and self.mode not in (RUN, RUN_ARMS):
self.runp.reset()
self.run_k = 0
if mode in WALKERS and self.mode != mode: # a walker takes over: its memory starts afresh
r.walkers[mode].reset()
self.walk_k = 0
self.mode = mode
q = raw[L.R_Q]
if mode == WALK:
self.cmd = np.clip(raw[R_CMD], -a.cmd_max, a.cmd_max)
a.walk(d, self.cmd)
self._plan(["waist", "arms"], q[L.UPPER])
elif mode == STAND:
self.cmd = np.zeros(3)
ff = np.clip(a._support_ff(d), -r.tau_max[L.LEGS], r.tau_max[L.LEGS])
self._plan(["legs", "waist", "arms"], np.r_[r.stance, q[L.UPPER]], TAU=np.r_[ff, np.zeros(L.NU)],
kp=r.kp0, kd=r.kd0, rate=np.r_[np.full(12, STAND_RATE), np.full(L.NU, np.inf)])
elif mode in WALKERS:
pol = r.walkers[mode]
lo, hi = walker_cmd(pol, a.cmd_max)
self.cmd = np.clip(raw[R_CMD], lo, hi)
up = np.clip(q[L.UPPER], r.lo[L.UPPER], r.hi[L.UPPER])
if self.walk_k % 2 == 0: # the policies run at 50 Hz
self.walk_tgt = np.asarray(pol.step(d.qpos[r.fq + 3:r.fq + 7], d.qvel[r.fv + 3:r.fv + 6],
d.qpos[r.qadr], d.qvel[r.vadr], self.cmd,
up[L.ARMS.start - 12:], float(up[0])), float)[:12]
self.wrist_ff = (pol.wrist_torque(r.kp0[L.ARMS]) if mode == WALK_FALCON else np.zeros(14))
self.walk_k += 1
self._plan(["legs", "waist", "arms"], np.r_[self.walk_tgt, up],
TAU=np.r_[np.zeros(12 + L.NW), np.clip(self.wrist_ff, -r.tau_max[L.ARMS], r.tau_max[L.ARMS])],
kp=np.r_[np.minimum(pol.kp, r.kp_max[:12]), r.kp0[L.UPPER]],
kd=np.r_[np.minimum(pol.kd, r.kd_max[:12]), r.kd0[L.UPPER]])
elif mode in (RUN, RUN_ARMS):
self.cmd = np.clip(raw[R_CMD], RUN_CMD[:, 0], RUN_CMD[:, 1])
if self.run_k % 2 == 0: # the policy runs at 50 Hz
sd = d.sensordata
s = r.sens
self.run_tgt = self.runp.step(sd[s["orientation_pelvis"]:s["orientation_pelvis"] + 4],
sd[s["gyro_pelvis"]:s["gyro_pelvis"] + 3], d.qpos[r.qadr],
d.qvel[r.vadr], self.cmd)
self.run_k += 1
if mode == RUN:
self._plan(["legs", "waist", "arms"], self.run_tgt, kp=r.run_kp, kd=r.run_kd)
else:
self._plan(["legs", "waist", "arms"], np.r_[self.run_tgt[:L.ARMS.start], q[L.ARMS]],
kp=np.r_[r.run_kp[:L.ARMS.start], r.kp0[L.ARMS]],
kd=np.r_[r.run_kd[:L.ARMS.start], r.kd0[L.ARMS]])
else:
self.cmd = np.zeros(3)
self._plan(["legs", "waist", "arms"], q, QD=np.clip(raw[L.R_DQ], -r.speed, r.speed),
TAU=np.clip(raw[L.R_TAU], -r.tau_max, r.tau_max), kp=np.clip(raw[L.R_KP], 0.0, r.kp_max),
kd=np.clip(raw[L.R_KD], 0.0, r.kd_max))
# ------------------------------------------------------------------ the hands' grip
def _grip_gap(self, side: str, name: str) -> tuple[float, float]:
"""(distance from the palm to the object's surface, their relative speed)."""
m, d, g = self.m, self.d, self.grippables[name]
p = d.site_xpos[self.robot.palm[side]]
b = g["body"]
c = d.xpos[b]
if g.get("half_length"): # a rod: its axis is the body's local `axis`, +- half_length
ax = d.xmat[b].reshape(3, 3)[:, "xyz".index(g.get("axis", "x"))]
s = float(np.clip((p - c) @ ax, -g["half_length"], g["half_length"]))
c = c + s * ax
gap = float(np.linalg.norm(p - c)) - g["radius"]
vo = np.zeros(6)
vh = np.zeros(6)
mujoco.mj_objectVelocity(m, d, mujoco.mjtObj.mjOBJ_BODY, b, vo, 0)
mujoco.mj_objectVelocity(m, d, mujoco.mjtObj.mjOBJ_SITE, self.robot.palm[side], vh, 0)
return gap, float(np.linalg.norm(vo[3:] - vh[3:]))
def _grips(self, req) -> None:
m, d = self.m, self.d
if self.grippables:
mujoco.mj_kinematics(m, d) # positions and velocities as they are now (a task may just
mujoco.mj_comPos(m, d) # have placed or launched a prop: the speed test below must
mujoco.mj_comVel(m, d) # not read the step before)
for i, side in enumerate(SIDES):
if side in self.real_hands: # a real hand never welds (realhand.py drives its jaws)
continue
want = bool(req[i])
self.grip_req[side] = want
if not self.grippables:
continue
if self.held[side] is not None and not want:
name = self.held[side]
d.eq_active[self.welds[(side, name)]] = 0
self.held[side] = None
self.ref.event("release", hand=side, object=name)
elif self.held[side] is None and want and side not in self.tool_hands:
best = None
by_gripper = {self.held[s] for s in self.real_hands} # held by friction in a gripper: not weldable
for name in self.grippables:
if name in self.pins or name in by_gripper or not self.task.may_grip(self, side, name):
continue
gap, speed = self._grip_gap(side, name)
if gap <= GRIP_REACH and speed <= GRIP_SPEED and (best is None or gap < best[0]):
best = (gap, name)
if best is not None:
self.grab(side, best[1])
def grab(self, side: str, name: str, event: bool = True) -> None:
"""Weld the object to the hand as they are now (the grip; also how a task puts an object in a hand at t = 0)."""
if side in self.real_hands:
raise ValueError(f"the {side} hand is a real hand: it holds by friction only (use close_on)")
m, d = self.m, self.d
eq = self.welds[(side, name)]
b1, b2 = self.robot.mount[side], self.grippables[name]["body"]
mujoco.mj_kinematics(m, d)
R1 = d.xmat[b1].reshape(3, 3)
rel_p = R1.T @ (d.xpos[b2] - d.xpos[b1])
q1n, rel_q = np.zeros(4), np.zeros(4)
mujoco.mju_negQuat(q1n, d.xquat[b1])
mujoco.mju_mulQuat(rel_q, q1n, d.xquat[b2])
m.eq_data[eq, 0:3] = 0.0 # the weld's anchor: the object's origin
m.eq_data[eq, 3:6] = rel_p
m.eq_data[eq, 6:10] = rel_q
m.eq_data[eq, 10] = 1.0
d.eq_active[eq] = 1
self.held[side] = name
self.grip_req[side] = True
if event:
self.ref.event("grip", hand=side, object=name)
# ------------------------------------------------------------------ the real hands (realhand.py)
def close_on(self, side: str, name: str, closure: float = 1.0, settle_s: float = 0.3) -> dict:
"""At reset: close a real hand's jaws on the free body `name` placed between them and settle the grasp
(realhand.RealHands.close_on); the closure command stays in force."""
if side not in self.real_hands:
raise ValueError(f"the {side} hand is not a real hand (sc.real_hands[{side!r}] = 'dex1' in build())")
return self.hands.close_on(side, name, closure, settle_s)
def jaw_frame(self, side: str) -> tuple[np.ndarray, np.ndarray]:
"""(position, rotation) of a real hand's jaw centre: columns x closing axis (towards jaw a, the palm side), y
across the jaws, z along the fingers. A finger hand: its grasp frame (grasp_frame)."""
return self.hands.jaw_frame(side)
def grasp_frame(self, side: str) -> tuple[np.ndarray, np.ndarray]:
"""(position, rotation) of a finger hand's grasp site (realhand.FingerHands.grasp_frame): where a handle's axis
sits in the closed hand; columns x out of the palm, y = z x x, z along the fingers."""
return self.hands.grasp_frame(side)
def grip_cmd(self, side: str) -> float:
"""The grip value in force on a side: a real hand's closure command, else 1.0 / 0.0 for the weld grip."""
if side in self.real_hands:
return self.hands.cmd[side]
return float(self.grip_req[side])
def holder(self, name: str) -> list[str]:
"""The hands that grip the object."""
return [s for s in SIDES if self.held[s] == name]
# ------------------------------------------------------------------ free bodies (a task's props)
def put(self, name: str, pos, quat=(1, 0, 0, 0), vel=(0, 0, 0), angvel=(0, 0, 0)) -> None:
"""Place a free body (and set its velocity): resets, launches."""
qa, va = self.free[name]
self.d.qpos[qa:qa + 3] = pos
self.d.qpos[qa + 3:qa + 7] = quat
self.d.qvel[va:va + 3] = vel
self.d.qvel[va + 3:va + 6] = angvel
def pin(self, name: str, pos=None, quat=(1, 0, 0, 0)) -> None:
"""Hold a free body in place until unpin() / launch() (re-placed at the start of every control step)."""
if pos is not None:
self.put(name, pos, quat)
qa, _ = self.free[name]
self.pins[name] = self.d.qpos[qa:qa + 7].copy()
def unpin(self, name: str) -> None:
self.pins.pop(name, None)
def launch(self, name: str, pos, vel, angvel=(0, 0, 0)) -> None:
self.pins.pop(name, None)
self.put(name, pos, vel=vel, angvel=angvel)
def pos(self, name: str) -> np.ndarray:
return self.d.xpos[self.m.body(name).id].copy()
def vel(self, name: str) -> np.ndarray:
"""A free body's linear velocity in the world."""
_, va = self.free[name]
return self.d.qvel[va:va + 3].copy()
# ------------------------------------------------------------------ the robot's state (privileged)
def pelvis(self) -> np.ndarray:
"""x, y, z, yaw of the pelvis."""
d, r = self.d, self.robot
return np.r_[d.qpos[r.fq:r.fq + 3], _yaw(d.qpos[r.fq + 3:r.fq + 7])]
def com(self) -> np.ndarray:
return self.d.subtree_com[self.robot.pelvis].copy()
def upright(self) -> float:
"""The cosine of the torso's tilt from vertical (1 upright)."""
return float(self.d.xmat[self.robot.torso].reshape(3, 3)[2, 2])
def robot_aabb(self) -> tuple[np.ndarray, np.ndarray]:
"""The lower and upper corners of the robot's collision geometry (bounding spheres of its geoms, tight for the
small links): what "the whole body past a plane" is measured on."""
return self.ref.robot_extent()
# ------------------------------------------------------------------ what a real G1 senses
@property
def proprio_layout(self) -> list[str]:
J = [j[:-6] for j in self.L.JOINTS]
return ([f"{j}_pos" for j in J] + [f"{j}_vel" for j in J] + [f"{j}_torque" for j in J] + [f"{j}_target" for j in J]
+ [f"imu_pelvis_{k}" for k in ("qw", "qx", "qy", "qz", "gx", "gy", "gz", "ax", "ay", "az")]
+ [f"imu_torso_{k}" for k in ("qw", "qx", "qy", "qz", "gx", "gy", "gz", "ax", "ay", "az")]
+ ["holding_left", "holding_right", "mode", "cmd_vx", "cmd_vy", "cmd_wz", "time_s"]
+ (self.hands.layout() if self.hands else []))
def proprio(self) -> np.ndarray:
d, r, a = self.d, self.robot, self.robot.arb
sd, s = d.sensordata, r.sens
imu = lambda w: np.r_[sd[s[f"orientation_{w}"]:s[f"orientation_{w}"] + 4], sd[s[f"gyro_{w}"]:s[f"gyro_{w}"] + 3], # noqa: E731
sd[s[f"accelerometer_{w}"]:s[f"accelerometer_{w}"] + 3]]
return np.r_[d.qpos[r.qadr], d.qvel[r.vadr], d.ctrl[a.aid], a.target(), imu("pelvis"), imu("torso"),
[float(self.held["left"] is not None), float(self.held["right"] is not None), float(self.mode)],
self.cmd, [self.t], self.hands.proprio() if self.hands else []].astype(np.float32)
def render(self, camera: str, width: int = 480, height: int = 270, depth: bool = False) -> np.ndarray:
key = (width, height)
if key not in self._renderers:
self._renderers[key] = mujoco.Renderer(self.m, height, width)
R = self._renderers[key]
if depth:
R.enable_depth_rendering()
R.update_scene(self.d, camera=camera)
out = R.render().copy()
if depth:
R.disable_depth_rendering()
return out
def close(self) -> None:
for R in self._renderers.values():
try:
R.close()
except Exception: # noqa: BLE001
pass
self._renderers = {}
# ------------------------------------------------------------------ identity
def state_sha(self) -> str:
"""The simulator's state, the controllers' memory, the grips and the referee's record."""
d, m, a = self.d, self.m, self.robot.arb
h = hashlib.sha256()
ho, st = a.ho or {}, a.settle or {}
extra = [np.r_[ho.get("i", -1), ho.get("n", -1)], ho.get("q_from", np.zeros(0)), ho.get("kp_from", np.zeros(0)),
ho.get("kd_from", np.zeros(0)), np.r_[st.get("i", -1)], np.asarray(st.get("w", []), float).ravel(),
np.zeros(0) if self.last_raw is None else self.last_raw, *[self.pins[k] for k in sorted(self.pins)]]
for arr in (d.qpos, d.qvel, d.ctrl, d.act, d.eq_active, m.eq_data, d.qacc_warmstart, a.memory(),
*self.runp.memory(), self.run_tgt, self.cmd, *extra,
*[self.robot.walkers[k].state() for k in sorted(self.robot.walkers)], self.walk_tgt, self.wrist_ff):
h.update(np.nan_to_num(np.ascontiguousarray(arr, dtype=np.float64), nan=1e300, posinf=1e301,
neginf=-1e301).tobytes())
if self.hands: # (only a world with a real hand: the others' hashes stay as they were)
h.update(np.ascontiguousarray(self.hands.memory(), dtype=np.float64).tobytes())
h.update(json.dumps([self.k, self.mode, self.run_k, self.walk_k, self.refused, self.unstable, self.held, self.grip_req, sorted(self.pins), self.ref.digest()],
sort_keys=True, default=_jd).encode())
return h.hexdigest()
def _jd(o):
"""JSON for the state hash: arrays as lists, trackers by their state(); anything else is a bug (its repr would put
a memory address into the hash)."""
if hasattr(o, "tolist"):
return o.tolist()
if hasattr(o, "state"):
return o.state()
if isinstance(o, (set, frozenset)):
return sorted(o)
raise TypeError(f"{type(o).__name__} in the referee's record has no state(): the state hash cannot cover it")
# ------------------------------------------------------------------------------------------------ the action types
class Actions:
"""The agent's action types: each a view of the sim row. One row is one control step (10 ms) unless a chunk's dt
spreads it over several (hold, or a straight line from the previous command)."""
def __init__(self, robot: Robot):
r = self.r = robot
a = robot.arb
L = self.L = robot.L
_names = lambda sl: [j[:-6] for j in L.JOINTS[sl]] # noqa: E731
g01 = (np.zeros(2), np.ones(2))
q = (r.lo, r.hi)
walk = (-a.cmd_max, a.cmd_max)
run = (RUN_CMD[:, 0], RUN_CMD[:, 1])
cat = lambda *b: (np.concatenate([x[0] for x in b]), np.concatenate([x[1] for x in b])) # noqa: E731
sub = lambda sl: (r.lo[sl], r.hi[sl]) # noqa: E731
self.types = {
"stand": dict(layout=_names(L.UPPER) + GRIPS, bounds=cat(sub(L.UPPER), g01),
meaning=f"the platform holds the legs in the stance; you give the waist's {L.NW} and the arms' 14 "
"joint targets (rad)"),
"walk": dict(layout=VEL + _names(L.UPPER) + GRIPS, bounds=cat(walk, sub(L.UPPER), g01),
meaning="Unitree's walking policy drives the legs from the velocity command (vx forward, vy to "
"the left, m/s; wz turning left, rad/s; the robot's own frame); you give the waist and "
"arm joint targets"),
"run": dict(layout=VEL + GRIPS, bounds=cat(run, g01),
meaning=f"the running policy drives all {L.NJ} joints from the velocity command (it swings the arms)"),
"run_arms": dict(layout=VEL + _names(L.ARMS) + GRIPS, bounds=cat(run, sub(L.ARMS), g01),
meaning="the running policy drives the legs and the waist; you give the 14 arm joint targets"),
"joints": dict(layout=_names(slice(0, L.NJ)) + GRIPS, bounds=cat(q, g01),
meaning=f"you give all {L.NJ} joint targets (rad); the default PD gains, no feed-forward"),
"lowcmd": dict(layout=[f"{n}_{k}" for k in ("q", "dq", "tau", "kp", "kd") for n in _names(slice(0, L.NJ))] + GRIPS,
bounds=cat(q, (-r.speed, r.speed), (-r.tau_max, r.tau_max), (np.zeros(L.NJ), r.kp_max),
(np.zeros(L.NJ), r.kd_max), g01),
meaning=f"Unitree's LowCmd for all {L.NJ} joints: position targets (rad), velocity targets "
"(rad/s), feed-forward torques (N m), kp, kd; the motor torque is "
"kp (q - q_measured) + kd (dq - dq_measured) + tau, evaluated at 1 kHz"),
}
if not r.has_run: # a robot without a running policy
del self.types["run"], self.types["run_arms"]
for mode, name, who in ((WALK_FALCON, "walk_falcon", "FALCON's walking policy (LeCAR-Lab, trained with arm motions "
"and forces on the hands; it also nudges the wrists)"),
(WALK_AGILE, "walk_agile", "AGILE's velocity-height walking policy (NVIDIA WBC-AGILE, "
"trained while the arms and the waist moved)")):
if mode in r.walkers:
self.types[name] = dict(layout=VEL + _names(L.UPPER) + GRIPS,
bounds=cat(walker_cmd(r.walkers[mode], a.cmd_max), sub(L.UPPER), g01),
meaning=f"{who} drives the legs from the velocity command (vx forward, vy to "
"the left, m/s; wz turning left, rad/s; the robot's own frame); you "
"give the waist and arm joint targets")
self.real = dict(getattr(r, "real_hands", {}) or {}) # the sides with a real hand (realhand.py)
if self.real:
note = "; ".join(f"grip_{s}: the {s} gripper's closure command, 0 (open, 90 mm) to 1 (closed)"
if self.real[s] == "dex1" else
f"grip_{s}: the {s} hand's closure command, 0 (open, the fingers straight) to 1 (every "
"drive closing towards its closed position; fingers stop on what they touch)"
for s in SIDES if s in self.real)
for t in self.types.values():
t["meaning"] += f" ({note})"
for t in self.types.values():
t["dim"] = len(t["layout"])
assert len(t["bounds"][0]) == t["dim"]
def clip(self, typ: str, rows) -> np.ndarray:
lo, hi = self.types[typ]["bounds"]
return np.clip(np.asarray(rows, dtype=np.float64), lo, hi)
def to_raw(self, typ: str, row, world: "World") -> np.ndarray:
"""An agent row -> the sim row. Joints the row does not name keep their current targets."""
r, L = self.r, self.L
row = np.asarray(row, dtype=np.float64)
raw = np.zeros(L.RAW_DIM)
raw[L.R_Q] = r.arb.target()
raw[L.R_KP], raw[L.R_KD] = r.kp0, r.kd0
raw[L.R_GRIP] = (row[-2:] >= 0.5).astype(float)
for i, s in enumerate(SIDES): # a real hand: the closure command itself, in [0, 1]
if s in self.real:
raw[L.R_GRIP.start + i] = min(max(float(row[-2 + i]), 0.0), 1.0)
if typ == "stand":
raw[R_MODE] = STAND
raw[L.R_Q][L.UPPER] = row[0:L.NU]
elif typ in ("walk", "walk_falcon", "walk_agile"):
raw[R_MODE] = {"walk": WALK, "walk_falcon": WALK_FALCON, "walk_agile": WALK_AGILE}[typ]
raw[R_CMD] = row[0:3]
raw[L.R_Q][L.UPPER] = row[3:3 + L.NU]
elif typ == "run":
raw[R_MODE] = RUN
raw[R_CMD] = row[0:3]
elif typ == "run_arms":
raw[R_MODE] = RUN_ARMS
raw[R_CMD] = row[0:3]
raw[L.R_Q][L.ARMS] = row[3:17]
elif typ == "joints":
raw[R_MODE] = JOINT
raw[L.R_Q] = row[0:L.NJ]
elif typ == "lowcmd":
raw[R_MODE] = JOINT
n = L.NJ
raw[L.R_Q], raw[L.R_DQ], raw[L.R_TAU] = row[0:n], row[n:2 * n], row[2 * n:3 * n]
raw[L.R_KP], raw[L.R_KD] = row[3 * n:4 * n], row[4 * n:5 * n]
else:
raise ValueError(f"unknown action type {typ!r}; one of {list(self.types)}")
return raw
def current(self, typ: str, world: "World") -> np.ndarray:
"""The command in force as a row of this type: where a chunk's first row is interpolated from. It is read from
the sim row in force (World.last_raw, part of the state: a replayed episode has it too): the values that row
gave for what this type names when it was of this type's mode; otherwise the robot's current targets with zero
velocity command, velocities and torques and the default gains."""
r, L = self.r, self.L
tgt = r.arb.target()
raw = world.last_raw
mode = {"stand": STAND, "walk": WALK, "run": RUN, "run_arms": RUN_ARMS, "joints": JOINT, "lowcmd": JOINT,
"walk_falcon": WALK_FALCON, "walk_agile": WALK_AGILE}[typ]
same = raw is not None and int(raw[R_MODE]) == mode
grip = raw[L.R_GRIP].copy() if raw is not None else np.array([world.grip_cmd(s) for s in SIDES])
q = raw[L.R_Q] if same else tgt
cmd = raw[R_CMD] if same else np.zeros(3)
if typ == "stand":
return np.r_[q[L.UPPER], grip]
if typ in ("walk", "walk_falcon", "walk_agile"):
return np.r_[cmd, q[L.UPPER], grip]
if typ == "run":
return np.r_[cmd, grip]
if typ == "run_arms":
return np.r_[cmd, q[L.ARMS], grip]
if typ == "joints":
return np.r_[q, grip]
if same:
return np.r_[q, raw[L.R_DQ], raw[L.R_TAU], raw[L.R_KP], raw[L.R_KD], grip]
return np.r_[tgt, np.zeros(L.NJ), np.zeros(L.NJ), r.kp0, r.kd0, grip]
def hold(self, world: "World") -> tuple[str, np.ndarray]:
"""Keep the command in force with no velocity: a walking robot stops and keeps its balance on the walking
policy, a running one is slowed by the running policy, joint targets (with their gains and feed-forward
torques, as a `lowcmd` row) stay as they are with zero target velocities."""
typ = {STAND: "stand", WALK: "walk", RUN: "run", RUN_ARMS: "run_arms", JOINT: "lowcmd",
WALK_FALCON: "walk_falcon", WALK_AGILE: "walk_agile"}[world.mode]
row = self.current(typ, world)
if typ in ("walk", "run", "run_arms", "walk_falcon", "walk_agile"):
row[0:3] = 0.0
elif typ == "lowcmd":
row[self.L.NJ:2 * self.L.NJ] = 0.0
return typ, row
def spec(self) -> dict:
out = {}
for name, t in self.types.items():
lo, hi = t["bounds"]
out[name] = {"dim": t["dim"], "layout": t["layout"], "lower": [round(float(x), 4) for x in lo],
"upper": [round(float(x), 4) for x in hi], "meaning": t["meaning"]}
return out