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,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