feat(reflector_pair): add ReflectorPairMatcher for two flat reflective strips on a wall

Pure geometry core for the upcoming wall reflector detection action. The wall
line is fitted from dark rays only; each strip edge is the half-step bearing
between the intensity core and its neighbour, intersected with that line, so
the range bias of bright returns never enters the pose. Exactly one valid pair
is required; two or more report ambiguous. Synthetic tests cover geometry,
quantisation, bloom, bright range bias, realistic range noise, wall ends,
occluders, ambiguity and malformed input.
This commit is contained in:
2026-11-12 10:12:57 +07:00
parent 5c1688ac50
commit 7ce7c7db52
8 changed files with 1981 additions and 0 deletions

View File

@@ -0,0 +1,586 @@
#include <dock_pattern_detector/reflector_pair_matcher.h>
#include <algorithm>
#include <cmath>
#include <limits>
namespace dock_pattern_detector
{
namespace
{
constexpr double kPi = 3.14159265358979323846;
constexpr double kEpsilon = 1e-9;
double wrap(double angle)
{
return std::atan2(std::sin(angle), std::cos(angle));
}
bool finitePose(const ReflectorPose2D& p)
{
return std::isfinite(p.x) && std::isfinite(p.y) && std::isfinite(p.yaw);
}
} // namespace
bool ReflectorPairMatcher::configure(const ReflectorPairProfile& profile, std::string& error)
{
if (!profile.validate(error))
{
return false;
}
profile_ = profile;
configured_ = true;
return true;
}
bool ReflectorPairMatcher::fitLine(const std::vector<std::size_t>& indices, Line& line) const
{
if (indices.size() < 3)
{
return false;
}
double mx = 0.0;
double my = 0.0;
for (const auto index : indices)
{
mx += rays_[index].x;
my += rays_[index].y;
}
mx /= static_cast<double>(indices.size());
my /= static_cast<double>(indices.size());
double xx = 0.0;
double xy = 0.0;
double yy = 0.0;
for (const auto i : indices)
{
const double dx = rays_[i].x - mx;
const double dy = rays_[i].y - my;
xx += dx * dx;
xy += dx * dy;
yy += dy * dy;
}
if (!std::isfinite(xx + yy) || xx + yy < kEpsilon ||
std::hypot(xx - yy, 2.0 * xy) < kEpsilon)
{
return false;
}
const double angle = 0.5 * std::atan2(2.0 * xy, xx - yy);
line.nx = -std::sin(angle);
line.ny = std::cos(angle);
line.rho = line.nx * mx + line.ny * my;
// n phải hướng từ tường về gốc sensor, nghĩa là rho mang dấu âm.
if (line.rho > 0.0)
{
line.nx = -line.nx;
line.ny = -line.ny;
line.rho = -line.rho;
}
if (line.rho >= -kEpsilon)
{
return false;
}
double sum = 0.0;
line.max_residual = 0.0;
for (const auto i : indices)
{
const double e = std::abs(line.nx * rays_[i].x + line.ny * rays_[i].y - line.rho);
sum += e * e;
line.max_residual = std::max(line.max_residual, e);
}
line.rms = std::sqrt(sum / static_cast<double>(indices.size()));
return std::isfinite(line.rms) && std::isfinite(line.max_residual);
}
bool ReflectorPairMatcher::evaluatePair(const Candidate& first_candidate, const Candidate& second_candidate,
const robot_line_extraction::ScanGeometry& geometry,
const ReflectorPose2D& scan_in_prior, ReflectorPairDetection& out,
const char*& reason)
{
const auto fail = [&reason](const char* why)
{
reason = why;
return false;
};
support_.clear();
left_support_.clear();
right_support_.clear();
std::size_t lo = first_candidate.first;
std::size_t hi = second_candidate.last;
bool left_open = true;
bool right_open = true;
// Khi gặp mép tường, giữ chỉ số tia hợp lệ cuối; phía còn lại vẫn có thể bù baseline.
for (;;)
{
const bool have_sides = left_support_.size() >= profile_.wall_min_points_each_side &&
right_support_.size() >= profile_.wall_min_points_each_side;
bool have_span = false;
if (have_sides &&
std::hypot(rays_[left_support_.back()].x - rays_[right_support_.back()].x,
rays_[left_support_.back()].y - rays_[right_support_.back()].y) >=
profile_.wall_min_span)
{
// Span phải đo theo TLS, không theo dây nối hai đầu: nhiễu pháp tuyến làm dây dài giả.
support_.clear();
for (std::size_t index = lo; index <= hi; ++index)
{
if (!rays_[index].valid)
{
return fail("wall_occluded_or_invalid");
}
if (!rays_[index].masked)
{
support_.push_back(index);
}
}
Line provisional_wall;
if (!fitLine(support_, provisional_wall))
{
return fail("wall_degenerate");
}
double minimum = std::numeric_limits<double>::infinity();
double maximum = -minimum;
for (const std::size_t index : support_)
{
const double along = -provisional_wall.ny * rays_[index].x +
provisional_wall.nx * rays_[index].y;
minimum = std::min(minimum, along);
maximum = std::max(maximum, along);
}
have_span = maximum - minimum >= profile_.wall_min_span;
}
if (have_sides && have_span)
{
break;
}
bool advanced = false;
if (left_open && (left_support_.size() < profile_.wall_min_points_each_side || !have_span))
{
if (lo == 0 || !rays_[lo - 1].valid)
{
left_open = false;
}
else
{
--lo;
if (!rays_[lo].masked)
{
left_support_.push_back(lo);
}
advanced = true;
}
}
if (right_open && (right_support_.size() < profile_.wall_min_points_each_side || !have_span))
{
if (hi + 1 >= rays_.size() || !rays_[hi + 1].valid)
{
right_open = false;
}
else
{
++hi;
if (!rays_[hi].masked)
{
right_support_.push_back(hi);
}
advanced = true;
}
}
if (!advanced)
{
return fail("wall_support");
}
}
support_.clear();
for (std::size_t i = lo; i <= hi; ++i)
{
if (!rays_[i].valid)
{
return fail("wall_occluded_or_invalid");
}
if (!rays_[i].masked)
{
if (!support_.empty())
{
const Ray& prev = rays_[support_.back()];
if (std::hypot(rays_[i].x - prev.x, rays_[i].y - prev.y) > profile_.wall_max_gap)
{
return fail("wall_gap_or_occlusion");
}
}
support_.push_back(i);
}
}
Line wall;
if (!fitLine(support_, wall))
{
return fail("wall_degenerate");
}
if (wall.rms > profile_.wall_max_rms || wall.max_residual > profile_.wall_max_residual)
{
return fail("wall_residual_or_occlusion");
}
// Range sáng không tham gia fit hay tọa độ mép; chỉ dùng để loại vật sáng rõ ràng
// nằm ngoài mặt tường. Dung sai này cho phép bias range phản quang hữu hạn, cần hiệu chuẩn.
for (std::size_t i = lo; i <= hi; ++i)
{
if (!rays_[i].masked)
{
continue;
}
const double angle = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
const double ray_normal_dot = wall.nx * std::cos(angle) + wall.ny * std::sin(angle);
if (std::abs(ray_normal_dot) < kEpsilon)
{
return fail("wall_occlusion_unknown");
}
const double expected = wall.rho / ray_normal_dot;
if (expected <= 0.0 || !std::isfinite(expected))
{
return fail("wall_occlusion_unknown");
}
const double observed = rays_[i].range;
if (rays_[i].bright)
{
if (std::abs(observed - expected) * std::abs(ray_normal_dot) >
profile_.wall_max_residual + profile_.wall_merge_distance)
{
return fail("bright_off_wall");
}
}
else if ((expected - observed) * std::abs(ray_normal_dot) > profile_.wall_max_residual)
{
return fail("wall_occlusion");
}
}
// So phần dư trung bình có dấu của hai đầu và vùng giữa trên CÙNG đường fit.
// Góc fit riêng trên đoạn ngắn rất nhạy với nhiễu range và không đo được hai mặt bền vững.
double left_residual = 0.0;
double middle_residual = 0.0;
double right_residual = 0.0;
std::size_t middle_count = 0;
for (const std::size_t index : support_)
{
const double residual = wall.nx * rays_[index].x + wall.ny * rays_[index].y - wall.rho;
if (index < first_candidate.first)
{
left_residual += residual;
}
else if (index > second_candidate.last)
{
right_residual += residual;
}
else
{
middle_residual += residual;
++middle_count;
}
}
if (middle_count == 0)
{
return fail("wall_support");
}
left_residual /= static_cast<double>(left_support_.size());
right_residual /= static_cast<double>(right_support_.size());
middle_residual /= static_cast<double>(middle_count);
if (std::abs(left_residual - middle_residual) > profile_.wall_merge_distance ||
std::abs(right_residual - middle_residual) > profile_.wall_merge_distance ||
std::abs(left_residual - right_residual) > profile_.wall_merge_distance)
{
return fail("wall_not_same_line");
}
const double tangent_x = -wall.ny;
const double tangent_y = wall.nx;
double support_min = std::numeric_limits<double>::infinity();
double support_max = -support_min;
for (const auto i : support_)
{
const double v = tangent_x * rays_[i].x + tangent_y * rays_[i].y;
support_min = std::min(support_min, v);
support_max = std::max(support_max, v);
}
if (support_max - support_min < profile_.wall_min_span)
{
return fail("wall_span");
}
const std::array<std::size_t, 4> core{{first_candidate.core_first, first_candidate.core_last,
second_candidate.core_first, second_candidate.core_last}};
std::array<double, 4> edge_x{};
std::array<double, 4> edge_y{};
std::array<double, 4> uncertainty{};
for (std::size_t j = 0; j < 4; ++j)
{
const double index = static_cast<double>(core[j]) + (j % 2 == 0 ? -0.5 : 0.5);
const double angle = geometry.angle_min + index * geometry.angle_increment;
const double ux = std::cos(angle);
const double uy = std::sin(angle);
const double denominator = wall.nx * ux + wall.ny * uy;
if (std::abs(denominator) < profile_.min_ray_wall_cos)
{
return fail("edge_parallel");
}
const double distance = wall.rho / denominator;
if (!std::isfinite(distance) || distance <= 0.0)
{
return fail("edge_behind_sensor");
}
edge_x[j] = distance * ux;
edge_y[j] = distance * uy;
const double along = tangent_x * edge_x[j] + tangent_y * edge_y[j];
if (along < support_min - profile_.wall_max_extrapolation ||
along > support_max + profile_.wall_max_extrapolation)
{
return fail("wall_extrapolation");
}
uncertainty[j] = std::abs(wall.rho) * std::abs(geometry.angle_increment) /
(2.0 * denominator * denominator) + profile_.edge_bias_bound;
if (!std::isfinite(uncertainty[j]) || uncertainty[j] > profile_.max_edge_uncertainty)
{
return fail("edge_uncertainty");
}
}
const double first_width = std::hypot(edge_x[1] - edge_x[0], edge_y[1] - edge_y[0]);
const double second_width = std::hypot(edge_x[3] - edge_x[2], edge_y[3] - edge_y[2]);
if (std::abs(first_width - profile_.tape_width) > profile_.width_tolerance ||
std::abs(second_width - profile_.tape_width) > profile_.width_tolerance)
{
return fail("width");
}
const double first_center_x = (edge_x[0] + edge_x[1]) / 2.0;
const double first_center_y = (edge_y[0] + edge_y[1]) / 2.0;
const double second_center_x = (edge_x[2] + edge_x[3]) / 2.0;
const double second_center_y = (edge_y[2] + edge_y[3]) / 2.0;
const double spacing = std::hypot(second_center_x - first_center_x, second_center_y - first_center_y);
if (std::abs(spacing - profile_.tape_spacing) > profile_.spacing_tolerance)
{
return fail("spacing");
}
const double cos_yaw = std::cos(scan_in_prior.yaw);
const double sin_yaw = std::sin(scan_in_prior.yaw);
const double center_x = (first_center_x + second_center_x) / 2.0;
const double center_y = (first_center_y + second_center_y) / 2.0;
const double yaw = wrap(std::atan2(wall.ny, wall.nx) + scan_in_prior.yaw);
ReflectorPose2D marker{scan_in_prior.x + cos_yaw * center_x - sin_yaw * center_y,
scan_in_prior.y + sin_yaw * center_x + cos_yaw * center_y, yaw};
if (!finitePose(marker))
{
return fail("nonfinite_pose");
}
if (std::abs(wrap(std::atan2(marker.y, marker.x) - profile_.search_center_yaw)) > profile_.search_fov)
{
return fail("search_fov");
}
if (profile_.has_prior &&
(std::hypot(marker.x - profile_.prior_x, marker.y - profile_.prior_y) > profile_.prior_position_tolerance ||
std::abs(wrap(marker.yaw - profile_.prior_yaw)) > profile_.prior_yaw_tolerance))
{
return fail("prior");
}
const double nx = std::cos(yaw);
const double ny = std::sin(yaw);
ReflectorPose2D target{marker.x + profile_.offset_x * nx - profile_.offset_y * ny,
marker.y + profile_.offset_x * ny + profile_.offset_y * nx,
wrap(yaw + profile_.offset_yaw)};
if (!finitePose(target))
{
return fail("nonfinite_pose");
}
out.marker = marker;
out.target = target;
out.widths = {{first_width, second_width}};
out.spacing = spacing;
out.wall_rms = wall.rms;
out.wall_max_residual = wall.max_residual;
out.wall_support = {{left_support_.size(), right_support_.size()}};
out.edge_uncertainty = uncertainty;
return true;
}
ReflectorPairDetection ReflectorPairMatcher::match(
const robot_line_extraction::ScanGeometry& geometry, const std::vector<double>& ranges,
const std::vector<float>& intensities, const ReflectorPairLimits& limits,
const ReflectorPose2D& scan_in_prior)
{
ReflectorPairDetection result;
const auto fail = [&result](const char* why)
{
result.reason = why;
return result;
};
if (!configured_)
{
return fail("not_configured");
}
if (!std::isfinite(limits.min_range) || !std::isfinite(limits.max_range) ||
limits.min_range < 0.0 || limits.max_range <= limits.min_range ||
limits.max_candidates < 2 || limits.max_candidates > 128 ||
limits.max_pairs < 1 || limits.max_pairs > 8128 ||
limits.max_scan_rays < 2 || limits.max_scan_rays > 65536 || !finitePose(scan_in_prior))
{
return fail("invalid_limits_or_transform");
}
if (geometry.size > limits.max_scan_rays)
{
return fail("capacity_scan_rays");
}
std::string geometry_error;
if (!geometry.validate(geometry_error) || ranges.size() != geometry.size ||
!std::isfinite(geometry.angle_min + (geometry.size - 1) * geometry.angle_increment))
{
return fail("invalid_scan_geometry_or_ranges");
}
if (intensities.empty())
{
return fail("no_intensity_data");
}
if (intensities.size() != ranges.size())
{
return fail("intensity_size_mismatch");
}
rays_.resize(geometry.size);
candidates_.clear();
// Reserve theo scan lớn nhất từng thấy, không tạo vector tạm cho từng cặp.
support_.reserve(geometry.size);
left_support_.reserve(geometry.size);
right_support_.reserve(geometry.size);
candidates_.reserve(limits.max_candidates);
for (std::size_t i = 0; i < geometry.size; ++i)
{
Ray& ray = rays_[i];
ray = Ray{};
const double r = ranges[i];
ray.valid = std::isfinite(r) && r > 0.0 && r >= limits.min_range && r <= limits.max_range &&
std::isfinite(intensities[i]);
if (ray.valid)
{
ray.range = r;
ray.bright = intensities[i] >= profile_.tape_min_intensity;
if (!ray.bright)
{
const double angle = geometry.angle_min + static_cast<double>(i) * geometry.angle_increment;
ray.x = r * std::cos(angle);
ray.y = r * std::sin(angle);
}
}
}
const double steps_d = std::ceil(profile_.tape_bloom_max_angle / std::abs(geometry.angle_increment));
const std::size_t skirt = steps_d >= static_cast<double>(geometry.size)
? geometry.size : static_cast<std::size_t>(steps_d);
for (std::size_t i = 0; i < geometry.size;)
{
if (!rays_[i].valid || !rays_[i].bright)
{
++i;
continue;
}
const std::size_t first = i;
while (i < geometry.size && rays_[i].valid && rays_[i].bright)
{
++i;
}
const std::size_t last = i - 1;
const std::size_t mask_first = first > skirt ? first - skirt : 0;
const std::size_t mask_last = last + std::min(skirt, geometry.size - 1 - last);
for (std::size_t j = mask_first; j <= mask_last; ++j)
{
rays_[j].masked = true;
}
std::size_t best_start = 0;
std::size_t best_len = 0;
std::size_t ties = 0;
for (std::size_t j = first; j <= last;)
{
if (intensities[j] < profile_.tape_core_intensity)
{
++j;
continue;
}
const std::size_t start = j;
while (j <= last && intensities[j] >= profile_.tape_core_intensity)
{
++j;
}
const std::size_t length = j - start;
if (length > best_len)
{
best_start = start;
best_len = length;
ties = 1;
}
else if (length == best_len)
{
++ties;
}
}
if (best_len < profile_.tape_min_points || ties != 1 ||
static_cast<double>(best_len) / static_cast<double>(last - first + 1) <
profile_.tape_plateau_min_fraction || best_start == 0 ||
best_start + best_len >= geometry.size || !rays_[best_start - 1].valid ||
!rays_[best_start + best_len].valid ||
intensities[best_start - 1] >= profile_.tape_core_intensity ||
intensities[best_start + best_len] >= profile_.tape_core_intensity)
{
++result.rejected_runs;
continue;
}
if (candidates_.size() >= limits.max_candidates)
{
result.candidate_count = candidates_.size() + 1;
return fail("capacity_candidates");
}
candidates_.push_back(Candidate{first, last, best_start, best_start + best_len - 1});
}
result.candidate_count = candidates_.size();
if (candidates_.size() < 2)
{
return fail(result.rejected_runs ? "insufficient_candidates_or_core" : "insufficient_candidates");
}
const std::size_t count = candidates_.size() * (candidates_.size() - 1) / 2;
if (count > limits.max_pairs)
{
return fail("capacity_pairs");
}
const char* last_reason = "no_valid_pair";
for (std::size_t i = 0; i < candidates_.size(); ++i)
{
for (std::size_t j = i + 1; j < candidates_.size(); ++j)
{
++result.tested_pairs;
ReflectorPairDetection pair;
if (evaluatePair(candidates_[i], candidates_[j], geometry, scan_in_prior, pair, last_reason))
{
++result.valid_pairs;
if (result.valid_pairs == 1)
{
result.marker = pair.marker;
result.target = pair.target;
result.widths = pair.widths;
result.spacing = pair.spacing;
result.wall_rms = pair.wall_rms;
result.wall_max_residual = pair.wall_max_residual;
result.wall_support = pair.wall_support;
result.edge_uncertainty = pair.edge_uncertainty;
}
}
}
}
if (result.valid_pairs > 1)
{
// Không trả pose tùy ý khi còn nhiều cặp hợp lệ.
result.marker = ReflectorPose2D{};
result.target = ReflectorPose2D{};
result.widths = {{0.0, 0.0}};
result.spacing = 0.0;
result.wall_rms = 0.0;
result.wall_max_residual = 0.0;
result.wall_support = {{0, 0}};
result.edge_uncertainty = {{0.0, 0.0, 0.0, 0.0}};
return fail("ambiguous");
}
if (result.valid_pairs == 0)
{
result.reason = last_reason;
return result;
}
result.valid = true;
result.reason.clear();
return result;
}
} // namespace dock_pattern_detector

