yxma commited on
Commit
84e6423
·
verified ·
1 Parent(s): 76d1d84

Add example dataloader: ReactWindowDataset for short contact-rich window sampling + demo (static grid + GIF) with sensor-frame overlay

Browse files
README.md CHANGED
@@ -107,6 +107,46 @@ with open("bad_frames.json") as f:
107
  # For 2026-03-23 recordings, also ignore the left-sensor fields (right-only pilot).
108
  ```
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  ## Recording-file previews
111
 
112
  Per-file GIF previews live under [`figures/episode_previews/`](figures/episode_previews) — first 2 minutes at 10× speed, showing all 3 RealSense cameras with projected GelSight axes plus both tactile pads. (The on-disk recording unit is called an "episode" purely for file naming — these boundaries don't carry semantic / action meaning for this dataset.)
@@ -139,3 +179,4 @@ Released under [Creative Commons Attribution 4.0](https://creativecommons.org/li
139
  ## Citation
140
 
141
  If you use this dataset, please cite (TODO: add bibtex).
 
 
107
  # For 2026-03-23 recordings, also ignore the left-sensor fields (right-only pilot).
108
  ```
109
 
110
+ ## Example dataloader — short contact-rich windows
111
+
112
+ A reference PyTorch `Dataset` is shipped under [`examples/react_window_dataset.py`](examples/react_window_dataset.py). It scans the processed `.pt` files, applies the contact filter, drops windows that overlap [`bad_frames.json`](bad_frames.json), and respects the per-date `active_sensors` field from [`tasks.json`](tasks.json).
113
+
114
+ ```python
115
+ from examples.react_window_dataset import ReactWindowDataset
116
+ from torch.utils.data import DataLoader
117
+
118
+ ds = ReactWindowDataset(
119
+ data_root="processed/mode1_v1/motherboard",
120
+ bad_frames_path="bad_frames.json",
121
+ tasks_json_path="tasks.json",
122
+ window_length=16, # frames per window
123
+ stride=1, # within-window stride (1 = consecutive)
124
+ window_step=16, # step between window starts (overlap control)
125
+ contact_metric="mixed", # "intensity" | "area" | "mixed"
126
+ tactile_threshold=0.4,
127
+ min_contact_fraction=0.6, # ≥ 60 % of window frames must have contact
128
+ which_sensors="any", # "any" | "both" | "left" | "right"
129
+ skip_bad_frames=True,
130
+ respect_active_sensors=True, # mask out left modalities for 2026-03-23 pilot
131
+ )
132
+ print(len(ds), "windows")
133
+ loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)
134
+ ```
135
+
136
+ With the defaults shown above, the dataset assembles **9,230 contact-rich 16-frame windows** across the 27 bimanual recordings. Each sample is a dict of `(T, …)` tensors plus metadata (`episode`, `frame_start`, `active_sensors`, …).
137
+
138
+ ### Example output
139
+
140
+ Four random windows, time runs left→right; each cell is `view | tactile_left | tactile_right` with sensor frame axes (X red, Y green, Z blue-ish) projected onto the view:
141
+
142
+ ![dataloader sample grid](figures/dataloader_examples/sample_grid.png)
143
+
144
+ One window played frame-by-frame with the sensor-frame overlay:
145
+
146
+ ![dataloader sample GIF](figures/dataloader_examples/sample_window.gif)
147
+
148
+ Full demo script: [`examples/demo_react_window.py`](examples/demo_react_window.py).
149
+
150
  ## Recording-file previews
151
 
