Files
dock_pattern_detector/test/v_pattern_matcher_test.cpp
duongtd 000374791b Separate the measured calibration from the derived offset
offset_x/y/yaw carried two different things at once. Part of it is geometry
that can be worked out on paper - half the robot, the footprint padding, how
far the wings project toward the robot, the clearance. The rest is whatever
the real station turns out to need: a laser mounted slightly off, odometry
bias, a systematic lean in the detection.

Folded into one number, changing the footprint silently discards the field
correction that was tuned into it, and nobody can look at the value later and
say which half is which. The first time someone re-derives the geometry, the
calibration is gone and nothing says so.

calib_x/y/yaw are added on top, in the same frame, defaulting to zero. Dock,
measure how far base_link ended up from where it should have, subtract it
here. The geometry stays derivable and the correction stays visible.

They are bounded to 0.30 m and 0.20 rad. Field calibration is centimetres and
degrees; needing half a metre means offset_x is wrong, and taping over that
with a calibration term hides the cause until the next footprint change makes
it worse.
2026-08-26 15:07:24 +07:00

503 lines
16 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm khớp chữ V bằng scan TỔNG HỢP — dựng hình trước, sinh tia sau, nên biết trước đáp án.
*
* Bốn nhóm:
* 1. dò đúng — đỉnh, hướng, offset, hình nghiêng;
* 2. TỪ CHỐI — đây mới là phần quan trọng: pallet đánh lừa, tường cắt nhau ở xa, hình méo;
* 3. cổng tìm kiếm — prior và quạt;
* 4. nhiều ứng viên, và config hỏng.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include <robot_line_extraction/line_extractor.h>
#include <dock_pattern_detector/v_pattern_matcher.h>
namespace
{
using dock_pattern_detector::Detection;
using dock_pattern_detector::DockProfile;
using dock_pattern_detector::PatternType;
using dock_pattern_detector::VPatternMatcher;
using robot_line_extraction::Line;
using robot_line_extraction::LineExtractionParams;
using robot_line_extraction::LineExtractor;
using robot_line_extraction::ScanGeometry;
constexpr double kInf = std::numeric_limits<double>::infinity();
struct Segment
{
double ax, ay, bx, by; // [m]
};
ScanGeometry geometry(std::size_t rays = 600, double angle_min = -0.8, double angle_max = 0.8)
{
ScanGeometry g;
g.angle_min = angle_min;
g.angle_increment = (angle_max - angle_min) / static_cast<double>(rays - 1);
g.size = rays;
return g;
}
/// @brief Chiếu tia lên một tập đoạn thẳng, lấy điểm trúng gần nhất. Không trúng gì thì kInf.
std::vector<double> rayCast(const ScanGeometry& g, const std::vector<Segment>& world)
{
std::vector<double> ranges(g.size, kInf);
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);
for (const Segment& s : world)
{
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 < ranges[i])
{
ranges[i] = t;
}
}
}
return ranges;
}
/**
* @brief Hai cánh của một tấm chữ V.
*
* @param apex_x [m] đỉnh trên trục x
* @param half_angle [rad] độ nghiêng mỗi cánh so với trục y
* @param wing [m] chiều dài một cánh
* @param yaw [rad] xoay cả tấm quanh đỉnh
*
* Góc TRONG tại đỉnh = pi - 2*half_angle. `half = pi/4` cho tấm mở 90 độ.
*/
std::vector<Segment> vPlate(double apex_x, double half_angle, double wing, double yaw = 0.0)
{
const double c = std::cos(yaw);
const double s = std::sin(yaw);
const auto rot = [&](double x, double y, double& ox, double& oy) {
ox = apex_x + c * (x - apex_x) - s * y;
oy = s * (x - apex_x) + c * y;
};
const double tip_x = apex_x + wing * std::sin(half_angle);
const double tip_y = wing * std::cos(half_angle);
Segment w1;
Segment w2;
rot(apex_x, 0.0, w1.ax, w1.ay);
rot(tip_x, tip_y, w1.bx, w1.by);
rot(apex_x, 0.0, w2.ax, w2.ay);
rot(tip_x, -tip_y, w2.bx, w2.by);
return { w1, w2 };
}
DockProfile vProfile()
{
DockProfile p;
p.pattern = PatternType::kV;
p.vertex_angle = M_PI / 2.0; // [rad] tấm mở 90 độ
p.wing_length = 0.30; // [m]
p.angle_tolerance = 0.20; // [rad]
p.length_tolerance = 0.06; // [m]
p.vertex_gap = 0.05; // [m]
p.min_wing_points = 5;
p.min_confidence = 0.3;
return p;
}
LineExtractionParams extractorParams()
{
LineExtractionParams p;
p.min_split_dist = 0.02; // [m]
p.max_line_gap = 0.08; // [m]
p.min_line_length = 0.05; // [m]
p.min_line_points = 5;
p.outlier_dist = 0.10; // [m]
return p;
}
/// @brief Dựng thế giới, chiếu tia, trích đoạn, khớp — đúng chuỗi mà handler sẽ chạy.
class Rig
{
public:
explicit Rig(const DockProfile& profile = vProfile())
{
std::string error;
ok_ = extractor_.configure(extractorParams(), error) && matcher_.configure(profile, error);
error_ = error;
}
Detection run(const std::vector<Segment>& world, const ScanGeometry& g = geometry())
{
std::string error;
if (!extractor_.extract(g, rayCast(g, world), lines_, error))
{
Detection d;
d.reason = error;
return d;
}
return matcher_.match(lines_);
}
bool ok_ = false;
std::string error_;
LineExtractor extractor_;
VPatternMatcher matcher_;
std::vector<Line> lines_;
};
// ================================================================================================
// 1. Dò đúng
// ================================================================================================
TEST(VPatternMatcher, FindsTheApexOfAPlateInFront)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, 1.20, 0.02);
EXPECT_NEAR(d.apex_y, 0.00, 0.02);
EXPECT_NEAR(d.measured_vertex_angle, M_PI / 2.0, 0.10);
EXPECT_GT(d.confidence, 0.5);
}
TEST(VPatternMatcher, TheYawPointsBackAtTheSensorNotIntoThePlate)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
// Tấm ở phía +x, cảm biến ở gốc, nên phân giác phải chỉ về -x tức yaw ~ pi. Lệch 180 độ ở đây là
// robot lùi vào tấm sạc thay vì tiến vào — chính vì thế dấu được chọn theo vị trí cảm biến chứ
// không theo thứ tự hai cánh.
EXPECT_NEAR(std::fabs(d.yaw), M_PI, 0.10);
}
TEST(VPatternMatcher, TheOffsetMovesTheGoalOutTowardTheRobot)
{
DockProfile p = vProfile();
p.offset_x = 0.60; // [m] lùi ra trước mặt sạc
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
// Đỉnh ở x=1.20; offset dọc pháp tuyến hướng RA phía robot nên goal phải ở x ~ 0.60, GẦN hơn.
EXPECT_NEAR(d.apex_x, 1.20, 0.02);
EXPECT_NEAR(d.x, 0.60, 0.03);
EXPECT_NEAR(d.y, 0.00, 0.03);
}
TEST(VPatternMatcher, CalibrationShiftsTheGoalOnTopOfTheOffset)
{
DockProfile p = vProfile();
p.offset_x = 0.60; // [m] phần HÌNH HỌC, suy ra bằng công thức
p.calib_x = -0.03; // [m] phần ĐO ĐƯỢC: lần dock thật dừng xa 3 cm
p.calib_y = 0.02; // [m]
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
ASSERT_TRUE(d.valid) << d.reason;
// Đỉnh ở x=1.20; hiệu chỉnh cộng thẳng vào offset, cùng hệ quy chiếu của hình.
// Hình quay 180 độ so với trục x của cảm biến nên +x của hình là -x của cảm biến.
EXPECT_NEAR(d.apex_x, 1.20, 0.02);
EXPECT_NEAR(d.x, 1.20 - (0.60 - 0.03), 0.03);
EXPECT_NEAR(d.y, -0.02, 0.03);
}
TEST(VPatternMatcher, RefusesACalibrationBigEnoughToBeHidingAGeometryError)
{
VPatternMatcher matcher;
std::string error;
DockProfile huge = vProfile();
huge.calib_x = 0.5; // [m]
// Hiệu chỉnh hiện trường là centimet. Nửa mét nghĩa là `offset_x` sai, và dán băng dính lên nó
// bằng calib là giấu mất nguyên nhân — lần đổi footprint sau sẽ không ai hiểu con số này từ đâu.
EXPECT_FALSE(matcher.configure(huge, error));
EXPECT_NE(error.find("calib_x"), std::string::npos) << error;
DockProfile spin = vProfile();
spin.calib_yaw = 0.6; // [rad] ~34 do
EXPECT_FALSE(matcher.configure(spin, error));
EXPECT_NE(error.find("calib_yaw"), std::string::npos) << error;
// Hiệu chỉnh thật thì phải nhận.
DockProfile ok = vProfile();
ok.calib_x = -0.03;
ok.calib_yaw = 0.02;
EXPECT_TRUE(matcher.configure(ok, error)) << error;
}
TEST(VPatternMatcher, ATiltedPlateIsStillFoundAndItsYawFollows)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30, 0.25));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.measured_vertex_angle, M_PI / 2.0, 0.12);
// Tấm xoay 0.25 rad thì phân giác hướng ra cũng xoay đúng ngần ấy.
const double expected = std::atan2(std::sin(M_PI + 0.25), std::cos(M_PI + 0.25));
EXPECT_NEAR(std::atan2(std::sin(d.yaw - expected), std::cos(d.yaw - expected)), 0.0, 0.12);
}
TEST(VPatternMatcher, AWiderPlateIsFoundWhenTheProfileSaysSo)
{
DockProfile p = vProfile();
p.vertex_angle = 2.0944; // [rad] 120 độ
p.wing_length = 0.25; // [m]
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Góc trong = pi - 2*half; muốn 120 độ thì half = 30 độ.
const Detection d = rig.run(vPlate(1.10, M_PI / 6.0, 0.25));
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.measured_vertex_angle, 2.0944, 0.12);
}
// ================================================================================================
// 2. Từ chối — phần quan trọng nhất
// ================================================================================================
TEST(VPatternMatcher, APalletCornerIsNotADock)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Hai mặt vuông góc của một pallet: ĐÚNG góc 90 độ, nhưng cạnh dài 0.8 m chứ không phải 0.30 m.
// Đây là dương tính giả điển hình trong kho, và chỉ cổng chiều dài chặn được nó.
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.80));
ASSERT_EQ(rig.lines_.size(), 2U) << "cần đúng 2 đoạn, nếu không thì cổng chiều dài chưa bị thử";
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("wing length"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, TwoWallsThatCrossFarFromTheirEndsAreNotAV)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Hai bức tường vuông góc nhưng KHÔNG chạm nhau — giao điểm của hai ĐƯỜNG nằm ngoài cả hai đoạn.
// Chỉ dựa vào góc thì ca này lọt; cổng `vertex_gap` là thứ chặn nó.
const std::vector<Segment> world = {
{ 1.00, 0.35, 1.30, 0.65 },
{ 1.00, -0.35, 1.30, -0.65 },
};
const Detection d = rig.run(world);
ASSERT_EQ(rig.lines_.size(), 2U) << "cần đúng 2 đoạn, nếu không thì matcher chưa hề bị thử";
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("do not end at the crossing"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, AFlatWallHasNoVertexAtAll)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run({ { 1.50, -1.00, 1.50, 1.00 } });
EXPECT_FALSE(d.valid);
EXPECT_FALSE(d.reason.empty());
}
TEST(VPatternMatcher, APlateWithTheWrongOpeningIsRejected)
{
Rig rig; // profile chờ 90 độ
ASSERT_TRUE(rig.ok_) << rig.error_;
// Tấm mở 140 độ: đúng chiều dài cánh, đúng chỗ, chỉ sai góc.
const Detection d = rig.run(vPlate(1.20, M_PI / 9.0, 0.30));
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("angle"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, HalfAPlateIsNotEnough)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Một cánh bị vật khác che hoàn toàn. Còn một đoạn thì không có đỉnh nào để đo.
std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
world.pop_back();
const Detection d = rig.run(world);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("2 line segments"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, AnEmptySceneSaysSoInsteadOfGuessing)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run({});
EXPECT_FALSE(d.valid);
EXPECT_EQ(d.candidate_count, 0U);
EXPECT_FALSE(d.reason.empty());
}
// ================================================================================================
// 3. Cổng tìm kiếm
// ================================================================================================
TEST(VPatternMatcher, ThePriorGateRejectsATrueVInTheWrongPlace)
{
DockProfile p = vProfile();
p.has_prior = true;
p.prior_x = 1.20; // [m] trạm kỳ vọng ở đây
p.prior_y = 0.00; // [m]
p.search_radius = 0.30; // [m]
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Một tấm chữ V hoàn hảo, nhưng ở chỗ khác — trong kho thì đó là trạm của người khác, hoặc một
// vật thể trùng hình. Không có cổng này thì robot dock vào nhầm chỗ, rất tự tin.
const Detection d = rig.run(vPlate(2.20, M_PI / 4.0, 0.30));
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("search gate"), std::string::npos) << d.reason;
}
TEST(VPatternMatcher, ThePriorGateAcceptsTheOneItExpects)
{
DockProfile p = vProfile();
p.has_prior = true;
p.prior_x = 1.20;
p.prior_y = 0.00;
p.search_radius = 0.30;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
const Detection d = rig.run(vPlate(1.20, M_PI / 4.0, 0.30));
EXPECT_TRUE(d.valid) << d.reason;
}
TEST(VPatternMatcher, TheSectorGateRejectsWhatIsNotInFront)
{
DockProfile p = vProfile();
p.search_fov = 0.15; // [rad] quạt hẹp quanh trục x
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Tấm lệch sang bên: bearing của đỉnh ~0.46 rad, ngoài quạt.
const std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
std::vector<Segment> shifted;
for (Segment s : world)
{
s.ay += 0.60;
s.by += 0.60;
shifted.push_back(s);
}
const Detection d = rig.run(shifted);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("search gate"), std::string::npos) << d.reason;
}
// ================================================================================================
// 4. Nhiều ứng viên và config hỏng
// ================================================================================================
TEST(VPatternMatcher, TwoPlatesInViewAreBothCountedAndTheBetterOneWins)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
std::vector<Segment> world = vPlate(1.20, M_PI / 4.0, 0.30);
for (Segment s : vPlate(1.60, M_PI / 4.0, 0.30))
{
s.ay += 0.90;
s.by += 0.90;
world.push_back(s);
}
const Detection d = rig.run(world);
ASSERT_TRUE(d.valid) << d.reason;
// Đếm được nhiều hơn một là tín hiệu cho tầng trên: trong tầm có nhiều hình giống nhau, và cổng
// prior mới là thứ quyết định lấy cái nào.
EXPECT_GE(d.candidate_count, 2U);
}
TEST(VPatternMatcher, RefusesAProfileThatCanNeverMatch)
{
VPatternMatcher matcher;
std::string error;
DockProfile flat = vProfile();
flat.vertex_angle = M_PI; // hai cánh thành một đường thẳng
EXPECT_FALSE(matcher.configure(flat, error));
EXPECT_NE(error.find("vertex_angle"), std::string::npos);
DockProfile loose_gap = vProfile();
loose_gap.vertex_gap = loose_gap.wing_length;
// Khe đỉnh rộng bằng cả cánh thì hai bức tường cắt nhau ở đâu cũng lọt — mất đúng cái cổng phân
// biệt chữ V thật với giao điểm ngẫu nhiên.
EXPECT_FALSE(matcher.configure(loose_gap, error));
EXPECT_NE(error.find("vertex_gap"), std::string::npos);
DockProfile loose_len = vProfile();
loose_len.length_tolerance = loose_len.wing_length;
EXPECT_FALSE(matcher.configure(loose_len, error));
DockProfile not_ready = vProfile();
not_ready.pattern = PatternType::kCylinder;
// Nói thẳng thay vì nhận config rồi không bao giờ dò ra gì.
EXPECT_FALSE(matcher.configure(not_ready, error));
EXPECT_NE(error.find("not implemented"), std::string::npos);
// Profile hỏng bị từ chối thì bộ cũ phải còn nguyên.
DockProfile good = vProfile();
ASSERT_TRUE(matcher.configure(good, error)) << error;
EXPECT_DOUBLE_EQ(matcher.profile().wing_length, good.wing_length);
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}