# React — usage examples Reference code for sampling clean training windows from this dataset. **Use these examples (or copy their patterns) to avoid sampling on top of known data-quality issues.** ## What's in here | File | Purpose | |---|---| | [`react_window_dataset.py`](react_window_dataset.py) | A PyTorch `Dataset` that yields short multimodal windows with all four quality filters applied at enumeration time. Drop-in usable. | | [`demo_react_window.py`](demo_react_window.py) | End-to-end usage example — builds the dataset, prints one sample's structure, renders a static grid of N random windows as a PNG. | ## What the dataloader filters out The published `.pt` files have already had **OT-uninitialized recording prefixes** trimmed (those bad spans were before the dataloader ever sees the data — see [`docs/caveats.md`](../docs/caveats.md)). On top of that, `ReactWindowDataset` applies four enumeration-time filters: | # | Filter | What it catches | |---|---|---| | 1 | `skip_bad_frames` | Windows overlapping any interval in `bad_frames.json` (`intensity_spikes`, `pose_teleports_{L,R}`, `ot_loss_{L,R}`). These are *broken* data: LED glitches, mocap solver flips, mid-episode OptiTrack track loss. | | 2 | `respect_active_sensors` | Ignores inactive sensors per `tasks.json:per_date_notes` when checking contact + motion predicates. | | 3 | `min_contact_fraction` | Drops windows where fewer than `min_contact_fraction` of frames have tactile contact (chosen sensor + metric + threshold). Forces samples to be contact-rich. | | 4 | **`require_motion`** | **Drops windows where the active sensors are essentially stationary** (operator paused mid-manipulation). The recorded data is healthy, but a near-zero-motion window contains no dynamics to learn. | Filter (4) is the one most people forget. Without it, you'll get the occasional "wait, the sensor isn't moving in this clip" sample even though everything else is clean. ## Minimal recipe ```python from examples.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, # (1) (2) — broken data + inactive-sensor handling skip_bad_frames = True, respect_active_sensors = True, # (3) — contact-richness contact_metric = "mixed", tactile_threshold = 0.4, min_contact_fraction = 0.5, which_sensors = "any", # (4) — motion content (recommended for dynamics learning) require_motion = True, min_motion_mps = 0.01, # 10 mm/s min_motion_fraction = 0.25, which_sensors_must_move = "all_active", ) loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2) ``` ## Recommended defaults by use case - **Dynamics / world-model learning**: all four filters on. The recipe above. - **UMI-style imitation / pose-as-action**: same recipe; filter (4) is critical here because stationary windows give you constant-action labels. - **Studying static tactile patterns** (e.g. classification of contact shapes): turn filter (4) OFF (`require_motion=False`) — you specifically want windows where the sensor is held still on an object. ## Loading a single `.pt` directly (without this dataloader) If you're rolling your own sampler, replicate the filter logic by hand: ```python import json, torch, numpy as np ep_key = "2026-05-11/episode_017" ep = torch.load(f"processed/mode1_v1/motherboard/{ep_key}.pt", weights_only=False) T = ep["view"].shape[0] bad = json.load(open("bad_frames.json"))["episodes"][ep_key] # Frame-level mask (True = drop) mask = np.zeros(T, dtype=bool) for s, e in (bad["intensity_spikes"] + bad["pose_teleports_L"] + bad["pose_teleports_R"] + bad["ot_loss_L"] + bad["ot_loss_R"]): mask[s:e + 1] = True # Per-frame motion mask (use this in addition to bad_frames) pose_L = ep["sensor_left_pose"].numpy() pose_R = ep["sensor_right_pose"].numpy() speed_L = np.linalg.norm(np.diff(pose_L[:, :3], axis=0), axis=1) * 30 # m/s speed_R = np.linalg.norm(np.diff(pose_R[:, :3], axis=0), axis=1) * 30 moving_L = np.concatenate([[speed_L[0]], speed_L]) >= 0.01 # 10 mm/s moving_R = np.concatenate([[speed_R[0]], speed_R]) >= 0.01 # Then when picking a window [t, t+L): def good(t, L): if mask[t:t + L].any(): return False return moving_L[t:t + L].mean() >= 0.25 and moving_R[t:t + L].mean() >= 0.25 ``` ## Coordinates note All frame indices in `bad_frames.json` and in the `.pt` files are in **trimmed** coordinates — the OT-uninitialized prefixes were cut from the published `.pt` files. The trim offset per file is recorded as `_contact_meta.trim_offset` inside the `.pt`. You don't need to apply it yourself: this loader and the metadata are already aligned. If you also need to read the original H5 archive (held in `MultimodalData/twm/data///`), remember to **add the trim offset back** before indexing into the H5 — the H5 still has the pre-trim timeline. ```python trim_offset = ep["_contact_meta"]["trim_offset"] h5_index = pt_index + trim_offset # only needed when reading raw H5 ``` ## Visualizing a single .pt or a whole task Use `examples/play_react_pt.py` to scrub through React data interactively (same key bindings as `python -m twm.visualize` for H5 archives). ```bash # Single .pt (mode1_v1 episode or one mode2_v1 segment) python examples/play_react_pt.py \ processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt # Whole task: all 27 episodes are discovered; same-source segments are # concatenated into one playback timeline. N / P jumps between episodes. python examples/play_react_pt.py processed/mode2_v1/motherboard # Headless: write one MP4 per episode into a directory python examples/play_react_pt.py processed/mode2_v1/motherboard \ --save_video_dir /tmp/react_mp4s ``` Controls: | Key | Action | |---|---| | `space` | pause / resume | | `left / a`, `right / d` | prev / next frame | | `1..6` | speed 1x / 2x / 5x / 10x / 25x / 50x | | `r` | reset GelSight diff reference to current frame | | **`n` / `p`** | **next / previous episode** | | `q` | quit | Panel layout (1280 x 480): - **Row 1**: cam0 view, tactile_L raw, tactile_L diff, tactile_R raw, tactile_R diff - **Row 2**: OT pose text (live x/y/z + quaternion), contact-intensity trail plot, controls cheatsheet - **Status bar at top**: episode index, frame index in the concatenated timeline, segment number, source-H5 frame range - **Red border for 1 frame** when crossing a segment boundary (visible cue that a bad interval was cut here). Vertical red marks in the trail plot show recent boundaries. The GelSight diff is computed against `_contact_meta.ref_p01_*` (the quietest frame of the episode), so it reads as the absolute contact on the gel rather than change since the start of the clip.