152
  Per-file GIF previews live under [`figures/episode_previews/`](figures/episode_previews) — first 2 minutes at 10× speed, showing all 3 RealSense cameras with projected GelSight axes plus both tactile pads. (The on-disk recording unit is called an "episode" purely for file naming — these boundaries don't carry semantic / action meaning for this dataset.)
 
179
  ## Citation
180
 
181
  If you use this dataset, please cite (TODO: add bibtex).
182
+
examples/demo_react_window.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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]
129
+ T = s["view"].shape[0]
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
+
159
+ cell_w = W_row // n_cols
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()
examples/react_window_dataset.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ -----
9
+ ```python
10
+ 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
+
34
+ import json
35
+ from pathlib import Path
36
+ from typing import Iterable
37
+
38
+ import numpy as np
39
+ import torch
40
+ from torch.utils.data import Dataset
41
+
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__(
89
+ self,
90
+ data_root: str | Path,
91
+ bad_frames_path: str | Path | None = None,
92
+ tasks_json_path: str | Path | None = None,
93
+ *,
94
+ window_length: int = 16,
95
+ stride: int = 1,
96
+ window_step: int | None = None,
97
+ contact_metric: str = "mixed",
98
+ tactile_threshold: float = 0.4,
99
+ min_contact_fraction: float = 0.5,
100
+ which_sensors: str = "any",
101
+ tasks: Iterable[str] | None = None,
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
+
113
+ self.data_root = Path(data_root)
114
+ self.window_length = int(window_length)
115
+ self.stride = int(stride)
116
+ self.window_step = int(window_step) if window_step is not None else max(1, window_length // 2)
117
+ self.contact_metric = contact_metric
118
+ self.tactile_threshold = float(tactile_threshold)
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():
125
+ self.bad = json.loads(Path(bad_frames_path).read_text()).get("episodes", {})
126
+ elif skip_bad_frames and bad_frames_path is not None:
127
+ print(f"[ReactWindowDataset] WARNING: bad_frames_path={bad_frames_path} not found; not filtering.")
128
+
129
+ self.per_date = {}
130
+ if tasks_json_path is not None and Path(tasks_json_path).is_file():
131
+ tj = json.loads(Path(tasks_json_path).read_text())
132
+ for tk, td in tj.get("tasks", {}).items():
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}")
142
+ tasks = set(tasks) if tasks is not None else None
143
+ dates = set(dates) if dates is not None else None
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"]
172
+ if self.respect_active_sensors and date in self.per_date:
173
+ active = list(self.per_date[date].get("active_sensors", active))
174
+
175
+ mL = d[f"tactile_left_{self.contact_metric}"].numpy()
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]
200
+ for s, e in (bf.get("intensity_spikes", [])
201
+ + bf.get("pose_teleports_L", [])
202
+ + bf.get("pose_teleports_R", [])):
203
+ bad_mask[s:e + 1] = True
204
+
205
+ ep_idx = len(self.episodes)
206
+ self.episodes.append(d)
207
+ self.episode_paths.append(pt)
208
+ self.episode_keys.append(key)
209
+ self.episode_active.append(active)
210
+
211
+ # Enumerate windows
212
+ kept = 0
213
+ for t_start in range(0, T - span + 1, self.window_step):
214
+ t_end = t_start + span - 1
215
+ frame_idx = np.arange(t_start, t_start + span, self.stride)
216
+ if bad_mask[t_start:t_end + 1].any():
217
+ continue
218
+ frac = contact_frame[frame_idx].mean()
219
+ if frac < self.min_contact_fraction:
220
+ continue
221
+ self.windows.append((ep_idx, t_start))
222
+ kept += 1
223
+ print(f"[ReactWindowDataset] {key}: T={T}, active={active}, "
224
+ f"kept {kept} windows")
225
+
226
+ print(f"[ReactWindowDataset] total windows: {len(self.windows)} "
227
+ f"(window_length={self.window_length}, stride={self.stride}, "
228
+ f"window_step={self.window_step})")
229
+
230
+ def __len__(self) -> int:
231
+ return len(self.windows)
232
+
233
+ def __getitem__(self, idx: int) -> dict:
234
+ ep_idx, t_start = self.windows[idx]
235
+ ep = self.episodes[ep_idx]
236
+ frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride)
237
+ sample = {
238
+ "view": ep["view"][frame_idx], # (T, 3, 128, 128) uint8
239
+ "tactile_left": ep["tactile_left"][frame_idx],
240
+ "tactile_right": ep["tactile_right"][frame_idx],
241
+ "sensor_left_pose": ep["sensor_left_pose"][frame_idx], # (T, 7) f32
242
+ "sensor_right_pose": ep["sensor_right_pose"][frame_idx],
243
+ "timestamps": ep["timestamps"][frame_idx], # (T,) f64
244
+ "tactile_left_intensity": ep["tactile_left_intensity"][frame_idx],
245
+ "tactile_right_intensity": ep["tactile_right_intensity"][frame_idx],
246
+ "tactile_left_mixed": ep["tactile_left_mixed"][frame_idx],
247
+ "tactile_right_mixed": ep["tactile_right_mixed"][frame_idx],
248
+ }
249
+ # Metadata (not batched by default DataLoader because they're scalars/strings)
250
+ sample["episode"] = str(self.episode_paths[ep_idx])
251
+ sample["episode_key"] = self.episode_keys[ep_idx]
252
+ sample["frame_start"] = int(t_start)
253
+ sample["frame_end"] = int(frame_idx[-1].item())
254
+ sample["active_sensors"] = list(self.episode_active[ep_idx])
255
+ return sample
256
+
257
+
258
+ if __name__ == "__main__":
259
+ import argparse
260
+ ap = argparse.ArgumentParser()
261
+ ap.add_argument("--data_root", required=True)
262
+ ap.add_argument("--bad_frames", default=None)
263
+ ap.add_argument("--tasks_json", default=None)
264
+ ap.add_argument("--window_length", type=int, default=16)
265
+ ap.add_argument("--stride", type=int, default=1)
266
+ ap.add_argument("--window_step", type=int, default=None)
267
+ ap.add_argument("--tactile_threshold", type=float, default=0.4)
268
+ ap.add_argument("--min_contact_fraction", type=float, default=0.5)
269
+ ap.add_argument("--contact_metric", default="mixed", choices=CONTACT_METRICS)
270
+ ap.add_argument("--which_sensors", default="any", choices=["any", "both", "left", "right"])
271
+ args = ap.parse_args()
272
+ ds = ReactWindowDataset(
273
+ data_root=args.data_root,
274
+ bad_frames_path=args.bad_frames,
275
+ tasks_json_path=args.tasks_json,
276
+ window_length=args.window_length,
277
+ stride=args.stride,
278
+ window_step=args.window_step,
279
+ contact_metric=args.contact_metric,
280
+ tactile_threshold=args.tactile_threshold,
281
+ min_contact_fraction=args.min_contact_fraction,
282
+ which_sensors=args.which_sensors,
283
+ )
284
+ print(f"len(ds) = {len(ds)}")
285
+ if len(ds):
286
+ sample = ds[0]
287
+ for k, v in sample.items():
288
+ if isinstance(v, torch.Tensor):
289
+ print(f" {k:30s} {tuple(v.shape)} {v.dtype}")
290
+ else:
291
+ print(f" {k:30s} {v!r}")
figures/dataloader_examples/sample_grid.png ADDED

Git LFS Details

  • SHA256: f1435ec8b105dc8e77678ff862d81978aa683080d538731441304f8ca75f52e1
  • Pointer size: 132 Bytes
  • Size of remote file: 2.32 MB
figures/dataloader_examples/sample_window.gif ADDED

Git LFS Details

  • SHA256: c4be8fb1bfa9b50dc0dd59fbc4cb267d8cb7704958bb05bef463f786b9ae3196
  • Pointer size: 131 Bytes
  • Size of remote file: 866 kB