File size: 13,565 Bytes
b4396f0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
#!/usr/bin/env python3
"""Build the gripper-event segment map for DATA V2 (SPEC in WORKLOG).

Segments: debounced gripper-command sign changes on action[6];
segment k ends at boundary k (the switching frame belongs to the
segment it completes); the tail after the last boundary merges
into the last segment. Typing walks an ordered per-task sub-goal
list: a segment ending in a transition INTO closed takes the
current sub-goal's grasp phrase; INTO open takes its release
phrase and advances the pointer. Train episodes only (factory
split replicated: per task, last ceil(0.1*n) episodes held out).

Outputs (in ~/sera_v4_experiments/quest_probe/):
  segment_map.npz   — segments + per-frame table + comp3 anchors
  segment_map_summary.json — distributions for verification
  segment_spotcheck.txt    — 10 random episodes vs gripper trace
"""
import glob
import json
import math
import os

import numpy as np
import pandas as pd

SNAP = os.path.expanduser(
    "~/.cache/huggingface/hub/datasets--lerobot--libero/snapshots/"
    "a1aaacb7f6cd6ee5fb43120f673cebb0cfea7dd4"
)
OUT_DIR = os.path.expanduser("~/sera_v4_experiments/quest_probe")
DEBOUNCE = 3
EVAL_SPLIT = 0.1

# (grasp_phrase, release_phrase) per sub-goal, in execution order.
SUBGOALS = {
    0: [("pick up the white mug", "put the white mug on the left plate"),
        ("pick up the yellow and white mug", "put the yellow and white mug on the right plate")],
    1: [("pick up the white mug", "put the white mug on the plate"),
        ("pick up the chocolate pudding", "put the chocolate pudding to the right of the plate")],
    2: [("pick up the yellow and white mug", "put the yellow and white mug in the microwave"),
        ("close the microwave", "close the microwave")],
    3: [("turn on the stove", "turn on the stove"),
        ("pick up the moka pot", "put the moka pot on the stove")],
    4: [("pick up the alphabet soup", "put the alphabet soup in the basket"),
        ("pick up the cream cheese box", "put the cream cheese box in the basket")],
    5: [("pick up the alphabet soup", "put the alphabet soup in the basket"),
        ("pick up the tomato sauce", "put the tomato sauce in the basket")],
    6: [("pick up the moka pot", "put the moka pot on the stove"),
        ("pick up the moka pot", "put the moka pot on the stove")],
    7: [("pick up the cream cheese box", "put the cream cheese box in the basket"),
        ("pick up the butter", "put the butter in the basket")],
    8: [("pick up the black bowl", "put the black bowl in the bottom drawer of the cabinet"),
        ("close the drawer", "close the drawer")],
    9: [("pick up the book", "place the book in the back compartment of the caddy")],
    10: [("pick up the bowl", "put the bowl on the plate")],
    11: [("pick up the wine bottle", "put the wine bottle on the rack")],
    12: [("open the top drawer", "open the top drawer"),
         ("pick up the bowl", "put the bowl inside the top drawer")],
    13: [("pick up the cream cheese", "put the cream cheese in the bowl")],
    14: [("pick up the wine bottle", "put the wine bottle on top of the cabinet")],
    15: [("push the plate to the front of the stove", "push the plate to the front of the stove")],
    16: [("turn on the stove", "turn on the stove")],
    17: [("pick up the bowl", "put the bowl on the stove")],
    18: [("pick up the bowl", "put the bowl on top of the cabinet")],
    19: [("open the middle drawer of the cabinet", "open the middle drawer of the cabinet")],
}
_OBJ = ["orange juice", "ketchup", "cream cheese", "bbq sauce", "alphabet soup",
        "milk", "salad dressing", "butter", "tomato sauce", "chocolate pudding"]
for i, x in enumerate(_OBJ):
    SUBGOALS[20 + i] = [(f"pick up the {x}", f"place the {x} in the basket")]
_SPATIAL = ["next to the cookie box", "in the top drawer of the wooden cabinet",
            "on the ramekin", "on the stove", "between the plate and the ramekin",
            "on the cookie box", "next to the plate", "next to the ramekin",
            "from table center", "on the wooden cabinet"]
for i, q in enumerate(_SPATIAL):
    SUBGOALS[30 + i] = [(f"pick up the black bowl {q}", "place the black bowl on the plate")]


def seg_type(phrase: str) -> str:
    if phrase.startswith("pick up"):
        return "pick"
    if phrase.startswith(("put ", "place ")):
        return "place"
    if phrase.startswith("open"):
        return "open"
    if phrase.startswith("close"):
        return "close"
    if phrase.startswith("turn on"):
        return "turn_on"
    if phrase.startswith("push"):
        return "push"
    return "other"


def hash_coin(ep: int, frame: int, salt: int) -> bool:
    h = ((ep * 2654435761) ^ (frame * 40503) ^ (salt * 974711)) & 0xFFFFFFFF
    return (h % 1000) < 500


