#!/usr/bin/python3 """P3: compare raw/world 3D clouds against independent Gazebo truth at two yaws.""" import argparse import json import math import os from pathlib import Path import sys import time import xml.etree.ElementTree as ET import numpy as np import rclpy from sensor_msgs.msg import PointCloud2 from nav_msgs.msg import Odometry from rclpy.qos import qos_profile_sensor_data from check_omni_robot import Probe, Sim, reset_and_settle, sim_env, shutdown_probe sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src/r2027_robot_description/scripts')) from sim_data_adapter import xyz_views def stamp(m): return m.header.stamp.sec * 1_000_000_000 + m.header.stamp.nanosec def points(m): return np.stack(xyz_views(m), axis=-1).reshape(-1, 3) class LidarProbe(Probe): def __init__(self): super().__init__() self.raw = {} self.world = {} self.body = [] self.sensor = [] self.create_subscription(PointCloud2, '/lidar/points', lambda m: self.raw.update({stamp(m): m}), qos_profile_sensor_data) self.create_subscription(PointCloud2, '/cloud_registered', lambda m: self.world.update({stamp(m): m}), 10) self.create_subscription(Odometry, '/body_odom', self.body.append, 10) self.create_subscription(Odometry, '/aft_mapped_to_init', self.sensor.append, 10) def check_phase(probe, out, yaw): ok, settle = reset_and_settle(probe, -4.5, 4.5, .17, yaw, str(out)) if not ok: raise RuntimeError('robot did not settle') cutoff = int(probe.now() * 1e9) deadline = time.monotonic() + 60 pairs = [] while time.monotonic() < deadline: rclpy.spin_once(probe, timeout_sec=.02) pairs = sorted(s for s in probe.world if s >= cutoff and s in probe.raw) if len(pairs) >= 8 and probe.body and probe.sensor: break if len(pairs) < 8: raise RuntimeError('not enough paired raw/world clouds: %d' % len(pairs)) truth = probe.get_state() if truth is None: raise RuntimeError('independent truth unavailable') s = pairs[-1] raw, world = probe.raw[s], probe.world[s] pr, pw = points(raw), points(world) good = np.isfinite(pr).all(axis=1) & np.isfinite(pw).all(axis=1) pr, pw = pr[good], pw[good] c, sn = math.cos(truth['yaw']), math.sin(truth['yaw']) R = np.array([[c, -sn, 0], [sn, c, 0], [0, 0, 1]]) expected = (pr + [.015, 0, .33]) @ R.T + truth['pos'] error = float(np.max(np.linalg.norm(expected - pw, axis=1))) floor = int(np.count_nonzero(np.abs(pw[:, 2]) < .005)) north = int(np.count_nonzero((np.abs(pw[:, 1]-5.5) < .005) & (pw[:, 2] >= -.005) & (pw[:, 2] <= .045))) west = int(np.count_nonzero((np.abs(pw[:, 0]+5.5) < .005) & (pw[:, 2] >= -.005) & (pw[:, 2] <= .045))) dt = np.diff(pairs) / 1e9 body, sensor = probe.body[-1], probe.sensor[-1] shift = sensor.pose.pose.position.z - body.pose.pose.position.z checks = dict(raw_frame=raw.header.frame_id == 'lidar', world_frame=world.header.frame_id == 'world', cloud_3d=len(np.unique(np.round(pr[:, 2], 3))) > 10, finite_points=len(pw) > 1000, exact_stamp=stamp(raw) == stamp(world), stamp_monotonic=bool(np.all(dt > 0)), scan_rate=bool(np.max(dt) < .3), transform_matches_truth=error < .005, floor_correct=floor > 100, north_wall_correct=north > 2, west_wall_correct=west > 2, odom_frames=body.header.frame_id == 'world' and body.child_frame_id == 'base_link' and sensor.header.frame_id == 'world' and sensor.child_frame_id == 'lidar', sensor_mount=abs(shift-.33) < .001) np.savez_compressed(out / ('cloud_yaw_%d.npz' % round(yaw*180/math.pi)), raw=pr, world=pw, expected=expected) return dict(yaw=yaw, checks=checks, ok=all(checks.values()), settle=settle, truth=truth, stamp_ns=s, paired_clouds=len(pairs), finite_points=len(pw), fields=[f.name for f in raw.fields], rate_sim_hz=float(1/np.mean(dt)), transform_error_m=error, floor_points=floor, north_wall_points=north, west_wall_points=west, mount_shift_z=shift) def main(): ap = argparse.ArgumentParser() ap.add_argument('--out', required=True) args = ap.parse_args() out = Path(args.out).resolve() out.mkdir(parents=True, exist_ok=True) os.environ.update(sim_env()) sim = Sim(str(out/'sim')) report = {'phases': [], 'status': 'INVALID'} probe = None try: ok, why = sim.start(lidar=True) report['sim_start'] = why if not ok: raise RuntimeError(why) rclpy.init() probe = LidarProbe() if not probe.wait_clock(): raise RuntimeError('no clock') for yaw in (0., math.pi/2): phase = check_phase(probe, out, yaw) report['phases'].append(phase) print('yaw %.3f: %s' % (yaw, phase['checks']), flush=True) report['status'] = 'PASS' if all(p['ok'] for p in report['phases']) else 'FAIL' except Exception as exc: report['error'] = repr(exc) print(report['error'], flush=True) finally: report['ros_cleanup_errors'] = shutdown_probe(probe) report['teardown'] = sim.stop() (out/'result.json').write_text(json.dumps(report, ensure_ascii=False, indent=2)+'\n') return {'PASS': 0, 'FAIL': 30, 'INVALID': 40}[report['status']] if __name__ == '__main__': sys.exit(main())