Files
robot_line_extraction/test/line_extraction_test.cpp
duongtd d8f11d2df6 fix: keep a segment whose least-squares refinement did not converge
extract() dropped any run whose weighted fit ran out of iterations. That was
too harsh: a failed refinement loses only the covariance, while the angle,
radius, endpoints and support all remain those of the endpoint fit and stay
usable.

Measured on a V dock plate at 2 m with 34 rays on the plate: both wings split
correctly with 17-18 points each and lengths correct to a few millimetres, yet
one of the two vanished on roughly half of the noise realizations because its
fit hit the 50-iteration cap. Everything downstream then saw one line where
there were two, and the corner disappeared. End-to-end V detection rate was
48%; keeping the segment takes it to 100% across 0-5 mm tape protrusion at
both 2 m and 3 m.

Line now reports hasCovariance(), false when the fit did not converge, and
mergeLines() refuses to merge such a segment - merging decides by comparing
line parameters against their own covariance, so a meaningless covariance must
not be allowed to make that decision.

TheLeastSquaresLoopIsBounded keeps guarding the iteration cap itself; the new
ALineThatFailedToRefineIsStillReturned guards against dropping the segment,
and fails if extract() goes back to discarding it.
2026-08-26 15:55:32 +07:00

489 lines
17 KiB
C++