def debounced_runs(state: np.ndarray) -> list[tuple[int, bool]]:
    """Return [(start_frame, is_closed)] runs of the debounced state."""
    runs = []
    cur = bool(state[0])
    start = 0
    i = 1
    n = len(state)
    while i < n:
        if bool(state[i]) != cur:
            # candidate transition at i; confirm persistence
            j = i
            while j < n and bool(state[j]) != cur and j - i < DEBOUNCE:
                j += 1
            if j - i >= DEBOUNCE or j == n:
                runs.append((start, cur))
                start = i
                cur = bool(state[i])
                i = j
                continue
            i = j  # blip: skip the short opposite run
            continue
        i += 1
    runs.append((start, cur))
    return runs


def main() -> None:
    os.makedirs(OUT_DIR, exist_ok=True)
    tasks = pd.read_parquet(SNAP + "/meta/tasks.parquet")
    # tasks.parquet: index = instruction string, column task_index = id
    task_text = {int(r["task_index"]): str(idx) for idx, r in tasks.iterrows()}
    files = sorted(glob.glob(SNAP + "/data/chunk-000/*.parquet"))
    frames = pd.concat(
        [pd.read_parquet(f, columns=["episode_index", "frame_index", "task_index", "action"])
         for f in files],
        ignore_index=True,
    )
    frames = frames.sort_values(["episode_index", "frame_index"]).reset_index(drop=True)
    act = np.stack(frames["action"].to_numpy()).astype(np.float32)
    grip = act[:, 6]
    uniq = np.unique(np.round(grip, 3))
    print("gripper unique values (rounded):", uniq[:10], "... total", len(uniq))
    closed_is_positive = True  # determined below from episode starts
    first_vals = []
    for ep, grp in frames.groupby("episode_index"):
        first_vals.append(grp["action"].iloc[0][6])
    first_vals = np.array(first_vals)
    open_val = 1.0 if np.mean(first_vals > 0) > 0.5 else -1.0
    # episodes start OPEN; open_val is the value at frame 0 for most episodes
    closed_is_positive = open_val < 0
    print(f"frame-0 gripper: mean={first_vals.mean():.3f}; open_val={open_val:+.0f} "
          f"-> closed is {'positive' if closed_is_positive else 'negative'}")
    is_closed_all = grip > 0 if closed_is_positive else grip < 0

    ep_arr = frames["episode_index"].to_numpy()
    fr_arr = frames["frame_index"].to_numpy()
    tk_arr = frames["task_index"].to_numpy()

    # episode -> (row slice, task)
    ep_rows: dict[int, tuple[int, int, int]] = {}
    starts = np.flatnonzero(np.r_[True, ep_arr[1:] != ep_arr[:-1]])
    ends = np.r_[starts[1:], len(ep_arr)]
    for s, e in zip(starts, ends):
        ep_rows[int(ep_arr[s])] = (int(s), int(e), int(tk_arr[s]))
    all_eps = sorted(ep_rows)
    print("episodes:", len(all_eps), "frames:", len(frames))

    # replicate factory split: group by task (ascending ep order), hold out last ceil(0.1n)
    by_task: dict[int, list[int]] = {}
    for ep in all_eps:
        by_task.setdefault(ep_rows[ep][2], []).append(ep)
    train_eps, eval_eps = [], []
    for t, eps in sorted(by_task.items()):
        n_eval = math.ceil(len(eps) * EVAL_SPLIT)
        train_eps.extend(eps[: len(eps) - n_eval])
        eval_eps.extend(eps[len(eps) - n_eval:])
    train_set = set(train_eps)
    print(f"split: {len(train_eps)} train / {len(eval_eps)} eval episodes")

    phrases: list[str] = []
    phrase_id: dict[str, int] = {}

    def pid(p: str) -> int:
        if p not in phrase_id:
            phrase_id[p] = len(phrases)
            phrases.append(p)
        return phrase_id[p]

    seg_ep, seg_start, seg_end, seg_pid, seg_typ = [], [], [], [], []
    frame_key, frame_pid, frame_seg_end = [], [], []
    anch_ep, anch_fr, anch_tk, anch_end, anch_pid = [], [], [], [], []
    segs_per_ep = {}
    first_trans_closed = 0
    eps_with_trans = 0

    for ep in train_eps:
        s, e, tk = ep_rows[ep]
        state = is_closed_all[s:e]
        n = e - s
        runs = debounced_runs(state)
        # segments: seg j = [run_j.start, run_{j+1}.start] inclusive; last run merges into previous
        bounds = []  # (start, end_inclusive, end_state_closed or None)
        if len(runs) == 1:
            bounds.append((0, n - 1, None))
        else:
            for j in range(len(runs) - 1):
                st = runs[j][0]
                en = runs[j + 1][0]  # switching frame belongs to this segment
                if j == len(runs) - 2:
                    en = n - 1  # merge tail run into last segment
                bounds.append((st, en, runs[j + 1][1]))
            eps_with_trans += 1
            if runs[1][1]:
                first_trans_closed += 1
        subgoals = SUBGOALS[tk]
        g = 0
        ep_seg_ids = []
        for (st, en, end_closed) in bounds:
            if end_closed is None:
                ph = subgoals[min(g, len(subgoals) - 1)][0]
            elif end_closed:
                ph = subgoals[min(g, len(subgoals) - 1)][0]
            else:
                ph = subgoals[min(g, len(subgoals) - 1)][1]
                g += 1
            sid = len(seg_ep)
            ep_seg_ids.append(sid)
            seg_ep.append(ep)
            seg_start.append(st)
            seg_end.append(en)
            seg_pid.append(pid(ph))
            seg_typ.append(seg_type(ph))
            for f in range(st, en + 1):
                frame_key.append(ep * 100000 + f)
                frame_pid.append(seg_pid[-1])
                frame_seg_end.append(en)
                if hash_coin(ep, f, salt=7):  # comp3 anchor subsample 1/2
                    anch_ep.append(ep)
                    anch_fr.append(f)
                    anch_tk.append(tk)
                    anch_end.append(en)
                    anch_pid.append(seg_pid[-1])
        segs_per_ep[ep] = len(bounds)

    seg_len = np.array(seg_end) - np.array(seg_start) + 1
    from collections import Counter
    type_counts = Counter(seg_typ)
    spe = Counter(segs_per_ep.values())
    summary = {
        "train_episodes": len(train_eps),
        "eval_episodes": len(eval_eps),
        "total_segments": len(seg_ep),
        "segments_per_episode_hist": {str(k): v for k, v in sorted(spe.items())},
        "segment_length_frames": {
            "min": int(seg_len.min()), "p25": float(np.percentile(seg_len, 25)),
            "median": float(np.percentile(seg_len, 50)),
            "p75": float(np.percentile(seg_len, 75)), "max": int(seg_len.max()),
            "mean": float(seg_len.mean()),
        },
        "segments_by_type": dict(type_counts),
        "comp3_anchors_after_half_subsample": len(anch_ep),
        "episodes_with_gripper_transition": eps_with_trans,
        "first_transition_into_closed": first_trans_closed,
        "unique_phrases": len(phrases),
    }
    print(json.dumps(summary, indent=1))

    np.savez_compressed(
        os.path.join(OUT_DIR, "segment_map.npz"),
        seg_ep=np.array(seg_ep), seg_start=np.array(seg_start), seg_end=np.array(seg_end),
        seg_pid=np.array(seg_pid), phrases=np.array(phrases),
        frame_key=np.array(frame_key), frame_pid=np.array(frame_pid),
        frame_seg_end=np.array(frame_seg_end),
        anch_ep=np.array(anch_ep), anch_fr=np.array(anch_fr), anch_tk=np.array(anch_tk),
        anch_end=np.array(anch_end), anch_pid=np.array(anch_pid),
        train_eps=np.array(sorted(train_set)),
    )
    with open(os.path.join(OUT_DIR, "segment_map_summary.json"), "w") as f:
        json.dump(summary, f, indent=1)

    # spot-check: 10 random train episodes vs raw gripper trace (run-length)
    rng = np.random.default_rng(7)
    picks = rng.choice(train_eps, size=10, replace=False)
    lines = []
    seg_by_ep: dict[int, list[int]] = {}
    for sid, ep in enumerate(seg_ep):
        seg_by_ep.setdefault(ep, []).append(sid)
    for ep in sorted(int(p) for p in picks):
        s, e, tk = ep_rows[ep]
        raw = is_closed_all[s:e]
        rle = []
        cur, cnt = bool(raw[0]), 1
        for v in raw[1:]:
            if bool(v) == cur:
                cnt += 1
            else:
                rle.append(("C" if cur else "O") + str(cnt))
                cur, cnt = bool(v), 1
        rle.append(("C" if cur else "O") + str(cnt))
        lines.append(f"EP {ep} task {tk}: {task_text[tk]}")
        lines.append("  gripper RLE (O=open,C=closed): " + " ".join(rle))
        for sid in seg_by_ep[ep]:
            lines.append(
                f"  seg [{seg_start[sid]:4d}..{seg_end[sid]:4d}] {seg_typ[sid]:8s} "
                f"\"{phrases[seg_pid[sid]]}\""
            )
    with open(os.path.join(OUT_DIR, "segment_spotcheck.txt"), "w") as f:
        f.write("\n".join(lines) + "\n")
    print("spotcheck written;", len(picks), "episodes")
    print("parse table check — task 30:", SUBGOALS[30], "| task 12:", SUBGOALS[12])


if __name__ == "__main__":
    main()