Datasets:
Download src/robotics/sim/so101_env.py from Nabidnur/RoboRACE-Bench: direct link, hf CLI and curl.
- Browser
- Download file 13.5 kB
-
https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench/resolve/main/src/robotics/sim/so101_env.py
- Command line
-
hf download hf://datasets/Nabidnur/RoboRACE-Bench/src/robotics/sim/so101_env.py
-
curl -L -o so101_env.py https://huggingface.co/datasets/Nabidnur/RoboRACE-Bench/resolve/main/src/robotics/sim/so101_env.py
13.5 kB
| """SO-101 arm (MuJoCo Menagerie) pick-and-place rollouts with physics outcomes and 6 cameras. | |
| * Robot: `robotstudio_so101` from MuJoCo Menagerie (Apache-2.0), fetched by scripts/fetch_assets.sh. | |
| * Control: damped-least-squares IK on the `gripperframe` site (position + fingers-down | |
| orientation) feeding the arm's position actuators; scripted waypoints. | |
| * Grasp: kinematic attachment while the gripper is closed on an object; on release the | |
| object is a free rigid body again, so drops, misses and misplacements are real physics. | |
| * Ground truth: computed from the FINAL simulator state (object inside the bowl / resting on | |
| the target cube), never from the scripted intent. | |
| * Cameras: front, left, right, back, top (static) + the arm's own wrist camera. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import os | |
| import random | |
| from dataclasses import dataclass, field | |
| from pathlib import Path | |
| os.environ.setdefault("MUJOCO_GL", "egl") | |
| import mujoco # noqa: E402 | |
| import numpy as np # noqa: E402 | |
| ROOT = Path(__file__).resolve().parents[3] / "third_party/menagerie/robotstudio_so101" | |
| COLORS = {"red": "0.85 0.12 0.12 1", "green": "0.12 0.65 0.2 1", "blue": "0.15 0.3 0.9 1", | |
| "yellow": "0.95 0.8 0.1 1", "orange": "1 0.5 0.05 1", "purple": "0.55 0.2 0.75 1"} | |
| HALF = 0.0125 # 2.5 cm cubes | |
| BOWL_R, BOWL_H = 0.042, 0.03 | |
| CAMERAS = ("front", "left", "right", "back", "top") # wrist_cam exists but sees only the fingers at rest | |
| REST = np.array([0.0, -1.3, 1.69, 1.4, 0.0]) # folded beside the base: clear views for all cameras | |
| ARM = ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll") | |
| G_OPEN, G_CLOSED = 1.2, 0.15 | |
| def _bowl(name, rgba, n=40): | |
| w = [] | |
| for i in range(n): | |
| a = 2 * math.pi * i / n | |
| w.append(f'<geom type="box" size="0.003 {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.002" pos="0 0 0.002" ' | |
| 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.02" 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_so101"> | |
| <include file="so101.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="10 10" 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.2 -0.4 1.2" dir="0 0.3 -1" diffuse="0.55 0.55 0.55" castshadow="true"/> | |
| <light pos="0.4 0.4 1.0" dir="-0.3 -0.3 -1" diffuse="0.25 0.25 0.25" castshadow="false"/> | |
| <geom name="table" type="plane" size="1.5 1.5 0.01" material="table"/> | |
| <body name="look" pos="0.2 0 0.02"/> | |
| <camera name="front" mode="targetbody" target="look" pos="0.62 0.0 0.36"/> | |
| <camera name="left" mode="targetbody" target="look" pos="0.25 0.48 0.32"/> | |
| <camera name="right" mode="targetbody" target="look" pos="0.25 -0.48 0.32"/> | |
| <camera name="back" mode="targetbody" target="look" pos="-0.16 0.10 0.56"/> | |
| <camera name="top" pos="0.21 0 0.62" xyaxes="0 -1 0 1 0 0"/> | |
| {bodies}{bowl} | |
| </worldbody> | |
| </mujoco>""" | |
| class Episode: | |
| task: str | |
| family: str # put / stack | |
| mode: str # scripted intent: success / miss_grasp / drop_transit / wrong_place / wrong_object | |
| success: bool # GROUND TRUTH from final physics state | |
| views: dict = field(default_factory=dict) | |
| frames: list = field(default_factory=list) # optional video frames (dict per frame) | |
| info: dict = field(default_factory=dict) | |
| class SO101Env: | |
| 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_bodies = {m.body(n).id for n in ("base", "shoulder", "upper_arm", "lower_arm", "wrist", "gripper", | |
| "camera_mount", "moving_jaw_so101_v1")} | |
| for g in range(m.ngeom): # robot is kinematic w.r.t. objects: no robot-object contacts | |
| if m.geom_bodyid[g] in robot_bodies: | |
| m.geom_contype[g] = m.geom_conaffinity[g] = 0 | |
| self.sid = m.site("gripperframe").id | |
| self.gid = m.body("gripper").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(n).id for n in ARM] | |
| self.grip_u = m.actuator("gripper").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 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) | |
| ep = target - d.site_xpos[self.sid] | |
| a = d.site_xpos[self.sid] - d.xpos[self.gid] | |
| a /= np.linalg.norm(a) | |
| eo = np.cross(a, [0, 0, -1.0]) | |
| jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv)) | |
| mujoco.mj_jacSite(m, d, jp, jr, self.sid) | |
| 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) < 2e-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.d.site_xpos[self.sid] + np.array([0, 0, -0.004]) | |
| 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): | |
| """Interpolate the fingertip from its current position to `target` over `steps` control ticks.""" | |
| start = self.d.site_xpos[self.sid].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): | |
| self.d.qpos[self.arm_q] = q[self.arm_q] | |
| self.d.ctrl[self.arm_u] = q[self.arm_q] | |
| 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="wrist_cam" if c == "wrist" else 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.13, rmax=0.25, sep=0.075): | |
| for _ in range(500): | |
| r, th = rng.uniform(rmin, rmax), rng.uniform(-1.0, 1.0) | |
| 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") | |
| MODES = ("miss_grasp", "drop_transit", "wrong_place", "wrong_object") | |
| 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.09) | |
| oxy = _xy(rng, [bxy, cxy], sep=0.08) | |
| env = SO101Env(scene_xml([target, other], bowl, bxy)) | |
| env.place(target, (*cxy, HALF)) | |
| env.place(other, (*oxy, HALF)) | |
| dest = np.array([*bxy, 0.035]) | |
| 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.08) | |
| oxy = _xy(rng, [bxy, cxy], sep=0.07) | |
| env = SO101Env(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.004]) | |
| task = f"stack the {target} cube on the {base} cube" | |
| q_home = env.ik(np.array([0.18, 0.0, 0.14]), np.zeros(env.m.nq), iters=300) | |
| env.settle(q_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.028, 0.04) * 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.045 if family == "put" else 0.05 | |
| dest = dest + np.array([d0 * math.cos(ang), d0 * math.sin(ang), 0]) | |
| dest[2] = HALF + 0.006 | |
| up = 0.09 | |
| env.move(np.array([p[0], p[1], up]), 40, G_OPEN, rec) | |
| env.move(np.array([p[0], p[1], HALF + 0.002]), 30, G_OPEN, rec) | |
| env.hold(12, G_CLOSED, rec) | |
| if mode != "miss_grasp" and np.linalg.norm(env.d.site_xpos[env.sid][:2] - env.body_pos(f"{pick}_cube")[:2]) < 0.015: | |
| env.attached = pick | |
| env.move(np.array([p[0], p[1], up]), 30, 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, 25, G_CLOSED, rec) | |
| env.attached = None | |
| env.hold(10, G_OPEN, rec) | |
| env.move(np.array([dest[0], dest[1], up]), 25, G_OPEN, rec) | |
| else: | |
| env.move(np.array([dest[0], dest[1], up]), 50, G_CLOSED, rec) | |
| env.move(dest + np.array([0, 0, 0.01]), 30, G_CLOSED, rec) | |
| env.attached = None | |
| env.hold(12, G_OPEN, rec) | |
| env.move(env.d.site_xpos[env.sid] + np.array([0, 0, 0.06]), 20, G_OPEN, rec) | |
| env.move_joints(REST, 60, 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.006 and tp[2] < BOWL_H + 0.01 | |
| 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.006 | |
| 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 | |