feat(leg_pattern): add LegPatternMatcher for 4-leg trolleys

Finds a 4-leg trolley in a raw LaserScan without line extraction:
shadow filter, leg clusters in ray order with free/occluded/attached edges,
pair hypotheses from cart_opening/cart_depth/diagonal, then a Gauss-Newton
pose fit over every leg point with an along-ray residual, Huber weights and
backtracking. Gates: pair spacing after the fit, see-through leg positions,
optional empty interior, entry side (entry tape / prior yaw / facing the
sensor), optional prior, confidence, and ambiguity between two carts.

LegProfile validates every key at load. Two gtests (7 + 23) run on a
synthetic ray-cast scan (test/leg_scan_sim.h). Used by trolley_detection_action.
This commit is contained in:
2026-10-28 13:43:56 +07:00
parent edc6b30431
commit c568e90c53
11 changed files with 3324 additions and 0 deletions

View File

@@ -0,0 +1,476 @@
/*********************************************************************
*
* 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`.
*
* Năm 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. config hỏng.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <string>
#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());
}
// ================================================================================================
// 1. Dò đúng
// ================================================================================================
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, 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, 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. 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(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();
}

230
test/leg_pose_fit_test.cpp Normal file
View File

@@ -0,0 +1,230 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm phép khớp tư thế xe trên mọi điểm chân — điểm sinh bằng ray-cast lên mô hình đã biết, nên
* đáp án biết trước.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <vector>
#include <dock_pattern_detector/leg_pose_fit.h>
#include "leg_scan_sim.h"
namespace
{
using dock_pattern_detector::FitNoise;
using dock_pattern_detector::FitPoint;
using dock_pattern_detector::LegModel;
using dock_pattern_detector::LegProfile;
using dock_pattern_detector::LegShape;
using dock_pattern_detector::Pose2D;
using dock_pattern_detector::PoseFitResult;
constexpr double kDeg = M_PI / 180.0;
/// @brief Xe `tci_trolley` (mô hình sim): cạnh vào 0.517 m, dọc 0.720 m, chân hộp 30 mm.
LegProfile tciTrolley()
{
LegProfile p;
p.cart_opening = 0.517;
p.cart_depth = 0.720;
p.leg_shape = LegShape::kBox;
p.leg_width = 0.030;
return p;
}
/// @brief Điểm của từng chân lấy từ ray-cast, gán đúng góc theo id vật trúng.
std::vector<FitPoint> pointsOf(const LegProfile& p, double cx, double cy, double axis,
double sigma = 0.0)
{
leg_scan_sim::World world;
const std::vector<int> ids = leg_scan_sim::addCart(world, p, cx, cy, axis);
const auto g = leg_scan_sim::s300Geometry();
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g, sigma);
std::vector<FitPoint> points;
for (std::size_t i = 0; i < g.size; ++i)
{
for (int k = 0; k < 4; ++k)
{
if (scan.hit[i] >= 0 && scan.hit[i] == ids[k])
{
const double b = g.angle_min + static_cast<double>(i) * g.angle_increment;
FitPoint fp;
fp.x = scan.ranges[i] * std::cos(b);
fp.y = scan.ranges[i] * std::sin(b);
fp.corner = k;
points.push_back(fp);
}
}
}
return points;
}
FitNoise s300Noise()
{
FitNoise n;
n.range_sigma = 0.01;
n.angle_increment = leg_scan_sim::s300Geometry().angle_increment;
return n;
}
double yawError(double a, double b)
{
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
}
TEST(LegPoseFit, ConvergesOnNoiseFreeBoxLegs)
{
const LegProfile p = tciTrolley();
const double cx = 1.26, cy = 0.05, axis = M_PI + 10.0 * kDeg;
const std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
ASSERT_GE(pts.size(), 12u);
Pose2D init;
init.x = cx + 0.05; // lệch 5 cm, 5°
init.y = cy - 0.05;
init.yaw = axis + 5.0 * kDeg;
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
ASSERT_TRUE(fit.valid);
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
EXPECT_NEAR(fit.pose.y, cy, 1e-3);
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.05 * kDeg);
EXPECT_LT(fit.rms, 1e-3);
}
TEST(LegPoseFit, ConvergesOnRoundLegs)
{
LegProfile p = tciTrolley();
p.leg_shape = LegShape::kRound;
p.leg_width = 0.040;
const double cx = 1.30, cy = -0.10, axis = M_PI - 8.0 * kDeg;
const std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
Pose2D init;
init.x = cx - 0.04;
init.y = cy + 0.04;
init.yaw = axis - 4.0 * kDeg;
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
ASSERT_TRUE(fit.valid);
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
EXPECT_NEAR(fit.pose.y, cy, 1e-3);
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.05 * kDeg);
}
TEST(LegPoseFit, HuberKeepsOneStrayPointFromPullingThePose)
{
const LegProfile p = tciTrolley();
const double cx = 1.26, cy = 0.0, axis = M_PI;
std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
ASSERT_FALSE(pts.empty());
// Một điểm lai lạc 10 cm sau chân trước-trái.
FitPoint stray = pts.front();
stray.x += 0.10;
pts.push_back(stray);
Pose2D init;
init.x = cx + 0.02;
init.y = cy;
init.yaw = axis;
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
ASSERT_TRUE(fit.valid);
// Điểm lạc nằm trên tia của chính nó, nên kéo xe DỌC tia đó (−15° so với trục x). Trục dọc (x) có
// mọi mặt trước giữ nên không xê dịch; trục ngang chỉ có điểm mép giữ nên nhích ~2.6 mm — cùng cỡ
// khi không có Huber. Trong matcher, điểm lạc như vậy bị bước "cắt điểm xa" bỏ trước khi khớp.
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
EXPECT_NEAR(fit.pose.y, cy, 3e-3);
}
TEST(LegPoseFit, TwoLegsAreEnoughWhenTheModelIsKnown)
{
const LegProfile p = tciTrolley();
const double cx = 1.26, cy = 0.0, axis = M_PI + 5.0 * kDeg;
std::vector<FitPoint> all = pointsOf(p, cx, cy, axis);
std::vector<FitPoint> pts;
for (const FitPoint& fp : all)
{
if (fp.corner == dock_pattern_detector::kEntryLeft ||
fp.corner == dock_pattern_detector::kEntryRight)
{
pts.push_back(fp);
}
}
ASSERT_GE(pts.size(), 6u);
Pose2D init;
init.x = cx + 0.02;
init.y = cy + 0.02;
init.yaw = axis + 2.0 * kDeg;
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
ASSERT_TRUE(fit.valid);
EXPECT_NEAR(fit.pose.x, cx, 2e-3);
EXPECT_NEAR(fit.pose.y, cy, 2e-3);
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.2 * kDeg);
}
TEST(LegPoseFit, IsDeterministic)
{
const LegProfile p = tciTrolley();
const std::vector<FitPoint> pts = pointsOf(p, 1.2, 0.03, M_PI + 0.1, 0.01);
Pose2D init;
init.x = 1.22;
init.y = 0.0;
init.yaw = M_PI + 0.08;
const PoseFitResult a = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
const PoseFitResult b = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
EXPECT_EQ(a.pose.x, b.pose.x);
EXPECT_EQ(a.pose.y, b.pose.y);
EXPECT_EQ(a.pose.yaw, b.pose.yaw);
EXPECT_EQ(a.iterations, b.iterations);
}
TEST(LegPoseFit, ProcrustesRecoversAnExactPose)
{
const LegModel m = LegModel::fromProfile(tciTrolley());
Pose2D truth;
truth.x = 1.5;
truth.y = -0.3;
truth.yaw = 2.7;
std::vector<std::array<double, 2>> model_pts, scan_pts;
for (int k = 0; k < 3; ++k)
{
const std::array<double, 2> c = m.corner(k);
model_pts.push_back(c);
scan_pts.push_back({ truth.x + std::cos(truth.yaw) * c[0] - std::sin(truth.yaw) * c[1],
truth.y + std::sin(truth.yaw) * c[0] + std::cos(truth.yaw) * c[1] });
}
Pose2D out;
ASSERT_TRUE(dock_pattern_detector::procrustes2D(model_pts, scan_pts, out));
EXPECT_NEAR(out.x, truth.x, 1e-9);
EXPECT_NEAR(out.y, truth.y, 1e-9);
EXPECT_NEAR(yawError(out.yaw, truth.yaw), 0.0, 1e-9);
}
TEST(LegPoseFit, BoxSignedDistanceIsZeroOnTheFaceAndSignedInside)
{
const LegModel m = LegModel::fromProfile(tciTrolley());
const std::array<double, 2> c = m.corner(dock_pattern_detector::kEntryLeft);
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0] + 0.015, c[1]), 0.0, 1e-12);
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0], c[1]), -0.015, 1e-12);
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0] + 0.115, c[1]), 0.10, 1e-12);
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

216
test/leg_scan_sim.h Normal file
View File

@@ -0,0 +1,216 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Dựng scan TỔNG HỢP cho test dò xe hàng: đặt chân hộp/tròn, tường, vật cản vào một thế giới 2D,
* chiếu tia từ gốc, biết trước đáp án. Chỉ dùng trong test.
*
* Author: DuongTD
*********************************************************************/
#ifndef DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_
#define DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_
#include <cmath>
#include <cstddef>
#include <limits>
#include <random>
#include <vector>
#include <robot_line_extraction/types.h>
#include <dock_pattern_detector/leg_profile.h>
namespace leg_scan_sim
{
struct Segment
{
double ax, ay, bx, by; // [m]
int shape; // vật mà đoạn thuộc về
};
struct Circle
{
double cx, cy, r; // [m]
int shape;
};
/// @brief Thế giới 2D. Mỗi vật có một id; vật có id trong `bright` trả cường độ cao.
struct World
{
std::vector<Segment> segments;
std::vector<Circle> circles;
std::vector<bool> bright; // theo id vật
int next_id = 0;
int newShape(bool is_bright = false)
{
bright.push_back(is_bright);
return next_id++;
}
/// @brief Hộp tâm (cx, cy), cạnh `size_x` dọc trục x của nó, `size_y` dọc trục y, xoay `yaw`.
int addBox(double cx, double cy, double size_x, double size_y, double yaw, bool is_bright = false)
{
const int id = newShape(is_bright);
const double c = std::cos(yaw);
const double s = std::sin(yaw);
const double hx = size_x / 2.0;
const double hy = size_y / 2.0;
const double lx[4] = { hx, -hx, -hx, hx };
const double ly[4] = { hy, hy, -hy, -hy };
double px[4], py[4];
for (int i = 0; i < 4; ++i)
{
px[i] = cx + c * lx[i] - s * ly[i];
py[i] = cy + s * lx[i] + c * ly[i];
}
for (int i = 0; i < 4; ++i)
{
const int j = (i + 1) % 4;
segments.push_back({ px[i], py[i], px[j], py[j], id });
}
return id;
}
int addCircle(double cx, double cy, double r, bool is_bright = false)
{
const int id = newShape(is_bright);
circles.push_back({ cx, cy, r, id });
return id;
}
int addWall(double ax, double ay, double bx, double by)
{
const int id = newShape(false);
segments.push_back({ ax, ay, bx, by, id });
return id;
}
};
/**
* @brief Đặt 4 chân của xe: tâm (cx, cy), trục x của xe (pháp tuyến cạnh vào hướng ra ngoài) theo
* @p axis. Bỏ chân nào thì đặt `skip[k] = true` (thứ tự góc như `LegCorner`).
* @return id của 4 chân (−1 nếu bỏ).
*/
inline std::vector<int> addCart(World& w, const dock_pattern_detector::LegProfile& p, double cx,
double cy, double axis, const bool skip[4] = nullptr,
const bool taped[4] = nullptr)
{
const double hx = p.cart_depth / 2.0;
const double hy = p.cart_opening / 2.0;
const double lx[4] = { hx, hx, -hx, -hx };
const double ly[4] = { hy, -hy, hy, -hy };
const double c = std::cos(axis);
const double s = std::sin(axis);
std::vector<int> ids(4, -1);
for (int k = 0; k < 4; ++k)
{
if (skip != nullptr && skip[k])
{
continue;
}
const double x = cx + c * lx[k] - s * ly[k];
const double y = cy + s * lx[k] + c * ly[k];
const bool is_bright = taped != nullptr && taped[k];
if (p.leg_shape == dock_pattern_detector::LegShape::kRound)
{
ids[k] = w.addCircle(x, y, p.leg_width / 2.0, is_bright);
}
else
{
ids[k] = w.addBox(x, y, p.effectiveLegDepth(), p.leg_width, axis + p.leg_yaw_offset,
is_bright);
}
}
return ids;
}
/// @brief Hình học SICK S300 sim của hook_150: 541 tia trên ±1.588 rad.
inline robot_line_extraction::ScanGeometry s300Geometry()
{
robot_line_extraction::ScanGeometry g;
g.angle_min = -1.588249619;
g.size = 541;
g.angle_increment = (2.0 * 1.588249619) / static_cast<double>(g.size - 1);
return g;
}
struct Scan
{
std::vector<double> ranges;
std::vector<float> intensities;
std::vector<int> hit; // id vật mà tia trúng, −1 nếu không trúng
};
/**
* @brief Chiếu tia từ gốc. @p sigma > 0 thì cộng nhiễu Gauss vào range, hạt giống @p seed cố định
* — test vẫn tất định.
*/
inline Scan rayCast(const World& w, const robot_line_extraction::ScanGeometry& g, double sigma = 0.0,
unsigned seed = 1)
{
constexpr double kInf = std::numeric_limits<double>::infinity();
Scan scan;
scan.ranges.assign(g.size, kInf);
scan.intensities.assign(g.size, 0.0f);
scan.hit.assign(g.size, -1);
std::mt19937 rng(seed);
std::normal_distribution<double> noise(0.0, sigma > 0.0 ? sigma : 1.0);
for (std::size_t i = 0; i < g.size; ++i)
{
const double bearing = g.angle_min + static_cast<double>(i) * g.angle_increment;
const double dx = std::cos(bearing);
const double dy = std::sin(bearing);
double best = kInf;
int best_id = -1;
for (const Segment& s : w.segments)
{
const double ex = s.bx - s.ax;
const double ey = s.by - s.ay;
const double det = dx * (-ey) - dy * (-ex);
if (std::fabs(det) < 1e-12)
{
continue;
}
const double t = (s.ax * (-ey) - s.ay * (-ex)) / det;
const double u = (dx * s.ay - dy * s.ax) / det;
if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < best)
{
best = t;
best_id = s.shape;
}
}
for (const Circle& c : w.circles)
{
// |t·d − c|² = r² → t² − 2t(d·c) + |c|² − r² = 0
const double b = dx * c.cx + dy * c.cy;
const double disc = b * b - (c.cx * c.cx + c.cy * c.cy - c.r * c.r);
if (disc < 0.0)
{
continue;
}
const double t = b - std::sqrt(disc);
if (t > 0.0 && t < best)
{
best = t;
best_id = c.shape;
}
}
if (best_id >= 0)
{
const double n = sigma > 0.0 ? noise(rng) : 0.0;
scan.ranges[i] = best + n;
scan.hit[i] = best_id;
scan.intensities[i] = w.bright[best_id] ? 2000.0f : 100.0f;
}
}
return scan;
}
} // namespace leg_scan_sim
#endif // DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_