"""How much grasp error the jaws tolerate, at the current opening and at wider ones. The scripted expert grasps pieces in the settings profile's scene (run with PHASE2_PROFILE=baseline) on purpose off-centre: the pinch point is shifted 0, 2, 4 or 6 mm along the jaws' closing direction (both ways) or across it, with the jaws opened 3 mm beyond the piece on each side (the expert's current setting) or 5, 7, 9 mm. It descends straight down from above, closes and lifts 30 mm. No collision checking: the point is to see what physically happens. Per trial: held (piece lifted 15 mm and upright), toppled (tilted over 45 deg), not lifted, and whether another piece moved more than 2 mm (wider jaws can hit neighbours) or the piece was pushed more than 2 mm before the jaws closed. Writes jaw_tolerance.md and jaw_tolerance.json to --out. Run: PHASE2_PROFILE=baseline .venv/bin/python sim/jaw_tolerance.py """ from __future__ import annotations import argparse import json import multiprocessing as mp import sys from collections import defaultdict from pathlib import Path HERE = Path(__file__).resolve().parent sys.path.insert(0, str(HERE)) SOURCES = {"e7": "e5", "g8": "f6", "e2": "e4", "b1": "c3"} # pawn and knight, near and far side MARGINS_MM = (3.0, 5.0, 7.0, 9.0) OFFSETS_MM = (0.0, 2.0, 4.0, 6.0) DIRECTIONS = ("along+", "along-", "across") def trial(job): import warnings warnings.filterwarnings("ignore") import chess import mujoco import numpy as np from episode import EpisodeRunner, Task, load_config from expert import Destination, Trajectory from piece_sets import sample_piece_set global _runner if "_runner" not in globals(): cfg = load_config() _runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng(0), cfg, "jaw"), render=False) r = _runner ex, d, w = r.expert, r.d, r.w src, margin, off, direction, seed = job rng = np.random.default_rng(seed) squares = r._assign_bodies(chess.Board(), rng) task = Task(squares[src], src, Destination("square", None, SOURCES[src]), squares, [], chess.Board().fen(), "jaw") task = r.setup(np.random.default_rng(seed), task=task) name = task.target plan = ex.plan_pick(d, name, np.random.default_rng(seed)) # the expert's yaw for this piece grasp, offset = ex.grasp_for(name, plan.yaw, d, margin / 1000) lo, hi = r.grip_range if not lo <= grasp.open_q <= hi: return dict(job=job, outcome="opening beyond the gripper") axis = np.array([np.cos(plan.yaw), np.sin(plan.yaw), 0.0]) across = np.array([-axis[1], axis[0], 0.0]) vec = {"along+": axis, "along-": -axis, "across": across}[direction] base = w.base_pos(d, name) point = base + [0, 0, grasp.tip_height] + vec * off / 1000 top = ex._neighbour_tops(d, base, 0.045, exclude=(name,)) above = np.r_[point[:2], max(top + ex.e["travel_clearance_mm"] / 1000 + 0.004, point[2] + 0.025)] ex.speed = 1.0 ex._grip_floor = grasp.contact_q traj = Trajectory() q_now = d.qpos[ex.kin.qadr].copy() q_above = ex._solve(above, plan.yaw, offset, plan.q_grasp, global_search=True) ex._joint_move(traj, q_now, q_above, float(d.qpos[r.grip_qadr]), grasp.open_q, "approach") q = ex._cart_move(traj, q_above, above, point, plan.yaw, plan.yaw, offset, grasp.open_q, grasp.open_q, "descend", ex.e["vertical_speed"], 0.7, 1.8) n_before_close = len(traj) ex._hold(traj, q, grasp.open_q, ex.close_q, 0.45, "close") ex._hold(traj, q, ex.close_q, ex.close_q, 0.25, "close") ex._cart_move(traj, q, point, point + [0, 0, 0.03], plan.yaw, plan.yaw, offset, ex.close_q, ex.close_q, "lift", ex.e["vertical_speed"], 0.5, 1.5) start = {n: w.base_pos(d, n) for n in w.pieces} others = [n for n in task.squares.values() if n != name] pushed = 0.0 for i, (qq, g, ph) in enumerate(zip(traj.q, traj.g, traj.phase)): r._step_frame(qq, g, task, None, ph, lambda phase: None) if i == n_before_close - 1: pushed = float(np.linalg.norm(w.base_pos(d, name)[:2] - start[name][:2])) rise = float(w.base_pos(d, name)[2] - start[name][2]) tilt = float(w.tilt_deg(d, name)) moved = max(float(np.linalg.norm(w.base_pos(d, n) - start[n])) for n in others) outcome = ("toppled" if tilt > 45 else "held" if rise > 0.015 and tilt < 20 else "not lifted") return dict(job=job, piece=w.kind[name], outcome=outcome, neighbour_moved=moved > 0.002, pushed_before_close=pushed > 0.002, rise_mm=round(1000 * rise, 1), tilt_deg=round(tilt, 1), open_q_rad=round(float(grasp.open_q), 4)) # gripper joint angle, not a width def main(): ap = argparse.ArgumentParser(description=__doc__) ap.add_argument("--repeats", type=int, default=2, help="trials per condition (different start poses)") ap.add_argument("--workers", type=int, default=8) ap.add_argument("--out", default=str(HERE / "reports" / "baseline_eval" / "jaw_tolerance")) args = ap.parse_args() jobs = [] for src in SOURCES: for margin in MARGINS_MM: for off in OFFSETS_MM: for direction in (("along+",) if off == 0 else DIRECTIONS): for rep in range(args.repeats): jobs.append((src, margin, off, direction, 1000 * rep + len(jobs))) with mp.get_context("spawn").Pool(args.workers) as pool: results = pool.map(trial, jobs, chunksize=4) out = Path(args.out) out.mkdir(parents=True, exist_ok=True) (out / "jaw_tolerance.json").write_text(json.dumps(results, indent=1)) table = defaultdict(list) for r in results: src, margin, off, direction, _ = r["job"] piece = r.get("piece", "pawn" if src in ("e7", "e2") else "knight") table[(piece, margin, off)].append(r) lines = ["# Jaw tolerance", "", "The scripted expert grasps pieces in the baseline scene deliberately off-centre (pinch point shifted " "along the closing direction, both ways, or across it) with the jaws opened 3 mm beyond the piece on " "each side (current) or wider, then lifts 30 mm. **Clean hold** = lifted and upright with no other " "piece moved more than 2 mm.", "", f"{len(results)} trials, pawns on e7/e2 and knights on g8/b1, {args.repeats} start poses per condition.", ""] for piece in ("pawn", "knight"): lines += [f"## {piece.capitalize()}s: clean hold % (trials)", "", "| opening per side | " + " | ".join(f"{o:.0f} mm off" for o in OFFSETS_MM) + " |", "|---|" + "---|" * len(OFFSETS_MM)] for margin in MARGINS_MM: cells = [] for off in OFFSETS_MM: rs = table[(piece, margin, off)] clean = sum(r["outcome"] == "held" and not r["neighbour_moved"] for r in rs) cells.append(f"{100 * clean / max(len(rs), 1):.0f} ({len(rs)})") lines.append(f"| {margin:.0f} mm{' (current)' if margin == 3 else ''} | " + " | ".join(cells) + " |") rs = [r for k, v in table.items() if k[0] == piece for r in v] lines += ["", "Failures by kind: " + ", ".join( f"{k} {v}" for k, v in sorted(defaultdict(int, {o: sum(r['outcome'] == o for r in rs) for o in ('toppled', 'not lifted', 'opening beyond the gripper')}).items())) + f"; a neighbour moved in {sum(r.get('neighbour_moved', False) for r in rs)}; the piece was pushed " f"before closing in {sum(r.get('pushed_before_close', False) for r in rs)}.", ""] (out / "jaw_tolerance.md").write_text("\n".join(lines) + "\n") print("\n".join(lines)) if __name__ == "__main__": main()