Files
robot_line_extraction/test/line_extraction_test.cpp
duongtd 8df353ded6 fix: a merged segment lost the scan it was built from, so pointAt read past the end
The constructor mergeLines uses took only the fitted parameters and the ray
indices, leaving c_data_ and r_data_ default-constructed. pointAt indexes
r_data_.xs directly, so asking a merged segment where one of its own rays is
read past the end of an empty vector.

Two callers already do exactly that. The reflective-tape check walks the ray
span of a wing and reads each point; the arc matcher gathers the points of
adjacent segments to fit a circle to them. The arc matcher is how it surfaced -
it segfaulted, and AddressSanitizer put it on line.cpp:58.

It stayed hidden because mergeLines almost never fires with the default
parameters: a gap wide enough to split at is already wider than max_line_gap,
which is the gate merging has to pass. That is the merge gate working as
intended, and it is also why this could not be reached from a synthesized
scene - a scene-based test here would guard nothing, so the regression test
builds a merged Line directly instead.

The constructor now takes the scan data, like the other one. A merged segment
is still built from the same scan, so there was never a reason for it to lose
it, and a consumer cannot tell a merged segment from a fresh one - the
invariant has to be that every segment answers for every ray it supports.

pointAt also bounds-checks now and returns NaN for a ray it does not carry.
That is a second line of defence, not the fix: every caller already has to
reject non-finite points because a real scan contains them, so a future
constructor that forgets the data degrades instead of reading out of bounds.
2026-08-26 20:09:06 +07:00

