Files
dock_pattern_detector/test/leg_pattern_matcher_test.cpp

1021 lines
35 KiB
C++
Raw 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.
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm dò xe hàng 4 chân bằng scan TỔNG HỢP — đặt chân vào thế giới 2D, chiếu tia, biết trước đáp
* án. Số xe theo mô hình sim `tci_trolley`, hình học scan theo SICK S300 sim của `hook_150`.
*
* Sáu nhóm:
* 1. dò đúng — thẳng, xoay, lệch ngang, chân tròn;
* 2. che khuất — 1 chân bị che vẫn nhận, 2 chân bị che thì từ chối, tia xuyên qua thì từ chối;
* 3. TỪ CHỐI — chân người, chân dính tường, lòng xe có vật, hai xe sát nhau;
* 4. dải phản quang, prior, nhiễu;
* 5. chân dính làm chân yếu, lidar trả 0 khi không phản hồi;
* 6. config hỏng.
*
* Scan thật của lidar KIT nằm ở `leg_pattern_matcher_kit_test.cpp`.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <string>
#include <utility>
#include <vector>
#include <dock_pattern_detector/leg_pattern_matcher.h>
#include "leg_scan_sim.h"
namespace
{
using dock_pattern_detector::LegDetection;
using dock_pattern_detector::LegPatternMatcher;
using dock_pattern_detector::LegProfile;
using dock_pattern_detector::LegShape;
using dock_pattern_detector::Pose2D;
using dock_pattern_detector::ScanLimits;
using dock_pattern_detector::TapeLegs;
using leg_scan_sim::World;
constexpr double kDeg = M_PI / 180.0;
/// Tâm xe khi cạnh vào cách cảm biến 0.9 m (pose chuẩn bị của plan): 0.9 + 0.720/2.
constexpr double kCx = 1.26;
LegProfile tciTrolley()
{
LegProfile p;
p.cart_opening = 0.517;
p.cart_depth = 0.720;
p.leg_shape = LegShape::kBox;
p.leg_width = 0.030;
p.min_legs = 3;
return p;
}
ScanLimits s300Limits()
{
ScanLimits l;
l.min_range = 0.10;
l.max_range = 3.0;
l.range_sigma = 0.01;
return l;
}
double yawError(double a, double b)
{
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
}
/// @brief Cấu hình matcher, chiếu tia lên @p world, dò. Prior frame trùng frame scan.
LegDetection detect(const LegProfile& p, const World& world, double sigma = 0.0,
unsigned seed = 1)
{
LegPatternMatcher matcher;
std::string error;
EXPECT_TRUE(matcher.configure(p, error)) << error;
const auto g = leg_scan_sim::s300Geometry();
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g, sigma, seed);
return matcher.match(g, scan.ranges, scan.intensities, s300Limits(), Pose2D());
}
LegDetection matchScan(const LegProfile& p, const robot_line_extraction::ScanGeometry& geometry,
const leg_scan_sim::Scan& scan)
{
LegPatternMatcher matcher;
std::string error;
EXPECT_TRUE(matcher.configure(p, error)) << error;
return matcher.match(geometry, scan.ranges, scan.intensities, s300Limits(), Pose2D());
}
void addClimbingBloomSkirts(leg_scan_sim::Scan& scan, double threshold)
{
std::vector<std::pair<std::size_t, std::size_t>> runs;
std::size_t i = 0;
while (i < scan.intensities.size())
{
if (scan.intensities[i] < threshold)
{
++i;
continue;
}
const std::size_t first = i;
while (i + 1 < scan.intensities.size() && scan.intensities[i + 1] >= threshold)
{
++i;
}
runs.emplace_back(first, i);
++i;
}
const auto paint = [&](std::size_t edge, int step) {
const double r0 = scan.ranges[edge];
for (int k = 1; k <= 4; ++k)
{
const long index = static_cast<long>(edge) + step * k;
if (index < 0 || index >= static_cast<long>(scan.ranges.size()) ||
scan.intensities[index] >= threshold)
{
break;
}
scan.ranges[index] = r0 + 0.008 * k;
scan.intensities[index] = 100.0f;
}
const long background = static_cast<long>(edge) + step * 5;
if (background >= 0 && background < static_cast<long>(scan.ranges.size()) &&
scan.intensities[background] < threshold)
{
scan.ranges[background] = r0 + 0.20;
scan.intensities[background] = 100.0f;
}
};
for (const auto& run : runs)
{
paint(run.first, -1);
paint(run.second, +1);
}
}
std::pair<std::size_t, std::size_t> firstBrightRun(const leg_scan_sim::Scan& scan,
double threshold)
{
for (std::size_t i = 0; i < scan.intensities.size(); ++i)
{
if (scan.intensities[i] < threshold)
{
continue;
}
std::size_t last = i;
while (last + 1 < scan.intensities.size() && scan.intensities[last + 1] >= threshold)
{
++last;
}
return { i, last };
}
return { scan.intensities.size(), scan.intensities.size() };
}
LegProfile reflectiveTrolley()
{
LegProfile p = tciTrolley();
p.tape_enabled = true;
p.tape_legs = TapeLegs::kEntry;
p.tape_min_intensity = 1000.0;
p.tape_min_points = 2;
p.tape_bloom_max_angle = 0.10;
return p;
}
// ================================================================================================
// 1. Dò đúng
// ================================================================================================
TEST(LegProfile, ValidatesAllBrightBiasThreshold)
{
LegProfile p = tciTrolley();
std::string error;
EXPECT_TRUE(p.validate(error)) << error;
for (double value : {-0.001, 0.101, std::numeric_limits<double>::quiet_NaN()})
{
p.tape_range_bias_all_max_std = value;
EXPECT_FALSE(p.validate(error));
}
p.tape_range_bias_all_max_std = 0.02;
EXPECT_TRUE(p.validate(error)) << error;
p.tape_enabled = true;
EXPECT_FALSE(p.validate(error));
p.tape_range_bias_sigma = 0.05;
EXPECT_TRUE(p.validate(error)) << error;
p.tape_range_bias_all_max_std = 0.0;
p.tape_enabled = false;
p.tape_range_bias_sigma = 0.0;
EXPECT_TRUE(p.validate(error)) << error;
}
TEST(LegPatternMatcher, FindsACartFacingTheSensor)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.center_x, kCx, 0.003);
EXPECT_NEAR(d.center_y, 0.0, 0.003);
// Pháp tuyến cạnh vào trỏ VỀ cảm biến — cùng quy ước V/arc.
EXPECT_LT(yawError(d.center_yaw, M_PI), 0.3 * kDeg);
EXPECT_EQ(d.legs_seen, 4);
EXPECT_NEAR(d.measured_opening, p.cart_opening, 0.02);
EXPECT_NEAR(d.measured_depth, p.cart_depth, 0.02);
}
TEST(LegPatternMatcher, FollowsARotatedCart)
{
const LegProfile p = tciTrolley();
for (double rot : { -22.5, -15.0, -7.5, 7.5, 15.0, 22.5 })
{
World w;
const double axis = M_PI + rot * kDeg;
leg_scan_sim::addCart(w, p, kCx, 0.0, axis);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << "rotation " << rot << ": " << d.reason;
EXPECT_NEAR(d.center_x, kCx, 0.003) << "rotation " << rot;
EXPECT_NEAR(d.center_y, 0.0, 0.003) << "rotation " << rot;
EXPECT_LT(yawError(d.center_yaw, axis), 0.3 * kDeg) << "rotation " << rot;
}
}
TEST(LegPatternMatcher, FollowsALateralOffset)
{
const LegProfile p = tciTrolley();
for (double y : { -0.20, -0.10, 0.10, 0.20 })
{
World w;
leg_scan_sim::addCart(w, p, kCx, y, M_PI);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << "offset " << y << ": " << d.reason;
EXPECT_NEAR(d.center_y, y, 0.003) << "offset " << y;
}
}
TEST(LegPatternMatcher, FindsRoundLegs)
{
LegProfile p = tciTrolley();
p.leg_shape = LegShape::kRound;
p.leg_width = 0.040;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.05, M_PI + 10.0 * kDeg);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.center_x, kCx, 0.003);
EXPECT_NEAR(d.center_y, 0.05, 0.003);
}
TEST(LegPatternMatcher, AppliesTheOffsetLikeTheVMatcher)
{
LegProfile p = tciTrolley();
p.offset_x = 0.10;
p.offset_yaw = 0.05;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
// offset_x dọc pháp tuyến cạnh vào, hướng về phía robot: pháp tuyến trỏ −x nên đích lùi về x nhỏ.
EXPECT_NEAR(d.x, kCx - 0.10, 0.003);
EXPECT_LT(yawError(d.yaw, M_PI + 0.05), 0.3 * kDeg);
}
TEST(LegPatternMatcher, RejectsACartBeyondMaxRange)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, 3.6, 0.0, M_PI);
EXPECT_FALSE(detect(p, w).valid);
}
// ================================================================================================
// 2. Che khuất
// ================================================================================================
TEST(LegPatternMatcher, AcceptsOneLegHiddenBehindAnother)
{
const LegProfile p = tciTrolley();
World w;
// Cảm biến nằm đúng trên đường thẳng qua hai chân của một cạnh dọc: chân sau của cạnh đó nấp sau
// chân trước.
leg_scan_sim::addCart(w, p, kCx, p.cart_opening / 2.0, M_PI);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_EQ(d.legs_seen, 3);
EXPECT_EQ(d.legs_occluded, 1);
EXPECT_NEAR(d.center_y, p.cart_opening / 2.0, 0.005);
}
TEST(LegPatternMatcher, RejectsWhenABoxHidesTwoLegs)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
// Thùng hàng chắn trước cả hai chân bên trái.
w.addBox(0.6, 0.15, 0.10, 0.20, 0.0);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("leg"), std::string::npos) << d.reason;
}
TEST(LegPatternMatcher, AcceptsTwoHiddenLegsWithMinLegsTwoAndAPrior)
{
LegProfile p = tciTrolley();
p.min_legs = 2;
p.has_prior = true;
p.prior_x = kCx;
p.prior_y = 0.0;
p.prior_yaw = M_PI;
p.prior_yaw_tolerance = 0.35;
p.search_radius = 0.30;
p.min_confidence = 0.3;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
w.addBox(0.6, 0.15, 0.10, 0.20, 0.0);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.center_y, 0.0, 0.01);
}
TEST(LegPatternMatcher, RejectsWhenTheScanPassesWhereALegMustStand)
{
const LegProfile p = tciTrolley();
World w;
const bool skip[4] = { false, false, false, true }; // thiếu chân sau-phải, phía sau trống
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, skip);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("leg_missing"), std::string::npos) << d.reason;
}
// ================================================================================================
// 3. Từ chối
// ================================================================================================
TEST(LegPatternMatcher, IgnoresAPersonsLegs)
{
const LegProfile p = tciTrolley();
World w;
w.addCircle(1.0, 0.125, 0.06);
w.addCircle(1.0, -0.125, 0.06);
EXPECT_FALSE(detect(p, w).valid);
}
TEST(LegPatternMatcher, LegsTouchingAWallAreNotFreeStanding)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
// Tường áp sát mặt sau hai chân sau: mép cụm liền với tường → "dính" → hai chân sau bị loại.
w.addWall(kCx + p.cart_depth / 2.0 + p.leg_width / 2.0, -3.0,
kCx + p.cart_depth / 2.0 + p.leg_width / 2.0, 3.0);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid);
}
TEST(LegPatternMatcher, InteriorGateRejectsACartWithSomethingInside)
{
LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
w.addBox(kCx, 0.0, 0.15, 0.15, 0.0);
p.max_interior_points = 0;
const LegDetection blocked = detect(p, w);
EXPECT_FALSE(blocked.valid);
EXPECT_NE(blocked.reason.find("inside the cart"), std::string::npos) << blocked.reason;
p.max_interior_points = -1; // cổng tắt
EXPECT_TRUE(detect(p, w).valid);
}
TEST(LegPatternMatcher, TwoCartsSideBySideWithoutAPriorAreAmbiguous)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.485, M_PI);
leg_scan_sim::addCart(w, p, kCx, -0.485, M_PI);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("ambiguous"), std::string::npos) << d.reason;
}
TEST(LegPatternMatcher, LegsOfTwoNeighboursDoNotMakeAPhantomCart)
{
// Hai xe sát nhau, prior đặt ĐÚNG GIỮA hai xe: bốn chân phía trong (khe 0.453 m) gần giống một xe
// 0.517 m. Không được nhận "xe" đó.
LegProfile p = tciTrolley();
p.has_prior = true;
p.prior_x = kCx;
p.prior_y = 0.0;
p.prior_yaw = M_PI;
p.prior_yaw_tolerance = 0.35;
p.search_radius = 0.20;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.485, M_PI);
leg_scan_sim::addCart(w, p, kCx, -0.485, M_PI);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid) << "phantom at (" << d.center_x << ", " << d.center_y << ")";
}
TEST(LegPatternMatcher, APriorPicksOneCartOfARow)
{
LegProfile p = tciTrolley();
p.has_prior = true;
p.prior_x = kCx;
p.prior_y = 0.0;
p.prior_yaw = M_PI;
p.prior_yaw_tolerance = 0.35;
p.search_radius = 0.30;
World w;
// Dãy 3 xe bước 0.97 m như world factory_ss_demo: khe chân hai xe kề nhau 0.453 m.
for (double y : { -0.97, 0.0, 0.97 })
{
leg_scan_sim::addCart(w, p, kCx, y, M_PI);
}
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.center_y, 0.0, 0.005);
EXPECT_NEAR(d.center_x, kCx, 0.005);
}
// ================================================================================================
// 4. Dải phản quang, nhiễu
// ================================================================================================
TEST(LegPatternMatcher, EntryTapeDecidesWhichEndIsTheEntry)
{
LegProfile p = tciTrolley();
p.tape_enabled = true;
p.tape_legs = TapeLegs::kEntry;
p.tape_min_intensity = 1000.0;
{
World w;
const bool taped[4] = { true, true, false, false }; // dải ở hai chân phía cảm biến
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, nullptr, taped);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_LT(yawError(d.center_yaw, M_PI), 0.3 * kDeg);
}
{
World w;
const bool taped[4] = { false, false, true, true }; // dải ở đầu xa: cạnh vào là đầu xa
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, nullptr, taped);
const LegDetection d = detect(p, w);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_LT(yawError(d.center_yaw, 0.0), 0.3 * kDeg);
}
}
TEST(LegPatternMatcher, BrightCoreWithClimbingBloomIsFreeAndNotAttached)
{
const LegProfile p = reflectiveTrolley();
World world;
const bool taped[4] = { true, true, false, false };
leg_scan_sim::addCart(world, p, kCx, 0.0, M_PI, nullptr, taped);
const auto geometry = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, geometry);
addClimbingBloomSkirts(scan, p.tape_min_intensity);
const LegDetection d = matchScan(p, geometry, scan);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_EQ(d.legs_seen, 4);
EXPECT_EQ(d.legs_attached, 0);
EXPECT_EQ(d.legs_partial, 0);
}
TEST(LegPatternMatcher, BrightCoreAgainstSameRangeWallRemainsAttached)
{
LegProfile p = reflectiveTrolley();
p.accept_attached_legs = true;
World world;
const bool taped[4] = { true, true, false, false };
leg_scan_sim::addCart(world, p, kCx, 0.0, M_PI, nullptr, taped);
const auto geometry = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, geometry);
addClimbingBloomSkirts(scan, p.tape_min_intensity);
const auto run = firstBrightRun(scan, p.tape_min_intensity);
ASSERT_LT(run.first, scan.ranges.size());
const double r0 = scan.ranges[run.first];
for (int step = 1; step <= 17; ++step)
{
const long index = static_cast<long>(run.first) - step;
ASSERT_GE(index, 0);
if (scan.intensities[index] >= p.tape_min_intensity)
{
break;
}
scan.ranges[index] = r0 + 0.002 * step;
scan.intensities[index] = 100.0f;
}
const LegDetection d = matchScan(p, geometry, scan);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_GE(d.legs_attached, 1);
}
TEST(LegPatternMatcher, OccluderAtBrightCoreEdgeMakesTheLegPartial)
{
const LegProfile p = reflectiveTrolley();
World world;
const bool taped[4] = { true, true, false, false };
leg_scan_sim::addCart(world, p, kCx, 0.0, M_PI, nullptr, taped);
const auto geometry = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, geometry);
addClimbingBloomSkirts(scan, p.tape_min_intensity);
const auto run = firstBrightRun(scan, p.tape_min_intensity);
ASSERT_LT(run.first, scan.ranges.size());
ASSERT_GT(run.first, 0u);
scan.ranges[run.first - 1] = scan.ranges[run.first] - 0.20;
scan.intensities[run.first - 1] = 100.0f;
const LegDetection d = matchScan(p, geometry, scan);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_GE(d.legs_partial, 1);
}
TEST(LegPatternMatcher, RejectsFarTapedCoreWithTenCentimeterRangeRamp)
{
LegProfile p = reflectiveTrolley();
p.tape_legs = TapeLegs::kAll;
p.tape_range_bias_sigma = 0.05;
p.leg_cluster_gap = 0.12;
World world;
const bool taped[4] = { true, true, true, true };
const std::vector<int> ids = leg_scan_sim::addCart(world, p, kCx, 0.0, M_PI, nullptr, taped);
const auto geometry = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, geometry);
const LegDetection baseline = matchScan(p, geometry, scan);
ASSERT_TRUE(baseline.valid) << baseline.reason;
ASSERT_EQ(baseline.legs_seen, 4);
std::vector<std::size_t> far_right_core;
for (std::size_t i = 0; i < scan.hit.size(); ++i)
{
if (scan.hit[i] == ids[dock_pattern_detector::kFarRight] &&
scan.intensities[i] >= p.tape_min_intensity)
{
far_right_core.push_back(i);
}
}
ASSERT_GE(far_right_core.size(), 2u);
const double ramp_start = scan.ranges[far_right_core.front()];
for (std::size_t i = 0; i < far_right_core.size(); ++i)
{
const double fraction = static_cast<double>(i) /
static_cast<double>(far_right_core.size() - 1);
scan.ranges[far_right_core[i]] = ramp_start + 0.10 * fraction;
}
const LegDetection detection = matchScan(p, geometry, scan);
ASSERT_TRUE(detection.valid) << detection.reason;
EXPECT_EQ(detection.legs_seen, 3);
EXPECT_EQ(detection.tape_bright_rays[dock_pattern_detector::kEntryLeft],
baseline.tape_bright_rays[dock_pattern_detector::kEntryLeft]);
EXPECT_EQ(detection.tape_bright_rays[dock_pattern_detector::kEntryRight],
baseline.tape_bright_rays[dock_pattern_detector::kEntryRight]);
EXPECT_EQ(detection.tape_bright_rays[dock_pattern_detector::kFarLeft],
baseline.tape_bright_rays[dock_pattern_detector::kFarLeft]);
EXPECT_EQ(detection.tape_bright_rays[dock_pattern_detector::kFarRight], 0u);
}
TEST(LegPatternMatcher, ZeroTapeCorrectionKeysPreserveLegacySyntheticResult)
{
LegProfile before = tciTrolley();
LegProfile disabled = before;
disabled.tape_enabled = true;
disabled.tape_legs = TapeLegs::kEntry;
disabled.tape_min_intensity = 1000.0;
disabled.tape_min_points = 2;
disabled.tape_bloom_max_angle = 0.0;
disabled.tape_range_bias_sigma = 0.0;
World world;
const bool taped[4] = { true, true, false, false };
leg_scan_sim::addCart(world, before, kCx, 0.0, M_PI, nullptr, taped);
const auto geometry = leg_scan_sim::s300Geometry();
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, geometry);
const LegDetection a = matchScan(before, geometry, scan);
const LegDetection b = matchScan(disabled, geometry, scan);
ASSERT_TRUE(a.valid) << a.reason;
ASSERT_TRUE(b.valid) << b.reason;
EXPECT_EQ(a.center_x, b.center_x);
EXPECT_EQ(a.center_y, b.center_y);
EXPECT_EQ(a.center_yaw, b.center_yaw);
EXPECT_EQ(a.legs_seen, b.legs_seen);
EXPECT_EQ(a.measured_opening, b.measured_opening);
EXPECT_EQ(a.measured_depth, b.measured_depth);
}
TEST(LegPatternMatcher, TapeWithoutIntensitiesSaysSo)
{
LegProfile p = tciTrolley();
p.tape_enabled = true;
LegPatternMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(p, error)) << error;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
const auto g = leg_scan_sim::s300Geometry();
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(w, g);
const LegDetection d = matcher.match(g, scan.ranges, {}, s300Limits(), Pose2D());
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("no intensity"), std::string::npos) << d.reason;
}
TEST(LegPatternMatcher, TapeDisabledIgnoresIntensities)
{
const LegProfile p = tciTrolley();
LegPatternMatcher matcher;
std::string error;
ASSERT_TRUE(matcher.configure(p, error)) << error;
World w;
leg_scan_sim::addCart(w, p, kCx, 0.03, M_PI + 0.1);
const auto g = leg_scan_sim::s300Geometry();
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(w, g);
const LegDetection with = matcher.match(g, scan.ranges, scan.intensities, s300Limits(), Pose2D());
const LegDetection without = matcher.match(g, scan.ranges, {}, s300Limits(), Pose2D());
ASSERT_TRUE(with.valid) << with.reason;
EXPECT_EQ(with.center_x, without.center_x);
EXPECT_EQ(with.center_y, without.center_y);
EXPECT_EQ(with.center_yaw, without.center_yaw);
}
TEST(LegPatternMatcher, StaysWithinToleranceUnderS300Noise)
{
// σ 10 mm của S300 sim trên chân 30 mm. Đây là sai số MỖI SCAN; handler còn lọc nhiều scan.
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
double sum_xy = 0.0, max_xy = 0.0, sum_yaw = 0.0, max_yaw = 0.0;
int found = 0;
for (unsigned seed = 1; seed <= 50; ++seed)
{
const LegDetection d = detect(p, w, 0.01, seed);
if (!d.valid)
{
continue;
}
++found;
const double exy = std::hypot(d.center_x - kCx, d.center_y);
const double eyaw = yawError(d.center_yaw, M_PI);
sum_xy += exy;
sum_yaw += eyaw;
max_xy = std::max(max_xy, exy);
max_yaw = std::max(max_yaw, eyaw);
}
ASSERT_GE(found, 45) << "detection rate under noise";
EXPECT_LT(sum_xy / found, 0.005);
EXPECT_LT(sum_yaw / found, 0.5 * kDeg);
EXPECT_LT(max_xy, 0.015);
EXPECT_LT(max_yaw, 2.0 * kDeg);
}
TEST(LegPatternMatcher, AcceptsACartWithinTheDimensionTolerance)
{
// Cùng một loại xe nhưng chiếc này gia công lệch: hẹp hơn profile 3 cm, dài hơn 2.5 cm — trong
// cart_dim_tolerance (4 cm). Phải dò được, kể cả khi một chân nấp sau chân kia: chỉ 3 chân thì
// điểm số chân chỉ có 0.375, nên phần khớp không được trừ điểm vì lệch mô hình.
const LegProfile p = tciTrolley();
LegProfile real = p;
real.cart_opening = p.cart_opening - 0.03;
real.cart_depth = p.cart_depth + 0.025;
for (double cy : { 0.0, real.cart_opening / 2.0 }) // đủ 4 chân / một chân nấp sau chân kia
{
World w;
leg_scan_sim::addCart(w, real, kCx, cy, M_PI);
const LegDetection d = detect(p, w, 0.01, 3);
ASSERT_TRUE(d.valid) << "cy " << cy << ": " << d.reason;
EXPECT_GE(d.confidence, p.min_confidence) << "cy " << cy;
EXPECT_NEAR(d.center_x, kCx, 0.02) << "cy " << cy;
EXPECT_NEAR(d.center_y, cy, 0.015) << "cy " << cy;
EXPECT_LT(yawError(d.center_yaw, M_PI), 2.0 * kDeg) << "cy " << cy;
}
}
TEST(LegPatternMatcher, RejectsACartFarOutsideTheDimensionTolerance)
{
// Nới điểm tin theo dung sai không được biến thành nhận mọi vật 4 chân: xe rộng hơn profile 15 cm
// vẫn không có cặp chân nào đúng cạnh vào.
const LegProfile p = tciTrolley();
LegProfile real = p;
real.cart_opening = p.cart_opening + 0.15;
World w;
leg_scan_sim::addCart(w, real, kCx, 0.0, M_PI);
const LegDetection d = detect(p, w);
EXPECT_FALSE(d.valid) << "confidence " << d.confidence;
}
TEST(LegPatternMatcher, IsDeterministic)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.07, M_PI + 0.12);
const LegDetection a = detect(p, w, 0.01, 7);
const LegDetection b = detect(p, w, 0.01, 7);
ASSERT_TRUE(a.valid) << a.reason;
EXPECT_EQ(a.center_x, b.center_x);
EXPECT_EQ(a.center_y, b.center_y);
EXPECT_EQ(a.center_yaw, b.center_yaw);
}
// ================================================================================================
// 5. Chân dính (`accept_attached_legs`) và lidar trả 0 khi không phản hồi (`zero_range_is_no_echo`)
// ================================================================================================
/// @brief Như detect(), nhưng chọn được ScanLimits và đổi tia không trúng gì (inf) thành 0 như driver
/// lidar KIT.
LegDetection detectWith(const LegProfile& p, const World& world, bool zero_for_no_echo,
bool zero_range_is_no_echo)
{
LegPatternMatcher matcher;
std::string error;
EXPECT_TRUE(matcher.configure(p, error)) << error;
const auto g = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g);
if (zero_for_no_echo)
{
for (double& r : scan.ranges)
{
r = std::isfinite(r) ? r : 0.0;
}
}
ScanLimits limits = s300Limits();
limits.zero_range_is_no_echo = zero_range_is_no_echo;
return matcher.match(g, scan.ranges, scan.intensities, limits, Pose2D());
}
TEST(LegPatternMatcher, AttachedLegCountsWhenEnabled)
{
// Ca robot KIT 28/10: một chân bị che (ở đây: chân xa-trái nấp sau chân vào-trái), và chân xa-phải
// đứng trước một vật cách 8 cm — gần hơn leg_min_depth_gap nên mép cụm "dính". Chỉ còn hai chân tự
// do.
LegProfile p = tciTrolley();
World w;
const double cy = p.cart_opening / 2.0;
leg_scan_sim::addCart(w, p, kCx, cy, M_PI);
const double behind = kCx + p.cart_depth / 2.0 + p.leg_width / 2.0 + 0.08;
w.addWall(behind, p.cart_opening - 0.15, behind, p.cart_opening + 0.15);
p.accept_attached_legs = false;
const LegDetection off = detectWith(p, w, false, false);
EXPECT_FALSE(off.valid);
EXPECT_NE(off.reason.find("too few legs"), std::string::npos) << off.reason;
p.accept_attached_legs = true;
const LegDetection on = detectWith(p, w, false, false);
ASSERT_TRUE(on.valid) << on.reason;
EXPECT_EQ(on.legs_seen, 3);
EXPECT_EQ(on.legs_attached, 1);
EXPECT_EQ(on.legs_occluded, 1);
EXPECT_NEAR(on.center_x, kCx, 0.005);
EXPECT_NEAR(on.center_y, cy, 0.005);
EXPECT_LT(yawError(on.center_yaw, M_PI), 0.5 * kDeg);
}
TEST(LegPatternMatcher, AttachedLegsCannotStartAHypothesis)
{
// Chỉ còn hai chân xa, cả hai dính tường phía sau: đúng khoảng cách cart_opening nhưng là chân yếu.
// Hai chỗ lồi trên tường cũng trông y như vậy, nên không được tự dựng xe.
LegProfile p = tciTrolley();
p.accept_attached_legs = true;
World w;
const bool skip[4] = { true, true, false, false };
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, skip);
const double behind = kCx + p.cart_depth / 2.0 + p.leg_width / 2.0 + 0.08;
w.addWall(behind, -0.8, behind, 0.8);
const LegDetection d = detectWith(p, w, false, false);
EXPECT_FALSE(d.valid);
EXPECT_EQ(d.leg_candidates, 2u);
EXPECT_EQ(d.hypotheses, 0u);
EXPECT_NE(d.reason.find("attached legs cannot start a hypothesis"), std::string::npos)
<< d.reason;
}
TEST(LegPatternMatcher, ZeroRangeAsNoEchoMatchesAnInfScan)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.05, M_PI + 10.0 * kDeg);
const LegDetection inf_scan = detectWith(p, w, false, false);
const LegDetection zero_blocked = detectWith(p, w, true, false);
const LegDetection zero_no_echo = detectWith(p, w, true, true);
ASSERT_TRUE(inf_scan.valid) << inf_scan.reason;
ASSERT_TRUE(zero_blocked.valid) << zero_blocked.reason;
ASSERT_TRUE(zero_no_echo.valid) << zero_no_echo.reason;
// Đọc 0 là "bị chắn sát cảm biến": mép nào cũng thành mép bị che.
EXPECT_EQ(inf_scan.legs_partial, 0);
EXPECT_EQ(zero_blocked.legs_partial, 4);
// Đọc 0 là "không phản hồi": y hệt scan trả inf, từng bit.
EXPECT_EQ(zero_no_echo.legs_partial, 0);
EXPECT_EQ(zero_no_echo.center_x, inf_scan.center_x);
EXPECT_EQ(zero_no_echo.center_y, inf_scan.center_y);
EXPECT_EQ(zero_no_echo.center_yaw, inf_scan.center_yaw);
}
TEST(LegPatternMatcher, ZeroRangeIsNoEvidenceButABackgroundStillSeesThrough)
{
const LegProfile p = tciTrolley();
const bool skip[4] = { false, false, false, true }; // thiếu chân sau-phải
// Phía sau trống, mọi tia đi qua chỗ chân đều trả 0: không biết tia đi tới đâu, nên không loại
// xe (với scan trả inf thì loại — xem RejectsWhenTheScanPassesWhereALegMustStand).
World open;
leg_scan_sim::addCart(open, p, kCx, 0.0, M_PI, skip);
const LegDetection unknown = detectWith(p, open, true, true);
ASSERT_TRUE(unknown.valid) << unknown.reason;
EXPECT_EQ(unknown.legs_seen, 3);
EXPECT_EQ(unknown.legs_out_of_view, 1);
// Có tường phía sau: tia đi qua chỗ chân rồi trả về từ tường, đó là bằng chứng thật.
World backed = open;
backed.addWall(2.4, -1.0, 2.4, 1.0);
const LegDetection missing = detectWith(p, backed, true, true);
EXPECT_FALSE(missing.valid);
EXPECT_NE(missing.reason.find("leg_missing"), std::string::npos) << missing.reason;
}
// ================================================================================================
// 6. Config
// ================================================================================================
TEST(LegProfile, ValidateRefusesBrokenProfiles)
{
std::string error;
LegProfile p = tciTrolley();
EXPECT_TRUE(p.validate(error)) << error;
p = tciTrolley();
p.cart_opening = 0.0;
EXPECT_FALSE(p.validate(error));
p = tciTrolley();
p.min_legs = 2; // không có prior
EXPECT_FALSE(p.validate(error));
p = tciTrolley();
p.cart_opening = 0.70; // gần vuông với cart_depth 0.72, không có gì chọn cạnh vào
EXPECT_FALSE(p.validate(error));
p = tciTrolley();
p.tape_legs = TapeLegs::kEntry; // quên bật dải
EXPECT_FALSE(p.validate(error));
p = tciTrolley();
p.leg_shape = LegShape::kRound;
p.leg_depth = 0.02; // chân tròn không có bề dày riêng
EXPECT_FALSE(p.validate(error));
p = tciTrolley();
p.cart_dim_tolerance = 0.20; // ≥ cạnh ngắn / 4
EXPECT_FALSE(p.validate(error));
}
TEST(LegProfile, TapeBloomAndRangeBiasRequireValidRanges)
{
std::string error;
LegProfile p = tciTrolley();
p.tape_bloom_max_angle = 0.10;
EXPECT_TRUE(p.validate(error)) << error;
p = reflectiveTrolley();
p.tape_bloom_max_angle = 0.5;
EXPECT_FALSE(p.validate(error));
p = reflectiveTrolley();
p.tape_range_bias_sigma = 0.201;
EXPECT_FALSE(p.validate(error));
p = reflectiveTrolley();
p.tape_range_bias_sigma = std::numeric_limits<double>::infinity();
EXPECT_FALSE(p.validate(error));
p = reflectiveTrolley();
EXPECT_TRUE(p.validate(error)) << error;
}
TEST(LegProfile, TapePlateauRequiresValidFractionAndBloom)
{
std::string error;
LegProfile p = reflectiveTrolley();
for (double value : { -0.01, 1.0, std::numeric_limits<double>::quiet_NaN() })
{
p.tape_plateau_min_fraction = value;
EXPECT_FALSE(p.validate(error)) << value;
EXPECT_NE(error.find("tape_plateau_min_fraction"), std::string::npos);
}
p = tciTrolley();
p.tape_plateau_min_fraction = 0.65;
EXPECT_TRUE(p.validate(error)) << error;
p = reflectiveTrolley();
p.tape_bloom_max_angle = 0.0;
p.tape_plateau_min_fraction = 0.65;
EXPECT_FALSE(p.validate(error));
p.tape_plateau_min_fraction = 0.0;
EXPECT_TRUE(p.validate(error)) << error;
p = tciTrolley();
EXPECT_TRUE(p.validate(error)) << error;
p = reflectiveTrolley();
p.tape_plateau_min_fraction = 0.65;
EXPECT_TRUE(p.validate(error)) << error;
}
TEST(LegProfile, TapeOffIgnoresTunedKeysButStillRejectsEntryTape)
{
LegProfile p = tciTrolley();
std::string error;
EXPECT_TRUE(p.ignoredTapeKeys().empty());
p.tape_bloom_max_angle = 0.10;
p.tape_range_bias_sigma = 0.05;
p.tape_plateau_min_fraction = 0.65;
p.tape_range_bias_all_max_std = 0.02;
ASSERT_TRUE(p.validate(error)) << error;
EXPECT_EQ(p.ignoredTapeKeys(), "tape_bloom_max_angle 0.100, tape_range_bias_sigma 0.050, "
"tape_plateau_min_fraction 0.650, tape_range_bias_all_max_std 0.020");
p.tape_enabled = true;
EXPECT_TRUE(p.validate(error)) << error;
EXPECT_TRUE(p.ignoredTapeKeys().empty());
p.tape_enabled = false;
p.tape_legs = TapeLegs::kEntry;
EXPECT_FALSE(p.validate(error));
EXPECT_EQ(error, "tape_legs 'entry' requires tape_enabled: true (forgot to turn the tape on?)");
p.tape_legs = TapeLegs::kAll;
p.tape_bloom_max_angle = 0.0;
p.tape_plateau_min_fraction = 0.0;
p.tape_range_bias_all_max_std = 0.0;
EXPECT_EQ(p.ignoredTapeKeys(), "tape_range_bias_sigma 0.050");
}
TEST(LegProfile, TapeKeyRangesAreCheckedEvenWhenTapeIsOff)
{
std::string error;
const double nan = std::numeric_limits<double>::quiet_NaN();
const double inf = std::numeric_limits<double>::infinity();
for (bool enabled : { false, true })
{
for (const auto& test : { std::pair<double LegProfile::*, double>{ &LegProfile::tape_bloom_max_angle, 0.5 },
{ &LegProfile::tape_range_bias_sigma, 0.201 },
{ &LegProfile::tape_plateau_min_fraction, 1.0 },
{ &LegProfile::tape_range_bias_all_max_std, 0.101 } })
{
for (double value : { -0.01, test.second, nan, inf })
{
LegProfile p = tciTrolley();
p.tape_enabled = enabled;
p.*test.first = value;
EXPECT_FALSE(p.validate(error)) << "tape_enabled=" << enabled << ", value=" << value;
}
}
}
}
TEST(LegPatternMatcher, PlateauRescuesEdgeRampButRejectsSlopeAndShortPlateau)
{
LegProfile p = reflectiveTrolley();
p.tape_legs = TapeLegs::kAll;
p.tape_plateau_min_fraction = 0.65;
p.leg_width_tolerance = 0.02;
p.shadow_min_angle = 0.0;
robot_line_extraction::ScanGeometry geometry;
geometry.angle_min = -0.1;
geometry.angle_increment = 0.004;
geometry.size = 50;
const auto run = [&](const std::vector<double>& values, std::size_t min_points, double fraction) {
LegProfile profile = p;
profile.tape_min_points = min_points;
profile.tape_plateau_min_fraction = fraction;
leg_scan_sim::Scan scan;
scan.ranges.assign(geometry.size, std::numeric_limits<double>::infinity());
scan.intensities.assign(geometry.size, 0.0f);
for (std::size_t i = 0; i < values.size(); ++i)
{
scan.ranges[10 + i] = values[i];
scan.intensities[10 + i] = 2000.0f;
}
return matchScan(profile, geometry, scan);
};
const LegDetection rescued = run({1.060, 1.035, 1.010, 1.005, 1.000, 1.004, 1.006, 1.008, 1.010, 1.009}, 2, 0.65);
EXPECT_EQ(rescued.leg_candidates, 1u) << rescued.reason;
EXPECT_NE(rescued.reason.find("1 bright core(s) kept by their plateau"), std::string::npos);
const LegDetection sloped = run({1.000, 1.015, 1.030, 1.045, 1.060}, 2, 0.65);
EXPECT_EQ(sloped.leg_candidates, 0u) << sloped.reason;
EXPECT_NE(sloped.reason.find("1 bright core(s) spread"), std::string::npos);
const LegDetection short_plateau = run({1.000, 1.004, 1.030, 1.055}, 3, 0.4);
EXPECT_EQ(short_plateau.leg_candidates, 0u) << short_plateau.reason;
EXPECT_NE(short_plateau.reason.find("1 bright core(s) spread"), std::string::npos);
}
TEST(LegPatternMatcher, MatchBeforeConfigureSaysSo)
{
LegPatternMatcher matcher;
const auto g = leg_scan_sim::s300Geometry();
const std::vector<double> ranges(g.size, 1.0);
const LegDetection d = matcher.match(g, ranges, {}, s300Limits(), Pose2D());
EXPECT_FALSE(d.valid);
EXPECT_FALSE(d.reason.empty());
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}