#!/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()