yxma commited on
Commit
cc62065
·
verified ·
1 Parent(s): 7684a18

examples/: upgraded ReactWindowDataset (adds motion filter to catch operator-paused windows the bad_frames check cant); canonical self-contained demo_react_window.py (no twm dependency); new examples/README.md with four-filter explanation and recipes per use case

Browse files
examples/README.md ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # React — usage examples
2
+
3
+ Reference code for sampling clean training windows from this dataset. **Use
4
+ these examples (or copy their patterns) to avoid sampling on top of known
5
+ data-quality issues.**
6
+
7
+ ## What's in here
8
+
9
+ | File | Purpose |
10
+ |---|---|
11
+ | [`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. |
12
+ | [`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. |
13
+
14
+ ## What the dataloader filters out
15
+
16
+ The published `.pt` files have already had **OT-uninitialized recording
17
+ prefixes** trimmed (those bad spans were before the dataloader ever sees
18
+ the data — see [`docs/caveats.md`](../docs/caveats.md)). On top of that,
19
+ `ReactWindowDataset` applies four enumeration-time filters:
20
+
21
+ | # | Filter | What it catches |
22
+ |---|---|---|
23
+ | 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. |
24
+ | 2 | `respect_active_sensors` | Ignores inactive sensors per `tasks.json:per_date_notes` when checking contact + motion predicates. |
25
+ | 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. |
26
+ | 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. |
27
+
28
+ Filter (4) is the one most people forget. Without it, you'll get the
29
+ occasional "wait, the sensor isn't moving in this clip" sample even
30
+ though everything else is clean.
31
+
32
+ ## Minimal recipe
33
+
34
+ ```python
35
+ from examples.react_window_dataset import ReactWindowDataset
36
+ from torch.utils.data import DataLoader
37
+
38
+ ds = ReactWindowDataset(
39
+ data_root = "processed/mode1_v1/motherboard",
40
+ bad_frames_path = "bad_frames.json",
41
+ tasks_json_path = "tasks.json",
42
+ window_length = 16,
43
+ # (1) (2) — broken data + inactive-sensor handling
44
+ skip_bad_frames = True,
45
+ respect_active_sensors = True,
46
+ # (3) — contact-richness
47
+ contact_metric = "mixed",
48
+ tactile_threshold = 0.4,
49
+ min_contact_fraction = 0.5,
50
+ which_sensors = "any",
51
+ # (4) — motion content (recommended for dynamics learning)
52
+ require_motion = True,
53
+ min_motion_mps = 0.03, # 30 mm/s
54
+ min_motion_fraction = 0.5,
55
+ which_sensors_must_move = "all_active",
56
+ )
57
+ loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
58
+ ```
59
+
60
+ ## Recommended defaults by use case
61
+
62
+ - **Dynamics / world-model learning**: all four filters on. The recipe above.
63
+ - **UMI-style imitation / pose-as-action**: same recipe; filter (4) is
64
+ critical here because stationary windows give you constant-action labels.
65
+ - **Studying static tactile patterns** (e.g. classification of contact
66
+ shapes): turn filter (4) OFF (`require_motion=False`) — you specifically
67
+ want windows where the sensor is held still on an object.
68
+
69
+ ## Loading a single `.pt` directly (without this dataloader)
70
+
71
+ If you're rolling your own sampler, replicate the filter logic by hand:
72
+
73
+ ```python
74
+ import json, torch, numpy as np
75
+
76
+ ep_key = "2026-05-11/episode_017"
77
+ ep = torch.load(f"processed/mode1_v1/motherboard/{ep_key}.pt", weights_only=False)
78
+ T = ep["view"].shape[0]
79
+ bad = json.load(open("bad_frames.json"))["episodes"][ep_key]
80
+
81
+ # Frame-level mask (True = drop)
82
+ mask = np.zeros(T, dtype=bool)
83
+ for s, e in (bad["intensity_spikes"]
84
+ + bad["pose_teleports_L"] + bad["pose_teleports_R"]
85
+ + bad["ot_loss_L"] + bad["ot_loss_R"]):
86
+ mask[s:e + 1] = True
87
+
88
+ # Per-frame motion mask (use this in addition to bad_frames)
89
+ pose_L = ep["sensor_left_pose"].numpy()
90
+ pose_R = ep["sensor_right_pose"].numpy()
91
+ speed_L = np.linalg.norm(np.diff(pose_L[:, :3], axis=0), axis=1) * 30 # m/s
92
+ speed_R = np.linalg.norm(np.diff(pose_R[:, :3], axis=0), axis=1) * 30
93
+ moving_L = np.concatenate([[speed_L[0]], speed_L]) >= 0.03 # 30 mm/s
94
+ moving_R = np.concatenate([[speed_R[0]], speed_R]) >= 0.03
95
+
96
+ # Then when picking a window [t, t+L):
97
+ def good(t, L):
98
+ if mask[t:t + L].any():
99
+ return False
100
+ return moving_L[t:t + L].mean() >= 0.5 and moving_R[t:t + L].mean() >= 0.5
101
+ ```
102
+
103
+ ## Coordinates note
104
+
105
+ All frame indices in `bad_frames.json` and in the `.pt` files are in
106
+ **trimmed** coordinates — the OT-uninitialized prefixes were cut from
107
+ the published `.pt` files. The trim offset per file is recorded as
108
+ `_contact_meta.trim_offset` inside the `.pt`. You don't need to apply
109
+ it yourself: this loader and the metadata are already aligned.
110
+
111
+ If you also need to read the original H5 archive (held in
112
+ `MultimodalData/twm/data/<task>/<date>/`), remember to **add the trim
113
+ offset back** before indexing into the H5 — the H5 still has the
114
+ pre-trim timeline.
115
+
116
+ ```python
117
+ trim_offset = ep["_contact_meta"]["trim_offset"]
118
+ h5_index = pt_index + trim_offset # only needed when reading raw H5
119
+ ```
examples/demo_react_window.py CHANGED
@@ -1,128 +1,56 @@
1
- """Demonstrate ReactWindowDataset:
2
- - build the dataset with sensible defaults
3
- - sample N random windows
4
- - render static grid PNG (N rows × 8 cols, each cell a [view | tac_L | tac_R] composite)
5
- - render one window as a GIF with sensor-frame axes projected on `view`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  """
7
- import json
8
  import sys
9
  from pathlib import Path
10
 
11
  import cv2
12
  import numpy as np
13
  import torch
14
- from PIL import Image, ImageDraw, ImageFont
15
- from scipy.spatial.transform import Rotation
16
 
17
- sys.path.insert(0, "/tmp")
 
18
  from react_window_dataset import ReactWindowDataset
19
 
20
- OUT = Path("/media/yxma/Disk1/twm/figures/dataloader_examples")
21
- OUT.mkdir(parents=True, exist_ok=True)
22
 
23
- DATA_ROOT = Path("/media/yxma/Disk1/twm/processed/mode1_v1/motherboard")
24
- BAD_FRAMES = Path("/media/yxma/Disk1/twm/figures/dataset_figures/bad_frames.json")
25
- TASKS_JSON = Path("/tmp/tasks_local.json") # written below from HF
26
-
27
- # `view` in the .pt = realsense/cam0/color, center-cropped 640→480 then resized → 128
28
- # cam0 serial = 143322063538 → T_mocap_to_cam_right.json
29
- CALIB_DIR = Path("/home/yxma/MultimodalData/twm/calibration/result")
30
- CAM_CALIB_FOR_VIEW = CALIB_DIR / "T_mocap_to_cam_right.json"
31
- GEL_LEFT_CALIB = CALIB_DIR / "T_gel_to_rigid_left.json"
32
- GEL_RIGHT_CALIB = CALIB_DIR / "T_gel_to_rigid_right.json"
33
-
34
- AX_COLORS_RGB = [(0, 0, 255), (0, 255, 0), (255, 128, 0)] # X red, Y green, Z blue-ish
35
- AX_LABELS = ["X", "Y", "Z"]
36
- GEL_DOT_COLOR = {"L": (0, 255, 120), "R": (0, 180, 255)}
37
-
38
-
39
- def load_calib():
40
- cam = json.loads(CAM_CALIB_FOR_VIEW.read_text())
41
- return {
42
- "T_mocap_to_cam": np.array(cam["T_mocap_to_cam"], np.float64),
43
- "intrinsics": cam["intrinsics"],
44
- "gel_left": np.array(json.loads(GEL_LEFT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64),
45
- "gel_right": np.array(json.loads(GEL_RIGHT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64),
46
- }
47
-
48
-
49
- def pose_to_T(pose_7):
50
- """7-vec (x,y,z, qx,qy,qz,qw) in meters → 4×4 in mm."""
51
- pos_mm = np.array(pose_7[:3], np.float64) * 1000.0
52
- q = np.array(pose_7[3:], np.float64)
53
- q /= np.linalg.norm(q)
54
- T = np.eye(4)
55
- T[:3, :3] = Rotation.from_quat(q).as_matrix()
56
- T[:3, 3] = pos_mm
57
- return T
58
-
59
-
60
- def project_to_view(P_world_mm, calib, *, view_size=128, orig_w=640, orig_h=480):
61
- """Project a single mocap-frame point (mm) into 128×128 view coords.
62
-
63
- The .pt `view` was made by center-cropping cam0 from 640×480 → 480×480 and
64
- then bilinear-resizing to 128×128. We replicate that here.
65
- """
66
- T_m2c = calib["T_mocap_to_cam"]
67
- I = calib["intrinsics"]
68
- P = (T_m2c @ np.append(P_world_mm, 1.0))[:3]
69
- if P[2] <= 0:
70
- return None
71
- u640 = I["fx"] * P[0] / P[2] + I["ppx"]
72
- v480 = I["fy"] * P[1] / P[2] + I["ppy"]
73
- crop_left = (orig_w - orig_h) / 2.0 # 80
74
- u_in_crop = u640 - crop_left
75
- s = view_size / orig_h # 128/480
76
- return (u_in_crop * s, v480 * s)
77
-
78
-
79
- def project_gel_with_axes(pose_7, gel_center_mm, calib, axis_len_mm=80.0):
80
- """Return (center_uv, [(x_uv, y_uv, z_uv) or None])."""
81
- if pose_7 is None or np.allclose(pose_7, 0.0):
82
- return None, None
83
- T_r2m = pose_to_T(pose_7)
84
- P_gel = (T_r2m @ np.append(gel_center_mm, 1.0))[:3]
85
- R = T_r2m[:3, :3]
86
- tips = [P_gel + R @ np.array([axis_len_mm, 0, 0]),
87
- P_gel + R @ np.array([0, axis_len_mm, 0]),
88
- P_gel + R @ np.array([0, 0, axis_len_mm])]
89
- center = project_to_view(P_gel, calib)
90
- if center is None:
91
- return None, None
92
- return center, [project_to_view(t, calib) for t in tips]
93
-
94
-
95
- def to_hwc(t):
96
  return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()
97
 
98
 
99
- def annotate_view(view_uint8, pose_L, pose_R, calib, *, scale=1):
100
- """Draw sensor axes on a (H, W, 3) RGB image. Returns annotated copy."""
101
- H, W, _ = view_uint8.shape
102
- img = view_uint8.copy()
103
- for side, pose, gel in [("L", pose_L, calib["gel_left"]),
104
- ("R", pose_R, calib["gel_right"])]:
105
- ctr, axes = project_gel_with_axes(pose, gel, calib)
106
- if ctr is None:
107
- continue
108
- cx, cy = int(round(ctr[0])), int(round(ctr[1]))
109
- if axes is not None:
110
- for tip, c, lab in zip(axes, AX_COLORS_RGB, AX_LABELS):
111
- if tip is None:
112
- continue
113
- tx, ty = int(round(tip[0])), int(round(tip[1]))
114
- cv2.line(img, (cx, cy), (tx, ty), c, max(1, scale), cv2.LINE_AA)
115
- dot_color = GEL_DOT_COLOR[side]
116
- cv2.circle(img, (cx, cy), max(2, 3 * scale), dot_color, -1, cv2.LINE_AA)
117
- cv2.circle(img, (cx, cy), max(2, 3 * scale) + 1, (255, 255, 255), 1, cv2.LINE_AA)
118
- cv2.putText(img, side, (cx + 4, cy + 4),
119
- cv2.FONT_HERSHEY_SIMPLEX, 0.4 * scale,
120
- dot_color, max(1, scale), cv2.LINE_AA)
121
- return img
122
 
123
 
124
- def make_static_grid(ds, sample_indices, calib, out_path,
125
- n_cols=6, cell_scale=3):
 
 
126
  rows = []
127
  for idx in sample_indices:
128
  s = ds[idx]
@@ -130,29 +58,24 @@ def make_static_grid(ds, sample_indices, calib, out_path,
130
  pick = np.linspace(0, T - 1, n_cols).astype(int)
131
  cells = []
132
  for t in pick:
133
- view_rgb = to_hwc(s["view"][t]).astype(np.uint8)
134
- view_rgb = annotate_view(view_rgb,
135
- s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None,
136
- s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None,
137
- calib, scale=1)
138
- tl = to_hwc(s["tactile_left"][t])
139
- tr = to_hwc(s["tactile_right"][t])
140
- # Stack horizontally: view | tac_L | tac_R, each 128×128
141
- triplet = np.concatenate([view_rgb, tl, tr], axis=1) # (128, 384, 3)
142
- # Upscale for clarity
143
- triplet = cv2.resize(triplet, (triplet.shape[1] * cell_scale, triplet.shape[0] * cell_scale),
144
- interpolation=cv2.INTER_NEAREST)
145
  cells.append(triplet)
146
  rows.append(np.concatenate(cells, axis=1))
147
 
148
  H_row = rows[0].shape[0]
149
  W_row = rows[0].shape[1]
 
150
  pad_y = 16
151
- label_h = 88 # vertical label band above each row
152
  canvas_h = 60 + len(rows) * (H_row + label_h + pad_y)
153
- canvas = np.full((canvas_h, W_row + 20, 3), 245, dtype=np.uint8)
154
-
155
- # Page header
156
  cv2.putText(canvas, f"ReactWindowDataset — {n_cols} evenly-spaced frames per sample (time runs left → right)",
157
  (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 50, 50), 2, cv2.LINE_AA)
158
 
@@ -160,102 +83,86 @@ def make_static_grid(ds, sample_indices, calib, out_path,
160
  for r, idx in enumerate(sample_indices):
161
  s = ds[idx]
162
  y0 = 60 + r * (H_row + label_h + pad_y)
163
- # Sample label band
164
- ep = s["episode_key"]
165
  dur_s = float(s["timestamps"][-1] - s["timestamps"][0])
166
  mL = float(s["tactile_left_mixed"].max())
167
  mR = float(s["tactile_right_mixed"].max())
168
- cv2.putText(canvas, f"sample #{idx} · {ep} · frames {s['frame_start']}-{s['frame_end']} ({dur_s:.2f}s) · active: {','.join(s['active_sensors'])} · peak mixed L={mL:.2f} R={mR:.2f}",
169
- (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)
170
- # Per-cell time labels
 
 
 
 
171
  T = s["view"].shape[0]
172
  pick = np.linspace(0, T - 1, n_cols).astype(int)
173
  for c, t in enumerate(pick):
174
  cv2.putText(canvas, f"t = {int(t)} (frame {s['frame_start'] + int(t)})",
175
- (10 + c * cell_w + 8, y0 + 56), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (90, 90, 90), 1, cv2.LINE_AA)
 
176
  cv2.putText(canvas, "view | tactile_left | tactile_right",
177
  (10, y0 + 76), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (130, 130, 130), 1, cv2.LINE_AA)
178
- # Place row
179
  canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r]
180
 
 
181
  Image.fromarray(canvas).save(out_path)
182
- print(f" static -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
183
-
184
-
185
- def make_gif(ds, sample_idx, calib, out_path, *, panel_scale=3, fps=15):
186
- s = ds[sample_idx]
187
- T = s["view"].shape[0]
188
- frames = []
189
- for t in range(T):
190
- view_rgb = to_hwc(s["view"][t]).astype(np.uint8)
191
- view_ann = annotate_view(view_rgb,
192
- s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None,
193
- s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None,
194
- calib, scale=1)
195
- # Upscale each subpanel
196
- view_big = cv2.resize(view_ann, (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
197
- tl_big = cv2.resize(to_hwc(s["tactile_left"][t]),
198
- (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
199
- tr_big = cv2.resize(to_hwc(s["tactile_right"][t]),
200
- (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST)
201
- triplet = np.concatenate([view_big, tl_big, tr_big], axis=1)
202
- # Header strip with frame counter
203
- H, W, _ = triplet.shape
204
- header = np.full((36, W, 3), 230, dtype=np.uint8)
205
- text = f"{s['episode_key']} frame {s['frame_start'] + t}/{s['frame_end']} ({t+1}/{T}) | view | tactile_L | tactile_R"
206
- cv2.putText(header, text, (8, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)
207
- panel = np.concatenate([header, triplet], axis=0)
208
- frames.append(panel)
209
-
210
- # Shared-palette GIF
211
- pil = [Image.fromarray(f) for f in frames]
212
- mosaic = Image.new("RGB", (pil[0].width * min(8, len(pil)), pil[0].height))
213
- for i, im in enumerate(pil[: min(8, len(pil))]):
214
- mosaic.paste(im, (i * pil[0].width, 0))
215
- pal = mosaic.quantize(colors=128, method=Image.MEDIANCUT, dither=Image.NONE)
216
- qframes = [im.quantize(palette=pal, dither=Image.NONE) for im in pil]
217
- qframes[0].save(out_path, save_all=True, append_images=qframes[1:],
218
- duration=int(round(1000 / fps)), loop=0, optimize=True, disposal=0)
219
- print(f" gif -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
220
 
221
 
222
  def main():
223
- # tasks.json was pre-fetched to TASKS_JSON via the base env
224
- if not TASKS_JSON.exists():
225
- raise FileNotFoundError(f"{TASKS_JSON} missing; fetch from yxma/React first")
226
- calib = load_calib()
227
-
228
- print("=== Build dataset ===")
 
 
 
 
 
 
 
 
 
229
  ds = ReactWindowDataset(
230
- data_root=DATA_ROOT,
231
- bad_frames_path=BAD_FRAMES,
232
- tasks_json_path=TASKS_JSON,
233
- window_length=16,
234
- stride=1,
235
- window_step=16,
236
- contact_metric="mixed",
237
- tactile_threshold=0.4,
238
- min_contact_fraction=0.6,
239
- which_sensors="any",
240
- skip_bad_frames=True,
241
- respect_active_sensors=True,
 
 
 
 
242
  )
243
 
244
- rng = np.random.default_rng(42)
245
- pick = rng.choice(len(ds), 4, replace=False)
246
- print(f"\n=== Render 4 random samples ===")
247
- make_static_grid(ds, pick, calib, OUT / "sample_grid.png")
248
- print(f"\n=== Render one as GIF ===")
249
- make_gif(ds, int(pick[0]), calib, OUT / "sample_window.gif")
250
 
251
- print("\nSample dict shapes (sample 0):")
252
- s = ds[int(pick[0])]
253
- for k, v in s.items():
 
 
 
254
  if isinstance(v, torch.Tensor):
255
  print(f" {k:30s} {tuple(v.shape)} {v.dtype}")
256
  else:
257
  print(f" {k:30s} {v!r}")
258
 
 
 
 
 
259
 
260
  if __name__ == "__main__":
261
  main()
 
1
+ """End-to-end usage example for `ReactWindowDataset`.
2
+
3
+ Run this against a local checkout of the React HF dataset:
4
+
5
+ python examples/demo_react_window.py \\
6
+ --data_root processed/mode1_v1/motherboard \\
7
+ --bad_frames bad_frames.json \\
8
+ --tasks_json tasks.json \\
9
+ --n_samples 4 \\
10
+ --out_dir /tmp/react_demo_out
11
+
12
+ What this script does
13
+ ---------------------
14
+ 1. Builds `ReactWindowDataset` with all four quality filters on (see the
15
+ module docstring of `react_window_dataset.py` for what each catches).
16
+ 2. Prints how many windows survived and the shape of one sample.
17
+ 3. Renders a static grid of `--n_samples` random windows as a PNG. Each
18
+ row = one window; each cell = `view | tactile_left | tactile_right`
19
+ for a single frame inside that window.
20
+
21
+ Self-contained: only depends on numpy, torch, Pillow, and `cv2`. No
22
+ recording-machine code is needed — everything required to read the
23
+ published .pt files is shipped here.
24
  """
25
+ import argparse
26
  import sys
27
  from pathlib import Path
28
 
29
  import cv2
30
  import numpy as np
31
  import torch
32
+ from PIL import Image
 
33
 
34
+ # Same-directory import.
35
+ sys.path.insert(0, str(Path(__file__).parent))
36
  from react_window_dataset import ReactWindowDataset
37
 
 
 
38
 
39
+ def _to_hwc(t):
40
+ """(3, H, W) torch uint8 → (H, W, 3) numpy uint8."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()
42
 
43
 
44
+ def _view_to_rgb(view_chw_uint8):
45
+ """`view` was extracted from RealSense cam0 which records BGR
46
+ (`rs.format.bgr8`); convert to RGB for PIL."""
47
+ return view_chw_uint8.permute(1, 2, 0).numpy()[..., ::-1].copy()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
 
50
+ def make_static_grid(ds, sample_indices, out_path: Path, *,
51
+ n_cols: int = 6, cell_scale: int = 3) -> None:
52
+ """One row per window, `n_cols` evenly-spaced frames per window. Each
53
+ cell is `view | tactile_left | tactile_right`."""
54
  rows = []
55
  for idx in sample_indices:
56
  s = ds[idx]
 
58
  pick = np.linspace(0, T - 1, n_cols).astype(int)
59
  cells = []
60
  for t in pick:
61
+ view = _view_to_rgb(s["view"][t]).astype(np.uint8)
62
+ tac_L = _to_hwc(s["tactile_left"][t]).astype(np.uint8)
63
+ tac_R = _to_hwc(s["tactile_right"][t]).astype(np.uint8)
64
+ triplet = np.concatenate([view, tac_L, tac_R], axis=1) # (128, 384, 3)
65
+ triplet = cv2.resize(
66
+ triplet,
67
+ (triplet.shape[1] * cell_scale, triplet.shape[0] * cell_scale),
68
+ interpolation=cv2.INTER_NEAREST,
69
+ )
 
 
 
70
  cells.append(triplet)
71
  rows.append(np.concatenate(cells, axis=1))
72
 
73
  H_row = rows[0].shape[0]
74
  W_row = rows[0].shape[1]
75
+ label_h = 88
76
  pad_y = 16
 
77
  canvas_h = 60 + len(rows) * (H_row + label_h + pad_y)
78
+ canvas = np.full((canvas_h, W_row + 20, 3), 245, np.uint8)
 
 
79
  cv2.putText(canvas, f"ReactWindowDataset — {n_cols} evenly-spaced frames per sample (time runs left → right)",
80
  (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 50, 50), 2, cv2.LINE_AA)
81
 
 
83
  for r, idx in enumerate(sample_indices):
84
  s = ds[idx]
85
  y0 = 60 + r * (H_row + label_h + pad_y)
 
 
86
  dur_s = float(s["timestamps"][-1] - s["timestamps"][0])
87
  mL = float(s["tactile_left_mixed"].max())
88
  mR = float(s["tactile_right_mixed"].max())
89
+ cv2.putText(
90
+ canvas,
91
+ (f"sample #{idx} · {s['episode_key']} · frames {s['frame_start']}-{s['frame_end']} "
92
+ f"({dur_s:.2f}s) · active: {','.join(s['active_sensors'])} · "
93
+ f"peak mixed L={mL:.2f} R={mR:.2f}"),
94
+ (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA,
95
+ )
96
  T = s["view"].shape[0]
97
  pick = np.linspace(0, T - 1, n_cols).astype(int)
98
  for c, t in enumerate(pick):
99
  cv2.putText(canvas, f"t = {int(t)} (frame {s['frame_start'] + int(t)})",
100
+ (10 + c * cell_w + 8, y0 + 56),
101
+ cv2.FONT_HERSHEY_SIMPLEX, 0.45, (90, 90, 90), 1, cv2.LINE_AA)
102
  cv2.putText(canvas, "view | tactile_left | tactile_right",
103
  (10, y0 + 76), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (130, 130, 130), 1, cv2.LINE_AA)
 
104
  canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r]
105
 
106
+ out_path.parent.mkdir(parents=True, exist_ok=True)
107
  Image.fromarray(canvas).save(out_path)
108
+ print(f" grid -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
 
110
 
111
  def main():
112
+ ap = argparse.ArgumentParser()
113
+ ap.add_argument("--data_root", required=True,
114
+ help="processed/mode1_v1/motherboard (relative to dataset root)")
115
+ ap.add_argument("--bad_frames", default="bad_frames.json")
116
+ ap.add_argument("--tasks_json", default="tasks.json")
117
+ ap.add_argument("--n_samples", type=int, default=4)
118
+ ap.add_argument("--out_dir", default="/tmp/react_demo_out")
119
+ ap.add_argument("--window_length", type=int, default=16)
120
+ ap.add_argument("--seed", type=int, default=42)
121
+ ap.add_argument("--no_motion_filter", action="store_true",
122
+ help="Disable the motion filter (useful if you want stationary "
123
+ "contact windows for studying static tactile patterns).")
124
+ args = ap.parse_args()
125
+
126
+ print("=== Building dataset (all four quality filters on) ===")
127
  ds = ReactWindowDataset(
128
+ data_root = args.data_root,
129
+ bad_frames_path = args.bad_frames,
130
+ tasks_json_path = args.tasks_json,
131
+ window_length = args.window_length,
132
+ stride = 1,
133
+ window_step = max(1, args.window_length // 2),
134
+ contact_metric = "mixed",
135
+ tactile_threshold = 0.4,
136
+ min_contact_fraction = 0.5,
137
+ which_sensors = "any",
138
+ skip_bad_frames = True,
139
+ respect_active_sensors = True,
140
+ require_motion = not args.no_motion_filter,
141
+ min_motion_mps = 0.03,
142
+ min_motion_fraction = 0.5,
143
+ which_sensors_must_move = "all_active",
144
  )
145
 
146
+ if len(ds) == 0:
147
+ print("No windows passed the filters. Try lowering `min_contact_fraction` "
148
+ "or disabling `require_motion`.")
149
+ return
 
 
150
 
151
+ rng = np.random.default_rng(args.seed)
152
+ pick = rng.choice(len(ds), min(args.n_samples, len(ds)), replace=False)
153
+
154
+ print(f"\n=== One sample's structure (#{int(pick[0])}) ===")
155
+ s0 = ds[int(pick[0])]
156
+ for k, v in s0.items():
157
  if isinstance(v, torch.Tensor):
158
  print(f" {k:30s} {tuple(v.shape)} {v.dtype}")
159
  else:
160
  print(f" {k:30s} {v!r}")
161
 
162
+ print(f"\n=== Static grid of {len(pick)} random windows ===")
163
+ out_dir = Path(args.out_dir)
164
+ make_static_grid(ds, pick, out_dir / "sample_grid.png")
165
+
166
 
167
  if __name__ == "__main__":
168
  main()
examples/react_window_dataset.py CHANGED
@@ -1,8 +1,47 @@
1
- """React: short-horizon contact-rich window dataset.
2
 
3
- A PyTorch `Dataset` that yields short multimodal windows sampled from the
4
- React recordings, filtered to be contact-rich and free of known data-quality
5
- issues. Intended for tactile-visual dynamics / world-model learning.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  Usage
8
  -----
@@ -11,23 +50,31 @@ from react_window_dataset import ReactWindowDataset
11
  from torch.utils.data import DataLoader
12
 
13
  ds = ReactWindowDataset(
14
- data_root="processed/mode1_v1/motherboard",
15
- bad_frames_path="bad_frames.json",
16
- tasks_json_path="tasks.json",
17
- window_length=16, # frames per window
18
- stride=1, # within-window frame stride (1 = consecutive)
19
- window_step=8, # step between window start indices
20
- contact_metric="mixed", # which tactile metric to threshold on
21
- tactile_threshold=0.4,
22
- min_contact_fraction=0.5, # ≥ 50% of window frames must have contact
23
- which_sensors="any", # "any" | "both" | "left" | "right"
24
- skip_bad_frames=True,
25
- respect_active_sensors=True, # mask out left modalities for right-only pilot
 
 
 
 
 
 
 
26
  )
27
  loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
28
  ```
29
 
30
- Each sample is a dict of `(T, ...)` tensors plus metadata.
 
31
  """
32
  from __future__ import annotations
33
 
@@ -42,47 +89,81 @@ from torch.utils.data import Dataset
42
  CONTACT_METRICS = ("intensity", "area", "mixed")
43
 
44
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  class ReactWindowDataset(Dataset):
46
  """Per-window dataset over the React recordings.
47
 
 
 
48
  Parameters
49
  ----------
50
  data_root : path
51
- Directory containing `<task>/<date>/episode_*.pt` files. Searched
52
- recursively.
53
  bad_frames_path : optional path
54
- `bad_frames.json` (the shipped skip-list). If None, no quality filter.
55
  tasks_json_path : optional path
56
- `tasks.json`. Used for `respect_active_sensors` mode.
 
57
  window_length : int
58
- Number of frames per sample.
59
  stride : int
60
- Frame stride within a window. `stride=1` → consecutive frames,
61
- `stride=2` → every other source frame, etc. Span of a window in
62
- source-frame indices = `(window_length - 1) * stride + 1`.
63
  window_step : int, default `window_length // 2`
64
  Step between window start indices within an episode. Controls
65
  overlap between adjacent windows.
 
66
  contact_metric : {"intensity", "area", "mixed"}
67
  Which per-frame tactile metric to threshold on.
68
  tactile_threshold : float
69
- Minimum value of the chosen metric to count as contact.
70
  min_contact_fraction : float in [0, 1]
71
- A window is kept only if at least this fraction of its frames satisfy
72
- the contact predicate.
73
  which_sensors : {"any", "both", "left", "right"}
74
- How left + right sensors combine when checking the predicate.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  tasks, dates : optional iterables of str
76
- Filter episodes by task name and/or date string.
77
- skip_bad_frames : bool
78
- If True, drop windows whose source-frame span overlaps any flagged
79
- interval in `bad_frames.json`.
80
- respect_active_sensors : bool
81
- If True (and `tasks.json` has per-date `active_sensors`), windows on
82
- right-only recordings (2026-03-23 pilot) auto-fallback to right-only
83
- contact predicate, and the returned sample carries an
84
- `active_sensors` field so dataloaders can mask the inactive
85
- modalities.
86
  """
87
 
88
  def __init__(
@@ -102,11 +183,18 @@ class ReactWindowDataset(Dataset):
102
  dates: Iterable[str] | None = None,
103
  skip_bad_frames: bool = True,
104
  respect_active_sensors: bool = True,
 
 
 
 
 
105
  ):
106
  if contact_metric not in CONTACT_METRICS:
107
  raise ValueError(f"contact_metric must be one of {CONTACT_METRICS}")
108
  if which_sensors not in ("any", "both", "left", "right"):
109
  raise ValueError("which_sensors must be 'any' | 'both' | 'left' | 'right'")
 
 
110
  if window_length < 1 or stride < 1:
111
  raise ValueError("window_length and stride must be ≥ 1")
112
 
@@ -119,6 +207,12 @@ class ReactWindowDataset(Dataset):
119
  self.min_contact_fraction = float(min_contact_fraction)
120
  self.which_sensors = which_sensors
121
  self.respect_active_sensors = bool(respect_active_sensors)
 
 
 
 
 
 
122
 
123
  self.bad = {}
124
  if bad_frames_path is not None and Path(bad_frames_path).is_file():
@@ -133,9 +227,7 @@ class ReactWindowDataset(Dataset):
133
  for d, info in td.get("per_date_notes", {}).items():
134
  self.per_date[d] = info
135
 
136
- self.skip_bad_frames = bool(skip_bad_frames)
137
-
138
- # Discover episodes
139
  pt_files = sorted(self.data_root.rglob("episode_*.pt"))
140
  if not pt_files:
141
  raise RuntimeError(f"No episode_*.pt under {self.data_root}")
@@ -144,28 +236,28 @@ class ReactWindowDataset(Dataset):
144
 
145
  self.episodes: list[dict] = []
146
  self.episode_paths: list[Path] = []
147
- self.episode_keys: list[str] = [] # "<date>/<stem>" for bad_frames lookup
148
  self.episode_active: list[list[str]] = []
149
- self.windows: list[tuple[int, int]] = [] # (ep_idx, t_start)
 
 
150
 
151
- span = (self.window_length - 1) * self.stride + 1 # source-frame span
 
 
 
 
152
 
153
  for pt in pt_files:
154
  rel = pt.relative_to(self.data_root)
155
- # rel.parts == (<task>, <date>, "episode_NNN.pt") OR (<date>, ...)
156
  if len(rel.parts) == 3:
157
- task, date, _ = rel.parts
158
- key = f"{date}/{pt.stem}"
159
  elif len(rel.parts) == 2:
160
- task, date = None, rel.parts[0]
161
- key = f"{date}/{pt.stem}"
162
  else:
163
  task, date, key = None, None, pt.stem
164
-
165
- if tasks is not None and task not in tasks:
166
- continue
167
- if dates is not None and date not in dates:
168
- continue
169
 
170
  d = torch.load(pt, weights_only=False, map_location="cpu")
171
  active = ["left", "right"]
@@ -176,24 +268,18 @@ class ReactWindowDataset(Dataset):
176
  mR = d[f"tactile_right_{self.contact_metric}"].numpy()
177
  T = mL.shape[0]
178
 
179
- # Per-frame contact predicate respecting which_sensors and active_sensors
180
  cL = mL > self.tactile_threshold
181
  cR = mR > self.tactile_threshold
182
- if "left" not in active:
183
- cL = np.zeros_like(cL)
184
- if "right" not in active:
185
- cR = np.zeros_like(cR)
186
  req = self.which_sensors
187
- if req == "any":
188
- contact_frame = cL | cR
189
- elif req == "both":
190
- contact_frame = cL & cR
191
- elif req == "left":
192
- contact_frame = cL
193
- else:
194
- contact_frame = cR
195
 
196
- # Bad-frame mask
197
  bad_mask = np.zeros(T, dtype=bool)
198
  if self.skip_bad_frames and key in self.bad:
199
  bf = self.bad[key]
@@ -204,30 +290,58 @@ class ReactWindowDataset(Dataset):
204
  + bf.get("ot_loss_R", [])):
205
  bad_mask[s:e + 1] = True
206
 
 
 
 
 
 
 
 
 
 
 
 
207
  ep_idx = len(self.episodes)
208
  self.episodes.append(d)
209
  self.episode_paths.append(pt)
210
  self.episode_keys.append(key)
211
  self.episode_active.append(active)
212
 
213
- # Enumerate windows
214
  kept = 0
215
  for t_start in range(0, T - span + 1, self.window_step):
 
216
  t_end = t_start + span - 1
217
  frame_idx = np.arange(t_start, t_start + span, self.stride)
 
218
  if bad_mask[t_start:t_end + 1].any():
 
219
  continue
220
- frac = contact_frame[frame_idx].mean()
221
- if frac < self.min_contact_fraction:
222
  continue
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  self.windows.append((ep_idx, t_start))
224
  kept += 1
225
- print(f"[ReactWindowDataset] {key}: T={T}, active={active}, "
226
- f"kept {kept} windows")
227
 
228
  print(f"[ReactWindowDataset] total windows: {len(self.windows)} "
229
  f"(window_length={self.window_length}, stride={self.stride}, "
230
  f"window_step={self.window_step})")
 
 
231
 
232
  def __len__(self) -> int:
233
  return len(self.windows)
@@ -237,18 +351,17 @@ class ReactWindowDataset(Dataset):
237
  ep = self.episodes[ep_idx]
238
  frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride)
239
  sample = {
240
- "view": ep["view"][frame_idx], # (T, 3, 128, 128) uint8
241
  "tactile_left": ep["tactile_left"][frame_idx],
242
  "tactile_right": ep["tactile_right"][frame_idx],
243
- "sensor_left_pose": ep["sensor_left_pose"][frame_idx], # (T, 7) f32
244
  "sensor_right_pose": ep["sensor_right_pose"][frame_idx],
245
- "timestamps": ep["timestamps"][frame_idx], # (T,) f64
246
  "tactile_left_intensity": ep["tactile_left_intensity"][frame_idx],
247
  "tactile_right_intensity": ep["tactile_right_intensity"][frame_idx],
248
  "tactile_left_mixed": ep["tactile_left_mixed"][frame_idx],
249
  "tactile_right_mixed": ep["tactile_right_mixed"][frame_idx],
250
  }
251
- # Metadata (not batched by default DataLoader because they're scalars/strings)
252
  sample["episode"] = str(self.episode_paths[ep_idx])
253
  sample["episode_key"] = self.episode_keys[ep_idx]
254
  sample["frame_start"] = int(t_start)
@@ -270,6 +383,11 @@ if __name__ == "__main__":
270
  ap.add_argument("--min_contact_fraction", type=float, default=0.5)
271
  ap.add_argument("--contact_metric", default="mixed", choices=CONTACT_METRICS)
272
  ap.add_argument("--which_sensors", default="any", choices=["any", "both", "left", "right"])
 
 
 
 
 
273
  args = ap.parse_args()
274
  ds = ReactWindowDataset(
275
  data_root=args.data_root,
@@ -282,8 +400,12 @@ if __name__ == "__main__":
282
  tactile_threshold=args.tactile_threshold,
283
  min_contact_fraction=args.min_contact_fraction,
284
  which_sensors=args.which_sensors,
 
 
 
 
285
  )
286
- print(f"len(ds) = {len(ds)}")
287
  if len(ds):
288
  sample = ds[0]
289
  for k, v in sample.items():
 
1
+ """React: short-horizon contact-rich window dataset (PyTorch).
2
 
3
+ Yields short multimodal windows sampled from the React recordings, with all
4
+ known data-quality issues filtered out at window-enumeration time. Intended
5
+ for tactile-visual dynamics / world-model / UMI-style imitation learning.
6
+
7
+ What each filter catches
8
+ ------------------------
9
+
10
+ 1. `skip_bad_frames` → windows overlapping any flagged interval in
11
+ `bad_frames.json` are dropped. Covers:
12
+ - `intensity_spikes` — single-frame GelSight LED glitches
13
+ - `pose_teleports_{L,R}` — translation-velocity > 5 m/s solver flips
14
+ - `ot_loss_{L,R}` — mid-episode OptiTrack track loss
15
+ (pose held stale for ≥ 0.25 s while the
16
+ cross-modal motion check shows the sensor
17
+ was actually moving)
18
+
19
+ 2. `respect_active_sensors` → per-date metadata in `tasks.json` tells us
20
+ which GelSight rigid bodies were actually in use that day; the predicate
21
+ below ignores inactive sensors when deciding "is this window useful?".
22
+
23
+ 3. `min_contact_fraction` → windows where fewer than this fraction of
24
+ frames have tactile contact (per the configured metric + threshold +
25
+ `which_sensors`) are dropped. Forces samples to be contact-rich.
26
+
27
+ 4. `require_motion` → windows where the sensor is sitting essentially
28
+ still (operator paused mid-manipulation) are dropped. Specifically: an
29
+ active sensor "passes" if at least `min_motion_fraction` of its frames
30
+ have per-frame translation speed ≥ `min_motion_mps`. The
31
+ `which_sensors_must_move` parameter says whether every active sensor
32
+ must pass, or just one.
33
+
34
+ This catches the failure mode that bad_frames.json *can't* — windows
35
+ where OT is healthy and pose is changing every frame, but the change
36
+ is sub-millimeter per frame so there's nothing to learn dynamics from.
37
+
38
+ Coordinates note
39
+ ----------------
40
+ All frame indices in `bad_frames.json` and the .pt files are in TRIMMED
41
+ coordinates: the OT-uninitialized prefixes at the start of three episodes
42
+ have been cut from the published .pt files (see `_contact_meta.trim_offset`
43
+ inside each .pt). You don't need to do anything special — this loader and
44
+ the metadata are already aligned.
45
 
46
  Usage
47
  -----
 
50
  from torch.utils.data import DataLoader
51
 
52
  ds = ReactWindowDataset(
53
+ data_root = "processed/mode1_v1/motherboard",
54
+ bad_frames_path = "bad_frames.json",
55
+ tasks_json_path = "tasks.json",
56
+ window_length = 16,
57
+ stride = 1,
58
+ window_step = 8,
59
+ # contact filter
60
+ contact_metric = "mixed",
61
+ tactile_threshold = 0.4,
62
+ min_contact_fraction = 0.5,
63
+ which_sensors = "any",
64
+ # quality filters (recommended on)
65
+ skip_bad_frames = True,
66
+ respect_active_sensors = True,
67
+ # motion filter (recommended on for dynamics learning)
68
+ require_motion = True,
69
+ min_motion_mps = 0.03, # 30 mm/s — above "paused"
70
+ min_motion_fraction = 0.5,
71
+ which_sensors_must_move = "all_active",
72
  )
73
  loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
74
  ```
75
 
76
+ Each sample is a dict of `(T, ...)` tensors plus per-window metadata
77
+ (`episode`, `episode_key`, `frame_start`, `frame_end`, `active_sensors`).
78
  """
79
  from __future__ import annotations
80
 
 
89
  CONTACT_METRICS = ("intensity", "area", "mixed")
90
 
91
 
92
+ def _per_frame_speed_mps(pose7: np.ndarray, fps: float = 30.0) -> np.ndarray:
93
+ """Per-frame translation speed in m/s. Output shape == input frame count;
94
+ pad the first frame's speed with the second frame's (forward difference)."""
95
+ if pose7.shape[0] < 2:
96
+ return np.zeros(pose7.shape[0], dtype=np.float64)
97
+ d = np.linalg.norm(np.diff(pose7[:, :3], axis=0), axis=1) * fps
98
+ out = np.empty(pose7.shape[0], dtype=np.float64)
99
+ out[0] = d[0]
100
+ out[1:] = d
101
+ return out
102
+
103
+
104
  class ReactWindowDataset(Dataset):
105
  """Per-window dataset over the React recordings.
106
 
107
+ See the module docstring for what each filter catches.
108
+
109
  Parameters
110
  ----------
111
  data_root : path
112
+ Directory containing `<task>/<date>/episode_*.pt` files (searched
113
+ recursively).
114
  bad_frames_path : optional path
115
+ Path to `bad_frames.json`. If None, no quality filter is applied.
116
  tasks_json_path : optional path
117
+ Path to `tasks.json`. Used for the `respect_active_sensors` mode.
118
+
119
  window_length : int
120
+ Frames per sample (default 16).
121
  stride : int
122
+ Frame stride *within* a window. `stride=1` → consecutive source
123
+ frames; `stride=2` → every other source frame; etc. Span of a
124
+ window in source-frame indices = `(window_length - 1) * stride + 1`.
125
  window_step : int, default `window_length // 2`
126
  Step between window start indices within an episode. Controls
127
  overlap between adjacent windows.
128
+
129
  contact_metric : {"intensity", "area", "mixed"}
130
  Which per-frame tactile metric to threshold on.
131
  tactile_threshold : float
132
+ Minimum value of the chosen metric to count a frame as in-contact.
133
  min_contact_fraction : float in [0, 1]
134
+ Window must have this fraction of in-contact frames.
 
135
  which_sensors : {"any", "both", "left", "right"}
136
+ How left + right sensors combine when checking the contact
137
+ predicate. (Inactive sensors per `tasks.json` are always excluded.)
138
+
139
+ skip_bad_frames : bool, default True
140
+ Drop windows whose source-frame span overlaps any interval in
141
+ `intensity_spikes / pose_teleports_{L,R} / ot_loss_{L,R}`.
142
+ respect_active_sensors : bool, default True
143
+ If True (and `tasks.json` has per-date `active_sensors`), inactive
144
+ sensors are ignored by both the contact filter and the motion
145
+ filter, and the returned sample carries an `active_sensors` field
146
+ so downstream code can mask out the inactive modalities.
147
+
148
+ require_motion : bool, default False
149
+ Toggle the motion filter (off for back-compat; recommended on for
150
+ dynamics learning).
151
+ min_motion_mps : float, default 0.03
152
+ Per-frame translation speed (in m/s) above which a frame counts as
153
+ "moving" for a given sensor.
154
+ min_motion_fraction : float in [0, 1], default 0.5
155
+ An active sensor passes the motion filter if ≥ this fraction of
156
+ the window's frames have speed ≥ `min_motion_mps`.
157
+ which_sensors_must_move : {"any", "all_active"}, default "all_active"
158
+ Whether every active sensor must pass the motion filter (strict;
159
+ rejects the "left held still while right moves" pattern), or just
160
+ one. "all_active" is what you typically want for dynamics learning.
161
+
162
  tasks, dates : optional iterables of str
163
+ Restrict to specific task names / date strings.
164
+
165
+ fps : float, default 30
166
+ Frame rate used to convert pose deltas to m/s.
 
 
 
 
 
 
167
  """
168
 
169
  def __init__(
 
183
  dates: Iterable[str] | None = None,
184
  skip_bad_frames: bool = True,
185
  respect_active_sensors: bool = True,
186
+ require_motion: bool = False,
187
+ min_motion_mps: float = 0.03,
188
+ min_motion_fraction: float = 0.5,
189
+ which_sensors_must_move: str = "all_active",
190
+ fps: float = 30.0,
191
  ):
192
  if contact_metric not in CONTACT_METRICS:
193
  raise ValueError(f"contact_metric must be one of {CONTACT_METRICS}")
194
  if which_sensors not in ("any", "both", "left", "right"):
195
  raise ValueError("which_sensors must be 'any' | 'both' | 'left' | 'right'")
196
+ if which_sensors_must_move not in ("any", "all_active"):
197
+ raise ValueError("which_sensors_must_move must be 'any' | 'all_active'")
198
  if window_length < 1 or stride < 1:
199
  raise ValueError("window_length and stride must be ≥ 1")
200
 
 
207
  self.min_contact_fraction = float(min_contact_fraction)
208
  self.which_sensors = which_sensors
209
  self.respect_active_sensors = bool(respect_active_sensors)
210
+ self.skip_bad_frames = bool(skip_bad_frames)
211
+ self.require_motion = bool(require_motion)
212
+ self.min_motion_mps = float(min_motion_mps)
213
+ self.min_motion_fraction = float(min_motion_fraction)
214
+ self.which_sensors_must_move = which_sensors_must_move
215
+ self.fps = float(fps)
216
 
217
  self.bad = {}
218
  if bad_frames_path is not None and Path(bad_frames_path).is_file():
 
227
  for d, info in td.get("per_date_notes", {}).items():
228
  self.per_date[d] = info
229
 
230
+ # ── Episode discovery ────────────────────────────────────────────
 
 
231
  pt_files = sorted(self.data_root.rglob("episode_*.pt"))
232
  if not pt_files:
233
  raise RuntimeError(f"No episode_*.pt under {self.data_root}")
 
236
 
237
  self.episodes: list[dict] = []
238
  self.episode_paths: list[Path] = []
239
+ self.episode_keys: list[str] = []
240
  self.episode_active: list[list[str]] = []
241
+ self.windows: list[tuple[int, int]] = []
242
+
243
+ span = (self.window_length - 1) * self.stride + 1
244
 
245
+ # Counters for reporting how many windows each filter rejects
246
+ n_total_candidates = 0
247
+ n_drop_bad = 0
248
+ n_drop_contact = 0
249
+ n_drop_motion = 0
250
 
251
  for pt in pt_files:
252
  rel = pt.relative_to(self.data_root)
 
253
  if len(rel.parts) == 3:
254
+ task, date, _ = rel.parts; key = f"{date}/{pt.stem}"
 
255
  elif len(rel.parts) == 2:
256
+ task, date = None, rel.parts[0]; key = f"{date}/{pt.stem}"
 
257
  else:
258
  task, date, key = None, None, pt.stem
259
+ if tasks is not None and task not in tasks: continue
260
+ if dates is not None and date not in dates: continue
 
 
 
261
 
262
  d = torch.load(pt, weights_only=False, map_location="cpu")
263
  active = ["left", "right"]
 
268
  mR = d[f"tactile_right_{self.contact_metric}"].numpy()
269
  T = mL.shape[0]
270
 
271
+ # Contact predicate (respecting active sensors)
272
  cL = mL > self.tactile_threshold
273
  cR = mR > self.tactile_threshold
274
+ if "left" not in active: cL[:] = False
275
+ if "right" not in active: cR[:] = False
 
 
276
  req = self.which_sensors
277
+ if req == "any": contact_frame = cL | cR
278
+ elif req == "both": contact_frame = cL & cR
279
+ elif req == "left": contact_frame = cL
280
+ else: contact_frame = cR
 
 
 
 
281
 
282
+ # Bad-frame mask (intensity, pose_teleport, ot_loss)
283
  bad_mask = np.zeros(T, dtype=bool)
284
  if self.skip_bad_frames and key in self.bad:
285
  bf = self.bad[key]
 
290
  + bf.get("ot_loss_R", [])):
291
  bad_mask[s:e + 1] = True
292
 
293
+ # Per-frame motion predicate per sensor
294
+ if self.require_motion:
295
+ pose_L = d["sensor_left_pose"].numpy()
296
+ pose_R = d["sensor_right_pose"].numpy()
297
+ speed_L = _per_frame_speed_mps(pose_L, self.fps)
298
+ speed_R = _per_frame_speed_mps(pose_R, self.fps)
299
+ moving_L = speed_L >= self.min_motion_mps
300
+ moving_R = speed_R >= self.min_motion_mps
301
+ else:
302
+ moving_L = moving_R = None
303
+
304
  ep_idx = len(self.episodes)
305
  self.episodes.append(d)
306
  self.episode_paths.append(pt)
307
  self.episode_keys.append(key)
308
  self.episode_active.append(active)
309
 
 
310
  kept = 0
311
  for t_start in range(0, T - span + 1, self.window_step):
312
+ n_total_candidates += 1
313
  t_end = t_start + span - 1
314
  frame_idx = np.arange(t_start, t_start + span, self.stride)
315
+
316
  if bad_mask[t_start:t_end + 1].any():
317
+ n_drop_bad += 1
318
  continue
319
+ if contact_frame[frame_idx].mean() < self.min_contact_fraction:
320
+ n_drop_contact += 1
321
  continue
322
+ if self.require_motion:
323
+ passed = []
324
+ for side, mov in [("left", moving_L), ("right", moving_R)]:
325
+ if side not in active:
326
+ continue
327
+ passed.append(mov[frame_idx].mean() >= self.min_motion_fraction)
328
+ if self.which_sensors_must_move == "all_active":
329
+ ok = bool(passed) and all(passed)
330
+ else: # "any"
331
+ ok = any(passed)
332
+ if not ok:
333
+ n_drop_motion += 1
334
+ continue
335
+
336
  self.windows.append((ep_idx, t_start))
337
  kept += 1
338
+ print(f"[ReactWindowDataset] {key}: T={T}, active={active}, kept {kept} windows")
 
339
 
340
  print(f"[ReactWindowDataset] total windows: {len(self.windows)} "
341
  f"(window_length={self.window_length}, stride={self.stride}, "
342
  f"window_step={self.window_step})")
343
+ print(f"[ReactWindowDataset] enumerated {n_total_candidates} candidates: "
344
+ f"-{n_drop_bad} bad_frames, -{n_drop_contact} contact, -{n_drop_motion} motion")
345
 
346
  def __len__(self) -> int:
347
  return len(self.windows)
 
351
  ep = self.episodes[ep_idx]
352
  frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride)
353
  sample = {
354
+ "view": ep["view"][frame_idx],
355
  "tactile_left": ep["tactile_left"][frame_idx],
356
  "tactile_right": ep["tactile_right"][frame_idx],
357
+ "sensor_left_pose": ep["sensor_left_pose"][frame_idx],
358
  "sensor_right_pose": ep["sensor_right_pose"][frame_idx],
359
+ "timestamps": ep["timestamps"][frame_idx],
360
  "tactile_left_intensity": ep["tactile_left_intensity"][frame_idx],
361
  "tactile_right_intensity": ep["tactile_right_intensity"][frame_idx],
362
  "tactile_left_mixed": ep["tactile_left_mixed"][frame_idx],
363
  "tactile_right_mixed": ep["tactile_right_mixed"][frame_idx],
364
  }
 
365
  sample["episode"] = str(self.episode_paths[ep_idx])
366
  sample["episode_key"] = self.episode_keys[ep_idx]
367
  sample["frame_start"] = int(t_start)
 
383
  ap.add_argument("--min_contact_fraction", type=float, default=0.5)
384
  ap.add_argument("--contact_metric", default="mixed", choices=CONTACT_METRICS)
385
  ap.add_argument("--which_sensors", default="any", choices=["any", "both", "left", "right"])
386
+ ap.add_argument("--require_motion", action="store_true")
387
+ ap.add_argument("--min_motion_mps", type=float, default=0.03)
388
+ ap.add_argument("--min_motion_fraction", type=float, default=0.5)
389
+ ap.add_argument("--which_sensors_must_move", default="all_active",
390
+ choices=["any", "all_active"])
391
  args = ap.parse_args()
392
  ds = ReactWindowDataset(
393
  data_root=args.data_root,
 
400
  tactile_threshold=args.tactile_threshold,
401
  min_contact_fraction=args.min_contact_fraction,
402
  which_sensors=args.which_sensors,
403
+ require_motion=args.require_motion,
404
+ min_motion_mps=args.min_motion_mps,
405
+ min_motion_fraction=args.min_motion_fraction,
406
+ which_sensors_must_move=args.which_sensors_must_move,
407
  )
408
+ print(f"\nlen(ds) = {len(ds)}")
409
  if len(ds):
410
  sample = ds[0]
411
  for k, v in sample.items():