View File

@@ -0,0 +1,178 @@
#include <dock_pattern_detector/reflector_pair_profile.h>
#include <cmath>
#include <sstream>
namespace dock_pattern_detector
{
namespace
{
constexpr double kPi = 3.14159265358979323846;
bool validateValue(bool valid, const char* name, double value, const char* range,
std::string& error)
{
if (valid)
{
return true;
}
std::ostringstream message;
message << name << "=" << value << " must be " << range;
error = message.str();
return false;
}
} // namespace
bool ReflectorPairProfile::validate(std::string& error) const
{
error.clear();
const auto check = [&error](const char* name, double value, bool valid, const char* range)
{
return validateValue(std::isfinite(value) && valid, name, value, range, error);
};
if (!check("tape_width", tape_width, tape_width > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("width_tolerance", width_tolerance, width_tolerance > 0.0 && width_tolerance < tape_width,
"finite and in (0, tape_width) [m]"))
{
return false;
}
if (!check("tape_spacing", tape_spacing, tape_spacing > tape_width,
"finite and > tape_width [m]"))
{
return false;
}
if (!check("spacing_tolerance", spacing_tolerance,
spacing_tolerance > 0.0 && spacing_tolerance < tape_spacing,
"finite and in (0, tape_spacing) [m]"))
{
return false;
}
if (!check("tape_min_intensity", tape_min_intensity, tape_min_intensity >= 0.0,
"finite and >= 0 [driver units]"))
{
return false;
}
if (!check("tape_core_intensity", tape_core_intensity, tape_core_intensity >= tape_min_intensity,
"finite and >= tape_min_intensity [driver units]"))
{
return false;
}
if (!validateValue(tape_min_points >= 3, "tape_min_points", static_cast<double>(tape_min_points),
">= 3 [rays]", error))
{
return false;
}
if (!check("tape_bloom_max_angle", tape_bloom_max_angle,
tape_bloom_max_angle >= 0.0 && tape_bloom_max_angle < kPi,
"finite and in [0, pi) [rad]"))
{
return false;
}
if (!check("tape_plateau_min_fraction", tape_plateau_min_fraction,
tape_plateau_min_fraction > 0.0 && tape_plateau_min_fraction <= 1.0,
"finite and in (0, 1]"))
{
return false;
}
if (!check("edge_bias_bound", edge_bias_bound, edge_bias_bound >= 0.0,
"finite and >= 0 [m]"))
{
return false;
}
if (!check("max_edge_uncertainty", max_edge_uncertainty, max_edge_uncertainty > 0.0,
"finite and > 0 [m]"))
{
return false;
}
if (!check("min_ray_wall_cos", min_ray_wall_cos, min_ray_wall_cos > 0.0 && min_ray_wall_cos <= 1.0,
"finite and in (0, 1]"))
{
return false;
}
if (!validateValue(wall_min_points_each_side >= 3, "wall_min_points_each_side",
static_cast<double>(wall_min_points_each_side), ">= 3 [rays]", error))
{
return false;
}
if (!check("wall_min_span", wall_min_span, wall_min_span > tape_spacing,
"finite and > tape_spacing [m]"))
{
return false;
}
if (!check("wall_max_rms", wall_max_rms, wall_max_rms > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("wall_max_residual", wall_max_residual, wall_max_residual >= wall_max_rms,
"finite and >= wall_max_rms [m]"))
{
return false;
}
if (!check("wall_max_gap", wall_max_gap, wall_max_gap >= tape_width,
"finite and >= tape_width [m]"))
{
return false;
}
if (!check("wall_max_extrapolation", wall_max_extrapolation, wall_max_extrapolation >= 0.0,
"finite and >= 0 [m]"))
{
return false;
}
if (!check("wall_merge_distance", wall_merge_distance, wall_merge_distance > 0.0,
"finite and > 0 [m]"))
{
return false;
}
if (!check("prior_x", prior_x, true, "finite [m]"))
{
return false;
}
if (!check("prior_y", prior_y, true, "finite [m]"))
{
return false;
}
if (!check("prior_yaw", prior_yaw, true, "finite [rad]"))
{
return false;
}
if (has_prior)
{
if (!check("prior_position_tolerance", prior_position_tolerance, prior_position_tolerance > 0.0,
"finite and > 0 [m] when has_prior"))
{
return false;
}
if (!check("prior_yaw_tolerance", prior_yaw_tolerance,
prior_yaw_tolerance > 0.0 && prior_yaw_tolerance <= kPi,
"finite and in (0, pi] [rad] when has_prior"))
{
return false;
}
}
if (!check("search_center_yaw", search_center_yaw, true, "finite [rad]"))
{
return false;
}
if (!check("search_fov", search_fov, search_fov > 0.0 && search_fov <= kPi,
"finite and in (0, pi] [rad]"))
{
return false;
}
if (!check("offset_x", offset_x, offset_x > 0.0, "finite and > 0 [m]"))
{
return false;
}
if (!check("offset_y", offset_y, true, "finite [m]"))
{
return false;
}
if (!check("offset_yaw", offset_yaw, true, "finite [rad]"))
{
return false;
}
return true;
}
} // namespace dock_pattern_detector