reactive-labs-team's picture
Release wm-stage: 15 tasks (part 7)
a8f90d0 verified
Raw History Blame Contribute Delete
31.9 kB
"""Capping cell CL-2: press caps onto pens standing in the puck station and rack them, with an I2RT YAM.
Builds the `gauntlet.Task` the acceptance run uses. Read-only: the acceptance run checks this file's hash and
uses its own copy. Lengths in metres, forces in newtons, world frame = robot base frame as built.
"""
from __future__ import annotations
import math
import os
import sys
import zlib
import mujoco
import numpy as np
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "gauntlet"))
import gauntlet as G # noqa: E402
SCENE = os.path.join(HERE, "scene.xml")
# ---- Parts (CAP_FIT_SPEC.md) ----
MARKERS = tuple(f"marker_{k}" for k in range(4))
CAPS = tuple(f"cap_{k}" for k in range(6))
BARREL_R, SHOULDER_Z, NECK_R, NIB_END = 0.0070, 0.110, 0.0050, 0.131 # marker frame: origin at the tail end, +z to the nib
COLLAR_Z = 0.055
CAP_WALL, CAP_DEPTH, CAP_LEN, NSEG = 0.0040, 0.0222, 0.0250, 8 # cap frame: origin at the mouth, +z to the closed end
CHAMFER_W, CHAMFER_H, CHAMFER_T = 0.0035, 0.0060, 0.0010 # mouth lead-in (scene.xml: cap_k_chamfer)
INKS = {"red": (0.86, 0.10, 0.08, 1.0), "yellow": (0.96, 0.80, 0.08, 1.0),
"green": (0.08, 0.62, 0.20, 1.0), "blue": (0.08, 0.28, 0.88, 1.0)}
# ---- Press fit (detent) ----
# The cap's bore slides on the neck (real contact geometry, radial clearance per cap). The moulded detent is a ring
# on a short slide along each neck (scene.xml: marker_k_ring) that only caps touch: the cap mouth pushes it down
# against a stiff hold whose force is capped by the seating force profile. When the ring bottoms out the cap has
# clicked; from then on it is held down on the pen with RETAIN_N and comes off only under a larger pull.
E_START, E_PEAK, E_DRAG, E_SEAT = 0.0045, 0.0030, 0.0020, 0.0006 # mouth height above the shoulder
RETAIN_N = 20.0 # a seated cap comes off only under a pull above this (held 16 ms)
RING_TRAVEL = E_START - E_SEAT
RING_KP = 20000.0 # N/m: the ring's stiffness while it holds (0.46 mm at 9.1 N)
# ---- Fixtures ----
PUCK_FLOOR, PUCK_TOP, PUCK_BORE, PUCK_PITCH, PUCK_N = 0.005, 0.040, 0.00715, 0.040, 3
STATION_POSE = (0.270, -0.060, math.radians(-12.5)) # puck station: local +y runs along the row of pucks
PUCK_SHIM = 0.0015 # per-puck floor height scatter (pen standing height)
RACK_FLOOR, RACK_TOP, RACK_BORE, RACK_PITCH, RACK_HOLES = 0.004, 0.030, 0.0075, 0.036, 4
FEEDER_FLOOR, FEEDER_HALF = 0.004, 0.065
DONE_RACK_GAP = 0.044 # finished rack: row centre line this far behind the shipping rack row
# Nominal mounts. The feeder and the shipping rack each have two documented mounts (A and B).
FEEDER_MOUNTS = ((0.160, 0.240, math.radians(56.0)), (0.085, 0.280, math.radians(73.0)))
RACK_MOUNTS = ((0.170, -0.240, math.radians(-54.7)), (0.100, -0.275, math.radians(-70.0))) # yaw: local +x points away from the arm
# ---- Acceptance limits (ACCEPTANCE_TESTS.md) ----
CRUSH_N = 12.0 # axial load on the nest floor (16 ms mean): nib damage above this
SIDE_N = 6.0 # sideways load on the nest (16 ms mean)
RACK_TILT_DEG = 5.0
RACK_SEAT_M = 0.003 # tail within this of the hole floor
BYSTANDER_M = 0.005 # finished rack may not move more than this
CYCLE_BASE_S, CYCLE_PER_MARKER_S = 30.0, 40.0
FAULT_MIN_ONSET_S = 55.0 # no T4 fault starts before the 30 s set-up allowance + one stage at budget pace (150 s / 6)
EPISODE_S = 170.0
# ---- Per-episode variation: (public range), documented cell limit = 25 % wider ----
SNAP_N = (6.0, 9.2) # peak seating force, cap to cap
DRAG_FRAC = (0.30, 0.50) # sliding resistance after the snap, as a fraction of the peak
CLEAR_M = (0.0005, 0.0010) # radial clearance of the cap bore on the neck
FRICTION = (0.6, 1.0) # cap and marker surface friction
CAP_SPREAD = 0.040 # caps stand within this of the feeder centre (each axis)
FIX_JITTER, FIX_YAW = 0.008, math.radians(4.0)
# The overhead camera's bracket comes off for lens cleaning at every batch change and goes back within this of its
# drawing position (each axis), height and tilt (CELL_SHEET.md); the fixture datum dots are there to check it.
CAM_MOUNT_XY, CAM_MOUNT_Z, CAM_MOUNT_DEG = 0.007, 0.002, 0.2
# Placement band of the next episode: "in_range" (the public runner), "in_between" or "outside" (acceptance run).
BAND = "in_range"
HOME = {"robot/joint1": 0.0, "robot/joint2": 1.20, "robot/joint3": 1.15, "robot/joint4": -1.25,
"robot/joint5": 0.0, "robot/joint6": 0.0, "robot/left_finger": 0.030, "robot/right_finger": 0.030}
EPISODE: dict = {}
def _widen(lo, hi, band, rng):
"""A draw from the public range, or (band 'outside') from the 25 % margins beyond it."""
w = hi - lo
if band == "outside":
return float(rng.uniform(hi, hi + 0.25 * w)) if rng.random() < 0.5 else float(rng.uniform(lo - 0.25 * w, lo))
return float(rng.uniform(lo, hi))
def _sym(half, band, rng):
"""Symmetric scatter; 'outside' draws from the 25 % ring beyond the public half-range."""
if band == "outside":
return float(rng.choice([-1.0, 1.0]) * rng.uniform(half, 1.25 * half))
return float(rng.uniform(-half, half))
def _mount(mounts, band, rng):
a, b = np.array(mounts[0]), np.array(mounts[1])
if band == "in_between":
t = float(rng.uniform(0.3, 0.7))
elif band == "outside":
t = float(rng.uniform(1.0, 1.25)) if rng.random() < 0.5 else float(rng.uniform(-0.25, 0.0))
else:
t = float(rng.integers(2))
return a + t * (b - a)
def _rz(a):
c, s = math.cos(a), math.sin(a)
return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])
def _quat(r):
q = np.zeros(4)
mujoco.mju_mat2Quat(q, np.asarray(r, float).flatten())
return q
def plan(rng: np.random.Generator, band: str, pspec=None) -> dict:
"""Everything that varies in one episode."""
jit = FIX_JITTER * (1.25 if band == "outside" else 1.0)
yj = FIX_YAW * (1.25 if band == "outside" else 1.0)
rng.random() # reserved draw
n = 3
ep = {"band": band, "n": n}
ep["station"] = (STATION_POSE[0] + rng.uniform(-jit, jit), STATION_POSE[1] + rng.uniform(-jit, jit),
STATION_POSE[2] + rng.uniform(-yj, yj))
f = _mount(FEEDER_MOUNTS, band, rng)
ep["feeder"] = (f[0] + rng.uniform(-jit, jit), f[1] + rng.uniform(-jit, jit), f[2] + rng.uniform(-yj, yj))
r = _mount(RACK_MOUNTS, band, rng)
ep["rack"] = (r[0] + rng.uniform(-jit, jit), r[1] + rng.uniform(-jit, jit), r[2] + rng.uniform(-yj, yj))
names = list(INKS)
inks = [names[int(rng.integers(len(names)))] for _ in range(n)]
ep["marker_ink"] = inks
ep["puck_of"] = [int(x) for x in rng.permutation(PUCK_N)[:n]]
ep["shim"] = [_sym(PUCK_SHIM, band, rng) for _ in range(PUCK_N)]
ep["spin"] = [float(rng.uniform(-math.pi, math.pi)) for _ in range(n)]
# caps: one per marker plus one or two spares (a spare may be of an ink that is not in the batch)
n_caps = min(len(CAPS), n + int(rng.integers(1, 3)))
cap_ink = list(inks) + [names[int(rng.integers(len(names)))] for _ in range(n_caps - n)]
order = rng.permutation(n_caps)
ep["cap_ink"] = [cap_ink[int(i)] for i in order]
spread = CAP_SPREAD * (1.25 if band == "outside" else 1.0)
xy = []
while len(xy) < n_caps: # dart throwing: caps at least 40 mm apart
for _ in range(300):
c = (float(rng.uniform(-spread, spread)), float(rng.uniform(-spread, spread)))
if all(math.hypot(c[0] - b[0], c[1] - b[1]) >= 0.040 for b in xy):
xy.append(c)
break
else:
xy = []
ep["cap_xy"] = xy
ep["cap_yaw"] = [float(rng.uniform(-math.pi, math.pi)) for _ in range(n_caps)]
ep["snap_n"] = _widen(*SNAP_N, band, rng)
ep["drag"] = float(rng.uniform(*DRAG_FRAC))
ep["clear"] = [_widen(*CLEAR_M, band, rng) for _ in range(n_caps)]
ep["friction"] = float(rng.uniform(*FRICTION))
ep["budget_s"] = CYCLE_BASE_S + CYCLE_PER_MARKER_S * n
# later draws (after all earlier ones): seating force cap by cap, overhead camera bracket re-seat
ep["snap_cap"] = [_widen(*SNAP_N, band, rng) for _ in range(n_caps)]
ep["cam_mount"] = [_sym(CAM_MOUNT_XY, band, rng), _sym(CAM_MOUNT_XY, band, rng), float(rng.uniform(-CAM_MOUNT_Z, CAM_MOUNT_Z)),
_sym(CAM_MOUNT_DEG, band, rng), float(rng.uniform(-math.pi, math.pi))]
return ep
def _place_fixed(m, name, x, y, yaw):
b = m.body(name).id
m.body_pos[b] = (x, y, 0.0)
m.body_quat[b] = (math.cos(yaw / 2), 0.0, 0.0, math.sin(yaw / 2))
def _set_free(m, d, name, pos, quat):
adr = m.jnt_qposadr[m.body_jntadr[m.body(name).id]]
d.qpos[adr:adr + 3] = pos
d.qpos[adr + 3:adr + 7] = quat
def _park(m, d, name, k):
b = m.body(name).id
m.body_gravcomp[b] = 1.0
for g in range(m.ngeom):
if m.geom_bodyid[g] == b:
m.geom_contype[g] = m.geom_conaffinity[g] = 0
m.geom_rgba[g] = (0, 0, 0, 0)
m.geom_matid[g] = -1
_set_free(m, d, name, (-0.5 - 0.06 * k, 0.9, -0.5), (1, 0, 0, 0))
def _paint(m, name, rgba, only=None):
b = m.body(name).id
for g in range(m.ngeom):
if m.geom_bodyid[g] == b:
gn = m.geom(g).name
if only is not None and not any(gn.endswith(s) for s in only):
continue
m.geom_matid[g] = -1
m.geom_rgba[g] = rgba
def setup(m: mujoco.MjModel, d: mujoco.MjData, rng: np.random.Generator, pspec=None) -> None:
"""Lays out the cell for one episode."""
ep = plan(rng, BAND, pspec)
EPISODE.clear()
EPISODE.update(ep)
_place_fixed(m, "puck_station", *ep["station"])
# overhead camera bracket: shifted and tilted about a horizontal axis at a random bearing
cid = m.camera("overhead").id
dx, dy, dz, tdeg, tax = ep["cam_mount"]
m.cam_pos[cid] += np.array([dx, dy, dz])
ax_w = np.array([math.cos(tax), math.sin(tax), 0.0])
rc = np.zeros(9); mujoco.mju_quat2Mat(rc, m.cam_quat[cid]); rc = rc.reshape(3, 3)
ax_c = rc.T @ ax_w # the tilt axis in the camera frame
qt = np.zeros(4); mujoco.mju_axisAngle2Quat(qt, ax_c, math.radians(tdeg))
qn = np.zeros(4); mujoco.mju_mulQuat(qn, m.cam_quat[cid], qt)
m.cam_quat[cid] = qn
for j in range(PUCK_N):
m.geom_pos[m.geom(f"puck_station_floor_{j}").id, 2] = PUCK_FLOOR - 0.0010 + ep["shim"][j]
_place_fixed(m, "cap_feeder", *ep["feeder"])
_place_fixed(m, "ship_rack", *ep["rack"])
# finished rack (bystander): parallel to the shipping rack, one row further from the arm. The tier's offset of
# the shipping rack (applied by the gauntlet after this) is added here so the two stay side by side.
rx, ry, ryaw = ep["rack"]
off = np.array(pspec.dest_xy_m[:2]) if pspec is not None else np.zeros(2)
out = np.array([math.cos(ryaw), math.sin(ryaw)])
dp = np.array([rx, ry]) + off + DONE_RACK_GAP * out
_set_free(m, d, "done_rack", (dp[0], dp[1], 0.0003), (math.cos(ryaw / 2), 0, 0, math.sin(ryaw / 2)))
# markers standing in their pucks
sx, sy, syaw = ep["station"]
rs = _rz(syaw)
for k, name in enumerate(MARKERS):
if k >= ep["n"]:
_park(m, d, name, k)
continue
j = ep["puck_of"][k]
pw = rs @ np.array([0.0, (j - (PUCK_N - 1) / 2) * PUCK_PITCH, PUCK_FLOOR + ep["shim"][j] + 0.0002]) + np.array([sx, sy, 0.0])
a = ep["spin"][k]
qw = np.array([math.cos(a / 2), 0.0, 0.0, math.sin(a / 2)])
if k == 0 and pspec is not None: # undo the raw offset the gauntlet applies to the monitored marker
pw[:2] -= np.array(pspec.target_xy_m[:2])
inv = np.array([math.cos(-math.radians(pspec.target_yaw_deg) / 2), 0, 0, math.sin(-math.radians(pspec.target_yaw_deg) / 2)])
out_q = np.zeros(4); mujoco.mju_mulQuat(out_q, inv, qw); qw = out_q
_set_free(m, d, name, pw, qw)
ink = INKS[ep["marker_ink"][k]]
_paint(m, name, ink, only=("_tail", "_barrel", "_collar", "_grip", "_nib"))
b = m.body(name).id
for g in range(m.ngeom):
if m.geom_bodyid[g] == b and m.geom_priority[g] == 0: # the glossy neck and nib keep their own friction
m.geom_friction[g, 0] = ep["friction"]
# caps on the feeder, mouth down
fx, fy, fyaw = ep["feeder"]
rf = _rz(fyaw)
for k, name in enumerate(CAPS):
if k >= len(ep["cap_ink"]):
_park(m, d, name, 10 + k)
continue
cx, cy = ep["cap_xy"][k]
pw = rf @ np.array([cx, cy, FEEDER_FLOOR + 0.0006]) + np.array([fx, fy, 0.0])
a = ep["cap_yaw"][k]
_set_free(m, d, name, pw, (math.cos(a / 2), 0, 0, math.sin(a / 2)))
_paint(m, name, INKS[ep["cap_ink"][k]], only=("_top", "_skin"))
r_in = NECK_R + ep["clear"][k]
for s in range(NSEG):
g = m.geom(f"{name}_wall_{s}").id
ang = 2 * math.pi * s / NSEG
rc_ = r_in + CAP_WALL / 2
m.geom_pos[g, 0], m.geom_pos[g, 1] = rc_ * math.cos(ang), rc_ * math.sin(ang)
m.geom_size[g, 1] = (r_in + CAP_WALL) * math.tan(math.pi / NSEG)
m.geom_friction[g, 0] = ep["friction"]
tilt = math.atan2(-CHAMFER_W, CHAMFER_H)
rc_ = r_in + CHAMFER_W / 2 + (CHAMFER_T / 2) * math.cos(tilt)
for s in range(NSEG): # mouth lead-in chamfer, from r_in + CHAMFER_W at the mouth to r_in
g = m.geom(f"{name}_chamfer_{s}").id
ang = 2 * math.pi * s / NSEG
m.geom_pos[g, 0], m.geom_pos[g, 1] = rc_ * math.cos(ang), rc_ * math.sin(ang)
m.geom_size[g, 1] = (r_in + CHAMFER_W + CHAMFER_T) * math.tan(math.pi / NSEG)
m.geom_friction[g, 0] = ep["friction"]
r_ft = r_in + CHAMFER_W + (CAP_WALL - CHAMFER_W) / 2
for s in range(4):
g = m.geom(f"{name}_foot_{s}").id
ang = math.pi / 4 + s * math.pi / 2
m.geom_pos[g, 0], m.geom_pos[g, 1] = r_ft * math.cos(ang), r_ft * math.sin(ang)
m.geom_friction[g, 0] = ep["friction"]
m.geom_friction[m.geom(f"{name}_top").id, 0] = ep["friction"]
mujoco.mj_forward(m, d)
def tilt_deg(rot) -> float:
return math.degrees(math.acos(float(np.clip(rot[2, 2], -1.0, 1.0))))
class Capping:
"""The privileged side of the cell: the press fit between caps and marker necks, the nest load cell, the stage
record and the cell's own limits. `substep` runs before every physics step, `tick` after every control tick."""
def __init__(self, m, d, pspec, control_dt_s):
self.ep = dict(EPISODE)
EPISODE["proc"] = self
self.p = pspec
self.dt = float(m.opt.timestep)
self.cdt = control_dt_s
n, nc = self.ep["n"], len(self.ep["cap_ink"])
self.n, self.nc = n, nc
self.mb = np.array([m.body(MARKERS[k]).id for k in range(n)])
self.cb = np.array([m.body(CAPS[k]).id for k in range(nc)])
self.target = m.body(MARKERS[0]).id
self.snap = self.ep["snap_n"]
self.snap_c = np.array(self.ep["snap_cap"], float)
self.drag = self.ep["drag"]
self.latched = np.full(nc, -1) # marker index a cap is seated on
self.latched_by = np.full(n, -1) # cap seated on each marker
self.pull_n = np.zeros(n, int)
self.ring_q = [int(m.jnt_qposadr[m.joint(f"{MARKERS[k]}_ring").id]) for k in range(n)]
self.ring_v = [int(m.jnt_dofadr[m.joint(f"{MARKERS[k]}_ring").id]) for k in range(n)]
self.ring_sp = np.zeros(n)
self.eq = [[m.equality(f"seat_c{c}_m{k}").id for k in range(n)] for c in range(nc)]
nest = m.body("puck_station").id
self.nest = nest
self.pucks = [m.body(f"puck_station_p{j}").id for j in range(PUCK_N)]
self.is_nest = np.isin(m.geom_bodyid, [nest] + self.pucks)
self.is_floor = np.zeros(m.ngeom, bool)
self.floor_j = np.full(m.ngeom, -1)
for j in range(PUCK_N):
g = m.geom(f"puck_station_floor_{j}").id
self.is_floor[g] = True
self.floor_j[g] = j
self.floor_tick = np.zeros(PUCK_N)
rx = [b for b in range(m.nbody) if (m.body(b).name or "").startswith("robot/")]
self.is_robot = np.isin(m.geom_bodyid, rx)
self.is_item = np.isin(m.geom_bodyid, np.concatenate([self.mb, self.cb]))
self.geom_item = {int(b): np.nonzero(m.geom_bodyid == b)[0] for b in np.concatenate([self.mb, self.cb])}
self.width = max(1, round(0.016 / self.dt))
self.win = np.zeros((self.width, 3)) # per substep: floor load, vertical load, side load
self.wi = 0
self.tick_sum = np.zeros(3); self.tick_n = 0
self.wsum = [0.0, 0.0, 0.0]
self.peak = [0.0, 0.0, 0.0]
self.f6 = np.zeros(6)
self._eq_type = int(mujoco.mjtConstraint.mjCNSTR_EQUALITY)
seed = zlib.crc32(repr((pspec.tier, pspec.idx, round(self.snap, 6), round(self.ep["friction"], 6))).encode())
self.rng = np.random.default_rng(seed)
self.noise = 0.0 if pspec.tier == "T0" else (0.25 if pspec.tier == "T2" else 0.12)
self.load = 0.0
self.t = 0.0
self.ticks = 0
self.done_rack = m.body("done_rack").id
self.done_rack0 = None
self.rack = m.body("ship_rack").id
self.events: dict = {} # stage name -> time first achieved
self.viol: dict = {} # violation -> time first seen
self.seat_n = np.zeros(n, int)
self.rack_n = np.zeros(n, int)
self.racked_at = np.full(n, np.nan)
self.crushed = np.zeros(n, bool)
self.in_nest = -1
self.max_side = 0.0
self.max_floor = 0.0
self.press_peak = np.zeros(n)
self.final = {}
# T4 work-timed faults: `seated_any` once any cap has clicked onto any pen; `holding` while both gripper pads
# touch one cap or pen after that (gauntlet triggers "seated" and "grasp")
self.seated_any = False
self.holding = False
self.held_s = 0.0
pads = [m.body("robot/left_pad").id, m.body("robot/right_pad").id]
self.pad_of_geom = np.full(m.ngeom, -1)
for i, b in enumerate(pads):
self.pad_of_geom[m.geom_bodyid == b] = i
# -- press fit -------------------------------------------------------------------------------------------
def _profile(self, push, c):
"""Seating resistance (N) of cap c after the ring has been pushed `push` metres down from where the fit starts."""
snap = float(self.snap_c[c])
a, b = E_START - E_PEAK, E_START - E_DRAG
if push <= a:
return max(0.03, snap * (push / a) ** 2)
if push <= b:
return snap * (1.0 - (1.0 - self.drag) * (push - a) / (b - a))
return snap * self.drag
def weld_force(self, m, d, eid):
"""World force the seat weld `eid` put on the cap in the last step: its three position rows act on the cap
(body2) with the opposite sign of their constraint force."""
if d.nefc == 0:
return None
rows = np.nonzero((d.efc_id[:d.nefc] == eid) & (d.efc_type[:d.nefc] == self._eq_type))[0][:3]
if len(rows) == 0:
return None
return -d.efc_force[rows]
def substep(self, m, d):
xp, xm = d.xpos, d.xmat
xf = d.xfrc_applied
xf[self.cb] = 0.0
for k in range(self.n):
qa, da = self.ring_q[k], self.ring_v[k]
q = float(d.qpos[qa])
a = xm[self.mb[k]][2::3]
sh = xp[self.mb[k]] + SHOULDER_Z * a
c_l = self.latched_by[k]
if c_l >= 0:
# seated: the cap is held on the pen (weld) until something pulls it off harder than RETAIN_N
f = self.weld_force(m, d, self.eq[c_l][k])
pull = -float(f @ a) if f is not None else 0.0 # the weld pulls the cap down the pen when it is pulled off
self.pull_n[k] = self.pull_n[k] + 1 if pull > RETAIN_N else 0
if self.pull_n[k] >= self.width:
d.eq_active[self.eq[c_l][k]] = 0
self.latched[c_l] = -1
self.latched_by[k] = -1
self.ring_sp[k] = 0.0
d.qpos[qa] = 0.0; d.qvel[da] = 0.0
d.qfrc_applied[da] = RING_KP * (-RING_TRAVEL - q)
continue
rel = xp[self.cb] - sh
e = rel @ a
rad = np.linalg.norm(rel - e[:, None] * a, axis=1)
near = np.nonzero((rad < 0.0025) & (e > -0.002) & (e < E_START + 0.0015))[0]
if len(near) == 0:
if q < -1e-5 or self.ring_sp[k] != 0.0:
d.qpos[qa] = 0.0; d.qvel[da] = 0.0 # nothing on the ring: it springs back
self.ring_sp[k] = 0.0
d.qfrc_applied[da] = 0.0
continue
c = int(near[np.argmin(e[near])])
push = -q
lim = self._profile(push, c)
f = RING_KP * (self.ring_sp[k] - q)
if f > lim: # pushed past the fit's resistance: the ring gives way
f = lim
self.ring_sp[k] = q + lim / RING_KP
d.qfrc_applied[da] = f
if push >= RING_TRAVEL - 0.0001 and float(xm[self.cb[c]][2::3] @ a) > 0.970 and self.latched[c] < 0:
self.latched[c] = k # click: the cap is held where it is
self.latched_by[k] = c
self.pull_n[k] = 0
eid = self.eq[c][k]
rm = xm[self.mb[k]].reshape(3, 3)
m.eq_data[eid, 0:3] = 0.0
m.eq_data[eid, 3:6] = rm.T @ (xp[self.cb[c]] - xp[self.mb[k]])
qi = np.zeros(4); mujoco.mju_negQuat(qi, d.xquat[self.mb[k]])
qr = np.zeros(4); mujoco.mju_mulQuat(qr, qi, d.xquat[self.cb[c]])
m.eq_data[eid, 6:10] = qr
m.eq_data[eid, 10] = 1.0
d.eq_active[eid] = 1
# nest loads from the contacts of the previous step
floor = vert = side = 0.0
n = d.ncon
if n:
gg = d.contact.geom[:n]
hit = np.nonzero(self.is_nest[gg[:, 0]] | self.is_nest[gg[:, 1]])[0]
if len(hit):
# elliptic cones: the contact-frame force is efc_force at the contact's efc_address (normal, then the two
# tangential rows when condim >= 3), the same numbers mj_contactForce reports
adr = d.contact.efc_address[hit]
dim = d.contact.dim[hit]
ok = adr >= 0
a0 = np.where(ok, adr, 0)
ef = d.efc_force
f0 = np.where(ok, ef[a0], 0.0)
t = ok & (dim >= 3)
f1 = np.where(t, ef[np.where(t, a0 + 1, 0)], 0.0)
f2 = np.where(t, ef[np.where(t, a0 + 2, 0)], 0.0)
fr = d.contact.frame[hit]
w = f0[:, None] * fr[:, 0:3] + f1[:, None] * fr[:, 3:6] + f2[:, None] * fr[:, 6:9]
g1, g2 = gg[hit, 0], gg[hit, 1]
sgn = np.where(self.is_nest[g2], 1.0, -1.0) # the contact force acts on geom2 along the frame
tot = (sgn[:, None] * w).sum(0)
fl1, fl2 = self.is_floor[g1], self.is_floor[g2]
flm = fl1 | fl2
if flm.any():
af = np.abs(f0[flm])
floor = float(af.sum())
np.add.at(self.floor_tick, np.where(fl1[flm], self.floor_j[g1[flm]], self.floor_j[g2[flm]]), af)
vert = max(0.0, -float(tot[2]))
side = math.hypot(float(tot[0]), float(tot[1]))
w = self.win[self.wi % self.width]
self.wsum[0] += floor - w[0]; self.wsum[1] += vert - w[1]; self.wsum[2] += side - w[2]
w[0] = floor; w[1] = vert; w[2] = side
self.wi += 1
for q in range(3):
b = self.wsum[q] / self.width
if b > self.peak[q]:
self.peak[q] = b
self.tick_sum[0] += floor; self.tick_sum[1] += vert; self.tick_sum[2] += side
self.tick_n += 1
# -- per control tick ------------------------------------------------------------------------------------
def _robot_touch(self, m, d):
"""Set of item bodies the robot is touching; sets `holding` (both pads on one item, after the first click)."""
out = set()
pad_items = (set(), set())
n = d.ncon
if n:
g1 = np.asarray(d.contact.geom1[:n]); g2 = np.asarray(d.contact.geom2[:n])
for i in np.nonzero((self.is_robot[g1] & self.is_item[g2]) | (self.is_robot[g2] & self.is_item[g1]))[0]:
rg, ig = (g1[i], g2[i]) if self.is_robot[g1[i]] else (g2[i], g1[i])
b = int(m.geom_bodyid[ig])
out.add(b)
k = int(self.pad_of_geom[rg])
if k >= 0:
pad_items[k].add(b)
self.seated_any = self.seated_any or bool(np.any(self.latched >= 0))
self.holding = self.seated_any and bool(pad_items[0] & pad_items[1])
self.held_s += self.cdt * self.holding
return out
def marker_state(self, m, d, k, touch):
"""(seated in the nest, standing in a rack hole, tilt in degrees) of marker k."""
b = self.mb[k]
p = d.xpos[b]; r = d.xmat[b].reshape(3, 3)
tilt = tilt_deg(r)
free = int(b) not in touch
j = self.ep["puck_of"][k]
pp = d.xpos[self.pucks[j]]
seated = math.hypot(p[0] - pp[0], p[1] - pp[1]) < 0.004 and p[2] < pp[2] + PUCK_TOP # still in its puck
rp = d.xpos[self.rack]; rr = d.xmat[self.rack].reshape(3, 3)
loc = rr.T @ (p - rp)
hole = -1
for h in range(RACK_HOLES):
y = (h - (RACK_HOLES - 1) / 2) * RACK_PITCH
if math.hypot(loc[0], loc[1] - y) < 0.003 and abs(loc[2] - RACK_FLOOR) < RACK_SEAT_M:
hole = h
capc = np.nonzero(self.latched == k)[0]
cap_free = len(capc) == 0 or int(self.cb[capc[0]]) not in touch
racked = free and cap_free and hole >= 0 and tilt <= RACK_TILT_DEG
return seated, racked, tilt, hole
def cap_on(self, k):
"""(index of the cap seated on marker k or -1, colour matches)."""
c = np.nonzero(self.latched == k)[0]
if len(c) == 0:
return -1, False
c = int(c[0])
return c, self.ep["cap_ink"][c] == self.ep["marker_ink"][k]
def tick(self, m, d, disturbance_time):
self.t = float(d.time)
self.ticks += 1
if self.tick_n:
mean = self.tick_sum / self.tick_n
self.load = float(mean[1]) + (float(self.rng.normal(0.0, self.noise)) if self.noise else 0.0)
self.tick_sum[:] = 0.0; self.tick_n = 0
peak, self.peak = self.peak, [0.0, 0.0, 0.0]
self.max_floor = max(self.max_floor, float(peak[0])); self.max_side = max(self.max_side, float(peak[2]))
if self.done_rack0 is None:
self.done_rack0 = d.xpos[self.done_rack].copy()
touch = self._robot_touch(m, d)
in_nest = -1
if float(self.floor_tick.max()) > 0.0:
jmax = int(np.argmax(self.floor_tick))
for k in range(self.n):
if self.ep["puck_of"][k] == jmax:
in_nest = k
self.floor_tick[:] = 0.0
if in_nest >= 0:
self.press_peak[in_nest] = max(self.press_peak[in_nest], float(peak[0]))
if peak[0] > CRUSH_N:
self.viol.setdefault("tip_crush", self.t)
if in_nest >= 0:
self.crushed[in_nest] = True
if peak[2] > SIDE_N:
self.viol.setdefault("side_load", self.t)
if float(np.linalg.norm(d.xpos[self.done_rack] - self.done_rack0)) > BYSTANDER_M:
self.viol.setdefault("finished_rack_moved", self.t)
for k in range(self.n):
p = d.xpos[self.mb[k]]
if p[2] < -0.02:
self.viol.setdefault("marker_off_bench", self.t)
seated, racked, tilt, hole = self.marker_state(m, d, k, touch)
c, match = self.cap_on(k)
if c >= 0 and match and not self.crushed[k]:
self.events.setdefault(f"cap:{k}", self.t)
if racked and c >= 0:
self.rack_n[k] += 1
if self.rack_n[k] == 5:
self.racked_at[k] = self.t
else:
self.rack_n[k] = 0
self.racked_at[k] = np.nan
self.final[k] = {"seated": bool(seated), "racked": bool(racked), "tilt_deg": round(tilt, 2), "hole": int(hole),
"cap": int(c), "cap_match": bool(match), "crushed": bool(self.crushed[k]),
"held": int(self.mb[k]) in touch, "pos": [round(float(x), 4) for x in p]}
def io(self):
return {"batch": int(self.n), "nest_load_n": float(self.load), "cycle_budget_s": float(self.ep["budget_s"])}
# -- verdicts --------------------------------------------------------------------------------------------
def stages(self):
"""Ordered stage list for the episode: cap and rack for each marker."""
out = []
budget = self.ep["budget_s"]
for k in range(self.n):
fin = self.final.get(k, {})
ink = self.ep["marker_ink"][k]
c, match = self.cap_on(k)
cap_ok = c >= 0 and match and not self.crushed[k]
reason = ""
if not cap_ok:
reason = ("force" if self.crushed[k] else "colour" if c >= 0 else
"insert" if fin.get("seated", True) else "knocked_out")
out.append({"name": f"cap:marker_{k}", "skill": "cap", "done": bool(cap_ok), "t": self.events.get(f"cap:{k}") if cap_ok else None,
"reason": reason, "ink": ink, "press_peak_n": round(float(self.press_peak[k]), 2)})
rt = self.racked_at[k]
racked = bool(fin.get("racked")) and cap_ok and not np.isnan(rt)
late = racked and rt > budget
reason = ""
if not racked:
reason = ("fault" if not cap_ok else "grasp" if fin.get("held") else
"insert" if fin.get("hole", -1) >= 0 or fin.get("seated") else "transport")
elif late:
reason = "timeout"
out.append({"name": f"rack:marker_{k}", "skill": "rack", "done": bool(racked and not late),
"t": None if not racked else float(rt), "reason": reason, "tilt_deg": fin.get("tilt_deg")})
return out
@staticmethod
def _why_not_seated(fin):
if fin.get("held"):
return "grasp"
p = fin.get("pos", [0, 0, 1])
return "transport" if p[2] < 0.012 else "approach"
def all_done(self):
return all(s["done"] for s in self.stages())
def success(pe, p0) -> bool:
proc = EPISODE.get("proc")
return bool(proc is not None and proc.all_done())
def progress(pe, p0) -> float:
proc = EPISODE.get("proc")
if proc is None:
return 0.0
st = proc.stages()
return sum(1 for s in st if s["done"]) / max(1, len(st))
def audit(watch, f, poses, body_names, settle_start, dt, proc=None):
"""The cell's own limits (tip crush, nest side load, finished rack, marker off the bench) as safety violations,
and the stage record as metrics."""
if proc is None:
return [], {}
st = proc.stages()
rack_t = [s["t"] for s in st if s["skill"] == "rack" and s["t"] is not None]
all_racked = all(s["t"] is not None for s in st if s["skill"] == "rack")
metrics = {
"stages": st, "violation_times": {k: round(v, 3) for k, v in proc.viol.items()},
"n_markers": proc.n, "budget_s": proc.ep["budget_s"], "band": proc.ep["band"],
"cycle_time_s": round(max(rack_t), 3) if (all_racked and rack_t) else None,
"max_nest_floor_n": round(proc.max_floor, 2), "max_nest_side_n": round(proc.max_side, 2),
"snap_n": [round(float(x), 2) for x in proc.snap_c], "cam_mount": [round(float(x), 4) for x in proc.ep["cam_mount"]], "final": proc.final,
}
return list(proc.viol), metrics
TASK = G.Task(
task_id="cl2_capping_cell",
scene_xml=SCENE,
target_body="marker_0",
support_body="ship_rack",
bystander_bodies=("done_rack",),
success=success,
progress=progress,
pad_pattern=r"^robot/(left_pad|right_pad)$",
gripper_actuators=("robot/gripper",),
observed_bodies=("puck_station", "cap_feeder", "ship_rack"),
control_dt_s=0.02,
episode_s=EPISODE_S,
perception_hz=2.0,
perception_noise_m=(0.001, 0.002),
home_qpos=HOME,
safety=G.SafetyLimits(max_grasp_force_n=35.0, max_contact_force_n=60.0, bystander_tol_m=0.02, drop_z_tol_m=0.05),
setup=setup,
cameras=(("overhead", 320, 240, True), ("robot/wrist_cam", 160, 120, False)),
audit=audit,
process=Capping,
disturb_speed={"push": 0.3, "knockout": 0.3},
# T4 faults start only after real work: half 1-95 s after the first cap clicks onto a pen, half after 0.2-30 s
# of holding a cap or pen with both pads once a cap has clicked (the delay counts held time only), and never
# before 55 s, so at least one stage is due when one starts. A fault batch is scored against budget pace
# (harness.episode_report): 0 with no stage done before the fault, so waiting for the fault earns nothing.
fault_triggers=("seated", "grasp"),
fault_delay_s={"seated": (1.0, 95.0), "grasp": (0.2, 30.0)},
fault_min_onset_s=FAULT_MIN_ONSET_S,
# The cell stands on a ground base plate: the adversarial tier's base tilt, base height and joint-reading
# offsets are narrowed to what a 1 mm press fit can be asked to absorb (see CELL_SHEET.md).
tier_ranges={"T2": {"table_tilt_deg": (-0.5, 0.5), "proprio_bias": (0.002, 0.002), "table_dz_m": (-0.006, 0.006)},
"T3": {"table_dz_m": (-0.006, 0.006)}},
)