File size: 20,661 Bytes
cc62065
84e6423
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
 
 
 
 
 
 
 
cc62065
 
 
 
 
 
 
 
 
 
70ded71
cc62065
 
 
 
 
fc9b06b
3bb8031
cc62065
84e6423
 
 
 
cc62065
 
84e6423
 
 
 
 
 
 
 
 
 
 
 
 
 
cc62065
 
 
 
 
 
 
 
 
 
 
 
84e6423
 
 
cc62065
 
84e6423
 
 
cc62065
 
84e6423
cc62065
84e6423
cc62065
 
84e6423
cc62065
84e6423
cc62065
 
 
84e6423
 
 
cc62065
84e6423
 
 
cc62065
84e6423
cc62065
84e6423
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3bb8031
cc62065
 
 
 
 
 
 
84e6423
cc62065
 
 
 
84e6423
 
 
 
 
 
 
 
 
 
 
 
 
 
70ded71
84e6423
 
 
 
cc62065
fc9b06b
3bb8031
cc62065
 
84e6423
 
 
 
 
cc62065
 
84e6423
 
 
 
 
 
 
 
 
 
 
 
cc62065
 
 
 
 
 
84e6423
 
 
 
 
 
 
 
 
 
 
 
 
 
cc62065
84e6423
 
 
 
 
 
 
 
cc62065
84e6423
cc62065
 
 
84e6423
cc62065
 
 
 
 
84e6423
 
 
 
cc62065
84e6423
cc62065
84e6423
 
cc62065
 
84e6423
 
 
 
 
 
 
 
 
 
cc62065
84e6423
 
cc62065
 
84e6423
cc62065
 
 
 
84e6423
cc62065
84e6423
 
 
 
 
3ad2833
 
 
84e6423
 
cc62065
 
 
 
 
 
 
 
 
 
 
84e6423
 
 
 
 
 
 
 
cc62065
84e6423
 
cc62065
84e6423
cc62065
84e6423
cc62065
 
84e6423
cc62065
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
 
cc62065
84e6423
d78749e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84e6423
 
 
 
 
 
 
 
 
cc62065
84e6423
 
cc62065
84e6423
cc62065
84e6423
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc62065
fc9b06b
3bb8031
cc62065
 
84e6423
 
 
 
 
 
 
 
 
 
 
 
cc62065
 
 
 
84e6423
cc62065
84e6423
 
 
 
 
 
 
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
"""React: short-horizon contact-rich window dataset (PyTorch).

Yields short multimodal windows sampled from the React recordings, with all
known data-quality issues filtered out at window-enumeration time. Intended
for tactile-visual dynamics / world-model / UMI-style imitation learning.

What each filter catches
------------------------

1. `skip_bad_frames`  →  windows overlapping any flagged interval in
   `bad_frames.json` are dropped. Covers:
   - `intensity_spikes`         — single-frame GelSight LED glitches
   - `pose_teleports_{L,R}`     — translation-velocity > 5 m/s solver flips
   - `ot_loss_{L,R}`            — mid-episode OptiTrack track loss
                                  (pose held stale for ≥ 0.25 s while the
                                  cross-modal motion check shows the sensor
                                  was actually moving)

2. `respect_active_sensors`  →  per-date metadata in `tasks.json` tells us
   which GelSight rigid bodies were actually in use that day; the predicate
   below ignores inactive sensors when deciding "is this window useful?".

3. `min_contact_fraction`  →  windows where fewer than this fraction of
   frames have tactile contact (per the configured metric + threshold +
   `which_sensors`) are dropped. Forces samples to be contact-rich.

4. `require_motion`  →  windows where the sensor is sitting essentially
   still (operator paused mid-manipulation) are dropped. Specifically: an
   active sensor "passes" if at least `min_motion_fraction` of its frames
   have per-frame translation speed ≥ `min_motion_mps`. The
   `which_sensors_must_move` parameter says whether every active sensor
   must pass, or just one.

   This catches the failure mode that bad_frames.json *can't* — windows
   where OT is healthy and pose is changing every frame, but the change
   is sub-millimeter per frame so there's nothing to learn dynamics from.

Coordinates note
----------------
All frame indices in `bad_frames.json` and the .pt files are in TRIMMED
coordinates: the OT-uninitialized prefixes at the start of three episodes
have been cut from the published .pt files (see `_contact_meta.trim_offset`
inside each .pt). You don't need to do anything special — this loader and
the metadata are already aligned.

Usage
-----
```python
from react_window_dataset import ReactWindowDataset
from torch.utils.data import DataLoader

ds = ReactWindowDataset(
    data_root        = "processed/mode1_v1/motherboard",
    bad_frames_path  = "bad_frames.json",
    tasks_json_path  = "tasks.json",
    window_length    = 16,
    stride           = 1,
    window_step      = 8,
    # contact filter
    contact_metric        = "mixed",
    tactile_threshold     = 0.4,
    min_contact_fraction  = 0.5,
    which_sensors         = "both",
    # quality filters (recommended on)
    skip_bad_frames        = True,
    respect_active_sensors = True,
    # motion filter (recommended on for dynamics learning)
    require_motion              = True,
    min_motion_mps              = 0.01,    # 10 mm/s — below typical slow manipulation
    min_motion_fraction         = 0.25,
    which_sensors_must_move     = "all_active",
)
loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
```

Each sample is a dict of `(T, ...)` tensors plus per-window metadata
(`episode`, `episode_key`, `frame_start`, `frame_end`, `active_sensors`).
"""
from __future__ import annotations

