"""Stage 1 — ISR: Information-Standardized Trajectory Resampling. Core algorithm derived from the OFFICIAL implementation (Apache-2.0): https://github.com/D-Robotics-AI-Lab/ISR (Yang et al., IROS 2026, arXiv:2606.22907) Functions `_velocities`, `_acceleration_magnitudes`, `_gripper_forced`, and the DP in `isr_resample` follow src/isr/{kinematics,gripper,resample_trajectory}.py of that repo, condensed into one self-contained file with our pipeline IO around it. WHAT IT DOES (paper §3, in one breath): instead of keeping every k-th frame in TIME, keep frames equally spaced in INFORMATION — info between two frames = λ_dist·(spatial distance moved) + λ_acc·(accumulated acceleration). Pauses/slow drift contribute ~0 info → collapse; fast motion and decel-before-contact are info-dense → sampled densely. A DP picks the frame subset whose consecutive info gaps are closest to d_target. Frames where the gripper changes are FORCE-kept (the one moment you can never drop). KNOBS (play with these): --d-target 0.05 target info gap between kept frames; ↑ = more compression --lambda-acc 0.01 weight of acceleration info; ↑ = keep more dynamic-change frames (paper: 0.01 pick/place, 0.03 push-T; ablation shows contact-rich tasks collapse without it) --lambda-dist 1.0 weight of spatial distance (paper keeps 1.0 always) --baseline 0 also emit a time-uniform k× downsample for comparison (0 = off) Run: python isr_resample.py # all episodes in trajs/, default knobs python isr_resample.py --d-target 0.1 --lambda-acc 0.03 python isr_resample.py --episodes 0 111 --baseline 3 Outputs: out/isr/ep{N}.npz (kept indices + resampled arrays) and out/isr/stats.json. """ import argparse, json from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent TRAJS = HERE / "trajs" OUT = HERE / "out" / "isr" # ── kinematics (from official repo src/isr/kinematics.py, forward + mean_dt methods) ── def _velocities(positions: np.ndarray, times: np.ndarray) -> np.ndarray: v = np.zeros_like(positions) dt = np.maximum(times[1:] - times[:-1], 1e-9) v[:-1] = (positions[1:] - positions[:-1]) / dt[:, None] v[-1] = v[-2] if len(v) > 1 else 0.0 return v def _acceleration_magnitudes(positions: np.ndarray, times: np.ndarray) -> np.ndarray: v = _velocities(positions, times) a = np.zeros_like(v) dt = np.maximum(times[1:] - times[:-1], 1e-9) if len(v) > 2: mean_dt = 0.5 * (dt[:-1] + dt[1:]) a[1:-1] = (v[1:-1] - v[:-2]) / mean_dt[:, None] a[0], a[-1] = a[1], a[-2] return np.linalg.norm(a, axis=1) # ── gripper forcing (from official repo src/isr/gripper.py) ── def _gripper_forced(gripper: np.ndarray | None, n: int, threshold=0.05, max_gap=20) -> list[int]: """Frames around gripper-state changes are always kept; nearby change-frames are expanded into continuous ranges so the whole open/close motion survives resampling.""" if gripper is None: return [] idx = [] for i in range(n - 1): if abs(float(gripper[i + 1]) - float(gripper[i])) > threshold: idx += [i, i + 1] idx = sorted(set(idx)) if not idx: return [] out, cs, ce = [], idx[0], idx[0] for i in idx[1:]: if i - ce <= max_gap: ce = i else: out += list(range(cs, ce + 1)); cs = ce = i out += list(range(cs, ce + 1)) return [i for i in out if 0 <= i < n] # ── the ISR DP (from official repo src/isr/resample_trajectory.py) ── def isr_resample(positions, times, gripper=None, d_target=0.05, lambda_dist=1.0, lambda_acc=0.01, gripper_threshold=0.05) -> list[int]: """Pick frame indices whose consecutive info gaps best match d_target. Info(k→i) = λ_dist·‖p_i − p_k‖ (secant, enforces spatial uniformity) + λ_acc·Σ|a| over (k..i) (dynamics inside the segment, via prefix sum). DP: cost[i] = min over k 0: acc_prefix[1:] = np.cumsum(_acceleration_magnitudes(positions, times)) cost = np.full(n, np.inf) prev = np.full(n, -1, dtype=int) cost[0] = 0.0 for i in range(1, n): # vectorized over all candidate predecessors k < i dist = np.linalg.norm(positions[i] - positions[:i], axis=1) info = lambda_dist * dist + lambda_acc * (acc_prefix[i] - acc_prefix[:i]) total = cost[:i] + (info - d_target) ** 2 k = int(np.argmin(total)) cost[i], prev[i] = total[k], k keep, i = [], n - 1 while i >= 0: keep.append(i) if i == 0: break i = int(prev[i]) keep.reverse() return sorted(set(keep + _gripper_forced(gripper, n, gripper_threshold))) def time_uniform(n: int, k: int) -> list[int]: """Baseline: keep every k-th frame (always include the last).""" idx = list(range(0, n, k)) return sorted(set(idx + [n - 1])) def run(episodes, d_target, lambda_dist, lambda_acc, baseline, gripper_threshold=0.05): OUT.mkdir(parents=True, exist_ok=True) index = json.loads((TRAJS / "index.json").read_text()) stats = {"knobs": {"d_target": d_target, "lambda_dist": lambda_dist, "lambda_acc": lambda_acc, "gripper_threshold": gripper_threshold}, "source": index["source"], "episodes": {}} files = sorted(TRAJS.glob("ep*.npz")) if episodes: files = [f for f in files if int(f.stem[2:]) in episodes] n_files = len(files) for j, f in enumerate(files): d = np.load(f) pos, ts = d["positions"], d["timestamps"] grip = d["gripper"] if "gripper" in d else None keep = isr_resample(pos, ts, grip, d_target, lambda_dist, lambda_acc, gripper_threshold) forced = _gripper_forced(grip, len(pos), gripper_threshold) save = {"keep": np.array(keep), "positions": pos[keep], "timestamps": ts[keep], "actions": d["actions"][keep], "forced": np.array(forced, dtype=int)} if grip is not None: save["gripper"] = grip[keep] np.savez(OUT / f.name, **save) st = {"frames_in": len(pos), "frames_out": len(keep), "ratio": round(len(keep) / len(pos), 3), "gripper_forced": len(forced)} if baseline: bl = time_uniform(len(pos), baseline) np.savez(OUT / f"{f.stem}_baseline{baseline}x.npz", keep=np.array(bl), positions=pos[bl], timestamps=ts[bl], actions=d["actions"][bl]) st[f"baseline_{baseline}x_frames"] = len(bl) stats["episodes"][f.stem] = st # throttle logging on big runs — every 50 + first/last if n_files <= 50 or j % 50 == 0 or j == n_files - 1: print(f" [{j+1}/{n_files}] {f.stem}: {len(pos)} -> {len(keep)} frames " f"({100*len(keep)/len(pos):.0f}% kept, {len(forced)} gripper-forced)", flush=True) ratios = [e["ratio"] for e in stats["episodes"].values()] stats["summary"] = {"episodes": n_files, "mean_kept": round(float(np.mean(ratios)), 3), "min_kept": round(float(np.min(ratios)), 3), "max_kept": round(float(np.max(ratios)), 3)} (OUT / "stats.json").write_text(json.dumps(stats, indent=2)) print(f"wrote {OUT}/stats.json | mean kept {stats['summary']['mean_kept']:.0%} " f"(range {stats['summary']['min_kept']:.0%}-{stats['summary']['max_kept']:.0%})") if __name__ == "__main__": ap = argparse.ArgumentParser(description="ISR resampling (derived from D-Robotics-AI-Lab/ISR, Apache-2.0)") ap.add_argument("--episodes", type=int, nargs="*", default=None, help="subset; default = all in trajs/") ap.add_argument("--d-target", type=float, default=0.05) ap.add_argument("--lambda-dist", type=float, default=1.0) ap.add_argument("--lambda-acc", type=float, default=0.01) ap.add_argument("--gripper-threshold", type=float, default=0.05, help="|Δgripper| that forces a keep; scale to the gripper's units (0.05 for a 0-1 channel)") ap.add_argument("--baseline", type=int, default=0, help="also write time-uniform k× baseline (0=off)") a = ap.parse_args() run(a.episodes, a.d_target, a.lambda_dist, a.lambda_acc, a.baseline, a.gripper_threshold)