File size: 13,471 Bytes
5a3fcf5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""Referent labels for the SO-101 shards from the demonstrations themselves ("hindsight"): no detector, no hand marks.

The gripper's 3D tip comes from the recorded joints (URDF forward kinematics, with the joint offsets of the camera
fit). Where the gripper closes on an object is where that object was; where it opens is where the object was put.
Per frame the labels are the active step's skill code, the object point ("what") and the destination point ("where",
or none) in the robot's base frame, in metres. The policy sees them as form B: projected into the fixed camera with
the fitted camera (scripts/fit_camera.py), plus their offset from the projected tip.

Steps per task (REALWORLD.md, Stage 2):
  towel    fold:           what = grasp point (then the tip, the towel edge is in the hand), where = release point
  cups     pick-and-place: what = pink cup at grasp 1, where = release 1 (beige cup); then
           pick-and-place: what = grasp 2 (the beige cup), where = release 2 (white cup)
  drawer   open:  what = handle (the first reach before the block grasp; then the tip while pulling), no where;
           pick-and-place: what = block grasp point, where = block release point (inside the drawer);
           close: what = the handle where the pull ended (drawer open), no where
  push     push:  what = the mug, where = where the mug ends. The gripper never opens in this task, so the mug is found
           by colour in the fixed view (yellow) and placed on the table plane through the camera.
Gripper events: a fall (close) or rise (open) of more than --delta units within --win frames (10 Hz). An episode whose
events do not match its task's pattern is listed and gets no labels (mask False).

