File size: 8,171 Bytes
6077747 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 | #!/usr/bin/env python3
"""Scan RoboTwin hard demos and update trajectory timestep stats tables.
Reads:
/share/robotwin2.0-hard/<task>/<demo>/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/<task>/<demo>/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()
|