diff --git a/minco_ws/docs/diagnostics/DUAL_GEOMETRY.md b/minco_ws/docs/diagnostics/DUAL_GEOMETRY.md new file mode 100644 index 0000000..3c438d0 --- /dev/null +++ b/minco_ws/docs/diagnostics/DUAL_GEOMETRY.md @@ -0,0 +1,60 @@ +# 静止双 MID360 安装及公共平面检查 + +此诊断独立于正式场地任务。仅运行雷达驱动、原始数据记录器和离线分析器, +不启动 Point-LIO、TF、融合发布、规划、串口或底盘,不修改现场 site.yaml。 +坐标称为局部 body,使用配置的 X 前、Y 左、Z 上与安装参考点,不声明已对齐比赛场地。 + +先确保车体和环境静止、无其他雷达驱动占用端口。真实安装尺寸、轴方向及 SN 与安装位置的 +对应关系必须由现场核对;点云重合只能提供证据,不能代替实物确认。 +车架空时,地面在 body 中会比车轮落地时更低,不能把该差值直接当安装高度误差。 + +## 采集 + +```bash +cd /home/xie/RC2027_BR_code +source /opt/ros/humble/setup.bash +source minco_ws/install/mission/setup.bash +export ROS_DOMAIN_ID=78 ROS_LOCALHOST_ONLY=1 +python3 minco_ws/docs/diagnostics/capture_dual_geometry.py \ + --site /home/xie/br_vehicle_config_rain_20261119_explicit/site.yaml \ + --out minco_ws/log/rain-net-006/static_02 --duration 20 \ + --discovery-interface enp1s0 --discovery-host 192.168.1.50 +``` + +输出目录必须不存在。先检查驱动配置要求的原始 CustomMsg、每设备独立话题、SDK 零外参和 +内部融合关闭,随后进行有限时间采样,最后停止本次驱动。 +记录上下两路 CustomMsg 和各自 IMU 的原始 CDR,不重写源时间、offset 或坐标。 +bag 的存储时间是接收时间,消息载荷中的设备时间原样保留。 +保存 site/driver/SDK JSON 副本、源时间/点数元数据、命令及退出日志。 +`capture.json` 的 PASS 仅表示记录成功,不是安装几何通过。 + +## 离线分析 + +```bash +export OPENBLAS_NUM_THREADS=1 OMP_NUM_THREADS=1 +python3 minco_ws/docs/diagnostics/analyze_dual_geometry.py \ + minco_ws/log/rain-net-006/static_02 \ + --out minco_ws/log/rain-net-006/static_02/analysis +``` + +分析器只施加配置中的刚体变换,不做 ICP、优化平移、拟合后对齐或场地先验变换。 +保留 0.1–8 m 范围内有限点,并以 4 cm 体素质心减少离线分析数量;完整原始数据仍在 bag 中。 +彩色 PLY、XY/XZ/YZ 图不去地面、不去自身回波;仅平面拟合副本排除配置的车体包络。 +每个传感器独立提取平面,以候选法向、原点截距及共同可见切向区域筛选,再双向报告 +实际点到另一平面的残差。筛选阈值只是候选搜索范围,不是允许安装误差。 +未有共同观测、共面但空间不重叠、单一平面及重复墙面都不能据此确认全部六自由度外参。 + +`--swap-roles` 只在离线副本中交换两路的角色,供排查接线/命名疑点;不会修改配置或发布消息。 +输出明确记录使用的话题及是否交换。任何这样的假设都必须经过实物 SN 核对后再决定现场改动。 +IMU 统计给出两路重力方向、均值与波动;加速度偏置会影响倾角,静止重力不能验证 yaw。 +报告状态保留 MEASUREMENTS_PENDING,最终验收需结合现场测量及公共目标确认。 + +## 验证分析器 + +```bash +python3 -m unittest discover -s minco_ws/docs/diagnostics -p test_dual_geometry.py -v +``` + +覆盖生产 `project_scan` 与诊断坐标变换/原始点时刻的一致性、带离群点的平面恢复、 +5 cm 平行面偏差不被对齐消除、没有共同可见区域时拒绝匹配、线状数据不构成平面。 +诊断依赖 ROS Humble、NumPy、SciPy、Matplotlib 与 rosbag2_py,使用现有安装,不下载依赖。 diff --git a/minco_ws/docs/diagnostics/analyze_dual_geometry.py b/minco_ws/docs/diagnostics/analyze_dual_geometry.py new file mode 100644 index 0000000..882e0bb --- /dev/null +++ b/minco_ws/docs/diagnostics/analyze_dual_geometry.py @@ -0,0 +1,285 @@ +#!/usr/bin/env python3 +"""Offline stationary dual-lidar plane diagnostics; never calibrate or publish.""" +import argparse +import hashlib +import json +import math +from pathlib import Path + +import numpy as np + + +def yaw_matrix(yaw): + c, s = math.cos(yaw), math.sin(yaw) + return np.array([[c, -s, 0.], [s, c, 0.], [0., 0., 1.]]) + + +def voxel_centroids(points, size=.04): + keys = np.floor(points / size).astype(np.int64) + _, inverse, count = np.unique(keys, axis=0, return_inverse=True, return_counts=True) + return np.column_stack([np.bincount(inverse, weights=points[:, i]) / count for i in range(3)]) + + +def fit_plane(points): + center = points.mean(axis=0) + eigenvalues, vectors = np.linalg.eigh((points - center).T @ (points - center) / len(points)) + normal = vectors[:, 0] + if normal[np.argmax(np.abs(normal))] < 0: + normal = -normal + return normal, -float(normal @ center), eigenvalues + + +def extract_planes(points, seed=24, max_planes=8, threshold=.02): + rng = np.random.default_rng(seed) + remaining = np.arange(len(points)) + output = [] + for _ in range(max_planes): + if len(remaining) < 300: + break + candidates = points[remaining] + score_points = candidates[rng.choice(len(candidates), min(6000, len(candidates)), replace=False)] + triples = candidates[rng.integers(0, len(candidates), (640, 3))] + normals = np.cross(triples[:, 1] - triples[:, 0], triples[:, 2] - triples[:, 0]) + norms = np.linalg.norm(normals, axis=1) + good = norms > .02 + normals = normals[good] / norms[good, None] + offsets = -np.einsum('ij,ij->i', normals, triples[good, 0]) + if not len(normals): + break + scores = [] + for begin in range(0, len(normals), 64): + distances = np.abs(score_points @ normals[begin:begin + 64].T + offsets[begin:begin + 64]) + scores.extend(np.sum(distances < threshold, axis=0).tolist()) + best = int(np.argmax(scores)) + normal, offset = normals[best], float(offsets[best]) + for _ in range(3): + mask = np.abs(candidates @ normal + offset) < threshold + if mask.sum() < 300: + break + normal, offset, _ = fit_plane(candidates[mask]) + mask = np.abs(candidates @ normal + offset) < threshold + if mask.sum() < 300: + break + indices = remaining[mask] + normal, offset, eigenvalues = fit_plane(points[indices]) + if eigenvalues[1] < .01: + break + residuals = np.abs(points[indices] @ normal + offset) + output.append({'id': len(output), 'normal': normal.tolist(), 'offset_m': offset, + 'count': len(indices), 'rms_m': float(np.sqrt(np.mean(residuals ** 2))), + 'p95_m': float(np.percentile(residuals, 95)), + 'center': points[indices].mean(axis=0).tolist(), + 'bbox_min': points[indices].min(axis=0).tolist(), + 'bbox_max': points[indices].max(axis=0).tolist(), + 'eigenvalues': eigenvalues.tolist(), 'indices': indices}) + remaining = remaining[~mask] + return output + + +def compare_planes(clouds, planes): + from scipy.spatial import cKDTree + pairs = [] + for a in planes[0]: + an = np.array(a['normal']) + pa = clouds[0][a['indices']] + for b in planes[1]: + bn = np.array(b['normal']) + sign = 1 if an @ bn >= 0 else -1 + bn = bn * sign + bd = b['offset_m'] * sign + angle = float(np.degrees(np.arccos(np.clip(an @ bn, -1, 1)))) + if angle > 10 or abs(a['offset_m'] - bd) > .35: + continue + pb = clouds[1][b['indices']] + axis = np.eye(3)[int(np.argmin(np.abs(an)))] + u = np.cross(an, axis) + u /= np.linalg.norm(u) + v = np.cross(an, u) + basis = np.column_stack([u, v]) + a_distance = cKDTree(pb @ basis).query(pa @ basis, workers=1)[0] + b_distance = cKDTree(pa @ basis).query(pb @ basis, workers=1)[0] + a_common, b_common = a_distance < .12, b_distance < .12 + if min(a_common.sum(), b_common.sum()) < 50: + continue + residual_a = np.abs(pa[a_common] @ bn + bd) + residual_b = np.abs(pb[b_common] @ an + a['offset_m']) + residual = np.r_[residual_a, residual_b] + pairs.append({'upper_id': a['id'], 'lower_id': b['id'], 'angle_deg': angle, + 'offset_at_origin_difference_m': abs(a['offset_m'] - bd), + 'common_upper_voxels': int(a_common.sum()), + 'common_lower_voxels': int(b_common.sum()), + 'cross_plane_abs_p50_m': float(np.median(residual)), + 'cross_plane_abs_p95_m': float(np.percentile(residual, 95)), + 'upper_to_lower_abs_p50_m': float(np.median(residual_a)), + 'lower_to_upper_abs_p50_m': float(np.median(residual_b))}) + return pairs + + +def write_ply(path, clouds): + dtype = np.dtype([('x', '= .1) & (ranges <= 8) + body = xyz[roi] @ rotations[i].T + mounts[i] + voxels = voxel_centroids(body) + clouds.append(voxels) + # Only exclude configured vehicle envelope in the plane-fit copy. + # The saved raw bag and overview/PLY retain these returns. + self_hit = np.all((voxels >= self_min) & (voxels <= self_max), axis=1) + fit_cloud = voxels[~self_hit] + analysis_clouds.append(fit_cloud) + sensor_planes = extract_planes(fit_cloud, seed=24 + i) + planes.append(sensor_planes) + imu = np.array(imus[i], dtype=np.float64) + if len(imu) < 100: + raise ValueError('insufficient IMU') + acc = imu[:, 1:4] @ rotations[i].T + gyro = imu[:, 4:7] @ rotations[i].T + gravity = acc.mean(axis=0) + report['sensors'][name] = { + 'source_topic': topics[i], + 'raw_points': len(xyz), 'nonfinite_points': int((~valid).sum()), + 'roi_points': int(roi.sum()), 'voxel_count': len(voxels), + 'plane_fit_excluded_self_voxels': int(self_hit.sum()), + 'imu_count': len(imu), 'imu_source_nonmonotonic': int(np.sum(np.diff(imu[:, 0]) <= 0)), + 'mean_acceleration_body_g': gravity.tolist(), 'acceleration_std_g': acc.std(axis=0).tolist(), + 'mean_gyro_body_native': gyro.mean(axis=0).tolist(), 'gyro_std_native': gyro.std(axis=0).tolist(), + 'gravity_tilt_deg': float(np.degrees(np.arctan2(np.linalg.norm(gravity[:2]), gravity[2]))), + 'planes': [{k: v for k, v in p.items() if k != 'indices'} for p in sensor_planes]} + report['plane_pairs'] = compare_planes(analysis_clouds, planes) + normals = np.array([planes[0][p['upper_id']]['normal'] for p in report['plane_pairs']]) + if len(normals): + singular = np.linalg.svd(normals, compute_uv=False) + report['matched_normal_singular_values'] = singular.tolist() + report['matched_normal_rank_at_0_1'] = int((singular > .1).sum()) + else: + report['matched_normal_rank_at_0_1'] = 0 + av = np.array(report['sensors']['upper']['mean_acceleration_body_g']) + bv = np.array(report['sensors']['lower']['mean_acceleration_body_g']) + report['gravity_direction_difference_deg'] = float(np.degrees(np.arccos( + np.clip(av @ bv / np.linalg.norm(av) / np.linalg.norm(bv), -1, 1)))) + report['limitations'] = ['Physical dimensions and scene/stationary confirmation required', + 'Gravity cannot determine yaw; accelerometer bias affects tilt', + 'Plane matches are geometric candidates, not surveyed correspondences', + 'A single plane cannot validate all six extrinsic degrees of freedom', + 'No ground removal, ICP alignment or field pose is used'] + for i, name in enumerate(('upper', 'lower')): + np.save(args.out / (name + '_body_voxels.npy'), clouds[i]) + write_ply(args.out / 'configured_overlay.ply', clouds) + overview(args.out / 'configured_overlay.png', clouds, mounts) + (args.out / 'geometry_report.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps({k: v for k, v in report.items() if k != 'sensors'}, indent=2)) + for name, sensor in report['sensors'].items(): + print(name, 'raw_points', sensor['raw_points'], 'voxel_count', sensor['voxel_count'], + 'planes', [(p['id'], p['count'], p['normal'], p['offset_m']) for p in sensor['planes']]) + + +if __name__ == '__main__': + main() diff --git a/minco_ws/docs/diagnostics/capture_dual_geometry.py b/minco_ws/docs/diagnostics/capture_dual_geometry.py new file mode 100644 index 0000000..bcd96d9 --- /dev/null +++ b/minco_ws/docs/diagnostics/capture_dual_geometry.py @@ -0,0 +1,138 @@ +#!/usr/bin/env python3 +"""Bounded driver-only raw recording for stationary installation diagnostics.""" +import argparse +import hashlib +import json +import os +from pathlib import Path +import re +import shutil +import signal +import subprocess +import time + +import rclpy +from rclpy.node import Node +from rclpy.qos import qos_profile_sensor_data +import rosbag2_py +import yaml +from livox_ros_driver2.msg import CustomMsg +from sensor_msgs.msg import Imu +from br_vehicle_mission.deployment import load_driver +from br_vehicle_mission.livox_scan import read_scan + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--site', required=True) + parser.add_argument('--out', required=True) + parser.add_argument('--duration', type=float, default=20.) + parser.add_argument('--discovery-interface', default='') + parser.add_argument('--discovery-host', default='') + args = parser.parse_args() + if not 2 <= args.duration <= 120: + parser.error('duration must be 2..120 seconds') + if bool(args.discovery_interface) != bool(args.discovery_host): + parser.error('discovery interface and host must be supplied together') + site_path = Path(args.site).resolve() + site = yaml.safe_load(site_path.read_text()) + driver_path = Path(site['driver_params_file']) + driver = load_driver(driver_path) + root = Path(args.out).resolve() + root.mkdir(parents=True, exist_ok=False) + for name, path in [('site.yaml', site_path), ('driver.yaml', driver_path), + ('dual_mid360.json', Path(driver['user_config_path']))]: + shutil.copyfile(path, root / name) + sensors = site['sensors'] + topics = {'upper': (sensors['upper_lidar_topic'], CustomMsg, 'livox_ros_driver2/msg/CustomMsg'), + 'lower': (sensors['lower_lidar_topic'], CustomMsg, 'livox_ros_driver2/msg/CustomMsg'), + 'upper_imu': (sensors['upper_imu_topic'], Imu, 'sensor_msgs/msg/Imu'), + 'lower_imu': (sensors['lower_lidar_topic'].replace('/lidar_', '/imu_'), Imu, + 'sensor_msgs/msg/Imu')} + command = ['ros2', 'launch', 'br_vehicle_mission', 'dual_mid360_driver.launch.py', + 'driver_params_file:=' + str(driver_path)] + if args.discovery_interface: + command += ['driver_discovery_interface:=' + args.discovery_interface, + 'driver_discovery_host_ip:=' + args.discovery_host] + report = {'scope': 'Raw stationary geometry recording; driver only; no LIO, TF, planner or chassis', + 'command': command, 'start_ns': time.time_ns(), 'ros_domain_id': os.environ.get('ROS_DOMAIN_ID'), + 'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + 'samples': {key: [] for key in topics}, 'errors': []} + process = None + writer = None + rclpy.init() + node = Node('dual_geometry_recorder') + + def receive(key, raw): + receive_ns = node.get_clock().now().nanoseconds + topic, _, _ = topics[key] + writer.write(topic, raw, receive_ns) + row = {'receive_ns': receive_ns} + if key in ('upper', 'lower'): + scan = read_scan(raw) + offsets = scan.offsets + if not len(offsets) or scan.timebase != scan.stamp_ns: + raise ValueError('empty scan or inconsistent timebase') + if (offsets[1:] < offsets[:-1]).any() or int(offsets.max()) >= 100000000: + raise ValueError('invalid point offsets') + row.update(stamp_ns=scan.stamp_ns, points=scan.point_num, frame=scan.frame, + lidar_id=scan.lidar_id, end_ns=scan.timebase + int(offsets.max())) + report['samples'][key].append(row) + + try: + with (root / 'driver.log').open('w') as log: + process = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True) + try: + end = time.monotonic() + 6 + while time.monotonic() < end: + if process.poll() is not None: + raise RuntimeError('driver exited during warmup') + rclpy.spin_once(node, timeout_sec=.05) + writer = rosbag2_py.SequentialWriter() + writer.open(rosbag2_py.StorageOptions(uri=str(root / 'raw_bag'), storage_id='sqlite3'), + rosbag2_py.ConverterOptions('', '')) + for key, (topic, cls, type_name) in topics.items(): + writer.create_topic(rosbag2_py.TopicMetadata(name=topic, type=type_name, + serialization_format='cdr')) + node.create_subscription(cls, topic, lambda raw, k=key: receive(k, raw), + qos_profile_sensor_data, raw=True) + report['sample_start_ns'] = time.time_ns() + end = time.monotonic() + args.duration + while time.monotonic() < end: + if process.poll() is not None: + raise RuntimeError('driver exited during recording') + rclpy.spin_once(node, timeout_sec=.05) + report['sample_end_ns'] = time.time_ns() + finally: + if process.poll() is None: + process.send_signal(signal.SIGINT) + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + report['forced_sigterm'] = True + os.killpg(process.pid, signal.SIGTERM) + process.wait(timeout=5) + report['driver_launcher_exit'] = process.returncode + except Exception as exc: + report['errors'].append(repr(exc)) + finally: + node.destroy_node() + rclpy.shutdown() + writer = None + report['end_ns'] = time.time_ns() + report['counts'] = {key: len(rows) for key, rows in report['samples'].items()} + log_path = root / 'driver.log' + report['container_clean_shutdown'] = bool(log_path.exists() and re.search( + r'\[component_container_mt-\d+\]: process has finished cleanly', log_path.read_text())) + report['status'] = 'PASS' if (not report['errors'] and not report.get('forced_sigterm') + and report.get('driver_launcher_exit') == 0 + and report['container_clean_shutdown'] + and min(report['counts'].values()) >= 20) else 'FAIL' + (root / 'capture.json').write_text(json.dumps(report, indent=2) + '\n') + print(json.dumps({key: value for key, value in report.items() if key != 'samples'}, indent=2)) + return 0 if report['status'] == 'PASS' else 1 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/minco_ws/docs/diagnostics/test_dual_geometry.py b/minco_ws/docs/diagnostics/test_dual_geometry.py new file mode 100644 index 0000000..457814d --- /dev/null +++ b/minco_ws/docs/diagnostics/test_dual_geometry.py @@ -0,0 +1,60 @@ +"""Synthetic counterexamples for the stationary plane diagnostic.""" +import unittest +import numpy as np + +from analyze_dual_geometry import compare_planes, extract_planes, fit_plane, yaw_matrix + + +def one_plane(points): + normal, offset, _ = fit_plane(points) + return {'id': 0, 'normal': normal.tolist(), 'offset_m': offset, + 'indices': np.arange(len(points))} + + +class GeometryDiagnosticTests(unittest.TestCase): + def setUp(self): + self.rng = np.random.default_rng(472) + self.xy = self.rng.uniform(-2, 2, (1200, 2)) + + def test_configured_yaw_matches_production_projection_and_preserves_time(self): + from br_vehicle_mission.dual_lidar_fusion import project_scan + raw = np.array([[2., 0., .3], [0., -2., .7], [-2., 1., -.5]]) + offsets = np.array([0, 1000, 49999000], dtype=np.int64) + mount = np.array([.325, 0., .044]) + history = [(1., np.zeros(3), np.array([0., 0., 0., 1.])), + (1.075, np.zeros(3), np.array([0., 0., 0., 1.]))] + xyz, origins, stamps, _ = project_scan(raw, offsets, 1000000000, history, + mount, yaw_matrix(np.pi / 2), False) + expected = np.column_stack([-raw[:, 1], raw[:, 0], raw[:, 2]]) + mount + np.testing.assert_allclose(xyz, expected, atol=1e-14) + np.testing.assert_array_equal(stamps, 1000000000 + offsets) + np.testing.assert_allclose(origins, np.tile(mount, (len(raw), 1)), atol=1e-14) + + def test_plane_recovery_with_outliers(self): + plane = np.column_stack([self.xy, -.15 + self.rng.normal(0, .002, len(self.xy))]) + outliers = self.rng.uniform(-3, 3, (400, 3)) + planes = extract_planes(np.r_[plane, outliers], max_planes=1) + self.assertEqual(len(planes), 1) + self.assertGreater(planes[0]['normal'][2], .999) + self.assertLess(abs(planes[0]['offset_m'] - .15), .002) + + def test_parallel_plane_bias_is_reported_not_removed(self): + a = np.column_stack([self.xy, self.rng.normal(0, .002, len(self.xy))]) + b = np.column_stack([self.xy, .05 + self.rng.normal(0, .002, len(self.xy))]) + pairs = compare_planes([a, b], [[one_plane(a)], [one_plane(b)]]) + self.assertEqual(len(pairs), 1) + self.assertGreater(pairs[0]['cross_plane_abs_p50_m'], .045) + self.assertLess(pairs[0]['cross_plane_abs_p50_m'], .055) + + def test_same_infinite_plane_without_common_patch_is_rejected(self): + a = np.column_stack([self.xy, np.zeros(len(self.xy))]) + b = a + [20., 0., 0.] + self.assertEqual(compare_planes([a, b], [[one_plane(a)], [one_plane(b)]]), []) + + def test_line_does_not_establish_a_plane(self): + line = np.column_stack([np.linspace(-2, 2, 600), np.zeros((600, 2))]) + self.assertEqual(extract_planes(line), []) + + +if __name__ == '__main__': + unittest.main()