feat(leg_pattern): add LegPatternMatcher for 4-leg trolleys
Finds a 4-leg trolley in a raw LaserScan without line extraction: shadow filter, leg clusters in ray order with free/occluded/attached edges, pair hypotheses from cart_opening/cart_depth/diagonal, then a Gauss-Newton pose fit over every leg point with an along-ray residual, Huber weights and backtracking. Gates: pair spacing after the fit, see-through leg positions, optional empty interior, entry side (entry tape / prior yaw / facing the sensor), optional prior, confidence, and ambiguity between two carts. LegProfile validates every key at load. Two gtests (7 + 23) run on a synthetic ray-cast scan (test/leg_scan_sim.h). Used by trolley_detection_action.
This commit is contained in:
@@ -65,6 +65,10 @@ add_library(dock_pattern_detector SHARED
|
||||
src/arc_pattern_matcher.cpp
|
||||
src/circle_fit.cpp
|
||||
src/v_pattern_matcher.cpp
|
||||
# Dò xe hàng 4 chân: đọc scan thô, không qua đoạn thẳng. Dùng bởi trolley_detection_action.
|
||||
src/leg_profile.cpp
|
||||
src/leg_pose_fit.cpp
|
||||
src/leg_pattern_matcher.cpp
|
||||
)
|
||||
|
||||
target_compile_options(dock_pattern_detector PRIVATE -Wall -Wextra)
|
||||
@@ -230,4 +234,34 @@ if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN)
|
||||
)
|
||||
endif()
|
||||
|
||||
# Hai test của bộ dò xe hàng dùng chung bộ dựng scan tổng hợp `test/leg_scan_sim.h`.
|
||||
foreach(leg_test leg_pose_fit_test leg_pattern_matcher_test)
|
||||
catkin_add_gtest(${leg_test} test/${leg_test}.cpp)
|
||||
|
||||
if(TARGET ${leg_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(${leg_test} PROPERTIES EXCLUDE_FROM_ALL FALSE)
|
||||
|
||||
target_compile_options(${leg_test} PRIVATE -Wall -Wextra)
|
||||
|
||||
target_include_directories(${leg_test}
|
||||
PRIVATE
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/include
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/test
|
||||
)
|
||||
|
||||
target_include_directories(${leg_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(${leg_test}
|
||||
dock_pattern_detector
|
||||
pthread
|
||||
)
|
||||
endif()
|
||||
endforeach()
|
||||
|
||||
endif()
|
||||
|
||||
20
README.md
20
README.md
@@ -151,11 +151,31 @@ config rồi không bao giờ dò ra gì — hai thứ đó nhìn giống hệt
|
||||
tại, hoặc trượt cái hình có thật. Giá trị mặc định trong code chỉ để test chạy, **không phải** giá
|
||||
trị cho trạm thật.
|
||||
|
||||
## Xe hàng 4 chân — `LegPatternMatcher`
|
||||
|
||||
Bộ dò thứ ba, **không** thuộc enum `PatternType` và không dùng `DockProfile`: profile riêng
|
||||
`LegProfile` (`leg_profile.h`), đầu vào là `ranges` + `intensities` THÔ chứ không phải đoạn thẳng —
|
||||
chân xe chỉ là một cụm vài tia. Handler dùng nó là gói `trolley_detection_action`; chuỗi sạc
|
||||
(`dock_pattern_action`) không đổi.
|
||||
|
||||
Các bước: lọc điểm kéo đuôi → tách cụm theo thứ tự tia → phân loại mép cụm (tự do / bị che / dính
|
||||
tường) và bề rộng biểu kiến → giả thuyết từ cặp chân khớp `cart_opening` / `cart_depth` / đường chéo
|
||||
→ gán chân vào 4 góc, khớp tư thế Gauss-Newton trên **mọi điểm chân** theo mô hình biên chân
|
||||
(`leg_pose_fit.h`) → kiểm khoảng cách từng cặp chân → bằng chứng phủ định (tia đi xuyên chỗ một chân
|
||||
phải đứng thì loại) → lòng xe trống → chọn cạnh vào (dải `entry`, prior, hoặc cạnh quay về cảm
|
||||
biến) → cổng prior → từ chối khi hai xe điểm sát nhau ở hai chỗ.
|
||||
|
||||
Quy ước đầu ra giống V/arc: `center_yaw` là pháp tuyến cạnh vào hướng về cảm biến; lật theo cách
|
||||
robot chui (tiến/lùi) là việc của handler. Plan đầy đủ: `Test/docs/trolley_detection_action/` của
|
||||
workspace phát triển.
|
||||
|
||||
## Build và test
|
||||
|
||||
```bash
|
||||
catkin_make --pkg dock_pattern_detector
|
||||
./devel/lib/dock_pattern_detector/v_pattern_matcher_test # 16 test
|
||||
./devel/lib/dock_pattern_detector/leg_pose_fit_test
|
||||
./devel/lib/dock_pattern_detector/leg_pattern_matcher_test
|
||||
```
|
||||
|
||||
Test chạy đúng chuỗi mà handler sẽ chạy: dựng thế giới → chiếu tia → `robot_line_extraction` →
|
||||
|
||||
243
include/dock_pattern_detector/leg_pattern_matcher.h
Normal file
243
include/dock_pattern_detector/leg_pattern_matcher.h
Normal file
@@ -0,0 +1,243 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — tìm xe hàng 4 chân trong một LaserScan thô.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_LEG_PATTERN_MATCHER_H_
|
||||
#define DOCK_PATTERN_DETECTOR_LEG_PATTERN_MATCHER_H_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_line_extraction/types.h>
|
||||
|
||||
#include <dock_pattern_detector/leg_pose_fit.h>
|
||||
#include <dock_pattern_detector/leg_profile.h>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
|
||||
/// @brief Giới hạn range dùng được của lidar. [m]
|
||||
struct ScanLimits
|
||||
{
|
||||
double min_range = 0.10;
|
||||
double max_range = 3.0;
|
||||
/// [m] σ nhiễu range, làm trọng số khớp tư thế.
|
||||
double range_sigma = 0.01;
|
||||
};
|
||||
|
||||
/**
|
||||
* @struct LegDetection
|
||||
* @brief Kết quả dò xe hàng, trong **frame của scan**.
|
||||
*
|
||||
* Cùng quy ước với `Detection` của V/arc: `center_yaw` là pháp tuyến cạnh vào hướng RA phía cảm
|
||||
* biến; `x, y, yaw` = tâm cộng offset của profile theo đúng công thức V/arc. Lật hướng theo cách
|
||||
* robot chui (tiến/lùi) KHÔNG làm ở đây — đó là việc của handler.
|
||||
*/
|
||||
struct LegDetection
|
||||
{
|
||||
bool valid = false;
|
||||
|
||||
double x = 0.0; ///< [m] đích = tâm + offset
|
||||
double y = 0.0; ///< [m]
|
||||
double yaw = 0.0; ///< [rad]
|
||||
|
||||
double center_x = 0.0; ///< [m] tâm hình chữ nhật tâm chân
|
||||
double center_y = 0.0; ///< [m]
|
||||
double center_yaw = 0.0; ///< [rad] pháp tuyến cạnh vào, hướng về cảm biến
|
||||
|
||||
double confidence = 0.0; ///< [-] trong [0, 1]
|
||||
|
||||
/// Vì sao không dò ra, hoặc rỗng khi dò ra. Nói rõ hỏng ở CỔNG NÀO.
|
||||
std::string reason;
|
||||
|
||||
int legs_seen = 0; ///< chân có cụm gán vào (đủ hoặc partial)
|
||||
int legs_partial = 0; ///< trong số đó, chân bị che một phần
|
||||
int legs_occluded = 0; ///< chân không thấy vì có vật gần hơn chắn
|
||||
int legs_distorted = 0; ///< có vật ở đúng chỗ nhưng cụm trượt cổng hình dạng
|
||||
int legs_out_of_view = 0; ///< chân ngoài quạt/tầm/scan
|
||||
|
||||
double fit_rms = 0.0; ///< [m]
|
||||
int fit_iterations = 0;
|
||||
|
||||
/// [m] Kích thước đo từ tâm thô của các chân thấy được; 0 = không đo được cạnh đó.
|
||||
double measured_opening = 0.0;
|
||||
double measured_depth = 0.0;
|
||||
|
||||
/// Số tia sáng trên từng chân (thứ tự @ref LegCorner), 0 khi dải tắt hoặc chân không thấy.
|
||||
std::array<std::size_t, kLegCount> tape_bright_rays = { { 0, 0, 0, 0 } };
|
||||
|
||||
std::size_t leg_candidates = 0; ///< cụm qua được cổng chân
|
||||
std::size_t hypotheses = 0; ///< giả thuyết xe đã xét
|
||||
std::size_t accepted = 0; ///< giả thuyết qua mọi cổng
|
||||
};
|
||||
|
||||
/**
|
||||
* @class LegPatternMatcher
|
||||
* @brief Dò xe hàng 4 chân từ `ranges` (+ `intensities` tuỳ chọn) của MỘT scan.
|
||||
*
|
||||
* Hình học thuần: không TF, không action, không ROS. Vào là scan thô; ra là pose trong frame của
|
||||
* scan. Không qua `LineExtractor`: chân xe là một cụm vài tia, không phải đoạn thẳng.
|
||||
*
|
||||
* ## Các bước
|
||||
*
|
||||
* 1. Lọc tia (range, quạt, cường độ) + lọc điểm kéo đuôi theo góc β.
|
||||
* 2. Tách cụm theo thứ tự tia.
|
||||
* 3. Phân loại cụm chân: mép tự do / bị che / dính; bề rộng biểu kiến; cắt điểm xa; dải `all`.
|
||||
* 4. Giả thuyết từ cặp chân khớp `cart_opening`, `cart_depth` hoặc đường chéo.
|
||||
* 5. Gán chân vào 4 góc dự đoán, khớp tư thế trên mọi điểm chân (@ref fitCartPose).
|
||||
* 6. Bằng chứng phủ định: tia đi xuyên qua chỗ một chân phải đứng → loại.
|
||||
* 7. Lòng xe trống (tuỳ chọn).
|
||||
* 8. Chọn cạnh vào: dải `entry` → prior yaw → cạnh quay về cảm biến.
|
||||
* 9. Cổng prior (trong `prior_frame`).
|
||||
* 10. Điểm tin.
|
||||
* 11. Mơ hồ: hai xe điểm sát nhau mà khác chỗ → từ chối cả lượt.
|
||||
*
|
||||
* Tất định: không ngẫu nhiên, thứ tự duyệt cố định. Buffer là member và giữ capacity, nên không
|
||||
* cấp phát lớn mỗi scan sau vài scan đầu.
|
||||
*
|
||||
* @note Không thread-safe. Một matcher cho một consumer.
|
||||
*/
|
||||
class LegPatternMatcher
|
||||
{
|
||||
public:
|
||||
LegPatternMatcher() = default;
|
||||
|
||||
/// @brief Nhận profile. Sai miền thì giữ bộ cũ và trả false.
|
||||
bool configure(const LegProfile& profile, std::string& error);
|
||||
|
||||
const LegProfile& profile() const
|
||||
{
|
||||
return profile_;
|
||||
}
|
||||
|
||||
bool configured() const
|
||||
{
|
||||
return configured_;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Dò xe trong một scan.
|
||||
*
|
||||
* @param geometry Hình dạng scan (`angle_min`, `angle_increment`, `size`).
|
||||
* @param ranges [m] Phải có đúng `geometry.size` phần tử.
|
||||
* @param intensities Có thể rỗng; chỉ đọc khi `tape_enabled`.
|
||||
* @param limits Range dùng được + σ nhiễu.
|
||||
* @param scan_in_prior_frame Pose của frame scan trong `prior_frame` (2D). Prior và quạt tìm
|
||||
* kiếm được tính trên điểm đã đổi sang frame này.
|
||||
*/
|
||||
LegDetection match(const robot_line_extraction::ScanGeometry& geometry,
|
||||
const std::vector<double>& ranges, const std::vector<float>& intensities,
|
||||
const ScanLimits& limits, const Pose2D& scan_in_prior_frame);
|
||||
|
||||
private:
|
||||
struct Ray
|
||||
{
|
||||
double range = 0.0; // [m]
|
||||
double x = 0.0; // [m] frame scan
|
||||
double y = 0.0; // [m]
|
||||
bool valid = false; // range hữu hạn, trong giới hạn
|
||||
bool in_fan = true; // trong quạt tìm kiếm
|
||||
bool shadow = false; // điểm kéo đuôi, đã bỏ
|
||||
bool bright = false; // cường độ ≥ ngưỡng (chỉ khi tape_enabled)
|
||||
};
|
||||
|
||||
struct LegCandidate
|
||||
{
|
||||
std::size_t first = 0; // chỉ số tia đầu/cuối của cụm (sau cắt)
|
||||
std::size_t last = 0;
|
||||
double rough_x = 0.0; // [m] tâm thô
|
||||
double rough_y = 0.0;
|
||||
double r_min = 0.0; // [m]
|
||||
bool partial = false;
|
||||
std::size_t bright = 0;
|
||||
std::vector<std::size_t> points; // chỉ số tia thuộc chân
|
||||
};
|
||||
|
||||
struct Hypothesis
|
||||
{
|
||||
Pose2D pose; // hệ xe trong frame scan; yaw = pháp tuyến cạnh vào hướng về cảm biến
|
||||
std::array<int, kLegCount> legs = { { -1, -1, -1, -1 } }; // chỉ số LegCandidate theo góc
|
||||
double confidence = 0.0;
|
||||
int stage = 0; // cổng cuối cùng đã tới (xem `Stage` trong .cpp)
|
||||
std::string failure; // chi tiết khi bị loại
|
||||
LegDetection detail; // điền khi qua mọi cổng
|
||||
};
|
||||
|
||||
struct AssocPair
|
||||
{
|
||||
double distance = 0.0;
|
||||
int corner = 0;
|
||||
int leg = 0;
|
||||
};
|
||||
|
||||
bool usable(std::size_t i) const
|
||||
{
|
||||
return rays_[i].valid && rays_[i].in_fan && !rays_[i].shadow;
|
||||
}
|
||||
|
||||
void prepareRays(const robot_line_extraction::ScanGeometry& geometry,
|
||||
const std::vector<double>& ranges, const std::vector<float>& intensities,
|
||||
const ScanLimits& limits, const Pose2D& scan_in_prior_frame);
|
||||
void filterShadows(double dtheta);
|
||||
void buildCandidates(double dtheta);
|
||||
void processCluster(double dtheta);
|
||||
|
||||
/// @brief Phân loại mép bên ngoài tia @p edge theo hướng @p step (−1 / +1).
|
||||
/// @return 0 tự do, 1 bị che, 2 dính.
|
||||
int classifyEdge(std::size_t edge, int step) const;
|
||||
|
||||
void generateHypotheses(double dtheta, const Pose2D& scan_in_prior_frame);
|
||||
void addHypothesis(double cx, double cy, double axis, const Pose2D& scan_in_prior_frame);
|
||||
|
||||
/// @brief Gán cụm chân vào 4 góc dự đoán của @p h. @return số góc có chân.
|
||||
int associate(Hypothesis& h, double dtheta);
|
||||
|
||||
/// @brief Chạy bước 5–10 cho một giả thuyết; ghi `stage` và `failure`. @return true khi qua hết.
|
||||
bool evaluate(Hypothesis& h, const ScanLimits& limits, const Pose2D& scan_in_prior_frame,
|
||||
double dtheta);
|
||||
|
||||
/// @brief Phân loại một góc không có chân: 0 ngoài tầm, 1 bị che, 2 có vật méo, 3 tia xuyên qua.
|
||||
int classifyMissingCorner(double px, double py, const ScanLimits& limits) const;
|
||||
|
||||
/// @brief Đếm chân bị che / méo / ngoài tầm / tia xuyên qua của các góc chưa có chân.
|
||||
void classifyMissingCorners(const Hypothesis& h, const ScanLimits& limits, int& occluded,
|
||||
int& distorted, int& out_of_view, int& see_through) const;
|
||||
|
||||
std::string describeClusterRejections() const;
|
||||
|
||||
LegProfile profile_;
|
||||
LegModel model_;
|
||||
bool configured_ = false;
|
||||
|
||||
// Hình dạng scan đang xử lý.
|
||||
double angle_min_ = 0.0;
|
||||
double angle_increment_ = 0.0;
|
||||
double min_range_ = 0.0;
|
||||
|
||||
// Buffer dùng lại giữa các scan.
|
||||
std::vector<Ray> rays_;
|
||||
std::vector<std::size_t> cluster_;
|
||||
std::vector<LegCandidate> legs_;
|
||||
std::vector<Hypothesis> hypotheses_;
|
||||
std::vector<FitPoint> fit_points_;
|
||||
std::vector<AssocPair> assoc_pairs_;
|
||||
|
||||
// Đếm lý do loại cụm (bước 3) — để nói ra cổng nào chặn.
|
||||
std::size_t clusters_ = 0;
|
||||
std::size_t rejected_attached_ = 0;
|
||||
std::size_t rejected_width_ = 0;
|
||||
std::size_t rejected_points_ = 0;
|
||||
std::size_t rejected_tape_ = 0;
|
||||
double width_miss_ = 0.0; // [m] bề rộng của cụm trượt cổng bề rộng sát nhất
|
||||
bool truncated_ = false;
|
||||
};
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_LEG_PATTERN_MATCHER_H_
|
||||
124
include/dock_pattern_detector/leg_pose_fit.h
Normal file
124
include/dock_pattern_detector/leg_pose_fit.h
Normal file
@@ -0,0 +1,124 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — khớp tư thế xe hàng 4 chân trên toàn bộ điểm chân.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_LEG_POSE_FIT_H_
|
||||
#define DOCK_PATTERN_DETECTOR_LEG_POSE_FIT_H_
|
||||
|
||||
#include <array>
|
||||
#include <cstddef>
|
||||
#include <vector>
|
||||
|
||||
#include <dock_pattern_detector/leg_profile.h>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
|
||||
/// @brief Pose phẳng. [m, m, rad]
|
||||
struct Pose2D
|
||||
{
|
||||
double x = 0.0;
|
||||
double y = 0.0;
|
||||
double yaw = 0.0;
|
||||
};
|
||||
|
||||
/// @brief Góc của xe, đánh số cố định trong hệ của xe.
|
||||
enum LegCorner : int
|
||||
{
|
||||
kEntryLeft = 0, ///< (+depth/2, +opening/2)
|
||||
kEntryRight = 1, ///< (+depth/2, −opening/2)
|
||||
kFarLeft = 2, ///< (−depth/2, +opening/2)
|
||||
kFarRight = 3 ///< (−depth/2, −opening/2)
|
||||
};
|
||||
|
||||
constexpr int kLegCount = 4;
|
||||
|
||||
/**
|
||||
* @struct LegModel
|
||||
* @brief Mô hình hình học của xe: vị trí 4 chân và biên của từng chân.
|
||||
*
|
||||
* **Hệ của xe:** gốc ở tâm hình chữ nhật tâm chân; trục x là pháp tuyến cạnh vào hướng RA ngoài
|
||||
* (cạnh vào nằm ở x = +depth/2); trục y sang trái. Cùng quy ước với V/arc: yaw của xe trỏ về phía
|
||||
* cảm biến khi robot đứng trước cạnh vào.
|
||||
*/
|
||||
struct LegModel
|
||||
{
|
||||
double cart_opening = 0.0; ///< [m]
|
||||
double cart_depth = 0.0; ///< [m]
|
||||
LegShape shape = LegShape::kBox;
|
||||
double leg_width = 0.0; ///< [m] dọc trục y của xe
|
||||
double leg_depth = 0.0; ///< [m] dọc trục x của xe (đã áp mặc định)
|
||||
double leg_yaw_offset = 0.0; ///< [rad]
|
||||
|
||||
static LegModel fromProfile(const LegProfile& profile);
|
||||
|
||||
/// @brief Tâm chân @p corner trong hệ của xe.
|
||||
std::array<double, 2> corner(int corner) const;
|
||||
|
||||
/**
|
||||
* @brief [m] Khoảng cách có dấu từ điểm (@p px, @p py) — trong hệ của xe — tới biên chân @p corner.
|
||||
*
|
||||
* Dương ngoài chân, âm trong chân, 0 trên mặt. box: SDF hình chữ nhật xoay `leg_yaw_offset`;
|
||||
* round: `‖p − c‖ − leg_width/2` — khoảng cách hình học, không phải dạng đại số `‖p − c‖² − r²`
|
||||
* (dạng đó lệch theo khoảng cách tới tâm).
|
||||
*/
|
||||
double signedDistance(int corner, double px, double py) const;
|
||||
};
|
||||
|
||||
/// @brief Một điểm scan đã gán cho một chân. Cảm biến ở gốc frame scan, nên hướng tia suy từ (x, y).
|
||||
struct FitPoint
|
||||
{
|
||||
double x = 0.0; ///< [m] frame của scan
|
||||
double y = 0.0; ///< [m]
|
||||
int corner = 0; ///< chân mà điểm thuộc về
|
||||
};
|
||||
|
||||
/// @brief Kết quả khớp tư thế.
|
||||
struct PoseFitResult
|
||||
{
|
||||
bool valid = false;
|
||||
Pose2D pose; ///< pose của xe trong frame của scan
|
||||
double rms = 0.0; ///< [m] RMS phần dư hình học
|
||||
double normalized_rms = 0.0; ///< [-] RMS của phần dư chia σ kỳ vọng của từng điểm
|
||||
int iterations = 0;
|
||||
bool converged = false;
|
||||
};
|
||||
|
||||
/// @brief Tham số mô hình nhiễu của lidar, dùng làm trọng số.
|
||||
struct FitNoise
|
||||
{
|
||||
double range_sigma = 0.01; ///< [m] σ nhiễu range
|
||||
double angle_increment = 0.0; ///< [rad] |Δθ| giữa hai tia
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Procrustes 2D nghiệm đóng: pose sao cho model[i] (hệ xe) rơi vào scan[i] (frame scan).
|
||||
* @return false nếu ít hơn 2 cặp hoặc các điểm model trùng nhau.
|
||||
*/
|
||||
bool procrustes2D(const std::vector<std::array<double, 2>>& model,
|
||||
const std::vector<std::array<double, 2>>& scan, Pose2D& out);
|
||||
|
||||
/**
|
||||
* @brief Khớp pose xe trên mọi điểm chân bằng Gauss-Newton 3 bậc tự do có trọng số + Huber.
|
||||
*
|
||||
* Phần dư, với cảm biến ở gốc frame scan:
|
||||
* - tia của điểm CẮT chân dự đoán: cự ly dự đoán dọc tia − cự ly đo, σ = `range_sigma`. Đúng chiều
|
||||
* nhiễu của lidar, và biết mặt nào của chân đang quay về cảm biến;
|
||||
* - tia TRƯỢT chân (điểm mép khi pose còn lệch): khoảng cách có dấu tới biên chân
|
||||
* (@ref LegModel::signedDistance), σ chiếu theo pháp tuyến biên `n` lên hướng tia `u`:
|
||||
* `σ² = (n·u)²·range_sigma² + (n·u⊥)²·(r·Δθ/√12)²`.
|
||||
*
|
||||
* Huber δ = 2σ để điểm lai còn sót không kéo lệch. Mỗi bước chỉ được nhận nếu làm giảm tổng mất
|
||||
* mát Huber (chia đôi bước tới 6 lần). Dừng khi bước < 0.1 mm và < 0.01°, hoặc không bước nào làm
|
||||
* giảm mất mát, tối đa @p max_iterations vòng. Tất định.
|
||||
*/
|
||||
PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& points,
|
||||
const Pose2D& initial, const FitNoise& noise, int max_iterations = 10);
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_LEG_POSE_FIT_H_
|
||||
209
include/dock_pattern_detector/leg_profile.h
Normal file
209
include/dock_pattern_detector/leg_profile.h
Normal file
@@ -0,0 +1,209 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — hình học của MỘT loại xe hàng 4 chân.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_LEG_PROFILE_H_
|
||||
#define DOCK_PATTERN_DETECTOR_LEG_PROFILE_H_
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <string>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
|
||||
/// @brief Tiết diện chân ở độ cao mặt quét lidar.
|
||||
enum class LegShape
|
||||
{
|
||||
kBox, ///< Hộp vuông/chữ nhật `leg_width × leg_depth`, có thể xoay `leg_yaw_offset`.
|
||||
kRound ///< Ống tròn đường kính `leg_width`.
|
||||
};
|
||||
|
||||
const char* toString(LegShape shape);
|
||||
|
||||
/// @brief Đọc tên tiết diện từ YAML (`box` / `round`). @return false nếu tên không có thật.
|
||||
bool legShapeFromString(const std::string& name, LegShape& out, std::string& error);
|
||||
|
||||
/// @brief Chân nào mang dải phản quang. Chỉ có nghĩa khi `tape_enabled`.
|
||||
enum class TapeLegs
|
||||
{
|
||||
kAll, ///< Cả 4 chân: chống nhầm — cụm không sáng không thành chân.
|
||||
kEntry ///< Chỉ 2 chân cạnh vào: chống nhầm VÀ phân biệt đầu/đuôi xe.
|
||||
};
|
||||
|
||||
const char* toString(TapeLegs legs);
|
||||
|
||||
/// @brief Đọc tên từ YAML (`all` / `entry`). @return false nếu tên không có thật.
|
||||
bool tapeLegsFromString(const std::string& name, TapeLegs& out, std::string& error);
|
||||
|
||||
/**
|
||||
* @struct LegProfile
|
||||
* @brief Hình học + cổng của MỘT loại xe hàng 4 chân.
|
||||
*
|
||||
* Đặt tên theo **hướng robot chui**, không theo "dài/rộng": `cart_opening` là khoảng tâm–tâm hai
|
||||
* chân của CẠNH VÀO (ngang hướng chui), `cart_depth` là khoảng tâm–tâm DỌC hướng chui. Nhầm hai số
|
||||
* này là robot chui vào cạnh dài hơn hay ngắn hơn dự định — nên tên phải nói lên vai trò.
|
||||
*
|
||||
* Không có hằng số kích thước nào trong code: mọi số của xe nằm ở đây, nạp từ YAML.
|
||||
*/
|
||||
struct LegProfile
|
||||
{
|
||||
// --- Hình xe -----------------------------------------------------------------------------------
|
||||
|
||||
/// [m] Tâm–tâm hai chân của cạnh vào. Bắt buộc khai (0 = chưa khai, `validate()` từ chối).
|
||||
double cart_opening = 0.0;
|
||||
|
||||
/// [m] Tâm–tâm hai chân dọc hướng chui. Bắt buộc khai.
|
||||
double cart_depth = 0.0;
|
||||
|
||||
/**
|
||||
* [m] Dung sai cho cạnh và đường chéo khi ghép cặp chân.
|
||||
*
|
||||
* Tăng: chịu được xe méo/đo sai, nhưng dễ ghép chân của HAI xe đỗ sát nhau thành một xe. Phải
|
||||
* nhỏ hơn hiệu giữa `cart_opening` và khe chân của hai xe kề nhau trong kho.
|
||||
*/
|
||||
double cart_dim_tolerance = 0.04;
|
||||
|
||||
LegShape leg_shape = LegShape::kBox;
|
||||
|
||||
/// [m] box: cạnh dọc theo `cart_opening`; round: đường kính. Đo ở đúng độ cao lidar. Bắt buộc.
|
||||
double leg_width = 0.0;
|
||||
|
||||
/// [m] Dung sai bề rộng cụm chân so với bề rộng biểu kiến dự đoán.
|
||||
double leg_width_tolerance = 0.02;
|
||||
|
||||
/// [m] box: cạnh dọc theo `cart_depth`; 0 = bằng `leg_width` (chân vuông). round: phải là 0.
|
||||
double leg_depth = 0.0;
|
||||
|
||||
/// [rad] box: chân lắp xoay so với cạnh xe (lắp chéo 45° → 0.785). round: phải là 0.
|
||||
double leg_yaw_offset = 0.0;
|
||||
|
||||
// --- Tách cụm ----------------------------------------------------------------------------------
|
||||
|
||||
/// [tia] Số tia tối thiểu của một cụm chân, sau khi đã cắt điểm xa.
|
||||
std::size_t min_leg_points = 2;
|
||||
|
||||
/**
|
||||
* [rad] Lọc điểm kéo đuôi: góc tại điểm xa giữa tia và đoạn nối sang điểm kề nhỏ hơn ngần này thì
|
||||
* điểm xa là điểm lai (mixed pixel), bỏ. 0 = tắt.
|
||||
*/
|
||||
double shadow_min_angle = 0.17;
|
||||
|
||||
/// [m] Sàn ngưỡng ngắt cụm giữa hai tia kề nhau; ngưỡng thật là max(sàn này, 2·r·Δθ).
|
||||
double leg_cluster_gap = 0.05;
|
||||
|
||||
/// [m] Độ nhảy range tối thiểu để mép cụm là mép thật của một vật đứng tự do.
|
||||
double leg_min_depth_gap = 0.15;
|
||||
|
||||
// --- Mô hình -----------------------------------------------------------------------------------
|
||||
|
||||
/// Số chân phải THẤY (đủ hoặc bị che một phần). 2 chỉ được khi `has_prior`.
|
||||
int min_legs = 3;
|
||||
|
||||
/// [m] Sàn bán kính gán chân vào góc dự đoán; bán kính thật cộng thêm r·Δθ.
|
||||
double leg_assoc_radius = 0.06;
|
||||
|
||||
/// [điểm] Cổng lòng xe trống: điểm scan trong lòng xe vượt ngần này thì loại. < 0 = tắt.
|
||||
int max_interior_points = -1;
|
||||
|
||||
/// [m] Thu nhỏ hình chữ nhật tâm chân ngần này trước khi đếm điểm lòng xe.
|
||||
double interior_margin = 0.10;
|
||||
|
||||
/// [-] Hạng hai đạt ≥ (1 − ngần này) × điểm hạng nhất mà tâm khác chỗ → từ chối cả lượt.
|
||||
double ambiguity_margin = 0.15;
|
||||
|
||||
/// [-] Điểm tin tối thiểu, trong [0, 1].
|
||||
double min_confidence = 0.5;
|
||||
|
||||
// --- Dải phản quang ----------------------------------------------------------------------------
|
||||
|
||||
bool tape_enabled = false;
|
||||
TapeLegs tape_legs = TapeLegs::kAll;
|
||||
|
||||
/// [đơn vị cảm biến] Ngưỡng cường độ; thang riêng của từng lidar — PHẢI ĐO.
|
||||
double tape_min_intensity = 500.0;
|
||||
|
||||
/// [tia] Số tia sáng tối thiểu để một chân được coi là có dải.
|
||||
std::size_t tape_min_points = 1;
|
||||
|
||||
// --- Prior, trong `prior_frame` của handler (thường là base_link) -------------------------------
|
||||
|
||||
bool has_prior = false;
|
||||
double prior_x = 0.0; ///< [m]
|
||||
double prior_y = 0.0; ///< [m]
|
||||
|
||||
/// [rad] Hướng kỳ vọng của pháp tuyến cạnh vào (hướng RA phía cảm biến), trong `prior_frame`.
|
||||
double prior_yaw = 0.0;
|
||||
|
||||
/// [rad] Dung sai yaw quanh `prior_yaw`. π = không dùng yaw.
|
||||
double prior_yaw_tolerance = M_PI;
|
||||
|
||||
/// [m] Tâm xe cách (prior_x, prior_y) xa hơn ngần này thì loại. Chỉ dùng khi `has_prior`.
|
||||
double search_radius = 1.5;
|
||||
|
||||
/// [rad] Nửa góc quạt quanh trục x của `prior_frame`. ≤ 0 = không giới hạn quạt.
|
||||
double search_fov = 0.0;
|
||||
|
||||
// --- Offset đầu ra, cùng công thức với V/arc ----------------------------------------------------
|
||||
|
||||
/// [m] Dịch đích dọc pháp tuyến cạnh vào, hướng RA phía robot.
|
||||
double offset_x = 0.0;
|
||||
/// [m] Dịch đích sang trái trong hệ của xe.
|
||||
double offset_y = 0.0;
|
||||
/// [rad] Bù xe lắp lệch nhỏ. Không dùng để lật hướng chui — đó là việc của handler.
|
||||
double offset_yaw = 0.0;
|
||||
|
||||
/// @brief [m] Bề dày chân dọc `cart_depth` sau khi áp mặc định (0 → `leg_width`).
|
||||
double effectiveLegDepth() const
|
||||
{
|
||||
if (leg_shape == LegShape::kRound)
|
||||
{
|
||||
return leg_width;
|
||||
}
|
||||
return leg_depth > 0.0 ? leg_depth : leg_width;
|
||||
}
|
||||
|
||||
/// @brief [m] Bề rộng biểu kiến lớn nhất của một chân, nhìn từ mọi hướng.
|
||||
double maxApparentLegWidth() const
|
||||
{
|
||||
if (leg_shape == LegShape::kRound)
|
||||
{
|
||||
return leg_width;
|
||||
}
|
||||
return std::hypot(leg_width, effectiveLegDepth());
|
||||
}
|
||||
|
||||
/// @brief [m] Bề rộng biểu kiến nhỏ nhất của một chân (nhìn thẳng vào cạnh hẹp).
|
||||
double minApparentLegWidth() const
|
||||
{
|
||||
if (leg_shape == LegShape::kRound)
|
||||
{
|
||||
return leg_width;
|
||||
}
|
||||
return std::min(leg_width, effectiveLegDepth());
|
||||
}
|
||||
|
||||
/// @brief [m] Đường chéo của hình chữ nhật tâm chân.
|
||||
double cartDiagonal() const
|
||||
{
|
||||
return std::hypot(cart_opening, cart_depth);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Kiểm miền giá trị.
|
||||
* @param[out] error Khoá nào sai và vì sao.
|
||||
*
|
||||
* Kiểm lúc nạp config chứ không phải lúc dò: profile không thể khớp được biểu hiện thành "dò
|
||||
* mãi không ra", nhìn giống hệt xe không có trong tầm.
|
||||
*/
|
||||
bool validate(std::string& error) const;
|
||||
};
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_LEG_PROFILE_H_
|
||||
1141
src/leg_pattern_matcher.cpp
Normal file
1141
src/leg_pattern_matcher.cpp
Normal file
File diff suppressed because it is too large
Load Diff
394
src/leg_pose_fit.cpp
Normal file
394
src/leg_pose_fit.cpp
Normal file
@@ -0,0 +1,394 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — khớp tư thế xe hàng 4 chân.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <dock_pattern_detector/leg_pose_fit.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <vector>
|
||||
|
||||
#include <Eigen/Dense>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
namespace
|
||||
{
|
||||
constexpr double kStepTranslation = 1e-6; // [m] bước sai phân số cho Jacobian
|
||||
constexpr double kStepRotation = 1e-6; // [rad]
|
||||
constexpr double kStopTranslation = 1e-4; // [m] 0.1 mm
|
||||
constexpr double kStopRotation = 1.745329e-4; // [rad] 0.01°
|
||||
constexpr double kMinSigma = 1e-4; // [m] sàn σ để điểm đơn lẻ không thống trị
|
||||
constexpr double kHuberK = 2.0; // Huber δ = 2σ
|
||||
|
||||
constexpr int kMaxHalvings = 6; // tìm bước lùi: tối đa 6 lần chia đôi
|
||||
|
||||
double wrapAngle(double a)
|
||||
{
|
||||
return std::atan2(std::sin(a), std::cos(a));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief [m] Cự ly dọc tia (từ gốc, hướng @p ux, @p uy) tới mặt chân @p corner của xe đặt ở pose
|
||||
* (x, y, yaw). @return false nếu tia không cắt chân.
|
||||
*/
|
||||
bool rayEntry(const LegModel& model, int corner, double x, double y, double yaw, double ux,
|
||||
double uy, double& t)
|
||||
{
|
||||
const std::array<double, 2> local = model.corner(corner);
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
const double cx = x + c * local[0] - s * local[1];
|
||||
const double cy = y + s * local[0] + c * local[1];
|
||||
|
||||
if (model.shape == LegShape::kRound)
|
||||
{
|
||||
const double b = ux * cx + uy * cy;
|
||||
const double disc = b * b - (cx * cx + cy * cy - model.leg_width * model.leg_width / 4.0);
|
||||
if (disc < 0.0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
t = b - std::sqrt(disc);
|
||||
return t > 0.0;
|
||||
}
|
||||
|
||||
// Hộp: đưa tia về hệ của chân rồi cắt hai cặp mặt song song (slab).
|
||||
const double phi = yaw + model.leg_yaw_offset;
|
||||
const double cp = std::cos(phi);
|
||||
const double sp = std::sin(phi);
|
||||
const double ox = cp * (-cx) + sp * (-cy);
|
||||
const double oy = -sp * (-cx) + cp * (-cy);
|
||||
const double dx = cp * ux + sp * uy;
|
||||
const double dy = -sp * ux + cp * uy;
|
||||
const double half[2] = { model.leg_depth / 2.0, model.leg_width / 2.0 };
|
||||
const double origin[2] = { ox, oy };
|
||||
const double dir[2] = { dx, dy };
|
||||
|
||||
double t_min = -std::numeric_limits<double>::infinity();
|
||||
double t_max = std::numeric_limits<double>::infinity();
|
||||
for (int axis = 0; axis < 2; ++axis)
|
||||
{
|
||||
if (std::fabs(dir[axis]) < 1e-12)
|
||||
{
|
||||
if (std::fabs(origin[axis]) > half[axis])
|
||||
{
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const double t1 = (-half[axis] - origin[axis]) / dir[axis];
|
||||
const double t2 = (half[axis] - origin[axis]) / dir[axis];
|
||||
t_min = std::max(t_min, std::min(t1, t2));
|
||||
t_max = std::min(t_max, std::max(t1, t2));
|
||||
}
|
||||
if (t_min > t_max || t_min <= 0.0)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
t = t_min;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Phần dư của một điểm với pose (x, y, yaw) của xe.
|
||||
*
|
||||
* Tia cắt chân dự đoán: phần dư = cự ly dự đoán dọc tia − cự ly đo. Đây đúng là chiều nhiễu của
|
||||
* lidar, và nó biết mặt nào của chân quay về cảm biến. Tia trượt chân (điểm mép khi pose còn lệch):
|
||||
* rơi về khoảng cách có dấu tới biên chân.
|
||||
*
|
||||
* Vì sao không dùng khoảng cách có dấu cho mọi điểm: nó không biết mặt nào đang được nhìn. Chân tròn
|
||||
* khi đó có nghiệm "gương" — điểm nằm trên nửa SAU của đường tròn, tâm lệch về phía cảm biến cỡ một
|
||||
* đường kính. Chân hộp dưới nhiễu thì điểm lọt vào trong hộp bị tính tới mặt GẦN NHẤT (thường là mặt
|
||||
* bên) thay vì mặt tia đi vào, nên cả xe bị kéo về phía cảm biến vài mm có hệ thống.
|
||||
*/
|
||||
double residual(const LegModel& model, const FitPoint& p, double x, double y, double yaw,
|
||||
bool& on_ray)
|
||||
{
|
||||
const double range = std::hypot(p.x, p.y);
|
||||
double t = 0.0;
|
||||
if (range > 1e-9 && rayEntry(model, p.corner, x, y, yaw, p.x / range, p.y / range, t))
|
||||
{
|
||||
on_ray = true;
|
||||
return t - range;
|
||||
}
|
||||
on_ray = false;
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
const double dx = p.x - x;
|
||||
const double dy = p.y - y;
|
||||
return model.signedDistance(p.corner, c * dx + s * dy, -s * dx + c * dy);
|
||||
}
|
||||
|
||||
double residual(const LegModel& model, const FitPoint& p, double x, double y, double yaw)
|
||||
{
|
||||
bool on_ray = false;
|
||||
return residual(model, p, x, y, yaw, on_ray);
|
||||
}
|
||||
|
||||
struct PointTerm
|
||||
{
|
||||
double r = 0.0; // [m] phần dư
|
||||
Eigen::Vector3d jacobian; // ∂r/∂(x, y, yaw)
|
||||
double sigma = kMinSigma; // [m]
|
||||
};
|
||||
|
||||
PointTerm evaluate(const LegModel& model, const FitPoint& p, const Eigen::Vector3d& pose,
|
||||
const FitNoise& noise)
|
||||
{
|
||||
PointTerm t;
|
||||
bool on_ray = false;
|
||||
t.r = residual(model, p, pose.x(), pose.y(), pose.z(), on_ray);
|
||||
|
||||
// Jacobian bằng sai phân trung tâm: SDF hộp không khả vi ở góc, và vài chục điểm × 3 bậc tự do
|
||||
// thì sai phân rẻ hơn viết đạo hàm giải tích cho từng nhánh của SDF.
|
||||
t.jacobian.x() = (residual(model, p, pose.x() + kStepTranslation, pose.y(), pose.z()) -
|
||||
residual(model, p, pose.x() - kStepTranslation, pose.y(), pose.z())) /
|
||||
(2.0 * kStepTranslation);
|
||||
t.jacobian.y() = (residual(model, p, pose.x(), pose.y() + kStepTranslation, pose.z()) -
|
||||
residual(model, p, pose.x(), pose.y() - kStepTranslation, pose.z())) /
|
||||
(2.0 * kStepTranslation);
|
||||
t.jacobian.z() = (residual(model, p, pose.x(), pose.y(), pose.z() + kStepRotation) -
|
||||
residual(model, p, pose.x(), pose.y(), pose.z() - kStepRotation)) /
|
||||
(2.0 * kStepRotation);
|
||||
|
||||
if (on_ray)
|
||||
{
|
||||
// Phần dư dọc tia: nhiễu chính là nhiễu range.
|
||||
t.sigma = std::max(kMinSigma, noise.range_sigma);
|
||||
return t;
|
||||
}
|
||||
|
||||
// Tia trượt chân: phần dư là khoảng cách tới biên. Pháp tuyến biên tại điểm, trong frame scan:
|
||||
// r phụ thuộc (p − t), nên ∂r/∂p = −∂r/∂t.
|
||||
double nx = -t.jacobian.x();
|
||||
double ny = -t.jacobian.y();
|
||||
const double nn = std::hypot(nx, ny);
|
||||
const double range = std::hypot(p.x, p.y);
|
||||
if (nn > 1e-9 && range > 1e-9)
|
||||
{
|
||||
nx /= nn;
|
||||
ny /= nn;
|
||||
const double ux = p.x / range;
|
||||
const double uy = p.y / range;
|
||||
const double along = nx * ux + ny * uy; // thành phần dọc tia: nhiễu range
|
||||
const double across = -nx * uy + ny * ux; // thành phần ngang tia: lượng tử góc
|
||||
const double sigma_across = range * noise.angle_increment / std::sqrt(12.0);
|
||||
const double var = along * along * noise.range_sigma * noise.range_sigma +
|
||||
across * across * sigma_across * sigma_across;
|
||||
t.sigma = std::max(kMinSigma, std::sqrt(var));
|
||||
}
|
||||
else
|
||||
{
|
||||
t.sigma = std::max(kMinSigma, noise.range_sigma);
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
/// @brief Tổng mất mát Huber của mọi điểm tại @p pose — thước đo để chấp nhận một bước.
|
||||
double robustCost(const LegModel& model, const std::vector<FitPoint>& points,
|
||||
const Eigen::Vector3d& pose, const FitNoise& noise)
|
||||
{
|
||||
double cost = 0.0;
|
||||
for (const FitPoint& p : points)
|
||||
{
|
||||
const PointTerm t = evaluate(model, p, pose, noise);
|
||||
const double e = std::fabs(t.r) / t.sigma;
|
||||
cost += (e <= kHuberK) ? 0.5 * e * e : kHuberK * e - 0.5 * kHuberK * kHuberK;
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
LegModel LegModel::fromProfile(const LegProfile& profile)
|
||||
{
|
||||
LegModel m;
|
||||
m.cart_opening = profile.cart_opening;
|
||||
m.cart_depth = profile.cart_depth;
|
||||
m.shape = profile.leg_shape;
|
||||
m.leg_width = profile.leg_width;
|
||||
m.leg_depth = profile.effectiveLegDepth();
|
||||
m.leg_yaw_offset = profile.leg_shape == LegShape::kBox ? profile.leg_yaw_offset : 0.0;
|
||||
return m;
|
||||
}
|
||||
|
||||
std::array<double, 2> LegModel::corner(int corner) const
|
||||
{
|
||||
const double hx = cart_depth / 2.0;
|
||||
const double hy = cart_opening / 2.0;
|
||||
switch (corner)
|
||||
{
|
||||
case kEntryLeft:
|
||||
return { hx, hy };
|
||||
case kEntryRight:
|
||||
return { hx, -hy };
|
||||
case kFarLeft:
|
||||
return { -hx, hy };
|
||||
default:
|
||||
return { -hx, -hy };
|
||||
}
|
||||
}
|
||||
|
||||
double LegModel::signedDistance(int corner_id, double px, double py) const
|
||||
{
|
||||
const std::array<double, 2> c = corner(corner_id);
|
||||
const double dx = px - c[0];
|
||||
const double dy = py - c[1];
|
||||
|
||||
if (shape == LegShape::kRound)
|
||||
{
|
||||
return std::hypot(dx, dy) - leg_width / 2.0;
|
||||
}
|
||||
|
||||
// Đưa điểm về hệ của chân (chân có thể lắp xoay so với cạnh xe), rồi SDF hình chữ nhật.
|
||||
const double co = std::cos(leg_yaw_offset);
|
||||
const double so = std::sin(leg_yaw_offset);
|
||||
const double lx = co * dx + so * dy;
|
||||
const double ly = -so * dx + co * dy;
|
||||
const double qx = std::fabs(lx) - leg_depth / 2.0;
|
||||
const double qy = std::fabs(ly) - leg_width / 2.0;
|
||||
const double outside = std::hypot(std::max(qx, 0.0), std::max(qy, 0.0));
|
||||
const double inside = std::min(std::max(qx, qy), 0.0);
|
||||
return outside + inside;
|
||||
}
|
||||
|
||||
bool procrustes2D(const std::vector<std::array<double, 2>>& model,
|
||||
const std::vector<std::array<double, 2>>& scan, Pose2D& out)
|
||||
{
|
||||
const std::size_t n = std::min(model.size(), scan.size());
|
||||
if (n < 2)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
double mx = 0.0, my = 0.0, sx = 0.0, sy = 0.0;
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
mx += model[i][0];
|
||||
my += model[i][1];
|
||||
sx += scan[i][0];
|
||||
sy += scan[i][1];
|
||||
}
|
||||
mx /= static_cast<double>(n);
|
||||
my /= static_cast<double>(n);
|
||||
sx /= static_cast<double>(n);
|
||||
sy /= static_cast<double>(n);
|
||||
|
||||
double dot = 0.0;
|
||||
double cross = 0.0;
|
||||
double spread = 0.0;
|
||||
for (std::size_t i = 0; i < n; ++i)
|
||||
{
|
||||
const double ax = model[i][0] - mx;
|
||||
const double ay = model[i][1] - my;
|
||||
const double bx = scan[i][0] - sx;
|
||||
const double by = scan[i][1] - sy;
|
||||
dot += ax * bx + ay * by;
|
||||
cross += ax * by - ay * bx;
|
||||
spread += ax * ax + ay * ay;
|
||||
}
|
||||
if (spread < 1e-12)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const double yaw = std::atan2(cross, dot);
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
out.yaw = yaw;
|
||||
out.x = sx - (c * mx - s * my);
|
||||
out.y = sy - (s * mx + c * my);
|
||||
return true;
|
||||
}
|
||||
|
||||
PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& points,
|
||||
const Pose2D& initial, const FitNoise& noise, int max_iterations)
|
||||
{
|
||||
PoseFitResult result;
|
||||
result.pose = initial;
|
||||
if (points.size() < 3)
|
||||
{
|
||||
return result; // 3 bậc tự do cần ít nhất 3 phần dư
|
||||
}
|
||||
|
||||
Eigen::Vector3d pose(initial.x, initial.y, initial.yaw);
|
||||
|
||||
for (int iter = 0; iter < max_iterations; ++iter)
|
||||
{
|
||||
Eigen::Matrix3d normal = Eigen::Matrix3d::Zero();
|
||||
Eigen::Vector3d rhs = Eigen::Vector3d::Zero();
|
||||
|
||||
for (const FitPoint& p : points)
|
||||
{
|
||||
const PointTerm t = evaluate(model, p, pose, noise);
|
||||
const double e = std::fabs(t.r) / t.sigma;
|
||||
const double huber = (e <= kHuberK) ? 1.0 : kHuberK / e;
|
||||
const double w = huber / (t.sigma * t.sigma);
|
||||
normal += w * t.jacobian * t.jacobian.transpose();
|
||||
rhs -= w * t.jacobian * t.r;
|
||||
}
|
||||
|
||||
// Giảm chấn rất nhỏ: chỉ để nghiệm tồn tại khi hình học suy biến (ví dụ chỉ thấy hai chân
|
||||
// thẳng hàng với tia), không đủ lớn để làm chậm hội tụ ở ca thường.
|
||||
normal += 1e-9 * (1.0 + normal.trace()) * Eigen::Matrix3d::Identity();
|
||||
Eigen::Vector3d step = normal.ldlt().solve(rhs);
|
||||
if (!step.allFinite())
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
// Tìm bước lùi: phần dư không trơn ở mép chân (tia vừa trượt khỏi chân đổi công thức), nên một
|
||||
// bước Gauss-Newton đủ dài có thể làm tệ đi. Chỉ nhận bước làm giảm mất mát Huber; chia đôi tới
|
||||
// khi giảm, hết lượt chia mà vẫn không giảm thì coi như đã ở đáy.
|
||||
const double cost_now = robustCost(model, points, pose, noise);
|
||||
bool accepted = false;
|
||||
for (int halving = 0; halving <= kMaxHalvings; ++halving)
|
||||
{
|
||||
Eigen::Vector3d candidate = pose + step;
|
||||
candidate.z() = wrapAngle(candidate.z());
|
||||
if (robustCost(model, points, candidate, noise) < cost_now)
|
||||
{
|
||||
pose = candidate;
|
||||
accepted = true;
|
||||
break;
|
||||
}
|
||||
step *= 0.5;
|
||||
}
|
||||
result.iterations = iter + 1;
|
||||
if (!accepted)
|
||||
{
|
||||
result.converged = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (std::hypot(step.x(), step.y()) < kStopTranslation && std::fabs(step.z()) < kStopRotation)
|
||||
{
|
||||
result.converged = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
double sum_r2 = 0.0;
|
||||
double sum_e2 = 0.0;
|
||||
for (const FitPoint& p : points)
|
||||
{
|
||||
const PointTerm t = evaluate(model, p, pose, noise);
|
||||
sum_r2 += t.r * t.r;
|
||||
sum_e2 += (t.r / t.sigma) * (t.r / t.sigma);
|
||||
}
|
||||
const double n = static_cast<double>(points.size());
|
||||
result.rms = std::sqrt(sum_r2 / n);
|
||||
result.normalized_rms = std::sqrt(sum_e2 / n);
|
||||
result.pose.x = pose.x();
|
||||
result.pose.y = pose.y();
|
||||
result.pose.yaw = pose.z();
|
||||
result.valid = pose.allFinite() && std::isfinite(result.rms);
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
237
src/leg_profile.cpp
Normal file
237
src/leg_profile.cpp
Normal file
@@ -0,0 +1,237 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* dock_pattern_detector — kiểm miền của LegProfile.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <dock_pattern_detector/leg_profile.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
|
||||
namespace dock_pattern_detector
|
||||
{
|
||||
namespace
|
||||
{
|
||||
bool positiveFinite(double value)
|
||||
{
|
||||
return std::isfinite(value) && value > 0.0;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
const char* toString(LegShape shape)
|
||||
{
|
||||
switch (shape)
|
||||
{
|
||||
case LegShape::kBox:
|
||||
return "box";
|
||||
case LegShape::kRound:
|
||||
return "round";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
bool legShapeFromString(const std::string& name, LegShape& out, std::string& error)
|
||||
{
|
||||
if (name == "box")
|
||||
{
|
||||
out = LegShape::kBox;
|
||||
return true;
|
||||
}
|
||||
if (name == "round")
|
||||
{
|
||||
out = LegShape::kRound;
|
||||
return true;
|
||||
}
|
||||
error = "unknown leg_shape '" + name + "'; known values are: box, round";
|
||||
return false;
|
||||
}
|
||||
|
||||
const char* toString(TapeLegs legs)
|
||||
{
|
||||
switch (legs)
|
||||
{
|
||||
case TapeLegs::kAll:
|
||||
return "all";
|
||||
case TapeLegs::kEntry:
|
||||
return "entry";
|
||||
}
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
bool tapeLegsFromString(const std::string& name, TapeLegs& out, std::string& error)
|
||||
{
|
||||
if (name == "all")
|
||||
{
|
||||
out = TapeLegs::kAll;
|
||||
return true;
|
||||
}
|
||||
if (name == "entry")
|
||||
{
|
||||
out = TapeLegs::kEntry;
|
||||
return true;
|
||||
}
|
||||
error = "unknown tape_legs '" + name + "'; known values are: all, entry";
|
||||
return false;
|
||||
}
|
||||
|
||||
bool LegProfile::validate(std::string& error) const
|
||||
{
|
||||
if (!positiveFinite(cart_opening) || !positiveFinite(cart_depth))
|
||||
{
|
||||
error = "cart_opening and cart_depth must be finite and > 0 [m] (both are required)";
|
||||
return false;
|
||||
}
|
||||
if (!positiveFinite(leg_width))
|
||||
{
|
||||
error = "leg_width must be finite and > 0 [m] (it is required)";
|
||||
return false;
|
||||
}
|
||||
if (cart_opening <= leg_width + 0.2)
|
||||
{
|
||||
// Khe lọt giữa hai chân cạnh vào dưới 0.2 m: không robot nào chui được. Gần như chắc là khai
|
||||
// nhầm đơn vị (mm thay vì m) hoặc nhầm hai khoá.
|
||||
error = "cart_opening must exceed leg_width + 0.2 m; nothing fits through a narrower opening "
|
||||
"(wrong unit?)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(cart_dim_tolerance) || cart_dim_tolerance <= 0.0 ||
|
||||
cart_dim_tolerance >= std::min(cart_opening, cart_depth) / 4.0)
|
||||
{
|
||||
error = "cart_dim_tolerance must be > 0 and < min(cart_opening, cart_depth)/4 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(leg_width_tolerance) || leg_width_tolerance < 0.0)
|
||||
{
|
||||
error = "leg_width_tolerance must be finite and >= 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(leg_depth) || leg_depth < 0.0)
|
||||
{
|
||||
error = "leg_depth must be finite and >= 0 [m] (0 = same as leg_width)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(leg_yaw_offset))
|
||||
{
|
||||
error = "leg_yaw_offset must be finite [rad]";
|
||||
return false;
|
||||
}
|
||||
if (leg_shape == LegShape::kRound && (leg_depth > 0.0 || leg_yaw_offset != 0.0))
|
||||
{
|
||||
// Nói thẳng thay vì nhận rồi lờ đi: chân tròn không có bề dày riêng hay góc xoay.
|
||||
error = "leg_depth and leg_yaw_offset only apply to leg_shape 'box'";
|
||||
return false;
|
||||
}
|
||||
if (min_leg_points < 1)
|
||||
{
|
||||
error = "min_leg_points must be >= 1";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(shadow_min_angle) || shadow_min_angle < 0.0 ||
|
||||
shadow_min_angle >= M_PI / 2.0)
|
||||
{
|
||||
error = "shadow_min_angle must be in [0, pi/2) [rad] (0 disables the shadow filter)";
|
||||
return false;
|
||||
}
|
||||
if (!positiveFinite(leg_cluster_gap))
|
||||
{
|
||||
error = "leg_cluster_gap must be finite and > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!positiveFinite(leg_min_depth_gap))
|
||||
{
|
||||
error = "leg_min_depth_gap must be finite and > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (min_legs < 2 || min_legs > 4)
|
||||
{
|
||||
error = "min_legs must be 2, 3 or 4";
|
||||
return false;
|
||||
}
|
||||
if (min_legs == 2 && !has_prior)
|
||||
{
|
||||
// Hai chân có thể là cạnh vào, cạnh dọc hoặc đường chéo, mỗi loại hai phía. Không có prior thì
|
||||
// không có gì chọn giữa các khả năng đó.
|
||||
error = "min_legs 2 requires has_prior: two legs alone fit several cart poses";
|
||||
return false;
|
||||
}
|
||||
if (!positiveFinite(leg_assoc_radius))
|
||||
{
|
||||
error = "leg_assoc_radius must be finite and > 0 [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(interior_margin) || interior_margin < 0.0 ||
|
||||
2.0 * interior_margin >= std::min(cart_opening, cart_depth))
|
||||
{
|
||||
error = "interior_margin must be >= 0 and leave a non-empty interior [m]";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(ambiguity_margin) || ambiguity_margin < 0.0 || ambiguity_margin >= 1.0)
|
||||
{
|
||||
error = "ambiguity_margin must be in [0, 1)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(min_confidence) || min_confidence < 0.0 || min_confidence > 1.0)
|
||||
{
|
||||
error = "min_confidence must be in [0, 1]";
|
||||
return false;
|
||||
}
|
||||
if (tape_legs == TapeLegs::kEntry && !tape_enabled)
|
||||
{
|
||||
error = "tape_legs 'entry' requires tape_enabled: true (forgot to turn the tape on?)";
|
||||
return false;
|
||||
}
|
||||
if (tape_enabled && (!std::isfinite(tape_min_intensity) || tape_min_points < 1))
|
||||
{
|
||||
error = "tape_min_intensity must be finite and tape_min_points >= 1";
|
||||
return false;
|
||||
}
|
||||
if (std::fabs(cart_opening - cart_depth) < 2.0 * cart_dim_tolerance)
|
||||
{
|
||||
// Xe gần vuông: hình học không biết cạnh nào là cạnh vào. Dò ra cạnh bên là robot chui ngang
|
||||
// vào chân xe — phải có thứ khác chọn hộ.
|
||||
const bool yaw_prior = has_prior && prior_yaw_tolerance < M_PI / 4.0;
|
||||
const bool entry_tape = tape_enabled && tape_legs == TapeLegs::kEntry;
|
||||
if (!yaw_prior && !entry_tape)
|
||||
{
|
||||
error = "cart_opening and cart_depth differ by less than 2*cart_dim_tolerance, so the entry "
|
||||
"side is ambiguous by 90 deg; set has_prior with prior_yaw_tolerance < pi/4, or "
|
||||
"tape_legs: entry";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (has_prior)
|
||||
{
|
||||
if (!std::isfinite(prior_x) || !std::isfinite(prior_y) || !std::isfinite(prior_yaw))
|
||||
{
|
||||
error = "prior_x, prior_y and prior_yaw must be finite";
|
||||
return false;
|
||||
}
|
||||
if (!positiveFinite(search_radius))
|
||||
{
|
||||
error = "search_radius must be finite and > 0 [m] when has_prior is true";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(prior_yaw_tolerance) || prior_yaw_tolerance <= 0.0 ||
|
||||
prior_yaw_tolerance > M_PI)
|
||||
{
|
||||
error = "prior_yaw_tolerance must be in (0, pi] [rad]";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!std::isfinite(search_fov))
|
||||
{
|
||||
error = "search_fov must be finite [rad] (<= 0 disables the fan)";
|
||||
return false;
|
||||
}
|
||||
if (!std::isfinite(offset_x) || !std::isfinite(offset_y) || !std::isfinite(offset_yaw))
|
||||
{
|
||||
error = "offset_x, offset_y and offset_yaw must be finite";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace dock_pattern_detector
|
||||
476
test/leg_pattern_matcher_test.cpp
Normal file
476
test/leg_pattern_matcher_test.cpp
Normal file
@@ -0,0 +1,476 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Kiểm dò xe hàng 4 chân bằng scan TỔNG HỢP — đặt chân vào thế giới 2D, chiếu tia, biết trước đáp
|
||||
* án. Số xe theo mô hình sim `tci_trolley`, hình học scan theo SICK S300 sim của `hook_150`.
|
||||
*
|
||||
* Năm nhóm:
|
||||
* 1. dò đúng — thẳng, xoay, lệch ngang, chân tròn;
|
||||
* 2. che khuất — 1 chân bị che vẫn nhận, 2 chân bị che thì từ chối, tia xuyên qua thì từ chối;
|
||||
* 3. TỪ CHỐI — chân người, chân dính tường, lòng xe có vật, hai xe sát nhau;
|
||||
* 4. dải phản quang, prior, nhiễu;
|
||||
* 5. config hỏng.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include <dock_pattern_detector/leg_pattern_matcher.h>
|
||||
|
||||
#include "leg_scan_sim.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
using dock_pattern_detector::LegDetection;
|
||||
using dock_pattern_detector::LegPatternMatcher;
|
||||
using dock_pattern_detector::LegProfile;
|
||||
using dock_pattern_detector::LegShape;
|
||||
using dock_pattern_detector::Pose2D;
|
||||
using dock_pattern_detector::ScanLimits;
|
||||
using dock_pattern_detector::TapeLegs;
|
||||
using leg_scan_sim::World;
|
||||
|
||||
constexpr double kDeg = M_PI / 180.0;
|
||||
|
||||
/// Tâm xe khi cạnh vào cách cảm biến 0.9 m (pose chuẩn bị của plan): 0.9 + 0.720/2.
|
||||
constexpr double kCx = 1.26;
|
||||
|
||||
LegProfile tciTrolley()
|
||||
{
|
||||
LegProfile p;
|
||||
p.cart_opening = 0.517;
|
||||
p.cart_depth = 0.720;
|
||||
p.leg_shape = LegShape::kBox;
|
||||
p.leg_width = 0.030;
|
||||
p.min_legs = 3;
|
||||
return p;
|
||||
}
|
||||
|
||||
ScanLimits s300Limits()
|
||||
{
|
||||
ScanLimits l;
|
||||
l.min_range = 0.10;
|
||||
l.max_range = 3.0;
|
||||
l.range_sigma = 0.01;
|
||||
return l;
|
||||
}
|
||||
|
||||
double yawError(double a, double b)
|
||||
{
|
||||
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
|
||||
}
|
||||
|
||||
/// @brief Cấu hình matcher, chiếu tia lên @p world, dò. Prior frame trùng frame scan.
|
||||
LegDetection detect(const LegProfile& p, const World& world, double sigma = 0.0,
|
||||
unsigned seed = 1)
|
||||
{
|
||||
LegPatternMatcher matcher;
|
||||
std::string error;
|
||||
EXPECT_TRUE(matcher.configure(p, error)) << error;
|
||||
const auto g = leg_scan_sim::s300Geometry();
|
||||
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g, sigma, seed);
|
||||
return matcher.match(g, scan.ranges, scan.intensities, s300Limits(), Pose2D());
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 1. Dò đúng
|
||||
// ================================================================================================
|
||||
|
||||
TEST(LegPatternMatcher, FindsACartFacingTheSensor)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.center_x, kCx, 0.003);
|
||||
EXPECT_NEAR(d.center_y, 0.0, 0.003);
|
||||
// Pháp tuyến cạnh vào trỏ VỀ cảm biến — cùng quy ước V/arc.
|
||||
EXPECT_LT(yawError(d.center_yaw, M_PI), 0.3 * kDeg);
|
||||
EXPECT_EQ(d.legs_seen, 4);
|
||||
EXPECT_NEAR(d.measured_opening, p.cart_opening, 0.02);
|
||||
EXPECT_NEAR(d.measured_depth, p.cart_depth, 0.02);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, FollowsARotatedCart)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
for (double rot : { -22.5, -15.0, -7.5, 7.5, 15.0, 22.5 })
|
||||
{
|
||||
World w;
|
||||
const double axis = M_PI + rot * kDeg;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, axis);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << "rotation " << rot << ": " << d.reason;
|
||||
EXPECT_NEAR(d.center_x, kCx, 0.003) << "rotation " << rot;
|
||||
EXPECT_NEAR(d.center_y, 0.0, 0.003) << "rotation " << rot;
|
||||
EXPECT_LT(yawError(d.center_yaw, axis), 0.3 * kDeg) << "rotation " << rot;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, FollowsALateralOffset)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
for (double y : { -0.20, -0.10, 0.10, 0.20 })
|
||||
{
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, y, M_PI);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << "offset " << y << ": " << d.reason;
|
||||
EXPECT_NEAR(d.center_y, y, 0.003) << "offset " << y;
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, FindsRoundLegs)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.leg_shape = LegShape::kRound;
|
||||
p.leg_width = 0.040;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.05, M_PI + 10.0 * kDeg);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.center_x, kCx, 0.003);
|
||||
EXPECT_NEAR(d.center_y, 0.05, 0.003);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, AppliesTheOffsetLikeTheVMatcher)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.offset_x = 0.10;
|
||||
p.offset_yaw = 0.05;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
// offset_x dọc pháp tuyến cạnh vào, hướng về phía robot: pháp tuyến trỏ −x nên đích lùi về x nhỏ.
|
||||
EXPECT_NEAR(d.x, kCx - 0.10, 0.003);
|
||||
EXPECT_LT(yawError(d.yaw, M_PI + 0.05), 0.3 * kDeg);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, RejectsACartBeyondMaxRange)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, 3.6, 0.0, M_PI);
|
||||
EXPECT_FALSE(detect(p, w).valid);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 2. Che khuất
|
||||
// ================================================================================================
|
||||
|
||||
TEST(LegPatternMatcher, AcceptsOneLegHiddenBehindAnother)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
// Cảm biến nằm đúng trên đường thẳng qua hai chân của một cạnh dọc: chân sau của cạnh đó nấp sau
|
||||
// chân trước.
|
||||
leg_scan_sim::addCart(w, p, kCx, p.cart_opening / 2.0, M_PI);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_EQ(d.legs_seen, 3);
|
||||
EXPECT_EQ(d.legs_occluded, 1);
|
||||
EXPECT_NEAR(d.center_y, p.cart_opening / 2.0, 0.005);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, RejectsWhenABoxHidesTwoLegs)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
// Thùng hàng chắn trước cả hai chân bên trái.
|
||||
w.addBox(0.6, 0.15, 0.10, 0.20, 0.0);
|
||||
const LegDetection d = detect(p, w);
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_NE(d.reason.find("leg"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, AcceptsTwoHiddenLegsWithMinLegsTwoAndAPrior)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.min_legs = 2;
|
||||
p.has_prior = true;
|
||||
p.prior_x = kCx;
|
||||
p.prior_y = 0.0;
|
||||
p.prior_yaw = M_PI;
|
||||
p.prior_yaw_tolerance = 0.35;
|
||||
p.search_radius = 0.30;
|
||||
p.min_confidence = 0.3;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
w.addBox(0.6, 0.15, 0.10, 0.20, 0.0);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.center_y, 0.0, 0.01);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, RejectsWhenTheScanPassesWhereALegMustStand)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
const bool skip[4] = { false, false, false, true }; // thiếu chân sau-phải, phía sau trống
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, skip);
|
||||
const LegDetection d = detect(p, w);
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_NE(d.reason.find("leg_missing"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 3. Từ chối
|
||||
// ================================================================================================
|
||||
|
||||
TEST(LegPatternMatcher, IgnoresAPersonsLegs)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
w.addCircle(1.0, 0.125, 0.06);
|
||||
w.addCircle(1.0, -0.125, 0.06);
|
||||
EXPECT_FALSE(detect(p, w).valid);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, LegsTouchingAWallAreNotFreeStanding)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
// Tường áp sát mặt sau hai chân sau: mép cụm liền với tường → "dính" → hai chân sau bị loại.
|
||||
w.addWall(kCx + p.cart_depth / 2.0 + p.leg_width / 2.0, -3.0,
|
||||
kCx + p.cart_depth / 2.0 + p.leg_width / 2.0, 3.0);
|
||||
const LegDetection d = detect(p, w);
|
||||
EXPECT_FALSE(d.valid);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, InteriorGateRejectsACartWithSomethingInside)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
w.addBox(kCx, 0.0, 0.15, 0.15, 0.0);
|
||||
|
||||
p.max_interior_points = 0;
|
||||
const LegDetection blocked = detect(p, w);
|
||||
EXPECT_FALSE(blocked.valid);
|
||||
EXPECT_NE(blocked.reason.find("inside the cart"), std::string::npos) << blocked.reason;
|
||||
|
||||
p.max_interior_points = -1; // cổng tắt
|
||||
EXPECT_TRUE(detect(p, w).valid);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, TwoCartsSideBySideWithoutAPriorAreAmbiguous)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.485, M_PI);
|
||||
leg_scan_sim::addCart(w, p, kCx, -0.485, M_PI);
|
||||
const LegDetection d = detect(p, w);
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_NE(d.reason.find("ambiguous"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, LegsOfTwoNeighboursDoNotMakeAPhantomCart)
|
||||
{
|
||||
// Hai xe sát nhau, prior đặt ĐÚNG GIỮA hai xe: bốn chân phía trong (khe 0.453 m) gần giống một xe
|
||||
// 0.517 m. Không được nhận "xe" đó.
|
||||
LegProfile p = tciTrolley();
|
||||
p.has_prior = true;
|
||||
p.prior_x = kCx;
|
||||
p.prior_y = 0.0;
|
||||
p.prior_yaw = M_PI;
|
||||
p.prior_yaw_tolerance = 0.35;
|
||||
p.search_radius = 0.20;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.485, M_PI);
|
||||
leg_scan_sim::addCart(w, p, kCx, -0.485, M_PI);
|
||||
const LegDetection d = detect(p, w);
|
||||
EXPECT_FALSE(d.valid) << "phantom at (" << d.center_x << ", " << d.center_y << ")";
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, APriorPicksOneCartOfARow)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.has_prior = true;
|
||||
p.prior_x = kCx;
|
||||
p.prior_y = 0.0;
|
||||
p.prior_yaw = M_PI;
|
||||
p.prior_yaw_tolerance = 0.35;
|
||||
p.search_radius = 0.30;
|
||||
World w;
|
||||
// Dãy 3 xe bước 0.97 m như world factory_ss_demo: khe chân hai xe kề nhau 0.453 m.
|
||||
for (double y : { -0.97, 0.0, 0.97 })
|
||||
{
|
||||
leg_scan_sim::addCart(w, p, kCx, y, M_PI);
|
||||
}
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_NEAR(d.center_y, 0.0, 0.005);
|
||||
EXPECT_NEAR(d.center_x, kCx, 0.005);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 4. Dải phản quang, nhiễu
|
||||
// ================================================================================================
|
||||
|
||||
TEST(LegPatternMatcher, EntryTapeDecidesWhichEndIsTheEntry)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.tape_enabled = true;
|
||||
p.tape_legs = TapeLegs::kEntry;
|
||||
p.tape_min_intensity = 1000.0;
|
||||
|
||||
{
|
||||
World w;
|
||||
const bool taped[4] = { true, true, false, false }; // dải ở hai chân phía cảm biến
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, nullptr, taped);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_LT(yawError(d.center_yaw, M_PI), 0.3 * kDeg);
|
||||
}
|
||||
{
|
||||
World w;
|
||||
const bool taped[4] = { false, false, true, true }; // dải ở đầu xa: cạnh vào là đầu xa
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, nullptr, taped);
|
||||
const LegDetection d = detect(p, w);
|
||||
ASSERT_TRUE(d.valid) << d.reason;
|
||||
EXPECT_LT(yawError(d.center_yaw, 0.0), 0.3 * kDeg);
|
||||
}
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, TapeWithoutIntensitiesSaysSo)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.tape_enabled = true;
|
||||
LegPatternMatcher matcher;
|
||||
std::string error;
|
||||
ASSERT_TRUE(matcher.configure(p, error)) << error;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
const auto g = leg_scan_sim::s300Geometry();
|
||||
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(w, g);
|
||||
const LegDetection d = matcher.match(g, scan.ranges, {}, s300Limits(), Pose2D());
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_NE(d.reason.find("no intensity"), std::string::npos) << d.reason;
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, TapeDisabledIgnoresIntensities)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
LegPatternMatcher matcher;
|
||||
std::string error;
|
||||
ASSERT_TRUE(matcher.configure(p, error)) << error;
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.03, M_PI + 0.1);
|
||||
const auto g = leg_scan_sim::s300Geometry();
|
||||
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(w, g);
|
||||
const LegDetection with = matcher.match(g, scan.ranges, scan.intensities, s300Limits(), Pose2D());
|
||||
const LegDetection without = matcher.match(g, scan.ranges, {}, s300Limits(), Pose2D());
|
||||
ASSERT_TRUE(with.valid) << with.reason;
|
||||
EXPECT_EQ(with.center_x, without.center_x);
|
||||
EXPECT_EQ(with.center_y, without.center_y);
|
||||
EXPECT_EQ(with.center_yaw, without.center_yaw);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, StaysWithinToleranceUnderS300Noise)
|
||||
{
|
||||
// σ 10 mm của S300 sim trên chân 30 mm. Đây là sai số MỖI SCAN; handler còn lọc nhiều scan.
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI);
|
||||
|
||||
double sum_xy = 0.0, max_xy = 0.0, sum_yaw = 0.0, max_yaw = 0.0;
|
||||
int found = 0;
|
||||
for (unsigned seed = 1; seed <= 50; ++seed)
|
||||
{
|
||||
const LegDetection d = detect(p, w, 0.01, seed);
|
||||
if (!d.valid)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
++found;
|
||||
const double exy = std::hypot(d.center_x - kCx, d.center_y);
|
||||
const double eyaw = yawError(d.center_yaw, M_PI);
|
||||
sum_xy += exy;
|
||||
sum_yaw += eyaw;
|
||||
max_xy = std::max(max_xy, exy);
|
||||
max_yaw = std::max(max_yaw, eyaw);
|
||||
}
|
||||
ASSERT_GE(found, 45) << "detection rate under noise";
|
||||
EXPECT_LT(sum_xy / found, 0.005);
|
||||
EXPECT_LT(sum_yaw / found, 0.5 * kDeg);
|
||||
EXPECT_LT(max_xy, 0.015);
|
||||
EXPECT_LT(max_yaw, 2.0 * kDeg);
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, IsDeterministic)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
World w;
|
||||
leg_scan_sim::addCart(w, p, kCx, 0.07, M_PI + 0.12);
|
||||
const LegDetection a = detect(p, w, 0.01, 7);
|
||||
const LegDetection b = detect(p, w, 0.01, 7);
|
||||
ASSERT_TRUE(a.valid) << a.reason;
|
||||
EXPECT_EQ(a.center_x, b.center_x);
|
||||
EXPECT_EQ(a.center_y, b.center_y);
|
||||
EXPECT_EQ(a.center_yaw, b.center_yaw);
|
||||
}
|
||||
|
||||
// ================================================================================================
|
||||
// 5. Config
|
||||
// ================================================================================================
|
||||
|
||||
TEST(LegProfile, ValidateRefusesBrokenProfiles)
|
||||
{
|
||||
std::string error;
|
||||
|
||||
LegProfile p = tciTrolley();
|
||||
EXPECT_TRUE(p.validate(error)) << error;
|
||||
|
||||
p = tciTrolley();
|
||||
p.cart_opening = 0.0;
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
|
||||
p = tciTrolley();
|
||||
p.min_legs = 2; // không có prior
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
|
||||
p = tciTrolley();
|
||||
p.cart_opening = 0.70; // gần vuông với cart_depth 0.72, không có gì chọn cạnh vào
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
|
||||
p = tciTrolley();
|
||||
p.tape_legs = TapeLegs::kEntry; // quên bật dải
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
|
||||
p = tciTrolley();
|
||||
p.leg_shape = LegShape::kRound;
|
||||
p.leg_depth = 0.02; // chân tròn không có bề dày riêng
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
|
||||
p = tciTrolley();
|
||||
p.cart_dim_tolerance = 0.20; // ≥ cạnh ngắn / 4
|
||||
EXPECT_FALSE(p.validate(error));
|
||||
}
|
||||
|
||||
TEST(LegPatternMatcher, MatchBeforeConfigureSaysSo)
|
||||
{
|
||||
LegPatternMatcher matcher;
|
||||
const auto g = leg_scan_sim::s300Geometry();
|
||||
const std::vector<double> ranges(g.size, 1.0);
|
||||
const LegDetection d = matcher.match(g, ranges, {}, s300Limits(), Pose2D());
|
||||
EXPECT_FALSE(d.valid);
|
||||
EXPECT_FALSE(d.reason.empty());
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
230
test/leg_pose_fit_test.cpp
Normal file
230
test/leg_pose_fit_test.cpp
Normal file
@@ -0,0 +1,230 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Kiểm phép khớp tư thế xe trên mọi điểm chân — điểm sinh bằng ray-cast lên mô hình đã biết, nên
|
||||
* đáp án biết trước.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
#include <dock_pattern_detector/leg_pose_fit.h>
|
||||
|
||||
#include "leg_scan_sim.h"
|
||||
|
||||
namespace
|
||||
{
|
||||
using dock_pattern_detector::FitNoise;
|
||||
using dock_pattern_detector::FitPoint;
|
||||
using dock_pattern_detector::LegModel;
|
||||
using dock_pattern_detector::LegProfile;
|
||||
using dock_pattern_detector::LegShape;
|
||||
using dock_pattern_detector::Pose2D;
|
||||
using dock_pattern_detector::PoseFitResult;
|
||||
|
||||
constexpr double kDeg = M_PI / 180.0;
|
||||
|
||||
/// @brief Xe `tci_trolley` (mô hình sim): cạnh vào 0.517 m, dọc 0.720 m, chân hộp 30 mm.
|
||||
LegProfile tciTrolley()
|
||||
{
|
||||
LegProfile p;
|
||||
p.cart_opening = 0.517;
|
||||
p.cart_depth = 0.720;
|
||||
p.leg_shape = LegShape::kBox;
|
||||
p.leg_width = 0.030;
|
||||
return p;
|
||||
}
|
||||
|
||||
/// @brief Điểm của từng chân lấy từ ray-cast, gán đúng góc theo id vật trúng.
|
||||
std::vector<FitPoint> pointsOf(const LegProfile& p, double cx, double cy, double axis,
|
||||
double sigma = 0.0)
|
||||
{
|
||||
leg_scan_sim::World world;
|
||||
const std::vector<int> ids = leg_scan_sim::addCart(world, p, cx, cy, axis);
|
||||
const auto g = leg_scan_sim::s300Geometry();
|
||||
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g, sigma);
|
||||
|
||||
std::vector<FitPoint> points;
|
||||
for (std::size_t i = 0; i < g.size; ++i)
|
||||
{
|
||||
for (int k = 0; k < 4; ++k)
|
||||
{
|
||||
if (scan.hit[i] >= 0 && scan.hit[i] == ids[k])
|
||||
{
|
||||
const double b = g.angle_min + static_cast<double>(i) * g.angle_increment;
|
||||
FitPoint fp;
|
||||
fp.x = scan.ranges[i] * std::cos(b);
|
||||
fp.y = scan.ranges[i] * std::sin(b);
|
||||
fp.corner = k;
|
||||
points.push_back(fp);
|
||||
}
|
||||
}
|
||||
}
|
||||
return points;
|
||||
}
|
||||
|
||||
FitNoise s300Noise()
|
||||
{
|
||||
FitNoise n;
|
||||
n.range_sigma = 0.01;
|
||||
n.angle_increment = leg_scan_sim::s300Geometry().angle_increment;
|
||||
return n;
|
||||
}
|
||||
|
||||
double yawError(double a, double b)
|
||||
{
|
||||
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, ConvergesOnNoiseFreeBoxLegs)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
const double cx = 1.26, cy = 0.05, axis = M_PI + 10.0 * kDeg;
|
||||
const std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
|
||||
ASSERT_GE(pts.size(), 12u);
|
||||
|
||||
Pose2D init;
|
||||
init.x = cx + 0.05; // lệch 5 cm, 5°
|
||||
init.y = cy - 0.05;
|
||||
init.yaw = axis + 5.0 * kDeg;
|
||||
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
|
||||
ASSERT_TRUE(fit.valid);
|
||||
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
|
||||
EXPECT_NEAR(fit.pose.y, cy, 1e-3);
|
||||
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.05 * kDeg);
|
||||
EXPECT_LT(fit.rms, 1e-3);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, ConvergesOnRoundLegs)
|
||||
{
|
||||
LegProfile p = tciTrolley();
|
||||
p.leg_shape = LegShape::kRound;
|
||||
p.leg_width = 0.040;
|
||||
const double cx = 1.30, cy = -0.10, axis = M_PI - 8.0 * kDeg;
|
||||
const std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
|
||||
|
||||
Pose2D init;
|
||||
init.x = cx - 0.04;
|
||||
init.y = cy + 0.04;
|
||||
init.yaw = axis - 4.0 * kDeg;
|
||||
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
|
||||
ASSERT_TRUE(fit.valid);
|
||||
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
|
||||
EXPECT_NEAR(fit.pose.y, cy, 1e-3);
|
||||
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.05 * kDeg);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, HuberKeepsOneStrayPointFromPullingThePose)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
const double cx = 1.26, cy = 0.0, axis = M_PI;
|
||||
std::vector<FitPoint> pts = pointsOf(p, cx, cy, axis);
|
||||
ASSERT_FALSE(pts.empty());
|
||||
|
||||
// Một điểm lai lạc 10 cm sau chân trước-trái.
|
||||
FitPoint stray = pts.front();
|
||||
stray.x += 0.10;
|
||||
pts.push_back(stray);
|
||||
|
||||
Pose2D init;
|
||||
init.x = cx + 0.02;
|
||||
init.y = cy;
|
||||
init.yaw = axis;
|
||||
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
|
||||
ASSERT_TRUE(fit.valid);
|
||||
// Điểm lạc nằm trên tia của chính nó, nên kéo xe DỌC tia đó (−15° so với trục x). Trục dọc (x) có
|
||||
// mọi mặt trước giữ nên không xê dịch; trục ngang chỉ có điểm mép giữ nên nhích ~2.6 mm — cùng cỡ
|
||||
// khi không có Huber. Trong matcher, điểm lạc như vậy bị bước "cắt điểm xa" bỏ trước khi khớp.
|
||||
EXPECT_NEAR(fit.pose.x, cx, 1e-3);
|
||||
EXPECT_NEAR(fit.pose.y, cy, 3e-3);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, TwoLegsAreEnoughWhenTheModelIsKnown)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
const double cx = 1.26, cy = 0.0, axis = M_PI + 5.0 * kDeg;
|
||||
std::vector<FitPoint> all = pointsOf(p, cx, cy, axis);
|
||||
std::vector<FitPoint> pts;
|
||||
for (const FitPoint& fp : all)
|
||||
{
|
||||
if (fp.corner == dock_pattern_detector::kEntryLeft ||
|
||||
fp.corner == dock_pattern_detector::kEntryRight)
|
||||
{
|
||||
pts.push_back(fp);
|
||||
}
|
||||
}
|
||||
ASSERT_GE(pts.size(), 6u);
|
||||
|
||||
Pose2D init;
|
||||
init.x = cx + 0.02;
|
||||
init.y = cy + 0.02;
|
||||
init.yaw = axis + 2.0 * kDeg;
|
||||
const PoseFitResult fit = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
|
||||
ASSERT_TRUE(fit.valid);
|
||||
EXPECT_NEAR(fit.pose.x, cx, 2e-3);
|
||||
EXPECT_NEAR(fit.pose.y, cy, 2e-3);
|
||||
EXPECT_LT(yawError(fit.pose.yaw, axis), 0.2 * kDeg);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, IsDeterministic)
|
||||
{
|
||||
const LegProfile p = tciTrolley();
|
||||
const std::vector<FitPoint> pts = pointsOf(p, 1.2, 0.03, M_PI + 0.1, 0.01);
|
||||
Pose2D init;
|
||||
init.x = 1.22;
|
||||
init.y = 0.0;
|
||||
init.yaw = M_PI + 0.08;
|
||||
const PoseFitResult a = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
const PoseFitResult b = fitCartPose(LegModel::fromProfile(p), pts, init, s300Noise());
|
||||
EXPECT_EQ(a.pose.x, b.pose.x);
|
||||
EXPECT_EQ(a.pose.y, b.pose.y);
|
||||
EXPECT_EQ(a.pose.yaw, b.pose.yaw);
|
||||
EXPECT_EQ(a.iterations, b.iterations);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, ProcrustesRecoversAnExactPose)
|
||||
{
|
||||
const LegModel m = LegModel::fromProfile(tciTrolley());
|
||||
Pose2D truth;
|
||||
truth.x = 1.5;
|
||||
truth.y = -0.3;
|
||||
truth.yaw = 2.7;
|
||||
std::vector<std::array<double, 2>> model_pts, scan_pts;
|
||||
for (int k = 0; k < 3; ++k)
|
||||
{
|
||||
const std::array<double, 2> c = m.corner(k);
|
||||
model_pts.push_back(c);
|
||||
scan_pts.push_back({ truth.x + std::cos(truth.yaw) * c[0] - std::sin(truth.yaw) * c[1],
|
||||
truth.y + std::sin(truth.yaw) * c[0] + std::cos(truth.yaw) * c[1] });
|
||||
}
|
||||
Pose2D out;
|
||||
ASSERT_TRUE(dock_pattern_detector::procrustes2D(model_pts, scan_pts, out));
|
||||
EXPECT_NEAR(out.x, truth.x, 1e-9);
|
||||
EXPECT_NEAR(out.y, truth.y, 1e-9);
|
||||
EXPECT_NEAR(yawError(out.yaw, truth.yaw), 0.0, 1e-9);
|
||||
}
|
||||
|
||||
TEST(LegPoseFit, BoxSignedDistanceIsZeroOnTheFaceAndSignedInside)
|
||||
{
|
||||
const LegModel m = LegModel::fromProfile(tciTrolley());
|
||||
const std::array<double, 2> c = m.corner(dock_pattern_detector::kEntryLeft);
|
||||
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0] + 0.015, c[1]), 0.0, 1e-12);
|
||||
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0], c[1]), -0.015, 1e-12);
|
||||
EXPECT_NEAR(m.signedDistance(dock_pattern_detector::kEntryLeft, c[0] + 0.115, c[1]), 0.10, 1e-12);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main(int argc, char** argv)
|
||||
{
|
||||
testing::InitGoogleTest(&argc, argv);
|
||||
return RUN_ALL_TESTS();
|
||||
}
|
||||
216
test/leg_scan_sim.h
Normal file
216
test/leg_scan_sim.h
Normal file
@@ -0,0 +1,216 @@
|
||||
/*********************************************************************
|
||||
*
|
||||
* Software License Agreement (BSD License)
|
||||
*
|
||||
* Dựng scan TỔNG HỢP cho test dò xe hàng: đặt chân hộp/tròn, tường, vật cản vào một thế giới 2D,
|
||||
* chiếu tia từ gốc, biết trước đáp án. Chỉ dùng trong test.
|
||||
*
|
||||
* Author: DuongTD
|
||||
*********************************************************************/
|
||||
#ifndef DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_
|
||||
#define DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_
|
||||
|
||||
#include <cmath>
|
||||
#include <cstddef>
|
||||
#include <limits>
|
||||
#include <random>
|
||||
#include <vector>
|
||||
|
||||
#include <robot_line_extraction/types.h>
|
||||
|
||||
#include <dock_pattern_detector/leg_profile.h>
|
||||
|
||||
namespace leg_scan_sim
|
||||
{
|
||||
|
||||
struct Segment
|
||||
{
|
||||
double ax, ay, bx, by; // [m]
|
||||
int shape; // vật mà đoạn thuộc về
|
||||
};
|
||||
|
||||
struct Circle
|
||||
{
|
||||
double cx, cy, r; // [m]
|
||||
int shape;
|
||||
};
|
||||
|
||||
/// @brief Thế giới 2D. Mỗi vật có một id; vật có id trong `bright` trả cường độ cao.
|
||||
struct World
|
||||
{
|
||||
std::vector<Segment> segments;
|
||||
std::vector<Circle> circles;
|
||||
std::vector<bool> bright; // theo id vật
|
||||
int next_id = 0;
|
||||
|
||||
int newShape(bool is_bright = false)
|
||||
{
|
||||
bright.push_back(is_bright);
|
||||
return next_id++;
|
||||
}
|
||||
|
||||
/// @brief Hộp tâm (cx, cy), cạnh `size_x` dọc trục x của nó, `size_y` dọc trục y, xoay `yaw`.
|
||||
int addBox(double cx, double cy, double size_x, double size_y, double yaw, bool is_bright = false)
|
||||
{
|
||||
const int id = newShape(is_bright);
|
||||
const double c = std::cos(yaw);
|
||||
const double s = std::sin(yaw);
|
||||
const double hx = size_x / 2.0;
|
||||
const double hy = size_y / 2.0;
|
||||
const double lx[4] = { hx, -hx, -hx, hx };
|
||||
const double ly[4] = { hy, hy, -hy, -hy };
|
||||
double px[4], py[4];
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
px[i] = cx + c * lx[i] - s * ly[i];
|
||||
py[i] = cy + s * lx[i] + c * ly[i];
|
||||
}
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
const int j = (i + 1) % 4;
|
||||
segments.push_back({ px[i], py[i], px[j], py[j], id });
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
int addCircle(double cx, double cy, double r, bool is_bright = false)
|
||||
{
|
||||
const int id = newShape(is_bright);
|
||||
circles.push_back({ cx, cy, r, id });
|
||||
return id;
|
||||
}
|
||||
|
||||
int addWall(double ax, double ay, double bx, double by)
|
||||
{
|
||||
const int id = newShape(false);
|
||||
segments.push_back({ ax, ay, bx, by, id });
|
||||
return id;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Đặt 4 chân của xe: tâm (cx, cy), trục x của xe (pháp tuyến cạnh vào hướng ra ngoài) theo
|
||||
* @p axis. Bỏ chân nào thì đặt `skip[k] = true` (thứ tự góc như `LegCorner`).
|
||||
* @return id của 4 chân (−1 nếu bỏ).
|
||||
*/
|
||||
inline std::vector<int> addCart(World& w, const dock_pattern_detector::LegProfile& p, double cx,
|
||||
double cy, double axis, const bool skip[4] = nullptr,
|
||||
const bool taped[4] = nullptr)
|
||||
{
|
||||
const double hx = p.cart_depth / 2.0;
|
||||
const double hy = p.cart_opening / 2.0;
|
||||
const double lx[4] = { hx, hx, -hx, -hx };
|
||||
const double ly[4] = { hy, -hy, hy, -hy };
|
||||
const double c = std::cos(axis);
|
||||
const double s = std::sin(axis);
|
||||
std::vector<int> ids(4, -1);
|
||||
for (int k = 0; k < 4; ++k)
|
||||
{
|
||||
if (skip != nullptr && skip[k])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const double x = cx + c * lx[k] - s * ly[k];
|
||||
const double y = cy + s * lx[k] + c * ly[k];
|
||||
const bool is_bright = taped != nullptr && taped[k];
|
||||
if (p.leg_shape == dock_pattern_detector::LegShape::kRound)
|
||||
{
|
||||
ids[k] = w.addCircle(x, y, p.leg_width / 2.0, is_bright);
|
||||
}
|
||||
else
|
||||
{
|
||||
ids[k] = w.addBox(x, y, p.effectiveLegDepth(), p.leg_width, axis + p.leg_yaw_offset,
|
||||
is_bright);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
/// @brief Hình học SICK S300 sim của hook_150: 541 tia trên ±1.588 rad.
|
||||
inline robot_line_extraction::ScanGeometry s300Geometry()
|
||||
{
|
||||
robot_line_extraction::ScanGeometry g;
|
||||
g.angle_min = -1.588249619;
|
||||
g.size = 541;
|
||||
g.angle_increment = (2.0 * 1.588249619) / static_cast<double>(g.size - 1);
|
||||
return g;
|
||||
}
|
||||
|
||||
struct Scan
|
||||
{
|
||||
std::vector<double> ranges;
|
||||
std::vector<float> intensities;
|
||||
std::vector<int> hit; // id vật mà tia trúng, −1 nếu không trúng
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Chiếu tia từ gốc. @p sigma > 0 thì cộng nhiễu Gauss vào range, hạt giống @p seed cố định
|
||||
* — test vẫn tất định.
|
||||
*/
|
||||
inline Scan rayCast(const World& w, const robot_line_extraction::ScanGeometry& g, double sigma = 0.0,
|
||||
unsigned seed = 1)
|
||||
{
|
||||
constexpr double kInf = std::numeric_limits<double>::infinity();
|
||||
Scan scan;
|
||||
scan.ranges.assign(g.size, kInf);
|
||||
scan.intensities.assign(g.size, 0.0f);
|
||||
scan.hit.assign(g.size, -1);
|
||||
std::mt19937 rng(seed);
|
||||
std::normal_distribution<double> noise(0.0, sigma > 0.0 ? sigma : 1.0);
|
||||
|
||||
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);
|
||||
double best = kInf;
|
||||
int best_id = -1;
|
||||
|
||||
for (const Segment& s : w.segments)
|
||||
{
|
||||
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 < best)
|
||||
{
|
||||
best = t;
|
||||
best_id = s.shape;
|
||||
}
|
||||
}
|
||||
for (const Circle& c : w.circles)
|
||||
{
|
||||
// |t·d − c|² = r² → t² − 2t(d·c) + |c|² − r² = 0
|
||||
const double b = dx * c.cx + dy * c.cy;
|
||||
const double disc = b * b - (c.cx * c.cx + c.cy * c.cy - c.r * c.r);
|
||||
if (disc < 0.0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
const double t = b - std::sqrt(disc);
|
||||
if (t > 0.0 && t < best)
|
||||
{
|
||||
best = t;
|
||||
best_id = c.shape;
|
||||
}
|
||||
}
|
||||
|
||||
if (best_id >= 0)
|
||||
{
|
||||
const double n = sigma > 0.0 ? noise(rng) : 0.0;
|
||||
scan.ranges[i] = best + n;
|
||||
scan.hit[i] = best_id;
|
||||
scan.intensities[i] = w.bright[best_id] ? 2000.0f : 100.0f;
|
||||
}
|
||||
}
|
||||
return scan;
|
||||
}
|
||||
|
||||
} // namespace leg_scan_sim
|
||||
|
||||
#endif // DOCK_PATTERN_DETECTOR_TEST_LEG_SCAN_SIM_H_
|
||||
Reference in New Issue
Block a user