613 lines
23 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(Line, TotalLeastSquaresIsAnchoredByEveryPointNotJustTheTwoEnds)
{
// Mầm của phép tinh chỉnh quyết định hai chuyện: nó có hội tụ không, và còn lại gì nếu không.
// Mầm qua hai đầu mút để hướng của cả đoạn tựa lên đúng HAI tia, nên nhiễu tầm của hai tia đó
// vào thẳng góc của đoạn — rồi vào thẳng đỉnh chữ V, vì đỉnh là giao của hai cánh.
//
// Dựng đúng tình huống phân biệt hai cách: tường phẳng, 19 điểm giữa sạch, chỉ hai đầu mút bị
// đẩy ngược chiều nhau. Phản đối xứng nên nó XOAY đoạn chứ không tịnh tiến. Khớp hai đầu mút
// nghiêng theo trọn vẹn; khớp đủ điểm bị 19 điểm giữa neo lại.
const ScanGeometry g = geometry(21, -0.3, 0.3);
std::vector<double> ranges = wallScan(g, 2.0);
ranges.front() += 0.03; // [m] đẩy ra
ranges.back() -= 0.03; // [m] kéo vào
robot_line_extraction::CachedData c_data;
robot_line_extraction::RangeData r_data;
std::vector<unsigned int> indices;
for (std::size_t i = 0; i < g.size; ++i)
{
const double bearing = bearingOf(g, i);
c_data.bearings.push_back(bearing);
c_data.cos_bearings.push_back(std::cos(bearing));
c_data.sin_bearings.push_back(std::sin(bearing));
c_data.indices.push_back(static_cast<unsigned int>(i));
r_data.ranges.push_back(ranges[i]);
r_data.xs.push_back(ranges[i] * std::cos(bearing));
r_data.ys.push_back(ranges[i] * std::sin(bearing));
indices.push_back(static_cast<unsigned int>(i));
}
Line line(c_data, r_data, tightParams(), indices);
line.endpointFit();
const double endpoint_angle = line.getAngle();
line.totalLeastSqFit();
const double tls_angle = line.getAngle();
// Pháp tuyến thật của tường ở 0. Hai đầu bị đẩy kéo khớp hai đầu mút đi hẳn; khớp đủ điểm chịu
// chưa tới một phần ba mức đó.
EXPECT_GT(std::fabs(endpoint_angle), 0.040);
EXPECT_LT(std::fabs(tls_angle), 0.020);
EXPECT_LT(std::fabs(tls_angle), std::fabs(endpoint_angle) / 3.0);
}
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(Line, AMergedSegmentStillKnowsItsRays)
{
// Hồi quy cho một lần đọc TRÀN MẢNG có thật. Constructor dùng khi gộp hai đoạn không mang theo dữ
// liệu scan, nên đoạn đã gộp có `r_data_` RỖNG — mà `pointAt` lại đọc thẳng vào đó. Bất kỳ ai hỏi
// đoạn đã gộp về toạ độ một tia đều đọc qua cuối một vector rỗng. Cổng dải phản quang làm đúng
// thế; bộ khớp cung tròn cũng vậy, và nó segfault — đó là cách lỗi này lộ ra.
//
// Người dùng đoạn thẳng KHÔNG phân biệt được đoạn đã gộp với đoạn nguyên, nên bất biến là: mọi
// đoạn đều trả lời được về mọi tia nó đỡ.
//
// Test đánh THẲNG vào constructor gộp chứ không đi vòng qua bộ trích đoạn, vì với tham số mặc
// định `mergeLines` gần như không bao giờ nổ: khe hở đủ rộng để TÁCH thì đã quá `max_line_gap` để
// GỘP. Chính vì thế lỗi này nằm im được lâu, và cũng chính vì thế một cảnh dựng sẵn không phải là
// chỗ canh đáng tin.
const ScanGeometry g = geometry(40, -0.4, 0.4);
const std::vector<double> ranges = wallScan(g, 2.0);
robot_line_extraction::CachedData c_data;
robot_line_extraction::RangeData r_data;
for (std::size_t i = 0; i < g.size; ++i)
{
const double bearing = bearingOf(g, i);
c_data.bearings.push_back(bearing);
c_data.cos_bearings.push_back(std::cos(bearing));
c_data.sin_bearings.push_back(std::sin(bearing));
c_data.indices.push_back(static_cast<unsigned int>(i));
r_data.ranges.push_back(ranges[i]);
r_data.xs.push_back(ranges[i] * std::cos(bearing));
r_data.ys.push_back(ranges[i] * std::sin(bearing));
}
// Đúng thứ `mergeLines` dựng: tham số đã khớp xong, tập tia của cả hai nửa nối lại.
std::vector<unsigned int> indices;
for (unsigned int i = 0; i < 40u; ++i)
{
indices.push_back(i);
}
const std::array<double, 4> cov{ { 1e-6, 0.0, 0.0, 1e-6 } };
const Line merged(c_data, r_data, /*angle=*/0.0, /*radius=*/2.0, cov,
{ { r_data.xs.front(), r_data.ys.front() } },
{ { r_data.xs.back(), r_data.ys.back() } }, indices);
ASSERT_TRUE(merged.hasCovariance());
for (const unsigned int ray : merged.getIndices())
{
const std::array<double, 2> p = merged.pointAt(ray);
ASSERT_TRUE(std::isfinite(p[0]) && std::isfinite(p[1])) << "tia " << ray;
// Và phải là toạ độ của CHÍNH tia đó, không phải một tia khác.
EXPECT_NEAR(p[0], r_data.xs[ray], 1e-12);
EXPECT_NEAR(p[1], r_data.ys[ray], 1e-12);
}
}
TEST(LineExtractor, EverySegmentTheExtractorReturnsCanReportItsOwnRays)
{
// Bất biến rộng, quét trên một cảnh nhiều mặt. Không ép được đường gộp từ đây (xem test trên),
// nên nó không thay thế test kia — nó canh mọi đường DẪN TỚI một đoạn, kể cả đường sau này mới có.
Rig rig;
ASSERT_TRUE(rig.ok_) << rig.error_;
const ScanGeometry g = geometry(360, -1.2, 1.2);
const std::vector<double> ranges = vPlateScan(g, 1.5, M_PI / 4.0, 0.30);
ASSERT_TRUE(rig.run(g, ranges)) << rig.error_;
ASSERT_FALSE(rig.lines_.empty());
for (const Line& line : rig.lines_)
{
for (const unsigned int ray : line.getIndices())
{
const std::array<double, 2> p = line.pointAt(ray);
ASSERT_TRUE(std::isfinite(p[0]) && std::isfinite(p[1])) << "tia " << ray;
const double bearing = bearingOf(g, ray);
EXPECT_NEAR(p[0], ranges[ray] * std::cos(bearing), 1e-9);
EXPECT_NEAR(p[1], ranges[ray] * std::sin(bearing), 1e-9);
}
}
}
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();
}