Files
wall_reflector_detection_ac…/sim/sweep_wall_detection.py
duongtd b5da961449 feat(sim): Gazebo wall model, detection sweep and evaluation scripts
- sim/models/wall_reflector_pair: wall with two 3 cm strips 9 cm apart
  (laser_retro 2000 on the strips, 0 on the wall), generated by
  gen_wall_models.py; spawn_wall_reflector.launch places it.
- sim/eval_wall_reflector.py: compares the published marker/target with the
  Gazebo ground truth, read from the handler success log because the nav
  core TF never reaches ROS; --align-by-robot when map != Gazebo world.
- sim/sweep_wall_detection.py: places the wall at several distances and
  angles behind the robot, sends DetectWallReflectors, writes a CSV and
  dumps the scan of every failed case.
- Handler success log now prints marker, target and frame (debug/state).
- Install sim/ in both catkin and standalone builds.
2026-11-12 13:44:16 +07:00

282 lines
14 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""SIM-ONLY: quét vùng làm việc của DetectWallReflectors trong Gazebo.
Với mỗi cặp (khoảng cách, góc), script:
1. đọc pose robot trong Gazebo, đặt lại model tường sau lưng robot (lidar sau, `entry_direction:
backward`): mặt dải cách lidar sau `distance` mét, tường xoay `angle` độ quanh tâm cặp dải;
2. gửi instant action `DetectWallReflectors` qua `vda5050_send.py` (MQTT, cùng config với robot);
3. đọc log của amr_control (phải ghi theo DÒNG — chạy launch qua `stdbuf -oL -eL`) tới khi có
dòng thành công hoặc timeout của handler;
4. nếu thành công, so marker/target với ground truth giống `eval_wall_reflector.py --align-by-robot`
(world→map suy từ pose robot, nên sai số là của detector so với chính robot).
Robot phải đứng yên suốt quá trình quét. Kết quả in bảng và ghi CSV.
"""
import argparse
import csv
import importlib.util
import json
import math
import os
import re
import subprocess
import sys
import time
HERE = os.path.dirname(os.path.abspath(__file__))
MODEL_SDF = os.path.join(HERE, 'models', 'wall_reflector_pair', 'model.sdf')
SEND_SCRIPT = os.path.normpath(os.path.join(
HERE, '..', '..', '..', '..', '..', '..', '..', 'Controllers', 'Packages', 'amr_comunication',
'scripts', 'vda5050_send.py'))
# Lidar sau của hook_150 nằm ở base −0.454 m (diff_hook_150.urdf.xacro: laser_dx); mặt dải ở x model
# −0.052 (gen_wall_models.py: TAPE_FACE_X).
REAR_LIDAR_OFFSET = 0.454
TAPE_FACE_X = -0.052
FAIL_PATTERN = re.compile(r"\[wall_reflector\] '[^']+': (wall_reflector timeout: .*|"
r"lidar faces opposite entry_direction|scan plane tilt.*|"
r"wall_reflector: failed to publish.*|unknown profile.*)")
DEBUG_REASON = re.compile(r"\[wall_reflector\]\[debug\] '[^']+': (.*)")
def load_eval_module():
spec = importlib.util.spec_from_file_location('eval_wall_reflector',
os.path.join(HERE, 'eval_wall_reflector.py'))
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def wall_pose_behind(robot, distance, angle, lateral):
"""Pose model tường (world) để mặt dải cách lidar sau `distance`, xoay `angle` rad."""
x, y, yaw = robot
heading = (math.cos(yaw), math.sin(yaw))
side = (-heading[1], heading[0])
face_x = x - (REAR_LIDAR_OFFSET + distance) * heading[0] + lateral * side[0]
face_y = y - (REAR_LIDAR_OFFSET + distance) * heading[1] + lateral * side[1]
model_yaw = yaw + math.pi + angle
# Mặt dải ở x model TAPE_FACE_X: gốc model = mặt − R(model_yaw)·(TAPE_FACE_X, 0).
return (face_x - TAPE_FACE_X * math.cos(model_yaw),
face_y - TAPE_FACE_X * math.sin(model_yaw),
model_yaw)
def wait_for_result(log_path, offset, timeout):
deadline = time.monotonic() + timeout
last_reason = ''
position = offset
buffer = ''
while time.monotonic() < deadline:
with open(log_path, encoding='utf-8', errors='replace') as stream:
stream.seek(position)
chunk = stream.read()
position = stream.tell()
buffer += chunk
lines = buffer.split('\n')
buffer = lines.pop()
for line in lines:
reason = DEBUG_REASON.search(line)
if reason and not reason.group(1).startswith(('started profile', 'scan=')):
last_reason = reason.group(1)
failure = FAIL_PATTERN.search(line)
if failure:
return 'fail', failure.group(1), None
match = EVAL.LOG_PATTERN.search(line)
if match:
values = [float(v) for v in match.groups()[:6]]
return 'ok', last_reason, (tuple(values[:3]), tuple(values[3:]))
time.sleep(0.2)
return 'no_result', last_reason or 'không thấy dòng kết quả (log có ghi theo dòng không?)', None
def main():
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('--log', required=True, help='Log amr_control đang được ghi (tee)')
parser.add_argument('--distances', type=float, nargs='+', default=[0.6, 1.0, 1.4],
help='Khoảng cách lidar sau → mặt dải [m]')
parser.add_argument('--angles', type=float, nargs='+', default=[0.0, 20.0, -20.0, 30.0, -30.0],
help='Góc xoay tường quanh tâm cặp dải [độ]')
parser.add_argument('--lateral', type=float, default=0.0, help='Dịch tường dọc mặt [m]')
parser.add_argument('--timeout', type=float, default=20.0, help='Chờ mỗi lượt [s]')
parser.add_argument('--settle', type=float, default=1.0, help='Chờ sau khi đặt tường [s]')
parser.add_argument('--offset-x', type=float, default=0.85)
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('--csv', default='/tmp/wall_sweep.csv')
parser.add_argument('--scan-topic', default='/b_scan')
parser.add_argument('--bright', type=float, default=1000.0,
help='Ngưỡng intensity coi là tia sáng khi chẩn đoán (= tape_min_intensity)')
args = parser.parse_args()
import rospy
import tf2_ros
from gazebo_msgs.msg import ModelStates
from gazebo_msgs.srv import DeleteModel, SpawnModel
from geometry_msgs.msg import Pose
from sensor_msgs.msg import LaserScan
rospy.init_node('sweep_wall_detection', anonymous=True)
rospy.wait_for_service('/gazebo/delete_model', timeout=10)
rospy.wait_for_service('/gazebo/spawn_sdf_model', timeout=10)
delete_model = rospy.ServiceProxy('/gazebo/delete_model', DeleteModel)
spawn_model = rospy.ServiceProxy('/gazebo/spawn_sdf_model', SpawnModel)
tf_buffer = tf2_ros.Buffer()
tf_listener = tf2_ros.TransformListener(tf_buffer) # noqa: F841 — phải sống suốt vòng quét
with open(MODEL_SDF, encoding='utf-8') as stream:
sdf = stream.read()
def yaw_of(q):
return math.atan2(2.0 * (q.w * q.z + q.x * q.y), 1.0 - 2.0 * (q.y * q.y + q.z * q.z))
def model_pose(name):
states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=5)
pose = states.pose[states.name.index(name)]
return (pose.position.x, pose.position.y, yaw_of(pose.orientation))
def model_present(name):
states = rospy.wait_for_message('/gazebo/model_states', ModelStates, timeout=5)
return name in states.name
def wait_until(predicate, timeout):
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
if predicate():
return True
time.sleep(0.2)
return False
def place_wall(wall):
"""Xoá tường cũ, đợi nó biến mất, spawn ở `wall`, đợi đúng chỗ. Lỗi thì báo, không im lặng.
Xoá rồi spawn cùng tên ngay lập tức có thể bị Gazebo từ chối ("already exists") — lần quét
12/11 mất 5/15 lượt vì không kiểm `success` của spawn.
"""
if model_present(args.wall_model):
delete_model(args.wall_model)
if not wait_until(lambda: not model_present(args.wall_model), 5.0):
return 'không xoá được model tường cũ'
pose = Pose()
pose.position.x, pose.position.y = wall[0], wall[1]
pose.orientation.z, pose.orientation.w = math.sin(wall[2] / 2), math.cos(wall[2] / 2)
message = ''
for _ in range(3):
response = spawn_model(args.wall_model, sdf, '', pose, 'world')
message = response.status_message
if response.success:
break
time.sleep(0.5)
else:
return 'spawn thất bại: ' + message
def at_requested_pose():
if not model_present(args.wall_model):
return False
x, y, yaw = model_pose(args.wall_model)
return (math.hypot(x - wall[0], y - wall[1]) < 0.01 and
abs(EVAL.wrap(yaw - wall[2])) < 0.01)
if not wait_until(at_requested_pose, 5.0):
return 'tường không xuất hiện đúng pose sau khi spawn'
return ''
rows = []
case = 0
for distance in args.distances:
for angle_degrees in args.angles:
case += 1
robot_world = model_pose(args.robot_model)
wall = wall_pose_behind(robot_world, distance, math.radians(angle_degrees), args.lateral)
placement_error = place_wall(wall)
if placement_error:
print('{:>4.2f} m {:>+6.1f}° lỗi đặt tường: {}'.format(
distance, angle_degrees, placement_error), flush=True)
rows.append({'distance_m': distance, 'angle_deg': angle_degrees,
'status': 'wall_error', 'reason': placement_error,
'marker_lateral_mm': '', 'marker_depth_mm': '', 'yaw_deg': '',
'target_lateral_mm': '', 'target_depth_mm': ''})
continue
time.sleep(args.settle)
offset = os.path.getsize(args.log)
action_id = 'wall-sweep-{}-{}'.format(case, int(time.time()))
message = json.dumps({'actions': [{'actionType': 'DetectWallReflectors',
'actionId': action_id, 'blockingType': 'HARD',
'actionParameters': []}]})
sent = subprocess.run([sys.executable, SEND_SCRIPT, '/dev/stdin', '--kind',
'instantActions', '--no-validate'],
input=message, text=True, capture_output=True)
if sent.returncode != 0:
print('Gửi action lỗi:', sent.stdout, sent.stderr, file=sys.stderr)
return 1
status, reason, result = wait_for_result(args.log, offset, args.timeout)
if status != 'ok':
# Lưu một scan để biết vì sao không dò được: không có tia sáng nào (Gazebo không trả
# laser_retro), chỉ một dải (bị che), hay đủ hai dải mà matcher vẫn loại.
try:
scan = rospy.wait_for_message(args.scan_topic, LaserScan, timeout=5)
bright = [i for i, v in enumerate(scan.intensities) if v >= args.bright]
runs = []
for index in bright:
if runs and index == runs[-1][1] + 1:
runs[-1][1] = index
else:
runs.append([index, index])
dump = '/tmp/wall_sweep_fail_{}.json'.format(case)
with open(dump, 'w', encoding='utf-8') as stream:
json.dump({'distance_m': distance, 'angle_deg': angle_degrees,
'robot_world': robot_world, 'wall_world': wall,
'angle_min': scan.angle_min,
'angle_increment': scan.angle_increment,
'ranges': list(scan.ranges),
'intensities': list(scan.intensities),
'bright_runs': runs}, stream)
reason += ' | scan: {} tia sáng, run {}, max intensity {:.0f} → {}'.format(
len(bright), runs[:6], max(scan.intensities, default=0.0), dump)
except rospy.ROSException as exc:
reason += ' | không lấy được scan: {}'.format(exc)
row = {'distance_m': distance, 'angle_deg': angle_degrees, 'status': status,
'reason': reason, 'marker_lateral_mm': '', 'marker_depth_mm': '',
'yaw_deg': '', 'target_lateral_mm': '', 'target_depth_mm': ''}
if result is not None:
stamped = tf_buffer.lookup_transform(args.global_frame, args.base_frame,
rospy.Time(0), rospy.Duration(5.0))
t = stamped.transform
robot_global = (t.translation.x, t.translation.y, yaw_of(t.rotation))
alignment = EVAL.compose(robot_global, EVAL.inverse(robot_world))
wall_global = EVAL.compose(alignment, model_pose(args.wall_model))
marker_truth = EVAL.compose(wall_global, (EVAL.WALL_FACE_X, 0.0, math.pi))
target_truth = EVAL.compose(marker_truth, (args.offset_x, 0.0, 0.0))
nx, ny = math.cos(marker_truth[2]), math.sin(marker_truth[2])
marker, target = result
for label, estimate, truth in (('marker', marker, marker_truth),
('target', target, target_truth)):
ex, ey = estimate[0] - truth[0], estimate[1] - truth[1]
row[label + '_lateral_mm'] = round(1000.0 * (-ex * ny + ey * nx), 2)
row[label + '_depth_mm'] = round(1000.0 * (ex * nx + ey * ny), 2)
row['yaw_deg'] = round(math.degrees(EVAL.wrap(marker[2] - marker_truth[2])), 3)
rows.append(row)
print('{:>4.2f} m {:>+6.1f}° {:<9} marker lat {:>7} mm depth {:>7} mm yaw {:>7}° '
'target lat {:>7} mm {}'.format(
distance, angle_degrees, status, row['marker_lateral_mm'],
row['marker_depth_mm'], row['yaw_deg'], row['target_lateral_mm'],
reason), flush=True)
with open(args.csv, 'w', newline='', encoding='utf-8') as stream:
writer = csv.DictWriter(stream, fieldnames=list(rows[0].keys()))
writer.writeheader()
writer.writerows(rows)
print('CSV:', args.csv)
print('Cảnh báo: ModelStates không có stamp; sim không có bloom/bias của băng gương thật.')
return 0
EVAL = load_eval_module()
if __name__ == '__main__':
sys.exit(main())