#!/usr/bin/env python3 """Drive V2D-G1-SonicManip with a scripted pick, before any training. A learned policy failing tells you nothing about whether the environment is sound. This runs an open-loop reach / close / lift schedule instead, so the question is narrow: with a sensible action sequence, does the robot stay up, does SONIC put the hand where it was told, and does the object come off the table? Anything that fails here would have failed silently during training. cd simulation ./run_isaaclab.sh --python scripts/smoke_sonic_manip.py --headless """ from __future__ import annotations import argparse import os import sys import traceback from pathlib import Path from isaaclab.app import AppLauncher if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(line_buffering=True) parser = argparse.ArgumentParser(description="Scripted-pick smoke test for the SONIC manip env.") parser.add_argument("--task", type=str, default="V2D-G1-SonicManip-Play-v0") parser.add_argument("--num_envs", type=int, default=4) parser.add_argument("--steps", type=int, default=150) parser.add_argument("--video", type=Path, default=None, help="optional MP4 of env 0") parser.add_argument("--fps", type=float, default=25.0) AppLauncher.add_app_launcher_args(parser) args_cli = parser.parse_args() if args_cli.video: args_cli.enable_cameras = True app_launcher = AppLauncher(args_cli) simulation_app = app_launcher.app import gymnasium as gym # noqa: E402 import numpy as np # noqa: E402 import torch # noqa: E402 from isaaclab.utils.math import quat_apply # noqa: E402 from isaaclab_tasks.utils import parse_env_cfg # noqa: E402 import v2d_sim # noqa: E402, F401 from v2d_sim.tasks.g1_sonic_manip.mdp.observations import t as _t # noqa: E402 # Observation layout from PolicyObsCfg, in declaration order. _GRAV, _WRIST, _OBJ, _DELTA, _OBJV, _GRIP = ( slice(0, 3), slice(3, 6), slice(6, 9), slice(9, 12), slice(12, 15), slice(15, 16), ) #: Long enough for a marginally balanced object to visibly roll or topple. _SETTLE_STEPS = 20 def _object_repose(obj) -> tuple[torch.Tensor, torch.Tensor]: """Object position and how far its up axis leans off vertical, in degrees. The can's up axis is body +y: the reconstructed mesh is y-up, which is the whole reason its spawn rotation matters. """ pos = _t(obj.data.root_pos_w).clone() quat = _t(obj.data.root_quat_w) body_up = torch.tensor([0.0, 1.0, 0.0], device=quat.device).expand(quat.shape[0], 3) up_w = quat_apply(quat, body_up) return pos, torch.rad2deg(torch.arccos(up_w[:, 2].clamp(-1.0, 1.0))) def _rgb(img) -> np.ndarray | None: if img is None: return None if hasattr(img, "detach"): img = img.detach().cpu().numpy() img = np.asarray(img) if img.ndim == 4: img = img[0] img = img[..., :3] if img.dtype != np.uint8: scale = 255.0 if float(np.nanmax(img)) <= 1.5 else 1.0 img = np.clip(img * scale, 0, 255).astype(np.uint8) h, w = img.shape[:2] return img[: h - (h % 2), : w - (w % 2)] def main() -> None: env_cfg = parse_env_cfg(args_cli.task, device=args_cli.device, num_envs=args_cli.num_envs) render = "rgb_array" if args_cli.video else None env = gym.make(args_cli.task, cfg=env_cfg, render_mode=render) inner = env.unwrapped obs_dict, _ = env.reset() obs = obs_dict["policy"] acfg = env_cfg.actions.wrist lo = torch.tensor( [acfg.wrist_x[0], acfg.wrist_y[0], acfg.wrist_z[0]], device=inner.device ) hi = torch.tensor( [acfg.wrist_x[1], acfg.wrist_y[1], acfg.wrist_z[1]], device=inner.device ) center, half = (lo + hi) / 2.0, (hi - lo) / 2.0 robot = inner.scene["robot"] obj = inner.scene["object"] table_top = env_cfg.scene.table.init_state.pos[2] + 0.5 * env_cfg.scene.table.spawn.size[2] # Height gained is measured from the resting pose, not the table top: the # object origin already sits half an object-height above the table. rest_z = env_cfg.scene.object.init_state.pos[2] print(f"[smoke] task={args_cli.task} envs={inner.num_envs} device={inner.device}") print(f"[smoke] obs dim={obs.shape[1]} action dim={inner.action_manager.total_action_dim}") print(f"[smoke] joints={len(robot.joint_names)} table_top_z={table_top:.3f}") print(f"[smoke] object rests at z={rest_z:.3f} ({rest_z - table_top:.3f} above the table)") print(f"[smoke] wrist box x{tuple(acfg.wrist_x)} y{tuple(acfg.wrist_y)} z{tuple(acfg.wrist_z)}") print(f"[smoke] object start (pelvis frame) = {obs[0, _OBJ].tolist()}") # Does the can sit still before anything touches it? A wrong spawn rotation # leaves it balanced on a curved side, which the run summary cannot # distinguish from a grasp that knocked it over. p0, tilt0 = _object_repose(obj) hold = torch.zeros(inner.num_envs, 4, device=inner.device) hold[:, 2] = 1.0 # wrist parked at the top of its box, clear of the object hold[:, 3] = -1.0 for _ in range(_SETTLE_STEPS): env.step(hold) p1, tilt1 = _object_repose(obj) drift = torch.norm((p1 - p0)[:, :2], dim=1) print( f"[smoke] untouched for {_SETTLE_STEPS} steps: xy drift {drift.max():.4f} m, " f"tilt {tilt0.max():.1f} -> {tilt1.max():.1f} deg from vertical " "(firm if drift < ~5 mm and tilt stays put)" ) obs_dict, _ = env.reset() obs = obs_dict["policy"] n = args_cli.steps reach_end, close_end = int(0.40 * n), int(0.55 * n) frames: list[np.ndarray] = [] log: list[tuple[int, float, float, float, float, float]] = [] min_root_z = float("inf") for i in range(n): if not simulation_app.is_running(): break object_b = obs[:, _OBJ] want = object_b.clone() if i < reach_end: # Approach from slightly above, so the hand does not sweep the # object sideways off the table on the way in. want[:, 2] += 0.06 * (1.0 - i / max(1, reach_end)) grip = -1.0 elif i < close_end: grip = -1.0 + 2.0 * (i - reach_end) / max(1, close_end - reach_end) else: lift = (i - close_end) / max(1, n - close_end) want[:, 2] += 0.18 * lift grip = 1.0 a = torch.clamp((want - center) / half, -1.0, 1.0) action = torch.cat([a, torch.full_like(a[:, :1], grip)], dim=1) obs_dict, rew, term, trunc, _ = env.step(action) obs = obs_dict["policy"] root_z = robot.data.root_pos_w[:, 2] min_root_z = min(min_root_z, float(root_z.min())) if args_cli.video: fr = _rgb(inner.render()) if fr is not None: frames.append(fr) if i % 10 == 0 or i == n - 1: err = torch.norm(obs[:, _DELTA], dim=1).mean().item() lifted = (obj.data.root_pos_w[:, 2] - rest_z).mean().item() log.append( ( i, float(root_z.min()), err, lifted, float(rew.mean()), float((term | trunc).float().sum()), ) ) print(f"\n{'step':>5} {'min root_z':>11} {'hand-obj':>9} {'lift vs rest':>13} {'reward':>8} {'done':>5}") for row in log: print(f"{row[0]:5d} {row[1]:11.3f} {row[2]:9.3f} {row[3]:13.3f} {row[4]:8.3f} {row[5]:5.0f}") final_lift = (obj.data.root_pos_w[:, 2] - rest_z).detach().cpu().numpy() print(f"\n[smoke] min root_z over the run: {min_root_z:.3f} (fell if < 0.5)") print(f"[smoke] final lift above rest, per env: {np.round(final_lift, 3).tolist()}") print(f"[smoke] picked up (>3 cm above rest): {int((final_lift > 0.03).sum())}/{len(final_lift)}") if args_cli.video and frames: out = args_cli.video.resolve() out.parent.mkdir(parents=True, exist_ok=True) import imageio.v2 as imageio imageio.mimsave(str(out), frames, fps=float(args_cli.fps), codec="libx264", pixelformat="yuv420p") print(f"[smoke] wrote {out} ({len(frames)} frames)") env.close() if __name__ == "__main__": # os._exit in a bare finally would kill the process before the traceback # reaches the log, turning any failure into a silent early exit. code = 0 try: main() except Exception: traceback.print_exc() sys.stdout.flush() sys.stderr.flush() code = 1 finally: simulation_app.close() os._exit(code)