#!/usr/bin/env python3 """SIM-ONLY: so kết quả DetectWallReflectors với ground truth từ Gazebo. Handler ghi TF vào buffer tf3 nội bộ của nav core; host không phát lại sang ROS TF. Vì vậy script lấy kết quả từ dòng log thành công của handler (cần `debug/state: true`): ... output TF published: marker=(x, y, yaw) target=(x, y, yaw) frame=map Ba chế độ lấy ước lượng: --log FILE đọc dòng thành công CUỐI trong file log của amr_control --marker X Y YAW --target X Y YAW nhập tay từ dòng log đó --robot-final pose base của robot trong Gazebo sau khi compound GoToWallStation xong (đo cả detector + localization + controller, không chỉ detector) Ground truth: tâm marker nằm trên MẶT TƯỜNG tối (x model -0.05), giữa hai dải; pháp tuyến hướng ra phía robot. Sai số in trong hệ (t, n) của marker thật: lateral dọc tường, depth theo pháp tuyến. """ import argparse import math import re import sys LOG_PATTERN = re.compile( r"output TF published: marker=\(([-+\d.eE]+), ([-+\d.eE]+), ([-+\d.eE]+)\) " r"target=\(([-+\d.eE]+), ([-+\d.eE]+), ([-+\d.eE]+)\) frame=(\S+)") # Mặt tường tối trong frame model (gen_wall_models.py: WALL_FACE_X); tâm cặp dải ở y = 0. WALL_FACE_X = -0.05 def wrap(angle): return math.atan2(math.sin(angle), math.cos(angle)) def compose(parent, child): x, y, yaw = parent dx, dy, dyaw = child return (x + math.cos(yaw) * dx - math.sin(yaw) * dy, y + math.sin(yaw) * dx + math.cos(yaw) * dy, wrap(yaw + dyaw)) def inverse(pose): x, y, yaw = pose c, s = math.cos(yaw), math.sin(yaw) return (-c * x - s * y, s * x - c * y, wrap(-yaw)) def read_log(path): last = None with open(path, encoding='utf-8', errors='replace') as stream: for line in stream: match = LOG_PATTERN.search(line) if match: last = match if last is None: raise ValueError('không thấy dòng "output TF published: marker=..." trong ' + path + ' (debug/state có đang bật không?)') values = [float(v) for v in last.groups()[:6]] return tuple(values[:3]), tuple(values[3:]), last.group(7) def report(label, estimate, truth, normal): nx, ny = normal ex, ey = estimate[0] - truth[0], estimate[1] - truth[1] depth = ex * nx + ey * ny lateral = -ex * ny + ey * nx print('{}: lateral={:+.4f} m, depth={:+.4f} m, yaw={:+.3f} deg'.format( label, lateral, depth, math.degrees(wrap(estimate[2] - truth[2])))) print(' estimate=({:.4f}, {:.4f}, {:.4f}) truth=({:.4f}, {:.4f}, {:.4f})'.format( *estimate, *truth)) def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) alignment = parser.add_mutually_exclusive_group(required=True) alignment.add_argument('--world-to-map', type=float, nargs=3, metavar=('X', 'Y', 'YAW'), help='Pose của Gazebo world trong map, đo độc lập [m, m, rad]') alignment.add_argument('--assume-map-equals-world', action='store_true', help='Chỉ dùng sau khi đã xác nhận map và world trùng nhau') alignment.add_argument('--align-by-robot', action='store_true', help='Suy world→map từ pose robot trong Gazebo và TF map→base_link hiện ' 'tại. Sai số khi đó là sai số detector so với chính robot (không gồm ' 'sai số localization). Robot phải đứng yên từ lúc dò tới lúc chạy.') source = parser.add_mutually_exclusive_group(required=True) source.add_argument('--log', metavar='FILE', help='File log chứa dòng thành công của handler') source.add_argument('--marker', type=float, nargs=3, metavar=('X', 'Y', 'YAW')) source.add_argument('--robot-final', action='store_true', help='So pose robot sau compound với target thật (end-to-end)') parser.add_argument('--target', type=float, nargs=3, metavar=('X', 'Y', 'YAW'), help='Đi kèm --marker') parser.add_argument('--confirm-current-success', action='store_true', required=True, help='Xác nhận thủ công lượt action hiện tại đã thành công; TF/log có thể cũ') parser.add_argument('--wall-model', default='wall_reflector_pair') parser.add_argument('--robot-model', default='robot') parser.add_argument('--global-frame', default='map') parser.add_argument('--base-frame', default='base_link') parser.add_argument('--offset-x', type=float, default=0.85) parser.add_argument('--offset-y', type=float, default=0.0) parser.add_argument('--offset-yaw', type=float, default=0.0) parser.add_argument('--entry-direction', choices=('forward', 'backward'), default='backward') parser.add_argument('--timeout', type=float, default=5.0) args = parser.parse_args() if args.marker is not None and args.target is None: parser.error('--marker cần đi kèm --target') alignment_pose = tuple(args.world_to_map or (0.0, 0.0, 0.0)) if not all(math.isfinite(v) for v in (*alignment_pose, args.offset_x, args.offset_y, args.offset_yaw, args.timeout)) or args.timeout <= 0: parser.error('Alignment, offset phải hữu hạn và timeout phải dương') marker = target = None frame = None if args.log: try: marker, target, frame = read_log(args.log) except (OSError, ValueError) as exc: print('Không đọc được kết quả:', exc, file=sys.stderr) return 1 elif args.marker is not None: marker, target = tuple(args.marker), tuple(args.target) import rospy from gazebo_msgs.msg import ModelStates from tf.transformations import euler_from_quaternion def pose2d(pose, label): return pose2d_parts(pose.position, pose.orientation, label) def pose2d_parts(position, orientation, label): values = (position.x, position.y, orientation.x, orientation.y, orientation.z, orientation.w) if not all(math.isfinite(value) for value in values): raise ValueError(label + ': pose không hữu hạn') roll, pitch, yaw = euler_from_quaternion(values[2:]) if abs(roll) > 0.01 or abs(pitch) > 0.01: raise ValueError(label + ': phép đối chiếu 2D cần model gần thẳng đứng') return (position.x, position.y, yaw) rospy.init_node('eval_wall_reflector', anonymous=True) try: states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=args.timeout) wall = states.pose[states.name.index(args.wall_model)] robot = states.pose[states.name.index(args.robot_model)] robot_in_world = pose2d(robot, 'robot') if args.align_by_robot: import tf2_ros buffer = tf2_ros.Buffer() listener = tf2_ros.TransformListener(buffer) stamped = buffer.lookup_transform(args.global_frame, args.base_frame, rospy.Time(0), rospy.Duration(args.timeout)) transform = stamped.transform robot_in_global = pose2d_parts(transform.translation, transform.rotation, 'TF ' + args.global_frame + '->' + args.base_frame) alignment_pose = compose(robot_in_global, inverse(robot_in_world)) del listener wall_in_map = compose(alignment_pose, pose2d(wall, 'wall')) robot_in_map = compose(alignment_pose, robot_in_world) except Exception as exc: # rospy/tf2 lỗi đủ loại; script chỉ báo và thoát. print('Không thể đánh giá:', exc, file=sys.stderr) return 1 # Pháp tuyến mặt có dải là -x của model; quay π để +X marker hướng ra phía robot. marker_truth = compose(wall_in_map, (WALL_FACE_X, 0.0, math.pi)) heading = args.offset_yaw + (math.pi if args.entry_direction == 'forward' else 0.0) target_truth = compose(marker_truth, (args.offset_x, args.offset_y, heading)) normal = (math.cos(marker_truth[2]), math.sin(marker_truth[2])) if ((robot_in_map[0] - marker_truth[0]) * normal[0] + (robot_in_map[1] - marker_truth[1]) * normal[1]) <= 0: print('Robot không ở phía có dải của tường; ground truth pháp tuyến không áp dụng.', file=sys.stderr) return 1 print('world→map: {}{}'.format(alignment_pose, '' if frame is None else ', frame log=' + frame)) print('Cảnh báo: ModelStates không có stamp; dữ liệu không đồng bộ với lúc dò.') if args.robot_final: report('robot sau compound (detector + localization + controller)', robot_in_map, target_truth, normal) else: report('marker (detector)', marker, marker_truth, normal) report('target (detector + offset)', target, target_truth, normal) print('Robot hiện tại: ({:.4f}, {:.4f}, {:.4f})'.format(*robot_in_map)) return 0 if __name__ == '__main__': sys.exit(main())