Datasets:
Download src/robotics/sim/panda_env.py from Nabidnur/RoboRACE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench/resolve/main/src/robotics/sim/panda_env.py
- Command line
-
hf download hf://datasets/Nabidnur/RoboRACE-Bench/src/robotics/sim/panda_env.py
-
curl -L -o panda_env.py https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench/resolve/main/src/robotics/sim/panda_env.py
12.3 kB
| """Franka Emika Panda (MuJoCo Menagerie) version of the Track A rollouts: cross-embodiment replication. | |
| Same task families (put-in-bowl, stack), same four scripted failure modes, same five static cameras | |
| and the same physics-based ground truth as `so101_env`, scaled for a 7-DOF arm with ~0.85 m reach | |
| (5 cm cubes, 17 cm bowl). The SO-101 module is left untouched so its cached episodes stay reproducible. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import os | |
| import random | |
| from pathlib import Path | |
| os.environ.setdefault("MUJOCO_GL", "egl") | |
| import mujoco # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| from robotics.sim.so101_env import COLORS, MODES, Episode # noqa: E402 | |
| ROOT = Path(__file__).resolve().parents[3] / "third_party/menagerie/franka_emika_panda" | |
| HALF = 0.025 # 5 cm cubes | |
| BOWL_R, BOWL_H = 0.085, 0.055 | |
| CAMERAS = ("front", "left", "right", "back", "top") | |
| ARM = tuple(f"joint{i}" for i in range(1, 8)) | |
| HOME = np.array([0, 0, 0, -1.57079, 0, 1.57079, -0.7853]) | |
| REST = np.array([0.0, -1.5, 0.0, -2.9, 0.0, 1.5, 0.785]) # tucked above the base, clear of the workspace | |
| G_OPEN, G_CLOSED = 255.0, 160.0 # finger opening 8 cm / ~5 cm | |
| TCP = np.array([0.0, 0.0, 0.1034]) # finger-pad centre in the hand frame | |
| ROBOT_BODIES = ("link0", "link1", "link2", "link3", "link4", "link5", "link6", "link7", "hand", "left_finger", | |
| "right_finger") | |
| def _bowl(name, rgba, n=48): | |
| w = [] | |
| for i in range(n): | |
| a = 2 * math.pi * i / n | |
| w.append(f'<geom type="box" size="0.005 {BOWL_R * math.pi / n * 1.7:.4f} {BOWL_H / 2}" ' | |
| f'pos="{BOWL_R * math.cos(a):.4f} {BOWL_R * math.sin(a):.4f} {BOWL_H / 2}" euler="0 0 {a:.4f}" rgba="{rgba}"/>') | |
| return (f'<body name="{name}" pos="0 0 0"><geom type="cylinder" size="{BOWL_R} 0.003" pos="0 0 0.003" ' | |
| f'rgba="{rgba}"/>{"".join(w)}</body>') | |
| def scene_xml(cubes, bowl_color, bowl_xy): | |
| bodies = "".join( | |
| f'<body name="{c}_cube" pos="0 0 {HALF}"><freejoint name="{c}_free"/>' | |
| f'<geom type="box" size="{HALF} {HALF} {HALF}" rgba="{COLORS[c]}" mass="0.05" friction="1.2 0.01 0.001"/></body>' | |
| for c in cubes) | |
| bowl = _bowl(f"{bowl_color}_bowl", COLORS[bowl_color]).replace('pos="0 0 0"', f'pos="{bowl_xy[0]} {bowl_xy[1]} 0"', 1) \ | |
| if bowl_color else "" | |
| return f"""<mujoco model="roborace_panda"> | |
| <include file="panda.xml"/> | |
| <option timestep="0.002"/> | |
| <visual><global offwidth="960" offheight="960"/><quality shadowsize="4096"/> | |
| <headlight ambient="0.42 0.42 0.42" diffuse="0.45 0.45 0.45" specular="0 0 0"/></visual> | |
| <asset> | |
| <texture name="wood" type="2d" builtin="checker" rgb1="0.74 0.62 0.47" rgb2="0.70 0.58 0.44" width="256" height="256"/> | |
| <material name="table" texture="wood" texrepeat="8 8" reflectance="0"/> | |
| <texture type="skybox" builtin="gradient" rgb1="0.93 0.94 0.96" rgb2="0.75 0.78 0.82" width="256" height="512"/> | |
| </asset> | |
| <worldbody> | |
| <light pos="0.5 -0.8 2.2" dir="0 0.3 -1" diffuse="0.55 0.55 0.55" castshadow="true"/> | |
| <light pos="0.9 0.8 2.0" dir="-0.3 -0.3 -1" diffuse="0.25 0.25 0.25" castshadow="false"/> | |
| <geom name="table" type="plane" size="3 3 0.01" material="table"/> | |
| <body name="look" pos="0.5 0 0.04"/> | |
| <camera name="front" mode="targetbody" target="look" pos="1.38 0.0 0.74"/> | |
| <camera name="left" mode="targetbody" target="look" pos="0.60 0.98 0.66"/> | |
| <camera name="right" mode="targetbody" target="look" pos="0.60 -0.98 0.66"/> | |
| <camera name="back" mode="targetbody" target="look" pos="-0.28 0.42 1.18"/> | |
| <camera name="top" pos="0.52 0 1.32" xyaxes="0 -1 0 1 0 0"/> | |
| {bodies}{bowl} | |
| </worldbody> | |
| </mujoco>""" | |
| class PandaEnv: | |
| def __init__(self, xml): | |
| path = ROOT / "_roborace_scene.xml" | |
| path.write_text(xml) | |
| self.m = mujoco.MjModel.from_xml_path(str(path)) | |
| self.d = mujoco.MjData(self.m) | |
| m = self.m | |
| robot = {m.body(n).id for n in ROBOT_BODIES} | |
| for g in range(m.ngeom): # robot is kinematic w.r.t. objects: no robot-object contacts | |
| if m.geom_bodyid[g] in robot: | |
| m.geom_contype[g] = m.geom_conaffinity[g] = 0 | |
| self.hand = m.body("hand").id | |
| self.arm_q = [m.joint(n).qposadr[0] for n in ARM] | |
| self.arm_v = [m.joint(n).dofadr[0] for n in ARM] | |
| self.arm_u = [m.actuator(f"actuator{i}").id for i in range(1, 8)] | |
| self.grip_u = m.actuator("actuator8").id | |
| self.lo, self.hi = m.jnt_range[[m.joint(n).id for n in ARM]].T | |
| self.attached = None | |
| self.renderer = None | |
| mujoco.mj_forward(m, self.d) | |
| # ------------------------------------------------------------ kinematics | |
| def _tcp(m, d, hand): | |
| R = d.xmat[hand].reshape(3, 3) | |
| return d.xpos[hand] + R @ TCP, R[:, 2] | |
| def tcp(self): | |
| return self._tcp(self.m, self.d, self.hand)[0] | |
| def ik(self, target, q0, iters=120, w=0.3): | |
| m, d = self.m, mujoco.MjData(self.m) | |
| q = q0.copy() | |
| for _ in range(iters): | |
| d.qpos[:] = q | |
| mujoco.mj_kinematics(m, d) | |
| mujoco.mj_comPos(m, d) | |
| p, a = self._tcp(m, d, self.hand) | |
| ep = target - p | |
| eo = np.cross(a, [0, 0, -1.0]) | |
| jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv)) | |
| mujoco.mj_jac(m, d, jp, jr, p, self.hand) | |
| J = np.vstack([jp[:, self.arm_v], w * jr[:, self.arm_v]]) | |
| dq = J.T @ np.linalg.solve(J @ J.T + 1e-4 * np.eye(6), np.r_[ep, w * eo]) | |
| q[self.arm_q] = np.clip(q[self.arm_q] + np.clip(dq, -0.2, 0.2), self.lo, self.hi) | |
| if np.linalg.norm(ep) < 3e-4: | |
| break | |
| return q | |
| def body_pos(self, name): | |
| return self.d.xpos[self.m.body(name).id].copy() | |
| def _free_adr(self, cube): | |
| j = self.m.joint(f"{cube}_free") | |
| return j.qposadr[0], j.dofadr[0] | |
| def place(self, cube, xyz): | |
| qa, _ = self._free_adr(cube) | |
| self.d.qpos[qa:qa + 3] = xyz | |
| self.d.qpos[qa + 3:qa + 7] = [1, 0, 0, 0] | |
| # ------------------------------------------------------------ simulation | |
| def step(self, n=8): | |
| for _ in range(n): | |
| if self.attached: | |
| qa, va = self._free_adr(self.attached) | |
| self.d.qpos[qa:qa + 3] = self.tcp() | |
| self.d.qpos[qa + 3:qa + 7] = [1, 0, 0, 0] | |
| self.d.qvel[va:va + 6] = 0 | |
| mujoco.mj_step(self.m, self.d) | |
| def move(self, target, steps, grip, record=None, every=2): | |
| start = self.tcp().copy() | |
| q = self.d.qpos.copy() | |
| for k in range(1, steps + 1): | |
| s = 0.5 - 0.5 * math.cos(math.pi * k / steps) | |
| q = self.ik(start + (target - start) * s, q, iters=30) | |
| self.d.ctrl[self.arm_u] = q[self.arm_q] | |
| self.d.ctrl[self.grip_u] = grip | |
| self.step() | |
| if record is not None and k % every == 0: | |
| record.append(self.render_all(320)) | |
| def move_joints(self, q_target, steps, grip, record=None, every=2): | |
| q0 = self.d.qpos[self.arm_q].copy() | |
| for k in range(1, steps + 1): | |
| s = 0.5 - 0.5 * math.cos(math.pi * k / steps) | |
| self.d.ctrl[self.arm_u] = q0 + (q_target - q0) * s | |
| self.d.ctrl[self.grip_u] = grip | |
| self.step() | |
| if record is not None and k % every == 0: | |
| record.append(self.render_all(320)) | |
| def hold(self, steps, grip, record=None, every=2): | |
| for k in range(steps): | |
| self.d.ctrl[self.grip_u] = grip | |
| self.step() | |
| if record is not None and k % every == 0: | |
| record.append(self.render_all(320)) | |
| def settle(self, q_arm): | |
| self.d.qpos[self.arm_q] = q_arm | |
| self.d.ctrl[self.arm_u] = q_arm | |
| self.d.ctrl[self.grip_u] = G_OPEN | |
| mujoco.mj_forward(self.m, self.d) | |
| for _ in range(150): | |
| mujoco.mj_step(self.m, self.d) | |
| # ------------------------------------------------------------ rendering | |
| def render_all(self, size=448, cams=CAMERAS): | |
| if self.renderer is None or self.renderer.height != size: | |
| if self.renderer is not None: | |
| self.renderer.close() | |
| self.renderer = mujoco.Renderer(self.m, size, size) | |
| out = {} | |
| for c in cams: | |
| self.renderer.update_scene(self.d, camera=c) | |
| out[c] = self.renderer.render().copy() | |
| return out | |
| def close(self): | |
| if self.renderer is not None: | |
| self.renderer.close() | |
| self.renderer = None | |
| def _xy(rng, avoid, rmin=0.38, rmax=0.64, sep=0.15): | |
| for _ in range(500): | |
| r, th = rng.uniform(rmin, rmax), rng.uniform(-0.8, 0.8) | |
| p = (r * math.cos(th), r * math.sin(th)) | |
| if all(math.dist(p, a) > sep for a in avoid): | |
| return p | |
| raise RuntimeError("placement failed") | |
| def rollout(seed: int, want_success: bool | None = None, record_video=False, render_size=448) -> Episode: | |
| rng = random.Random(seed) | |
| family = "put" if rng.random() < 0.6 else "stack" | |
| cols = rng.sample(list(COLORS), 4) | |
| mode = "success" if (want_success if want_success is not None else rng.random() < 0.5) else rng.choice(MODES) | |
| if family == "put": | |
| target, other, bowl = cols[0], cols[1], cols[2] | |
| bxy = _xy(rng, [], sep=0.0) | |
| cxy = _xy(rng, [bxy], sep=0.18) | |
| oxy = _xy(rng, [bxy, cxy], sep=0.16) | |
| env = PandaEnv(scene_xml([target, other], bowl, bxy)) | |
| env.place(target, (*cxy, HALF)) | |
| env.place(other, (*oxy, HALF)) | |
| dest = np.array([*bxy, 0.07]) | |
| task = f"put the {target} cube in the {bowl} bowl" | |
| else: | |
| target, base, other = cols[0], cols[1], cols[2] | |
| bxy = _xy(rng, [], sep=0.0) | |
| cxy = _xy(rng, [bxy], sep=0.16) | |
| oxy = _xy(rng, [bxy, cxy], sep=0.14) | |
| env = PandaEnv(scene_xml([target, base, other], None, None)) | |
| env.place(target, (*cxy, HALF)) | |
| env.place(base, (*bxy, HALF)) | |
| env.place(other, (*oxy, HALF)) | |
| dest = np.array([*bxy, 3 * HALF + 0.006]) | |
| task = f"stack the {target} cube on the {base} cube" | |
| env.settle(HOME) | |
| rec = [] if record_video else None | |
| pick = other if mode == "wrong_object" else target | |
| p = env.body_pos(f"{pick}_cube") | |
| if mode == "miss_grasp": | |
| off = rng.uniform(0.056, 0.08) * np.array([math.cos(t := rng.uniform(0, 6.28)), math.sin(t), 0]) | |
| p = p + off | |
| if mode == "wrong_place": | |
| ang = rng.uniform(0, 2 * math.pi) | |
| d0 = BOWL_R + 0.09 if family == "put" else 0.10 | |
| dest = dest + np.array([d0 * math.cos(ang), d0 * math.sin(ang), 0]) | |
| dest[2] = HALF + 0.01 | |
| up = 0.24 | |
| env.move(np.array([p[0], p[1], up]), 50, G_OPEN, rec) | |
| env.move(np.array([p[0], p[1], HALF + 0.003]), 40, G_OPEN, rec) | |
| env.hold(14, G_CLOSED, rec) | |
| if mode != "miss_grasp" and np.linalg.norm(env.tcp()[:2] - env.body_pos(f"{pick}_cube")[:2]) < 0.03: | |
| env.attached = pick | |
| env.move(np.array([p[0], p[1], up]), 40, G_CLOSED, rec) | |
| if mode == "drop_transit": | |
| mid = (np.array([p[0], p[1], up]) + np.array([dest[0], dest[1], up])) / 2 | |
| env.move(mid, 30, G_CLOSED, rec) | |
| env.attached = None | |
| env.hold(12, G_OPEN, rec) | |
| env.move(np.array([dest[0], dest[1], up]), 30, G_OPEN, rec) | |
| else: | |
| env.move(np.array([dest[0], dest[1], up]), 60, G_CLOSED, rec) | |
| env.move(dest + np.array([0, 0, 0.015]), 40, G_CLOSED, rec) | |
| env.attached = None | |
| env.hold(14, G_OPEN, rec) | |
| env.move(env.tcp() + np.array([0, 0, 0.14]), 25, G_OPEN, rec) | |
| env.move_joints(REST, 80, G_OPEN, rec) | |
| env.hold(120, G_OPEN, rec, every=6) # let objects settle | |
| # ---- ground truth from physics | |
| tp = env.body_pos(f"{target}_cube") | |
| if family == "put": | |
| success = math.dist(tp[:2], bxy) < BOWL_R - 0.012 and tp[2] < BOWL_H + 0.02 | |
| else: | |
| bp = env.body_pos(f"{base}_cube") | |
| success = math.dist(tp[:2], bp[:2]) < 0.75 * HALF * 2 and abs(tp[2] - bp[2] - 2 * HALF) < 0.012 | |
| views = env.render_all(render_size) | |
| ep = Episode(task, family, mode, bool(success), views, rec or [], {"seed": seed, "target_final": tp.tolist()}) | |
| env.close() | |
| return ep | |