feat: detect a concave arc, the cradle that curves around the robot
Second shape after the V. Same output contract - a pose in the scan frame - so
dock_target and everything downstream of it are untouched.
CircleFit uses Taubin rather than Kasa, and that is the whole reason it is
worth writing rather than reaching for the four-line linear fit. Kasa is biased
on a SHORT arc, and a short arc is the normal case: the dock is partly hidden,
or the robot approaches at an angle. Measured on a true 0.40 m arc, 18 points,
3 mm noise, averaged over 200 seeds:
arc span Taubin Kasa
180 deg +0.0 mm -0.0 mm
90 deg +0.1 mm -1.4 mm
45 deg +1.9 mm -24.3 mm
30 deg +8.6 mm -101.6 mm <- Kasa reads 0.40 m as 0.298 m
20 deg +25.4 mm -256.7 mm
With Kasa a 0.40 m dock seen at an angle is scored as 0.30 m, falls outside
radius_tolerance, and the symptom is "it never detects" - indistinguishable
from the dock not being in range. arc_min_span defaults to 30 degrees off that
same table, because below it even Taubin starts to drift.
The matcher takes line segments as input even though it is looking for a curve.
The extractor breaks a curved surface into short straight pieces - correct
behaviour, and convenient here: those pieces are adjacent by ray number, so
their combined support is the arc's point run. That reuses the gap splitting
and outlier rejection that already ran instead of adding a second segmenter
beside the first. A short shallow arc can come out as one segment, looking
straight under min_split_dist, and still fits: the circle fit reads raw points
and does not care what the extractor called them.
Grouping keys on this_start >= prev_end, not >. On a distance split the
extractor SHARES the corner point between both halves, so two pieces of one
surface meet at the same ray number. Requiring strictly greater grouped
nothing, and every 0.5 rad fragment then failed arc_min_span - a real arc
rejected on a fragment's arithmetic. The shared point is also skipped when
gathering, so it does not get double weight at the joint.
The gates, in order:
- fit residual first, because EVERY set of points fits some circle, a right
angle included. Residual is the only thing separating an arc from a bend,
so radius and span only mean something after it passes.
- span has a floor (numerical: trust the fit) and a ceiling (geometric: a
longer arc is a different object). Not an equality - occlusion only ever
shortens an arc, the same asymmetry as the V's wing lengths.
- concavity: the centre must lie between the sensor and the surface. A convex
cylinder is the same circle curving the other way, and taking one for the
other puts the target pose behind the surface - the robot is told to drive
into the object.
The target is the deepest point, C * (1 + R/|C|), which depends only on centre
and radius and so does not move when part of the arc is hidden. The midpoint of
the observed arc would be easier and would shift the moment one side is
occluded.
tape_enabled is refused on an arc profile rather than ignored. findTape walks
the ray span of a fitted line and an arc produces none, so accepting the flag
would leave someone believing a gate is protecting them.
Measured end to end, 200 runs per cell, 3 mm noise, 690 rays: 100% detection at
1.4-2.0 rad of span out to 3 m, apex within 1-2 mm, radius read as 0.399-0.401
against a true 0.400. It thins out at 0.7 rad (77-80% near, 26% at 5 m), which
is arc_min_span doing its job.
This commit is contained in:
@@ -62,6 +62,8 @@ endif()
|
||||
# ========================================================
|
||||
add_library(dock_pattern_detector SHARED
|
||||
src/dock_profile.cpp
|
||||
src/arc_pattern_matcher.cpp
|
||||
src/circle_fit.cpp
|
||||
src/v_pattern_matcher.cpp
|
||||
)
|
||||
|
||||
@@ -176,4 +178,56 @@ if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
|
||||
)
|
||||
endif()
|
||||
|
||||
catkin_add_gtest(circle_fit_test test/circle_fit_test.cpp)
|
||||
|
||||
if(TARGET circle_fit_test)
|
||||
# catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make`
|
||||
# thường, đúng quy trình verify của repo.
|
||||
set_target_properties(circle_fit_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
|
||||
|
||||
target_compile_options(circle_fit_test PRIVATE -Wall -Wextra)
|
||||
|
||||
target_include_directories(circle_fit_test
|
||||
PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_include_directories(circle_fit_test SYSTEM
|
||||
PRIVATE
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
# catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain.
|
||||
target_link_libraries(circle_fit_test
|
||||
dock_pattern_detector
|
||||
pthread
|
||||
)
|
||||
endif()
|
||||
|
||||
catkin_add_gtest(arc_pattern_matcher_test test/arc_pattern_matcher_test.cpp)
|
||||
|
||||
if(TARGET arc_pattern_matcher_test)
|
||||
# catkin_add_gtest đặt target EXCLUDE_FROM_ALL; mở ra để binary có mặt sau `catkin_make`
|
||||
# thường, đúng quy trình verify của repo.
|
||||
set_target_properties(arc_pattern_matcher_test PROPERTIES EXCLUDE_FROM_ALL FALSE)
|
||||
|
||||
target_compile_options(arc_pattern_matcher_test PRIVATE -Wall -Wextra)
|
||||
|
||||
target_include_directories(arc_pattern_matcher_test
|
||||
PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
)
|
||||
|
||||
target_include_directories(arc_pattern_matcher_test SYSTEM
|
||||
PRIVATE
|
||||
${EIGEN3_INCLUDE_DIRS}
|
||||
)
|
||||
|
||||
# catkin_add_gtest dùng target_link_libraries dạng plain, nên phần bổ sung cũng phải plain.
|
||||
target_link_libraries(arc_pattern_matcher_test
|
||||
dock_pattern_detector
|
||||
pthread
|
||||
)
|
||||
endif()
|
||||
|
||||
endif()
|
||||
|
||||
91
include/dock_pattern_detector/arc_pattern_matcher.h
Normal file
91
include/dock_pattern_detector/arc_pattern_matcher.h
Normal file
@@ -0,0 +1,91 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — tìm máng cong LÕM trong một tập đoạn thẳng.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_ARC_PATTERN_MATCHER_H_
|
||||
#define DOCK_PATTERN_DETECTOR_ARC_PATTERN_MATCHER_H_
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_line_extraction/line.h>
|
||||
|
||||
#include <dock_pattern_detector/dock_profile.h>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
|
||||
/**
|
||||
* @class ArcPatternMatcher
|
||||
* @brief Ghép các đoạn thẳng LIỀN NHAU lại rồi khớp một đường tròn vào điểm của chúng.
|
||||
*
|
||||
* Hình học thuần, cùng hợp đồng với @ref VPatternMatcher: vào là danh sách đoạn của
|
||||
* `robot_line_extraction`, ra là một pose trong **frame của scan**. Không TF, không action.
|
||||
*
|
||||
* ## Vì sao vẫn nhận đoạn thẳng làm đầu vào, dù đang tìm đường cong
|
||||
*
|
||||
* Bộ trích đoạn bẻ một mặt cong thành nhiều đoạn thẳng ngắn — đó là hành vi đúng của nó, và ở đây
|
||||
* lại tiện: những đoạn ấy **liền nhau theo số tia**, nên tập tia của chúng gộp lại chính là chuỗi
|
||||
* điểm của cung. Đi đường này thì dùng lại được nguyên phần tách theo khe hở và lọc điểm rác đã
|
||||
* chạy, thay vì viết một bộ phân đoạn thứ hai chạy song song với bộ thứ nhất.
|
||||
*
|
||||
* Cung ngắn và thoải có thể ra đúng MỘT đoạn — trông thẳng dưới `min_split_dist`. Vẫn khớp được:
|
||||
* phép khớp tròn đọc điểm thô, không quan tâm bộ trích đoạn đã gọi nó là gì. Và chính chỗ đó là
|
||||
* cổng phân biệt: sai số khớp TRÒN nhỏ hơn hẳn sai số khớp THẲNG trên cùng chuỗi điểm.
|
||||
*
|
||||
* ## Luật khớp
|
||||
*
|
||||
* 1. Gom các đoạn liền nhau theo số tia thành một chuỗi ứng viên.
|
||||
* 2. Khớp đường tròn Taubin vào chuỗi đó.
|
||||
* 3. **Sai số khớp** phải dưới `arc_max_rms` — cổng chính, vì mọi tập điểm đều khớp được vào một
|
||||
* đường tròn nào đó, kể cả một góc vuông.
|
||||
* 4. **Bán kính** khớp `arc_radius`.
|
||||
* 5. **Góc mở quan sát được** phải ít nhất `arc_min_span` (để tin được phép khớp) và không quá
|
||||
* `arc_span` (dài hơn thì là mặt cong khác). Cận trên chứ không phải khớp đúng: che khuất chỉ
|
||||
* làm cung ngắn đi.
|
||||
* 6. **LÕM** — tâm phải nằm phía cảm biến so với mặt cong. Máng lõm ôm robot; trụ tròn thì ngược
|
||||
* lại, và hai thứ đó đòi hai pose đích khác nhau.
|
||||
*
|
||||
* ## Pose đích
|
||||
*
|
||||
* Điểm SÂU NHẤT của máng, tức điểm trên đường tròn xa cảm biến nhất dọc hướng cảm biến→tâm:
|
||||
* `P = C * (1 + R/|C|)`. Định nghĩa như vậy chỉ phụ thuộc tâm và bán kính — cả hai từ phép khớp —
|
||||
* nên nó **không đổi khi một phần cung bị che**. Lấy trung điểm của cung quan sát được thì tiện
|
||||
* hơn nhưng lệch ngay khi một bên bị khuất.
|
||||
*
|
||||
* `yaw` hướng từ P về phía cảm biến, đúng quy ước của chữ V.
|
||||
*
|
||||
* @note Không thread-safe. Một matcher cho một consumer.
|
||||
*/
|
||||
class ArcPatternMatcher
|
||||
{
|
||||
public:
|
||||
ArcPatternMatcher() = default;
|
||||
|
||||
/// @brief Nhận profile. Sai miền thì giữ bộ cũ và trả false.
|
||||
bool configure(const DockProfile& profile, std::string& error);
|
||||
|
||||
const DockProfile& profile() const
|
||||
{
|
||||
return profile_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Tìm máng cong lõm trong @p lines.
|
||||
*
|
||||
* @return Kết quả luôn hợp lệ để đọc. `valid == false` kèm `reason` nói rõ hỏng ở CỔNG NÀO —
|
||||
* "khớp được nhưng sai số lớn" và "không đủ điểm để khớp" đòi hai cách xử trí ngược nhau.
|
||||
*/
|
||||
Detection match(const std::vector<robot_line_extraction::Line>& lines) const;
|
||||
|
||||
private:
|
||||
DockProfile profile_;
|
||||
};
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_ARC_PATTERN_MATCHER_H_
|
||||
81
include/dock_pattern_detector/circle_fit.h
Normal file
81
include/dock_pattern_detector/circle_fit.h
Normal file
@@ -0,0 +1,81 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — khớp đường tròn vào một chuỗi điểm.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_CIRCLE_FIT_H_
|
||||
#define DOCK_PATTERN_DETECTOR_CIRCLE_FIT_H_
|
||||
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
|
||||
/**
|
||||
* @struct CircleFitResult
|
||||
* @brief Đường tròn khớp được, kèm mức khớp.
|
||||
*/
|
||||
struct CircleFitResult
|
||||
{
|
||||
bool valid = false;
|
||||
|
||||
double center_x = 0.0; ///< [m] trong frame của điểm đầu vào
|
||||
double center_y = 0.0; ///< [m]
|
||||
double radius = 0.0; ///< [m]
|
||||
|
||||
/**
|
||||
* [m] Sai số trung bình bình phương của cự ly điểm tới đường tròn.
|
||||
*
|
||||
* Đây là thứ phân biệt "một cung tròn thật" với "một khúc gãy tình cờ nằm gần đường tròn". Một
|
||||
* góc tường vuông cũng khớp được vào một đường tròn nào đó — nhưng với sai số lớn.
|
||||
*/
|
||||
double rms_error = 0.0;
|
||||
|
||||
/// [rad] Góc mở của cung ĐO ĐƯỢC, từ điểm đầu tới điểm cuối nhìn từ tâm.
|
||||
double span = 0.0;
|
||||
|
||||
std::size_t point_count = 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Khớp đường tròn vào @p xs / @p ys bằng phương pháp Taubin.
|
||||
*
|
||||
* Taubin chứ không phải Kåsa (bình phương tối thiểu tuyến tính trên `x^2 + y^2`), và đó là lựa chọn
|
||||
* có chủ đích. Kåsa lệch **hệ thống** trên cung ngắn — không phải nhiễu, mà là kéo bán kính xuống
|
||||
* đều đặn — mà cung ngắn đúng là ca thường gặp: trạm bị che một phần, hoặc robot nhìn chếch.
|
||||
*
|
||||
* Đo trên cung bán kính thật 0.40 m, 18 điểm, nhiễu 3 mm, trung bình 200 hạt giống:
|
||||
*
|
||||
* góc mở cung Taubin Kåsa
|
||||
* 180 deg +0.0 mm -0.0 mm
|
||||
* 90 deg +0.1 mm -1.4 mm
|
||||
* 45 deg +1.9 mm -24.3 mm
|
||||
* 30 deg +8.6 mm -101.6 mm <- Kåsa chấm 0.40 m thành 0.298 m
|
||||
* 20 deg +25.4 mm -256.7 mm
|
||||
*
|
||||
* Với Kåsa, một trạm 0.40 m nhìn chếch bị chấm thành 0.30 m rồi rớt cổng `radius_tolerance`, và
|
||||
* triệu chứng là "dò mãi không ra" — trông giống hệt trạm không có trong tầm.
|
||||
*
|
||||
* Taubin vẫn là dạng đóng, không lặp, nên chạy được trong control loop.
|
||||
*
|
||||
* @warning Bảng trên cũng là giới hạn của CHÍNH Taubin: dưới 30 độ góc mở, sai lệch của nó bắt đầu
|
||||
* lớn nhanh. Người gọi phải đặt ngưỡng góc mở tối thiểu, đừng tin một bán kính khớp từ một
|
||||
* mẩu cung 20 độ.
|
||||
*
|
||||
* @param xs,ys [m] toạ độ điểm, cùng độ dài. Phải là một chuỗi LIỀN NHAU dọc bề mặt — hàm này
|
||||
* không tự tách chuỗi, nó khớp đúng cái được đưa vào.
|
||||
* @return `valid == false` khi có ít hơn 3 điểm, khi mọi điểm gần như thẳng hàng (đường tròn suy
|
||||
* biến thành đường thẳng, bán kính chạy ra vô cùng), hoặc khi phép giải không hữu hạn.
|
||||
*
|
||||
* @note Ba điểm là tối thiểu tuyệt đối để xác định một đường tròn, nhưng ba điểm thì `rms_error`
|
||||
* luôn bằng 0 và không nói lên điều gì. Người gọi cần đặt ngưỡng số điểm riêng.
|
||||
*/
|
||||
CircleFitResult fitCircle(const std::vector<double>& xs, const std::vector<double>& ys);
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_CIRCLE_FIT_H_
|
||||
@@ -77,6 +77,54 @@ struct DockProfile
|
||||
*/
|
||||
double vertex_gap = 0.05;
|
||||
|
||||
// --- Cung tròn lõm (pattern: arc) ----------------------------------------------------------------
|
||||
//
|
||||
// Máng cong ôm lấy robot: tâm đường tròn nằm PHÍA CẢM BIẾN, mặt cong ở xa hơn tâm. Đây là thứ
|
||||
// phân biệt nó với trụ tròn (`cylinder`, chưa hiện thực) — trụ có tâm nằm SAU mặt cong.
|
||||
|
||||
/// [m] Bán kính máng, đo trên trạm thật.
|
||||
double arc_radius = 0.40;
|
||||
|
||||
/// [m] Sai lệch bán kính còn chấp nhận.
|
||||
double arc_radius_tolerance = 0.06;
|
||||
|
||||
/**
|
||||
* [rad] Góc mở TOÀN PHẦN của máng — bao nhiêu cung thật sự tồn tại trên tấm.
|
||||
*
|
||||
* Đây là cận TRÊN, không phải giá trị phải khớp đúng. Lý do giống hệt luật chiều dài cánh chữ V:
|
||||
* che khuất và nhìn chếch chỉ làm cung NGẮN đi, không bao giờ dài ra. Bắt khớp đúng nghĩa là chỉ
|
||||
* dò được khi nhìn trọn cả máng.
|
||||
*
|
||||
* Cung quan sát được dài HƠN ngần này thì không phải cái máng đó — là một mặt cong khác.
|
||||
*/
|
||||
double arc_span = 2.0;
|
||||
|
||||
/**
|
||||
* [rad] Góc mở tối thiểu quan sát được thì mới tin phép khớp.
|
||||
*
|
||||
* Không phải cổng hình học mà là cổng SỐ HỌC. Khớp đường tròn trên một mẩu cung quá ngắn thì bán
|
||||
* kính bắt đầu lệch nhanh: đo trên cung bán kính 0.40 m, nhiễu 3 mm, sai lệch trung bình là
|
||||
* +1.9 mm ở 45 độ, +8.6 mm ở 30 độ, +25.4 mm ở 20 độ. Dưới 30 độ, một cái máng 0.40 m có thể bị
|
||||
* chấm thành 0.43 m và rớt cổng bán kính — hoặc tệ hơn, một mặt phẳng hơi cong lọt qua.
|
||||
*
|
||||
* Mặc định 0.52 rad (30 độ) theo đúng bảng đó.
|
||||
*/
|
||||
double arc_min_span = 0.52;
|
||||
|
||||
/**
|
||||
* [m] Sai số khớp tối đa của điểm so với đường tròn.
|
||||
*
|
||||
* Đây là cổng CHÍNH chống nhầm, vì mọi tập điểm đều khớp được vào một đường tròn NÀO ĐÓ — kể cả
|
||||
* hai đoạn thẳng gặp nhau ở một góc vuông. Thứ phân biệt cung thật với khúc gãy là sai số khớp,
|
||||
* không phải việc có khớp được hay không.
|
||||
*
|
||||
* Đặt theo nhiễu tầm của cảm biến, cỡ 2-3 lần lệch chuẩn. nanoscan3 sim có 3 mm, nên 0.010 m.
|
||||
*/
|
||||
double arc_max_rms = 0.010;
|
||||
|
||||
/// Số điểm tối thiểu trên cung. Dưới 3 thì không có đường tròn nào để nói tới.
|
||||
std::size_t min_arc_points = 8;
|
||||
|
||||
// --- Dải phản quang ----------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
@@ -223,6 +271,19 @@ struct Detection
|
||||
/// Số tia sáng trên mỗi dải. Ít hơn 2 thì không đo nổi chiều dài.
|
||||
std::size_t tape_points[2] = { 0, 0 };
|
||||
|
||||
/// [m] Bán kính cung ĐO ĐƯỢC. 0 khi biên dạng không phải cung tròn.
|
||||
double measured_arc_radius = 0.0;
|
||||
|
||||
/// [rad] Góc mở cung ĐO ĐƯỢC — bao nhiêu cung thật sự nhìn thấy, không phải toàn phần.
|
||||
double measured_arc_span = 0.0;
|
||||
|
||||
/// [m] Sai số khớp đường tròn. So với `arc_max_rms` để biết đó là cung hay một khúc gãy.
|
||||
double measured_arc_rms = 0.0;
|
||||
|
||||
/// [m] Tâm đường tròn trong frame của scan. Với máng lõm, tâm nằm PHÍA CẢM BIẾN.
|
||||
double arc_center_x = 0.0;
|
||||
double arc_center_y = 0.0;
|
||||
|
||||
/// Số đoạn thẳng trích được từ scan. Nhiều bất thường = cảnh đang bị vụn, chỉnh trích đoạn;
|
||||
/// ít quá = đứng sai chỗ hoặc mục tiêu ngoài tầm. Hai ca khác hẳn nhau.
|
||||
std::size_t segment_count = 0;
|
||||
|
||||
358
src/arc_pattern_matcher.cpp
Normal file
358
src/arc_pattern_matcher.cpp
Normal file
@@ -0,0 +1,358 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — khớp máng cong lõm.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <dock_pattern_detector/arc_pattern_matcher.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
|
||||
#include <dock_pattern_detector/circle_fit.h>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
using robot_line_extraction::Line;
|
||||
|
||||
/**
|
||||
* @brief Số tia được phép hụt giữa hai đoạn mà vẫn coi là cùng một mặt.
|
||||
*
|
||||
* Bộ trích đoạn bỏ tia rác và tia ngoài tầm, nên hai đoạn của cùng một mặt cong hiếm khi có số tia
|
||||
* liền tù tì. Cho phép hụt vài tia; hụt nhiều hơn là đã sang vật khác, và gộp qua đó thì phép khớp
|
||||
* tròn sẽ ôm cả hai vật vào một đường tròn không tồn tại.
|
||||
*/
|
||||
constexpr unsigned int kMaxRayGapBetweenSegments = 4;
|
||||
|
||||
/// @brief Điểm khớp trong [0, 1]: 1 khi lệch bằng 0, 0 khi lệch chạm dung sai.
|
||||
double score(double deviation, double tolerance)
|
||||
{
|
||||
if (tolerance <= 0.0)
|
||||
{
|
||||
return 0.0;
|
||||
}
|
||||
return std::max(0.0, 1.0 - std::fabs(deviation) / tolerance);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
bool ArcPatternMatcher::configure(const DockProfile& profile, std::string& error)
|
||||
{
|
||||
if (!profile.validate(error))
|
||||
{
|
||||
return false; // Giữ bộ cũ; một profile áp nửa vời còn tệ hơn không áp.
|
||||
}
|
||||
if (profile.pattern != PatternType::kArc)
|
||||
{
|
||||
error = std::string("ArcPatternMatcher was given pattern '") + toString(profile.pattern) + "'";
|
||||
return false;
|
||||
}
|
||||
profile_ = profile;
|
||||
return true;
|
||||
}
|
||||
|
||||
Detection ArcPatternMatcher::match(const std::vector<Line>& lines) const
|
||||
{
|
||||
Detection best;
|
||||
best.segment_count = lines.size();
|
||||
|
||||
if (lines.empty())
|
||||
{
|
||||
best.reason = "scan yielded no line segments to group into an arc";
|
||||
return best;
|
||||
}
|
||||
|
||||
// Gom các đoạn LIỀN NHAU theo số tia. Đoạn đứng một mình cũng là một ứng viên: một cung ngắn và
|
||||
// thoải ra đúng một đoạn, và phép khớp tròn vẫn đọc được độ cong từ điểm thô của nó.
|
||||
std::vector<std::vector<std::size_t>> groups;
|
||||
for (std::size_t i = 0; i < lines.size(); ++i)
|
||||
{
|
||||
if (lines[i].getIndices().empty())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (!groups.empty())
|
||||
{
|
||||
const Line& prev = lines[groups.back().back()];
|
||||
const unsigned int prev_end = prev.getIndices().back();
|
||||
const unsigned int this_start = lines[i].getIndices().front();
|
||||
// `>=` chứ không phải `>`: khi tách theo khoảng cách, bộ trích đoạn DÙNG CHUNG điểm góc cho
|
||||
// cả hai nửa, nên hai đoạn của cùng một mặt cong gặp nhau ở đúng một số tia. Đòi hơn hẳn là
|
||||
// không nhóm nào được gộp, và mỗi mẩu cung 0.5 rad rớt sàn `arc_min_span` — cung thật bị bỏ
|
||||
// vì lý do số học của một mảnh vụn.
|
||||
if (this_start >= prev_end && this_start - prev_end <= kMaxRayGapBetweenSegments)
|
||||
{
|
||||
groups.back().push_back(i);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
groups.push_back({ i });
|
||||
}
|
||||
|
||||
std::size_t rejected_points = 0;
|
||||
std::size_t rejected_fit = 0;
|
||||
std::size_t rejected_rms = 0;
|
||||
std::size_t rejected_radius = 0;
|
||||
std::size_t rejected_span = 0;
|
||||
std::size_t rejected_convex = 0;
|
||||
std::size_t rejected_prior = 0;
|
||||
std::size_t rejected_confidence = 0;
|
||||
std::size_t accepted = 0;
|
||||
|
||||
// Ứng viên trượt SÁT NHẤT, kèm số ĐO ĐƯỢC. Chỉ đếm số lượng thì không biết nên nới dung sai bán
|
||||
// kính hay đứng gần lại — mà hai chuyện đó ngược nhau.
|
||||
bool have_near = false;
|
||||
double near_radius = 0.0;
|
||||
double near_span = 0.0;
|
||||
double near_rms = 0.0;
|
||||
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
|
||||
for (const std::vector<std::size_t>& group : groups)
|
||||
{
|
||||
xs.clear();
|
||||
ys.clear();
|
||||
bool have_prev_ray = false;
|
||||
unsigned int prev_ray = 0;
|
||||
for (const std::size_t li : group)
|
||||
{
|
||||
for (const unsigned int ray : lines[li].getIndices())
|
||||
{
|
||||
// Điểm góc dùng chung giữa hai đoạn liền nhau sẽ tới đây hai lần. Đếm nó hai lần thì nó
|
||||
// được cân nặng gấp đôi trong phép khớp — nhỏ, nhưng vô cớ, và nó luôn rơi đúng chỗ nối.
|
||||
if (have_prev_ray && ray == prev_ray)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
have_prev_ray = true;
|
||||
prev_ray = ray;
|
||||
|
||||
const std::array<double, 2> p = lines[li].pointAt(ray);
|
||||
if (!std::isfinite(p[0]) || !std::isfinite(p[1]))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
xs.push_back(p[0]);
|
||||
ys.push_back(p[1]);
|
||||
}
|
||||
}
|
||||
|
||||
if (xs.size() < profile_.min_arc_points)
|
||||
{
|
||||
++rejected_points;
|
||||
continue;
|
||||
}
|
||||
|
||||
const CircleFitResult fit = fitCircle(xs, ys);
|
||||
if (!fit.valid)
|
||||
{
|
||||
++rejected_fit; // Gần như thẳng hàng, hoặc suy biến. Không phải cung.
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!have_near)
|
||||
{
|
||||
have_near = true;
|
||||
near_radius = fit.radius;
|
||||
near_span = fit.span;
|
||||
near_rms = fit.rms_error;
|
||||
}
|
||||
|
||||
// Cổng CHÍNH, đặt trước mọi cổng khác: mọi tập điểm đều khớp được vào một đường tròn nào đó, kể
|
||||
// cả một góc vuông. Sai số khớp là thứ duy nhất phân biệt cung thật với khúc gãy, nên bán kính
|
||||
// và góc mở chỉ có nghĩa sau khi qua được cổng này.
|
||||
if (fit.rms_error > profile_.arc_max_rms)
|
||||
{
|
||||
++rejected_rms;
|
||||
if (fit.rms_error < near_rms)
|
||||
{
|
||||
near_radius = fit.radius;
|
||||
near_span = fit.span;
|
||||
near_rms = fit.rms_error;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Góc mở quan sát được: sàn là cổng SỐ HỌC (dưới đó bán kính khớp bắt đầu lệch nhanh), trần là
|
||||
// cổng HÌNH HỌC (cung dài hơn cả cái máng thì là mặt cong khác).
|
||||
if (fit.span < profile_.arc_min_span)
|
||||
{
|
||||
++rejected_span;
|
||||
continue;
|
||||
}
|
||||
if (fit.span > profile_.arc_span + profile_.arc_radius_tolerance / std::max(fit.radius, 1e-6))
|
||||
{
|
||||
++rejected_span;
|
||||
continue;
|
||||
}
|
||||
|
||||
const double radius_dev = fit.radius - profile_.arc_radius;
|
||||
if (std::fabs(radius_dev) > profile_.arc_radius_tolerance)
|
||||
{
|
||||
++rejected_radius;
|
||||
continue;
|
||||
}
|
||||
|
||||
// LÕM: tâm phải nằm giữa cảm biến và mặt cong. Gốc cảm biến là (0, 0) trong frame của scan, nên
|
||||
// điều kiện là |tâm| < cự ly trung bình của các điểm mặt. Trụ tròn thì ngược lại — và nếu nhận
|
||||
// nhầm, pose đích rơi ra sau mặt trụ, tức robot lái vào trong vật.
|
||||
const double center_range = std::hypot(fit.center_x, fit.center_y);
|
||||
double mean_point_range = 0.0;
|
||||
for (std::size_t k = 0; k < xs.size(); ++k)
|
||||
{
|
||||
mean_point_range += std::hypot(xs[k], ys[k]);
|
||||
}
|
||||
mean_point_range /= static_cast<double>(xs.size());
|
||||
|
||||
if (center_range >= mean_point_range || center_range < 1e-6)
|
||||
{
|
||||
++rejected_convex;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Điểm sâu nhất: trên đường tròn, dọc hướng cảm biến -> tâm, ra xa thêm một bán kính. Chỉ phụ
|
||||
// thuộc tâm và bán kính nên không đổi khi một phần cung bị che.
|
||||
const double scale = 1.0 + fit.radius / center_range;
|
||||
const double apex_x = fit.center_x * scale;
|
||||
const double apex_y = fit.center_y * scale;
|
||||
|
||||
// Hướng từ điểm sâu nhất về phía cảm biến, cùng quy ước với chữ V.
|
||||
const double yaw = std::atan2(-fit.center_y, -fit.center_x);
|
||||
|
||||
if (profile_.has_prior)
|
||||
{
|
||||
const double d = std::hypot(apex_x - profile_.prior_x, apex_y - profile_.prior_y);
|
||||
if (d > profile_.search_radius)
|
||||
{
|
||||
++rejected_prior;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (profile_.search_fov > 0.0 &&
|
||||
std::fabs(std::atan2(apex_y, apex_x)) > profile_.search_fov)
|
||||
{
|
||||
++rejected_prior;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Điểm tin: trục TỆ NHẤT trong ba tiêu chí, không phải trung bình — giống chữ V. Trung bình cho
|
||||
// một cung sai hẳn bán kính nhưng khớp đẹp lọt qua bằng điểm của tiêu chí kia.
|
||||
const double support = std::min(1.0, static_cast<double>(xs.size()) /
|
||||
static_cast<double>(profile_.min_arc_points * 2));
|
||||
const double rms_score = score(fit.rms_error, profile_.arc_max_rms);
|
||||
const double confidence =
|
||||
std::min({ score(radius_dev, profile_.arc_radius_tolerance), rms_score, support });
|
||||
|
||||
if (confidence < profile_.min_confidence)
|
||||
{
|
||||
++rejected_confidence;
|
||||
continue;
|
||||
}
|
||||
|
||||
++accepted;
|
||||
if (best.valid && confidence <= best.confidence)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
best.valid = true;
|
||||
best.confidence = confidence;
|
||||
best.apex_x = apex_x;
|
||||
best.apex_y = apex_y;
|
||||
best.measured_arc_radius = fit.radius;
|
||||
best.measured_arc_span = fit.span;
|
||||
best.measured_arc_rms = fit.rms_error;
|
||||
best.arc_center_x = fit.center_x;
|
||||
best.arc_center_y = fit.center_y;
|
||||
|
||||
// Pose đích = điểm sâu nhất dịch theo offset của profile, trong hệ của CHÍNH hình: x dọc pháp
|
||||
// tuyến hướng ra phía robot, y sang trái. Giống hệt chữ V.
|
||||
const double cos_y = std::cos(yaw);
|
||||
const double sin_y = std::sin(yaw);
|
||||
best.x = apex_x + cos_y * profile_.offset_x - sin_y * profile_.offset_y;
|
||||
best.y = apex_y + sin_y * profile_.offset_x + cos_y * profile_.offset_y;
|
||||
best.yaw =
|
||||
std::atan2(std::sin(yaw + profile_.offset_yaw), std::cos(yaw + profile_.offset_yaw));
|
||||
}
|
||||
|
||||
best.candidate_count = accepted;
|
||||
|
||||
if (!best.valid)
|
||||
{
|
||||
// Lý do cụ thể nhất trước: cái đếm nào lớn nhất nói đúng chỗ đang hỏng.
|
||||
char detail[192] = { 0 };
|
||||
if (have_near)
|
||||
{
|
||||
std::snprintf(detail, sizeof(detail),
|
||||
" (nearest fit: radius %.3f m vs %.3f+-%.3f, span %.3f rad (min %.3f, max"
|
||||
" %.3f), rms %.4f m vs max %.4f)",
|
||||
near_radius, profile_.arc_radius, profile_.arc_radius_tolerance, near_span,
|
||||
profile_.arc_min_span, profile_.arc_span, near_rms, profile_.arc_max_rms);
|
||||
}
|
||||
|
||||
if (rejected_prior > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_prior) +
|
||||
" arc(s) matched the shape but fell outside the search gate";
|
||||
}
|
||||
else if (rejected_confidence > 0)
|
||||
{
|
||||
best.reason =
|
||||
std::to_string(rejected_confidence) + " arc(s) matched but scored below min_confidence";
|
||||
best.reason += detail;
|
||||
}
|
||||
else if (rejected_convex > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_convex) +
|
||||
" arc(s) curve the WRONG WAY — centre behind the surface, so this is a convex "
|
||||
"cylinder, not a concave cradle";
|
||||
}
|
||||
else if (rejected_radius > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_radius) + " arc(s) fitted cleanly but at a radius the "
|
||||
"profile does not expect";
|
||||
best.reason += detail;
|
||||
}
|
||||
else if (rejected_span > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_span) +
|
||||
" arc(s) fitted cleanly but span too little or too much of a circle";
|
||||
best.reason += detail;
|
||||
}
|
||||
else if (rejected_rms > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_rms) +
|
||||
" run(s) of points fit a circle too loosely to be an arc — probably a corner "
|
||||
"or a flat surface";
|
||||
best.reason += detail;
|
||||
}
|
||||
else if (rejected_fit > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_fit) +
|
||||
" run(s) of points are collinear; a straight surface has no centre";
|
||||
}
|
||||
else if (rejected_points > 0)
|
||||
{
|
||||
best.reason = std::to_string(rejected_points) +
|
||||
" run(s) had fewer than min_arc_points; move closer or lower min_arc_points";
|
||||
}
|
||||
else
|
||||
{
|
||||
best.reason = "no run of points forms an arc";
|
||||
}
|
||||
|
||||
best.reason += " [" + std::to_string(lines.size()) + " segment(s) in the scan]";
|
||||
}
|
||||
|
||||
return best;
|
||||
}
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
195
src/circle_fit.cpp
Normal file
195
src/circle_fit.cpp
Normal file
@@ -0,0 +1,195 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — khớp đường tròn Taubin.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <dock_pattern_detector/circle_fit.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
/**
|
||||
* @brief Trần lặp Newton khi tìm nghiệm nhỏ nhất của đa thức đặc trưng.
|
||||
*
|
||||
* Newton ở đây xuất phát từ 0 và hội tụ trong vài vòng với dữ liệu lành. Trần này là để một chuỗi
|
||||
* điểm suy biến không treo control loop — cùng lý do với trần lặp trong `robot_line_extraction`.
|
||||
*/
|
||||
constexpr int kMaxNewtonIterations = 30;
|
||||
|
||||
/// [m] Dưới ngưỡng này thì tán xạ của chuỗi điểm coi như bằng 0: mọi điểm chồng lên nhau.
|
||||
constexpr double kMinScatter = 1e-12;
|
||||
|
||||
} // namespace
|
||||
|
||||
CircleFitResult fitCircle(const std::vector<double>& xs, const std::vector<double>& ys)
|
||||
{
|
||||
CircleFitResult out;
|
||||
|
||||
const std::size_t n = std::min(xs.size(), ys.size());
|
||||
if (n < 3)
|
||||
{
|
||||
return out; // Dưới ba điểm thì không có đường tròn nào để nói tới.
|
||||
}
|
||||
|
||||
// Dời về trọng tâm trước khi làm gì khác. Toạ độ trong frame cảm biến thường quanh vài mét, còn
|
||||
// bán kính dock quanh vài chục centimet; khớp thẳng trên số gốc là bình phương một đại lượng lớn
|
||||
// rồi trừ đi nhau, mất hết chữ số có nghĩa.
|
||||
double mean_x = 0.0;
|
||||
double mean_y = 0.0;
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
mean_x += xs[i];
|
||||
mean_y += ys[i];
|
||||
}
|
||||
mean_x /= static_cast<double>(n);
|
||||
mean_y /= static_cast<double>(n);
|
||||
|
||||
double m_xx = 0.0;
|
||||
double m_yy = 0.0;
|
||||
double m_xy = 0.0;
|
||||
double m_xz = 0.0;
|
||||
double m_yz = 0.0;
|
||||
double m_zz = 0.0;
|
||||
double m_z = 0.0;
|
||||
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const double u = xs[i] - mean_x;
|
||||
const double v = ys[i] - mean_y;
|
||||
const double z = u * u + v * v;
|
||||
m_xx += u * u;
|
||||
m_yy += v * v;
|
||||
m_xy += u * v;
|
||||
m_xz += u * z;
|
||||
m_yz += v * z;
|
||||
m_zz += z * z;
|
||||
m_z += z;
|
||||
}
|
||||
|
||||
const double inv_n = 1.0 / static_cast<double>(n);
|
||||
m_xx *= inv_n;
|
||||
m_yy *= inv_n;
|
||||
m_xy *= inv_n;
|
||||
m_xz *= inv_n;
|
||||
m_yz *= inv_n;
|
||||
m_zz *= inv_n;
|
||||
m_z *= inv_n;
|
||||
|
||||
if (m_xx + m_yy < kMinScatter)
|
||||
{
|
||||
return out; // Mọi điểm chồng lên nhau. Không có hướng, càng không có đường tròn.
|
||||
}
|
||||
|
||||
// Nghiệm nhỏ nhất của đa thức đặc trưng Taubin, tìm bằng Newton từ 0.
|
||||
const double cov_xy = m_xx * m_yy - m_xy * m_xy;
|
||||
const double var_z = m_zz - m_z * m_z;
|
||||
|
||||
const double a3 = 4.0 * m_z;
|
||||
const double a2 = -3.0 * m_z * m_z - m_zz;
|
||||
const double a1 = var_z * m_z + 4.0 * cov_xy * m_z - m_xz * m_xz - m_yz * m_yz;
|
||||
const double a0 = m_xz * (m_xz * m_yy - m_yz * m_xy) + m_yz * (m_yz * m_xx - m_xz * m_xy) -
|
||||
var_z * cov_xy;
|
||||
const double a22 = a2 + a2;
|
||||
const double a33 = a3 + a3 + a3;
|
||||
|
||||
double x = 0.0;
|
||||
double y = a0;
|
||||
for (int iter = 0; iter < kMaxNewtonIterations; ++iter)
|
||||
{
|
||||
const double dy = a1 + x * (a22 + a33 * x);
|
||||
if (std::fabs(dy) < 1e-18)
|
||||
{
|
||||
break; // Đạo hàm phẳng: không có bước Newton nào có nghĩa, dùng nghiệm đang có.
|
||||
}
|
||||
const double x_new = x - y / dy;
|
||||
if (!std::isfinite(x_new) || x_new == x)
|
||||
{
|
||||
break;
|
||||
}
|
||||
const double y_new = std::fabs(a0 + x_new * (a1 + x_new * (a2 + x_new * a3)));
|
||||
if (y_new >= std::fabs(y))
|
||||
{
|
||||
break; // Không cải thiện nữa. Nhận nghiệm đang có thay vì đi lang thang.
|
||||
}
|
||||
x = x_new;
|
||||
y = y_new;
|
||||
}
|
||||
|
||||
const double det = x * x - x * m_z + cov_xy;
|
||||
if (!std::isfinite(det) || std::fabs(det) < 1e-15)
|
||||
{
|
||||
// Định thức về 0 khi chuỗi điểm gần như THẲNG HÀNG: đường tròn khớp nhất là đường thẳng, tức
|
||||
// tâm ở vô cùng. Trả về không hợp lệ thay vì một tâm khổng lồ mà người gọi tưởng là thật.
|
||||
return out;
|
||||
}
|
||||
|
||||
const double center_u = (m_xz * (m_yy - x) - m_yz * m_xy) / det / 2.0;
|
||||
const double center_v = (m_yz * (m_xx - x) - m_xz * m_xy) / det / 2.0;
|
||||
const double radius = std::sqrt(center_u * center_u + center_v * center_v + m_z);
|
||||
|
||||
if (!std::isfinite(center_u) || !std::isfinite(center_v) || !std::isfinite(radius) ||
|
||||
radius <= 0.0)
|
||||
{
|
||||
return out;
|
||||
}
|
||||
|
||||
out.center_x = center_u + mean_x;
|
||||
out.center_y = center_v + mean_y;
|
||||
out.radius = radius;
|
||||
out.point_count = n;
|
||||
|
||||
// Sai số khớp và góc mở, đo lại trên chính đường tròn vừa tìm được.
|
||||
double sq_sum = 0.0;
|
||||
double angle_min = 0.0;
|
||||
double angle_max = 0.0;
|
||||
double prev_angle = 0.0;
|
||||
double unwrapped = 0.0;
|
||||
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const double dx = xs[i] - out.center_x;
|
||||
const double dy = ys[i] - out.center_y;
|
||||
const double d = std::hypot(dx, dy) - radius;
|
||||
sq_sum += d * d;
|
||||
|
||||
// Góc mở phải cộng dồn theo chuỗi rồi mới lấy biên, không lấy min/max của atan2 thô: một cung
|
||||
// vắt qua +-pi sẽ cho ra góc mở gần 2*pi trong khi nó chỉ vài độ.
|
||||
const double angle = std::atan2(dy, dx);
|
||||
if (i == 0)
|
||||
{
|
||||
prev_angle = angle;
|
||||
unwrapped = angle;
|
||||
angle_min = angle;
|
||||
angle_max = angle;
|
||||
continue;
|
||||
}
|
||||
double step = angle - prev_angle;
|
||||
while (step > M_PI)
|
||||
{
|
||||
step -= 2.0 * M_PI;
|
||||
}
|
||||
while (step < -M_PI)
|
||||
{
|
||||
step += 2.0 * M_PI;
|
||||
}
|
||||
unwrapped += step;
|
||||
prev_angle = angle;
|
||||
angle_min = std::min(angle_min, unwrapped);
|
||||
angle_max = std::max(angle_max, unwrapped);
|
||||
}
|
||||
|
||||
out.rms_error = std::sqrt(sq_sum / static_cast<double>(n));
|
||||
out.span = angle_max - angle_min;
|
||||
out.valid = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
@@ -124,6 +124,42 @@ bool DockProfile::validate(std::string& error) const
|
||||
error = "offset_x/offset_y/offset_yaw must be finite";
|
||||
return false;
|
||||
}
|
||||
if (pattern == PatternType::kArc)
|
||||
{
|
||||
if (!positive(arc_radius))
|
||||
{
|
||||
error = "arc_radius must be finite and > 0";
|
||||
return false;
|
||||
}
|
||||
if (!positive(arc_radius_tolerance) || arc_radius_tolerance >= arc_radius)
|
||||
{
|
||||
// Dung sai >= chính bán kính nghĩa là chấp nhận cả bán kính 0 — cổng vô nghĩa.
|
||||
error = "arc_radius_tolerance must be finite, > 0 and < arc_radius";
|
||||
return false;
|
||||
}
|
||||
if (!positive(arc_span) || arc_span > 2.0 * M_PI)
|
||||
{
|
||||
error = "arc_span must be finite, > 0 and <= 2*pi rad";
|
||||
return false;
|
||||
}
|
||||
if (!positive(arc_min_span) || arc_min_span > arc_span)
|
||||
{
|
||||
// Sàn cao hơn cả góc mở toàn phần thì không cung nào lọt được, kể cả cái máng thật.
|
||||
error = "arc_min_span must be finite, > 0 and <= arc_span";
|
||||
return false;
|
||||
}
|
||||
if (!positive(arc_max_rms))
|
||||
{
|
||||
// 0 nghĩa là đòi khớp hoàn hảo tuyệt đối — không phép đo nào của cảm biến thật đạt được.
|
||||
error = "arc_max_rms must be finite and > 0";
|
||||
return false;
|
||||
}
|
||||
if (min_arc_points < 3)
|
||||
{
|
||||
error = "min_arc_points must be >= 3; three points is the minimum for a circle";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (tape_enabled)
|
||||
{
|
||||
if (!positive(tape_spacing))
|
||||
@@ -152,6 +188,14 @@ bool DockProfile::validate(std::string& error) const
|
||||
error = "tape_min_intensity must be finite";
|
||||
return false;
|
||||
}
|
||||
if (pattern == PatternType::kArc)
|
||||
{
|
||||
// findTape quét theo chỉ số tia CỦA MỘT ĐOẠN THẲNG. Cung tròn không sinh ra đoạn thẳng nào
|
||||
// để quét, nên bật cờ này ở đây là khai một thứ sẽ không bao giờ chạy. Nói thẳng ra.
|
||||
error = "tape_enabled is not supported for pattern 'arc' yet; the tape search walks the ray "
|
||||
"span of a fitted line segment and an arc produces none";
|
||||
return false;
|
||||
}
|
||||
if (tape_spacing > 2.0 * wing_length)
|
||||
{
|
||||
// Hai dải dán TRÊN hai cánh, nên khoảng cách giữa chúng không thể vượt quá hai lần chiều dài
|
||||
@@ -176,11 +220,11 @@ bool DockProfile::validate(std::string& error) const
|
||||
error = "min_confidence must be in [0, 1]";
|
||||
return false;
|
||||
}
|
||||
if (pattern != PatternType::kV)
|
||||
if (pattern != PatternType::kV && pattern != PatternType::kArc)
|
||||
{
|
||||
// Nói thẳng thay vì nhận config rồi không bao giờ dò ra gì.
|
||||
error = std::string("pattern '") + toString(pattern) +
|
||||
"' is declared but not implemented yet; only 'v' is available";
|
||||
"' is declared but not implemented yet; available patterns are: v, arc";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
383
test/arc_pattern_matcher_test.cpp
Normal file
383
test/arc_pattern_matcher_test.cpp
Normal file
@@ -0,0 +1,383 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Kiểm khớp máng cong LÕM bằng scan TỔNG HỢP — dựng hình trước, sinh tia sau, biết trước đáp án.
|
||||
*
|
||||
* Bốn nhóm:
|
||||
* 1. dò đúng — điểm sâu nhất, hướng, offset, cung bị che một phần;
|
||||
* 2. TỪ CHỐI — đây mới là phần quan trọng: góc tường, mặt phẳng, trụ LỒI, bán kính sai;
|
||||
* 3. cổng tìm kiếm;
|
||||
* 4. 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/arc_pattern_matcher.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using dock_pattern_detector::ArcPatternMatcher;
|
||||
using dock_pattern_detector::Detection;
|
||||
using dock_pattern_detector::DockProfile;
|
||||
using dock_pattern_detector::PatternType;
|
||||
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 = 690, double angle_min = -0.9, double angle_max = 0.9)
|
||||
{
|
||||
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 Xấp xỉ một cung tròn bằng nhiều đoạn thẳng rất ngắn, để bộ chiếu tia dùng chung một mã.
|
||||
std::vector<Segment> arcSegments(double cx, double cy, double r, double a0, double span,
|
||||
std::size_t facets = 400)
|
||||
{
|
||||
std::vector<Segment> out;
|
||||
for (std::size_t i = 0; i + 1 < facets; ++i)
|
||||
{
|
||||
const double t0 = a0 + span * static_cast<double>(i) / static_cast<double>(facets - 1);
|
||||
const double t1 = a0 + span * static_cast<double>(i + 1) / static_cast<double>(facets - 1);
|
||||
out.push_back({ cx + r * std::cos(t0), cy + r * std::sin(t0), cx + r * std::cos(t1),
|
||||
cy + r * std::sin(t1) });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Máng LÕM ôm cảm biến: tâm ở @p center_x trên trục x, mặt cong ở XA hơn tâm.
|
||||
*
|
||||
* Cung được vẽ về phía +x tính từ tâm, nên mọi điểm mặt đều xa cảm biến hơn tâm — đúng định nghĩa
|
||||
* lõm mà matcher kiểm.
|
||||
*/
|
||||
std::vector<Segment> concaveCradle(double center_x, double r, double span)
|
||||
{
|
||||
return arcSegments(center_x, 0.0, r, -span / 2.0, span);
|
||||
}
|
||||
|
||||
/// @brief Trụ tròn LỒI: tâm ở @p center_x, mặt cong quay về phía cảm biến, tức GẦN hơn tâm.
|
||||
std::vector<Segment> convexCylinder(double center_x, double r, double span)
|
||||
{
|
||||
return arcSegments(center_x, 0.0, r, M_PI - span / 2.0, span);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
DockProfile arcProfile()
|
||||
{
|
||||
DockProfile p;
|
||||
p.pattern = PatternType::kArc;
|
||||
p.arc_radius = 0.40; // [m]
|
||||
p.arc_radius_tolerance = 0.06; // [m]
|
||||
p.arc_span = 2.2; // [rad] toàn phần của máng
|
||||
p.arc_min_span = 0.52; // [rad]
|
||||
p.arc_max_rms = 0.010; // [m]
|
||||
p.min_arc_points = 8;
|
||||
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;
|
||||
}
|
||||
|
||||
class Rig
|
||||
{
|
||||
public:
|
||||
explicit Rig(const DockProfile& profile = arcProfile())
|
||||
{
|
||||
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_;
|
||||
ArcPatternMatcher matcher_;
|
||||
std::vector<Line> lines_;
|
||||
};
|
||||
|
||||
// ================================================================================================
|
||||
// 1. Dò đúng
|
||||
// ================================================================================================
|
||||
|
||||
TEST(ArcPatternMatcher, FindsTheDeepestPointOfACradle)
|
||||
{
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
// Tâm ở x = 1.60, bán kính 0.40 -> điểm sâu nhất ở x = 2.00.
|
||||
const Detection d = rig.run(concaveCradle(1.60, 0.40, 2.0));
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.apex_x, 2.00, 0.02);
|
||||
EXPECT_NEAR(d.apex_y, 0.00, 0.02);
|
||||
EXPECT_NEAR(d.measured_arc_radius, 0.40, 0.02);
|
||||
EXPECT_NEAR(d.arc_center_x, 1.60, 0.02);
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, YawPointsBackAtTheSensor)
|
||||
{
|
||||
// Lệch 180 độ ở đây là robot lùi vào máng thay vì tiến vào, nên hướng phải canh riêng.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(concaveCradle(1.60, 0.40, 2.0));
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.yaw, M_PI, 0.05); // tam o +x, nen huong ve cam bien la -x
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, TheOffsetMovesTheTargetOutTowardsTheRobot)
|
||||
{
|
||||
DockProfile p = arcProfile();
|
||||
p.offset_x = 0.90; // [m]
|
||||
Rig rig(p);
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(concaveCradle(1.60, 0.40, 2.0));
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.apex_x, 2.00, 0.02);
|
||||
EXPECT_NEAR(d.x, 2.00 - 0.90, 0.03) << "offset phai keo dich VE PHIA robot";
|
||||
EXPECT_NEAR(d.y, 0.00, 0.03);
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, APartlyOccludedArcStillGivesTheSameDeepestPoint)
|
||||
{
|
||||
// Đây là lý do điểm đích được định nghĩa từ TÂM và BÁN KÍNH chứ không phải trung điểm cung quan
|
||||
// sát được: che một bên thì trung điểm dịch ngay, còn tâm thì không.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection full = rig.run(concaveCradle(1.60, 0.40, 2.0));
|
||||
ASSERT_TRUE(full.valid) << full.reason;
|
||||
|
||||
// Chỉ còn nửa bên phải của cung.
|
||||
const Detection half = rig.run(arcSegments(1.60, 0.0, 0.40, 0.0, 1.0));
|
||||
ASSERT_TRUE(half.valid) << half.reason;
|
||||
|
||||
EXPECT_NEAR(half.apex_x, full.apex_x, 0.03);
|
||||
EXPECT_NEAR(half.apex_y, full.apex_y, 0.03);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 2. Từ chối — phần quan trọng nhất
|
||||
// ================================================================================================
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesARightAngledCorner)
|
||||
{
|
||||
// Mọi tập điểm đều khớp được vào một đường tròn NÀO ĐÓ. Cổng duy nhất phân biệt là sai số khớp.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const std::vector<Segment> corner = { { 2.0, -0.4, 2.0, 0.0 }, { 2.0, 0.0, 2.4, 0.0 } };
|
||||
const Detection d = rig.run(corner);
|
||||
EXPECT_FALSE(d.valid) << "goc tuong bi nhan la mang cong";
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAFlatWall)
|
||||
{
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run({ { 2.0, -1.0, 2.0, 1.0 } });
|
||||
EXPECT_FALSE(d.valid) << "tuong phang bi nhan la mang cong";
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAConvexCylinder)
|
||||
{
|
||||
// Cùng bán kính, cùng chỗ, chỉ khác chiều cong. Nhận nhầm là pose đích rơi ra SAU mặt trụ, tức
|
||||
// robot được lệnh lái vào trong vật.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(convexCylinder(2.40, 0.40, 2.0));
|
||||
EXPECT_FALSE(d.valid) << d.reason;
|
||||
EXPECT_NE(d.reason.find("WRONG WAY"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAnArcOfTheWrongRadius)
|
||||
{
|
||||
Rig rig; // profile doi 0.40 m
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(concaveCradle(1.20, 0.80, 2.0));
|
||||
EXPECT_FALSE(d.valid) << d.reason;
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAnArcThatShowsTooLittleOfItself)
|
||||
{
|
||||
// Cổng SỐ HỌC, không phải hình học: dưới ngưỡng này bán kính khớp bắt đầu lệch nhanh, nên một
|
||||
// mẩu cung 15 độ không được phép quyết định robot đỗ ở đâu.
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(arcSegments(1.60, 0.0, 0.40, -0.13, 0.26)); // ~15 do
|
||||
EXPECT_FALSE(d.valid) << d.reason;
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAnArcThatSpansMoreThanTheProfileSays)
|
||||
{
|
||||
DockProfile p = arcProfile();
|
||||
p.arc_span = 1.0; // [rad] mang that chi mo 1.0 rad
|
||||
Rig rig(p);
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(concaveCradle(1.60, 0.40, 2.6)); // gan tron nua duong tron
|
||||
EXPECT_FALSE(d.valid) << d.reason;
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAScanWithNoSegments)
|
||||
{
|
||||
Rig rig;
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run({});
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_NE(d.reason.find("no line segments"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 3. Cổng tìm kiếm
|
||||
// ================================================================================================
|
||||
|
||||
TEST(ArcPatternMatcher, ThePriorGateRejectsACradleInTheWrongPlace)
|
||||
{
|
||||
DockProfile p = arcProfile();
|
||||
p.has_prior = true;
|
||||
p.prior_x = 5.0; // [m] cho doi mang o cho khac han
|
||||
p.prior_y = 0.0;
|
||||
p.search_radius = 0.5; // [m]
|
||||
Rig rig(p);
|
||||
ASSERT_TRUE(rig.ok_) << rig.error_;
|
||||
|
||||
const Detection d = rig.run(concaveCradle(1.60, 0.40, 2.0));
|
||||
EXPECT_FALSE(d.valid) << d.reason;
|
||||
EXPECT_NE(d.reason.find("search gate"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 4. Config hỏng
|
||||
// ================================================================================================
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAProfileThatCanNeverMatch)
|
||||
{
|
||||
std::string error;
|
||||
ArcPatternMatcher m;
|
||||
|
||||
DockProfile p = arcProfile();
|
||||
p.arc_radius_tolerance = p.arc_radius; // dung sai nuot tron phep do
|
||||
EXPECT_FALSE(m.configure(p, error));
|
||||
EXPECT_NE(error.find("arc_radius_tolerance"), std::string::npos) << error;
|
||||
|
||||
p = arcProfile();
|
||||
p.arc_min_span = p.arc_span + 0.1; // san cao hon tran: khong cung nao lot
|
||||
EXPECT_FALSE(m.configure(p, error));
|
||||
EXPECT_NE(error.find("arc_min_span"), std::string::npos) << error;
|
||||
|
||||
p = arcProfile();
|
||||
p.arc_max_rms = 0.0; // doi khop hoan hao tuyet doi
|
||||
EXPECT_FALSE(m.configure(p, error));
|
||||
EXPECT_NE(error.find("arc_max_rms"), std::string::npos) << error;
|
||||
|
||||
p = arcProfile();
|
||||
p.min_arc_points = 2;
|
||||
EXPECT_FALSE(m.configure(p, error));
|
||||
EXPECT_NE(error.find("min_arc_points"), std::string::npos) << error;
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesAProfileForADifferentPattern)
|
||||
{
|
||||
std::string error;
|
||||
ArcPatternMatcher m;
|
||||
|
||||
DockProfile p = arcProfile();
|
||||
p.pattern = PatternType::kV;
|
||||
EXPECT_FALSE(m.configure(p, error)) << "matcher cung nhan profile chu V";
|
||||
}
|
||||
|
||||
TEST(ArcPatternMatcher, RefusesTapeOnAnArcProfileInsteadOfSilentlyIgnoringIt)
|
||||
{
|
||||
// findTape quét theo chỉ số tia của MỘT ĐOẠN THẲNG; cung tròn không sinh ra đoạn nào để quét.
|
||||
// Nhận cờ rồi lặng lẽ bỏ qua là để người vận hành tưởng cổng phản quang đang bảo vệ mình.
|
||||
std::string error;
|
||||
ArcPatternMatcher m;
|
||||
|
||||
DockProfile p = arcProfile();
|
||||
p.tape_enabled = true;
|
||||
EXPECT_FALSE(m.configure(p, error));
|
||||
EXPECT_NE(error.find("tape_enabled"), std::string::npos) << error;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
249
test/circle_fit_test.cpp
Normal file
249
test/circle_fit_test.cpp
Normal file
@@ -0,0 +1,249 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Kiểm khớp đường tròn bằng điểm DỰNG SẴN trên một đường tròn biết trước, nên biết trước đáp án.
|
||||
*
|
||||
* Bốn nhóm:
|
||||
* 1. khớp đúng — cung đầy, cung ngắn, tâm lệch khỏi gốc;
|
||||
* 2. vì sao Taubin chứ không phải Kåsa — độ lệch trên cung ngắn;
|
||||
* 3. TỪ CHỐI — điểm thẳng hàng, điểm chồng nhau, quá ít điểm;
|
||||
* 4. rms_error và span có nói đúng chuyện gì không.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#include <dock_pattern_detector/circle_fit.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
using dock_pattern_detector::CircleFitResult;
|
||||
using dock_pattern_detector::fitCircle;
|
||||
|
||||
/**
|
||||
* @brief Sinh @p n điểm cách đều trên cung của đường tròn (@p cx, @p cy, @p r).
|
||||
*
|
||||
* @param a0 [rad] góc bắt đầu
|
||||
* @param span [rad] góc mở của cung
|
||||
* @param noise [m] lệch chuẩn của nhiễu theo phương BÁN KÍNH — đúng cách một LiDAR sai: nó đo sai
|
||||
* cự ly chứ không đo sai góc.
|
||||
*/
|
||||
void arcPoints(double cx, double cy, double r, double a0, double span, std::size_t n,
|
||||
std::vector<double>& xs, std::vector<double>& ys, double noise = 0.0,
|
||||
unsigned seed = 1)
|
||||
{
|
||||
xs.clear();
|
||||
ys.clear();
|
||||
std::mt19937 rng(seed);
|
||||
std::normal_distribution<double> nd(0.0, noise);
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const double t = a0 + span * static_cast<double>(i) / static_cast<double>(n - 1);
|
||||
const double rr = r + (noise > 0.0 ? nd(rng) : 0.0);
|
||||
xs.push_back(cx + rr * std::cos(t));
|
||||
ys.push_back(cy + rr * std::sin(t));
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 1. Khớp đúng
|
||||
// ================================================================================================
|
||||
|
||||
TEST(CircleFit, RecoversAFullCircle)
|
||||
{
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(0.0, 0.0, 0.5, 0.0, 2.0 * M_PI, 60, xs, ys);
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_NEAR(f.center_x, 0.0, 1e-6);
|
||||
EXPECT_NEAR(f.center_y, 0.0, 1e-6);
|
||||
EXPECT_NEAR(f.radius, 0.5, 1e-6);
|
||||
EXPECT_LT(f.rms_error, 1e-9);
|
||||
}
|
||||
|
||||
TEST(CircleFit, RecoversACircleWhoseCentreIsNotAtTheOrigin)
|
||||
{
|
||||
// Trạm dock nằm cách cảm biến vài mét trong khi bán kính chỉ vài chục centimet. Khớp thẳng trên
|
||||
// toạ độ gốc là bình phương một số lớn rồi trừ nhau — mất chữ số có nghĩa. Hàm dời về trọng tâm
|
||||
// trước, và test này canh đúng chỗ đó.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(12.4, -9.8, 0.35, 1.0, 1.2, 40, xs, ys);
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_NEAR(f.center_x, 12.4, 1e-5);
|
||||
EXPECT_NEAR(f.center_y, -9.8, 1e-5);
|
||||
EXPECT_NEAR(f.radius, 0.35, 1e-5);
|
||||
}
|
||||
|
||||
TEST(CircleFit, RecoversAShortArc)
|
||||
{
|
||||
// 40 độ là mức trạm dock thường lộ ra khi robot nhìn chếch.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(2.0, 0.3, 0.40, 2.6, 40.0 * M_PI / 180.0, 20, xs, ys);
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_NEAR(f.radius, 0.40, 1e-4);
|
||||
EXPECT_NEAR(f.center_x, 2.0, 1e-4);
|
||||
EXPECT_NEAR(f.center_y, 0.3, 1e-4);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 2. Vì sao Taubin
|
||||
// ================================================================================================
|
||||
|
||||
TEST(CircleFit, AShortNoisyArcDoesNotCollapseTheRadius)
|
||||
{
|
||||
// Đây là lý do dùng Taubin thay cho Kåsa. Kåsa tối thiểu hoá `(x^2+y^2 - ...)` nên trên cung ngắn
|
||||
// có nhiễu nó kéo bán kính XUỐNG một cách hệ thống — không phải nhiễu, mà là lệch: chạy 30 hạt
|
||||
// giống khác nhau thì trung bình vẫn thấp hơn thật. Trạm bán kính 0.40 m bị chấm thành 0.30 m
|
||||
// rồi rớt cổng `radius_tolerance`, và triệu chứng là "dò mãi không ra" chứ không phải một lỗi.
|
||||
//
|
||||
// Lấy trung bình trên nhiều hạt giống chứ không một lượt: một lượt đơn lẻ không phân biệt được
|
||||
// lệch với nhiễu.
|
||||
const double truth = 0.40;
|
||||
double sum = 0.0;
|
||||
int runs = 0;
|
||||
|
||||
for (unsigned seed = 1; seed <= 30; ++seed)
|
||||
{
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(2.0, 0.0, truth, 2.7, 45.0 * M_PI / 180.0, 18, xs, ys, 0.003, seed);
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
if (f.valid)
|
||||
{
|
||||
sum += f.radius;
|
||||
++runs;
|
||||
}
|
||||
}
|
||||
|
||||
ASSERT_GT(runs, 25);
|
||||
const double mean_radius = sum / runs;
|
||||
EXPECT_NEAR(mean_radius, truth, 0.06) << "ban kinh trung binh " << mean_radius;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 3. Từ chối
|
||||
// ================================================================================================
|
||||
|
||||
TEST(CircleFit, RefusesCollinearPoints)
|
||||
{
|
||||
// Đường tròn khớp nhất với một đoạn thẳng là đường tròn bán kính vô cùng. Trả về một tâm khổng lồ
|
||||
// mà người gọi tưởng là thật thì tệ hơn nhiều so với nói thẳng là không khớp được.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
xs.push_back(1.0 + 0.02 * i);
|
||||
ys.push_back(2.0);
|
||||
}
|
||||
|
||||
EXPECT_FALSE(fitCircle(xs, ys).valid);
|
||||
}
|
||||
|
||||
TEST(CircleFit, RefusesPointsAllAtTheSameSpot)
|
||||
{
|
||||
const std::vector<double> xs(10, 1.5);
|
||||
const std::vector<double> ys(10, -0.5);
|
||||
EXPECT_FALSE(fitCircle(xs, ys).valid);
|
||||
}
|
||||
|
||||
TEST(CircleFit, RefusesFewerThanThreePoints)
|
||||
{
|
||||
EXPECT_FALSE(fitCircle({}, {}).valid);
|
||||
EXPECT_FALSE(fitCircle({ 1.0 }, { 1.0 }).valid);
|
||||
EXPECT_FALSE(fitCircle({ 1.0, 2.0 }, { 1.0, 2.0 }).valid);
|
||||
}
|
||||
|
||||
TEST(CircleFit, UsesOnlyAsManyPointsAsBothArraysHave)
|
||||
{
|
||||
// Hai mảng lệch độ dài là lỗi của người gọi, nhưng đọc tràn mảng thì không phải cách báo lỗi.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(0.0, 0.0, 0.5, 0.0, 1.5, 20, xs, ys);
|
||||
xs.push_back(99.0); // thừa một phần tử
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_EQ(f.point_count, 20u);
|
||||
EXPECT_NEAR(f.radius, 0.5, 1e-6);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 4. rms_error và span
|
||||
// ================================================================================================
|
||||
|
||||
TEST(CircleFit, RmsErrorSeparatesARealArcFromABentCorner)
|
||||
{
|
||||
// Cổng chính chống nhầm. Hai đoạn thẳng gặp nhau ở một góc VẪN khớp được vào một đường tròn nào
|
||||
// đó — mọi tập điểm đều khớp được vào một đường tròn nào đó. Thứ phân biệt là sai số khớp.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(2.0, 0.0, 0.40, 2.6, 1.2, 30, xs, ys);
|
||||
const CircleFitResult arc = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(arc.valid);
|
||||
|
||||
// Góc vuông: 15 điểm dọc một cạnh, 15 điểm dọc cạnh kia.
|
||||
std::vector<double> cx;
|
||||
std::vector<double> cy;
|
||||
for (int i = 0; i < 15; ++i)
|
||||
{
|
||||
cx.push_back(2.0 - 0.02 * (14 - i));
|
||||
cy.push_back(0.0);
|
||||
}
|
||||
for (int i = 1; i <= 15; ++i)
|
||||
{
|
||||
cx.push_back(2.0);
|
||||
cy.push_back(0.02 * i);
|
||||
}
|
||||
const CircleFitResult corner = fitCircle(cx, cy);
|
||||
|
||||
if (corner.valid)
|
||||
{
|
||||
EXPECT_GT(corner.rms_error, 10.0 * std::max(arc.rms_error, 1e-6))
|
||||
<< "goc: " << corner.rms_error << " cung: " << arc.rms_error;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(CircleFit, SpanMeasuresTheArcNotTheWholeCircle)
|
||||
{
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(0.0, 0.0, 0.5, 0.2, 1.0, 25, xs, ys);
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_NEAR(f.span, 1.0, 1e-4);
|
||||
}
|
||||
|
||||
TEST(CircleFit, SpanIsCorrectForAnArcStraddlingPi)
|
||||
{
|
||||
// atan2 nhảy từ +pi sang -pi. Lấy min/max của góc thô thì một cung 30 độ vắt qua chỗ nhảy sẽ ra
|
||||
// góc mở gần 360 độ, và cổng `span` sẽ nhận đúng những cung nó phải loại.
|
||||
std::vector<double> xs;
|
||||
std::vector<double> ys;
|
||||
arcPoints(0.0, 0.0, 0.5, M_PI - 0.25, 0.5, 25, xs, ys);
|
||||
|
||||
const CircleFitResult f = fitCircle(xs, ys);
|
||||
ASSERT_TRUE(f.valid);
|
||||
EXPECT_NEAR(f.span, 0.5, 1e-4);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
Reference in New Issue
Block a user