#!/usr/bin/env python3 """Scan RoboTwin hard demos and update trajectory timestep stats tables. Reads: /share/robotwin2.0-hard///data/episode*.hdf5 → T = len(joint_action/vector) Writes: outputs/trajectory_timestep_stats.csv outputs/trajectory_timestep_stats.md """ from __future__ import annotations import argparse import csv import re from pathlib import Path import h5py import numpy as np DEFAULT_ROOT = Path("/share/robotwin2.0-hard") DEFAULT_OUT = Path(__file__).resolve().parents[1] / "outputs" def natural_key(value: object) -> list[object]: return [int(p) if p.isdigit() else p.lower() for p in re.split(r"(\d+)", str(value))] def episode_T(path: Path) -> int: with h5py.File(path, "r") as handle: if "joint_action/vector" in handle: return int(handle["joint_action/vector"].shape[0]) if "endpose/left_endpose" in handle: return int(handle["endpose/left_endpose"].shape[0]) raise KeyError(f"no known time dataset in {path}") def collect_rows(root: Path, write_logs: bool = True, force_logs: bool = False) -> list[dict]: rows: list[dict] = [] tasks = sorted([p for p in root.iterdir() if p.is_dir()], key=lambda p: natural_key(p.name)) for task_dir in tasks: demos = sorted( [p for p in task_dir.iterdir() if p.is_dir() and p.name.startswith("demo_clean")], key=lambda p: natural_key(p.name), ) for demo_dir in demos: data_dir = demo_dir / "data" if not data_dir.is_dir(): continue files = sorted(data_dir.glob("episode*.hdf5"), key=lambda p: natural_key(p.stem)) named_lengths: list[tuple[str, int]] = [] for path in files: try: named_lengths.append((path.name, episode_T(path))) except Exception as exc: # noqa: BLE001 print(f"FAIL {path}: {exc}", flush=True) if not named_lengths: continue lengths = [length for _, length in named_lengths] arr = np.asarray(lengths, dtype=np.int32) robot = demo_dir.name.replace("demo_clean_100_", "").replace("demo_clean_", "") row = { "task": task_dir.name, "demo": demo_dir.name, "robot": robot, "n_episodes": int(len(arr)), "min_T": int(arr.min()), "max_T": int(arr.max()), "mean_T": float(arr.mean()), "median_T": float(np.median(arr)), "std_T": float(arr.std()), "source": "joint_action/vector", "data_dir": str(data_dir), } rows.append(row) print( f"{row['task']:28} {row['demo']:24} n={row['n_episodes']:3d} " f"mean={row['mean_T']:7.1f}", flush=True, ) if write_logs: log_path = demo_dir / "episode_length_stats.log" if force_logs or not log_path.exists(): try: write_episode_length_stats_log(demo_dir, named_lengths) print(f" wrote {log_path}", flush=True) except OSError as exc: print(f" WARN cannot write {log_path}: {exc}", flush=True) return rows def write_csv(rows: list[dict], path: Path) -> None: fields = [ "task", "demo", "robot", "n_episodes", "min_T", "max_T", "mean_T", "median_T", "std_T", "source", "data_dir", ] with path.open("w", newline="", encoding="utf-8") as handle: writer = csv.DictWriter(handle, fieldnames=fields) writer.writeheader() for row in rows: writer.writerow( { **row, "mean_T": f"{row['mean_T']:.2f}", "median_T": f"{row['median_T']:.1f}", "std_T": f"{row['std_T']:.2f}", } ) def write_episode_length_stats_log(demo_dir: Path, lengths: list[tuple[str, int]]) -> Path: """Write per-demo episode_length_stats.log in the historical format.""" vals = [length for _, length in lengths] min_L = min(vals) max_L = max(vals) mean_L = sum(vals) / len(vals) min_eps = [name for name, length in lengths if length == min_L] max_eps = [name for name, length in lengths if length == max_L] lines = [ f"dataset: {demo_dir}", f"num_episodes: {len(lengths)}", f"min_length: {min_L}", f"max_length: {max_L}", f"mean_length: {mean_L:.2f}", f"min_episodes: {', '.join(min_eps)}", f"max_episodes: {', '.join(max_eps)}", "", "per_episode:", ] for name, length in lengths: lines.append(f" {name}: {length}") lines.append("") out = demo_dir / "episode_length_stats.log" out.write_text("\n".join(lines), encoding="utf-8") return out def write_md(rows: list[dict], path: Path) -> None: robots = sorted({r["robot"] for r in rows}, key=natural_key) tasks = sorted({r["task"] for r in rows}, key=natural_key) pivot = {(r["task"], r["robot"]): r for r in rows} lines = [ "# Trajectory timestep statistics", "", "Source: `/share/robotwin2.0-hard///data/episode*.hdf5` → `joint_action/vector` length (T).", "", "Regenerate:", "", "```bash", "cd /data/mani/progress_probe_repro", "python scripts/update_trajectory_timestep_stats.py", "```", "", f"Total combos: **{len(rows)}**", "", "## Summary (mean T)", "", "| task | " + " | ".join(robots) + " |", "| --- | " + " | ".join(["---:" for _ in robots]) + " |", ] for task in tasks: cells = [task] for robot in robots: hit = pivot.get((task, robot)) if hit is None: cells.append("") else: # mark incomplete collections note = "" if hit["n_episodes"] >= 100 else f" (n={hit['n_episodes']})" cells.append(f"{hit['mean_T']:.1f}{note}") lines.append("| " + " | ".join(cells) + " |") lines.append("") lines += ["## Per demo detail", ""] for task in tasks: lines.append(f"### {task}") lines.append("") lines.append("| demo | robot | n | min | max | mean | median | std |") lines.append("| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: |") for row in [r for r in rows if r["task"] == task]: lines.append( f"| `{row['demo']}` | {row['robot']} | {row['n_episodes']} | {row['min_T']} | " f"{row['max_T']} | {row['mean_T']:.1f} | {row['median_T']:.1f} | {row['std_T']:.1f} |" ) lines.append("") path.write_text("\n".join(lines), encoding="utf-8") def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--root", type=Path, default=DEFAULT_ROOT) parser.add_argument("--out-dir", type=Path, default=DEFAULT_OUT) parser.add_argument( "--write-logs", action=argparse.BooleanOptionalAction, default=True, help="Also write/update episode_length_stats.log under each demo dir", ) parser.add_argument( "--force-logs", action="store_true", help="Overwrite existing episode_length_stats.log files", ) args = parser.parse_args() args.out_dir.mkdir(parents=True, exist_ok=True) rows = collect_rows(args.root, write_logs=args.write_logs, force_logs=args.force_logs) csv_path = args.out_dir / "trajectory_timestep_stats.csv" md_path = args.out_dir / "trajectory_timestep_stats.md" write_csv(rows, csv_path) write_md(rows, md_path) print(f"wrote {csv_path}", flush=True) print(f"wrote {md_path}", flush=True) print(f"rows={len(rows)}", flush=True) if __name__ == "__main__": main()