"""Load an RSL-RL checkpoint, export ONNX, and run the 100-episode randomized Isaac Lab evaluation (RL-ISAAC). Research and simulation project only. Do not install this device in a real vehicle or attempt to drive a vehicle with it. It has not been built or tested on any vehicle. Simulation-tested ยท Not built. isaaclab.bat -p eval_policy.py [--episodes 100] [--nominal] (PYTHONPATH: package/simulation/isaac; queue: gpu) Each env runs exactly one episode of rl.episode_s on the spec course (course:, mirrored at random) at course.cruise_speed_mps, with the training randomization: vehicle V1 / V2, mass, steering ratio and torque, pedal forces, brake gain, drive force, tyre friction, pusher-gap offsets, motor strength and MCU gains, action latency 0-2 steps, estimator noise (Gauss-Markov), IMU bias and noise, 12-bit encoders, road grade, steering kick-back pulses and heading kicks, start offsets. Seed: meta.seed + rl.eval_seed_offset (training used meta.seed + rl.seed_offset). Per episode (true state, not the estimate): max |cross-track| and RMS, speed RMS error while the command is at cruise, reached end (s >= course length - rl.success.reach_end_margin_m), terminated (|cross-track| > 1.5 m or |heading error| > 1.0 rad), actuator peak / RMS torque and peak speed as fractions of stall / no-load. RL-ISAAC success rate >= thresholds.rl_isaac_success; success = reached end AND max |cross-track| <= rl.success.max_cross_track_m AND not terminated. No obstacles are in this task (obstacle stops are the rule-based supervisor's job, OBST-STOP), so rl.success.no_collision holds trivially. --nominal runs the same with randomization off (V1, no noise / disturbances; information only). """ import argparse import json import math import os import shutil import sys import tempfile sys.dont_write_bytecode = True from isaaclab.app import add_launcher_args, launch_simulation # noqa: E402 parser = argparse.ArgumentParser() parser.add_argument("checkpoint") parser.add_argument("onnx_out") parser.add_argument("eval_out") parser.add_argument("--episodes", type=int, default=None) parser.add_argument("--nominal", action="store_true") parser.add_argument("--no_export", action="store_true") add_launcher_args(parser) args = parser.parse_args() import gymnasium as gym # noqa: E402 import torch # noqa: E402 import golf_cart_isaac # noqa: E402,F401 from golf_cart_isaac.agents.rsl_rl_ppo_cfg import GolfCartPPORunnerCfg # noqa: E402 from golf_cart_isaac.env_cfg import P, GolfCartPathFollowEnvCfg # noqa: E402 rl = P["rl"] cfg = GolfCartPathFollowEnvCfg() cfg.scene.num_envs = args.episodes or int(rl["episodes_eval"]) cfg.eval_mode = True cfg.randomize = not args.nominal cfg.seed = int(P["seed"]) + int(rl["eval_seed_offset"]) n_steps = int(round(rl["episode_s"] * P["policy_hz"])) cfg.episode_length_s = rl["episode_s"] + 2.0 / P["policy_hz"] # the loop stops before the time-out reset args.device = cfg.sim.device with launch_simulation(cfg, args): out = {} 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(GolfCartPPORunnerCfg(), metadata.version("rsl-rl-lib")) env = gym.make(P["task"], 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) if not args.no_export: tmp = tempfile.mkdtemp() runner.export_policy_to_onnx(path=tmp, filename="policy.onnx") os.makedirs(os.path.dirname(os.path.abspath(args.onnx_out)), exist_ok=True) for f in os.listdir(tmp): shutil.copy(os.path.join(tmp, f), os.path.join(os.path.dirname(os.path.abspath(args.onnx_out)), f)) policy = runner.get_inference_policy(device=u.device) venv.reset() obs = venv.get_observations() N = u.num_envs dev = u.device active = torch.ones(N, dtype=torch.bool, device=dev) failed = torch.zeros(N, dtype=torch.bool, device=dev) snap = {k: torch.zeros(N, device=dev) for k in ("max_xte", "xte_sq", "n", "spd_sq", "n_cr", "s")} reached = torch.zeros(N, dtype=torch.bool, device=dev) peak_tau = torch.zeros(N, 3, device=dev) peak_w = torch.zeros(N, 3, device=dev) tau_sq = torch.zeros(N, 3, device=dev) n_sub = torch.zeros(N, device=dev) veh = u.veh.clone() chk_obs, chk_act = [], [] with torch.inference_mode(): for k in range(n_steps): act = policy(obs) if k % 45 == 0: # samples for the ONNX check (src/onnx_finalize.py) o = obs["policy"] if hasattr(obs, "keys") else obs chk_obs.append(o[:16].float().cpu()) chk_act.append(act[:16].float().cpu()) obs, _, dones, _ = venv.step(act) term = u.reset_terminated.bool() & active failed |= term keep = active & ~term # stats of envs that just terminated were reset: keep the last copy for name, src in (("max_xte", u.max_xte), ("xte_sq", u.xte_sq_sum), ("n", u.n_stat), ("spd_sq", u.spd_sq_sum), ("n_cr", u.n_cruise), ("s", u.s_path)): snap[name] = torch.where(keep, src, snap[name]) reached = torch.where(keep, u.reached, reached) peak_tau = torch.where(keep[:, None], u.peak_tau_frac, peak_tau) peak_w = torch.where(keep[:, None], u.peak_w_frac, peak_w) tau_sq = torch.where(keep[:, None], u.tau_sq_ep, tau_sq) n_sub = torch.where(keep, u.n_sub, n_sub) active &= ~term if not args.no_export: import numpy as np # noqa: PLC0415 np.savez(os.path.join(os.path.dirname(os.path.abspath(args.onnx_out)), "onnx_check.npz"), obs=torch.cat(chk_obs).numpy(), act=torch.cat(chk_act).numpy()) ms = rl["success"]["max_cross_track_m"] succ = reached & ~failed & (snap["max_xte"] <= ms) stall = u.stall rms_frac = torch.sqrt(tau_sq / n_sub.clamp(min=1)[:, None]) / stall xte_rms = torch.sqrt(snap["xte_sq"] / snap["n"].clamp(min=1)) spd_rms = torch.sqrt(snap["spd_sq"] / snap["n_cr"].clamp(min=1)) names = ["steer_motor", "brake_motor", "throttle_servo"] per = [] for i in range(N): per.append({"vehicle": u.vns[int(veh[i])], "success": bool(succ[i]), "reached_end": bool(reached[i]), "terminated": bool(failed[i]), "max_xte_m": round(float(snap["max_xte"][i]), 4), "xte_rms_m": round(float(xte_rms[i]), 4), "speed_rms_err_mps": round(float(spd_rms[i]), 4), "s_end_m": round(float(snap["s"][i]), 2)}) sr = float(succ.float().mean()) by_v = {} for vi, vn in enumerate(u.vns): m = veh == vi if bool(m.any()): by_v[vn] = {"episodes": int(m.sum()), "success_rate": float(succ[m].float().mean()), "max_xte_m": float(snap["max_xte"][m].max()), "xte_rms_m_mean": float(xte_rms[m].mean()), "speed_rms_err_mps_mean": float(spd_rms[m].mean())} out = { "generated_by": "simulation/isaac/tools/eval_policy.py (uv run tasks.py export)", "disclaimer": P["disclaimer"], "status_label": P["status"], "task": P["task"], "backend": "PhysX (isaaclab_physx.physics.PhysxCfg)", "physics_dt": u.cfg.sim.dt, "policy_hz": P["policy_hz"], "checkpoint": os.path.basename(args.checkpoint), "eval_seed": cfg.seed, "randomized": not args.nominal, "episodes": int(N), "episode_s": rl["episode_s"], "course": "spec course (mirrored at random)", "cruise_mps": P["course"]["cruise_speed_mps"], "success_rate": sr, "successes": int(succ.sum()), "terminated": int(failed.sum()), "reached_end": int(reached.sum()), "max_xte_m": float(snap["max_xte"].max()), "max_xte_m_mean": float(snap["max_xte"].mean()), "xte_rms_m_mean": float(xte_rms.mean()), "xte_rms_m_max": float(xte_rms.max()), "speed_rms_err_mps_mean": float(spd_rms.mean()), "speed_rms_err_mps_max": float(spd_rms.max()), "by_vehicle": by_v, "actuators": {n: {"peak_torque_frac_max": float(peak_tau[:, j].max()), "rms_torque_frac_max": float(rms_frac[:, j].max()), "peak_speed_frac_max": float(peak_w[:, j].max())} for j, n in enumerate(names)}, "actuator_note": ("fractions of the stall torque / no-load speed at the sizing voltage (simlib's values); the steering " "torque is at the steering-wheel axis. Information for the margins; SIM-TORQUE-* are judged on MuJoCo runs."), "success_definition": {"reach_end": f"s >= course length - {rl['success']['reach_end_margin_m']} m", "max_cross_track_m": ms, "terminated": rl["terminate"], "no_collision": "no obstacles in this task"}, "per_episode": per, "definitions": __doc__, } if not args.nominal: thr = float(P["thresholds"]["rl_isaac_success"]) out["criterion"] = {"id": "RL-ISAAC", "value": sr, "threshold": f">= {thr} (thresholds.rl_isaac_success)", "status": "PASS" if sr >= thr else "FAIL"} with open(args.eval_out, "w", encoding="utf-8", newline="\n") as fh: json.dump(out, fh, indent=1) fh.write("\n") print(f"eval written: success {sr:.3f} ({int(succ.sum())}/{N}), terminated {int(failed.sum())}, " f"max xte {out['max_xte_m']:.3f} m", flush=True) env.close() except BaseException: import traceback with open(os.path.join(os.path.dirname(os.path.abspath(args.onnx_out)), "eval_error.txt"), "w", encoding="utf-8") as fh: fh.write(traceback.format_exc()) raise