import json
from pathlib import Path
from typing import Iterable

import numpy as np
import torch
from torch.utils.data import Dataset

CONTACT_METRICS = ("intensity", "area", "mixed")


def _per_frame_speed_mps(pose7: np.ndarray, fps: float = 30.0) -> np.ndarray:
    """Per-frame translation speed in m/s. Output shape == input frame count;
    pad the first frame's speed with the second frame's (forward difference)."""
    if pose7.shape[0] < 2:
        return np.zeros(pose7.shape[0], dtype=np.float64)
    d = np.linalg.norm(np.diff(pose7[:, :3], axis=0), axis=1) * fps
    out = np.empty(pose7.shape[0], dtype=np.float64)
    out[0] = d[0]
    out[1:] = d
    return out


class ReactWindowDataset(Dataset):
    """Per-window dataset over the React recordings.

    See the module docstring for what each filter catches.

    Parameters
    ----------
    data_root : path
        Directory containing `<task>/<date>/episode_*.pt` files (searched
        recursively).
    bad_frames_path : optional path
        Path to `bad_frames.json`. If None, no quality filter is applied.
    tasks_json_path : optional path
        Path to `tasks.json`. Used for the `respect_active_sensors` mode.

    window_length : int
        Frames per sample (default 16).
    stride : int
        Frame stride *within* a window. `stride=1` → consecutive source
        frames; `stride=2` → every other source frame; etc. Span of a
        window in source-frame indices = `(window_length - 1) * stride + 1`.
    window_step : int, default `window_length // 2`
        Step between window start indices within an episode. Controls
        overlap between adjacent windows.

    contact_metric : {"intensity", "area", "mixed"}
        Which per-frame tactile metric to threshold on.
    tactile_threshold : float
        Minimum value of the chosen metric to count a frame as in-contact.
    min_contact_fraction : float in [0, 1]
        Window must have ≥ this fraction of in-contact frames.
    which_sensors : {"any", "both", "left", "right"}
        How left + right sensors combine when checking the contact
        predicate. (Inactive sensors per `tasks.json` are always excluded.)

    skip_bad_frames : bool, default True
        Drop windows whose source-frame span overlaps any interval in
        `intensity_spikes / pose_teleports_{L,R} / ot_loss_{L,R}`.
    respect_active_sensors : bool, default True
        If True (and `tasks.json` has per-date `active_sensors`), inactive
        sensors are ignored by both the contact filter and the motion
        filter, and the returned sample carries an `active_sensors` field
        so downstream code can mask out the inactive modalities.

    require_motion : bool, default False
        Toggle the motion filter (off for back-compat; recommended on for
        dynamics learning).
    min_motion_mps : float, default 0.03
        Per-frame translation speed (in m/s) above which a frame counts as
        "moving" for a given sensor.
    min_motion_fraction : float in [0, 1], default 0.25
        An active sensor passes the motion filter if ≥ this fraction of
        the window's frames have speed ≥ `min_motion_mps`.
    which_sensors_must_move : {"any", "all_active"}, default "all_active"
        Whether every active sensor must pass the motion filter (strict;
        rejects the "left held still while right moves" pattern), or just
        one. "all_active" is what you typically want for dynamics learning.

    tasks, dates : optional iterables of str
        Restrict to specific task names / date strings.

    fps : float, default 30
        Frame rate used to convert pose deltas to m/s.
    """

    def __init__(
        self,
        data_root: str | Path,
        bad_frames_path: str | Path | None = None,
        tasks_json_path: str | Path | None = None,
        *,
        window_length: int = 16,
        stride: int = 1,
        window_step: int | None = None,
        contact_metric: str = "mixed",
        tactile_threshold: float = 0.4,
        min_contact_fraction: float = 0.5,
        which_sensors: str = "both",   # bimanual default; pass "any" to allow single-hand contact
        tasks: Iterable[str] | None = None,
        dates: Iterable[str] | None = None,
        skip_bad_frames: bool = True,
        respect_active_sensors: bool = True,
        require_motion: bool = False,
        min_motion_mps: float = 0.01,
        min_motion_fraction: float = 0.25,
        which_sensors_must_move: str = "all_active",
        fps: float = 30.0,
    ):
        if contact_metric not in CONTACT_METRICS:
            raise ValueError(f"contact_metric must be one of {CONTACT_METRICS}")
        if which_sensors not in ("any", "both", "left", "right"):
            raise ValueError("which_sensors must be 'any' | 'both' | 'left' | 'right'")
        if which_sensors_must_move not in ("any", "all_active"):
            raise ValueError("which_sensors_must_move must be 'any' | 'all_active'")
        if window_length < 1 or stride < 1:
            raise ValueError("window_length and stride must be ≥ 1")

        self.data_root = Path(data_root)
        self.window_length = int(window_length)
        self.stride = int(stride)
        self.window_step = int(window_step) if window_step is not None else max(1, window_length // 2)
        self.contact_metric = contact_metric
        self.tactile_threshold = float(tactile_threshold)
        self.min_contact_fraction = float(min_contact_fraction)
        self.which_sensors = which_sensors
        self.respect_active_sensors = bool(respect_active_sensors)
        self.skip_bad_frames = bool(skip_bad_frames)
        self.require_motion = bool(require_motion)
        self.min_motion_mps = float(min_motion_mps)
        self.min_motion_fraction = float(min_motion_fraction)
        self.which_sensors_must_move = which_sensors_must_move
        self.fps = float(fps)

        self.bad = {}
        if bad_frames_path is not None and Path(bad_frames_path).is_file():
            self.bad = json.loads(Path(bad_frames_path).read_text()).get("episodes", {})
        elif skip_bad_frames and bad_frames_path is not None:
            print(f"[ReactWindowDataset] WARNING: bad_frames_path={bad_frames_path} not found; not filtering.")

        self.per_date = {}
        if tasks_json_path is not None and Path(tasks_json_path).is_file():
            tj = json.loads(Path(tasks_json_path).read_text())
            for tk, td in tj.get("tasks", {}).items():
                for d, info in td.get("per_date_notes", {}).items():
                    self.per_date[d] = info

        # ── Episode discovery ────────────────────────────────────────────
        pt_files = sorted(self.data_root.rglob("episode_*.pt"))
        if not pt_files:
            raise RuntimeError(f"No episode_*.pt under {self.data_root}")
        tasks = set(tasks) if tasks is not None else None
        dates = set(dates) if dates is not None else None

        self.episodes: list[dict] = []
        self.episode_paths: list[Path] = []
        self.episode_keys: list[str] = []
        self.episode_active: list[list[str]] = []
        self.windows: list[tuple[int, int]] = []

        span = (self.window_length - 1) * self.stride + 1

        # Counters for reporting how many windows each filter rejects
        n_total_candidates = 0
        n_drop_bad = 0
        n_drop_contact = 0
        n_drop_motion = 0

        for pt in pt_files:
            rel = pt.relative_to(self.data_root)
            if len(rel.parts) == 3:
                task, date, _ = rel.parts; key = f"{date}/{pt.stem}"
            elif len(rel.parts) == 2:
                task, date = None, rel.parts[0]; key = f"{date}/{pt.stem}"
            else:
                task, date, key = None, None, pt.stem
            if tasks is not None and task not in tasks: continue
            if dates is not None and date not in dates: continue

            d = torch.load(pt, weights_only=False, map_location="cpu")
            active = ["left", "right"]
            if self.respect_active_sensors and date in self.per_date:
                active = list(self.per_date[date].get("active_sensors", active))

            mL = d[f"tactile_left_{self.contact_metric}"].numpy()
            mR = d[f"tactile_right_{self.contact_metric}"].numpy()
            T = mL.shape[0]

            # Contact predicate (respecting active sensors)
            cL = mL > self.tactile_threshold
            cR = mR > self.tactile_threshold
            if "left"  not in active: cL[:] = False
            if "right" not in active: cR[:] = False
            req = self.which_sensors
            if   req == "any":   contact_frame = cL | cR
            elif req == "both":  contact_frame = cL & cR
            elif req == "left":  contact_frame = cL
            else:                contact_frame = cR

            # Bad-frame mask (intensity, pose_teleport, ot_loss)
            bad_mask = np.zeros(T, dtype=bool)
            if self.skip_bad_frames and key in self.bad:
                bf = self.bad[key]
                for s, e in (bf.get("intensity_spikes", [])
                             + bf.get("pose_teleports_L", [])
                             + bf.get("pose_teleports_R", [])
                             + bf.get("ot_loss_L", [])
                             + bf.get("ot_loss_R", [])):
                    bad_mask[s:e + 1] = True

            # Per-frame motion predicate per sensor
            if self.require_motion:
                pose_L = d["sensor_left_pose"].numpy()
                pose_R = d["sensor_right_pose"].numpy()
                speed_L = _per_frame_speed_mps(pose_L, self.fps)
                speed_R = _per_frame_speed_mps(pose_R, self.fps)
                moving_L = speed_L >= self.min_motion_mps
                moving_R = speed_R >= self.min_motion_mps
            else:
                moving_L = moving_R = None

            ep_idx = len(self.episodes)
            self.episodes.append(d)
            self.episode_paths.append(pt)
            self.episode_keys.append(key)
            self.episode_active.append(active)

            kept = 0
            for t_start in range(0, T - span + 1, self.window_step):
                n_total_candidates += 1
                t_end = t_start + span - 1
                frame_idx = np.arange(t_start, t_start + span, self.stride)

                if bad_mask[t_start:t_end + 1].any():
                    n_drop_bad += 1
                    continue
                if contact_frame[frame_idx].mean() < self.min_contact_fraction:
                    n_drop_contact += 1
                    continue
                if self.require_motion:
                    passed = []
                    for side, mov in [("left", moving_L), ("right", moving_R)]:
                        if side not in active:
                            continue
                        passed.append(mov[frame_idx].mean() >= self.min_motion_fraction)
                    if self.which_sensors_must_move == "all_active":
                        ok = bool(passed) and all(passed)
                    else:                       # "any"
                        ok = any(passed)
                    if not ok:
                        n_drop_motion += 1
                        continue

                self.windows.append((ep_idx, t_start))
                kept += 1
            print(f"[ReactWindowDataset] {key}: T={T}, active={active}, kept {kept} windows")

        # Persist build stats on the instance so callers can inspect / log them
        self.stats = {
            "n_episodes":           len(self.episodes),
            "n_candidates":         n_total_candidates,
            "n_dropped_bad_frames": n_drop_bad,
            "n_dropped_contact":    n_drop_contact,
            "n_dropped_motion":     n_drop_motion,
            "n_contact_rich_windows": len(self.windows),
            "window_length":        self.window_length,
            "stride":               self.stride,
            "window_step":          self.window_step,
            "min_contact_fraction": self.min_contact_fraction,
            "tactile_threshold":    self.tactile_threshold,
            "contact_metric":       self.contact_metric,
            "which_sensors":        self.which_sensors,
            "skip_bad_frames":      self.skip_bad_frames,
            "require_motion":       self.require_motion,
            "min_motion_mps":       self.min_motion_mps,
            "min_motion_fraction":  self.min_motion_fraction,
            "which_sensors_must_move": self.which_sensors_must_move,
        }

        # Headline summary — emphasises the contact-rich count, which is the
        # number you'd quote in a paper or a model training log.
        pct = 100.0 * len(self.windows) / max(1, n_total_candidates)
        print()
        print(f"[ReactWindowDataset] =================================")
        print(f"[ReactWindowDataset]   Contact-rich windows sampled: {len(self.windows):,}")
        print(f"[ReactWindowDataset]   ({pct:.1f}% of {n_total_candidates:,} sliding-window candidates)")
        print(f"[ReactWindowDataset] =================================")
        print(f"[ReactWindowDataset] Window spec: length={self.window_length}, stride={self.stride}, "
              f"step={self.window_step}  (≈{self.window_length / 30:.2f}s @ 30 fps)")
        print(f"[ReactWindowDataset] Rejected by filter:")
        print(f"[ReactWindowDataset]   bad_frames (intensity_spikes, pose_teleports, ot_loss):  {n_drop_bad:,}")
        print(f"[ReactWindowDataset]   contact    (< {self.min_contact_fraction:.0%} of frames in tactile contact):  {n_drop_contact:,}")
        print(f"[ReactWindowDataset]   motion     ({'enabled' if self.require_motion else 'disabled'}):  {n_drop_motion:,}")

    def __len__(self) -> int:
        return len(self.windows)

    def __getitem__(self, idx: int) -> dict:
        ep_idx, t_start = self.windows[idx]
        ep = self.episodes[ep_idx]
        frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride)
        sample = {
            "view":          ep["view"][frame_idx],
            "tactile_left":  ep["tactile_left"][frame_idx],
            "tactile_right": ep["tactile_right"][frame_idx],
            "sensor_left_pose":  ep["sensor_left_pose"][frame_idx],
            "sensor_right_pose": ep["sensor_right_pose"][frame_idx],
            "timestamps":    ep["timestamps"][frame_idx],
            "tactile_left_intensity":  ep["tactile_left_intensity"][frame_idx],
            "tactile_right_intensity": ep["tactile_right_intensity"][frame_idx],
            "tactile_left_mixed":   ep["tactile_left_mixed"][frame_idx],
            "tactile_right_mixed":  ep["tactile_right_mixed"][frame_idx],
        }
        sample["episode"] = str(self.episode_paths[ep_idx])
        sample["episode_key"] = self.episode_keys[ep_idx]
        sample["frame_start"] = int(t_start)
        sample["frame_end"]   = int(frame_idx[-1].item())
        sample["active_sensors"] = list(self.episode_active[ep_idx])
        return sample


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--data_root", required=True)
    ap.add_argument("--bad_frames", default=None)
    ap.add_argument("--tasks_json", default=None)
    ap.add_argument("--window_length", type=int, default=16)
    ap.add_argument("--stride", type=int, default=1)
    ap.add_argument("--window_step", type=int, default=None)
    ap.add_argument("--tactile_threshold", type=float, default=0.4)
    ap.add_argument("--min_contact_fraction", type=float, default=0.5)
    ap.add_argument("--contact_metric", default="mixed", choices=CONTACT_METRICS)
    ap.add_argument("--which_sensors", default="any", choices=["any", "both", "left", "right"])
    ap.add_argument("--require_motion", action="store_true")
    ap.add_argument("--min_motion_mps", type=float, default=0.01)
    ap.add_argument("--min_motion_fraction", type=float, default=0.25)
    ap.add_argument("--which_sensors_must_move", default="all_active",
                    choices=["any", "all_active"])
    args = ap.parse_args()
    ds = ReactWindowDataset(
        data_root=args.data_root,
        bad_frames_path=args.bad_frames,
        tasks_json_path=args.tasks_json,
        window_length=args.window_length,
        stride=args.stride,
        window_step=args.window_step,
        contact_metric=args.contact_metric,
        tactile_threshold=args.tactile_threshold,
        min_contact_fraction=args.min_contact_fraction,
        which_sensors=args.which_sensors,
        require_motion=args.require_motion,
        min_motion_mps=args.min_motion_mps,
        min_motion_fraction=args.min_motion_fraction,
        which_sensors_must_move=args.which_sensors_must_move,
    )
    print(f"\nlen(ds) = {len(ds)}")
    if len(ds):
        sample = ds[0]
        for k, v in sample.items():
            if isinstance(v, torch.Tensor):
                print(f"  {k:30s} {tuple(v.shape)}  {v.dtype}")
            else:
                print(f"  {k:30s} {v!r}")