Add example dataloader: ReactWindowDataset for short contact-rich window sampling + demo (static grid + GIF) with sensor-frame overlay
Browse filesFiles changed (5)
106 unmodified lines10710810911011111226 unmodified lines139140141106 unmodified lines# For 2026-03-23 recordings, also ignore the left-sensor fields (right-only pilot).```## Recording-file previewsPer-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.)26 unmodified lines## CitationIf you use this dataset, please cite (TODO: add bibtex).106 unmodified lines10710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115226 unmodified lines179180181182106 unmodified lines# For 2026-03-23 recordings, also ignore the left-sensor fields (right-only pilot).```## Example dataloader — short contact-rich windowsA 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).```pythonfrom examples.react_window_dataset import ReactWindowDatasetfrom torch.utils.data import DataLoaderds = ReactWindowDataset(data_root="processed/mode1_v1/motherboard",bad_frames_path="bad_frames.json",tasks_json_path="tasks.json",window_length=16, # frames per windowstride=1, # within-window stride (1 = consecutive)window_step=16, # step between window starts (overlap control)contact_metric="mixed", # "intensity" | "area" | "mixed"tactile_threshold=0.4,min_contact_fraction=0.6, # ≥ 60 % of window frames must have contactwhich_sensors="any", # "any" | "both" | "left" | "right"skip_bad_frames=True,respect_active_sensors=True, # mask out left modalities for 2026-03-23 pilot)print(len(ds), "windows")loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)```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`, …).### Example outputFour 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:One window played frame-by-frame with the sensor-frame overlay:Full demo script: [`examples/demo_react_window.py`](examples/demo_react_window.py).## Recording-file previewsPer-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.)26 unmodified lines## CitationIf you use this dataset, please cite (TODO: add bibtex).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261"""Demonstrate ReactWindowDataset: - build the dataset with sensible defaults - sample N random windows - render static grid PNG (N rows × 8 cols, each cell a [view | tac_L | tac_R] composite) - render one window as a GIF with sensor-frame axes projected on `view`"""import jsonimport sysfrom pathlib import Path
import cv2import numpy as npimport torchfrom PIL import Image, ImageDraw, ImageFontfrom scipy.spatial.transform import Rotation
sys.path.insert(0, "/tmp")from react_window_dataset import ReactWindowDataset
OUT = Path("/media/yxma/Disk1/twm/figures/dataloader_examples")OUT.mkdir(parents=True, exist_ok=True)
DATA_ROOT = Path("/media/yxma/Disk1/twm/processed/mode1_v1/motherboard")BAD_FRAMES = Path("/media/yxma/Disk1/twm/figures/dataset_figures/bad_frames.json")TASKS_JSON = Path("/tmp/tasks_local.json") # written below from HF
# `view` in the .pt = realsense/cam0/color, center-cropped 640→480 then resized → 128# cam0 serial = 143322063538 → T_mocap_to_cam_right.jsonCALIB_DIR = Path("/home/yxma/MultimodalData/twm/calibration/result")CAM_CALIB_FOR_VIEW = CALIB_DIR / "T_mocap_to_cam_right.json"GEL_LEFT_CALIB = CALIB_DIR / "T_gel_to_rigid_left.json"GEL_RIGHT_CALIB = CALIB_DIR / "T_gel_to_rigid_right.json"
AX_COLORS_RGB = [(0, 0, 255), (0, 255, 0), (255, 128, 0)] # X red, Y green, Z blue-ishAX_LABELS = ["X", "Y", "Z"]GEL_DOT_COLOR = {"L": (0, 255, 120), "R": (0, 180, 255)}
def load_calib(): cam = json.loads(CAM_CALIB_FOR_VIEW.read_text()) return { "T_mocap_to_cam": np.array(cam["T_mocap_to_cam"], np.float64), "intrinsics": cam["intrinsics"], "gel_left": np.array(json.loads(GEL_LEFT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64), "gel_right": np.array(json.loads(GEL_RIGHT_CALIB.read_text())["gel_center_in_rigid_mm"], np.float64), }
def pose_to_T(pose_7): """7-vec (x,y,z, qx,qy,qz,qw) in meters → 4×4 in mm.""" pos_mm = np.array(pose_7[:3], np.float64) * 1000.0 q = np.array(pose_7[3:], np.float64) q /= np.linalg.norm(q) T = np.eye(4) T[:3, :3] = Rotation.from_quat(q).as_matrix() T[:3, 3] = pos_mm return T
def project_to_view(P_world_mm, calib, *, view_size=128, orig_w=640, orig_h=480): """Project a single mocap-frame point (mm) into 128×128 view coords.
The .pt `view` was made by center-cropping cam0 from 640×480 → 480×480 and then bilinear-resizing to 128×128. We replicate that here. """ T_m2c = calib["T_mocap_to_cam"] I = calib["intrinsics"] P = (T_m2c @ np.append(P_world_mm, 1.0))[:3] if P[2] <= 0: return None u640 = I["fx"] * P[0] / P[2] + I["ppx"] v480 = I["fy"] * P[1] / P[2] + I["ppy"] crop_left = (orig_w - orig_h) / 2.0 # 80 u_in_crop = u640 - crop_left s = view_size / orig_h # 128/480 return (u_in_crop * s, v480 * s)
def project_gel_with_axes(pose_7, gel_center_mm, calib, axis_len_mm=80.0): """Return (center_uv, [(x_uv, y_uv, z_uv) or None]).""" if pose_7 is None or np.allclose(pose_7, 0.0): return None, None T_r2m = pose_to_T(pose_7) P_gel = (T_r2m @ np.append(gel_center_mm, 1.0))[:3] R = T_r2m[:3, :3] tips = [P_gel + R @ np.array([axis_len_mm, 0, 0]), P_gel + R @ np.array([0, axis_len_mm, 0]), P_gel + R @ np.array([0, 0, axis_len_mm])] center = project_to_view(P_gel, calib) if center is None: return None, None return center, [project_to_view(t, calib) for t in tips]
def to_hwc(t): return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()
def annotate_view(view_uint8, pose_L, pose_R, calib, *, scale=1): """Draw sensor axes on a (H, W, 3) RGB image. Returns annotated copy.""" H, W, _ = view_uint8.shape img = view_uint8.copy() for side, pose, gel in [("L", pose_L, calib["gel_left"]), ("R", pose_R, calib["gel_right"])]: ctr, axes = project_gel_with_axes(pose, gel, calib) if ctr is None: continue cx, cy = int(round(ctr[0])), int(round(ctr[1])) if axes is not None: for tip, c, lab in zip(axes, AX_COLORS_RGB, AX_LABELS): if tip is None: continue tx, ty = int(round(tip[0])), int(round(tip[1])) cv2.line(img, (cx, cy), (tx, ty), c, max(1, scale), cv2.LINE_AA) dot_color = GEL_DOT_COLOR[side] cv2.circle(img, (cx, cy), max(2, 3 * scale), dot_color, -1, cv2.LINE_AA) cv2.circle(img, (cx, cy), max(2, 3 * scale) + 1, (255, 255, 255), 1, cv2.LINE_AA) cv2.putText(img, side, (cx + 4, cy + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.4 * scale, dot_color, max(1, scale), cv2.LINE_AA) return img
def make_static_grid(ds, sample_indices, calib, out_path, n_cols=6, cell_scale=3): rows = [] for idx in sample_indices: s = ds[idx] T = s["view"].shape[0] pick = np.linspace(0, T - 1, n_cols).astype(int) cells = [] for t in pick: view_rgb = to_hwc(s["view"][t]).astype(np.uint8) view_rgb = annotate_view(view_rgb, s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None, s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None, calib, scale=1) tl = to_hwc(s["tactile_left"][t]) tr = to_hwc(s["tactile_right"][t]) # Stack horizontally: view | tac_L | tac_R, each 128×128 triplet = np.concatenate([view_rgb, tl, tr], axis=1) # (128, 384, 3) # Upscale for clarity triplet = cv2.resize(triplet, (triplet.shape[1] * cell_scale, triplet.shape[0] * cell_scale), interpolation=cv2.INTER_NEAREST) cells.append(triplet) rows.append(np.concatenate(cells, axis=1))
H_row = rows[0].shape[0] W_row = rows[0].shape[1] pad_y = 16 label_h = 88 # vertical label band above each row canvas_h = 60 + len(rows) * (H_row + label_h + pad_y) canvas = np.full((canvas_h, W_row + 20, 3), 245, dtype=np.uint8)
# Page header cv2.putText(canvas, f"ReactWindowDataset — {n_cols} evenly-spaced frames per sample (time runs left → right)", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (50, 50, 50), 2, cv2.LINE_AA)
cell_w = W_row // n_cols for r, idx in enumerate(sample_indices): s = ds[idx] y0 = 60 + r * (H_row + label_h + pad_y) # Sample label band ep = s["episode_key"] dur_s = float(s["timestamps"][-1] - s["timestamps"][0]) mL = float(s["tactile_left_mixed"].max()) mR = float(s["tactile_right_mixed"].max()) 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}", (10, y0 + 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA) # Per-cell time labels T = s["view"].shape[0] pick = np.linspace(0, T - 1, n_cols).astype(int) for c, t in enumerate(pick): cv2.putText(canvas, f"t = {int(t)} (frame {s['frame_start'] + int(t)})", (10 + c * cell_w + 8, y0 + 56), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (90, 90, 90), 1, cv2.LINE_AA) cv2.putText(canvas, "view | tactile_left | tactile_right", (10, y0 + 76), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (130, 130, 130), 1, cv2.LINE_AA) # Place row canvas[y0 + label_h:y0 + label_h + H_row, 10:10 + W_row] = rows[r]
Image.fromarray(canvas).save(out_path) print(f" static -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
def make_gif(ds, sample_idx, calib, out_path, *, panel_scale=3, fps=15): s = ds[sample_idx] T = s["view"].shape[0] frames = [] for t in range(T): view_rgb = to_hwc(s["view"][t]).astype(np.uint8) view_ann = annotate_view(view_rgb, s["sensor_left_pose"][t].numpy() if "left" in s["active_sensors"] else None, s["sensor_right_pose"][t].numpy() if "right" in s["active_sensors"] else None, calib, scale=1) # Upscale each subpanel view_big = cv2.resize(view_ann, (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST) tl_big = cv2.resize(to_hwc(s["tactile_left"][t]), (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST) tr_big = cv2.resize(to_hwc(s["tactile_right"][t]), (128 * panel_scale, 128 * panel_scale), cv2.INTER_NEAREST) triplet = np.concatenate([view_big, tl_big, tr_big], axis=1) # Header strip with frame counter H, W, _ = triplet.shape header = np.full((36, W, 3), 230, dtype=np.uint8) text = f"{s['episode_key']} frame {s['frame_start'] + t}/{s['frame_end']} ({t+1}/{T}) | view | tactile_L | tactile_R" cv2.putText(header, text, (8, 24), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA) panel = np.concatenate([header, triplet], axis=0) frames.append(panel)
# Shared-palette GIF pil = [Image.fromarray(f) for f in frames] mosaic = Image.new("RGB", (pil[0].width * min(8, len(pil)), pil[0].height)) for i, im in enumerate(pil[: min(8, len(pil))]): mosaic.paste(im, (i * pil[0].width, 0)) pal = mosaic.quantize(colors=128, method=Image.MEDIANCUT, dither=Image.NONE) qframes = [im.quantize(palette=pal, dither=Image.NONE) for im in pil] qframes[0].save(out_path, save_all=True, append_images=qframes[1:], duration=int(round(1000 / fps)), loop=0, optimize=True, disposal=0) print(f" gif -> {out_path} ({out_path.stat().st_size / 1024:.1f} KB)")
def main(): # tasks.json was pre-fetched to TASKS_JSON via the base env if not TASKS_JSON.exists(): raise FileNotFoundError(f"{TASKS_JSON} missing; fetch from yxma/React first") calib = load_calib()
print("=== Build dataset ===") ds = ReactWindowDataset( data_root=DATA_ROOT, bad_frames_path=BAD_FRAMES, tasks_json_path=TASKS_JSON, window_length=16, stride=1, window_step=16, contact_metric="mixed", tactile_threshold=0.4, min_contact_fraction=0.6, which_sensors="any", skip_bad_frames=True, respect_active_sensors=True, )
rng = np.random.default_rng(42) pick = rng.choice(len(ds), 4, replace=False) print(f"\n=== Render 4 random samples ===") make_static_grid(ds, pick, calib, OUT / "sample_grid.png") print(f"\n=== Render one as GIF ===") make_gif(ds, int(pick[0]), calib, OUT / "sample_window.gif")
print("\nSample dict shapes (sample 0):") s = ds[int(pick[0])] for k, v in s.items(): if isinstance(v, torch.Tensor): print(f" {k:30s} {tuple(v.shape)} {v.dtype}") else: print(f" {k:30s} {v!r}")
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291"""React: short-horizon contact-rich window dataset.
A PyTorch `Dataset` that yields short multimodal windows sampled from theReact recordings, filtered to be contact-rich and free of known data-qualityissues. Intended for tactile-visual dynamics / world-model learning.
Usage-----```pythonfrom react_window_dataset import ReactWindowDatasetfrom torch.utils.data import DataLoader
ds = ReactWindowDataset( data_root="processed/mode1_v1/motherboard", bad_frames_path="bad_frames.json", tasks_json_path="tasks.json", window_length=16, # frames per window stride=1, # within-window frame stride (1 = consecutive) window_step=8, # step between window start indices contact_metric="mixed", # which tactile metric to threshold on tactile_threshold=0.4, min_contact_fraction=0.5, # ≥ 50% of window frames must have contact which_sensors="any", # "any" | "both" | "left" | "right" skip_bad_frames=True, respect_active_sensors=True, # mask out left modalities for right-only pilot)loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)```
Each sample is a dict of `(T, ...)` tensors plus metadata."""from __future__ import annotations
import jsonfrom pathlib import Pathfrom typing import Iterable
import numpy as npimport torchfrom torch.utils.data import Dataset
CONTACT_METRICS = ("intensity", "area", "mixed")
class ReactWindowDataset(Dataset): """Per-window dataset over the React recordings.
Parameters ---------- data_root : path Directory containing `<task>/<date>/episode_*.pt` files. Searched recursively. bad_frames_path : optional path `bad_frames.json` (the shipped skip-list). If None, no quality filter. tasks_json_path : optional path `tasks.json`. Used for `respect_active_sensors` mode. window_length : int Number of frames per sample. stride : int Frame stride within a window. `stride=1` → consecutive frames, `stride=2` → every other source frame, etc. Span of a window in source-frame indices = `(window_length - 1) * stride + 1`. window_step : int, default `window_length // 2` Step between window start indices within an episode. Controls overlap between adjacent windows. contact_metric : {"intensity", "area", "mixed"} Which per-frame tactile metric to threshold on. tactile_threshold : float Minimum value of the chosen metric to count as contact. min_contact_fraction : float in [0, 1] A window is kept only if at least this fraction of its frames satisfy the contact predicate. which_sensors : {"any", "both", "left", "right"} How left + right sensors combine when checking the predicate. tasks, dates : optional iterables of str Filter episodes by task name and/or date string. skip_bad_frames : bool If True, drop windows whose source-frame span overlaps any flagged interval in `bad_frames.json`. respect_active_sensors : bool If True (and `tasks.json` has per-date `active_sensors`), windows on right-only recordings (2026-03-23 pilot) auto-fallback to right-only contact predicate, and the returned sample carries an `active_sensors` field so dataloaders can mask the inactive modalities. """
def __init__( self, data_root: str | Path, bad_frames_path: str | Path | None = None, tasks_json_path: str | Path | None = None, *, window_length: int = 16, stride: int = 1, window_step: int | None = None, contact_metric: str = "mixed", tactile_threshold: float = 0.4, min_contact_fraction: float = 0.5, which_sensors: str = "any", tasks: Iterable[str] | None = None, dates: Iterable[str] | None = None, skip_bad_frames: bool = True, respect_active_sensors: bool = True, ): if contact_metric not in CONTACT_METRICS: raise ValueError(f"contact_metric must be one of {CONTACT_METRICS}") if which_sensors not in ("any", "both", "left", "right"): raise ValueError("which_sensors must be 'any' | 'both' | 'left' | 'right'") if window_length < 1 or stride < 1: raise ValueError("window_length and stride must be ≥ 1")
self.data_root = Path(data_root) self.window_length = int(window_length) self.stride = int(stride) self.window_step = int(window_step) if window_step is not None else max(1, window_length // 2) self.contact_metric = contact_metric self.tactile_threshold = float(tactile_threshold) self.min_contact_fraction = float(min_contact_fraction) self.which_sensors = which_sensors self.respect_active_sensors = bool(respect_active_sensors)
self.bad = {} if bad_frames_path is not None and Path(bad_frames_path).is_file(): self.bad = json.loads(Path(bad_frames_path).read_text()).get("episodes", {}) elif skip_bad_frames and bad_frames_path is not None: print(f"[ReactWindowDataset] WARNING: bad_frames_path={bad_frames_path} not found; not filtering.")
self.per_date = {} if tasks_json_path is not None and Path(tasks_json_path).is_file(): tj = json.loads(Path(tasks_json_path).read_text()) for tk, td in tj.get("tasks", {}).items(): for d, info in td.get("per_date_notes", {}).items(): self.per_date[d] = info
self.skip_bad_frames = bool(skip_bad_frames)
# Discover episodes pt_files = sorted(self.data_root.rglob("episode_*.pt")) if not pt_files: raise RuntimeError(f"No episode_*.pt under {self.data_root}") tasks = set(tasks) if tasks is not None else None dates = set(dates) if dates is not None else None
self.episodes: list[dict] = [] self.episode_paths: list[Path] = [] self.episode_keys: list[str] = [] # "<date>/<stem>" for bad_frames lookup self.episode_active: list[list[str]] = [] self.windows: list[tuple[int, int]] = [] # (ep_idx, t_start)
span = (self.window_length - 1) * self.stride + 1 # source-frame span
for pt in pt_files: rel = pt.relative_to(self.data_root) # rel.parts == (<task>, <date>, "episode_NNN.pt") OR (<date>, ...) if len(rel.parts) == 3: task, date, _ = rel.parts key = f"{date}/{pt.stem}" elif len(rel.parts) == 2: task, date = None, rel.parts[0] key = f"{date}/{pt.stem}" else: task, date, key = None, None, pt.stem
if tasks is not None and task not in tasks: continue if dates is not None and date not in dates: continue
d = torch.load(pt, weights_only=False, map_location="cpu") active = ["left", "right"] if self.respect_active_sensors and date in self.per_date: active = list(self.per_date[date].get("active_sensors", active))
mL = d[f"tactile_left_{self.contact_metric}"].numpy() mR = d[f"tactile_right_{self.contact_metric}"].numpy() T = mL.shape[0]
# Per-frame contact predicate respecting which_sensors and active_sensors cL = mL > self.tactile_threshold cR = mR > self.tactile_threshold if "left" not in active: cL = np.zeros_like(cL) if "right" not in active: cR = np.zeros_like(cR) req = self.which_sensors if req == "any": contact_frame = cL | cR elif req == "both": contact_frame = cL & cR elif req == "left": contact_frame = cL else: contact_frame = cR
# Bad-frame mask bad_mask = np.zeros(T, dtype=bool) if self.skip_bad_frames and key in self.bad: bf = self.bad[key] for s, e in (bf.get("intensity_spikes", []) + bf.get("pose_teleports_L", []) + bf.get("pose_teleports_R", [])): bad_mask[s:e + 1] = True
ep_idx = len(self.episodes) self.episodes.append(d) self.episode_paths.append(pt) self.episode_keys.append(key) self.episode_active.append(active)
# Enumerate windows kept = 0 for t_start in range(0, T - span + 1, self.window_step): t_end = t_start + span - 1 frame_idx = np.arange(t_start, t_start + span, self.stride) if bad_mask[t_start:t_end + 1].any(): continue frac = contact_frame[frame_idx].mean() if frac < self.min_contact_fraction: continue self.windows.append((ep_idx, t_start)) kept += 1 print(f"[ReactWindowDataset] {key}: T={T}, active={active}, " f"kept {kept} windows")
print(f"[ReactWindowDataset] total windows: {len(self.windows)} " f"(window_length={self.window_length}, stride={self.stride}, " f"window_step={self.window_step})")
def __len__(self) -> int: return len(self.windows)
def __getitem__(self, idx: int) -> dict: ep_idx, t_start = self.windows[idx] ep = self.episodes[ep_idx] frame_idx = torch.arange(t_start, t_start + self.window_length * self.stride, self.stride) sample = { "view": ep["view"][frame_idx], # (T, 3, 128, 128) uint8 "tactile_left": ep["tactile_left"][frame_idx], "tactile_right": ep["tactile_right"][frame_idx], "sensor_left_pose": ep["sensor_left_pose"][frame_idx], # (T, 7) f32 "sensor_right_pose": ep["sensor_right_pose"][frame_idx], "timestamps": ep["timestamps"][frame_idx], # (T,) f64 "tactile_left_intensity": ep["tactile_left_intensity"][frame_idx], "tactile_right_intensity": ep["tactile_right_intensity"][frame_idx], "tactile_left_mixed": ep["tactile_left_mixed"][frame_idx], "tactile_right_mixed": ep["tactile_right_mixed"][frame_idx], } # Metadata (not batched by default DataLoader because they're scalars/strings) sample["episode"] = str(self.episode_paths[ep_idx]) sample["episode_key"] = self.episode_keys[ep_idx] sample["frame_start"] = int(t_start) sample["frame_end"] = int(frame_idx[-1].item()) sample["active_sensors"] = list(self.episode_active[ep_idx]) return sample
if __name__ == "__main__": import argparse ap = argparse.ArgumentParser() ap.add_argument("--data_root", required=True) ap.add_argument("--bad_frames", default=None) ap.add_argument("--tasks_json", default=None) ap.add_argument("--window_length", type=int, default=16) ap.add_argument("--stride", type=int, default=1) ap.add_argument("--window_step", type=int, default=None) ap.add_argument("--tactile_threshold", type=float, default=0.4) ap.add_argument("--min_contact_fraction", type=float, default=0.5) ap.add_argument("--contact_metric", default="mixed", choices=CONTACT_METRICS) ap.add_argument("--which_sensors", default="any", choices=["any", "both", "left", "right"]) args = ap.parse_args() ds = ReactWindowDataset( data_root=args.data_root, bad_frames_path=args.bad_frames, tasks_json_path=args.tasks_json, window_length=args.window_length, stride=args.stride, window_step=args.window_step, contact_metric=args.contact_metric, tactile_threshold=args.tactile_threshold, min_contact_fraction=args.min_contact_fraction, which_sensors=args.which_sensors, ) print(f"len(ds) = {len(ds)}") if len(ds): sample = ds[0] for k, v in sample.items(): if isinstance(v, torch.Tensor): print(f" {k:30s} {tuple(v.shape)} {v.dtype}") else: print(f" {k:30s} {v!r}")README.md+41
examples/demo_react_window.pyAdded+261
examples/react_window_dataset.pyAdded+291
figures/dataloader_examples/sample_grid.pngAdded

Large File Pointer Details
- SHA256: f1435ec8b105dc8e77678ff862d81978aa683080d538731441304f8ca75f52e1
- Pointer size: 132 Bytes
- Size of remote file: 2.32 MB
figures/dataloader_examples/sample_window.gifAdded

Large File Pointer Details
- SHA256: c4be8fb1bfa9b50dc0dd59fbc4cb267d8cb7704958bb05bef463f786b9ae3196
- Pointer size: 131 Bytes
- Size of remote file: 866 kB