feat(sru_ws): 方案 C 零样本评估工具链
tools/ 新增:export_bag_to_npz.py(rosbag→npz)、make_synthetic_bag.py (无真实数据时构造可复现输入)、sru_policy_math.py(策略数学,纯函数)、 sru_zeroshot_replay.py(回放评估),以及 tests/ 单测。 docs/SOLUTION_C_ASSESSMENT.md 记录判据与结论。 文档结论刻意写成「工具与判据已就绪,真实数据的零样本结论尚未获得」: 仓库里没有任何录过深度的包,所以现有数字全部来自合成输入,不构成 对策略能力的判断。文中每个数字都标了复现命令和待确认项。 运行产物 sru_ws/tools/_zs_out/ 不入库(见 .gitignore 第 10 节)。
This commit is contained in:
@@ -0,0 +1,200 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Export a depth+odom recording into the ``.npz`` that ``sru_zeroshot_replay.py`` eats.
|
||||
|
||||
Run this ON THE MACHINE THAT HAS ROS 2 (``source /opt/ros/humble/setup.bash``),
|
||||
then the replay script itself runs anywhere -- no ROS, no hardware.
|
||||
|
||||
# on the robot, after recording a bag:
|
||||
python3 export_bag_to_npz.py /path/to/bag_dir --out run1.npz --max-frames 600
|
||||
# anywhere:
|
||||
python3 sru_zeroshot_replay.py --npz run1.npz --csv --out ./zs_run1
|
||||
|
||||
Why a separate script: rosbag2 message *deserialisation* needs the generated
|
||||
ROS message types. Parsing CDR by hand would work but would silently diverge
|
||||
from the real message definitions the first time a field is added upstream --
|
||||
not a failure mode worth owning in the tool that is supposed to be the reference.
|
||||
|
||||
Timestamps: the Odin1 driver runs with ``use_host_ros_time: 0`` on this machine,
|
||||
so stamps come from the DEVICE clock. That is fine here -- everything is
|
||||
matched stamp-to-stamp, never against wall time.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
|
||||
def _decode_image(msg):
|
||||
"""sensor_msgs/Image -> (H, W) float32 metres. Only 32FC1 is meaningful here."""
|
||||
if msg.encoding != "32FC1":
|
||||
raise ValueError(f"unsupported depth encoding {msg.encoding!r} (want 32FC1)")
|
||||
h, w = int(msg.height), int(msg.width)
|
||||
buf = np.frombuffer(bytes(msg.data), dtype=np.float32)
|
||||
if buf.size < h * w:
|
||||
raise ValueError(f"short image buffer: {buf.size} < {h * w}")
|
||||
row = int(msg.step) // 4 if msg.step else w
|
||||
return buf[: h * row].reshape(h, row)[:, :w].copy()
|
||||
|
||||
|
||||
def collect(bag_dir, depth_topic, odom_topic, goal_topic, max_frames, stride,
|
||||
cmd_topic="/cmd_vel"):
|
||||
from rclpy.serialization import deserialize_message
|
||||
from rosbag2_py import (ConverterOptions, SequentialReader, StorageFilter,
|
||||
StorageOptions)
|
||||
from sensor_msgs.msg import Image
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
|
||||
reader = SequentialReader()
|
||||
reader.open(
|
||||
StorageOptions(uri=str(bag_dir), storage_id="sqlite3"),
|
||||
ConverterOptions(input_serialization_format="cdr",
|
||||
output_serialization_format="cdr"),
|
||||
)
|
||||
topics = {t.name: t.type for t in reader.get_all_topics_and_types()}
|
||||
for required in (depth_topic, odom_topic):
|
||||
if required not in topics:
|
||||
raise SystemExit(f"{bag_dir}: no topic {required}. Present:\n "
|
||||
+ "\n ".join(sorted(topics)))
|
||||
wanted = [depth_topic, odom_topic]
|
||||
if goal_topic and goal_topic in topics:
|
||||
wanted.append(goal_topic)
|
||||
if cmd_topic and cmd_topic in topics:
|
||||
wanted.append(cmd_topic)
|
||||
reader.set_filter(StorageFilter(topics=wanted))
|
||||
|
||||
depths, depth_stamps = [], []
|
||||
odom = [] # (stamp, pos(3), quat(4), lin(3), ang(3))
|
||||
goals = [] # (stamp, pos(3))
|
||||
cmds = [] # (stamp, vx, vy, wz) as PUBLISHED by the node
|
||||
seen = 0
|
||||
|
||||
while reader.has_next():
|
||||
topic, raw, stamp = reader.read_next()
|
||||
t = stamp * 1e-9
|
||||
if topic == depth_topic:
|
||||
take = (seen % stride == 0)
|
||||
seen += 1
|
||||
if not take:
|
||||
continue
|
||||
msg = deserialize_message(raw, Image)
|
||||
try:
|
||||
depths.append(_decode_image(msg))
|
||||
except ValueError as exc:
|
||||
raise SystemExit(f"{topic}: {exc}")
|
||||
depth_stamps.append(t)
|
||||
if max_frames and len(depths) >= max_frames:
|
||||
break
|
||||
elif topic == odom_topic:
|
||||
msg = deserialize_message(raw, Odometry)
|
||||
p, q = msg.pose.pose.position, msg.pose.pose.orientation
|
||||
lt, at = msg.twist.twist.linear, msg.twist.twist.angular
|
||||
odom.append((t, p.x, p.y, p.z, q.w, q.x, q.y, q.z,
|
||||
lt.x, lt.y, lt.z, at.x, at.y, at.z))
|
||||
elif cmd_topic and topic == cmd_topic:
|
||||
msg = deserialize_message(raw, Twist)
|
||||
cmds.append((t, msg.linear.x, msg.linear.y, msg.angular.z))
|
||||
elif goal_topic and topic == goal_topic:
|
||||
msg = deserialize_message(raw, PoseStamped)
|
||||
goals.append((t, msg.pose.position.x, msg.pose.position.y,
|
||||
msg.pose.position.z))
|
||||
|
||||
if not depths:
|
||||
raise SystemExit("no depth frames decoded")
|
||||
if not odom:
|
||||
raise SystemExit("no odometry decoded")
|
||||
|
||||
odom = np.array(odom, dtype=np.float64)
|
||||
odom = odom[np.argsort(odom[:, 0])]
|
||||
odom_t = odom[:, 0]
|
||||
|
||||
n = len(depths)
|
||||
depth_arr = np.stack(depths).astype(np.float32)
|
||||
pos = np.zeros((n, 3)); quat = np.zeros((n, 4))
|
||||
lin = np.zeros((n, 3)); ang = np.zeros((n, 3))
|
||||
stamp_arr = np.array(depth_stamps, dtype=np.float64)
|
||||
|
||||
for k, t in enumerate(stamp_arr):
|
||||
j = int(np.clip(np.searchsorted(odom_t, t), 0, len(odom_t) - 1))
|
||||
if j > 0 and abs(odom_t[j - 1] - t) < abs(odom_t[j] - t):
|
||||
j -= 1
|
||||
if abs(odom_t[j] - t) > 0.1:
|
||||
print(f"[export] warning: frame {k} has no odom within 100 ms "
|
||||
f"(gap {abs(odom_t[j] - t) * 1e3:.0f} ms); reusing nearest")
|
||||
pos[k] = odom[j, 1:4]
|
||||
quat[k] = odom[j, 4:8]
|
||||
lin[k] = odom[j, 8:11]
|
||||
ang[k] = odom[j, 11:14]
|
||||
|
||||
cmd_rec = None
|
||||
if cmds:
|
||||
ca = np.array(cmds, dtype=np.float64)
|
||||
ca = ca[np.argsort(ca[:, 0])]
|
||||
cmd_rec = np.zeros((n, 3))
|
||||
for k, t in enumerate(stamp_arr):
|
||||
j = int(np.clip(np.searchsorted(ca[:, 0], t), 0, len(ca) - 1))
|
||||
cmd_rec[k] = ca[j, 1:4]
|
||||
|
||||
if goals:
|
||||
ga = np.array(goals, dtype=np.float64)
|
||||
goal_arr = np.zeros((n, 3))
|
||||
for k, t in enumerate(stamp_arr):
|
||||
j = int(np.clip(np.searchsorted(ga[:, 0], t), 0, len(ga) - 1))
|
||||
goal_arr[k] = ga[j, 1:4]
|
||||
else:
|
||||
goal_arr = None
|
||||
|
||||
out = dict(depth=depth_arr, stamps=stamp_arr, pos_w=pos, quat_wxyz=quat,
|
||||
lin_vel_b=lin, ang_vel_b=ang, goal_w=goal_arr)
|
||||
if cmd_rec is not None:
|
||||
out["cmd_vel_rec"] = cmd_rec
|
||||
return out
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("bag", type=Path)
|
||||
ap.add_argument("--out", type=Path, required=True)
|
||||
ap.add_argument("--depth-topic", default="/odin1/depth_img_competetion")
|
||||
ap.add_argument("--odom-topic", default="/odin1/odometry_highfreq")
|
||||
ap.add_argument("--goal-topic", default="/goal_pose")
|
||||
ap.add_argument("--cmd-topic", default="/cmd_vel",
|
||||
help="recorded node output, used to verify replay==on-robot")
|
||||
ap.add_argument("--goal", default=None,
|
||||
help="fixed goal 'x,y,z' in the odom frame (overrides --goal-topic)")
|
||||
ap.add_argument("--max-frames", type=int, default=600)
|
||||
ap.add_argument("--stride", type=int, default=1, help="keep every Nth depth frame")
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
data = collect(args.bag, args.depth_topic, args.odom_topic, args.goal_topic,
|
||||
args.max_frames, max(1, args.stride), args.cmd_topic)
|
||||
|
||||
if args.goal:
|
||||
g = np.array([float(v) for v in args.goal.split(",")], dtype=np.float64)
|
||||
if g.size != 3:
|
||||
raise SystemExit("--goal must be 'x,y,z'")
|
||||
data["goal_w"] = np.tile(g, (len(data["depth"]), 1))
|
||||
if data["goal_w"] is None:
|
||||
# Fall back: 3 m straight ahead of the first pose. Recorded bags from
|
||||
# manual driving usually carry no /goal_pose at all.
|
||||
yaw = 2.0 * np.arctan2(data["quat_wxyz"][0, 3], data["quat_wxyz"][0, 0])
|
||||
data["goal_w"] = np.tile(
|
||||
data["pos_w"][0] + 3.0 * np.array([np.cos(yaw), np.sin(yaw), 0.0]),
|
||||
(len(data["depth"]), 1))
|
||||
print("[export] no /goal_pose in bag; using a synthetic goal 3 m ahead")
|
||||
|
||||
data["meta"] = str({"bag": str(args.bag), "depth_topic": args.depth_topic,
|
||||
"odom_topic": args.odom_topic, "goal": args.goal})
|
||||
args.out.parent.mkdir(parents=True, exist_ok=True)
|
||||
np.savez_compressed(args.out, **data)
|
||||
print(f"[export] {len(data['depth'])} frames "
|
||||
f"{data['depth'].shape[1:]} -> {args.out} "
|
||||
f"({args.out.stat().st_size / 1e6:.1f} MB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Write a small synthetic rosbag2 with depth + odometry.
|
||||
|
||||
Purpose: exercise the real recording -> export -> replay chain WITHOUT the
|
||||
robot. The depth frames come from the same analytic corridor renderer the
|
||||
replay script uses, so a round-trip through a bag must reproduce the same
|
||||
command sequence (up to LSTM warm-up noise). If it does not, the export or the
|
||||
message decoding is wrong -- which is exactly the bug you do not want to
|
||||
discover for the first time on the car.
|
||||
|
||||
Needs ROS 2 (``source /opt/ros/humble/setup.bash``).
|
||||
|
||||
python3 make_synthetic_bag.py /tmp/syn_bag --frames 40
|
||||
python3 export_bag_to_npz.py /tmp/syn_bag --out /tmp/syn.npz --goal 6,0,0
|
||||
python3 sru_zeroshot_replay.py --npz /tmp/syn.npz
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
|
||||
import sru_zeroshot_replay as replay
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("bag", type=Path)
|
||||
ap.add_argument("--frames", type=int, default=40)
|
||||
ap.add_argument("--dt", type=float, default=0.2)
|
||||
ap.add_argument("--depth-topic", default="/odin1/depth_img_competetion")
|
||||
ap.add_argument("--odom-topic", default="/odin1/odometry_highfreq")
|
||||
ap.add_argument("--goal-topic", default="/goal_pose")
|
||||
ap.add_argument("--cmd-topic", default="/cmd_vel")
|
||||
ap.add_argument("--goal", default="6,0,0")
|
||||
ap.add_argument("--cam-height", type=float, default=0.5)
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
from rclpy.serialization import serialize_message
|
||||
from rosbag2_py import (ConverterOptions, SequentialWriter, StorageOptions,
|
||||
TopicMetadata)
|
||||
from sensor_msgs.msg import Image
|
||||
from nav_msgs.msg import Odometry
|
||||
from geometry_msgs.msg import PoseStamped, Twist
|
||||
|
||||
if args.bag.exists():
|
||||
raise SystemExit(f"{args.bag} exists; remove it first")
|
||||
writer = SequentialWriter()
|
||||
writer.open(
|
||||
StorageOptions(uri=str(args.bag), storage_id="sqlite3"),
|
||||
ConverterOptions(input_serialization_format="cdr",
|
||||
output_serialization_format="cdr"),
|
||||
)
|
||||
for name, typ in ((args.depth_topic, "sensor_msgs/msg/Image"),
|
||||
(args.odom_topic, "nav_msgs/msg/Odometry"),
|
||||
(args.goal_topic, "geometry_msgs/msg/PoseStamped"),
|
||||
(args.cmd_topic, "geometry_msgs/msg/Twist")):
|
||||
writer.create_topic(TopicMetadata(name=name, type=typ,
|
||||
serialization_format="cdr"))
|
||||
|
||||
depth = replay.render_corridor(cam_height=args.cam_height)
|
||||
h, w = depth.shape
|
||||
goal = [float(v) for v in args.goal.split(",")]
|
||||
|
||||
t0 = 1_700_000_000.0
|
||||
n_odom = int(args.frames * args.dt * 50) # 50 Hz odom
|
||||
for k in range(n_odom):
|
||||
t = t0 + k / 50.0
|
||||
msg = Odometry()
|
||||
msg.header.stamp = rclpy_time(t)
|
||||
msg.header.frame_id = "odom"
|
||||
msg.child_frame_id = "base_link"
|
||||
msg.pose.pose.orientation.w = 1.0
|
||||
writer.write(args.odom_topic, serialize_message(msg), int(t * 1e9))
|
||||
|
||||
for k in range(args.frames):
|
||||
t = t0 + k * args.dt
|
||||
img = Image()
|
||||
img.header.stamp = rclpy_time(t)
|
||||
img.header.frame_id = "odin1_base_link"
|
||||
img.height, img.width = h, w
|
||||
img.encoding = "32FC1"
|
||||
img.is_bigendian = 0
|
||||
img.step = 4 * w
|
||||
img.data = depth.astype(np.float32).tobytes()
|
||||
writer.write(args.depth_topic, serialize_message(img), int(t * 1e9))
|
||||
|
||||
cmd = Twist() # a parked robot: the node would publish zeros
|
||||
writer.write(args.cmd_topic, serialize_message(cmd), int(t * 1e9))
|
||||
|
||||
if k == 0:
|
||||
pose = PoseStamped()
|
||||
pose.header.stamp = rclpy_time(t)
|
||||
pose.header.frame_id = "odom"
|
||||
pose.pose.position.x, pose.pose.position.y, pose.pose.position.z = goal
|
||||
pose.pose.orientation.w = 1.0
|
||||
writer.write(args.goal_topic, serialize_message(pose), int(t * 1e9))
|
||||
|
||||
del writer
|
||||
print(f"[synth-bag] {args.frames} depth frames ({h}x{w}) + {n_odom} odom -> {args.bag}")
|
||||
|
||||
|
||||
def rclpy_time(seconds):
|
||||
from builtin_interfaces.msg import Time
|
||||
sec = int(seconds)
|
||||
return Time(sec=sec, nanosec=int(round((seconds - sec) * 1e9)))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,283 @@
|
||||
"""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)
|
||||
@@ -0,0 +1,485 @@
|
||||
#!/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()
|
||||
@@ -0,0 +1,4 @@
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parents[1]))
|
||||
@@ -0,0 +1,264 @@
|
||||
"""Pure-logic tests for the SRU deployment contract.
|
||||
|
||||
Runs on a bare ``python3`` with numpy only -- no ROS, no onnxruntime, no cv2.
|
||||
The cv2 parity check self-skips when OpenCV is absent.
|
||||
|
||||
python3 -m pytest sru_ws/tools/tests -q
|
||||
"""
|
||||
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
import sru_policy_math as m
|
||||
|
||||
PKG = Path(__file__).resolve().parents[2] / "src" / "sru_nav_ros2" / "sru_nav_ros2"
|
||||
MODEL_PY = PKG / "model.py"
|
||||
CONSTANTS_PY = PKG / "constants.py"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Cross-check against the deployment package itself
|
||||
# ---------------------------------------------------------------------------
|
||||
def _model_py_int(name, resolved=None):
|
||||
"""Evaluate ``NAME = <int expression>`` straight out of model.py.
|
||||
|
||||
``POLICY_INPUT_DIM`` is written as ``STATE_DIM + DEPTH_EMBEDDING_DIM``, so the
|
||||
right-hand side is evaluated with the previously resolved names in scope
|
||||
instead of being assumed to be a literal.
|
||||
"""
|
||||
text = MODEL_PY.read_text()
|
||||
hit = re.search(rf"^{name}\s*=\s*([^\n#]+)", text, re.MULTILINE)
|
||||
assert hit, f"{name} not found in model.py"
|
||||
return int(eval(hit.group(1).strip(), {"__builtins__": {}}, resolved or {}))
|
||||
|
||||
|
||||
def test_architecture_constants_match_model_py():
|
||||
resolved = {}
|
||||
for name, expected in (("STATE_DIM", 16),
|
||||
("DEPTH_EMBEDDING_DIM", 2560),
|
||||
("LSTM_HIDDEN_DIM", 512),
|
||||
("POLICY_INPUT_DIM", 2576)):
|
||||
value = _model_py_int(name, resolved)
|
||||
assert value == expected, f"model.py {name}={value}, expected {expected}"
|
||||
resolved[name] = value
|
||||
assert m.STATE_DIM == resolved["STATE_DIM"]
|
||||
assert m.DEPTH_EMBEDDING_DIM == resolved["DEPTH_EMBEDDING_DIM"]
|
||||
assert m.POLICY_INPUT_DIM == resolved["POLICY_INPUT_DIM"]
|
||||
|
||||
|
||||
def test_constants_are_read_from_the_package_not_duplicated():
|
||||
# If this fails, sru_policy_math fell back to hard-coded defaults: the
|
||||
# constants.py file moved or became unreadable, and the "single source of
|
||||
# truth" guarantee is gone.
|
||||
assert m._CONST is not None, f"could not import {CONSTANTS_PY}"
|
||||
assert tuple(m.POLICY_SCALE_DEPLOY) == tuple(m._CONST.POLICY_SCALE)
|
||||
|
||||
|
||||
def test_deploy_scale_is_not_the_training_scale():
|
||||
"""Documents the mismatch that the zero-shot baseline must isolate."""
|
||||
assert tuple(m.POLICY_SCALE_DEPLOY) == (0.6, 0.3, 0.6)
|
||||
assert tuple(m.POLICY_SCALE_TRAIN_GO2) == (1.5, 1.0, 1.0)
|
||||
for deploy, train in zip(m.POLICY_SCALE_DEPLOY, m.POLICY_SCALE_TRAIN_GO2):
|
||||
assert deploy < train
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Depth preprocessing
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_sanitize_depth_thresholds_are_inclusive():
|
||||
d = np.array([[0.0, 0.1, 0.2499, 0.25, 5.0, 10.0, 10.0001, np.inf, np.nan]],
|
||||
dtype=np.float32)
|
||||
out = m.sanitize_depth(d)
|
||||
assert out.dtype == np.float32
|
||||
assert out[0, 0] == 0.0 # 0 is below min -> invalid
|
||||
assert out[0, 1] == 0.0 # below min
|
||||
assert out[0, 2] == 0.0 # just below min
|
||||
assert out[0, 3] == np.float32(0.25) # min_depth itself is KEPT
|
||||
assert out[0, 4] == np.float32(5.0)
|
||||
assert out[0, 5] == np.float32(10.0) # max_depth itself is KEPT
|
||||
assert out[0, 6] == 0.0 # just above max
|
||||
assert out[0, 7] == 0.0 # +inf -> 2*max -> zeroed
|
||||
assert out[0, 8] == 0.0 # nan
|
||||
|
||||
|
||||
def test_sanitize_depth_does_not_mutate_input():
|
||||
d = np.array([[np.nan, 99.0]], dtype=np.float32)
|
||||
_ = m.sanitize_depth(d)
|
||||
assert np.isnan(d[0, 0]) and d[0, 1] == np.float32(99.0)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("shape", [(228, 185), (185, 228), (1296, 1600),
|
||||
(960, 600), (600, 960), (40, 64), (1, 1)])
|
||||
def test_depth_preprocess_shape_and_dtype(shape):
|
||||
rng = np.random.default_rng(0)
|
||||
depth = rng.uniform(0.0, 12.0, size=shape).astype(np.float32)
|
||||
out = m.depth_preprocess(depth)
|
||||
assert out.shape == (1, 1, 40, 64)
|
||||
assert out.dtype == np.float32
|
||||
assert np.isfinite(out).all()
|
||||
assert out.min() >= 0.0 and out.max() <= m.MAX_DEPTH
|
||||
|
||||
|
||||
def test_depth_preprocess_zeroes_invalid_before_resize():
|
||||
"""A frame of NaN must become an all-zero tensor, not NaN."""
|
||||
depth = np.full((185, 228), np.nan, dtype=np.float32)
|
||||
out = m.depth_preprocess(depth)
|
||||
assert out.shape == (1, 1, 40, 64)
|
||||
assert np.all(out == 0.0)
|
||||
|
||||
|
||||
def test_resize_bilinear_preserves_constant_image():
|
||||
depth = np.full((185, 228), 3.5, dtype=np.float32)
|
||||
out = m.resize_bilinear(depth)
|
||||
assert np.allclose(out, 3.5, atol=1e-5)
|
||||
|
||||
|
||||
def test_resize_bilinear_identity_when_size_matches():
|
||||
depth = np.arange(40 * 64, dtype=np.float32).reshape(40, 64)
|
||||
out = m.resize_bilinear(depth)
|
||||
assert np.array_equal(out, depth)
|
||||
|
||||
|
||||
def test_resize_bilinear_matches_cv2():
|
||||
cv2 = pytest.importorskip("cv2")
|
||||
rng = np.random.default_rng(7)
|
||||
depth = rng.uniform(0.3, 9.0, size=(185, 228)).astype(np.float32)
|
||||
ref = cv2.resize(depth, (64, 40), interpolation=cv2.INTER_LINEAR)
|
||||
got = m.resize_bilinear(depth)
|
||||
assert np.allclose(got, ref, rtol=1e-4, atol=1e-3), np.abs(got - ref).max()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Target encoding
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_state_order_declaration():
|
||||
assert len(m.STATE_ORDER) == m.STATE_DIM == 16
|
||||
assert m.STATE_ORDER[0:3] == ("linear_vel.x", "linear_vel.y", "linear_vel.z")
|
||||
assert m.STATE_ORDER[3:6] == ("angular_vel.x", "angular_vel.y", "angular_vel.z")
|
||||
assert m.STATE_ORDER[6:9] == ("gravity.x", "gravity.y", "gravity.z")
|
||||
assert m.STATE_ORDER[9:12] == ("last_action.0", "last_action.1", "last_action.2")
|
||||
assert m.STATE_ORDER[12] == "target.dir.x"
|
||||
assert m.STATE_ORDER[15] == "target.log_dist"
|
||||
|
||||
|
||||
def test_target_encoding_straight_ahead():
|
||||
tgt, delta_b = m.normalize_target_position([1.0, 0.0, 0.0], [0.0, 0.0, 0.0],
|
||||
[1.0, 0.0, 0.0, 0.0])
|
||||
assert np.allclose(tgt[:3], [1.0, 0.0, 0.0], atol=1e-6)
|
||||
assert math.isclose(float(tgt[3]), math.log(2.0), rel_tol=1e-6)
|
||||
assert tgt.shape == (4,)
|
||||
assert delta_b.shape == (3,)
|
||||
|
||||
|
||||
def test_target_encoding_behind_robot():
|
||||
tgt, _ = m.normalize_target_position([-2.0, 0.0, 0.0], [0.0, 0.0, 0.0],
|
||||
[1.0, 0.0, 0.0, 0.0])
|
||||
assert np.allclose(tgt[:3], [-1.0, 0.0, 0.0], atol=1e-6)
|
||||
|
||||
|
||||
def test_target_encoding_direction_is_unit_length():
|
||||
tgt, _ = m.normalize_target_position([3.0, -4.0, 0.5], [1.0, 1.0, 0.0],
|
||||
[1.0, 0.0, 0.0, 0.0])
|
||||
assert math.isclose(float(np.linalg.norm(tgt[:3])), 1.0, rel_tol=1e-5)
|
||||
|
||||
|
||||
def test_target_encoding_invariant_to_global_yaw():
|
||||
"""Rotating robot AND goal together must not change the body-frame vector."""
|
||||
half = math.sqrt(0.5) # yaw = +90 deg -> q = (cos45, 0, 0, sin45)
|
||||
goal = np.array([2.0, 1.0, 0.0])
|
||||
rot_z90 = np.array([[0.0, -1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]])
|
||||
a, _ = m.normalize_target_position(goal, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0, 0.0])
|
||||
b, _ = m.normalize_target_position(rot_z90 @ goal, [0.0, 0.0, 0.0],
|
||||
[half, 0.0, 0.0, half])
|
||||
assert np.allclose(a, b, atol=1e-5)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# State vector assembly
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_build_state_vector_order_is_exact():
|
||||
state = m.build_state_vector([1, 2, 3], [4, 5, 6], [7, 8, 9],
|
||||
[10, 11, 12], [13, 14, 15, 16])
|
||||
assert state.shape == (16,)
|
||||
assert state.dtype == np.float32
|
||||
assert np.array_equal(state, np.arange(1, 17, dtype=np.float32))
|
||||
|
||||
|
||||
def test_build_state_vector_rejects_swapped_arity():
|
||||
with pytest.raises(ValueError):
|
||||
m.build_state_vector([1, 2], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15, 16])
|
||||
with pytest.raises(ValueError):
|
||||
m.build_state_vector([1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15])
|
||||
|
||||
|
||||
def test_state_plus_embedding_is_the_obs_width():
|
||||
state = m.build_state_vector([0] * 3, [0] * 3, [0, 0, -1], [0] * 3, [0] * 4)
|
||||
obs = np.concatenate([state, np.zeros(m.DEPTH_EMBEDDING_DIM, dtype=np.float32)])
|
||||
assert obs.shape == (2576,)
|
||||
assert obs.shape == (m.POLICY_INPUT_DIM,)
|
||||
|
||||
|
||||
def test_projected_gravity_flat_robot_is_minus_z():
|
||||
g = m.projected_gravity([1.0, 0.0, 0.0, 0.0])
|
||||
assert np.allclose(g, [0.0, 0.0, -1.0], atol=1e-6)
|
||||
assert math.isclose(float(np.linalg.norm(g)), 1.0, rel_tol=1e-6)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Action transform -- tanh * POLICY_SCALE
|
||||
# ---------------------------------------------------------------------------
|
||||
def test_policy_scale_output_is_bounded_by_scale():
|
||||
scale = np.array(m.POLICY_SCALE_DEPLOY, dtype=np.float32)
|
||||
for raw in ([0.0, 0.0, 0.0], [1e3, -1e3, 1e3], [-1e3, 1e3, -1e3]):
|
||||
cmd = m.apply_policy_scale(raw, scale)
|
||||
assert np.all(np.abs(cmd) <= scale + 1e-6)
|
||||
|
||||
|
||||
def test_policy_scale_zero_raw_is_zero_cmd():
|
||||
assert np.allclose(m.apply_policy_scale([0.0, 0.0, 0.0]), 0.0, atol=1e-7)
|
||||
|
||||
|
||||
def test_policy_scale_is_monotonic_and_correct_at_one():
|
||||
scale = (1.0, 1.0, 1.0)
|
||||
prev = -1.0
|
||||
for raw in np.linspace(-3, 3, 25):
|
||||
v = float(m.apply_policy_scale([raw, 0, 0], scale)[0])
|
||||
assert v > prev
|
||||
prev = v
|
||||
assert math.isclose(float(m.apply_policy_scale([1.0, 0, 0], scale)[0]),
|
||||
math.tanh(1.0), rel_tol=1e-6)
|
||||
|
||||
|
||||
def test_policy_scale_saturation_point_depends_only_on_raw():
|
||||
"""tanh saturates on raw, so |raw|>3 is already 99.5% of full scale."""
|
||||
full = m.apply_policy_scale([50.0, 50.0, 50.0])
|
||||
assert np.allclose(full, m.POLICY_SCALE_DEPLOY, atol=1e-5)
|
||||
|
||||
|
||||
def test_policy_scale_clamp_applies_after_scaling():
|
||||
cmd = m.apply_policy_scale([5.0, 5.0, 5.0], m.POLICY_SCALE_TRAIN_GO2,
|
||||
clamp=m.CHASSIS_LIMIT)
|
||||
assert np.allclose(cmd, m.CHASSIS_LIMIT, atol=1e-6)
|
||||
|
||||
|
||||
def test_deploy_vs_train_effective_ratio():
|
||||
"""0.40x / 0.18x / 0.60x -- the single cheapest thing to rule out first."""
|
||||
raw = [1.0, 1.0, 1.0]
|
||||
deploy = m.apply_policy_scale(raw, m.POLICY_SCALE_DEPLOY)
|
||||
deploy[1] *= m.LATERAL_VELOCITY_SCALE # node's extra vy damping
|
||||
train = m.apply_policy_scale(raw, m.POLICY_SCALE_TRAIN_GO2)
|
||||
ratio = deploy / train
|
||||
assert np.allclose(ratio, [0.40, 0.18, 0.60], atol=1e-5)
|
||||
|
||||
|
||||
def test_low_pass_convention_is_the_mirror_of_training():
|
||||
prev = np.zeros(3, dtype=np.float32)
|
||||
new = np.ones(3, dtype=np.float32)
|
||||
out = m.low_pass(prev, new, coef=(0.9, 0.5, 0.5))
|
||||
assert np.allclose(out, [0.9, 0.5, 0.5], atol=1e-6)
|
||||
# equivalent training-side alpha = 1 - c
|
||||
assert np.allclose(1.0 - np.array((0.9, 0.5, 0.5)), [0.1, 0.5, 0.5], atol=1e-9)
|
||||
Reference in New Issue
Block a user