"""RoboLab's tasks ported to RoboDojo (PROD-116): one task class per entry of dev_suite/robolab/tasks.yml. Each dev_suite/tasks/rl_.py (written by dev_suite/robolab/build.py) is ``rl_ = robolab_task("rl_")``. The success conditions come from tasks.yml and map onto RoboDojo's reward library: in / on_top A B -> is_A_in_B (A's origin over B's footprint, above B's bottom) out A B -> is_A_not_in_B upright A -> is_axis_up (z, 15 deg) stacked A B -> is_stacked (B on A) lower A B -> A's centre below B's top left_of / right_of A B -> is_A_on_B_left / right (5 cm) behind / in_front_of A B -> A's y 5 cm past B's (below) center A -> within 5 cm of the table centre still A -> is_not_moved (3 cm) {any: [...]} -> OR {k: n, of: [...]} -> OR over the n-subsets (exactly: is_N_A_in_B) Ours (rc_ tasks, PROD-120), judged here (`rc_cond`) from the poses, the metadata and the joints: within A B -> A's origin inside B's box (3-D) region A B [[x0, x1], [y0, y1]] -> A's origin there in B's frame axis_up A x|y|z deg -> that axis of A within deg of vertical (either way up) turned A B deg -> A's x axis within deg of B's y axis (either way) above A h -> A's origin h over the table shut A tag -> A's joint `tag` within 5% of its range of 0 (at rest) moved A d -> A over d from where it started [not, c] {all: [...]} -> AND `never: [c, ...]` in a task: the episode fails the first time one holds (RoboDojo's query with aim 0). `step_lim` overrides the step budget (300 per object moved, at least 600). Every task also needs both arms back home (as RoboDojo's own tasks do), which stands in for RoboLab's "gripper detached". """ from __future__ import annotations import itertools import types from pathlib import Path import numpy as np import yaml from env.environment.task_env import TaskEnv from env.reward_manager.reward_manager import RewardManager SPEC = Path(__file__).resolve().parents[1] / "robolab/tasks.yml" TABLE_CENTRE = [0.0, -0.05] # env frame, RoboDojo's scene config (env_cfg/scene/default.yml) SIDE_MARGIN = 0.05 # m past the reference object for left_of / right_of / behind / in_front_of TABLE_Z = 0.765 # env frame, the table top RC_OPS = ("within", "region", "axis_up", "turned", "above", "shut", "moved", "not") ONE_OBJECT = ("upright", "center", "still", "axis_up", "above", "shut", "moved") SHUT = 0.05 # of the joint's range def _y_past(parser, args) -> float: """1 if A's y is ``margin`` past B's: behind (away from the robot, +y) or in front (towards it, -y).""" env_idx = args["env_idx"] pos = [] for label in (args["label_A"], args["label_B"]): name = parser.layout_manager.get_instance_name(label=label, env_idx=env_idx) if name is None: return 0.0 pos.append(np.asarray(parser.layout_manager.get_instance_pose(inst_name=name, env_idx=env_idx)[0], dtype=float)) d = pos[0][1] - pos[1][1] return 1.0 if (d if args["behind"] else -d) > args["margin"] else 0.0 def _rot(q) -> np.ndarray: w, x, y, z = (float(v) for v in q) return np.array([[1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)], [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)], [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)]]) def _rc_cond(task, parser, args) -> float: return 1.0 if task.holds(args["cond"], args["env_idx"]) else 0.0 def compile_condition(rm: RewardManager, c): """A condition of tasks.yml -> a reward-manager check: a tuple, or a list = OR of (tuples | lists = AND of tuples).""" if (isinstance(c, dict) and "all" in c) or (isinstance(c, list) and c[0] in RC_OPS): return ("rc_cond", {"cond": c}) if isinstance(c, dict): if "any" in c: return [x for o in c["any"] for x in _alternatives(rm, o)] k, of = c["k"], c["of"] if c.get("exactly"): # all [in, A_i, B]: exactly k of them in B (container,) = {o[2] for o in of} return rm.is_N_A_in_B([o[1] for o in of], container, k) return [[compile_condition(rm, o) for o in subset] for subset in itertools.combinations(of, k)] op, a, b = (c + [None])[:3] if op in ("in", "on_top"): return rm.is_A_in_B(label_A=a, label_B=b) if op == "out": return rm.is_A_not_in_B(label_A=a, label_B=b) if op == "upright": return rm.is_axis_up(label=a, axis=[0.0, 0.0, 1.0], threshold=15) if op == "stacked": return rm.is_stacked([a, b], xy_threshold=0.04, in_order=True) if op == "lower": return rm.is_A_z_lower_than_B_bbox_zmax(label_A=a, label_B=b) if op == "left_of": return rm.is_A_on_B_left(label_A=a, label_B=b, x_threshold=SIDE_MARGIN) if op == "right_of": return rm.is_A_on_B_right(label_A=a, label_B=b, x_threshold=SIDE_MARGIN) if op in ("behind", "in_front_of"): return ("rl_y_past", {"label_A": a, "label_B": b, "behind": op == "behind", "margin": SIDE_MARGIN}) if op == "center": return rm.is_A_xy_distance_close_to_pos(label=a, pos=TABLE_CENTRE, dis_threshold=0.05) if op == "still": return rm.is_not_moved(label=a, dis_threshold=0.03) raise ValueError(f"unknown condition {c!r}") def _alternatives(rm, c) -> list: """The OR-alternatives of a condition (an `any` inside an `any` flattens).""" x = compile_condition(rm, c) return x if isinstance(x, list) and isinstance(c, dict) and "any" in c else [x] def stages(spec: dict) -> list[list]: """The task's condition lists, in order (one for `success`, several for `sequence`).""" return spec["sequence"] if "sequence" in spec else [spec["success"]] class RoboLabTask(TaskEnv): spec_name = "" def __init__(self, config, app, **kwargs): super().__init__(config, app, **kwargs) self.spec = yaml.safe_load(SPEC.read_text())["tasks"][self.spec_name] self.reward_manager = RewardManager(self.num_envs) parser = self.reward_manager.func_parser parser.rl_y_past = types.MethodType(_y_past, parser) parser.rc_cond = types.MethodType(lambda p, args: _rc_cond(self, p, args), parser) movers = {c[1] for stage in stages(self.spec) for c in _atoms(stage) if c[0] not in ("still", "moved", "shut")} self.step_lim = self.spec.get("step_lim", 300 * max(2, len(movers))) def _post_setup_scene(self, sim): super()._post_setup_scene(sim) self.reward_manager.initialize(self) def reset(self, seed=None, options=None): super().reset(seed=seed, options=options) self.reward_manager.reset() def run_reward(self): rm = self.reward_manager all_stages = stages(self.spec) for i, stage in enumerate(all_stages): checks = [compile_condition(rm, c) for c in stage] if i == len(all_stages) - 1: checks.append(rm.all_robot_back_to_origin()) rm.check(checks) for c in self.spec.get("never", []): rm.query([("rc_cond", {"cond": c})], 0) # ---- rc_cond: our conditions, from the scene's poses, metadata and joints ---------------------------------------- def _pose(self, label, env_idx): lm = self.scene_manager.layout_manager name = lm.get_instance_name(label=label, env_idx=env_idx) pos, quat = lm.get_instance_pose(inst_name=name, env_idx=env_idx) return name, np.asarray(pos, dtype=float), _rot(quat) def _extents(self, name, env_idx) -> np.ndarray: meta = self.scene_manager.layout_manager.get_instance_metadata(inst_name=name, env_idx=env_idx) return np.asarray(meta["geometry"]["aligned_bbox"]["extents"], dtype=float) def holds(self, c, env_idx) -> bool: if isinstance(c, dict): if "all" in c: return all(self.holds(o, env_idx) for o in c["all"]) if "any" in c: return any(self.holds(o, env_idx) for o in c["any"]) op = c[0] if op == "not": return not self.holds(c[1], env_idx) if op not in RC_OPS: return self.reward_manager.check_once(compile_condition(self.reward_manager, c), env_idx) name, pa, ra = self._pose(c[1], env_idx) if op in ("within", "region"): name_b, pb, rb = self._pose(c[2], env_idx) local = rb.T @ (pa - pb) if op == "within": return bool(np.all(np.abs(local) <= self._extents(name_b, env_idx) / 2)) (x0, x1), (y0, y1) = c[3] return bool(x0 <= local[0] <= x1 and y0 <= local[1] <= y1) if op == "axis_up": return abs(ra[2, "xyz".index(c[2])]) >= np.cos(np.radians(c[3])) if op == "turned": _, _, rb = self._pose(c[2], env_idx) ax, by = ra[:2, 0], rb[:2, 1] return abs(ax @ by) >= np.cos(np.radians(c[3])) * np.linalg.norm(ax) * np.linalg.norm(by) if op == "above": return pa[2] - TABLE_Z >= float(c[2]) if op == "moved": start = self.reward_manager.func_parser.pre_state[env_idx][name]["pose"] return float(np.linalg.norm(pa - np.asarray(start, dtype=float)[:3])) > float(c[2]) if op == "shut": lm = self.scene_manager.layout_manager joint = lm.get_instance_metadata(inst_name=name, env_idx=env_idx)["passive"]["functional"][c[2]]["parent_joint"] info = lm.get_scene_object(inst_name=name, env_idx=env_idx).get_joint_info(joint) return abs(info["position"]) <= SHUT * max(abs(info["lower"]), abs(info["upper"])) raise ValueError(f"unknown condition {c!r}") def gen_instruction(self, env_idx): return [self.spec["instruction"]] def _atoms(conditions) -> list: out = [] for c in conditions: if isinstance(c, dict): out += _atoms(c.get("any", c.get("all", c.get("of", [])))) elif c[0] == "not": out += _atoms([c[1]]) else: out.append(c) return out def robolab_task(name: str) -> type: return type(name, (RoboLabTask,), {"spec_name": name})