Files
RC2027_BR_code/sim_ws/tools/check_omni_robot.py
T

1589 lines
67 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""SIM-P2-001 简化全向机器人验收工具。
自己起停仿真(只起一个 server),跑 5 个运动用例 + 3 个停止用例 + 1 个暂停用例 + TF/odom 一致性,
把每步原始数据落到 log/p2_001/<run>/。
判定口径(任务书):
平移误差 ≤ 0.03 m,非目标方向漂移 ≤ 0.03 m
转角误差 ≤ 0.03 rad,原地转向平移 ≤ 0.03 m
odom 与真值:位置差 ≤ 0.02 m、yaw 差 ≤ 0.02 rad、水平速度差 ≤ 0.02 m/s
显式零指令后 ≤ 0.20 s 停稳;停止发布后 ≤ 0.70 s 停稳
停稳 = 水平速度 < 0.01 m/s 且角速度 < 0.02 rad/s,其后 1 s 平移 < 0.02 m
采集缺失一律 INVALID,不判 PASS。
只用本工具自己创建的进程;收尾按启动阶段确认过的 PID,绝不按进程名批量杀。
"""
import argparse
import atexit
import json
import math
import os
import re
import shutil
import signal
import shlex
import socket
import subprocess
import sys
import time
import uuid
import rclpy
from gazebo_msgs.srv import GetEntityState, SetEntityState
from geometry_msgs.msg import Twist
from nav_msgs.msg import Odometry
from rclpy.node import Node
from rclpy.parameter import Parameter
from rclpy.qos import DurabilityPolicy, QoSProfile, ReliabilityPolicy
from tf2_msgs.msg import TFMessage
WS = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
INSTALL = os.path.join(WS, 'install', 'classic')
MASTER = 'http://127.0.0.1:11355'
ROS_DOMAIN = '77'
OUTROOT = os.path.join(WS, 'log', 'p2_001')
ENTITY = 'r2027_omni'
BASE = ENTITY + '::base_link'
MOVING_TIME = 2.0 # 每个运动用例的指令持续时间(仿真秒)
SPAWN = (-4.5, 4.5, 0.17)
TOL_TRANS = 0.03 # 平移误差
TOL_DRIFT = 0.03 # 非目标方向漂移
TOL_YAW = 0.03 # 转角误差
TOL_ODO_POS = 0.02
TOL_ODO_YAW = 0.02
TOL_ODO_VEL = 0.02
STOP_V = 0.01
STOP_W = 0.02
TOL_STOP_DRIFT = 0.02
T_EXPLICIT_STOP = 0.20
T_TIMEOUT_STOP = 0.70
T_ALIGN = 0.03 # odom / 真值配对允许的最大时间差
STATUS_PASS = 'PASS'
STATUS_FAIL = 'FAIL'
STATUS_INVALID = 'INVALID'
EXIT_OK, EXIT_FAIL, EXIT_INVALID = 0, 30, 40
CASES = [
dict(id='M1', label='前进', yaw=0.0, cmd=(0.20, 0.0, 0.0),
expect=dict(dx=0.40, dy=0.0, dyaw=0.0), body=(0.20, 0.0)),
dict(id='M2', label='横移', yaw=0.0, cmd=(0.0, 0.20, 0.0),
expect=dict(dx=0.0, dy=0.40, dyaw=0.0), body=(0.0, 0.20)),
dict(id='M3', label='转向', yaw=0.0, cmd=(0.0, 0.0, 0.30),
expect=dict(dx=0.0, dy=0.0, dyaw=0.60), body=(0.0, 0.0)),
dict(id='M4', label='转向后前进', yaw=math.pi / 2, cmd=(0.20, 0.0, 0.0),
expect=dict(dx=0.0, dy=0.40, dyaw=0.0), body=(0.20, 0.0)),
dict(id='M5', label='转向后横移', yaw=math.pi / 2, cmd=(0.0, 0.20, 0.0),
expect=dict(dx=-0.40, dy=0.0, dyaw=0.0), body=(0.0, 0.20)),
]
# -----------------------------------------------------------------------------
# 基础设施
# -----------------------------------------------------------------------------
def sha256_file(path):
import hashlib
with open(path, 'rb') as f:
return hashlib.sha256(f.read()).hexdigest()
def log(msg):
print(msg, flush=True)
def ensure_dir(p):
os.makedirs(p, exist_ok=True)
return p
def _read_stat(pid):
try:
with open('/proc/%d/stat' % pid, encoding='utf-8') as f:
raw = f.read()
except OSError:
return None
tail = raw.rsplit(')', 1)[1].split()
return {'pid': pid, 'state': tail[0], 'ppid': int(tail[1])}
def _all_pids():
out = []
for e in os.listdir('/proc'):
if e.isdigit():
out.append(int(e))
return out
def _comm(pid):
try:
with open('/proc/%d/comm' % pid, encoding='utf-8') as f:
return f.read().strip()
except OSError:
return ''
def proc_tree(root_pid):
"""从自己的根 PID 用 PPID 关系往下找子进程(不含 root 以外任何人)。"""
stats = {}
for p in _all_pids():
st = _read_stat(p)
if st:
stats[p] = st
kids = {}
for p, st in stats.items():
kids.setdefault(st['ppid'], []).append(p)
out, stack = [], [root_pid]
while stack:
cur = stack.pop()
for c in kids.get(cur, []):
if c not in out:
out.append(c)
stack.append(c)
return out
def port_open(host='127.0.0.1', port=11355, timeout=0.4):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
try:
return s.connect_ex((host, port)) == 0
finally:
s.close()
def sim_env(extra=None):
env = dict(os.environ)
env.update({
'GAZEBO_MASTER_URI': MASTER,
'ROS_DOMAIN_ID': ROS_DOMAIN,
'ROS_LOCALHOST_ONLY': '1',
# 系统 3.10 才有 rclpy / numpy;env python3 可能命中别的解释器
'PATH': '/usr/bin:' + os.environ.get('PATH', ''),
})
if extra:
env.update(extra)
return env
def shutdown_probe(probe):
"""ROS may already be shut down by Ctrl+C; never block process cleanup."""
errors = []
if probe is not None:
if rclpy.ok():
try:
probe.send(0., 0., 0.)
except Exception as exc:
errors.append('stop command: ' + repr(exc))
try:
probe.destroy_node()
except Exception as exc:
errors.append('destroy node: ' + repr(exc))
if rclpy.ok():
try:
rclpy.shutdown()
except Exception as exc:
errors.append('ROS shutdown: ' + repr(exc))
return errors
class Sim(object):
"""一次仿真:启动 → 就绪 → 收尾。只碰自己创建的进程。"""
def __init__(self, outdir):
self.outdir = ensure_dir(outdir)
self.log_path = os.path.join(self.outdir, 'launch.log')
self.proc = None
self._fh = None
self.known = {}
self.teardown = {}
self.owner_token = None
self._stopping = False
self._old_hup = None
# Also clean up if a caller raises before its normal finally/stop path.
atexit.register(self.stop)
try:
self._old_hup = signal.getsignal(signal.SIGHUP)
signal.signal(signal.SIGHUP, self._on_hangup)
except ValueError: # Signal installation is limited to the main thread.
pass
def _on_hangup(self, signum, frame):
# Closing a test terminal normally sends SIGHUP. Unwind the caller's
# finally block instead of abandoning its detached launch children.
if not self._stopping:
raise KeyboardInterrupt('Test terminal closed (SIGHUP)')
def owns(self, pid):
if not self.owner_token or pid in (0, 1, os.getpid()):
return False
try:
marker = ('BR_SIM_RUN_TOKEN='+self.owner_token).encode()
with open('/proc/%d/environ'%pid,'rb') as stream:
return marker in stream.read().split(b'\0')
except (OSError, PermissionError):
return False
def refresh_owned(self):
# Environment identity survives ros2 launch's detached sessions and
# reparenting. Inspect only this private marker; never match process names.
if not self.owner_token:
return
for value in os.listdir('/proc'):
if value.isdigit() and self.owns(int(value)):
self.known[int(value)] = _comm(int(value))
def start(self, gui=False, timeout=90.0, lidar=False, navigation=False, spawn=None, drive='planar', world=None, terrain=False, sensor_model='generic', localization=False, lio_navigation=False, sensor_profile='ideal', split=False):
if port_open(port=11355):
return False, 'master 端口 11355 已被占用;本工具不去动占用者,直接退出'
if terrain and not navigation:
raise ValueError('terrain requires navigation mode')
if lio_navigation and (localization or world is not None):
raise ValueError('LIO navigation requires its dedicated entry')
if localization and (navigation or world is not None):
raise ValueError('localization evaluation uses its own complete-field entry')
if sensor_model not in ('generic','mid360') or (navigation and sensor_model!='generic'):
raise ValueError('MID360 is currently a separate sensor/localization entry')
if sensor_profile not in ('ideal','mild','stress') or (split and not lio_navigation):
raise ValueError('invalid noise profile or split without LIO navigation')
entry = ('br_sim_bringup scan_lio_split.launch.py' if split else
'br_sim_bringup '+('scan_lio_terrain.launch.py' if terrain else 'scan_lio.launch.py') if lio_navigation else
'br_sim_bringup mid360_sim.launch.py' if localization else
'br_sim_bringup '+('scan_terrain.launch.py' if terrain else 'scan_sim.launch.py') if navigation else
'br_sim_bringup robot_sim.launch.py')
options = ('gui:=%s' % ('true' if gui else 'false'))
if lio_navigation:
options += ' sensor_profile:='+sensor_profile
if not terrain and not split:
options += ' with_rviz:=false'
if split:options += ' terrain:='+('true' if terrain else 'false')
elif localization:
options += ' with_lio:=true sensor_profile:='+sensor_profile
elif not navigation:
options += ' lidar:=%s' % ('true' if lidar else 'false')
if drive not in ('planar', 'contact'):
raise ValueError('unknown drive mode')
options += ' drive:=%s' % drive
options += ' sensor_model:=%s sensor_profile:=%s' % (sensor_model,sensor_profile)
if spawn is not None:
if len(spawn) != 4 or not all(math.isfinite(float(v)) for v in spawn):
raise ValueError('spawn must contain finite x,y,z,yaw')
options += ' ' + ' '.join('%s:=%g' % (key, float(value))
for key, value in zip(('x', 'y', 'z', 'yaw'), spawn))
if world is not None:
if navigation:
raise ValueError('world override currently belongs to the robot-only entry')
options += ' ' + shlex.quote('world:='+os.path.abspath(world))
cmd = ('source /opt/ros/humble/setup.bash && '
'source %s/setup.bash && '
'exec ros2 launch %s %s' % (INSTALL, entry, options))
self._fh = open(self.log_path, 'w', encoding='utf-8')
self.owner_token = uuid.uuid4().hex
self.proc = subprocess.Popen(['bash', '-c', cmd], env=sim_env({'BR_SIM_RUN_TOKEN':self.owner_token}), cwd='/',
stdout=self._fh, stderr=subprocess.STDOUT,
start_new_session=True)
t0 = time.monotonic()
while time.monotonic() - t0 < timeout:
time.sleep(0.5)
self.refresh_owned()
if self.proc.poll() is not None:
return False, 'launch 进程提前退出 code=%s' % self.proc.returncode
for p in proc_tree(self.proc.pid):
self.known[p] = _comm(p)
# The port/clock can become ready before the robot is spawned.
# Require explicit success from either the legacy or split spawn client.
launch_log = self.log_text()
model_ready = ('Spawn status: SpawnEntity: Successfully spawned entity' in launch_log
or '已生成机器人' in launch_log)
if model_ready and port_open(port=11355) and any(v == 'gzserver' for v in self.known.values()):
return True, 'gzserver 与模型生成均已就绪(%.1f s)' % (time.monotonic() - t0)
return False, '在 %.0f s 内未就绪' % timeout
def log_text(self):
try:
with open(self.log_path, encoding='utf-8', errors='ignore') as f:
return f.read()
except OSError:
return ''
def stop(self):
if self.teardown:
return self.teardown
self._stopping = True
port = 11355
sigterm, sigkill = [], []
t0 = time.monotonic()
def alive(pid):
if not self.owns(pid):
return False
try:
os.kill(pid, 0)
return True
except OSError:
return False
deadline = t0 + 8.0
while time.monotonic() < deadline:
self.refresh_owned()
for pid in sorted(self.known):
if pid not in sigterm and alive(pid):
try:
os.kill(pid, signal.SIGTERM)
sigterm.append(pid)
except OSError:
pass
if not any(alive(p) for p in self.known):
break
time.sleep(0.25)
known = sorted(self.known)
for pid in known:
if alive(pid):
try:
os.kill(pid, signal.SIGKILL)
sigkill.append(pid)
except OSError:
pass
if self.proc is not None:
try:
self.proc.wait(timeout=1)
except subprocess.TimeoutExpired:
pass
# SIGKILL delivery is asynchronous; wait for owned processes to release
# the master socket before recording cleanup evidence or starting a run.
deadline = time.monotonic() + 2.0
while (any(alive(p) for p in self.known) or (sigkill and port_open(port=port))) and time.monotonic() < deadline:
time.sleep(0.05)
self.teardown = {'known_pids': known, 'sigterm': sigterm, 'sigkill': sigkill,
'port_free': not port_open(port=port),
'seconds': round(time.monotonic() - t0, 2),
'never_touched_unknown_pid': True}
if self._fh:
self._fh.close()
atexit.unregister(self.stop)
if self._old_hup is not None and signal.getsignal(signal.SIGHUP) == self._on_hangup:
signal.signal(signal.SIGHUP, self._old_hup)
return self.teardown
# -----------------------------------------------------------------------------
# 探针
# -----------------------------------------------------------------------------
class Probe(Node):
def __init__(self):
super().__init__('p2_001_check')
self.set_parameters([Parameter('use_sim_time', Parameter.Type.BOOL, True)])
self.odom = [] # [(stamp, pose(3+yaw), twist(3))]
self.tf_pairs = {} # 'a->b' -> count(仅作计数,不用于证明唯一性)
self.tf_static_pairs = {}
self.tf_raw = [] # 原始 /tf 样本:frame、时间戳、变换值
self.tf_static_raw = []
self.empty_clients = {}
self.pub = self.create_publisher(Twist, '/cmd_vel', 10)
self.create_subscription(Odometry, '/odom', self._on_odom, 100)
self.create_subscription(TFMessage, '/tf', self._on_tf, 100)
# /tf_static 是 transient_local:用默认 VOLATILE QoS 会一条都收不到
self.create_subscription(
TFMessage, '/tf_static', self._on_tf_static,
QoSProfile(depth=10, reliability=ReliabilityPolicy.RELIABLE,
durability=DurabilityPolicy.TRANSIENT_LOCAL))
self.cli_get = self.create_client(GetEntityState, '/gazebo/get_entity_state')
self.cli_set = self.create_client(SetEntityState, '/gazebo/set_entity_state')
self.last_pub_t = None
# ---- 回调
def _on_odom(self, m):
q = m.pose.pose.orientation
self.odom.append({
'stamp': m.header.stamp.sec + m.header.stamp.nanosec * 1e-9,
'frame': m.header.frame_id,
'child': m.child_frame_id,
'pos': [m.pose.pose.position.x, m.pose.pose.position.y, m.pose.pose.position.z],
'yaw': yaw_of(q),
'twist': [m.twist.twist.linear.x, m.twist.twist.linear.y,
m.twist.twist.linear.z],
'wz': m.twist.twist.angular.z,
})
@staticmethod
def _sample(tr):
return {'frame_id': tr.header.frame_id,
'child': tr.child_frame_id,
'stamp': round(tr.header.stamp.sec + tr.header.stamp.nanosec * 1e-9, 9),
'translation': [tr.transform.translation.x, tr.transform.translation.y,
tr.transform.translation.z],
'rotation': [tr.transform.rotation.x, tr.transform.rotation.y,
tr.transform.rotation.z, tr.transform.rotation.w]}
def _on_tf(self, m):
for tr in m.transforms:
k = '%s->%s' % (tr.header.frame_id, tr.child_frame_id)
self.tf_pairs[k] = self.tf_pairs.get(k, 0) + 1
if len(self.tf_raw) < 4000:
self.tf_raw.append(self._sample(tr))
def _on_tf_static(self, m):
for tr in m.transforms:
k = '%s->%s' % (tr.header.frame_id, tr.child_frame_id)
self.tf_static_pairs[k] = self.tf_static_pairs.get(k, 0) + 1
if len(self.tf_static_raw) < 200:
self.tf_static_raw.append(self._sample(tr))
# ---- 时间
def now(self):
return self.get_clock().now().nanoseconds * 1e-9
def pump(self, sim_dt):
"""推进仿真时间 sim_dt(按仿真时钟,不按墙钟)。"""
t_start = self.now()
deadline = time.monotonic() + max(30.0, sim_dt * 20.0)
while True:
if time.monotonic() > deadline:
raise TimeoutError("simulation clock stopped while waiting")
rclpy.spin_once(self, timeout_sec=0.005)
if self.now() - t_start >= sim_dt:
return self.now()
def wait_clock(self, timeout=60.0):
t0 = time.monotonic()
while time.monotonic() - t0 < timeout:
rclpy.spin_once(self, timeout_sec=0.05)
if self.now() > 0:
return True
return False
# ---- 服务
def _call(self, cli, req, timeout=5.0):
if not cli.wait_for_service(timeout_sec=timeout):
return None
fut = cli.call_async(req)
t0 = time.monotonic()
while not fut.done() and time.monotonic() - t0 < timeout:
rclpy.spin_once(self, timeout_sec=0.005)
return fut.result() if fut.done() else None
def get_state(self):
req = GetEntityState.Request()
req.name = BASE
req.reference_frame = 'world'
res = self._call(self.cli_get, req)
if res is None or not res.success:
return None
st = res.state
return {
'stamp': res.header.stamp.sec + res.header.stamp.nanosec * 1e-9,
'frame_id': res.header.frame_id,
'pos': [st.pose.position.x, st.pose.position.y, st.pose.position.z],
'yaw': yaw_of(st.pose.orientation),
'twist_world': [st.twist.linear.x, st.twist.linear.y, st.twist.linear.z],
'wz': st.twist.angular.z,
}
def set_state(self, x, y, z, yaw):
req = SetEntityState.Request()
# 用模型名而不是 link 名:带 fixed joint 的模型上,link 级置位实测
# 会把 yaw 落到与设定不同的值(设 π/2,读到 0.76 / 1.09)。
req.state.name = ENTITY
req.state.reference_frame = 'world'
req.state.pose.position.x = float(x)
req.state.pose.position.y = float(y)
req.state.pose.position.z = float(z)
req.state.pose.orientation.z = math.sin(yaw / 2.0)
req.state.pose.orientation.w = math.cos(yaw / 2.0)
req.state.twist.linear.x = 0.0
req.state.twist.linear.y = 0.0
req.state.twist.linear.z = 0.0
req.state.twist.angular.x = 0.0
req.state.twist.angular.y = 0.0
req.state.twist.angular.z = 0.0
res = self._call(self.cli_set, req)
return bool(res and res.success)
# ---- 指令
def send(self, vx, vy, wz):
self.last_pub_t = self.now()
m = Twist()
m.linear.x = float(vx)
m.linear.y = float(vy)
m.linear.z = 0.0
m.angular.x = 0.0
m.angular.y = 0.0
m.angular.z = float(wz)
self.pub.publish(m)
def hold(self, vx, vy, wz, sim_seconds, rate=20.0, sampler=None):
"""以 rate 持续发指令 sim_seconds 秒(仿真时间),期间可采样。"""
t0 = self.now()
deadline = time.monotonic() + max(30.0, sim_seconds * 20.0)
dt = 1.0 / rate
nxt = t0
while True:
if time.monotonic() > deadline:
self.send(0.0, 0.0, 0.0)
raise TimeoutError("simulation clock stopped while commanding motion")
now = self.now()
if now - t0 >= sim_seconds:
break
if now >= nxt:
self.send(vx, vy, wz)
nxt = now + dt
rclpy.spin_once(self, timeout_sec=0.005)
# 离截止不足 60 ms 时不再采样:采样要调一次服务(约几十 ms 仿真时间),
# 卡在截止点上会把指令窗口拖长(曾把 2.0 s 拖成 2.1 s、位移 0.3989→0.4189)。
if sampler is not None and (now - t0) < sim_seconds - 0.05:
sampler()
return self.now() - t0
class TFDuplicator(Node):
"""T1 反例:临时发布**同一对父子帧**(world->odom)的第二份静态变换。
只在本轮测试进程内存在,T1 判定完立即 destroy。用来证明 T1 的唯一性判据
真的依赖 ROS 发布端信息,而不是「数据里只看到一条边」这种自我安慰。
"""
def __init__(self):
super().__init__('t1_negative_dup_tf')
from geometry_msgs.msg import TransformStamped
qos = QoSProfile(depth=10, reliability=ReliabilityPolicy.RELIABLE,
durability=DurabilityPolicy.TRANSIENT_LOCAL)
self.pub = self.create_publisher(TFMessage, '/tf_static', qos)
self.get_logger().info('T1 反例:发布重复的 world->odom 静态变换')
self.publish_once()
def publish_once(self):
from geometry_msgs.msg import TransformStamped
m = TFMessage()
tr = TransformStamped()
tr.header.stamp.sec = 0
tr.header.stamp.nanosec = 0
tr.header.frame_id = 'world'
tr.child_frame_id = 'odom'
tr.transform.translation.x = 0.0
tr.transform.translation.y = 0.0
tr.transform.translation.z = 0.0
tr.transform.rotation.w = 1.0
m.transforms = [tr]
self.pub.publish(m)
def yaw_of(q):
return math.atan2(2.0 * (q.w * q.z + q.x * q.y),
1.0 - 2.0 * (q.y * q.y + q.z * q.z))
def wrap(a):
while a > math.pi:
a -= 2.0 * math.pi
while a < -math.pi:
a += 2.0 * math.pi
return a
def body_vel(truth):
"""把真值的世界速度转到车体系:v_body = R(-yaw) * v_world。"""
c, s = math.cos(truth['yaw']), math.sin(truth['yaw'])
vx, vy = truth['twist_world'][0], truth['twist_world'][1]
return c * vx + s * vy, -s * vx + c * vy
def speed_of(truth):
return math.hypot(truth['twist_world'][0], truth['twist_world'][1])
# -----------------------------------------------------------------------------
# 单用例
# -----------------------------------------------------------------------------
def reset_and_settle(probe, x, y, z, yaw, out, timeout_sim=8.0):
"""发零 → 置位姿清速度 → 落稳。返回 (ok, 记录)。"""
rec = {'set_pose': [x, y, z, yaw], 'zero_before_set': True}
probe.send(0.0, 0.0, 0.0)
probe.pump(0.30)
rec['set_ok'] = probe.set_state(x, y, z, yaw)
if not rec['set_ok']:
return False, rec
t0 = probe.now()
pose0 = None
drift = 0.0
vmax = 0.0
wmax = 0.0
stable_since = None
n = 0
while probe.now() - t0 < timeout_sim:
probe.pump(0.05)
s = probe.get_state()
if s is None:
continue
n += 1
if pose0 is None:
pose0 = s['pos']
drift = max(drift, math.hypot(s['pos'][0] - pose0[0], s['pos'][1] - pose0[1]))
vmax = max(vmax, speed_of(s))
wmax = max(wmax, abs(s['wz']))
if speed_of(s) < STOP_V and abs(s['wz']) < STOP_W:
if stable_since is None:
stable_since = probe.now()
elif probe.now() - stable_since >= 0.5:
break
else:
stable_since = None
final = probe.get_state()
rec.update({'samples': n, 'settle_sim_s': round(probe.now() - t0, 3),
'pose_after_set': pose0, 'final_pose': final['pos'] if final else None,
'settle_height_m': final['pos'][2] if final else None,
'residual_speed': speed_of(final) if final else None,
'residual_wz': abs(final['wz']) if final else None,
'drift_during_settle_m': drift})
ok = (final is not None and speed_of(final) < STOP_V and abs(final['wz']) < STOP_W
and drift <= 0.01)
return ok, rec
def run_motion_case(probe, case, out, cdir):
rec = {'id': case['id'], 'label': case['label'], 'yaw0': case['yaw'],
'cmd': dict(vx=case['cmd'][0], vy=case['cmd'][1], wz=case['cmd'][2]),
'expected': case['expect'], 'status': STATUS_INVALID}
ok, srec = reset_and_settle(probe, SPAWN[0], SPAWN[1], SPAWN[2], case['yaw'], out)
rec['reset'] = srec
if not ok:
rec['reason'] = '置位/落稳未通过:%r' % {k: srec.get(k) for k in
('set_ok', 'residual_speed',
'residual_wz', 'drift_during_settle_m')}
return rec
before = probe.get_state()
if before is None:
rec['reason'] = '起点真值查询失败'
return rec
rec['start_pose'] = before['pos']
rec['start_yaw'] = before['yaw']
# 采集窗口:指令持续时间 + 0.3 s,覆盖释放后段
samples = []
odom_before = len(probe.odom)
t0 = probe.now()
next_sample = t0
def sampler():
nonlocal next_sample
now = probe.now()
if now < next_sample:
return
next_sample = now + 0.04
s = probe.get_state()
if s is not None:
samples.append(s)
dur = probe.hold(case['cmd'][0], case['cmd'][1], case['cmd'][2],
MOVING_TIME, sampler=sampler)
rec['commanded_sim_s'] = round(dur, 3)
rec['protocol_duration_ok'] = abs(dur - MOVING_TIME) <= 0.15
if not rec['protocol_duration_ok']:
rec['status'] = STATUS_INVALID
rec['reason'] = ('指令窗口 %.3f s 偏离协议 %.1f s 超过 0.15 s,采集不合协议,判无效'
% (dur, MOVING_TIME))
return rec
probe.send(0.0, 0.0, 0.0)
probe.pump(0.30)
after = probe.get_state()
after_rest = None
probe.pump(1.0)
after_rest = probe.get_state()
rec['odom_during_cmd'] = probe.odom[odom_before:]
rec['truth_during_cmd'] = samples
if after is None or after_rest is None:
rec['reason'] = '终点真值查询失败'
return rec
rec['end_pose'] = after['pos']
rec['end_yaw'] = after['yaw']
rec['pose_after_stop_1s'] = after_rest['pos']
# 固定协议:指令保持 2 s,比较独立真值起点和停车终点。
# 期望位移已经在 CASES 中写成世界坐标,不能再当车体速度积分。
# 不从被测 odom 的响应时长反推期望值,否则会掩盖指令延迟。
exp = case['expect']
d = [after['pos'][i] - before['pos'][i] for i in range(3)]
dyaw = wrap(after['yaw'] - before['yaw'])
rec['measurement_basis'] = 'independent truth before command to settled stop; fixed 2 s protocol'
rec['delta'] = {'dx': round(d[0], 6), 'dy': round(d[1], 6), 'dz': round(d[2], 6),
'dyaw': round(dyaw, 6)}
rec['delta_after_stop'] = {
'dx': round(after_rest['pos'][0] - after['pos'][0], 6),
'dy': round(after_rest['pos'][1] - after['pos'][1], 6)}
ok_t = abs(d[0] - exp['dx']) <= TOL_TRANS
ok_s = abs(d[1] - exp['dy']) <= TOL_TRANS
ok_r = abs(dyaw - exp['dyaw']) <= TOL_YAW
rec['errors'] = {
'ex': round(d[0] - exp['dx'], 6), 'ey': round(d[1] - exp['dy'], 6),
'eyaw': round(dyaw - exp['dyaw'], 6)}
if abs(exp['dx']) > 1e-9:
drift = abs(d[1] - exp['dy'])
elif abs(exp['dy']) > 1e-9:
drift = abs(d[0] - exp['dx'])
else:
drift = math.hypot(d[0], d[1])
rec['drift_m'] = round(drift, 6)
# ---- 判据 2:车体系速度(odom.twist 与真值转车体后对比)
body_cmd = case['body']
moving = [s for s in samples if speed_of(s) > 0.10]
rec['moving_samples'] = len(moving)
if moving:
vb = [body_vel(s) for s in moving]
rec['body_vel_truth_mean'] = [round(sum(v[0] for v in vb) / len(vb), 6),
round(sum(v[1] for v in vb) / len(vb), 6)]
# odom.twist 在运动段的中位数
od = [o for o in rec['odom_during_cmd'] if abs(o['twist'][0]) + abs(o['twist'][1]) > 0.10]
if od:
rec['odom_twist_mean'] = [round(sum(o['twist'][0] for o in od) / len(od), 6),
round(sum(o['twist'][1] for o in od) / len(od), 6)]
rec['odom_twist_samples'] = len(od)
# ---- 判据 3:odom 与真值对齐比较
pairs = align(rec['odom_during_cmd'], samples)
rec['align'] = pairs['stats']
rec['align_pairs'] = pairs['pairs'][:120]
ok_body = True
body_note = '—'
if case['id'] in ('M4', 'M5'):
vb = rec.get('body_vel_truth_mean')
ot = rec.get('odom_twist_mean')
ok_body = bool(vb and ot
and abs(vb[0] - body_cmd[0]) <= 0.02
and abs(vb[1] - body_cmd[1]) <= 0.02
and abs(ot[0] - body_cmd[0]) <= 0.02
and abs(ot[1] - body_cmd[1]) <= 0.02)
body_note = ('真值车体系 v=(%.4f, %.4f),odom.twist=(%.4f, %.4f),指令=(%.2f, %.2f)'
% (vb[0] if vb else float('nan'), vb[1] if vb else float('nan'),
ot[0] if ot else float('nan'), ot[1] if ot else float('nan'),
body_cmd[0], body_cmd[1]))
rec['body_frame_ok'] = ok_body
rec['body_frame_note'] = body_note
# ---- 集合判定
checks = {
'translation': ok_t and ok_s,
'rotation': ok_r,
'drift': drift <= TOL_DRIFT,
'odom_pos': pairs['stats']['max_pos_diff'] <= TOL_ODO_POS,
'odom_yaw': pairs['stats']['max_yaw_diff'] <= TOL_ODO_YAW,
'odom_vel': pairs['stats']['max_vel_diff'] <= TOL_ODO_VEL,
'body_frame': ok_body,
'align_coverage': pairs['stats']['pairs'] >= 10,
}
rec['checks'] = checks
if not checks['align_coverage']:
rec['status'] = STATUS_INVALID
rec['reason'] = 'odom/真值可配对样本数 %d 不足 10,采集无效' % pairs['stats']['pairs']
return rec
rec['status'] = STATUS_PASS if all(checks.values()) else STATUS_FAIL
rec['judgement'] = ('Δ=(%.4f, %.4f) Δyaw=%.4f;漂移 %.4f;'
'odom-真值 位置 %.4f / yaw %.4f / 速度 %.4f'
% (d[0], d[1], dyaw, drift,
pairs['stats']['max_pos_diff'],
pairs['stats']['max_yaw_diff'],
pairs['stats']['max_vel_diff']))
return rec
def align(odom_list, truth_list):
"""Interpolate bracketing odom at the truth stamp; never extrapolate or bridge gaps.
Comparing a stale velocity with a later truth is invalid under acceleration.
The pose/velocity tolerances remain unchanged. Keep both source stamps.
"""
pairs = []
mp = my = mv = 0.0
for s in truth_list:
before = [o for o in odom_list if o['stamp'] <= s['stamp'] + 1e-9]
after = [o for o in odom_list if o['stamp'] >= s['stamp'] - 1e-9]
if not before or not after:
continue
lo, hi = max(before, key=lambda x:x['stamp']), min(after, key=lambda x:x['stamp'])
gap = hi['stamp']-lo['stamp']
if gap > T_ALIGN + 1e-9:
continue
ratio = (s['stamp']-lo['stamp'])/gap if gap > 1e-9 else 0.
o = dict(stamp=s['stamp'],
pos=[a+(b-a)*ratio for a,b in zip(lo['pos'],hi['pos'])],
twist=[a+(b-a)*ratio for a,b in zip(lo['twist'],hi['twist'])],
yaw=lo['yaw']+wrap(hi['yaw']-lo['yaw'])*ratio)
dp = math.hypot(o['pos'][0] - s['pos'][0], o['pos'][1] - s['pos'][1])
dy = abs(wrap(o['yaw'] - s['yaw']))
vb = body_vel(s)
dv = math.hypot(o['twist'][0] - vb[0], o['twist'][1] - vb[1])
mp = max(mp, dp)
my = max(my, dy)
mv = max(mv, dv)
pairs.append({'t_odom': round(o['stamp'], 6), 't_truth': round(s['stamp'], 6),
't_odom_before': lo['stamp'], 't_odom_after': hi['stamp'],
'interpolation_ratio': ratio,
'odom_twist': o['twist'], 'truth_body_velocity': list(vb),
'dt': round(s['stamp'] - o['stamp'], 6),
'odom_pose': [round(v, 6) for v in o['pos']],
'truth_pose': [round(v, 6) for v in s['pos']],
'pos_diff': round(dp, 6), 'yaw_diff': round(dy, 6),
'vel_diff': round(dv, 6)})
return {'pairs': pairs,
'stats': {'pairs': len(pairs), 'max_pos_diff': round(mp, 6),
'max_yaw_diff': round(my, 6), 'max_vel_diff': round(mv, 6)}}
def run_explicit_zero(probe, out):
"""显式零指令停车:0.2 m/s 跑到稳态 → 明确发零 → 计时。"""
rec = {'id': 'S1', 'label': '显式零指令停车', 'status': STATUS_INVALID}
ok, srec = reset_and_settle(probe, SPAWN[0], SPAWN[1], SPAWN[2], 0.0, out)
rec['reset'] = srec
if not ok:
rec['reason'] = '置位/落稳未通过'
return rec
probe.hold(0.20, 0.0, 0.0, 1.2)
s0 = probe.get_state()
if s0 is None or speed_of(s0) < 0.10:
rec['reason'] = '加速段未达到 0.10 m/s(实测 %r)' % (speed_of(s0) if s0 else None)
return rec
# 明确发零,记录首次发零时刻
t_zero = probe.now()
probe.send(0.0, 0.0, 0.0)
stopped_at = None
trail = []
t0 = probe.now()
while probe.now() - t0 < 1.5:
# 服务调用本身会推进仿真时间,比「pump 固定步长 + 偶尔采样」密得多,
# 否则停稳时刻会被 20 ms 采样间隔量粗(曾量出恰好 0.7000 s 的临界值)
probe.send(0.0, 0.0, 0.0)
s = probe.get_state()
if s is None:
continue
trail.append({'t': round(s['stamp'], 6), 'v': round(speed_of(s), 6),
'wz': round(s['wz'], 6)})
if stopped_at is None and speed_of(s) < STOP_V and abs(s['wz']) < STOP_W:
stopped_at = s['stamp']
rec['t_zero'] = round(t_zero, 6)
rec['trail'] = trail
if stopped_at is None:
rec['reason'] = '1.5 s 内未停稳'
return rec
rec['stop_latency_s'] = round(stopped_at - t_zero, 6)
# 停稳后 1 s 平移
p_stop = probe.get_state()
probe.pump(1.0)
p_later = probe.get_state()
if p_stop is None or p_later is None:
rec['reason'] = '停稳后位移查询失败'
return rec
rec['post_stop_drift_m'] = round(
math.hypot(p_later['pos'][0] - p_stop['pos'][0],
p_later['pos'][1] - p_stop['pos'][1]), 6)
checks = {'latency': rec['stop_latency_s'] <= T_EXPLICIT_STOP,
'post_drift': rec['post_stop_drift_m'] <= TOL_STOP_DRIFT}
rec['checks'] = checks
rec['status'] = STATUS_PASS if all(checks.values()) else STATUS_FAIL
rec['judgement'] = ('零指令后 %.4f s 停稳(阈值 %.2f s),其后 1 s 位移 %.4f m'
% (rec['stop_latency_s'], T_EXPLICIT_STOP, rec['post_stop_drift_m']))
return rec
def run_timeout_stop(probe, out):
"""停止发布后超时停车:不再发任何指令,靠转发节点 0.5 s 超时。"""
rec = {'id': 'S2', 'label': '停止发布后超时停车', 'status': STATUS_INVALID}
ok, srec = reset_and_settle(probe, SPAWN[0], SPAWN[1], SPAWN[2], 0.0, out)
rec['reset'] = srec
if not ok:
rec['reason'] = '置位/落稳未通过'
return rec
probe.hold(0.20, 0.0, 0.0, 1.2)
s0 = probe.get_state()
if s0 is None or speed_of(s0) < 0.10:
rec['reason'] = '加速段未达到 0.10 m/s'
return rec
# 用真正发出最后一条指令的时刻,而不是「hold 返回时刻」(差最多一个发布周期)
last_cmd_t = probe.last_pub_t
rec['last_cmd_t'] = round(last_cmd_t, 6)
stopped_at = None
trail = []
t0 = probe.now()
while probe.now() - t0 < 1.5:
# 不再发布任何指令;靠服务调用推进时间以获得密集采样
s = probe.get_state()
if s is None:
continue
trail.append({'t': round(s['stamp'], 6), 'v': round(speed_of(s), 6),
'wz': round(s['wz'], 6)})
if stopped_at is None and speed_of(s) < STOP_V and abs(s['wz']) < STOP_W:
stopped_at = s['stamp']
rec['trail'] = trail
if stopped_at is None:
rec['reason'] = '1.5 s 内未停稳(超时保护可能未生效)'
return rec
rec['stop_latency_s'] = round(stopped_at - last_cmd_t, 6)
p_stop = probe.get_state()
probe.pump(1.0)
p_later = probe.get_state()
rec['post_stop_drift_m'] = round(
math.hypot(p_later['pos'][0] - p_stop['pos'][0],
p_later['pos'][1] - p_stop['pos'][1]), 6) if (p_stop and p_later) else None
checks = {'latency': rec['stop_latency_s'] <= T_TIMEOUT_STOP,
'post_drift': (rec['post_stop_drift_m'] is not None
and rec['post_stop_drift_m'] <= TOL_STOP_DRIFT)}
rec['checks'] = checks
rec['status'] = STATUS_PASS if all(checks.values()) else STATUS_FAIL
rec['judgement'] = ('最后指令后 %.4f s 停稳(阈值 %.2f s),其后 1 s 位移 %s m'
% (rec['stop_latency_s'], T_TIMEOUT_STOP,
rec['post_stop_drift_m']))
return rec
def _empty_call(probe, name, timeout=8.0):
"""调用 std_srvs/Empty 服务;返回 (ok, 详情)。ok 只认服务的 success 字段。"""
from std_srvs.srv import Empty
if name not in probe.empty_clients:
probe.empty_clients[name] = probe.create_client(Empty, name)
cli = probe.empty_clients[name]
if not cli.wait_for_service(timeout_sec=timeout):
return False, '服务 %s 在 %.0f s 内不可用' % (name, timeout)
fut = cli.call_async(Empty.Request())
t0 = time.monotonic()
while not fut.done() and time.monotonic() - t0 < timeout:
rclpy.spin_once(probe, timeout_sec=0.005)
if not fut.done():
return False, '服务 %s 调用超时' % name
res = fut.result()
ok = bool(res is not None and getattr(res, 'success', True))
return ok, '服务 %s 返回 success=%s' % (name, ok)
def run_pause(probe, out, negative=False):
"""S3 静止暂停/恢复(R1 重写)。
要点:
1. 暂停服务**成功后**先处理一批在途消息再建基准(否则可能拿到暂停前的旧样本);
2. 观察期间持续 spin 回调,取**至少两次带仿真时间戳**的真实状态查询;
3. 用「时钟冻结 + 状态时间戳冻结 + 位姿冻结」三者共同证明暂停生效;
4. 恢复后必须看到时间**实际前进**;
5. 服务失败或数据不足 → INVALID,绝不拿缓存值当结论。
negative=True 是**定向反例**:暂停服务照样调用,但立刻恢复,使世界实际未暂停。
此时 S3 必须不能 PASS(预期 FAIL),用来证明这条判据不是摆设。
"""
rec = {'id': 'S3', 'label': '静止暂停/恢复', 'status': STATUS_INVALID,
'negative_control': negative}
ok, srec = reset_and_settle(probe, SPAWN[0], SPAWN[1], SPAWN[2], 0.0, out)
rec['reset'] = srec
if not ok:
rec['reason'] = '置位/落稳未通过'
return rec
probe.send(0.0, 0.0, 0.0)
probe.pump(0.20)
# 暂停前的运行态基线:两次查询的仿真时间应当不同(证明时钟在走)
run_a, run_b = probe.get_state(), probe.get_state()
rec['running_samples'] = [{'stamp': s['stamp'], 'pos': s['pos']} for s in
(run_a, run_b) if s]
if run_a is None or run_b is None:
rec['reason'] = '暂停前真值查询失败'
return rec
rec['clock_before_pause'] = probe.now()
ok_p, detail_p = _empty_call(probe, '/pause_physics')
rec['pause_call'] = {'ok': ok_p, 'detail': detail_p}
if not ok_p:
rec['reason'] = '暂停服务不可用:%s' % detail_p
return rec
if negative:
# 反例:立刻恢复,世界实际没有暂停
ok_u0, d_u0 = _empty_call(probe, '/unpause_physics')
rec['negative_undo'] = {'ok': ok_u0, 'detail': d_u0}
# ---- 处理在途消息:暂停(反例里是恢复)后先 spin 一段时间再建基准
t_wall = time.monotonic()
while time.monotonic() - t_wall < 0.35:
rclpy.spin_once(probe, timeout_sec=0.01)
# ---- 观察基准
base_clock = probe.now()
base_state = probe.get_state()
if base_state is None:
rec['reason'] = '暂停后基准真值查询失败'
return rec
rec['baseline'] = {'clock': base_clock, 'stamp': base_state['stamp'],
'pos': base_state['pos'], 'yaw': base_state['yaw']}
# ---- 观察窗口:持续处理回调,多次带时间戳的真实查询
samples = []
clocks = []
t_wall = time.monotonic()
while time.monotonic() - t_wall < 1.2:
rclpy.spin_once(probe, timeout_sec=0.01)
clocks.append(probe.now())
s = probe.get_state() # 每次都走真实服务,不用缓存
if s is not None:
samples.append({'stamp': s['stamp'], 'pos': s['pos'], 'yaw': s['yaw'],
'clock_at_call': clocks[-1]})
rec['pause_samples'] = samples
rec['pause_clock_read_count'] = len(clocks)
rec['pause_clock_reads'] = [round(c, 6) for c in clocks[::20]]
rec['wall_pause_s'] = round(time.monotonic() - t_wall, 3)
# ---- 恢复
ok_u, detail_u = _empty_call(probe, '/unpause_physics')
rec['unpause_call'] = {'ok': ok_u, 'detail': detail_u}
if not ok_u:
rec['reason'] = '恢复服务不可用:%s' % detail_u
return rec
after = probe.pump(0.6)
resumed_state = probe.get_state()
# ---- 判据
stamped = [s for s in samples if s['stamp'] > 0]
clock_drift = (max(clocks) - min(clocks)) if clocks else None
stamp_set = sorted({round(s['stamp'], 9) for s in stamped})
pose_delta = 0.0
for s in samples:
pose_delta = max(pose_delta,
math.hypot(s['pos'][0] - base_state['pos'][0],
s['pos'][1] - base_state['pos'][1]),
abs(wrap(s['yaw'] - base_state['yaw'])))
rec['observed'] = {
'stamped_samples': len(stamped),
'clock_reads': len(clocks),
'clock_drift': None if clock_drift is None else round(clock_drift, 9),
'distinct_state_stamps': len(stamp_set),
'state_stamps': [round(x, 6) for x in stamp_set][:6],
'max_pose_delta': round(pose_delta, 9),
'sim_advance_after_resume': round(after - base_clock, 6),
}
checks = {
# 注意:不看 negative 标志。反例里服务同样返回成功,是靠下面的
# 时钟/状态时间戳/位姿观察把它判掉的——否则就成了「按开关判死」。
'pause_service_ok': ok_p,
'samples_min2': len(stamped) >= 2,
'clock_frozen': clock_drift is not None and clock_drift < 1e-9,
'state_time_frozen': len(stamp_set) == 1,
'pose_frozen': pose_delta <= 1e-6,
'resumed': (after - base_clock) > 0.3,
'resume_state_advances': (resumed_state is not None
and resumed_state['stamp'] > base_state['stamp'] + 0.3),
}
rec['checks'] = checks
if not checks['samples_min2']:
rec['status'] = STATUS_INVALID
rec['reason'] = '暂停期间带时间戳的状态查询只有 %d 次,采集不足' % len(stamped)
return rec
rec['status'] = STATUS_PASS if all(checks.values()) else STATUS_FAIL
rec['judgement'] = ('暂停 %.2f s:时钟 %d 次读取漂移 %s,状态时间戳 %d 个取值 %s,'
'位姿最大变化 %.2e m/rad;恢复后仿真时间前进 %.3f s'
% (rec['wall_pause_s'], len(clocks), rec['observed']['clock_drift'],
len(stamp_set), rec['observed']['state_stamps'],
pose_delta, after - base_clock))
return rec
def _tf_edges(tf_samples):
"""把原始 TF 样本汇总成边集合:{父->子: [样本...]}(只用于列数据,不用于证明唯一性)。"""
edges = {}
for tr in tf_samples:
k = '%s->%s' % (tr['frame_id'], tr['child'])
edges.setdefault(k, []).append(tr)
return edges
def _topic_publishers(topic):
"""用 ROS 发布端信息取某话题的发布者节点名集合(唯一性只有这里能给)。"""
import shutil as _sh
exe = _sh.which('ros2') or '/opt/ros/humble/bin/ros2'
try:
p = subprocess.run([exe, 'topic', 'info', topic, '-v'], env=sim_env(),
cwd='/', capture_output=True, text=True, timeout=25)
except subprocess.TimeoutExpired:
return None, '查询 %s 超时' % topic
txt = (p.stdout or '') + (p.stderr or '')
nodes = []
for ln in txt.splitlines():
ln = ln.strip()
if ln.startswith('Node name:'):
nodes.append(ln.split(':', 1)[1].strip())
pubs = []
# 只保留 PUBLISHER 段的节点:按 "Endpoint type: PUBLISHER" 分段解析
cur = None
for ln in txt.splitlines():
ln = ln.strip()
if ln.startswith('Node name:'):
cur = ln.split(':', 1)[1].strip()
elif ln.startswith('Endpoint type:'):
if 'PUBLISHER' in ln and cur and cur not in pubs:
pubs.append(cur)
return pubs, txt[-1200:]
def run_tf_and_odom(probe, out):
"""T1 TF 结构与 odom 一致性(R1 重写)。
- 保留每条 TF 的 frame、时间戳与变换值;
- 检查父子关系、world→odom 是否单位变换、动态 TF 与 /odom 是否一致;
- **唯一性只由 ROS 发布端信息判定**(`ros2 topic info -v` 的 PUBLISHER 节点),
不再用「字典键计数」这种数据侧计数冒充发布者唯一。
"""
rec = {'id': 'T1', 'label': 'TF 与 odom 一致性', 'status': STATUS_INVALID}
tf_s = probe.tf_raw
st_s = probe.tf_static_raw
rec['tf_samples'] = tf_s[:40]
rec['tf_static_samples'] = st_s[:20]
rec['tf_sample_count'] = len(tf_s)
rec['tf_static_sample_count'] = len(st_s)
edges = _tf_edges(tf_s)
sedges = _tf_edges(st_s)
rec['tf_edges'] = {k: len(v) for k, v in edges.items()}
rec['tf_static_edges'] = {k: len(v) for k, v in sedges.items()}
pubs_tf, raw_tf = _topic_publishers('/tf')
pubs_st, raw_st = _topic_publishers('/tf_static')
pubs_odom, _ = _topic_publishers('/odom')
rec['publishers'] = {'tf': pubs_tf, 'tf_static': pubs_st, 'odom': pubs_odom}
rec['publisher_query_raw'] = {'tf': raw_tf, 'tf_static': raw_st}
# world -> odom 必须单位变换
ident = None
if 'world->odom' in sedges:
t = sedges['world->odom'][0]
ident = {'translation': t['translation'], 'rotation': t['rotation'],
'max_trans': max(abs(v) for v in t['translation']),
'max_rot_err': max(abs(t['rotation'][0]), abs(t['rotation'][1]),
abs(t['rotation'][2]),
abs(abs(t['rotation'][3]) - 1.0))}
rec['world_to_odom'] = ident
# 动态 TF 与 /odom 一致性:同时间戳下 odom->base_link 应等于 odom.pose
pairs = []
max_dp = max_dy = 0.0
odom_by_stamp = {round(o['stamp'], 6): o for o in probe.odom}
for t in tf_s:
if t['frame_id'] != 'odom' or t['child'] != 'base_link':
continue
o = odom_by_stamp.get(round(t['stamp'], 6))
if o is None:
continue
dp = math.hypot(t['translation'][0] - o['pos'][0],
t['translation'][1] - o['pos'][1])
dy = abs(wrap(math.atan2(2 * (t['rotation'][3] * t['rotation'][2]
+ t['rotation'][0] * t['rotation'][1]),
1 - 2 * (t['rotation'][1] ** 2 + t['rotation'][2] ** 2))
- o['yaw']))
max_dp = max(max_dp, dp)
max_dy = max(max_dy, dy)
pairs.append({'stamp': round(t['stamp'], 6), 'pos_diff': round(dp, 9),
'yaw_diff': round(dy, 9)})
rec['tf_odom_pairs'] = pairs[:60]
rec['tf_odom_pair_count'] = len(pairs)
rec['tf_odom_max_pos_diff'] = round(max_dp, 9)
rec['tf_odom_max_yaw_diff'] = round(max_dy, 9)
stamps = [o['stamp'] for o in probe.odom]
regress = sum(1 for i in range(1, len(stamps)) if stamps[i] < stamps[i - 1] - 1e-9)
rec['odom'] = {'frames': len(stamps), 'regressions': regress,
'frame_id': probe.odom[0]['frame'] if probe.odom else None,
'child_frame_id': probe.odom[0]['child'] if probe.odom else None}
dup = sorted(set(edges) & set(sedges))
rec['duplicate_edges_across_topics'] = dup
checks = {
# 唯一性由发布端信息判定
'tf_single_publisher': bool(pubs_tf) and len(pubs_tf) == 1,
'tf_static_single_publisher': bool(pubs_st) and len(pubs_st) == 1,
'static_and_dynamic_distinct': bool(pubs_tf and pubs_st) and pubs_tf != pubs_st,
'tf_publisher_is_odom_publisher': bool(pubs_tf and pubs_odom)
and pubs_tf == pubs_odom,
# 结构
'single_edge_each': (len(edges) == 1 and 'odom->base_link' in edges
and len(sedges) == 1 and 'world->odom' in sedges),
'no_edge_in_both': not dup,
'world_to_odom_identity': bool(ident) and ident['max_trans'] <= 1e-9
and ident['max_rot_err'] <= 1e-9,
'tf_matches_odom': (len(pairs) >= 10 and max_dp <= 1e-6 and max_dy <= 1e-6),
'odom_frames': (rec['odom']['frame_id'] == 'odom'
and rec['odom']['child_frame_id'] == 'base_link'),
'odom_monotonic': regress == 0 and len(stamps) > 100,
}
rec['checks'] = checks
if pubs_tf is None or pubs_st is None:
rec['status'] = STATUS_INVALID
rec['reason'] = '发布端信息查询失败,无法判定 TF 唯一性'
return rec
rec['status'] = STATUS_PASS if all(checks.values()) else STATUS_FAIL
rec['judgement'] = ('/tf 发布者 %s、/tf_static 发布者 %s、/odom 发布者 %s;'
'边 %s / %s;world→odom 平移 %.1e 旋转误差 %.1e;'
'TF-odom 配对 %d 条,最大差 %.2e m / %.2e rad'
% (pubs_tf, pubs_st, pubs_odom, rec['tf_edges'],
rec['tf_static_edges'],
ident['max_trans'] if ident else -1,
ident['max_rot_err'] if ident else -1,
len(pairs), max_dp, max_dy))
return rec
def sh_cmd(cmd, timeout=15):
p = subprocess.run(cmd, shell=True, env=sim_env(), cwd='/',
capture_output=True, text=True, timeout=timeout)
return {'cmd': cmd, 'rc': p.returncode,
'out': (p.stdout or '').strip()[-400:],
'err': (p.stderr or '').strip()[-400:]}
def check_model_geometry(out, drive='planar'):
"""从展开后的 SDF 模型计算外包络,与配置值对照(不依赖 Gazebo 运行时)。"""
src = os.path.join(WS, 'src', 'r2027_robot_description', 'sdf',
'r2027_omni_robot.sdf.xacro')
expanded = os.path.join(out, 'model_expanded.sdf')
xacro = shutil.which('xacro') or '/opt/ros/humble/bin/xacro'
p = subprocess.run([xacro, src, 'drive:='+drive, '-o', expanded],
env=sim_env(), capture_output=True, text=True, timeout=60)
if p.returncode != 0:
return {'ok': False, 'error': p.stderr[-400:], 'path': expanded}
import xml.etree.ElementTree as ET
root = ET.parse(expanded).getroot()
def rot(rpy):
r, pi_, y = rpy
cr, sr = math.cos(r), math.sin(r)
cp, sp = math.cos(pi_), math.sin(pi_)
cy, sy = math.cos(y), math.sin(y)
return [[cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr],
[sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr],
[-sp, cp * sr, cp * cr]]
def apply(R, v):
return [sum(R[i][j] * v[j] for j in range(3)) for i in range(3)]
def matmul(A, B):
return [[sum(A[i][k] * B[k][j] for k in range(3)) for j in range(3)]
for i in range(3)]
def pose_of(el):
e = el.find('pose')
if e is None or not (e.text or '').strip():
return [0.0] * 3, [0.0] * 3
v = [float(x) for x in e.text.split()]
return v[:3], v[3:6]
lo = [1e9] * 3
hi = [-1e9] * 3
parts = []
_seen = set()
for link in root.iter('link'):
lp, lr = pose_of(link)
Rl = rot(lr)
for el in list(link.findall('collision')) + list(link.findall('visual')):
g = el.find('geometry')
if g is None:
continue
cp, cr = pose_of(el)
c = [lp[i] + apply(Rl, cp)[i] for i in range(3)]
R = matmul(Rl, rot(cr))
box = g.find('box')
cyl = g.find('cylinder')
sphere = g.find('sphere')
pts = []
if box is not None:
sz = [float(v) / 2.0 for v in box.find('size').text.split()]
for sx in (-1, 1):
for sy in (-1, 1):
for szz in (-1, 1):
pts.append(apply(R, [sx * sz[0], sy * sz[1], szz * sz[2]]))
shape = 'box %s' % box.find('size').text.strip()
elif cyl is not None:
r = float(cyl.find('radius').text)
l = float(cyl.find('length').text)
for ang in range(0, 360, 15):
a = math.radians(ang)
for zz in (-l / 2.0, l / 2.0):
pts.append(apply(R, [r * math.cos(a), r * math.sin(a), zz]))
shape = 'cylinder r=%.3f L=%.3f' % (r, l)
elif sphere is not None:
r = float(sphere.find('radius').text)
pts = [[v if i==axis else 0. for i in range(3)]
for axis in range(3) for v in (-r,r)]
shape = 'sphere contact proxy r=%.3f' % r
else:
continue
for pp in pts:
w = [c[i] + pp[i] for i in range(3)]
for i in range(3):
lo[i] = min(lo[i], w[i])
hi[i] = max(hi[i], w[i])
key = (link.get('name'), shape, tuple(round(v, 6) for v in c))
if key not in _seen:
_seen.add(key)
parts.append({'link': link.get('name'), 'shape': shape,
'center': [round(v, 6) for v in c]})
size = [hi[i] - lo[i] for i in range(3)]
return {'ok': True, 'path': expanded,
'bbox_min': [round(v, 6) for v in lo],
'bbox_max': [round(v, 6) for v in hi],
'size_xyz': [round(v, 6) for v in size],
'footprint_xy': [round(size[0], 6), round(size[1], 6)],
'ground_below_base_link': round(-lo[2], 6),
'parts': parts}
def write_report(out, res):
L = []
A = L.append
A('# SIM-P2-001 简化全向机器人验收报告')
A('')
A('- 工具:`sim_ws/tools/check_omni_robot.py`(sha256 `%s`)'
% sha256_file(os.path.abspath(__file__)))
A('- 证据目录:`%s`' % out)
A('- 模型:`r2027_omni`(`r2027_robot_description/sdf/r2027_omni_robot.sdf.xacro`)')
A('- 世界:`robocon_gazebo/worlds/robocon_robot.world`(原场地 + `libgazebo_ros_state.so`)')
A('')
geo = res.get('geometry') or {}
if geo.get('ok'):
A('## 0. 模型实际外包络(由展开后的 SDF 模型计算)')
A('')
A('| 项 | 值 |')
A('|---|---|')
A('| XY 外包络 | **%.4f × %.4f m** |' % tuple(geo['footprint_xy']))
A('| 含高度 | %.4f m(z %.4f … %.4f) |'
% (geo['size_xyz'][2], geo['bbox_min'][2], geo['bbox_max'][2]))
A('| base_link 下方名义触地面 | %.4f m |' % geo['ground_below_base_link'])
A('')
A('部件中心(base_link 系):%s'
% '、'.join('%s(%s)@%s' % (p['link'], p['shape'], p['center'])
for p in geo['parts']))
A('')
A('## 1. 逐例结果')
A('')
A('| 用例 | 场景 | 指令 | 实测 Δ | 误差 | 漂移 | odom-真值(位置/yaw/速度) | 判定 |')
A('|---|---|---|---|---|---|---|---|')
for c in res['cases']:
if c['id'].startswith('M'):
d = c.get('delta') or {}
e = c.get('errors') or {}
al = c.get('align') or {}
A('| %s | %s | vx=%.2f vy=%.2f wz=%.2f | (%.4f, %.4f) Δyaw=%.4f | '
'(%+.4f, %+.4f) / %+.4f | %.4f | %.4f / %.4f / %.4f | **%s** |'
% (c['id'], c['label'], c['cmd']['vx'], c['cmd']['vy'], c['cmd']['wz'],
d.get('dx', 0), d.get('dy', 0), d.get('dyaw', 0),
e.get('ex', 0), e.get('ey', 0), e.get('eyaw', 0),
c.get('drift_m') or 0.0,
al.get('max_pos_diff', 0), al.get('max_yaw_diff', 0),
al.get('max_vel_diff', 0), c['status']))
else:
A('| %s | %s | — | — | — | — | — | **%s** |' % (c['id'], c['label'], c['status']))
A('')
A('## 2. 逐项判据')
A('')
for c in res['cases']:
A('### %s %s —— %s' % (c['id'], c['label'], c['status']))
A('')
A('%s' % (c.get('judgement') or c.get('reason') or ''))
A('')
ch = c.get('checks') or {}
if ch:
A('| 判据 | 结果 |')
A('|---|---|')
for k, v in ch.items():
A('| %s | %s |' % (k, '通过' if v else '**未通过**'))
A('')
if c.get('body_frame_note') and c['body_frame_note'] != '—':
A('- 车体系速度:%s' % c['body_frame_note'])
if c.get('reset'):
r = c['reset']
A('- 置位/落稳:set_ok=%s,静止高度 %.4f m,残余速度 %s m/s,'
'落稳期漂移 %.4f m,耗时 %.2f s'
% (r.get('set_ok'), r.get('settle_height_m') or 0,
('%.4f' % r['residual_speed']) if r.get('residual_speed') is not None else '—',
r.get('drift_during_settle_m') or 0, r.get('settle_sim_s') or 0))
A('')
A('## 3. 计数')
A('')
A('PASS %d / FAIL %d / INVALID %d' % (res['counts'][STATUS_PASS],
res['counts'][STATUS_FAIL],
res['counts'][STATUS_INVALID]))
A('')
A('## 4. 结论口径')
A('')
A('- 只验证**平地运动接口**,不据此评价坡道动力学、爬坡、制动距离或实车性能。')
A('- 外包络 0.80×0.80 m 来自 `planner_vehicle.yaml`;质量 5.51 kg(车体)+ 1.2×4 kg(轮)'
'是**建模假设**,惯量由简化几何计算,不等同实车。')
A('- 轮子为圆柱固定支撑件,本机插件不含辊子各向异性摩擦,**不代表麦轮真实接触**。')
A('- 采集缺失/无效的用例记 `INVALID`,不判 PASS。')
text = '\n'.join(L) + '\n'
with open(os.path.join(out, 'P2_REPORT.md'), 'w', encoding='utf-8') as f:
f.write(text)
return text
def main():
ap = argparse.ArgumentParser(description='SIM-P2-001 全向机器人验收')
ap.add_argument('--out', default=os.path.join(OUTROOT, 'run'))
ap.add_argument('--only', default='', help='只跑指定用例,逗号分隔(M1..M5,S1,S2,S3,T1)')
ap.add_argument('--gui', action='store_true')
ap.add_argument('--drive', choices=('planar', 'contact'), default='planar')
ap.add_argument('--s3-negative', action='store_true',
help='定向反例:暂停后立刻恢复(世界实际未暂停),S3 必须不能 PASS')
ap.add_argument('--t1-negative', action='store_true',
help='定向反例:临时加一条重复的 world->odom,T1 必须拒绝')
args = ap.parse_args()
# The probe and the child launch must join the same isolated ROS domain.
os.environ.update(sim_env())
out = ensure_dir(args.out)
only = [x.strip() for x in args.only.split(',') if x.strip()]
res = {'task': 'SIM-P2-001', 'drive': args.drive, 'cases': [], 'counts': {}}
res['geometry'] = check_model_geometry(out, args.drive)
log('[geometry] XY 外包络 %s m,base_link 下方触地面 %s m'
% (res['geometry'].get('footprint_xy'), res['geometry'].get('ground_below_base_link')))
if port_open(port=11355):
log('[FATAL] master 端口 11355 已被占用;不动占用者,直接退出')
return EXIT_INVALID
sim = Sim(os.path.join(out, 'sim'))
ok, why = sim.start(gui=args.gui, drive=args.drive)
res['sim_start'] = {'ok': ok, 'detail': why}
log('[sim] %s' % why)
if not ok:
res['teardown'] = sim.stop()
return EXIT_INVALID
rclpy.init()
probe = Probe()
try:
# 就绪:时钟前进 + odom 有消息 + 服务可用 + 模型位姿可查
if not probe.wait_clock(60.0):
log('[FATAL] /clock 未开始发布')
return EXIT_INVALID
ok_odom = False
t0 = time.monotonic()
while time.monotonic() - t0 < 60.0:
probe.pump(0.2)
if len(probe.odom) >= 5:
ok_odom = True
break
st0 = probe.get_state()
res['ready'] = {'clock': True, 'odom_msgs': len(probe.odom),
'odom_ok': ok_odom,
'state_ok': st0 is not None,
'spawn_pose_observed': st0['pos'] if st0 else None,
'get_entity_state_header_stamp': st0['stamp'] if st0 else None,
'get_entity_state_frame': st0['frame_id'] if st0 else None}
log('[ready] %r' % res['ready'])
if not (ok_odom and st0 is not None):
log('[FATAL] 采集未就绪')
res['counts'] = {STATUS_PASS: 0, STATUS_FAIL: 0, STATUS_INVALID: 1}
return EXIT_INVALID
# 出生位姿证据:先让它落稳
_, spawn_rec = reset_and_settle(probe, SPAWN[0], SPAWN[1], SPAWN[2], 0.0, out)
res['spawn'] = spawn_rec
log('[spawn] 落稳高度 %s,残余速度 %s'
% (spawn_rec.get('settle_height_m'), spawn_rec.get('residual_speed')))
def want(cid):
return (not only) or (cid in only)
for case in CASES:
if not want(case['id']):
continue
cdir = ensure_dir(os.path.join(out, 'cases', case['id']))
log('[RUN] %s %s' % (case['id'], case['label']))
rec = run_motion_case(probe, case, out, cdir)
with open(os.path.join(cdir, 'case.json'), 'w', encoding='utf-8') as f:
json.dump(rec, f, ensure_ascii=False, indent=2)
log(' -> %s %s' % (rec['status'],
(rec.get('judgement') or rec.get('reason') or '')[:160]))
res['cases'].append({k: v for k, v in rec.items()
if k not in ('odom_during_cmd', 'align_pairs')})
for fn, cid in ((run_explicit_zero, 'S1'), (run_timeout_stop, 'S2'),
(run_pause, 'S3')):
if not want(cid):
continue
cdir = ensure_dir(os.path.join(out, 'cases', cid))
log('[RUN] %s' % cid)
rec = (fn(probe, out, negative=args.s3_negative)
if fn is run_pause else fn(probe, out))
with open(os.path.join(cdir, 'case.json'), 'w', encoding='utf-8') as f:
json.dump(rec, f, ensure_ascii=False, indent=2)
log(' -> %s %s' % (rec['status'],
(rec.get('judgement') or rec.get('reason') or '')[:160]))
res['cases'].append({k: v for k, v in rec.items() if k != 'trail'})
if want('T1'):
dup = None
if args.t1_negative:
dup = TFDuplicator()
probe.pump(0.8) # 等发现完成
rec = run_tf_and_odom(probe, out)
if dup is not None:
rec['negative_control'] = True
try:
res['t1_negative_publisher'] = dup.get_name()
dup.destroy_node()
res['t1_negative_cleaned'] = True
except Exception: # noqa: BLE001
res['t1_negative_cleaned'] = False
cdir = ensure_dir(os.path.join(out, 'cases', 'T1'))
with open(os.path.join(cdir, 'case.json'), 'w', encoding='utf-8') as f:
json.dump(rec, f, ensure_ascii=False, indent=2)
log('[RUN] T1 -> %s %s' % (rec['status'], rec['judgement'][:160]))
res['cases'].append(rec)
# odom 原始数据单独存一份
with open(os.path.join(out, 'odom_raw.json'), 'w', encoding='utf-8') as f:
json.dump({'count': len(probe.odom),
'first': probe.odom[0] if probe.odom else None,
'last': probe.odom[-1] if probe.odom else None,
'samples': probe.odom[::10]}, f, ensure_ascii=False, indent=1)
res['tf'] = {'tf': dict(probe.tf_pairs), 'tf_static': dict(probe.tf_static_pairs)}
finally:
res['ros_cleanup_errors'] = shutdown_probe(probe)
res['teardown'] = sim.stop()
log('[teardown] %r' % res['teardown'])
res['counts'] = {STATUS_PASS: sum(1 for c in res['cases'] if c['status'] == STATUS_PASS),
STATUS_FAIL: sum(1 for c in res['cases'] if c['status'] == STATUS_FAIL),
STATUS_INVALID: sum(1 for c in res['cases']
if c['status'] == STATUS_INVALID)}
negatives = [c['id'] for c in res['cases'] if c.get('negative_control')]
res['negative_run'] = bool(negatives)
res['negative_cases'] = negatives
with open(os.path.join(out, 'p2_001.json'), 'w', encoding='utf-8') as f:
json.dump(res, f, ensure_ascii=False, indent=2)
write_report(out, res)
log('')
if negatives:
log('【反例运行】%s 预期非 PASS;这里的 FAIL 不计为生产用例失败'
% '、'.join(negatives))
log('PASS %d / FAIL %d / INVALID %d'
% (res['counts'][STATUS_PASS], res['counts'][STATUS_FAIL],
res['counts'][STATUS_INVALID]))
if res['counts'][STATUS_INVALID]:
return EXIT_INVALID
return EXIT_OK if res['counts'][STATUS_FAIL] == 0 else EXIT_FAIL
if __name__ == '__main__':
sys.exit(main())