Add mode2_v1 schema — 73 pre-sliced clean segments from 27 source episodes (104.7 min, bad intervals excluded by construction). New ReactSegmentDataset + demo. No bad_frames.json filtering needed at the dataloader; data is constructively clean. mode1_v1 stays for backward compatibility. See segments.json + new README section.
93065ec verified | """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}") | |