"""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 `//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] = [] # "/" 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 == (, , "episode_NNN.pt") OR (, ...) 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}")