dagger / code /1027_run /tasks /lever2npz.py
yqi19's picture
Upload code/1027_run/tasks/lever2npz.py with huggingface_hub
f6bc083 verified
Raw History Blame Contribute Delete
2.87 kB
#!/usr/bin/env python3
"""Convert lever_sim.py output dir → ep_NNNNNN.npz in pack_zarr format.
lever_sim writes:
<out>/ur5_steps.json - list of {i,t,phase,q_mm,tip:[x,y,z],...}
<out>/ur5_cam0.mp4 - front cam (optional)
<out>/ur5_cam1.mp4 - wrist cam (optional)
We produce:
<episodes_dir>/ep_NNNNNN.npz with keys:
robot0_eef_pos (N,3) float32 -- tip xyz
robot0_eef_quat (N,3) float32 -- rotvec (constant, derived from press orientation)
robot0_gripper_qpos (N,2) float32 -- [0.0, -0.0] (gripper always closed)
action (N,7) float32 -- [eef_pos_next, eef_quat_next, gripper_next] = state[t+1]
timestamp (N,) float64
The episode is accepted only if q_at_press_end_mm <= press_q_mm (lever actually pressed).
"""
import argparse, json, os, sys, glob
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument('--src-dir', required=True, help='dir with ur5_steps.json from one lever_sim run')
ap.add_argument('--episodes-dir', required=True, help='output episodes/ dir')
ap.add_argument('--ep-idx', type=int, required=True, help='episode index for filename')
ap.add_argument('--press-q-mm', type=float, default=-50.0, help='accept if q_at_press_end <= this (mm)')
A = ap.parse_args()
steps_file = os.path.join(A.src_dir, 'ur5_steps.json')
result_file = os.path.join(A.src_dir, 'result.json')
if not os.path.exists(steps_file):
sys.exit(f"No ur5_steps.json in {A.src_dir}")
steps = json.load(open(steps_file))
if not steps:
sys.exit("ur5_steps.json is empty")
# Check result for success
if os.path.exists(result_file):
res = json.load(open(result_file))
ur5 = res.get('ur5', {})
q_end = ur5.get('q_at_press_end_mm', None)
if q_end is not None and q_end > A.press_q_mm:
sys.exit(f"Episode rejected: q_at_press_end_mm={q_end:.1f} > {A.press_q_mm:.1f}")
print(f"q_at_press_end_mm={q_end}, accepted")
tips = np.array([s['tip'] for s in steps], dtype=np.float32) # (T, 3)
T = len(tips)
if T < 2:
sys.exit(f"Too few steps: {T}")
# rotvec: constant (gripper always closed, orientation approximately fixed during press)
# Use zero rotvec as placeholder — the DP will learn from tip trajectory
rotvec = np.zeros((T, 3), dtype=np.float32)
gripper = np.zeros((T, 2), dtype=np.float32) # closed = 0 width
# state: [pos(3), rotvec(3), gripper_w(1)] -> 7D
state = np.concatenate([tips, rotvec, gripper[:, :1]], axis=1) # (T,7)
# action = state[t+1], state = state[t], both of length T-1
N = T - 1
ep = dict(
robot0_eef_pos=tips[:N],
robot0_eef_quat=rotvec[:N],
robot0_gripper_qpos=gripper[:N],
action=state[1:], # next state
timestamp=(np.arange(N) * 0.1).astype(np.float64),
)
os.makedirs(A.episodes_dir, exist_ok=True)
out = os.path.join(A.episodes_dir, f'ep_{A.ep_idx:06d}.npz')
np.savez_compressed(out, **ep)
print(f"Wrote {out} ({N} rows)")