Download simulation/scripts/probe_wrist_tracking.py from hk239/v2d: direct link, hf CLI and curl.
- Browser
- Download file 9.61 kB
-
https://huggingface.co/datasets/hk239/v2d/resolve/main/simulation/scripts/probe_wrist_tracking.py
- Command line
-
hf download hf://datasets/hk239/v2d/simulation/scripts/probe_wrist_tracking.py
-
curl -L -o probe_wrist_tracking.py https://huggingface.co/datasets/hk239/v2d/resolve/main/simulation/scripts/probe_wrist_tracking.py
9.61 kB
| #!/usr/bin/env python3 | |
| """How accurately does SONIC track a commanded right-wrist VR target? | |
| The planned manipulation policy acts by moving that target, so its steady-state | |
| tracking error is the floor on grasp precision -- a policy cannot place the hand | |
| better than the controller beneath it. This sweeps a grid of targets in the | |
| pelvis frame, holds each until the arm settles, and reports commanded vs | |
| achieved. The reachable subset also bounds where objects may be spawned. | |
| Legs are given a constant standing reference (teleop mode), so any base motion | |
| is SONIC reacting to the arm, not commanded locomotion. | |
| cd simulation | |
| ./run_isaaclab.sh --python scripts/probe_wrist_tracking.py --headless | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import sys | |
| from pathlib import Path | |
| from isaaclab.app import AppLauncher | |
| if hasattr(sys.stdout, "reconfigure"): | |
| sys.stdout.reconfigure(line_buffering=True) | |
| _PROJECT = Path(__file__).resolve().parents[2] | |
| _DEFAULT_CKPT = _PROJECT / "checkpoints" / "sonic" / "sonic_v1_1" | |
| parser = argparse.ArgumentParser(description="SONIC wrist-target tracking accuracy.") | |
| parser.add_argument("--checkpoint", type=Path, default=_DEFAULT_CKPT) | |
| parser.add_argument("--hands", choices=("dex3", "inspire", "wuji"), default="wuji") | |
| parser.add_argument("--hold", type=int, default=100, help="control steps per target (50 Hz)") | |
| parser.add_argument("--settle", type=int, default=25, help="steps averaged at the end of each hold") | |
| parser.add_argument( | |
| "--x", type=float, nargs="+", default=[0.25, 0.40, 0.55], help="forward, pelvis frame" | |
| ) | |
| parser.add_argument("--y", type=float, nargs="+", default=[-0.30, -0.15, 0.0], help="lateral") | |
| parser.add_argument("--z", type=float, nargs="+", default=[-0.05, 0.10, 0.25], help="vertical") | |
| parser.add_argument("--output", type=Path, default=None, help="npz of the raw results") | |
| AppLauncher.add_app_launcher_args(parser) | |
| args_cli = parser.parse_args() | |
| app_launcher = AppLauncher(args_cli) | |
| simulation_app = app_launcher.app | |
| import numpy as np # noqa: E402 | |
| import torch # noqa: E402 | |
| import isaaclab.sim as sim_utils # noqa: E402 | |
| from isaaclab.assets import Articulation # noqa: E402 | |
| from isaaclab.sim import SimulationContext # noqa: E402 | |
| from v2d_sim.sonic import ( # noqa: E402 | |
| ACTION_CLIP, | |
| DEFAULT_ANGLES, | |
| G1_ACTION_SCALE, | |
| G1_SONIC_JOINT_NAMES, | |
| NUM_JOINTS, | |
| History, | |
| SonicOnnxAgent, | |
| pack_decoder, | |
| pack_encoder, | |
| vr3_local_from_bodies, | |
| ) | |
| from v2d_sim.sonic.robot_cfg import g1_sonic_articulation_cfg # noqa: E402 | |
| _CTRL_DT = 0.02 | |
| _SIM_DT = 0.005 | |
| _DECIMATION = 4 | |
| _PELVIS_Z = 0.78 | |
| def _np(x) -> np.ndarray: | |
| if hasattr(x, "detach"): | |
| return x.detach().cpu().numpy() | |
| return np.asarray(x) | |
| def _row(x) -> np.ndarray: | |
| a = np.asarray(_np(x), dtype=np.float64) | |
| return a[0] if a.ndim >= 2 else a | |
| def _xyzw_to_wxyz(q: np.ndarray) -> np.ndarray: | |
| q = np.asarray(q, dtype=np.float64) | |
| return np.stack([q[..., 3], q[..., 0], q[..., 1], q[..., 2]], axis=-1) | |
| def main() -> None: | |
| ckpt = args_cli.checkpoint.resolve() | |
| agent = SonicOnnxAgent(ckpt) | |
| sim = SimulationContext(sim_utils.SimulationCfg(dt=_SIM_DT, device=args_cli.device)) | |
| sim_utils.GroundPlaneCfg().func("/World/Ground", sim_utils.GroundPlaneCfg()) | |
| sim_utils.DomeLightCfg(intensity=2000.0).func( | |
| "/World/Light", sim_utils.DomeLightCfg(intensity=2000.0) | |
| ) | |
| robot = Articulation( | |
| g1_sonic_articulation_cfg("/World/Robot", init_pos=(0.0, 0.0, _PELVIS_Z), hands=args_cli.hands) | |
| ) | |
| sim.reset() | |
| device = sim.device | |
| names = list(robot.joint_names) | |
| sonic_ids = [names.index(n) for n in G1_SONIC_JOINT_NAMES] | |
| default = np.asarray(DEFAULT_ANGLES, dtype=np.float64) | |
| scale = np.asarray(G1_ACTION_SCALE, dtype=np.float64) | |
| q0 = np.zeros(len(names), dtype=np.float64) | |
| q0[sonic_ids] = default | |
| robot.write_root_pose_to_sim_index( | |
| root_pose=torch.tensor( | |
| [[0.0, 0.0, _PELVIS_Z, 0.0, 0.0, 0.0, 1.0]], dtype=torch.float32, device=device | |
| ) | |
| ) | |
| robot.write_root_velocity_to_sim_index(root_velocity=torch.zeros(1, 6, device=device)) | |
| robot.write_joint_state_to_sim_index( | |
| position=torch.tensor(q0, dtype=torch.float32, device=device).unsqueeze(0), | |
| velocity=torch.zeros(1, len(names), device=device), | |
| full_data=True, | |
| ) | |
| robot.write_data_to_sim() | |
| sim.step() | |
| robot.update(_SIM_DT) | |
| def proprio(): | |
| q = _row(robot.data.joint_pos)[sonic_ids] | |
| dq = _row(robot.data.joint_vel)[sonic_ids] | |
| return ( | |
| q, | |
| dq, | |
| _row(robot.data.root_ang_vel_b), | |
| _row(robot.data.projected_gravity_b), | |
| _row(robot.data.root_pos_w), | |
| _xyzw_to_wxyz(_row(robot.data.root_quat_w)), | |
| ) | |
| def measure(pelvis_pos, pelvis_quat): | |
| bp = np.asarray(_np(robot.data.body_pos_w), dtype=np.float64) | |
| bq = _xyzw_to_wxyz(np.asarray(_np(robot.data.body_quat_w), dtype=np.float64)) | |
| if bp.ndim == 3: | |
| bp, bq = bp[0], bq[0] | |
| return vr3_local_from_bodies(robot.body_names, bp, bq, pelvis_pos, pelvis_quat) | |
| # Constant standing reference: one frame, so every future index clamps to it. | |
| ref_q = default[None, :].copy() | |
| ref_dq = np.zeros((1, NUM_JOINTS), dtype=np.float64) | |
| ref_quat = np.array([[1.0, 0.0, 0.0, 0.0]], dtype=np.float64) | |
| hist = History() | |
| last_action = np.zeros(NUM_JOINTS, dtype=np.float32) | |
| q, dq, ang, grav, pos, quat = proprio() | |
| hist.fill(ang_vel=ang, q_rel=q - default, dq=dq, action=last_action, gravity=grav) | |
| stand_pos, stand_quat = measure(pos, quat) | |
| print(f"[probe] hands={args_cli.hands} joints={len(names)} sonic={len(sonic_ids)}", flush=True) | |
| print( | |
| f"[probe] standing wrist R = {np.array2string(stand_pos[1], precision=3)}" | |
| f" (pelvis frame) root_z={pos[2]:.3f}", | |
| flush=True, | |
| ) | |
| targets = np.array([[x, y, z] for x in args_cli.x for y in args_cli.y for z in args_cli.z]) | |
| print(f"[probe] {len(targets)} targets, {args_cli.hold} steps each\n", flush=True) | |
| print(f"{'commanded (x,y,z)':>26s} {'achieved':>26s} {'err':>7s} {'root_z':>7s} {'drift':>7s}") | |
| achieved = np.zeros_like(targets) | |
| errors = np.zeros(len(targets)) | |
| root_zs = np.zeros(len(targets)) | |
| drifts = np.zeros(len(targets)) | |
| vr_pos = np.tile(stand_pos, (1, 1, 1)) | |
| vr_quat = np.tile(stand_quat, (1, 1, 1)) | |
| for i, target in enumerate(targets): | |
| vr_pos[0, 1] = target | |
| tail: list[np.ndarray] = [] | |
| for step in range(args_cli.hold): | |
| if not simulation_app.is_running(): | |
| break | |
| q, dq, ang, grav, pos, quat = proprio() | |
| enc = pack_encoder( | |
| mode="teleop", | |
| t=0, | |
| joint_pos=ref_q, | |
| joint_vel=ref_dq, | |
| ref_quat_wxyz=ref_quat, | |
| robot_quat_wxyz=quat, | |
| vr_local_pos=vr_pos, | |
| vr_local_quat=vr_quat, | |
| ) | |
| action = np.clip(agent.decode(pack_decoder(agent.encode(enc), hist)), -ACTION_CLIP, ACTION_CLIP) | |
| last_action = action.astype(np.float32) | |
| robot.set_joint_position_target_index( | |
| target=torch.tensor( | |
| default + scale * last_action, dtype=torch.float32, device=device | |
| ).unsqueeze(0), | |
| joint_ids=sonic_ids, | |
| ) | |
| robot.write_data_to_sim() | |
| for _ in range(_DECIMATION): | |
| sim.step() | |
| robot.update(_SIM_DT) | |
| q, dq, ang, grav, pos, quat = proprio() | |
| hist.push(ang_vel=ang, q_rel=q - default, dq=dq, action=last_action, gravity=grav) | |
| if step >= args_cli.hold - args_cli.settle: | |
| tail.append(measure(pos, quat)[0][1]) | |
| got = np.mean(tail, axis=0) if tail else np.full(3, np.nan) | |
| achieved[i] = got | |
| errors[i] = float(np.linalg.norm(got - target)) | |
| root_zs[i] = pos[2] | |
| # Spread over the averaging window: large means it never settled. | |
| drifts[i] = float(np.linalg.norm(np.ptp(np.asarray(tail), axis=0))) if tail else np.nan | |
| print( | |
| f"{np.array2string(target, precision=3, floatmode='fixed'):>26s} " | |
| f"{np.array2string(got, precision=3, floatmode='fixed'):>26s} " | |
| f"{errors[i]:7.4f} {root_zs[i]:7.3f} {drifts[i]:7.4f}", | |
| flush=True, | |
| ) | |
| ok = root_zs > 0.6 | |
| print(f"\n[probe] {int(ok.sum())}/{len(targets)} targets kept the robot standing (root_z > 0.6)") | |
| if ok.any(): | |
| e = errors[ok] | |
| print( | |
| f"[probe] tracking error over those: median {np.median(e):.4f} m " | |
| f"mean {e.mean():.4f} m p90 {np.percentile(e, 90):.4f} m max {e.max():.4f} m" | |
| ) | |
| best = int(np.argmin(np.where(ok, errors, np.inf))) | |
| worst = int(np.argmax(np.where(ok, errors, -np.inf))) | |
| print(f"[probe] best {np.array2string(targets[best], precision=2)} -> {errors[best]:.4f} m") | |
| print(f"[probe] worst {np.array2string(targets[worst], precision=2)} -> {errors[worst]:.4f} m") | |
| if args_cli.output: | |
| args_cli.output.parent.mkdir(parents=True, exist_ok=True) | |
| np.savez( | |
| args_cli.output, | |
| targets=targets, | |
| achieved=achieved, | |
| errors=errors, | |
| root_z=root_zs, | |
| drift=drifts, | |
| stand_wrist=stand_pos[1], | |
| ) | |
| print(f"[probe] wrote {args_cli.output}") | |
| if __name__ == "__main__": | |
| main() | |
| simulation_app.close() | |