#!/usr/bin/env python3 """Zero-shot baseline for the SRU-Go2 policy on a recorded Odin1 depth stream. Pure offline: no ROS, no robot, no rclpy -- it imports the deployment package's ``LearningModel`` directly, so the arithmetic under test IS the deployment arithmetic (same ONNX files, same preprocessing, same LSTM bookkeeping). Two input modes --------------- 1. ``--npz`` a sequence exported from a rosbag by ``export_bag_to_npz.py`` (needs a bag that actually recorded ``/odin1/depth_img_competetion``) 2. ``--synthetic`` an analytically ray-cast corridor, rendered at the real Odin1 intrinsics. This validates the *pipeline* and measures the network's sensitivity to camera geometry. It is NOT evidence that the policy navigates. One inference pass, every gain reported -------------------------------------- The policy's raw output does not depend on ``POLICY_SCALE`` at all: the scale is applied after tanh, outside the network, and the value fed back as ``last_action`` is the pre-tanh raw action. So a single pass yields the full command sequence for every candidate gain. This script therefore reports deploy tanh(raw) * [0.6, 0.3, 0.6] (+ vy * 0.6) <- sru_nav.yaml today train tanh(raw) * [1.5, 1.0, 1.0] <- what Go2 trained with train@chassis the same, clamped to [0.5, 0.5, 0.5] and, for the deploy view only, the node's own low-pass filtered command. What replay can and cannot prove -------------------------------- The state fed to the policy is the *recorded* state. If the bag was recorded while another controller drove the robot, the policy is being evaluated off-policy: a "sane" command sequence means the network is not degenerate, not that the robot would have driven well. Only a real, closed-loop run proves the latter. Usage ----- python sru_zeroshot_replay.py --synthetic --steps 80 --out /tmp/zs python sru_zeroshot_replay.py --npz run1.npz --out /tmp/zs --csv """ from __future__ import annotations import argparse import csv import json import math import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent SRC = HERE.parent / "src" / "sru_nav_ros2" sys.path.insert(0, str(HERE)) sys.path.insert(0, str(SRC)) import sru_policy_math as pm # noqa: E402 (path setup must come first) VAE_PATH = SRC / "models" / "vae_encoder.onnx" POLICY_PATH = SRC / "models" / "nav_policy.onnx" # Odin1 intrinsics at the native 1600x1296 frame (from the ROS calibration). ODIN1_INTRINSICS = dict(fx=737.357, fy=737.292, cx=794.372, cy=666.259, width=1600, height=1296) # --------------------------------------------------------------------------- # Synthetic corridor # --------------------------------------------------------------------------- def _intrinsics_for(height, width): """Scale the native intrinsics to a rendered frame size (FOV preserved).""" sx = width / ODIN1_INTRINSICS["width"] sy = height / ODIN1_INTRINSICS["height"] return (ODIN1_INTRINSICS["fx"] * sx, ODIN1_INTRINSICS["fy"] * sy, ODIN1_INTRINSICS["cx"] * sx, ODIN1_INTRINSICS["cy"] * sy) def render_corridor(height=185, width=228, cam_height=0.5, corridor_half_width=1.2, end_distance=8.0, obstacle=True, noise_sigma=0.01, seed=0): """Analytic ray cast of a straight corridor with an optional box obstacle. Camera frame: x forward, y left, z up, mounted at ``cam_height`` above the floor, looking horizontally (pitch = 0, i.e. the trained pose). Returns ``(H, W)`` depth in metres, with invalid/far returns set to 0 the way the real pipeline does it. """ fx, fy, cx, cy = _intrinsics_for(height, width) u = np.arange(width, dtype=np.float64)[None, :] v = np.arange(height, dtype=np.float64)[:, None] dx = np.ones((height, width)) dy = -(u - cx) / fx + np.zeros((height, 1)) dz = -(v - cy) / fy + np.zeros((1, width)) norm = np.sqrt(dx * dx + dy * dy + dz * dz) dx, dy, dz = dx / norm, dy / norm, dz / norm big = np.full((height, width), np.inf) def hit_plane(t, mask): return np.where(mask & (t > 0.05), t, big) depth = big.copy() # floor at z = 0 : cam_z + t*dz = 0 with np.errstate(divide="ignore", invalid="ignore"): t = -cam_height / dz depth = np.minimum(depth, hit_plane(t, dz < -1e-6)) # threshold: z = 0 cannot be reached by upward rays; nothing else needed. # side walls y = +half (left) and y = -half (right) with np.errstate(divide="ignore", invalid="ignore"): t_left = corridor_half_width / dy t_right = -corridor_half_width / dy depth = np.minimum(depth, hit_plane(t_left, dy > 1e-6)) depth = np.minimum(depth, hit_plane(t_right, dy < -1e-6)) # end wall x = end_distance depth = np.minimum(depth, hit_plane(end_distance / dx, dx > 1e-6)) # box obstacle, axis aligned: x in [2.2, 2.7], |y| <= 0.45, z in [0, 0.65] if obstacle: lo = np.array([2.2, -0.45, 0.0]) hi = np.array([2.7, 0.45, 0.65]) with np.errstate(divide="ignore", invalid="ignore"): t1 = (lo[0] - 0.0) / dx t2 = (hi[0] - 0.0) / dx t3 = (lo[1] - 0.0) / dy t4 = (hi[1] - 0.0) / dy t5 = (lo[2] - cam_height) / dz t6 = (hi[2] - cam_height) / dz tmin = np.nanmax(np.stack([np.minimum(t1, t2), np.minimum(t3, t4), np.minimum(t5, t6)]), axis=0) tmax = np.nanmin(np.stack([np.maximum(t1, t2), np.maximum(t3, t4), np.maximum(t5, t6)]), axis=0) inside = (tmax >= tmin) & (tmax > 0.05) depth = np.where(inside & (tmin > 0.05), np.minimum(depth, tmin), depth) depth = np.where(np.isfinite(depth), depth, 0.0) rng = np.random.default_rng(seed) if noise_sigma > 0: depth = depth + rng.normal(0.0, noise_sigma, size=depth.shape) * (depth > 0) depth = np.clip(depth, 0.0, None).astype(np.float32) return depth def synthetic_sequence(steps=60, dt=0.2, goal_distance=6.0, **render_kwargs): """Open-loop sequence: robot frozen at the origin, pose/velocities zero. Deliberately static. Without a simulator there is no way to advance the robot consistently with the command, and faking an integrator would put invented dynamics into the state vector -- the exact thing this baseline is supposed to measure. """ depth = render_corridor(**render_kwargs)[None, ...] n = int(steps) depth_seq = np.repeat(depth, n, axis=0) return dict( depth=depth_seq, stamps=np.arange(n, dtype=np.float64) * dt, pos_w=np.zeros((n, 3)), quat_wxyz=np.tile(np.array([1.0, 0.0, 0.0, 0.0]), (n, 1)), lin_vel_b=np.zeros((n, 3)), ang_vel_b=np.zeros((n, 3)), goal_w=np.tile(np.array([goal_distance, 0.0, 0.0]), (n, 1)), meta=json.dumps({"source": "synthetic_corridor", **render_kwargs}), ) # --------------------------------------------------------------------------- # I/O # --------------------------------------------------------------------------- def load_npz(path): with np.load(path, allow_pickle=False) as z: data = {k: z[k] for k in z.files if k != "meta"} data["meta"] = str(z["meta"]) if "meta" in z.files else "{}" required = ("depth", "pos_w", "quat_wxyz", "goal_w") missing = [k for k in required if k not in data] if missing: raise SystemExit(f"{path}: missing arrays {missing}") n = len(data["depth"]) for key in ("lin_vel_b", "ang_vel_b"): if key not in data: data[key] = np.zeros((n, 3)) if "stamps" not in data: data["stamps"] = np.arange(n, dtype=np.float64) * 0.2 return data # --------------------------------------------------------------------------- # Inference # --------------------------------------------------------------------------- def run_policy(data, vae_path, policy_path): """One pass with the deployment model; returns raw actions per frame.""" from sru_nav_ros2.model import LearningModel model = LearningModel(str(vae_path), str(policy_path), policy_scale=[1.0, 1.0, 1.0], intra_op_num_threads=4) model.reset_hidden_state() n = len(data["depth"]) raws = np.zeros((n, 3), dtype=np.float32) targets_b = np.zeros((n, 3), dtype=np.float32) depths_used = np.zeros((n, 2), dtype=np.float32) # valid frac, mean near = np.zeros((n, 3), dtype=np.float32) # near_all, near_top, near_bot last_action = [0.0, 0.0, 0.0] for i in range(n): depth = np.asarray(data["depth"][i], dtype=np.float32) quat = data["quat_wxyz"][i] goal = data["goal_w"][i] if data["goal_w"].ndim == 2 else data["goal_w"] _, raw, target_vec_b = model.predict( linear_vel=data["lin_vel_b"][i], angular_vel=data["ang_vel_b"][i], gravity_vector=pm.projected_gravity(quat), last_action=last_action, target_pos_w=goal, robot_pos_w=data["pos_w"][i], robot_orientation_w=quat, depth_image=depth, is_reset=(i == 0), ) raws[i] = raw targets_b[i] = target_vec_b last_action = raw.tolist() pre = pm.depth_preprocess(depth)[0, 0] valid = pre > 0.0 depths_used[i] = (float(valid.mean()), float(pre[valid].mean()) if valid.any() else 0.0) # Near-field occupancy. A camera bracket / wiring loom / radar mount in # view shows up here as a persistent cluster at 0.25-0.6 m, and the # policy has no way to know it is structure rather than an obstacle -- # it will treat it as one. This is the quantitative form of # "不能自我遮挡" in the mounting spec. near_px = (pre >= pm.MIN_DEPTH) & (pre <= 0.6) near[i] = (float(near_px.mean()), float(near_px[:8].mean()), float(near_px[-8:].mean())) return raws, targets_b, depths_used, near # --------------------------------------------------------------------------- # Command views and statistics # --------------------------------------------------------------------------- def command_views(raws): """Every candidate gain applied to the SAME raw sequence.""" views = {} views["deploy"] = np.stack([ pm.apply_policy_scale(r, pm.POLICY_SCALE_DEPLOY) for r in raws ]) tmp = views["deploy"].copy() tmp[:, 1] *= pm.LATERAL_VELOCITY_SCALE # node's extra vy damping views["deploy"] = tmp views["train"] = np.stack([ pm.apply_policy_scale(r, pm.POLICY_SCALE_TRAIN_GO2) for r in raws ]) views["train@chassis"] = np.stack([ pm.apply_policy_scale(r, pm.POLICY_SCALE_TRAIN_GO2, clamp=pm.CHASSIS_LIMIT) for r in raws ]) lpf = np.zeros_like(views["deploy"]) prev = np.zeros(3, dtype=np.float32) for i, cmd in enumerate(views["deploy"]): prev = pm.low_pass(prev, cmd) lpf[i] = prev views["deploy+lpf"] = lpf return views def _sign_flips(x, eps=1e-3): s = np.sign(np.where(np.abs(x) < eps, 0.0, x)) s = s[s != 0] if s.size < 2: return 0 return int(np.sum(s[1:] != s[:-1])) def compare_with_recorded(cmds, recorded): """How far is the replay from what the node actually published on the robot? This is the only check that validates the whole offline tool against reality: the same depth frames must produce the same command the node produced when they were recorded. Compared against ``deploy+lpf`` because that is what the node publishes (policy scale -> lateral damping -> low-pass). """ rec = np.asarray(recorded, dtype=np.float32)[: len(cmds["deploy+lpf"])] ref = cmds["deploy+lpf"][: len(rec)] diff = ref - rec return { "frames_compared": int(len(rec)), "mean_abs_diff": np.abs(diff).mean(axis=0).round(5).tolist(), "max_abs_diff": np.abs(diff).max(axis=0).round(5).tolist(), "corr_vx": float(np.corrcoef(ref[:, 0], rec[:, 0])[0, 1]) if len(rec) > 1 and np.std(rec[:, 0]) > 1e-6 and np.std(ref[:, 0]) > 1e-6 else None, } def summarize(raws, cmds, targets_b, depths_used, near, dt): n = len(raws) # ``targets_b`` is the body-frame *delta* vector (not yet normalised), so the # distance is recoverable; only the bearing is used below. out = { "frames": int(n), "duration_s": float(n * dt), "depth": { "valid_fraction_mean": float(np.mean(depths_used[:, 0])), "valid_fraction_min": float(np.min(depths_used[:, 0])), "mean_range_m": float(np.mean(depths_used[:, 1])), "near_frac_mean": float(np.mean(near[:, 0])), "near_frac_max": float(np.max(near[:, 0])), "near_top_strip_mean": float(np.mean(near[:, 1])), "near_bottom_strip_mean": float(np.mean(near[:, 2])), }, "raw": { "abs_mean": np.abs(raws).mean(axis=0).round(4).tolist(), "abs_max": np.abs(raws).max(axis=0).round(4).tolist(), "sat_gt2_frac": (np.abs(raws) > 2.0).mean(axis=0).round(4).tolist(), "sat_gt3_frac": (np.abs(raws) > 3.0).mean(axis=0).round(4).tolist(), }, } for name, cmd in cmds.items(): planar = cmd[:, :2] pnorm = np.linalg.norm(planar, axis=1) tgt = targets_b[:, :2] tnorm = np.linalg.norm(tgt, axis=1) ok = (pnorm > 0.05) & (tnorm > 1e-6) cos = np.zeros(len(cmd)) cos[ok] = (planar[ok] * tgt[ok]).sum(axis=1) / (pnorm[ok] * tnorm[ok]) tail = cmd[int(len(cmd) * 0.8):] out[name] = { "abs_mean": np.abs(cmd).mean(axis=0).round(4).tolist(), "abs_mean_tail": np.abs(tail).mean(axis=0).round(4).tolist(), "abs_max": np.abs(cmd).max(axis=0).round(4).tolist(), "step_delta_rms": np.sqrt(np.mean(np.diff(cmd, axis=0) ** 2)).round(5) if len(cmd) > 1 else 0.0, "sign_flips_vx": _sign_flips(cmd[:, 0]), "sign_flips_omega": _sign_flips(cmd[:, 2]), "moving_frac": float(np.mean(pnorm > 0.05)), "backward_frac": float(np.mean(cmd[:, 0] < -0.02)), "goal_alignment": { "mean_cos": float(np.mean(cos[ok])) if ok.any() else None, "frac_cos_gt_0.5": float(np.mean(cos[ok] > 0.5)) if ok.any() else None, "frac_cos_lt_0": float(np.mean(cos[ok] < 0.0)) if ok.any() else None, }, } return out # --------------------------------------------------------------------------- # Entry point # --------------------------------------------------------------------------- def main(argv=None): ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) src = ap.add_mutually_exclusive_group(required=True) src.add_argument("--npz", type=Path, help="sequence exported from a rosbag") src.add_argument("--synthetic", action="store_true", help="analytically ray-cast corridor (pipeline test only)") ap.add_argument("--steps", type=int, default=60) ap.add_argument("--dt", type=float, default=0.2, help="frame period [s] (5 Hz)") ap.add_argument("--goal-distance", type=float, default=6.0) ap.add_argument("--cam-height", type=float, default=0.5, help="synthetic camera height above the floor [m]") ap.add_argument("--corridor-half-width", type=float, default=1.2) ap.add_argument("--no-obstacle", action="store_true") ap.add_argument("--out", type=Path, default=None, help="output directory") ap.add_argument("--csv", action="store_true", help="also write per-frame CSV") ap.add_argument("--dump-depth-png", action="store_true") ap.add_argument("--vae", type=Path, default=VAE_PATH) ap.add_argument("--policy", type=Path, default=POLICY_PATH) args = ap.parse_args(argv) if not args.vae.is_file() or not args.policy.is_file(): raise SystemExit(f"ONNX not found: {args.vae} / {args.policy}") if args.synthetic: data = synthetic_sequence(steps=args.steps, dt=args.dt, goal_distance=args.goal_distance, cam_height=args.cam_height, corridor_half_width=args.corridor_half_width, obstacle=not args.no_obstacle) label = f"synthetic(h={args.cam_height}m,goal={args.goal_distance}m)" else: data = load_npz(args.npz) label = str(args.npz) print(f"[replay] source : {label}") print(f"[replay] frames : {len(data['depth'])} " f"depth {data['depth'].shape[1:]} ") raws, targets_b, depths_used, near = run_policy(data, args.vae, args.policy) cmds = command_views(raws) summary = summarize(raws, cmds, targets_b, depths_used, near, args.dt) if "cmd_vel_rec" in data: summary["vs_recorded"] = compare_with_recorded(cmds, data["cmd_vel_rec"]) summary["source"] = label summary["meta"] = data.get("meta", "{}") print(f"[replay] depth valid : {summary['depth']['valid_fraction_mean']:.3f} " f"(min {summary['depth']['valid_fraction_min']:.3f}), " f"mean range {summary['depth']['mean_range_m']:.2f} m") print(f"[replay] near-field : {summary['depth']['near_frac_mean']:.3f} of pixels " f"in 0.25-0.60 m (max {summary['depth']['near_frac_max']:.3f}); " f"top strip {summary['depth']['near_top_strip_mean']:.3f}, " f"bottom strip {summary['depth']['near_bottom_strip_mean']:.3f}") print(f"[replay] raw |max| : " f"{['%.2f' % v for v in summary['raw']['abs_max']]}" f" sat(|raw|>3): " f"{['%.2f' % v for v in summary['raw']['sat_gt3_frac']]}") print() hdr = f"{'view':<14}{'|vx|':>7}{'|vy|':>7}{'|w|':>7}{'tail_w':>8}" \ f"{'dRMS':>8}{'flip_x':>7}{'mov%':>7}{'cos>0.5':>9}{'cos<0':>7}" print(hdr) print("-" * len(hdr)) for name in ("deploy", "deploy+lpf", "train", "train@chassis"): s = summary[name] ga = s["goal_alignment"] cos_ok = "-" if ga["frac_cos_gt_0.5"] is None else f"{ga['frac_cos_gt_0.5']:.2f}" cos_neg = "-" if ga["frac_cos_lt_0"] is None else f"{ga['frac_cos_lt_0']:.2f}" print(f"{name:<14}" f"{s['abs_mean'][0]:>7.3f}{s['abs_mean'][1]:>7.3f}" f"{s['abs_mean'][2]:>7.3f}{s['abs_mean_tail'][2]:>8.3f}" f"{s['step_delta_rms']:>8.4f}" f"{s['sign_flips_vx']:>7d}{s['moving_frac'] * 100:>7.1f}" f"{cos_ok:>9}{cos_neg:>7}") if "vs_recorded" in summary: vr = summary["vs_recorded"] print() print(f"[replay] vs recorded /cmd_vel ({vr['frames_compared']} frames): " f"mean|d|={['%.4f' % v for v in vr['mean_abs_diff']]} " f"max|d|={['%.4f' % v for v in vr['max_abs_diff']]} " f"corr_vx={vr['corr_vx']}") if args.out: args.out.mkdir(parents=True, exist_ok=True) (args.out / "summary.json").write_text( json.dumps(summary, indent=2, default=float)) if args.csv: with (args.out / "frames.csv").open("w", newline="") as fh: w = csv.writer(fh) w.writerow(["i", "t", "raw0", "raw1", "raw2", "deploy_vx", "deploy_vy", "deploy_w", "deploy_lpf_vx", "deploy_lpf_vy", "deploy_lpf_w", "train_vx", "train_vy", "train_w", "tgt_bx", "tgt_by", "tgt_bz", "depth_valid", "depth_mean"]) for i in range(len(raws)): w.writerow([i, f"{data['stamps'][i]:.3f}", *[f"{v:.5f}" for v in raws[i]], *[f"{v:.5f}" for v in cmds["deploy"][i]], *[f"{v:.5f}" for v in cmds["deploy+lpf"][i]], *[f"{v:.5f}" for v in cmds["train"][i]], *[f"{v:.5f}" for v in targets_b[i]], f"{depths_used[i, 0]:.4f}", f"{depths_used[i, 1]:.4f}"]) if args.dump_depth_png: try: import cv2 pre = pm.depth_preprocess(np.asarray(data["depth"][0])) img = pre[0, 0] img = (255.0 * img / max(1e-6, img.max())).astype(np.uint8) cv2.imwrite(str(args.out / "depth_40x64.png"), cv2.resize(img, (320, 200), interpolation=cv2.INTER_NEAREST)) raw = np.asarray(data["depth"][0], dtype=np.float32) raw = (255.0 * raw / max(1e-6, raw.max())).astype(np.uint8) cv2.imwrite(str(args.out / "depth_native.png"), raw) except ImportError: print("[replay] cv2 unavailable; skipped depth png") print(f"[replay] wrote : {args.out}") return summary, cmds, raws if __name__ == "__main__": main()