"""One primitive episode: randomise, set up a chess position, run the expert, judge it. An episode is simulated first without cameras. Only a success is replayed from the same saved state with rendering, which MuJoCo reproduces exactly, so failures cost no rendering and never reach the dataset. """ from __future__ import annotations import os import tomllib from dataclasses import dataclass, field from pathlib import Path import chess import mujoco import numpy as np from chess_world import SYMBOL_KIND, ChessWorld, quat_yaw from expert import Destination, Expert, PlanningFailed from overlay import Camera, Jitter, draw from piece_sets import PieceSet, compile_scene from randomize import Randomizer HERE = Path(__file__).resolve().parent CONFIG = HERE / "phase2_config.toml" JOINTS = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll", "gripper") FEATURE_NAMES = [f"{j}.pos" for j in JOINTS] BIN_SLOTS_X = (-0.028, 0.0, 0.028) def _merge(base: dict, over: dict) -> dict: out = dict(base) for k, v in over.items(): out[k] = _merge(base[k], v) if isinstance(v, dict) and isinstance(base.get(k), dict) else v return out def load_config(path: Path = CONFIG) -> dict: """The phase 2 config; with PHASE2_PROFILE= set, sim/phase2_.toml is merged over it (only the keys it lists change). Several comma-separated names are merged in order (e.g. baseline,dart). Worker processes inherit the variable.""" cfg = tomllib.loads(path.read_text()) profile = os.environ.get("PHASE2_PROFILE") if profile: for name in profile.split(","): cfg = _merge(cfg, tomllib.loads((path.parent / f"phase2_{name.strip()}.toml").read_text())) cfg["profile"] = profile return cfg @dataclass class Task: target: str # piece body to move source: str # its square dest: Destination squares: dict # square -> piece body, before the move bin_pieces: list fen: str kind: str = "legal" # legal, capture_to_bin, free, validation @dataclass class Result: success: bool reason: str = "" frames: int = 0 centre_error_mm: float | None = None tilt_deg: float | None = None max_disturbance_mm: float = 0.0 disturbed: list = field(default_factory=list) stray_contacts: dict = field(default_factory=dict) # unintended arm-piece contacts yaw_deg: float | None = None dart_offset_mm: list | None = None # executed sideways offset of a perturbed pick pre_close_touch: int = 0 # frames the arm touched the target before the jaws close class EpisodeRunner: def __init__(self, cfg: dict, piece_set: PieceSet, render: bool = False): self.cfg = cfg self.piece_set = piece_set self.m = compile_scene(piece_set) self.d = mujoco.MjData(self.m) self.w = ChessWorld(self.m) self.rand = Randomizer(self.m, self.w, cfg) self.expert = Expert(self.m, self.w, cfg) fps = cfg["dataset"]["fps"] self.n_sub = round(1 / (fps * self.m.opt.timestep)) assert abs(self.n_sub * self.m.opt.timestep * fps - 1) < 1e-6, "timestep must divide the frame time" self.grip_qadr = self.m.jnt_qposadr[self.m.joint("gripper").id] self.qadr = np.r_[self.expert.kin.qadr, self.grip_qadr] lo, hi = self.m.jnt_range[self.m.joint("gripper").id] self.grip_range = (lo, hi) self.arm_geoms = set(self.expert.arm_geoms) self.finger_geoms = {g for g in self.arm_geoms if self.m.geom_bodyid[g] in (self.m.body("gripper").id, self.m.body("moving_jaw_so101_v1").id)} self.piece_of_geom = {g: n for n, gs in self.expert.piece_geoms.items() for g in gs} self.renderers = None if render: ds = cfg["dataset"] # SIM_OFFSAMPLES=0 turns the offscreen anti-aliasing off: with it on (4 samples, as the # data was rendered) the GPU shades a few wrist-camera edge pixels differently from run # to run, which is enough to change closed-loop outcomes (sim/reports/grasp_trace). if os.environ.get("SIM_OFFSAMPLES") is not None: self.m.vis.quality.offsamples = int(os.environ["SIM_OFFSAMPLES"]) self.renderers = {c: mujoco.Renderer(self.m, ds["image_height"], ds["image_width"]) for c in ds["cameras"]} self.scene_option = mujoco.MjvOption() self.scene_option.geomgroup[3] = 0 # contact hulls never appear in policy images def close(self): if self.renderers: for r in self.renderers.values(): r.close() # ------------------------------------------------------------------ units def to_lerobot(self, q6) -> np.ndarray: """LeRobot SO-101 units: arm joints in degrees (use_degrees=True), gripper 0-100.""" out = np.degrees(np.asarray(q6[:5], float)) lo, hi = self.grip_range return np.r_[out, (q6[5] - lo) / (hi - lo) * 100].astype(np.float32) # ------------------------------------------------------------------ scene setup def setup(self, rng: np.random.Generator, task: Task | None = None, board_pose=None) -> Task: """Randomise the model, place the pieces and settle. Samples a task if none given. `board_pose` = ((dx, dy), yaw) overrides the randomised board placement (offset from the nominal centre); the tray and table then keep their randomised poses, which were chosen for the randomised board. """ mujoco.mj_resetData(self.m, self.d) self.episode_info = self.rand.apply(rng) if board_pose is not None: self.w.set_board_pose(*board_pose) self.episode_info["board"] = dict(offset_m=list(board_pose[0]), yaw_deg=float(np.degrees(board_pose[1]))) if task is None: task = self.sample_task(rng) for n in self.w.pieces: self.w.park(self.d, n) pc = self.cfg["pieces"] byaw = self.w.board_yaw() for sq, n in task.squares.items(): r = pc["offcentre_mm"] / 1000 * np.sqrt(rng.uniform()) a = rng.uniform(0, 2 * np.pi) if self.w.kind[n] == "knight": face = -np.pi / 2 if self.w.color[n] == "b" else np.pi / 2 yaw = byaw + face + np.radians(rng.uniform(-pc["knight_yaw_deg"], pc["knight_yaw_deg"])) else: yaw = rng.uniform(-np.pi, np.pi) self.w.place_on_square(self.d, n, sq, (r * np.cos(a), r * np.sin(a)), yaw) # Captured pieces lie across the tray in up to three slots (fewer in a small tray). spread = min(BIN_SLOTS_X[-1], self.w.bin_half[0] - 0.011) slots = np.array(BIN_SLOTS_X) / BIN_SLOTS_X[-1] * spread byaw_bin = self.w.bin_yaw() for slot, n in zip(rng.permutation(len(slots)), task.bin_pieces): k = self.w.kind[n] flip = np.pi if rng.random() < 0.5 else 0.0 lying = np.array([np.cos(-np.pi / 4), np.sin(-np.pi / 4), 0, 0]) # body +z along the tray's +y q = np.zeros(4) mujoco.mju_mulQuat(q, quat_yaw(byaw_bin + flip + rng.uniform(-0.15, 0.15)), lying) along = -self.w.height[k] / 2 if flip == 0 else self.w.height[k] / 2 self.w.place(self.d, n, self.w.bin_point(slots[slot], along, self.w.foot_radius[k] + 0.001), q) e = self.cfg["expert"] home = np.array(e["home"]) + rng.uniform(-e["home_jitter"], e["home_jitter"], 5) g = rng.uniform(*e["home_gripper"]) self.d.qpos[self.qadr] = np.r_[home, g] self.d.ctrl[:] = np.r_[home, g] mujoco.mj_kinematics(self.m, self.d) self.rand.place_overhead(self.d, rng, self.episode_info) # needs the arm at rest for _ in range(round(0.4 / self.m.opt.timestep)): mujoco.mj_step(self.m, self.d) self.home_end = np.array(e["home"]) + rng.uniform(-e["home_jitter"], e["home_jitter"], 5) if task.dest.kind == "square": task.dest.pos = self.w.square_center(task.dest.square) else: half = self.w.bin_half - 0.014 task.dest.pos = self.w.bin_point(*rng.uniform(-half, half)) return task def sample_task(self, rng) -> Task: pc = self.cfg["pieces"] if pc.get("fixed_moves"): board = chess.Board() mv = chess.Move.from_uci(pc["fixed_moves"][rng.integers(len(pc["fixed_moves"]))]) squares = self._assign_bodies(board, rng) s = chess.square_name(mv.from_square) return Task(squares[s], s, Destination("square", None, chess.square_name(mv.to_square)), squares, [], board.fen(), "fixed") for _ in range(100): board = chess.Board() for _ in range(rng.integers(pc["random_plies"][0], pc["random_plies"][1] + 1)): moves = list(board.legal_moves) if not moves: break board.push(moves[rng.integers(len(moves))]) kind, captured = "legal", None moves = list(board.legal_moves) if not moves or rng.random() < pc["free_move_probability"]: occupied = list(board.piece_map()) empty = [s for s in chess.SQUARES if s not in board.piece_map()] src, dst, kind = occupied[rng.integers(len(occupied))], empty[rng.integers(len(empty))], "free" else: mv = moves[rng.integers(len(moves))] src, dst = mv.from_square, mv.to_square if board.is_en_passant(mv): captured = chess.square(chess.square_file(dst), chess.square_rank(src)) elif board.is_capture(mv): captured = dst to_bin = False if captured is not None: if rng.random() < pc["capture_to_bin_probability"]: src, to_bin, kind = captured, True, "capture_to_bin" else: board.remove_piece_at(captured) squares = self._assign_bodies(board, rng) if squares is None: continue off_board = [n for n in self.w.pieces if n not in squares.values()] n_bin = min(rng.integers(pc["pieces_in_bin"][0], pc["pieces_in_bin"][1] + 1), len(off_board), len(BIN_SLOTS_X)) bin_pieces = [off_board[i] for i in rng.permutation(len(off_board))[:n_bin]] dest = Destination("bin", None) if to_bin else Destination("square", None, chess.square_name(dst)) s = chess.square_name(src) return Task(squares[s], s, dest, squares, bin_pieces, board.fen(), kind) raise RuntimeError("could not sample a position") def _assign_bodies(self, board, rng): free = {n for n in self.w.pieces} squares = {} for sq, piece in board.piece_map().items(): color = "w" if piece.color == chess.WHITE else "b" kind = SYMBOL_KIND[piece.symbol().lower()] options = sorted(n for n in free if self.w.color[n] == color and self.w.kind[n] == kind) if not options: return None # promoted piece without a spare body n = options[rng.integers(len(options))] free.remove(n) squares[chess.square_name(sq)] = n return squares # ------------------------------------------------------------------ execution def _step_frame(self, q5, g, task, recorder, phase, monitor, label=None): if recorder is not None: recorder.frame(self, task, np.r_[q5 if label is None else label, g]) self.d.ctrl[:5] = q5 self.d.ctrl[5] = g for _ in range(self.n_sub): mujoco.mj_step(self.m, self.d) monitor(phase) def run(self, task: Task, rng_seed: int, recorder=None, look_s: float = 0.0, pick=None, dart_attempt: int = 0) -> Result: """Execute the primitive from the current (set-up) state. `look_s` holds the hand still above the piece, jaws open, before the descent (the wrist camera sees it). `pick`: a ready PickPlan to execute instead of planning one. With [expert] dart_probability > 0 the pick is perturbed (Expert.perturb_pick) with that probability, drawn from (rng_seed, dart_attempt); dart_attempt < 0 turns it off.""" rng = np.random.default_rng(rng_seed) d, w = self.d, self.w start = {n: w.base_pos(d, n) for n in w.pieces} watched = [n for n in task.squares.values() if n != task.target] stray = {} pre_touch = [0] def monitor(phase): touched = False for c in d.contact[:d.ncon]: g1, g2 = c.geom1, c.geom2 for arm_g, other in ((g1, g2), (g2, g1)): if arm_g in self.arm_geoms and other in self.piece_of_geom: piece = self.piece_of_geom[other] touched |= piece == task.target and phase in ("approach", "look", "descend") if piece != task.target or arm_g not in self.finger_geoms: key = f"{phase}:{piece}" stray[key] = stray.get(key, 0) + 1 if phase in ("lift", "traverse", "place"): p1, p2 = self.piece_of_geom.get(g1), self.piece_of_geom.get(g2) if task.target in (p1, p2) and p1 and p2 and p1 != p2: key = f"carried:{p2 if p1 == task.target else p1}" stray[key] = stray.get(key, 0) + 1 pre_touch[0] += touched frames = 0 try: pick = pick or self.expert.plan_pick(d, task.target, rng) except PlanningFailed as exc: return Result(False, f"plan {exc}") dart = self.cfg["expert"].get("dart_probability", 0.0) if dart > 0 and dart_attempt >= 0 and pick.traj.label is None: drng = np.random.default_rng([rng_seed, 0xDA27, dart_attempt]) if drng.random() < dart: pick = self.expert.perturb_pick(d, task.target, pick, drng) if look_s > 0: t = pick.traj i = next((k for k, ph in enumerate(t.phase) if ph == "descend"), len(t)) n = round(look_s * self.cfg["dataset"]["fps"]) t.q[i:i] = [t.q[i - 1].copy()] * n t.g[i:i] = [t.g[i - 1]] * n t.phase[i:i] = ["look"] * n if t.label is not None: t.label[i:i] = [t.label[i - 1].copy()] * n labels = pick.traj.label or [None] * len(pick.traj) for q, g, ph, ql in zip(pick.traj.q, pick.traj.g, pick.traj.phase, labels): self._step_frame(q, g, task, recorder, ph, monitor, label=ql) frames += len(pick.traj) def result(*a, **k): return Result(*a, **k, dart_offset_mm=pick.dart_offset_mm, pre_close_touch=pre_touch[0]) touching = set() for c in d.contact[:d.ncon]: if self.piece_of_geom.get(c.geom1) == task.target: touching.add(self.m.geom_bodyid[c.geom2]) if self.piece_of_geom.get(c.geom2) == task.target: touching.add(self.m.geom_bodyid[c.geom1]) jaws = {self.m.body("gripper").id, self.m.body("moving_jaw_so101_v1").id} if not jaws <= touching or d.qpos[self.grip_qadr] < self.expert.close_q + 0.01: return result(False, "grasp: jaws not both on the piece", frames, stray_contacts=stray) try: lift = self.expert.plan_lift(d, task.target, pick, task.dest) except PlanningFailed as exc: return result(False, f"plan {exc}", frames, stray_contacts=stray) for q, g, ph in zip(lift.q, lift.g, lift.phase): self._step_frame(q, g, task, recorder, ph, monitor) frames += len(lift) if w.base_pos(d, task.target)[2] < start[task.target][2] + 0.003: return result(False, "grasp: piece did not lift", frames, stray_contacts=stray) try: place = self.expert.plan_place(d, task.target, pick, task.dest, rng, self.home_end) except PlanningFailed as exc: return result(False, f"plan {exc}", frames, stray_contacts=stray) # Carry to above the destination, then re-aim the descent from where the piece # actually hangs in the hand (it can slip a few millimetres on the way). split = next((i for i, ph in enumerate(place.phase) if ph == "place"), len(place)) for q, g, ph in zip(place.q[:split], place.g[:split], place.phase[:split]): self._step_frame(q, g, task, recorder, ph, monitor) rest = None if split < len(place): try: rest = self.expert.refine_descent(d, task.target, rng) except PlanningFailed: rest = None if rest is None: rest = type(place)(place.q[split:], place.g[split:], place.phase[split:]) for q, g, ph in zip(rest.q, rest.g, rest.phase): self._step_frame(q, g, task, recorder, ph, monitor) frames += split + len(rest) r = self._judge(task, start, watched, stray, frames, pick.yaw) r.dart_offset_mm, r.pre_close_touch = pick.dart_offset_mm, pre_touch[0] return r def _judge(self, task, start, watched, stray, frames, yaw) -> Result: d, w, v = self.d, self.w, self.cfg["validation"] moved = {n: float(np.linalg.norm(w.base_pos(d, n) - start[n]) * 1000) for n in watched} disturbed = sorted((n for n, mm in moved.items() if mm > v["disturb_mm"]), key=lambda n: -moved[n]) worst = max(moved.values(), default=0.0) final = w.base_pos(d, task.target) tilt = w.tilt_deg(d, task.target) r = Result(False, "", frames, max_disturbance_mm=round(worst, 2), disturbed=disturbed, stray_contacts=stray, tilt_deg=round(tilt, 1), yaw_deg=round(float(np.degrees(yaw)), 1)) if task.dest.kind == "bin": ok_place = w.in_bin(final) r.centre_error_mm = None reason = "" if ok_place else "piece not in the tray" else: err = float(np.linalg.norm(final[:2] - task.dest.pos[:2]) * 1000) r.centre_error_mm = round(err, 2) ok_place = err <= v["success_center_mm"] and tilt <= v["success_tilt_deg"] and abs(final[2] - w.board_top) < 0.003 reason = "" if ok_place else f"placement error {err:.1f} mm, tilt {tilt:.0f} deg" if disturbed: reason = (reason + "; " if reason else "") + f"disturbed {disturbed[0]} by {moved[disturbed[0]]:.1f} mm" r.success = ok_place and not disturbed r.reason = reason return r # ------------------------------------------------------------------ rendering def camera(self, name) -> Camera: cid = self.m.camera(name).id ds = self.cfg["dataset"] return Camera(self.d.cam_xpos[cid].copy(), self.d.cam_xmat[cid].reshape(3, 3).copy(), float(self.m.cam_fovy[cid]), ds["image_width"], ds["image_height"]) def render(self, name) -> np.ndarray: r = self.renderers[name] r.update_scene(self.d, camera=name, scene_option=self.scene_option) return r.render() class Highlighter: """Draws the per-episode red/blue squares with fixed per-camera calibration error.""" def __init__(self, runner: EpisodeRunner, task: Task, rng): cfg = runner.cfg o = cfg["overlay"] w = runner.w self.alpha = o["alpha"] self.outline = o.get("outline_px", 0) self.wrist_noise = o["wrist_frame_jitter_mm"] / 1000 self.rng = rng src = w.square_corners(task.source) dst = w.square_corners(task.dest.square) if task.dest.kind == "square" else w.bin_corners() self.polys = [(src + [0, 0, 0.0003], tuple(o["source_rgb"])), (dst + [0, 0, 0.0003], tuple(o["destination_rgb"]))] self.jitter = {c: Jitter.sample(rng, cfg) for c in cfg["dataset"]["cameras"]} def apply(self, runner: EpisodeRunner, name: str, image: np.ndarray) -> np.ndarray: extra = None if name == "wrist": extra = np.r_[self.rng.normal(0, self.wrist_noise, 2), 0] polys = [(self.jitter[name].apply(p, extra), rgb) for p, rgb in self.polys] return draw(image, runner.camera(name), polys, self.alpha, self.outline)