"""Load an RSL-RL checkpoint, export ONNX, and evaluate the residual policy in Isaac Lab (PhysX). isaaclab.bat -p eval_policy.py [--episodes 100] (PYTHONPATH: package/simulation/isaac; SIM01_DEMO_LIB: the reference library) Simulation-tested ยท Not built. Synthetic training materials only. Not for human or veterinary treatment. Each of the N environments runs one 8 s episode with the training randomization (servo zero offsets +-1 deg, PD gains +-20 %, masses +-15 %, joint friction, latency 0-2 steps, joint-reading and vision noise) on a reference drawn from the library. RL-ISAAC success = the arc centre stays within rl.success_tip_error_mm of the scripted reference's arc centre throughout the wrist-roll pass. The same episodes (same seed) are run a second time with the residual forced to zero (the scripted reference alone, same offsets), for comparison. Offsets are evaluated at the full +-1 deg (no curriculum); torque peak = the period-averaged R-arm servo load as a share of stall; the tunnel proxy force is the D29 contact model; an episode whose proxy force exceeds sim.pad_force_limit (2 N) ends there and counts as a failure (the MuJoCo COLLISION abort). """ import argparse import json import os import shutil import tempfile from isaaclab.app import add_launcher_args, launch_simulation parser = argparse.ArgumentParser() parser.add_argument("checkpoint") parser.add_argument("onnx_dir") parser.add_argument("eval_out") parser.add_argument("--episodes", type=int, default=100) add_launcher_args(parser) args = parser.parse_args() import gymnasium as gym # noqa: E402 import torch # noqa: E402 import sim01_isaac # noqa: E402,F401 from sim01_isaac.agents.rsl_rl_ppo_cfg import ResidualPassPPORunnerCfg # noqa: E402 from sim01_isaac.env_cfg import P, ResidualPassEnvCfg # noqa: E402 cfg = ResidualPassEnvCfg() cfg.scene.num_envs = args.episodes cfg.seed = 12345 # evaluation seed differs from the training seed args.device = cfg.sim.device with launch_simulation(cfg, args): try: from importlib import metadata from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper, handle_deprecated_rsl_rl_cfg from rsl_rl.runners import OnPolicyRunner agent = handle_deprecated_rsl_rl_cfg(ResidualPassPPORunnerCfg(), metadata.version("rsl-rl-lib")) env = gym.make("Isaac-Sim01-ResidualPass-v0", cfg=cfg) u = env.unwrapped venv = RslRlVecEnvWrapper(env, clip_actions=agent.clip_actions) runner = OnPolicyRunner(venv, agent.to_dict(), log_dir=None, device=agent.device) runner.load(args.checkpoint) tmp = tempfile.mkdtemp() runner.export_policy_to_onnx(path=tmp, filename="policy.onnx") os.makedirs(args.onnx_dir, exist_ok=True) for f in os.listdir(tmp): shutil.copy(os.path.join(tmp, f), os.path.join(args.onnx_dir, f)) policy = runner.get_inference_policy(device=u.device) u.offset_scale_override = 1.0 # evaluate at the full servo zero-offset range (no curriculum) T = int(round(P["rl"]["episode_s"] * P["rl"]["policy_hz"])) nA = len(P["policy_joints"]) results = {} for mode in ("policy", "zero_residual"): with torch.inference_mode(): torch.manual_seed(777) u._reset_idx(None) u.episode_length_buf[:] = 0 obs = venv.get_observations() emax = torch.zeros(u.num_envs, device=u.device) emean = torch.zeros(u.num_envs, device=u.device) tpk = torch.zeros(u.num_envs, device=u.device) col0 = u.n_collided.clone() fpk = torch.zeros(u.num_envs, device=u.device) if True: for k in range(T - 2): act = policy(obs) if mode == "policy" else torch.zeros(u.num_envs, nA, device=u.device) obs, _, dones, _ = venv.step(act) emax = torch.maximum(emax, u.err_pass_max) emean = u.err_sum / u.err_n.clamp(min=1) tpk = torch.maximum(tpk, u.tau_peak) fpk = torch.maximum(fpk, u.force_peak) collided = (u.n_collided - col0) > 0 ok = (emax <= P["rl"]["success_tip_error_mm"]) & ~collided results[mode] = {"episodes": int(u.num_envs), "success_rate": float(ok.float().mean()), "pass_err_max_mm_median": float(emax.median()), "pass_err_max_mm_p95": float(torch.quantile(emax, 0.95)), "err_mean_mm_median": float(emean.median()), "collisions": int(collided.sum()), "torque_peak_frac_max": float(tpk.max()), "torque_peak_frac_median": float(tpk.median()), "tunnel_proxy_force_peak_n_max": float(fpk.max()), "tunnel_proxy_force_peak_n_median": float(fpk.median()), "per_episode_pass_err_max_mm": [round(float(x), 4) for x in emax.cpu()]} out = {"task": P["rl"]["task_id"], "backend": "PhysX (isaaclab_physx.PhysxCfg)", "checkpoint": os.path.basename(args.checkpoint), "eval_seed": cfg.seed, "metric": f"max arc-centre error during the pass <= {P['rl']['success_tip_error_mm']} mm and no tunnel-proxy force above {P['pad_force_limit']} N", "results": results, "definitions": __doc__} out["RL-ISAAC"] = "PASS" if results["policy"]["success_rate"] >= 0.95 else "FAIL" json.dump(out, open(args.eval_out, "w"), indent=1) print("eval written", {k: v["success_rate"] for k, v in results.items()}, flush=True) env.close() except BaseException: import traceback open(args.eval_out + ".err.txt", "w").write(traceback.format_exc()) raise