File size: 16,994 Bytes
93065ec
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""React: short-horizon contact-rich window dataset over pre-sliced segments.

This is the `mode2_v1/` companion to `react_window_dataset.py`. The
difference is purely architectural:

- `ReactWindowDataset` operates on `processed/mode1_v1/<task>/<date>/episode_*.pt`,
  which include bad intervals (LED flicker, pose teleports, OT track loss),
  and uses `bad_frames.json` to skip windows that overlap a flagged span.

- `ReactSegmentDataset` (this file) operates on
  `processed/mode2_v1/<task>/<date>/episode_*.segment_*.pt`, where every
  `.pt` is already a contiguous clean span. No `bad_frames.json` lookup is
  needed; the data is *constructively* clean.

Filters that remain (these are about what kind of window you want, not
whether the data is good):

  1. `respect_active_sensors`  — ignore inactive sensors per `tasks.json`
  2. `min_contact_fraction`    — drop windows below the contact threshold
  3. `require_motion`          — drop "operator paused" windows

The per-segment `_contact_meta.source_h5_frame_range` lets you map any
window back to its position in the original H5 recording, e.g. for
inspection in `twm.visualize` or for cross-referencing with the original
H5 archive.

Usage
-----
```python
from react_segment_dataset import ReactSegmentDataset
from torch.utils.data import DataLoader

ds = ReactSegmentDataset(
    segments_root  = "processed/mode2_v1/motherboard",
    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",
    # motion filter (recommended for dynamics learning)
    require_motion              = True,
    min_motion_mps              = 0.01,
    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 the same dict as `ReactWindowDataset`, plus the segment
provenance (`source_episode`, `source_segment_idx`, `source_h5_frame_range`).
"""
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:
    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 ReactSegmentDataset(Dataset):
    """Per-window dataset over the pre-sliced React segments.

    Parameters
    ----------
    segments_root : path
        Directory containing `<task>/<date>/episode_*.segment_*.pt`
        (searched recursively). e.g. `processed/mode2_v1/motherboard`.
    tasks_json_path : optional path
        Path to `tasks.json`. Used for the `respect_active_sensors` mode.

    window_length, stride, window_step : window enumeration
    contact_metric, tactile_threshold, min_contact_fraction, which_sensors :
        contact filter parameters
    respect_active_sensors : bool, default True
    require_motion, min_motion_mps, min_motion_fraction,
    which_sensors_must_move : motion filter parameters

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

    fps : float, default 30
    """

    def __init__(
        self,
        segments_root: str | Path,
        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",
        tasks: Iterable[str] | None = None,
        dates: Iterable[str] | None = None,
        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.segments_root = Path(segments_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.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)

        # Per-date active-sensor info
        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

        # Discover segments
        pt_files = sorted(self.segments_root.rglob("episode_*.segment_*.pt"))
        if not pt_files:
            raise RuntimeError(f"No segment .pt files under {self.segments_root}")
        tasks_set = set(tasks) if tasks is not None else None
        dates_set = set(dates) if dates is not None else None

        self.segments: list[dict] = []          # cached .pt dicts
        self.segment_paths: list[Path] = []
        self.segment_meta: list[dict] = []      # source_episode, segment_idx, etc.
        self.segment_active: list[list[str]] = []
        self.windows: list[tuple[int, int]] = []   # (seg_idx, t_start)

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

        n_total_candidates = 0
        n_drop_contact = 0
        n_drop_motion = 0

        for pt in pt_files:
            rel = pt.relative_to(self.segments_root)
            # rel.parts == (<task>, <date>, "episode_NNN.segment_MM.pt") OR (<date>, ...)
            if len(rel.parts) == 3:
                task, date, _ = rel.parts
            elif len(rel.parts) == 2:
                task, date = None, rel.parts[0]
            else:
                task, date = None, None
            if tasks_set is not None and task not in tasks_set:
                continue
            if dates_set is not None and date not in dates_set:
                continue

            d = torch.load(pt, weights_only=False, map_location="cpu")
            meta = d.get("_contact_meta", {})
            src_ep = meta.get("source_episode") or rel.stem.split(".")[0]
            seg_idx = int(meta.get("source_segment_idx", 0))
            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]
            if T < span:
                continue   # segment too short to host any window

            # Contact predicate
            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

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

            seg_id = len(self.segments)
            self.segments.append(d)
            self.segment_paths.append(pt)
            self.segment_meta.append({
                "source_episode":          src_ep,
                "source_segment_idx":      seg_idx,
                "source_h5_frame_range":   meta.get("source_h5_frame_range"),
                "source_pt_frame_range":   meta.get("source_pt_frame_range"),
            })
            self.segment_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 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:
                        ok = any(passed)
                    if not ok:
                        n_drop_motion += 1
                        continue
                self.windows.append((seg_id, t_start))
                kept += 1
            # Compact per-segment print so noisy episodes don't drown the summary
            if kept > 0 or T >= span:
                print(f"[ReactSegmentDataset] {src_ep}/seg{seg_idx:02d}  "
                      f"T={T:>5d}  kept={kept:>3d} windows")

        self.stats = {
            "n_source_episodes":      len({m["source_episode"] for m in self.segment_meta}),
            "n_segments_loaded":      len(self.segments),
            "n_candidates":           n_total_candidates,
            "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,
            "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,
        }
        pct = 100.0 * len(self.windows) / max(1, n_total_candidates)
        print()
        print(f"[ReactSegmentDataset] =================================")
        print(f"[ReactSegmentDataset]   Contact-rich windows sampled: {len(self.windows):,}")
        print(f"[ReactSegmentDataset]   ({pct:.1f}% of {n_total_candidates:,} sliding-window candidates)")
        print(f"[ReactSegmentDataset] =================================")
        print(f"[ReactSegmentDataset] From {self.stats['n_segments_loaded']} segments across "
              f"{self.stats['n_source_episodes']} source episodes.")
        print(f"[ReactSegmentDataset] Window spec: length={self.window_length}, "
              f"stride={self.stride}, step={self.window_step}  "
              f"(≈{self.window_length / self.fps:.2f}s @ {self.fps:.0f} fps)")
        print(f"[ReactSegmentDataset] Rejected by filter:")
        print(f"[ReactSegmentDataset]   contact (< {self.min_contact_fraction:.0%} of frames in tactile contact):  {n_drop_contact:,}")
        print(f"[ReactSegmentDataset]   motion  ({'enabled' if self.require_motion else 'disabled'}):  {n_drop_motion:,}")
        print(f"[ReactSegmentDataset] (No bad_frames filter — segments are already clean by construction.)")

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

    def __getitem__(self, idx: int) -> dict:
        seg_id, t_start = self.windows[idx]
        seg = self.segments[seg_id]
        meta = self.segment_meta[seg_id]
        frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride)
        sample = {
            "view":          seg["view"][frame_idx],
            "tactile_left":  seg["tactile_left"][frame_idx],
            "tactile_right": seg["tactile_right"][frame_idx],
            "sensor_left_pose":  seg["sensor_left_pose"][frame_idx],
            "sensor_right_pose": seg["sensor_right_pose"][frame_idx],
            "timestamps":    seg["timestamps"][frame_idx],
            "tactile_left_intensity":  seg["tactile_left_intensity"][frame_idx],
            "tactile_right_intensity": seg["tactile_right_intensity"][frame_idx],
            "tactile_left_mixed":   seg["tactile_left_mixed"][frame_idx],
            "tactile_right_mixed":  seg["tactile_right_mixed"][frame_idx],
        }
        sample["segment_path"]         = str(self.segment_paths[seg_id])
        sample["source_episode"]       = meta["source_episode"]
        sample["source_segment_idx"]   = int(meta["source_segment_idx"])
        sample["source_h5_frame_range"]= meta["source_h5_frame_range"]
        sample["frame_start"]          = int(t_start)
        sample["frame_end"]            = int(frame_idx[-1].item())
        sample["active_sensors"]       = list(self.segment_active[seg_id])
        # H5 frame index of the first frame in this window (useful for cross-ref)
        h5_range = meta["source_h5_frame_range"]
        if h5_range is not None:
            sample["h5_frame_start"] = int(h5_range[0]) + int(t_start)
            sample["h5_frame_end"]   = int(h5_range[0]) + int(frame_idx[-1].item())
        return sample


if __name__ == "__main__":
    import argparse
    ap = argparse.ArgumentParser()
    ap.add_argument("--segments_root", required=True,
                    help="processed/mode2_v1/motherboard (relative to dataset root)")
    ap.add_argument("--tasks_json", default="tasks.json")
    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="both", 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 = ReactSegmentDataset(
        segments_root=args.segments_root,
        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}")