Download tools/scripts/dev_scripts.py from vietnhat/robodojo-hard-dev: direct link, hf CLI and curl.
- Browser
- Download file 12.1 kB
-
https://huggingface.co/datasets/vietnhat/robodojo-hard-dev/resolve/main/tools/scripts/dev_scripts.py
- Command line
-
hf download hf://datasets/vietnhat/robodojo-hard-dev/tools/scripts/dev_scripts.py
-
curl -L -o dev_scripts.py https://huggingface.co/datasets/vietnhat/robodojo-hard-dev/resolve/main/tools/scripts/dev_scripts.py
12.1 kB
| """Scripted solutions of our dev tasks (dev_suite/, PROD-104): they show each task can be done and that its success check fires. | |
| They read where the objects start from the episode's layout file (``ROBODOJO_LAYOUT_FILE``, written by | |
| dev_suite/sample_layouts.py) and the object metadata, not from the cameras: a check of the task, not of perception. | |
| Run one with ``remote_eval --planner script --script dev --tasks <task>``. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import math | |
| import os | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| import numpy as np | |
| from robodojo_agent.frames import TABLE_Z, tool_quat | |
| from robodojo_agent.geometry import quat_mul, quat_to_matrix | |
| from robodojo_agent.library import call | |
| from robodojo_agent.target import Target | |
| log = logging.getLogger("dev_scripts") | |
| OBJECTS = Path(os.environ.get("ROBODOJO_ROOT", Path.home() / "persist/coding/simulation/RoboDojo")) / "Assets/Object/RoboDojo" | |
| class Obj: | |
| pos: np.ndarray # origin, world | |
| rot: np.ndarray # 3x3, columns = the asset's axes in world | |
| meta: dict | |
| def world(self, local) -> np.ndarray: | |
| return self.pos + self.rot @ np.asarray(local, dtype=np.float64) | |
| def yaw(self, axis: int = 0) -> float: | |
| """Direction of one of the asset's axes about world z, degrees.""" | |
| d = self.rot[:, axis] | |
| return math.degrees(math.atan2(d[1], d[0])) | |
| def extents(self) -> np.ndarray: | |
| return np.asarray(self.meta["geometry"]["aligned_bbox"]["extents"], dtype=np.float64) | |
| def scene() -> dict[str, Obj]: | |
| """label -> object, from the episode's layout file.""" | |
| layout = json.loads(Path(os.environ["ROBODOJO_LAYOUT_FILE"]).read_text()) | |
| out = {} | |
| for section in ("Rigid", "Geometry", "Articulation"): | |
| for category, records in layout.get(section, {}).items(): | |
| for r in records: | |
| folder = "Clutter" if r.get("type") == "cluttered" else section | |
| meta = json.loads((OBJECTS / folder / category / f"{r['category_idx']:05d}/metadata.json").read_text()) | |
| out[r["label"]] = Obj(np.asarray(r["default_pos"], dtype=np.float64), quat_to_matrix(r["default_ori"]), meta) | |
| return out | |
| def fold(deg: float) -> float: | |
| return (deg + 90.0) % 180.0 - 90.0 | |
| def flat(v) -> np.ndarray: | |
| v = np.array([v[0], v[1], 0.0]) | |
| return v / np.linalg.norm(v) | |
| def heading(d) -> float: | |
| """``yaw_deg`` of a horizontal tool pointing along ``d`` (tool_quat: yaw 0 points at +y, positive turns towards -x).""" | |
| return math.degrees(math.atan2(-d[0], d[1])) | |
| def point(p, name: str = "", arm: str | None = None) -> Target: | |
| return Target((float(p[0]), float(p[1]), float(p[2])), name, arm=arm) | |
| # ---------------------------------------------------------------------------------------------------------------------- | |
| def put_mugs_into_pot(p): | |
| """Each arm takes the mug on its side across its body (the jaws clear of the handle) and sets it down in its half of the pot.""" | |
| s = scene() | |
| pot = s["pot"] | |
| c = pot.meta["active"]["place"]["up"]["contact_circle"]["center"] | |
| pot_c = pot.world([c[0], c[1], 0.0]) # centre of the pot's body (the handle sticks out to one side) | |
| for label, arm, side in (("mug0", "left", -1.0), ("mug1", "right", 1.0)): | |
| m = s[label] | |
| e = m.extents | |
| cc = m.meta["active"]["place"]["up"]["contact_circle"]["center"] | |
| body = m.world([cc[0], cc[1], 0.0]) # body axis (the bbox centre is off it, towards the handle) | |
| # jaws across the body (at most 7.6 cm), at right angles to the handle (the asset's +x): yaw_deg is the long axis | |
| target = Target((body[0], body[1], TABLE_Z + e[2] / 2), label, (e[1], e[1], e[2]), m.yaw(0), arm) | |
| out = yield call("grasp_top", target, depth=0.03, lift=0.08) | |
| if not out: | |
| log.warning("%s: %s", label, out.note) | |
| return | |
| dest = pot_c + np.array([side * 0.04, 0.0, 0.0]) | |
| top = out.data["point"][2] + 0.03 + 0.10 # mug bottom ~13 cm up while it crosses the pot's rim (as high as the arm goes) | |
| yield call("move", point([dest[0], dest[1], top], "over the pot"), arm=arm) | |
| yield call("place", Target((dest[0], dest[1], TABLE_Z + 0.012), "pot", arm=arm)) | |
| yield call("home", arm=arm) | |
| yield call("home") | |
| def insert_cassette_into_rack(p): | |
| """Grasp the standing cassette across its thickness, turn it in line with the slot, lower it into the slot.""" | |
| s = scene() | |
| cas, rack = s["cassette"], s["rack"] | |
| e = cas.extents | |
| target = Target(tuple(cas.pos), "cassette", tuple(e), cas.yaw(0), "right") | |
| out = yield call("grasp_top", target, lift=0.08) | |
| if not out: | |
| log.warning("cassette: %s", out.note) | |
| return | |
| turn = fold(rack.yaw(0) - cas.yaw(0)) | |
| if abs(turn) > 2: | |
| yield call("turn", None, arm="right", angle_deg=-turn) # a spin about the downward tool axis turns the yaw the other way | |
| yield call("place", Target((rack.pos[0], rack.pos[1], TABLE_Z + 0.01), "slot", arm="right")) | |
| yield call("home") | |
| def open_laptop(p): | |
| """The lid starts part open. Closed fingers, hand tilted forward: come in low between the lid and the keyboard, then | |
| sweep the fingertips round the hinge from 40 to 120 degrees, pushing the lid past upright wherever it starts. The | |
| left arm (the right one cannot take this pose across the table).""" | |
| lap = scene()["laptop"] | |
| f = flat(lap.rot[:, 1]) # from the front towards the hinge (the asset's +y) | |
| # measured in the head camera: the base's front edge is at the asset's y = 0, the hinge at y = 0.115, 1.2 cm up | |
| hinge = lap.world([0.0, 0.115, 0.012]) | |
| arm, radius = "left", 0.09 | |
| move = dict(arm=arm, pitch_deg=45.0, yaw_deg=heading(f)) | |
| def on_circle(deg: float) -> np.ndarray: | |
| a = math.radians(deg) | |
| return hinge - f * radius * math.cos(a) + [0, 0, radius * math.sin(a)] | |
| yield call("close", arm=arm) | |
| start = on_circle(40.0) # above the keyboard, in front of the lid | |
| yield call("move", point(start - f * 0.08 + [0, 0, 0.04], "in front of the laptop"), **move) | |
| yield call("move", point(start - f * 0.08, "level with the keyboard"), **move) | |
| for deg in range(40, 121, 10): | |
| yield call("move", point(on_circle(deg), f"{deg} deg round the hinge"), **move) | |
| yield call("home") | |
| def hang_headset_on_rack(p): | |
| """Pinch the lying headset at the top of its band with the right hand, turn the hand level and point it along the | |
| rack arm that points at the robot, jaws one above the other, so the headset hangs ear cups down with its arch facing | |
| along the arm. Slide in above the arm, lower until the band rests on it (the move stops short there), let go, pull | |
| the hand back out along the arm. (The left arm cannot take this pose there: 0 of 2.)""" | |
| s = scene() | |
| hs, rack = s["headset"], s["rack"] | |
| # the hook: of the rack's mug-handle rest points, the one on the arm pointing most towards the robot (-y), 25 cm up | |
| hooks = [rack.world(f[:3]) for f in rack.meta["passive"]["functional"]["handle_support_point"]["frame"]] | |
| hook = min(hooks, key=lambda h: float(flat(h - rack.pos) @ [0.0, 1.0, 0.0])) | |
| out_dir = flat(hook - rack.pos) # along the arm, away from the pole | |
| apex_dir = flat(hs.rot[:, 2]) # from the headset's middle to the top of its band (the asset's +z) | |
| apex = hs.pos + apex_dir * (hs.extents[2] / 2 - 0.012) | |
| arm = "right" | |
| jaws = math.degrees(math.atan2(apex_dir[1], apex_dir[0])) # the jaws close across the band: along apex_dir | |
| target = Target((apex[0], apex[1], TABLE_Z + 0.02), "band", (0.03, 0.03, 0.03), jaws + 90.0, arm) | |
| out = yield call("grasp_top", target, depth=0.025, lift=0.12) # higher at once and the swinging headset slips out | |
| if not out: | |
| log.warning("band: %s", out.note) | |
| return | |
| # Level hand pointing along the arm towards the pole, jaws one above the other: of the two spins, the one that turns | |
| # the band's middle-to-top direction (along the jaws since the grasp) to point up, so the ear cups hang below and the | |
| # arch faces along the arm. (Left to swing, the headset mostly stays in the grip as it was: 1 of 6 layouts hung.) | |
| q = np.asarray(p.obs.ee_pose[arm][3:], dtype=np.float64) | |
| q_inv = np.array([q[0], -q[1], -q[2], -q[3]]) | |
| yaw = heading(-out_dir) | |
| spin = max((90.0, -90.0), key=lambda sp: float((quat_to_matrix(quat_mul(tool_quat(90.0, yaw, sp), q_inv)) @ apex_dir)[2])) | |
| move = dict(arm=arm, pitch_deg=90.0, yaw_deg=yaw, spin_deg=spin) | |
| # The arm is a short stub with its rest point near the tip: aim 1.5 cm further in. Keep the hand 3.5 cm beside it: | |
| # the lower jaw then drops past the arm on opening, and the band (14 cm across inside) falls onto it. | |
| spot = hook - out_dir * 0.015 + np.array([-out_dir[1], out_dir[0], 0.0]) * 0.035 + [0, 0, 0.06] | |
| yield call("move", point(spot + out_dir * 0.14 + [0, 0, 0.03], "off the arm's tip"), **move) | |
| yield call("move", point(spot + out_dir * 0.14, "level with the arm"), **move) | |
| yield call("move", point(spot, "over the arm"), **move) | |
| yield call("nudge", None, arm=arm, dz=-0.08) # down until the band rests on the arm | |
| yield call("open", arm=arm) | |
| yield call("move", point(spot + out_dir * 0.14 - [0, 0, 0.03], "hand out"), **move) | |
| yield call("home") | |
| SCRIPTS = { | |
| "put_mugs_into_pot": put_mugs_into_pot, | |
| "insert_cassette_into_rack": insert_cassette_into_rack, | |
| "open_laptop": open_laptop, | |
| "hang_headset_on_rack": hang_headset_on_rack, | |
| } | |
| ROBOLAB_SPEC = Path(__file__).resolve().parents[2] / "dev_suite/robolab/tasks.yml" | |
| STAGED = 20 # dev_suite/robolab/build.py: layouts 20-22 are staged (the objects already where the success check wants them) | |
| def robolab(p): | |
| """The tasks of dev_suite/robolab/tasks.yml (RoboLab's rl_*, PROD-116; our hd_*, PROD-119) have no scripted solution, only checks of the task itself. | |
| Every layout starts with going home, so the success check fires on a scene that starts solved: it must on a staged | |
| layout (that is all there is), it must not on any other. There, a reach probe follows: the grasp point 3 cm over | |
| each object the task moves and each place it puts something (top, then side approach), then home. The outcomes are | |
| in calls.jsonl; a success after the first reach means the probe knocked the scene into a solved state.""" | |
| import yaml | |
| task = os.environ["ROBODOJO_TASK"] | |
| yield call("home") | |
| if int(Path(os.environ["ROBODOJO_LAYOUT_FILE"]).stem.rsplit("_", 1)[1]) >= STAGED: | |
| return | |
| spec = yaml.safe_load(ROBOLAB_SPEC.read_text())["tasks"][task] | |
| conditions = [c for stage in spec.get("sequence", [spec.get("success")]) for c in stage] | |
| atoms = [] | |
| while conditions: | |
| c = conditions.pop(0) | |
| if isinstance(c, dict): | |
| conditions += c.get("any", c.get("of", [])) | |
| elif c[0] != "still": | |
| atoms.append(c) | |
| labels = list(dict.fromkeys(label for c in atoms for label in c[1:3])) | |
| s = scene() | |
| for label in labels: | |
| o = s[label] | |
| size = np.abs(o.rot @ o.extents) | |
| target = Target(tuple(float(v) for v in o.pos), label, tuple(float(v) for v in size)) | |
| for approach in ("top", "side"): | |
| out = yield call("reach", target, approach=approach, height=0.03) | |
| if out: | |
| break | |
| log.info("reach %s: %s", label, out.note) | |
| yield call("home") | |
| def dev(p): | |
| """The scripted solution of the episode's dev task (``ROBODOJO_TASK``); the RoboLab tasks' checks (``robolab``); our | |
| robocurve-inspired tasks' solutions (rc_scripts, PROD-120).""" | |
| from robodojo_agent.rc_scripts import RC_SCRIPTS | |
| task = os.environ["ROBODOJO_TASK"] | |
| if task.startswith("rc_"): | |
| if int(Path(os.environ["ROBODOJO_LAYOUT_FILE"]).stem.rsplit("_", 1)[1]) >= STAGED: | |
| return (yield call("home")) # a staged layout: the success check must fire as it starts | |
| return (yield from RC_SCRIPTS[task](p)) | |
| return (yield from (robolab if task.startswith(("rl_", "hd_")) else SCRIPTS[task])(p)) | |