Files
dock_pattern_detector/test/v_pattern_matcher_test.cpp
duongtd cea149cae9 Accept a V whose far wing is foreshortened by the viewing angle
A run in simulation matched the pattern 23 times in 15 seconds out of roughly
435 scans - about five percent - and every miss reported the right vertex angle
with the wrong wing length. Measuring it: noise is not the cause (93 to 100
percent at the sensor's own 3 mm sigma) and neither is range (clean detections
out to 5 m). Viewing angle is. Turn the plate and the far wing goes nearly
edge-on to the beam, so few rays land on it and the extracted segment comes out
short. Past thirty degrees the detection rate falls to zero.

Requiring both wings at full length only works when the robot happens to face
the plate squarely, which is not something the approach guarantees. Occlusion
only ever shortens a wing; it cannot lengthen one. So the rule is no longer
symmetric: no wing may be LONGER than wing_length + tolerance, and at least one
must be within tolerance of it. A pallet corner still fails, because a pallet
has both sides long - that gate is untouched, and the test that covers it still
passes.

Confidence scores the length of the long wing rather than the short one. The
short wing is allowed to be short by the rule above, so penalising it again is
charging twice for the same thing, and it created a cliff: candidates cleared
the length gate only to fall at min_confidence. "Too little of it is visible to
trust" is already carried by the support term, which counts the rays on the
thinner wing and degrades smoothly.

With min_wing_points at 5, thirty degrees at 2.5 m goes from 0 to 77 percent,
forty degrees at 1.2 m from 0 to 80, fifty degrees from 0 to 82.

The rejection message also carries the measured vertex angle, both wing lengths
and the apex position now. Without them, "a wing 0.22 m because something is in
the way" and "a wing 0.80 m because that is a pallet" print the same line.
2026-08-26 15:24:31 +07:00

504 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, 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, AWingHiddenByAnObliqueViewIsStillAV)
{
DockProfile p = vProfile();
p.min_wing_points = 5;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Cánh xa bị nhìn nghiêng nên chỉ thấy 0.18 m thay vì 0.30 m. Che khuất chỉ làm NGẮN đi, không
// bao giờ dài ra — nên đây vẫn là chữ V thật. Bắt cả hai cánh đủ 0.30 m nghĩa là chỉ dò được khi
// robot đứng gần chính diện; đo được: nghiêng 40 độ là tỉ lệ trúng về 0.
const double ax = 1.20;
const std::vector<Segment> world = {
{ ax, 0.0, ax - 0.2121, 0.2121 }, // cánh đủ
{ ax, 0.0, ax - 0.1273, -0.1273 }, // cánh chỉ thấy 0.18 m
};
const Detection d = rig.run(world);
ASSERT_TRUE(d.valid) << d.reason;
EXPECT_NEAR(d.apex_x, ax, 0.03);
EXPECT_NEAR(std::max(d.measured_wing_length[0], d.measured_wing_length[1]), 0.30, 0.04);
EXPECT_LT(std::min(d.measured_wing_length[0], d.measured_wing_length[1]), 0.24);
}
TEST(VPatternMatcher, AWingLongerThanTheProfileIsStillRejected)
{
DockProfile p = vProfile();
p.min_wing_points = 5;
Rig rig(p);
ASSERT_TRUE(rig.ok_) << rig.error_;
// Luật bất đối xứng chỉ nới phía NGẮN. Một cạnh dài hơn `wing_length + tol` vẫn phải bị loại —
// đó là thứ giữ nguyên tác dụng chặn góc pallet, và pallet có CẢ HAI cạnh dài.
const double ax = 1.20;
const std::vector<Segment> world = {
{ ax, 0.0, ax - 0.2121, 0.2121 }, // cánh đủ 0.30 m
{ ax, 0.0, ax - 0.4243, -0.4243 }, // cạnh 0.60 m — quá dài
};
const Detection d = rig.run(world);
EXPECT_FALSE(d.valid);
EXPECT_NE(d.reason.find("wing length"), std::string::npos) << d.reason;
}
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();
}