File size: 13,260 Bytes
0fb9287
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
 
079e69d
 
 
 
 
98a23ba
 
 
0fb9287
 
 
 
 
 
079e69d
0fb9287
 
 
 
 
 
 
 
 
079e69d
 
0fb9287
 
98a23ba
079e69d
 
98a23ba
0fb9287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
 
 
 
 
 
 
0fb9287
 
98a23ba
 
0fb9287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
0fb9287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
 
 
 
 
 
 
 
 
 
079e69d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
 
 
 
 
 
 
 
079e69d
 
 
 
 
 
 
 
 
 
 
 
98a23ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
079e69d
98a23ba
079e69d
 
 
 
 
 
 
98a23ba
0fb9287
 
 
 
 
 
 
 
 
98a23ba
 
 
0fb9287
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
"""RoboLab's tasks ported to RoboDojo (PROD-116): one task class per entry of dev_suite/robolab/tasks.yml.

Each dev_suite/tasks/rl_<name>.py (written by dev_suite/robolab/build.py) is ``rl_<name> = robolab_task("rl_<name>")``.
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
Ours (dv_ tasks, dev_suite/diverse):
    joint A tag lo hi -> A's joint `tag` between lo and hi (the USD's units: deg for a hinge, m for a slide)
    links_within A B n -> at least n of articulation A's link centres inside B's box (forward kinematics, _link_centres)
    faces A axis [x, y, z] deg -> A's axis (x, -x, y, ...) within deg of that env-frame direction
    aligned A B d -> A's and B's origins within d of each other along y (side by side in a row across the table)
`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 os
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

# a task studio draft (PROD-146) brings its own tasks.yml; the sim server sets this per episode
SPEC = Path(os.environ.get("ROBODOJO_TASK_SPEC") or 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", "joint", "links_within", "faces", "aligned")
ONE_OBJECT = ("upright", "center", "still", "axis_up", "above", "shut", "moved", "joint", "faces")
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 _link_centres(self, label, env_idx) -> list:
        """An articulation's link centres (env frame) by forward kinematics from its root link's pose and its joint
        angles, with the chain the builder writes into the metadata (make_objects: passive.chain, passive.centres)."""
        name, p0, r0 = self._pose(label, env_idx)
        lm = self.scene_manager.layout_manager
        meta = lm.get_instance_metadata(inst_name=name, env_idx=env_idx)["passive"]
        obj = lm.get_scene_object(inst_name=name, env_idx=env_idx)
        frames = {meta["links"][0]: (r0, p0)}
        for j in meta["chain"]:
            info = obj.get_joint_info(j["joint"])
            limit = max(j["limits"], key=abs)  # the sim's units -> degrees, by the limit
            q = np.radians(info["position"] * limit / (info["upper"] if limit > 0 else info["lower"]))
            u = np.eye(3)["XYZ".index(j["axis"])]
            k = np.array([[0, -u[2], u[1]], [u[2], 0, -u[0]], [-u[1], u[0], 0]])
            rj = np.eye(3) + np.sin(q) * k + (1 - np.cos(q)) * k @ k  # Rodrigues
            r_p, t_p = frames[j["parent"]]
            a = np.asarray(j["at"], dtype=float)
            frames[j["child"]] = (r_p @ rj, t_p + r_p @ (a - rj @ a))
        return [t + r @ np.asarray(meta["centres"][k], dtype=float) for k, (r, t) in frames.items()]

    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 == "links_within":
            name_b, pb, rb = self._pose(c[2], env_idx)
            half = self._extents(name_b, env_idx) / 2
            inside = sum(bool(np.all(np.abs(rb.T @ (x - pb)) <= half)) for x in self._link_centres(c[1], env_idx))
            return inside >= int(c[3])
        if op == "aligned":
            _, pb, _ = self._pose(c[2], env_idx)
            return abs(pa[1] - pb[1]) <= float(c[3])
        if op == "faces":
            sign, axis = (-1.0, c[2][1]) if c[2].startswith("-") else (1.0, c[2])
            v, want = sign * ra[:, "xyz".index(axis)], np.asarray(c[3], dtype=float)
            return float(v @ want) >= np.cos(np.radians(c[4])) * np.linalg.norm(want)
        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 in ("shut", "joint"):
            lm = self.scene_manager.layout_manager
            functional = lm.get_instance_metadata(inst_name=name, env_idx=env_idx)["passive"]["functional"][c[2]]
            info = lm.get_scene_object(inst_name=name, env_idx=env_idx).get_joint_info(functional["parent_joint"])
            if op == "shut":
                return abs(info["position"]) <= SHUT * max(abs(info["lower"]), abs(info["upper"]))
            limit = max(functional["limits"], key=abs)  # the sim's units (rad) -> the USD's (deg) by the limit
            pos = info["position"] * limit / (info["upper"] if limit > 0 else info["lower"])
            return float(c[3]) <= pos <= float(c[4])
        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})