Files
RC2027_BR_code/minco_ws/docs/diagnostics/analyze_dual_geometry.py
T
walunt5 1928e1e3b7 feat(diagnostics): 双 MID360 静止安装与公共平面检查
只跑雷达驱动、原始数据记录器和离线分析器,不启动 Point-LIO、TF、融合发布、
规划、串口或底盘,不改现场 site.yaml。诊断与正式场地任务解耦。

坐标只声明为局部 body(X 前、Y 左、Z 上 + 安装参考点),不声明已对齐比赛场地。
README 写明两条边界:点云重合只能提供证据,不能代替实物确认;车架空时地面
比落地时更低,该差值不能直接当安装高度误差。
2026-11-19 16:44:55 +08:00

286 lines
14 KiB
Python

#!/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', '<f4'), ('y', '<f4'), ('z', '<f4'),
('red', 'u1'), ('green', 'u1'), ('blue', 'u1')])
out = np.empty(sum(map(len, clouds)), dtype=dtype)
pos = 0
for cloud, color in zip(clouds, ((30, 150, 245), (245, 100, 35))):
part = out[pos:pos + len(cloud)]
for i, name in enumerate(('x', 'y', 'z')):
part[name] = cloud[:, i]
for name, value in zip(('red', 'green', 'blue'), color):
part[name] = value
pos += len(cloud)
header = ('ply\nformat binary_little_endian 1.0\ncomment Diagnostic local body coordinates only\n'
f'element vertex {len(out)}\nproperty float x\nproperty float y\nproperty float z\n'
'property uchar red\nproperty uchar green\nproperty uchar blue\nend_header\n')
with path.open('wb') as f:
f.write(header.encode())
f.write(out.tobytes())
def overview(path, clouds, mounts):
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(16, 5))
for axis, dims, title in zip(axes, ((0, 1), (0, 2), (1, 2)), ('Top XY', 'Side XZ', 'Front YZ')):
for points, mount, color, name in zip(clouds, mounts, ('#1e96f5', '#f56423'), ('Upper', 'Lower')):
stride = max(1, len(points) // 25000)
view = points[::stride]
axis.scatter(view[:, dims[0]], view[:, dims[1]], s=.6, alpha=.45, c=color, label=name, rasterized=True)
axis.scatter([mount[dims[0]]], [mount[dims[1]]], marker='x', s=70, color=color)
axis.set_xlabel('XYZ'[dims[0]] + ' (m)')
axis.set_ylabel('XYZ'[dims[1]] + ' (m)')
axis.set_title(title)
axis.set_aspect('equal', adjustable='box')
axis.grid(alpha=.2)
axes[0].legend(markerscale=6)
fig.suptitle('Configured rigid transforms only; blue=upper, orange=lower; no ICP or ground/self filtering')
fig.tight_layout()
fig.savefig(path, dpi=160)
plt.close(fig)
def main():
import rosbag2_py
import yaml
from rclpy.serialization import deserialize_message
from sensor_msgs.msg import Imu
from br_vehicle_mission.livox_scan import read_scan
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('capture', type=Path)
parser.add_argument('--out', type=Path, required=True)
parser.add_argument('--swap-roles', action='store_true',
help='Offline hypothesis only: reverse source roles without editing the site')
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=False)
site = yaml.safe_load((args.capture / 'site.yaml').read_text())
capture = json.loads((args.capture / 'capture.json').read_text())
if capture['status'] != 'PASS':
raise ValueError('recording did not pass capture checks')
sensors = site['sensors']
topics = [sensors['upper_lidar_topic'], sensors['lower_lidar_topic']]
imu_topics = [sensors['upper_imu_topic'], topics[1].replace('/lidar_', '/imu_')]
frames = [sensors['upper_raw_frame'], sensors['lower_raw_frame']]
if args.swap_roles:
topics.reverse()
imu_topics.reverse()
frames.reverse()
mounts = [np.array(site['upper_position_base']), np.array(site['lower_position_base'])]
rotations = [np.eye(3), yaw_matrix(site['lower_yaw'])]
raw = [[], []]
imus = [[], []]
reader = rosbag2_py.SequentialReader()
reader.open(rosbag2_py.StorageOptions(uri=str(args.capture / 'raw_bag'), storage_id='sqlite3'),
rosbag2_py.ConverterOptions('', ''))
while reader.has_next():
topic, message, _ = reader.read_next()
if topic in topics:
i = topics.index(topic)
scan = read_scan(message)
if scan.frame != frames[i]:
raise ValueError('unexpected raw frame')
raw[i].append(scan.xyz.copy())
elif topic in imu_topics:
i = imu_topics.index(topic)
msg = deserialize_message(message, Imu)
acc, gyro = msg.linear_acceleration, msg.angular_velocity
imus[i].append([msg.header.stamp.sec * 1000000000 + msg.header.stamp.nanosec,
acc.x, acc.y, acc.z, gyro.x, gyro.y, gyro.z])
report = {'scope': 'Independent local body geometry; configured transforms only; no calibrated extrinsic update',
'status': 'MEASUREMENTS_PENDING',
'source_roles': dict(zip(('upper', 'lower'), topics)),
'roles_swapped_in_offline_copy': args.swap_roles,
'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'site_sha256': hashlib.sha256((args.capture / 'site.yaml').read_bytes()).hexdigest(),
'parameters': {'voxel_m': .04, 'range_min_m': .1, 'range_max_m': 8.,
'plane_threshold_m': .02, 'plane_matching_angle_gate_deg': 10.,
'plane_matching_offset_gate_m': .35, 'overlap_tangent_radius_m': .12},
'geometry': {k: site[k] for k in ('body_size', 'upper_position_base', 'lower_position_base',
'lower_yaw', 'lidar_to_imu_translation')},
'sensors': {}}
clouds = []
analysis_clouds = []
planes = []
length, width, height = site['body_size']
self_min = np.array([-length / 2 - .02, -width / 2 - .02, -.17])
self_max = np.array([length / 2 + .02, width / 2 + .02, height - .13])
for i, name in enumerate(('upper', 'lower')):
xyz = np.concatenate(raw[i]).astype(np.float64)
valid = np.isfinite(xyz).all(axis=1)
ranges = np.linalg.norm(xyz, axis=1)
roi = valid & (ranges >= .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()