File size: 12,468 Bytes
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
"""React: short-horizon contact-rich window dataset.

A PyTorch `Dataset` that yields short multimodal windows sampled from the
React recordings, filtered to be contact-rich and free of known data-quality
issues. Intended for tactile-visual dynamics / world-model learning.

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,            # frames per window
    stride=1,                    # within-window frame stride (1 = consecutive)
    window_step=8,               # step between window start indices
    contact_metric="mixed",      # which tactile metric to threshold on
    tactile_threshold=0.4,
    min_contact_fraction=0.5,    # ≥ 50% of window frames must have contact
    which_sensors="any",         # "any" | "both" | "left" | "right"
    skip_bad_frames=True,
    respect_active_sensors=True, # mask out left modalities for right-only pilot
)
loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
```

Each sample is a dict of `(T, ...)` tensors plus metadata.
"""
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")


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

    Parameters
    ----------
    data_root : path
        Directory containing `<task>/<date>/episode_*.pt` files. Searched
        recursively.
    bad_frames_path : optional path
        `bad_frames.json` (the shipped skip-list). If None, no quality filter.
    tasks_json_path : optional path
        `tasks.json`. Used for `respect_active_sensors` mode.
    window_length : int
        Number of frames per sample.
    stride : int
        Frame stride within a window. `stride=1` → consecutive 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 as contact.
    min_contact_fraction : float in [0, 1]
        A window is kept only if at least this fraction of its frames satisfy
        the contact predicate.
    which_sensors : {"any", "both", "left", "right"}
        How left + right sensors combine when checking the predicate.
    tasks, dates : optional iterables of str
        Filter episodes by task name and/or date string.
    skip_bad_frames : bool
        If True, drop windows whose source-frame span overlaps any flagged
        interval in `bad_frames.json`.
    respect_active_sensors : bool
        If True (and `tasks.json` has per-date `active_sensors`), windows on
        right-only recordings (2026-03-23 pilot) auto-fallback to right-only
        contact predicate, and the returned sample carries an
        `active_sensors` field so dataloaders can mask the inactive
        modalities.
    """

    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 = "any",
        tasks: Iterable[str] | None = None,
        dates: Iterable[str] | None = None,
        skip_bad_frames: bool = True,
        respect_active_sensors: bool = True,
    ):
        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 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.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

        self.skip_bad_frames = bool(skip_bad_frames)

        # Discover episodes
        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] = []      # "<date>/<stem>" for bad_frames lookup
        self.episode_active: list[list[str]] = []
        self.windows: list[tuple[int, int]] = []   # (ep_idx, t_start)

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

        for pt in pt_files:
            rel = pt.relative_to(self.data_root)
            # rel.parts == (<task>, <date>, "episode_NNN.pt") OR (<date>, ...)
            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]

            # Per-frame contact predicate respecting which_sensors and active_sensors
            cL = mL > self.tactile_threshold
            cR = mR > self.tactile_threshold
            if "left" not in active:
                cL = np.zeros_like(cL)
            if "right" not in active:
                cR = np.zeros_like(cR)
            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
            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", [])):
                    bad_mask[s:e + 1] = True

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

            # Enumerate windows
            kept = 0
            for t_start in range(0, T - span + 1, self.window_step):
                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():
                    continue
                frac = contact_frame[frame_idx].mean()
                if frac < self.min_contact_fraction:
                    continue
                self.windows.append((ep_idx, t_start))
                kept += 1
            print(f"[ReactWindowDataset] {key}: T={T}, active={active}, "
                  f"kept {kept} windows")

        print(f"[ReactWindowDataset] total windows: {len(self.windows)} "
              f"(window_length={self.window_length}, stride={self.stride}, "
              f"window_step={self.window_step})")

    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],            # (T, 3, 128, 128) uint8
            "tactile_left":  ep["tactile_left"][frame_idx],
            "tactile_right": ep["tactile_right"][frame_idx],
            "sensor_left_pose":  ep["sensor_left_pose"][frame_idx],   # (T, 7) f32
            "sensor_right_pose": ep["sensor_right_pose"][frame_idx],
            "timestamps":    ep["timestamps"][frame_idx],      # (T,) f64
            "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],
        }
        # Metadata (not batched by default DataLoader because they're scalars/strings)
        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"])
    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,
    )
    print(f"len(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}")