Download tools/sample_layouts.py from vietnhat/robodojo-dev-suite: direct link, hf CLI and curl.
- Browser
- Download file 11.4 kB
-
https://huggingface.co/datasets/vietnhat/robodojo-dev-suite/resolve/main/tools/sample_layouts.py
- Command line
-
hf download hf://datasets/vietnhat/robodojo-dev-suite/tools/sample_layouts.py
-
curl -L -o sample_layouts.py https://huggingface.co/datasets/vietnhat/robodojo-dev-suite/resolve/main/tools/sample_layouts.py
11.4 kB
| """Sample scene layouts for our dev tasks from their config, the way RoboDojo's eval layouts are laid out (PROD-104). | |
| python dev_suite/sample_layouts.py [--tasks open_laptop ...] [--num 20] [--seed 0] | |
| Writes dev_suite/layouts/RoboDojo/arx_x5/<seed>/<task>_<n>.json (robodojo_agent links to arx_x5). The simulator reads them | |
| when ROBODOJO_LAYOUT_ROOT=dev_suite/layouts (patches/robodojo-layout-root.patch; the launchers set it). Reads only the | |
| task config, RoboDojo's scene config and the object metadata, never Assets/Eval_Layout. | |
| Config, as in RoboDojo task configs: per section (Rigid, Geometry, Articulation; Clutter = a clutter asset as a rigid body) | |
| a list of groups {common, category, select_mode}. common: xlim, ylim (env frame, metres), rotate_rand + rotate_deg | |
| (scalar d = [-d, d], or [lo, hi]), relative_plane (Table or Ground), margin, and either zlim + qpos (fixed height and | |
| orientation) or place_tag (the asset's resting frame from its metadata, default "up"). Ours: physics overrides and, for an | |
| articulation, joint_ratio [lo, hi] (where its joints start). | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import math | |
| import os | |
| import random | |
| import sys | |
| from pathlib import Path | |
| import yaml | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE.parent / "src")) | |
| from robodojo_agent import eval_guard # noqa: E402 | |
| ROBODOJO_ROOT = Path(os.environ.get("ROBODOJO_ROOT", Path.home() / "persist/coding/simulation/RoboDojo")) | |
| OBJECTS = ROBODOJO_ROOT / "Assets/Object/RoboDojo" | |
| SECTIONS = ["Geometry", "Articulation", "Rigid", "Clutter"] # placement order: fixtures first | |
| TASKS: dict[str, dict] = json.loads((HERE / "tasks.json").read_text()) | |
| def qmul(a, b): | |
| aw, ax, ay, az = a | |
| bw, bx, by, bz = b | |
| return [aw * bw - ax * bx - ay * by - az * bz, aw * bx + ax * bw + ay * bz - az * by, | |
| aw * by - ax * bz + ay * bw + az * bx, aw * bz + ax * by - ay * bx + az * bw] | |
| def qrot(q, v): | |
| w, x, y, z = qmul(qmul(q, [0.0, *v]), [q[0], -q[1], -q[2], -q[3]]) | |
| return [x, y, z] | |
| def uniform(rng: random.Random, lim) -> float: | |
| lo, hi = sorted(float(v) for v in lim) | |
| return rng.uniform(lo, hi) | |
| def plane_height(scene: dict, plane: str) -> float: | |
| if plane == "Table": | |
| return scene["Table"]["default_pos"][2] + scene["Table"]["scale"][2] / 2 | |
| if plane == "Ground": | |
| return scene["Ground"]["default_pos"][2] + scene["Ground"]["thickness"] / 2 | |
| raise ValueError(f"relative_plane {plane!r}: only Table and Ground are supported") | |
| def instance(rng, scene, section, category, idx, label, common, occupied, placed=None) -> dict: | |
| """One object record. `placed` (label -> (x, y, half_x, half_y, z_bottom, z_top, yaw), filled in here) serves our | |
| relative placements: `inside: <label>` (just over that container's rim, beside what is already in it, or over it when | |
| full: dropped in when dev_suite/robolab/settle_layouts.py settles the layout), `on_top: <label>` (on its top; with | |
| `offset: [dx, dy]` at that point of the parent's frame, turned with it), `beside: [<label>, dx, dy]` (on the plane | |
| next to it, dx / dy = -1, 0 or 1), `near: [<label>, dx, dy, dz]` (the parent's frame, turned with it; the bottom dz | |
| above the parent's bottom). With `offset` / `near` the yaw (rotate_deg) is relative to the parent's.""" | |
| placed = {} if placed is None else placed | |
| folder = "Clutter" if section == "Clutter" else section | |
| meta = json.loads((OBJECTS / folder / category / f"{idx:05d}/metadata.json").read_text()) | |
| size_x, size_y, size_z = meta["geometry"]["aligned_bbox"]["extents"] | |
| d = common.get("rotate_deg", 0) if common.get("rotate_rand", False) else 0 | |
| yaw = math.radians(uniform(rng, d if isinstance(d, list) else [-d, d])) | |
| rel = common.get("near") or (common.get("offset") and [common["on_top"], *common["offset"]]) | |
| if rel: | |
| yaw += placed[rel[0]][6] | |
| turn = [math.cos(yaw / 2), 0.0, 0.0, math.sin(yaw / 2)] | |
| if common.get("zlim") is not None: # fixed height above the plane and a fixed orientation | |
| base, offset = list(common.get("qpos", [1.0, 0.0, 0.0, 0.0])), [0.0, 0.0, uniform(rng, common["zlim"])] | |
| else: # resting on the plane in the asset's placement frame | |
| place = meta["active"]["place"][common.get("place_tag", "up")] | |
| base = place["orientation"] | |
| offset = [-v for v in qrot(base, place["projection_circle"]["center"][:3])] | |
| lying = qrot(base, [size_x, size_y, size_z]) # extents in the placement frame, before the yaw | |
| size_x, size_y, size_z = (abs(v) for v in lying) | |
| half_x = (abs(math.cos(yaw)) * size_x + abs(math.sin(yaw)) * size_y) / 2 | |
| half_y = (abs(math.sin(yaw)) * size_x + abs(math.cos(yaw)) * size_y) / 2 | |
| margin = float(common.get("margin", 0.01)) | |
| z = plane_height(scene, common.get("relative_plane", "Table")) | |
| parent = common.get("inside") or common.get("on_top") | |
| if rel: # a fixed point of the parent's frame | |
| px, py, _, _, p_bottom, p_top, p_yaw = placed[rel[0]] | |
| x = px + math.cos(p_yaw) * rel[1] - math.sin(p_yaw) * rel[2] | |
| y = py + math.sin(p_yaw) * rel[1] + math.cos(p_yaw) * rel[2] | |
| z = p_top + 0.003 if "on_top" in common else p_bottom + (rel[3] if len(rel) > 3 else 0.0) | |
| occupied.append((x, y, half_x, half_y, rel[0] if "on_top" in common else None, label)) | |
| elif parent: | |
| px, py, phx, phy, p_bottom, p_top, _ = placed[parent] | |
| wall = 0.015 if common.get("inside") else 0.0 | |
| room = [(px - max(phx - half_x - wall, 0.0), px + max(phx - half_x - wall, 0.0)), | |
| (py - max(phy - half_y - wall, 0.0), py + max(phy - half_y - wall, 0.0))] | |
| mates = [o for o in occupied if o[4] == parent] | |
| z = p_top + 0.01 if common.get("inside") else p_top + 0.003 | |
| for _ in range(500): | |
| x, y = uniform(rng, room[0]), uniform(rng, room[1]) | |
| if all(abs(x - ox) >= half_x + ohx + 0.005 or abs(y - oy) >= half_y + ohy + 0.005 for ox, oy, ohx, ohy, *_ in mates): | |
| break | |
| else: # no floor space left: on top of what is already in there | |
| x, y = px, py | |
| z = max([z] + [placed[o[5]][5] + 0.005 for o in mates]) | |
| occupied.append((x, y, half_x, half_y, parent, label)) | |
| elif common.get("beside"): | |
| ref, dx, dy = common["beside"] | |
| rx, ry, rhx, rhy, *_ = placed[ref] | |
| x, y = rx + dx * (rhx + half_x + 0.07), ry + dy * (rhy + half_y + 0.07) | |
| occupied.append((x, y, half_x, half_y, None, label)) | |
| else: | |
| for _ in range(2000): | |
| x, y = uniform(rng, common["xlim"]), uniform(rng, common["ylim"]) | |
| if all(abs(x - o[0]) >= half_x + o[2] + margin or abs(y - o[1]) >= half_y + o[3] + margin | |
| for o in occupied if o[4] is None): | |
| break | |
| else: | |
| raise RuntimeError(f"no room for {label}") | |
| occupied.append((x, y, half_x, half_y, None, label)) | |
| placed[label] = (x, y, half_x, half_y, z, z + size_z, yaw) | |
| offset = qrot(turn, offset) | |
| physics = {k: v for k, v in (meta.get("physics") or {}).items() if k != "size"} | |
| if "friction" in physics: | |
| physics["static_friction"] = physics["dynamic_friction"] = physics.pop("friction") | |
| physics.update(common.get("physics", {})) | |
| physics["type"] = "rigid" if section == "Clutter" else section.lower() | |
| record = { | |
| "category": category, "category_idx": idx, "label": label, | |
| "default_pos": [x + offset[0], y + offset[1], z + offset[2]], | |
| "default_ori": qmul(turn, base), | |
| "scale": common.get("scale", [1.0, 1.0, 1.0]), | |
| "relative_plane": common.get("relative_plane", "Table"), | |
| "physics": physics, | |
| "visual": common.get("visual", {}), | |
| } | |
| if "joint_ratio" in common: # ours: where an articulation's joints start, 0 = lower limit .. 1 = upper (the task applies it) | |
| record["joint_ratio"] = uniform(rng, common["joint_ratio"]) | |
| if section == "Clutter": | |
| record["type"] = "cluttered" # RoboDojo then loads the asset from Object/RoboDojo/Clutter | |
| return record | |
| def camera_stand(scene: dict) -> dict: | |
| """The fixed head-camera stand of the scene config (RoboDojo puts it in every layout).""" | |
| (group,) = scene["Geometry"] | |
| common = group["common"] | |
| meta = json.loads((OBJECTS / "Geometry/camera_stand/00000/metadata.json").read_text()) | |
| physics = {k: v for k, v in (meta.get("physics") or {}).items() if k != "size"} | {"type": "geometry"} | |
| pos = [common["xlim"][0], common["ylim"][0], plane_height(scene, "Ground") + common["zlim"][0]] | |
| return {"category": "camera_stand", "category_idx": 0, "label": "camera_stand", "default_pos": pos, | |
| "default_ori": common["qpos"], "scale": [1.0, 1.0, 1.0], "relative_plane": "Ground", | |
| "physics": physics, "visual": {}} | |
| def layout(task: str, config: dict, scene: dict, rng: random.Random) -> dict: | |
| out = { | |
| "Room": {"default": scene["Room"]["default"], "default_pos": scene["Room"]["default_pos"], | |
| "default_rot": scene["Room"]["default_ori"], "scale": scene["Room"]["scale"]}, | |
| "Table": scene["Table"], "Ground": scene["Ground"], | |
| "Background": {"intensity": scene["Background"]["intensity"], "category_name": scene["Background"]["default"]}, | |
| "Geometry": {"camera_stand": [camera_stand(scene)]}, | |
| } | |
| occupied: list[tuple] = [] | |
| placed: dict[str, tuple] = {} | |
| for section in SECTIONS: | |
| for group in config.get(section, []): | |
| common, select = group["common"], group["select_mode"] | |
| picks = [(c["name"], i) for c in group["category"] for i in c["index"]] | |
| chosen = rng.sample(picks, select["nums"]) if select["mode"] == "unique" else rng.choices(picks, k=select["nums"]) | |
| for (category, idx), label in zip(chosen, select["label"]): | |
| rec = instance(rng, scene, section, category, idx, label, common, occupied, placed) | |
| out.setdefault("Rigid" if section == "Clutter" else section, {}).setdefault(category, []).append(rec) | |
| return out | |
| def main() -> None: | |
| p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| p.add_argument("--tasks", nargs="+", default=[t for t in TASKS if not t.startswith(("rl_", "hd_"))], | |
| help="default: all but the tasks of dev_suite/robolab/tasks.yml (rl_*, hd_*: build.py samples those)") | |
| p.add_argument("--num", type=int, default=20, help="layouts per task") | |
| p.add_argument("--seed", type=int, default=0) | |
| args = p.parse_args() | |
| scene = yaml.safe_load((ROBODOJO_ROOT / "env_cfg/scene/default.yml").read_text()) | |
| out_dir = HERE / "layouts/RoboDojo/arx_x5" / str(args.seed) | |
| out_dir.mkdir(parents=True, exist_ok=True) | |
| link = HERE / "layouts/RoboDojo/robodojo_agent" # our env cfg uses the arx_x5 scene | |
| if not link.exists(): | |
| link.symlink_to("arx_x5") | |
| for task in args.tasks: | |
| eval_guard.check_dev_task(task, TASKS[task]["steps"]) | |
| config = yaml.safe_load((HERE / "config" / f"{task}.yml").read_text()) | |
| for n in range(args.num): | |
| rng = random.Random(f"{task}/{args.seed}/{n}") | |
| (out_dir / f"{task}_{n}.json").write_text(json.dumps(layout(task, config, scene, rng), indent=1)) | |
| print(f"{task}: {args.num} layouts -> {out_dir}") | |
| if __name__ == "__main__": | |
| main() | |