#!/usr/bin/env python3 """Record an isolated Gazebo mapping/evaluation run; truth is recorder-only. Source ROS first. Example: python3 tools/capture_lio.py --profile mapping --output generated/lio_mapping --map generated/field.flmap python3 tools/capture_lio.py --profile evaluation --output generated/lio_evaluation --map generated/field.flmap """ import argparse import math import json import os from pathlib import Path import signal import subprocess import time import uuid import rclpy from rclpy.node import Node from rclpy.parameter import Parameter from rclpy.qos import qos_profile_sensor_data from geometry_msgs.msg import Twist from nav_msgs.msg import Odometry from std_srvs.srv import Trigger from tf2_msgs.msg import TFMessage import project_env def yaw(q): return math.atan2(2 * (q.w*q.z + q.x*q.y), 1 - 2 * (q.y*q.y + q.z*q.z)) class Driver(Node): def __init__(self, profile): super().__init__('field_lio_evaluation_driver', parameter_overrides=[Parameter('use_sim_time', value=True)]) self.publisher = self.create_publisher(Twist, os.environ.get('MANUAL_CMD_VEL_TOPIC', '/cmd_vel'), 10) self.origin = None self.pose = None self.index = 0 self.tf_publishers = set() self.map_odom_messages = 0 self.forbidden_tf = 0 self.tf_subscription = self.create_subscription(TFMessage, '/tf', self.on_tf, 500) # Verified against the existing occupancy map with room for the body footprint. self.route = ([(-4.4, 3.0), (-4.4, 0.7), (-5.15, 0.7), (-5.15, 3.0), (-5.0, 3.0)] if profile == 'mapping' else [(-4.6, 2.8), (-4.6, 1.0), (-5.1, 1.0), (-5.1, 2.8), (-5.0, 3.0)]) self.subscription = self.create_subscription(Odometry, '/odom', self.on_odom, qos_profile_sensor_data) def on_tf(self, msg, info): for transform in msg.transforms: if transform.header.frame_id == 'map' and transform.child_frame_id == 'odom': gid = info['publisher_gid'] if isinstance(info, dict) else info.publisher_gid self.tf_publishers.add(json.dumps(gid, sort_keys=True, default=str) if isinstance(gid, dict) else str(gid)) self.map_odom_messages += 1 if transform.header.frame_id == 'map' and transform.child_frame_id == 'base_link': self.forbidden_tf += 1 def on_odom(self, msg): p = msg.pose.pose if self.origin is None: self.origin = (p.position.x, p.position.y, yaw(p.orientation)) x, y, angle = self.origin dx, dy = p.position.x-x, p.position.y-y self.pose = (-5 + math.cos(angle)*dx + math.sin(angle)*dy, 3 - math.sin(angle)*dx + math.cos(angle)*dy, yaw(p.orientation)-angle) def drive(self, elapsed): command = Twist() if elapsed >= 5 and self.pose and elapsed % 30 > 2: x, y, angle = self.pose tx, ty = self.route[self.index] distance = math.hypot(tx-x, ty-y) if distance < 0.08: self.index = (self.index+1) % len(self.route) else: error = math.atan2(math.sin(math.atan2(ty-y, tx-x)-angle), math.cos(math.atan2(ty-y, tx-x)-angle)) command.angular.z = max(-0.4, min(0.4, 1.5*error)) if abs(error) < 0.3: command.linear.x = min(0.20, 0.8*distance) self.publisher.publish(command) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--profile', choices=['mapping', 'evaluation'], required=True) parser.add_argument('--output', type=Path, required=True) parser.add_argument('--map', type=Path, required=True) parser.add_argument('--duration', type=float, default=120) args = parser.parse_args() if args.output.exists(): parser.error('output directory must not already exist') if args.profile == 'evaluation' and not args.map.is_file(): parser.error('evaluation requires an existing map') args.output.mkdir(parents=True) args.map.parent.mkdir(parents=True, exist_ok=True) workspace = Path(__file__).resolve().parents[1] binary = project_env.find_bin_dir(workspace) session = uuid.uuid4().hex[:12] os.environ.update(ROS_DOMAIN_ID=str(50 + int(session[:8], 16) % 50), GZ_PARTITION=f'field_lio_{session}', ROS2CLI_DISABLE_DAEMON='1', FASTDDS_BUILTIN_TRANSPORTS='UDPv4', HEADLESS='1', NAV2='0', RVIZ='0', LOCALIZATION='lio', LIO_MODE='mapping' if args.profile == 'mapping' else 'localization', LIO_MAP=str(args.map.resolve()), LIO_EXPORT_MAP=str(args.map.resolve()), SENTRY_LOG=str((args.output/'stack.log').resolve())) (args.output/'runtime.json').write_text(json.dumps({'ROS_DOMAIN_ID': os.environ['ROS_DOMAIN_ID'], 'GZ_PARTITION': os.environ['GZ_PARTITION'], 'duration_sec': args.duration, 'profile': args.profile, 'IMU_sensor_noise': 'zero', 'control_input': 'wheel odometry only'}, indent=2)) processes = [] log_handles = [] rclpy.init() driver = Driver(args.profile) try: processes.append(subprocess.Popen(['bash', str(workspace/'scripts/sentry_up.sh')], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, cwd=workspace)) log = open(args.output/'record.log', 'w', encoding='utf8') log_handles.append(log) recorder = subprocess.Popen([str(binary/'field_localization_record'), '--ros-args', '-p', 'use_sim_time:=true', '-p', f'output_directory:={args.output.resolve()}', '-p', f'duration_sec:={args.duration}'], stdout=log, stderr=subprocess.STDOUT, start_new_session=True) processes.append(recorder) deadline = time.monotonic() + max(600, args.duration*10) start = None last_print = 0 while time.monotonic() < deadline and recorder.poll() is None: if (args.output/'STOP').exists(): raise RuntimeError('capture stopped through STOP file') rclpy.spin_once(driver, timeout_sec=0.02) if processes[0].poll() is not None: raise RuntimeError('simulation stack exited; inspect stack.log') if (args.output/'config.txt').exists(): now = driver.get_clock().now().nanoseconds*1e-9 if start is None: start = now driver.drive(now-start) if now-start > last_print+10: last_print = now-start print(f'{args.profile}: {last_print:.1f}/{args.duration:.1f} simulated seconds; odom pose={driver.pose}', flush=True) driver.publisher.publish(Twist()) if recorder.poll() is None: raise RuntimeError('capture deadline exceeded') if recorder.returncode or not (args.output/'complete.txt').exists(): raise RuntimeError('recorder failed; inspect record.log') if args.profile == 'mapping': client = driver.create_client(Trigger, '/field_localization/save_map') if not client.wait_for_service(timeout_sec=5): raise RuntimeError('LIO save_map service unavailable') future = client.call_async(Trigger.Request()) rclpy.spin_until_future_complete(driver, future, timeout_sec=10) if not future.done() or not future.result().success: raise RuntimeError('LIO map export failed') tf_summary = {'map_to_odom_publishers': len(driver.tf_publishers), 'map_to_odom_messages': driver.map_odom_messages, 'map_to_base_link_messages': driver.forbidden_tf} (args.output/'tf_validation.json').write_text(json.dumps(tf_summary, indent=2)) if len(driver.tf_publishers) != 1 or driver.map_odom_messages == 0 or driver.forbidden_tf: raise RuntimeError(f'TF validation failed: {tf_summary}') print(f'capture complete: {args.output}; TF validation={tf_summary}', flush=True) finally: driver.publisher.publish(Twist()) for process in reversed(processes): if process.poll() is None: os.killpg(process.pid, signal.SIGINT) for process in reversed(processes): try: process.wait(timeout=15) except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait() for handle in log_handles: handle.close() driver.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()