Writes ref.npz into every shard directory (train and val): step, skill, what (N, 3), where (N, 3), where_valid, ok
(frame labelled), tip (N, 3); and <out>/labels_report.json.
"""
import argparse
import json
import os
import sys

import numpy as np
import torch

sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from popt.so101 import SO101, SO101Torch, project  # noqa: E402

SKILLS = {"open": 0, "pick_place": 1, "close": 2, "push": 3, "fold": 4}  # PoP's 5 skill rows; row 5 = unspecified
TASK = {"so101-fold-towel": "towel", "so101-stack-cup-v4": "cups", "so101-drawer-v3": "drawer", "so101-push": "push"}


def events(g: np.ndarray, delta: float, win: int) -> list:
    """[(t, 'close' | 'open')], alternating; close at the end of a fall, open at the start of a rise."""
    d = g[win:] - g[:-win]
    out = []
    for kind, m in (("close", d < -delta), ("open", d > delta)):
        t = 0
        while t < len(m):
            if m[t]:
                s = t
                while t < len(m) and m[t]:
                    t += 1
                out.append((t - 1 + win if kind == "close" else s, kind))
            t += 1
    out.sort()
    merged = []
    for t, k in out:  # collapse repeats of the same kind (a fall in two stages is one close)
        if merged and merged[-1][1] == k:
            if k == "close":
                merged[-1] = (t, k)
            continue
        merged.append((t, k))
    return merged


def label_episode(task, tip, g, a, img=None, cam=None, table_z=None):
    """-> dict of per-frame arrays, or a reason string."""
    L = len(tip)
    step = np.full(L, -1); skill = np.full(L, -1)
    what = np.zeros((L, 3)); where = np.zeros((L, 3)); wv = np.zeros(L, bool)
    ev = events(g, a.delta, a.win)
    closes = [t for t, k in ev if k == "close"]
    opens = [t for t, k in ev if k == "open"]

    def fill(s, e, k, sk, obj, dst, grasp_t=None):
        step[s:e] = k; skill[s:e] = SKILLS[sk]
        what[s:e] = obj
        if grasp_t is not None and grasp_t < e:
            what[max(s, grasp_t):e] = tip[max(s, grasp_t):e]  # object in the hand
        if dst is not None:
            where[s:e] = dst; wv[s:e] = True

    if task in ("towel", "cups"):
        n = 1 if task == "towel" else 2
        seq, t0 = [], 0
        for _ in range(n):
            gc = [t for t in closes if t > t0 and any(o < t for o in opens)]
            if not gc:
                return "no_grasp"
            tg = gc[0]
            ro = [t for t in opens if t > tg]
            if not ro:
                return "no_release"
            tr = ro[0]
            seq.append((tg, tr)); t0 = tr
        s = 0
        for k, (tg, tr) in enumerate(seq):
            e = tr + 1 if k < n - 1 else L
            fill(s, e, k, "fold" if task == "towel" else "pick_place", tip[tg], tip[tr], grasp_t=tg)
            s = e
    elif task == "drawer":
        if not opens:
            return "no_events"
        first_open = opens[0]
        r = np.linalg.norm(tip[:, :2], axis=1)  # horizontal reach from the base
        # handle: the first reach peak after the gripper opens that is followed by a pull of at least 5 cm within
        # 4 s; end of the pull: the closest point to the base before the arm lifts (3 cm above the pull's lowest point)
        th = tp = None
        for t in range(first_open, L - 1):
            w = r[t:min(t + 40, L)]
            if len(w) > 2 and r[t] >= r[max(t - 5, 0):t + 6].max() and r[t] - w.min() > 0.05:
                th = t
                break
        if th is None:
            return "no_pull"
        lift = th + 1
        while lift < L and tip[lift, 2] - tip[th:lift + 1, 2].min() < 0.03:
            lift += 1
        tp = th + int(np.argmin(r[th:lift]))
        # block grasp: after the pull, the gripper falls 8 units below its open value and settles (hold value);
        # release: the first time it leaves the hold value by more than 1 unit, opening or closing
        # a close below --hold-min units holds nothing (missed grasp): wait for the gripper to reopen and look again
        start = tp + 1
        while True:
            g_open = g[start - 1]
            tc = start
            while tc < L and g[tc] > g_open - 8:
                tc += 1
            if tc >= L - 3:
                return "no_grasp"
            tg = tc
            while tg < L - 3 and g[tg + 3] < g[tg] - 0.5:
                tg += 1
            if g[tg] >= a.hold_min:
                break
            reo = tg + 1
            while reo < L and g[reo] < a.hold_min + 8:
                reo += 1
            if reo >= L - 3:
                return "no_grasp"
            while reo < L - 1 and g[reo + 1] > g[reo] + 0.5:  # let it finish opening
                reo += 1
            start = reo + 1
        tr = tg + 1
        while tr < L and abs(g[tr] - g[tg]) <= 1.0:
            tr += 1
        if tr >= L:
            return "no_release"
        fill(0, tp + 1, 0, "open", tip[th], None, grasp_t=th)
        fill(tp + 1, tr + 1, 1, "pick_place", tip[tg], tip[tr], grasp_t=tg)
        fill(tr + 1, L, 2, "close", tip[tp], None)
    elif task == "push":
        if img is None:
            return "no_image"
        mug = mug_track(img, cam, table_z, a)
        if mug is None:
            return "no_mug"
        fill(0, L, 0, "push", 0.0, mug[-1])
        what[:] = mug
    return {"step": step, "skill": skill, "what": what, "where": where, "where_valid": wv}


def yellow_mask(img):
    x = img.astype(np.float32) / 255
    mx, mn = x.max(-1), x.min(-1)
    dd = mx - mn + 1e-6
    r, g, b = x[..., 0], x[..., 1], x[..., 2]
    h = np.where(mx == r, ((g - b) / dd) % 6, np.where(mx == g, (b - r) / dd + 2, (r - g) / dd + 4)) * 60
    s = dd / (mx + 1e-6)
    return (h >= 42) & (h <= 66) & (s >= 0.45) & (mx >= 0.35)


def mug_track(img, cam, table_z, a):
    """Mug centroid per frame (yellow pixels; held over frames where it is hidden) -> 3D on the plane z = table_z
    + mug half height."""
    m = yellow_mask(np.asarray(img))
    L = len(m)
    pts = np.full((L, 2), np.nan)
    for t in range(L):
        ys, xs = np.nonzero(m[t])
        if len(xs) >= a.min_px:
            pts[t] = [xs.mean(), ys.mean()]
    ok = ~np.isnan(pts[:, 0])
    if ok.sum() < L // 2 or not ok[0]:
        return None
    for t in range(1, L):  # hold the last seen position
        if not ok[t]:
            pts[t] = pts[t - 1]
    return backproject(pts, cam, table_z + a.mug_half_height)


def backproject(uv, cam, z_plane):
    """Pixels (N, 2) in the stored image -> points on the plane z = z_plane (base frame)."""
    from popt.so101 import rotvec_to_matrix
    R = rotvec_to_matrix(torch.tensor(cam["rotvec"])).numpy()
    t = np.array(cam["t"]); f = np.array(cam["f"]); c = np.array(cam["c"])
    xy = (uv - c) / f
    if "k1" in cam:  # undo radial distortion by fixed-point iteration
        xd = xy.copy()
        for _ in range(10):
            r2 = (xy ** 2).sum(1, keepdims=True)
            xy = xd / (1 + cam["k1"] * r2 + cam.get("k2", 0.0) * r2 ** 2)
    rays = np.concatenate([xy, np.ones((len(xy), 1))], 1) @ R  # camera -> base directions (R^T d)
    C = -R.T @ t
    s = (z_plane - C[2]) / rays[:, 2]
    return C + s[:, None] * rays


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--shards", required=True, help="directory with train/ and val/")
    p.add_argument("--camera", required=True, help="directory with <shard>.json from scripts/fit_camera.py")
    p.add_argument("--urdf", required=True)
    p.add_argument("--delta", type=float, default=6.0, help="gripper change (units of 0-100) that counts as an event")
    p.add_argument("--win", type=int, default=3, help="frames (10 Hz) over which the change is measured")
    p.add_argument("--hold-min", type=float, default=8.0, help="drawer: a block hold keeps the gripper above this")
    p.add_argument("--release-tol", type=float, default=0.06, help="drawer: max distance (m) of a block release from the median")
    p.add_argument("--min-px", type=int, default=30, help="push: yellow pixels for the mug to count as seen")
    p.add_argument("--mug-half-height", type=float, default=0.045)
    a = p.parse_args()
    arm = SO101(a.urdf, 1)
    kin = SO101Torch(arm, "cpu")
    report, drawer_release = {}, {}
    for split in ("train", "val"):
        idx = json.load(open(os.path.join(a.shards, split, "index.json")))
        for s in idx["shards"]:
            d = os.path.join(a.shards, split, s["dir"])
            cam_j = json.load(open(os.path.join(a.camera, s["dir"] + ".json")))
            cam = cam_j["camera"] | ({"k1": cam_j["distortion_k1_k2"][0], "k2": cam_j["distortion_k1_k2"][1]} if "distortion_k1_k2" in cam_j else {})
            off = torch.tensor(cam_j.get("joint_offsets_deg", [0] * 5) + [0.0])
            z = np.load(os.path.join(d, "arrays.npz"))
            eps = json.load(open(os.path.join(d, "episodes.json")))
            N = s["frames"]
            with torch.no_grad():
                tip = kin.tip(torch.tensor(z["state"], dtype=torch.float32), off).numpy().astype(np.float64)
            task = TASK[s["dataset"].split("/")[-1]]
            # table height: the lowest tip heights reached while the gripper is closed on something
            table_z = float(np.percentile(tip[:, 2], 1))
            img = np.memmap(os.path.join(d, "agent.u8"), np.uint8, "r", shape=(N, 256, 256, 3)) if task == "push" else None
            out = {k: np.zeros((N,) + sh, dt) for k, sh, dt in (("step", (), np.int16), ("skill", (), np.int16),
                                                             ("what", (3,), np.float32), ("where", (3,), np.float32),
                                                             ("where_valid", (), bool), ("ok", (), bool))}
            rep = {"episodes": len(eps), "labelled": 0, "dropped": {}, "table_z": table_z, "dropped_episodes": {}}
            results = []
            for e in eps:
                sl = slice(e["start"], e["start"] + e["length"])
                r = label_episode(task, tip[sl], z["state"][sl, 5].astype(np.float64), a,
                                  img[sl] if img is not None else None, cam, table_z)
                results.append((e, sl, r))
            if task == "drawer":
                # the drawer unit does not move: a block release far from the usual one is a mislabelled event
                rel = lambda r: r["where"][int(np.argmax(r["step"] == 1))]  # noqa: E731
                if split == "train":
                    drawer_release[s["dataset"]] = np.median([rel(r) for _, _, r in results if not isinstance(r, str)], 0)
                med = drawer_release[s["dataset"]]
                results = [(e, sl, "release_off_drawer" if not isinstance(r, str) and np.linalg.norm(rel(r) - med) > a.release_tol else r)
                           for e, sl, r in results]
                rep["drawer_release_median_m"] = med.round(4).tolist()
            for e, sl, r in results:
                if isinstance(r, str):
                    rep["dropped"][r] = rep["dropped"].get(r, 0) + 1
                    rep["dropped_episodes"][str(e["source_episode"])] = r
                    continue
                for k in ("step", "skill", "what", "where", "where_valid"):
                    out[k][sl] = r[k]
                out["ok"][sl] = r["step"] >= 0
                rep["labelled"] += 1
            np.savez(os.path.join(d, "ref.npz"), tip=tip.astype(np.float32), **out)
            json.dump(cam_j, open(os.path.join(d, "camera.json"), "w"), indent=1)
            report[f"{split}/{s['dir']}"] = rep
            print(split, s["dataset"], rep, flush=True)
    json.dump(report, open(os.path.join(a.shards, "labels_report.json"), "w"), indent=1)


if __name__ == "__main__":
    main()