"""Pure-NumPy mirror of the SRU-Go2 deployment-side preprocessing. Why this file exists -------------------- ``sru_nav_ros2/model.py`` does the depth preprocessing, the target encoding, the 16-dim state assembly and the ``tanh * POLICY_SCALE`` action transform. All of it lives inside a class that imports ``onnxruntime`` and ``cv2``, so it cannot be exercised on a machine without those packages, and cannot be unit tested without an ONNX session. This module restates *exactly the same arithmetic* with NumPy only: depth (H, W, metres) -> sanitise -> bilinear resize -> [1,1,40,64] target (world) -> body-frame unit vector + log(distance) -> 4 dims 16-dim state -> [lin(3) ang(3) gravity(3) last_action(3) target(4)] raw action -> tanh(raw) * scale -> 3 dims Everything here is a *specification*, not a second implementation: the numeric constants are read from the deployment package's own ``constants.py`` whenever that file is reachable, so the two can never silently disagree. Two scales are defined on purpose. See ``POLICY_SCALE_TRAIN_GO2``. """ from __future__ import annotations import importlib.util from pathlib import Path import numpy as np # --------------------------------------------------------------------------- # Constants -- single source of truth is the deployment package # --------------------------------------------------------------------------- _PKG_CONSTANTS = ( Path(__file__).resolve().parents[1] / "src" / "sru_nav_ros2" / "sru_nav_ros2" / "constants.py" ) def _load_package_constants(): """Import ``sru_nav_ros2/constants.py`` by path (it imports nothing itself).""" if not _PKG_CONSTANTS.is_file(): return None spec = importlib.util.spec_from_file_location("_sru_nav_constants", _PKG_CONSTANTS) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) # type: ignore[union-attr] return module _CONST = _load_package_constants() MIN_DEPTH = float(getattr(_CONST, "DEFAULT_MIN_DEPTH", 0.25)) MAX_DEPTH = float(getattr(_CONST, "DEFAULT_MAX_DEPTH", 10.0)) ARRIVE_GOAL_THRESHOLD = float(getattr(_CONST, "ARRIVE_GOAL_THRESHOLD", 0.75)) #: What the node actually multiplies ``tanh(raw)`` by (constants.py / sru_nav.yaml). POLICY_SCALE_DEPLOY = tuple(getattr(_CONST, "POLICY_SCALE", (0.6, 0.3, 0.6))) #: Extra damping the node applies to ``linear.y`` *after* the policy scale. LATERAL_VELOCITY_SCALE = float(getattr(_CONST, "LATERAL_VELOCITY_SCALE", 0.6)) #: Node-side low-pass coefficients, convention ``out = c*new + (1-c)*prev``. LOW_PASS_FILTER_COEF = tuple(getattr(_CONST, "LOW_PASS_FILTER_COEF", (0.9, 0.5, 0.5))) #: The scale the Go2 policy was TRAINED with. Not a guess: the Go2 env config #: inherits ``ActionsCfg.velocity_command`` from ``navigation_env_cfg.py`` with #: ``use_raw_actions=True`` and ``policy_scaling=[1.5, 1.0, 1.0]``, and #: ``navigation_se2_actions.py:166-171`` SKIPS ``cfg.scale`` entirely when #: ``use_raw_actions`` is True. So Go2's own ``scale=[0.6, 0.3, 0.7]`` is dead #: code and the trained command range is ``tanh(raw) * [1.5, 1.0, 1.0]``. POLICY_SCALE_TRAIN_GO2 = (1.5, 1.0, 1.0) #: Chassis speed envelope measured/declared for RC2027 (m/s, m/s, rad/s). CHASSIS_LIMIT = (0.5, 0.5, 0.5) # VAE input geometry. Fixed by the exported ONNX; must not be changed. DEPTH_INPUT_SHAPE = (40, 64) # (H, W) fed to the encoder DEPTH_EMBEDDING_DIM = 64 * 5 * 8 # 2560 STATE_DIM = 16 POLICY_INPUT_DIM = STATE_DIM + DEPTH_EMBEDDING_DIM # 2576 #: Field order of the 16-dim state vector, in the order the network sees it. STATE_ORDER = ( "linear_vel.x", "linear_vel.y", "linear_vel.z", "angular_vel.x", "angular_vel.y", "angular_vel.z", "gravity.x", "gravity.y", "gravity.z", "last_action.0", "last_action.1", "last_action.2", "target.dir.x", "target.dir.y", "target.dir.z", "target.log_dist", ) # --------------------------------------------------------------------------- # 1. Depth # --------------------------------------------------------------------------- def sanitize_depth(depth, min_depth=MIN_DEPTH, max_depth=MAX_DEPTH): """Apply the node's invalidation rules, in the node's order. ``depth_callback`` does:: np.nan_to_num(d, nan=0.0, posinf=max_depth*2.0, neginf=0.0) d[d > max_depth] = 0.0 d[d < min_depth] = 0.0 Note ``posinf`` becomes ``2*max_depth`` and is then zeroed by the ``>`` test -- so +inf, NaN and "too far" all collapse to the same 0 sentinel the VAE was trained on. Anything inside ``[min_depth, max_depth]`` is kept as-is (the VAE input is raw metres, there is no normalisation step). """ d = np.asarray(depth, dtype=np.float32) if d.ndim != 2: raise ValueError(f"depth must be 2-D (H, W), got shape {d.shape}") d = np.nan_to_num(d, nan=0.0, posinf=max_depth * 2.0, neginf=0.0) d = d.astype(np.float32, copy=True) d[d > max_depth] = 0.0 d[d < min_depth] = 0.0 return d def resize_bilinear(img, out_hw=DEPTH_INPUT_SHAPE): """Bilinear resize to ``(H, W)`` with OpenCV's half-pixel convention. Equivalent to ``cv2.resize(img, (W, H), interpolation=cv2.INTER_LINEAR)``, reimplemented so the module has no cv2 dependency. Edge coordinates are clamped (edge replication), which is what cv2 does at the border. """ src = np.asarray(img, dtype=np.float32) if src.ndim != 2: raise ValueError(f"img must be 2-D (H, W), got shape {src.shape}") out_h, out_w = int(out_hw[0]), int(out_hw[1]) src_h, src_w = src.shape if src_h == out_h and src_w == out_w: return src.copy() def axis_coords(src_n, dst_n): scale = src_n / dst_n dst = np.arange(dst_n, dtype=np.float32) src_pos = (dst + 0.5) * scale - 0.5 i0 = np.floor(src_pos).astype(np.int64) w = (src_pos - i0).astype(np.float32) i0 = np.clip(i0, 0, src_n - 1) i1 = np.clip(i0 + 1, 0, src_n - 1) return i0, i1, w y0, y1, wy = axis_coords(src_h, out_h) x0, x1, wx = axis_coords(src_w, out_w) wy = wy[:, None] wx = wx[None, :] top = src[np.ix_(y0, x0)] * (1 - wx) + src[np.ix_(y0, x1)] * wx bot = src[np.ix_(y1, x0)] * (1 - wx) + src[np.ix_(y1, x1)] * wx return (top * (1 - wy) + bot * wy).astype(np.float32) def depth_preprocess(depth, min_depth=MIN_DEPTH, max_depth=MAX_DEPTH): """``(H, W)`` metres -> ``[1, 1, 40, 64]`` encoder input. The resize is anisotropic on purpose: the training-side raycast camera renders a 64x40 pinhole view whose FOV equals the Odin1's (fx_sim=29.49, fy_sim=22.76, see ``ODIN1_CAMERA_CONFIG``), and the real depth frame is 228x185 because the driver divides 1600x1296 by ``scale=7``. Both have the same 1.234 aspect, so a plain resize preserves the FOV mapping. """ d = sanitize_depth(depth, min_depth, max_depth) r = resize_bilinear(d, DEPTH_INPUT_SHAPE) return r[np.newaxis, np.newaxis, :, :] # --------------------------------------------------------------------------- # 2. Target encoding # --------------------------------------------------------------------------- def quat_to_rotmat(q_wxyz): """(w, x, y, z) -> 3x3 rotation matrix (world <- body).""" w, x, y, z = (float(v) for v in q_wxyz) n = w * w + x * x + y * y + z * z if n < 1e-12: return np.eye(3, dtype=np.float64) s = 2.0 / n return np.array( [ [1 - s * (y * y + z * z), s * (x * y - z * w), s * (x * z + y * w)], [s * (x * y + z * w), 1 - s * (x * x + z * z), s * (y * z - x * w)], [s * (x * z - y * w), s * (y * z + x * w), 1 - s * (x * x + y * y)], ], dtype=np.float64, ) def normalize_target_position(target_pos_w, robot_pos_w, robot_orientation_w): """World goal -> ``[dir_x, dir_y, dir_z, log(dist + 1)]`` in the body frame. Mirrors ``LearningModel.normalize_target_position``: rotate the delta into the body frame, unit-normalise its direction, and take ``log(dist + 1)`` of the *true* distance (``+1e-6`` guard added to the distance only). """ target = np.asarray(target_pos_w, dtype=np.float64).reshape(3) robot = np.asarray(robot_pos_w, dtype=np.float64).reshape(3) rot = quat_to_rotmat(robot_orientation_w) delta_b = rot.T @ (target - robot) dist = float(np.linalg.norm(delta_b) + 1e-6) direction = delta_b / dist log_dist = float(np.log(dist + 1.0)) out = np.concatenate([direction, [log_dist]]).astype(np.float32) return out, delta_b.astype(np.float32) # --------------------------------------------------------------------------- # 3. State vector # --------------------------------------------------------------------------- def build_state_vector(linear_vel, angular_vel, gravity_vector, last_action, target_pos_log): """Assemble the 16-dim state in the network's expected order. Order is load-bearing: a silent permutation here produces a policy that still runs and still outputs plausible-looking velocities, which is exactly the failure mode that is hardest to spot on a real robot. """ def _as3(v, name): a = np.asarray(v, dtype=np.float32).reshape(-1) if a.size != 3: raise ValueError(f"{name} must have 3 components, got {a.size}") return a lin = _as3(linear_vel, "linear_vel") ang = _as3(angular_vel, "angular_vel") grav = _as3(gravity_vector, "gravity_vector") act = _as3(last_action, "last_action") tgt = np.asarray(target_pos_log, dtype=np.float32).reshape(-1) if tgt.size != 4: raise ValueError(f"target_pos_log must have 4 components, got {tgt.size}") state = np.concatenate([lin, ang, grav, act, tgt]).astype(np.float32) assert state.size == STATE_DIM, state.size return state def projected_gravity(robot_orientation_w, gravity_magnitude=9.81): """World -Z gravity expressed in the body frame, unit length.""" rot = quat_to_rotmat(robot_orientation_w) g = rot.T @ np.array([0.0, 0.0, -float(gravity_magnitude)]) n = float(np.linalg.norm(g)) return (g / (n + 1e-6)).astype(np.float32) # --------------------------------------------------------------------------- # 4. Action transform # --------------------------------------------------------------------------- def apply_policy_scale(raw_action, scale=POLICY_SCALE_DEPLOY, clamp=None): """``cmd = tanh(raw) * scale``, optionally clamped afterwards. ``raw_action`` is the ONNX policy output *before* tanh (the deployment feeds the same pre-tanh values back in as ``last_action``, which is what the training-side ``last_action`` observation held as well -- raw actions are stored in ``_raw_navigation_velocity_actions``). ``clamp`` is applied *after* scaling and is the only place a chassis limit should be enforced: clamping raw or tanh'ed values instead would change the shape of the mapping, not just its range. """ raw = np.asarray(raw_action, dtype=np.float32).reshape(-1) s = np.asarray(scale, dtype=np.float32).reshape(-1) if raw.size != 3 or s.size != 3: raise ValueError(f"expected 3 components, got raw={raw.size}, scale={s.size}") cmd = np.tanh(raw) * s if clamp is not None: cmd = np.clip(cmd, -np.asarray(clamp, dtype=np.float32), np.asarray(clamp, dtype=np.float32)) return cmd.astype(np.float32) def low_pass(prev_cmd, new_cmd, coef=LOW_PASS_FILTER_COEF): """Node-side smoothing: ``out = c*new + (1-c)*prev`` (NOT the training form). Training used ``filtered = alpha*prev + (1-alpha)*new`` with ``alpha ~ U(0.3, 0.7)`` per env per dimension (``randomize_low_pass_filter_alpha``), so the two conventions are mirrored: deployment ``c=0.9`` for vx corresponds to training ``alpha=0.1``, which is *outside* the trained range. Keep the two names distinct in any report. """ c = np.asarray(coef, dtype=np.float32).reshape(-1) return (c * np.asarray(new_cmd, dtype=np.float32) + (1.0 - c) * np.asarray(prev_cmd, dtype=np.float32)).astype(np.float32)