/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm trích đoạn thẳng 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. hình cơ bản — tường thẳng, chữ V, khe hở;
* 2. ba lỗi của bản gốc — điểm rơi khi tách, tập tia của đoạn đã gộp, vòng lặp không trần;
* 3. đầu vào rác — rỗng, NaN, inf, sai kích thước;
* 4. cache bố cục scan.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <limits>
#include <string>
#include <vector>
#include <robot_line_extraction/line_extractor.h>
namespace
{
using robot_line_extraction::Line;
using robot_line_extraction::LineExtractionParams;
using robot_line_extraction::LineExtractor;
using robot_line_extraction::ScanGeometry;
constexpr double kNaN = std::numeric_limits<double>::quiet_NaN();
constexpr double kInf = std::numeric_limits<double>::infinity();
ScanGeometry geometry(std::size_t rays, double angle_min = -M_PI / 2.0,
double angle_max = M_PI / 2.0)
{
ScanGeometry g;
g.angle_min = angle_min;
g.angle_increment = (angle_max - angle_min) / static_cast<double>(rays - 1);
g.size = rays;
return g;
}
double bearingOf(const ScanGeometry& g, std::size_t i)
{
return g.angle_min + static_cast<double>(i) * g.angle_increment;
}
/**
* @brief Cự ly tới đường thẳng vô hạn dạng cực (@p angle, @p radius) dọc tia @p bearing.
* @return kInf khi tia không bao giờ cắt đường đó.
*/
double rangeToLine(double bearing, double angle, double radius)
{
const double denom = std::cos(bearing - angle);
if (denom <= 1e-9)
{
return kInf;
}
return radius / denom;
}
/// @brief Scan nhìn thẳng vào một BỨC TƯỜNG phẳng cách @p radius, pháp tuyến ở @p angle.
std::vector<double> wallScan(const ScanGeometry& g, double radius, double angle = 0.0)
{
std::vector<double> ranges(g.size);
for (std::size_t i = 0; i < g.size; ++i)
{
ranges[i] = rangeToLine(bearingOf(g, i), angle, radius);
}
return ranges;
}
/**
* @brief Scan nhìn vào một tấm chữ V — đúng hình của tấm dẫn hướng ở trạm sạc.
*
* Hai cánh gặp nhau tại đỉnh trên trục x, cách cảm biến @p apex_x, mỗi cánh nghiêng @p half_angle
* so với trục y. Tia nào không trúng cánh nào thì trả kInf, y như tia bay ra khoảng trống.
*/
std::vector<double> vPlateScan(const ScanGeometry& g, double apex_x, double half_angle,
double wing_length)
{
std::vector<double> ranges(g.size, kInf);
// Hai đầu cánh, đối xứng qua trục x.
const double tip_x = apex_x + wing_length * std::sin(half_angle);
const double tip_y = wing_length * std::cos(half_angle);
for (std::size_t i = 0; i < g.size; ++i)
{
const double bearing = bearingOf(g, i);
const double dx = std::cos(bearing);
const double dy = std::sin(bearing);
// Cắt tia với hai đoạn (apex -> tip) và (apex -> tip đối xứng); lấy điểm gần nhất.
for (const double side : { 1.0, -1.0 })
{
const double ax = apex_x;
const double ay = 0.0;
const double bx = tip_x;
const double by = side * tip_y;
// Giải t*d = a + u*(b-a), u thuộc [0,1], t > 0.
const double ex = bx - ax;
const double ey = by - ay;
const double det = dx * (-ey) - dy * (-ex);
if (std::fabs(det) < 1e-12)
{
continue;
}
const double t = (ax * (-ey) - ay * (-ex)) / det;
const double u = (dx * ay - dy * ax) / det;
if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < ranges[i])
{
ranges[i] = t;
}
}
}
return ranges;
}
LineExtractionParams tightParams()
{
LineExtractionParams p;
p.min_split_dist = 0.02; // [m]
p.max_line_gap = 0.10; // [m]
p.min_line_length = 0.05; // [m]
p.min_line_points = 5;
p.outlier_dist = 0.10; // [m]
p.min_range = 0.05; // [m]
p.max_range = 20.0; // [m]
return p;
}
/// @brief Extractor đã cấu hình, để test không lặp lại bốn dòng giống nhau.
class Rig
{
public:
explicit Rig(const LineExtractionParams& params = tightParams())
{
ok_ = extractor_.configure(params, error_);
}
bool run(const ScanGeometry& g, const std::vector<double>& ranges)
{
return extractor_.extract(g, ranges, lines_, error_);
}
bool ok_ = false;
std::string error_;
LineExtractor extractor_;
std::vector<Line> lines_;
};
// ================================================================================================
// 1. Hình cơ bản
// ================================================================================================
TEST(LineExtractor, FindsOneLineInAFlatWall)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
// Tường dựng ở radius 2.0, pháp tuyến 0. Khớp phải trả lại đúng hai con số đó.
EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-3);
EXPECT_NEAR(rig.lines_[0].getAngle(), 0.0, 1e-3);
EXPECT_GT(rig.lines_[0].numPoints(), 100U);
}
TEST(LineExtractor, RecoversTheAngleOfATiltedWall)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(g, wallScan(g, 1.5, 0.3))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
EXPECT_NEAR(rig.lines_[0].getRadius(), 1.5, 1e-3);
EXPECT_NEAR(rig.lines_[0].getAngle(), 0.3, 1e-3);
}
TEST(LineExtractor, SplitsAVPlateIntoTwoWings)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
// Đúng hình tấm dẫn hướng: đỉnh cách 1.2 m, hai cánh mở 45 độ, mỗi cánh 0.30 m.
const ScanGeometry g = geometry(400, -0.5, 0.5);
ASSERT_TRUE(rig.run(g, vPlateScan(g, 1.2, M_PI / 4.0, 0.30))) << rig.error_;
// Hai cánh phải RA HAI ĐOẠN. Ra một đoạn nghĩa là bước gộp đã nuốt mất góc kẹp, và bộ dò V
// không còn gì để đo.
ASSERT_EQ(rig.lines_.size(), 2U) << "V plate must not collapse into a single segment";
// Góc kẹp giữa hai pháp tuyến = góc mở của tấm. Hai cánh nghiêng +-45 độ so với trục y nên hai
// pháp tuyến cách nhau 90 độ.
const double delta =
std::fabs(robot_line_extraction::piToPi(rig.lines_[0].getAngle() - rig.lines_[1].getAngle()));
EXPECT_NEAR(delta, M_PI / 2.0, 0.10);
for (const Line& line : rig.lines_)
{
EXPECT_NEAR(line.length(), 0.30, 0.05) << "wing length must survive the fit";
}
}
TEST(LineExtractor, SplitsAtAGapEvenWhenBothSidesAreCollinear)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(300, -0.6, 0.6);
std::vector<double> ranges = wallScan(g, 2.0);
// Đục một lỗ giữa tường: hai nửa vẫn thẳng hàng hoàn hảo, nhưng chúng KHÔNG phải một bề mặt
// liền. Chỉ độ tản không phân biệt được ca này — phải là luật khe hở.
for (std::size_t i = 140; i < 170; ++i)
{
ranges[i] = kInf;
}
ASSERT_TRUE(rig.run(g, ranges)) << rig.error_;
EXPECT_EQ(rig.lines_.size(), 2U);
}
// ================================================================================================
// 2. Ba lỗi của bản gốc
// ================================================================================================
TEST(LineExtractor, ASplitLosesNoPoint)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(400, -0.5, 0.5);
ASSERT_TRUE(rig.run(g, vPlateScan(g, 1.2, M_PI / 4.0, 0.30))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 2U);
// Bản gốc cắt bằng `&indices[i_split-1]` và `&indices.back()`, làm rơi một điểm ở MỖI nửa tại
// MỖI lần tách. Đỉnh V thuộc về cả hai cánh, nên tổng số điểm đỡ phải bằng số tia trúng tấm
// CỘNG một (đỉnh được đếm hai lần), không được ít hơn.
const std::vector<double> ranges = vPlateScan(g, 1.2, M_PI / 4.0, 0.30);
std::size_t hits = 0;
for (const double r : ranges)
{
if (std::isfinite(r))
{
++hits;
}
}
const std::size_t support = rig.lines_[0].numPoints() + rig.lines_[1].numPoints();
EXPECT_EQ(support, hits + 1) << "split dropped points: " << hits << " hits but " << support
<< " supporting rays";
}
TEST(LineExtractor, AMergedLineReportsItsRealSupport)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(300, -0.6, 0.6);
std::vector<double> ranges = wallScan(g, 2.0);
// Một vết lồi nhỏ giữa tường, đủ để tách làm đôi nhưng hai nửa vẫn là một mặt phẳng — chính là
// ca mà bước gộp sinh ra để nối lại.
ranges[150] += 0.03;
ASSERT_TRUE(rig.run(g, ranges)) << rig.error_;
ASSERT_FALSE(rig.lines_.empty());
// Bản gốc gọi resize() rồi insert(end()), để lại nửa đầu vector toàn số 0: đoạn đã gộp báo gấp
// đôi số điểm thật, và mọi chỉ số ở nửa đầu đều trỏ về tia 0.
for (const Line& line : rig.lines_)
{
EXPECT_LE(line.numPoints(), g.size) << "merged support exceeds the whole scan";
const std::vector<unsigned int>& indices = line.getIndices();
ASSERT_FALSE(indices.empty());
const std::size_t zeros = static_cast<std::size_t>(std::count(indices.begin(), indices.end(), 0U));
EXPECT_LE(zeros, 1U) << "merged indices are zero-filled";
}
}
TEST(LineExtractor, TheLeastSquaresLoopIsBounded)
{
// Ngưỡng hội tụ đặt cực nhỏ so với độ chính xác của double: bản gốc lặp vô hạn ở đây, tức treo
// luôn control thread. Bản này dừng ở trần lặp và ĐI TIẾP.
LineExtractionParams params = tightParams();
params.least_sq_angle_thresh = 1e-300;
params.least_sq_radius_thresh = 1e-300;
Rig rig(params);
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_;
// Trả về được đã là một nửa: test này chết bằng cách TREO, không phải bằng cách fail.
SUCCEED();
}
TEST(LineExtractor, ALineThatFailedToRefineIsStillReturned)
{
// Không hội tụ KHÔNG phải lý do vứt đoạn. Đây là bản vá cho một hồi quy có thật: bản trước bỏ
// luôn đoạn nào không hội tụ, nên trên tấm chữ V ở 2 m — 34 tia, hai cánh tách đúng, mỗi cánh 17
// điểm, dài đúng tới vài milimet — MỘT trong hai cánh biến mất ở khoảng nửa số lượt, tuỳ nhiễu.
// Bộ dò chữ V nhìn thấy một đường ở chỗ đáng ra có hai, và tỉ lệ dò tụt còn 48%.
//
// Khớp qua hai đầu mút vẫn còn nguyên và vẫn dùng được; thứ duy nhất mất là hiệp phương sai.
LineExtractionParams params = tightParams();
params.least_sq_angle_thresh = 1e-300;
params.least_sq_radius_thresh = 1e-300;
Rig rig(params);
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1u) << "đoạn bị vứt vì tinh chỉnh không hội tụ";
const Line& line = rig.lines_.front();
// Hình học vẫn đúng, dù chỉ là khớp qua hai đầu mút.
EXPECT_NEAR(line.getRadius(), 2.0, 0.02);
EXPECT_NEAR(line.getAngle(), 0.0, 0.02);
// Và nó tự khai là không có hiệp phương sai, để bước gộp không quyết định dựa vào rác.
EXPECT_FALSE(line.hasCovariance());
}
// ================================================================================================
// 3. Đầu vào rác
// ================================================================================================
TEST(LineExtractor, AnEmptySceneYieldsNoLineAndNoError)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180);
// Không có gì trong tầm. Đây là câu trả lời bình thường, không phải lỗi — phòng trống thì trông
// đúng như vậy.
ASSERT_TRUE(rig.run(g, std::vector<double>(g.size, kInf))) << rig.error_;
EXPECT_TRUE(rig.lines_.empty());
}
TEST(LineExtractor, NaNRangesAreDroppedWithoutSpecialCasing)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180);
ASSERT_TRUE(rig.run(g, std::vector<double>(g.size, kNaN))) << rig.error_;
EXPECT_TRUE(rig.lines_.empty());
}
TEST(LineExtractor, AWallStillReadsCorrectlyThroughScatteredNaN)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(300, -0.6, 0.6);
std::vector<double> ranges = wallScan(g, 2.0);
// Tia hụt rải rác, đúng như cảm biến thật gặp bề mặt hấp thụ. NaN trượt cả hai phép so trong
// bộ lọc cự ly nên rơi ra ngay, không cần ca đặc biệt ở đâu khác.
for (std::size_t i = 20; i < g.size; i += 37)
{
ranges[i] = kNaN;
}
ASSERT_TRUE(rig.run(g, ranges)) << rig.error_;
ASSERT_FALSE(rig.lines_.empty());
EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-2);
}
TEST(LineExtractor, RefusesRangesThatDoNotMatchTheGeometry)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180);
// Sai kích thước là lỗi lập trình, không phải cảnh quan — nói ra thay vì đọc ngoài mảng.
EXPECT_FALSE(rig.run(g, std::vector<double>(10, 1.0)));
EXPECT_NE(rig.error_.find("does not match"), std::string::npos);
}
TEST(LineExtractor, RefusesAGeometryItCannotUse)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
ScanGeometry zero_step = geometry(180);
zero_step.angle_increment = 0.0; // mọi tia chung một hướng, scan sụp thành một điểm
EXPECT_FALSE(rig.run(zero_step, std::vector<double>(180, 1.0)));
ScanGeometry tiny;
tiny.angle_min = 0.0;
tiny.angle_increment = 0.01;
tiny.size = 1;
EXPECT_FALSE(rig.run(tiny, std::vector<double>(1, 1.0)));
}
TEST(LineExtractor, RefusesParametersThatCanNeverFit)
{
LineExtractor extractor;
std::string error;
LineExtractionParams zero_var = tightParams();
zero_var.range_var = 0.0;
// Phương sai 0 = tin tuyệt đối một phép đo; số gia bình phương tối thiểu ra vô cực ngay vòng đầu.
EXPECT_FALSE(extractor.configure(zero_var, error));
EXPECT_NE(error.find("range_var"), std::string::npos);
LineExtractionParams zero_split = tightParams();
zero_split.min_split_dist = 0.0;
// Tách ở mọi điểm thì không đoạn nào sống sót thành đường.
EXPECT_FALSE(extractor.configure(zero_split, error));
EXPECT_NE(error.find("min_split_dist"), std::string::npos);
LineExtractionParams two_points = tightParams();
two_points.min_line_points = 2;
// Hai điểm xác định đường chính xác nên hiệp phương sai của chúng vô nghĩa, mà bước gộp lại
// quyết định BẰNG hiệp phương sai.
EXPECT_FALSE(extractor.configure(two_points, error));
EXPECT_NE(error.find("min_line_points"), std::string::npos);
LineExtractionParams range_swap = tightParams();
range_swap.max_range = range_swap.min_range;
EXPECT_FALSE(extractor.configure(range_swap, error));
// Bộ tham số hỏng bị từ chối thì bộ cũ phải còn nguyên.
LineExtractionParams good = tightParams();
ASSERT_TRUE(extractor.configure(good, error)) << error;
EXPECT_DOUBLE_EQ(extractor.params().range_var, good.range_var);
}
// ================================================================================================
// 4. Cache bố cục scan
// ================================================================================================
TEST(LineExtractor, TheSameGeometryTwiceGivesTheSameAnswer)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
const double first_radius = rig.lines_[0].getRadius();
// Lần hai dùng lại bảng bearing đã cache. Kết quả phải khớp từng bit — lệch nghĩa là cache mang
// trạng thái của lần chạy trước sang.
ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
EXPECT_DOUBLE_EQ(rig.lines_[0].getRadius(), first_radius);
}
TEST(LineExtractor, ChangingTheGeometryRebuildsTheBearings)
{
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry coarse = geometry(180, -0.6, 0.6);
ASSERT_TRUE(rig.run(coarse, wallScan(coarse, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
// Bố cục khác hẳn. Giữ bảng cũ là mọi tia bị gán sai hướng, và tường 2 m ra một đường bịa.
const ScanGeometry fine = geometry(400, -1.0, 1.0);
ASSERT_TRUE(rig.run(fine, wallScan(fine, 2.0))) << rig.error_;
ASSERT_EQ(rig.lines_.size(), 1U);
EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-3);
EXPECT_NEAR(rig.lines_[0].getAngle(), 0.0, 1e-3);
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}