diff --git a/CMakeLists.txt b/CMakeLists.txt index 3cf9725..80ca6da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -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() diff --git a/README.md b/README.md index f2d8cfa..6c074b8 100644 --- a/README.md +++ b/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` → diff --git a/include/dock_pattern_detector/leg_pattern_matcher.h b/include/dock_pattern_detector/leg_pattern_matcher.h new file mode 100644 index 0000000..40c9dc3 --- /dev/null +++ b/include/dock_pattern_detector/leg_pattern_matcher.h @@ -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 +#include +#include +#include + +#include + +#include +#include + +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 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& ranges, const std::vector& 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 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 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& ranges, const std::vector& 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 rays_; + std::vector cluster_; + std::vector legs_; + std::vector hypotheses_; + std::vector fit_points_; + std::vector 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_ diff --git a/include/dock_pattern_detector/leg_pose_fit.h b/include/dock_pattern_detector/leg_pose_fit.h new file mode 100644 index 0000000..f65d720 --- /dev/null +++ b/include/dock_pattern_detector/leg_pose_fit.h @@ -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 +#include +#include + +#include + +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 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>& model, + const std::vector>& 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& points, + const Pose2D& initial, const FitNoise& noise, int max_iterations = 10); + +} // namespace dock_pattern_detector + +#endif // DOCK_PATTERN_DETECTOR_LEG_POSE_FIT_H_ diff --git a/include/dock_pattern_detector/leg_profile.h b/include/dock_pattern_detector/leg_profile.h new file mode 100644 index 0000000..c11b85e --- /dev/null +++ b/include/dock_pattern_detector/leg_profile.h @@ -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 +#include +#include +#include + +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_ diff --git a/src/leg_pattern_matcher.cpp b/src/leg_pattern_matcher.cpp new file mode 100644 index 0000000..376263b --- /dev/null +++ b/src/leg_pattern_matcher.cpp @@ -0,0 +1,1141 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * dock_pattern_detector — tìm xe hàng 4 chân trong một LaserScan thô. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace dock_pattern_detector +{ +namespace +{ +/// Chặn trên số cụm chân đưa vào bước ghép cặp. Bước 4 là O(k²); 40 cụm = 780 cặp, vẫn rẻ. Kho +/// có hơn 40 vật mảnh đứng tự do trong tầm thì giữ 40 cụm GẦN nhất — xe cần dò luôn ở gần. +constexpr std::size_t kMaxLegCandidates = 40; + +/// Số tia kéo đuôi tối đa bỏ qua khi tìm tia hàng xóm của mép cụm. +constexpr std::size_t kMaxShadowSkip = 5; + +/// Hai giả thuyết trùng nhau nếu tâm cách dưới ngần này và trục lệch dưới 3°. +constexpr double kDedupDistance = 0.05; // [m] +constexpr double kDedupAxis = 3.0 * M_PI / 180.0; // [rad] + +/// Hai xe được coi là KHÁC CHỖ khi tâm cách nhau quá ngần này (cổng mơ hồ). +constexpr double kAmbiguityDistance = 0.10; // [m] + +/// Nới cổng prior lúc lập giả thuyết (trước khi khớp), để tâm thô lệch vài cm không bị loại oan. +constexpr double kPriorPreGateSlack = 0.20; // [m] + +constexpr int kMaxFitRounds = 3; + +/// Cổng cuối cùng một giả thuyết đã tới. Thứ tự = mức tiến xa; lý do báo ra lấy cổng xa nhất. +enum Stage : int +{ + kStageLegs = 0, + kStageFit, + kStageMissing, + kStageInterior, + kStageEntryTape, + kStagePrior, + kStageConfidence, + kStagePassed, + kStageCount +}; + +double wrap(double a) +{ + return std::atan2(std::sin(a), std::cos(a)); +} + +double angleDiff(double a, double b) +{ + return std::fabs(wrap(a - b)); +} + +/// @brief Độ lệch hai trục không hướng (mod π). +double axisDiff(double a, double b) +{ + return std::fabs(wrap(2.0 * (a - b))) / 2.0; +} + +std::array toScan(const Pose2D& pose, const std::array& local) +{ + const double c = std::cos(pose.yaw); + const double s = std::sin(pose.yaw); + return { pose.x + c * local[0] - s * local[1], pose.y + s * local[0] + c * local[1] }; +} + +std::array toFrame(const Pose2D& frame, double x, double y) +{ + const double c = std::cos(frame.yaw); + const double s = std::sin(frame.yaw); + return { frame.x + c * x - s * y, frame.y + s * x + c * y }; +} + +std::string format(const char* fmt, double a, double b = 0.0, double c = 0.0, double d = 0.0) +{ + char buffer[256]; + std::snprintf(buffer, sizeof(buffer), fmt, a, b, c, d); + return buffer; +} +} // namespace + +bool LegPatternMatcher::configure(const LegProfile& 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. + } + profile_ = profile; + model_ = LegModel::fromProfile(profile); + configured_ = true; + return true; +} + +// ================================================================================================ +// Bước 1: tia +// ================================================================================================ + +void LegPatternMatcher::prepareRays(const robot_line_extraction::ScanGeometry& geometry, + const std::vector& ranges, + const std::vector& intensities, + const ScanLimits& limits, const Pose2D& scan_in_prior_frame) +{ + rays_.resize(geometry.size); + for (std::size_t i = 0; i < geometry.size; ++i) + { + Ray& r = rays_[i]; + r = Ray(); + r.range = ranges[i]; + r.valid = std::isfinite(r.range) && r.range >= limits.min_range && r.range <= limits.max_range; + if (!r.valid) + { + continue; + } + + const double bearing = geometry.angle_min + static_cast(i) * geometry.angle_increment; + r.x = r.range * std::cos(bearing); + r.y = r.range * std::sin(bearing); + + if (profile_.search_fov > 0.0) + { + // Quạt tính trong prior_frame (thường là base_link), không trong frame lidar: lidar có thể + // gắn lệch và xoay so với hướng robot. + const std::array p = toFrame(scan_in_prior_frame, r.x, r.y); + r.in_fan = std::fabs(std::atan2(p[1], p[0])) <= profile_.search_fov; + } + + if (profile_.tape_enabled) + { + r.bright = intensities[i] >= profile_.tape_min_intensity; + } + } +} + +void LegPatternMatcher::filterShadows(double dtheta) +{ + if (profile_.shadow_min_angle <= 0.0) + { + return; + } + + // Với hai tia kề A (xa hơn) và B (gần hơn), góc tại A giữa tia OA và đoạn AB là + // β = atan(OB·sinΔθ / (OA − OB·cosΔθ)). β nhỏ = A nằm gần như dọc theo tia: điểm lai giữa vật + // trước và nền sau. Chỉ đánh dấu A (điểm XA), nên điểm của chân — luôn là điểm gần — không mất. + const double sin_d = std::sin(dtheta); + const double cos_d = std::cos(dtheta); + const std::size_t n = rays_.size(); + for (std::size_t i = 0; i < n; ++i) + { + if (!rays_[i].valid) + { + continue; + } + for (int step = -1; step <= 1; step += 2) + { + const long j = static_cast(i) + step; + if (j < 0 || j >= static_cast(n) || !rays_[j].valid) + { + continue; + } + const double oa = rays_[i].range; + const double ob = rays_[j].range; + if (oa <= ob) + { + continue; + } + const double beta = std::atan2(ob * sin_d, oa - ob * cos_d); + if (beta < profile_.shadow_min_angle) + { + rays_[i].shadow = true; + } + } + } +} + +// ================================================================================================ +// Bước 2–3: cụm và chân +// ================================================================================================ + +int LegPatternMatcher::classifyEdge(std::size_t edge, int step) const +{ + const long n = static_cast(rays_.size()); + const double r_edge = rays_[edge].range; + + long j = static_cast(edge) + step; + std::size_t skipped = 0; + while (j >= 0 && j < n && rays_[j].valid && rays_[j].shadow && skipped < kMaxShadowSkip) + { + j += step; + ++skipped; + } + + if (j < 0 || j >= n) + { + return 1; // mép scan: không thấy được phía ngoài, coi như bị che + } + + const Ray& nb = rays_[j]; + if (!nb.valid) + { + // Có phản hồi nhưng gần hơn min_range: có vật sát cảm biến chắn. Không phản hồi hoặc xa hơn + // max_range: phía sau trống. + return (std::isfinite(nb.range) && nb.range < min_range_) ? 1 : 0; + } + if (!nb.in_fan) + { + return 1; // mép quạt tìm kiếm: không biết phía ngoài có gì + } + if (nb.shadow) + { + return 0; // còn kéo đuôi sau khi đã bỏ qua tối đa: một chuỗi điểm lai dẫn ra nền phía sau + } + if (nb.range >= r_edge + profile_.leg_min_depth_gap) + { + return 0; + } + if (nb.range <= r_edge - profile_.leg_min_depth_gap) + { + return 1; + } + return 2; +} + +void LegPatternMatcher::processCluster(double dtheta) +{ + ++clusters_; + + const int left = classifyEdge(cluster_.front(), -1); + const int right = classifyEdge(cluster_.back(), +1); + if (left == 2 || right == 2) + { + // Mép liền với vật khác ở cùng tầm: tường, tủ, thanh giằng. Không phải chân đứng tự do. + ++rejected_attached_; + return; + } + const bool partial = (left == 1 || right == 1); + + double r_min = std::numeric_limits::infinity(); + for (std::size_t idx : cluster_) + { + r_min = std::min(r_min, rays_[idx].range); + } + + // Cắt điểm xa: không điểm nào của một chân nằm xa hơn điểm gần nhất quá bề rộng biểu kiến lớn + // nhất. Lớp thứ hai sau bộ lọc kéo đuôi. + LegCandidate leg; + leg.partial = partial; + leg.r_min = r_min; + const double depth_limit = r_min + profile_.maxApparentLegWidth(); + for (std::size_t idx : cluster_) + { + if (rays_[idx].range <= depth_limit) + { + leg.points.push_back(idx); + } + } + if (leg.points.size() < profile_.min_leg_points) + { + ++rejected_points_; + return; + } + + // Dây cung giữa tia đầu và tia cuối luôn ngắn hơn bề rộng biểu kiến thật tới 2 khoảng tia: tia + // rơi BÊN TRONG mép vật. Cận dưới phải trừ phần đó, cận trên thì không. + const Ray& a = rays_[leg.points.front()]; + const Ray& b = rays_[leg.points.back()]; + const double chord = std::hypot(b.x - a.x, b.y - a.y); + const double upper = profile_.maxApparentLegWidth() + profile_.leg_width_tolerance; + const double lower = + profile_.minApparentLegWidth() - profile_.leg_width_tolerance - 2.0 * r_min * dtheta; + if (chord > upper || (!partial && chord < lower)) + { + ++rejected_width_; + const double miss = chord > upper ? chord - upper : lower - chord; + if (miss < width_miss_) + { + width_miss_ = miss; + } + return; + } + + for (std::size_t idx : leg.points) + { + if (rays_[idx].bright) + { + ++leg.bright; + } + } + if (profile_.tape_enabled && profile_.tape_legs == TapeLegs::kAll && + leg.bright < profile_.tape_min_points) + { + ++rejected_tape_; + return; + } + + // Tâm thô chỉ để lập giả thuyết: hướng trung bình của các tia, cự ly mặt gần + nửa bề rộng. + double ux = 0.0; + double uy = 0.0; + for (std::size_t idx : leg.points) + { + ux += rays_[idx].x / rays_[idx].range; + uy += rays_[idx].y / rays_[idx].range; + } + const double bearing = std::atan2(uy, ux); + const double centre_range = r_min + profile_.leg_width / 2.0; + leg.rough_x = centre_range * std::cos(bearing); + leg.rough_y = centre_range * std::sin(bearing); + leg.first = leg.points.front(); + leg.last = leg.points.back(); + legs_.push_back(std::move(leg)); +} + +void LegPatternMatcher::buildCandidates(double dtheta) +{ + legs_.clear(); + cluster_.clear(); + clusters_ = 0; + rejected_attached_ = 0; + rejected_width_ = 0; + rejected_points_ = 0; + rejected_tape_ = 0; + width_miss_ = std::numeric_limits::infinity(); + truncated_ = false; + + std::size_t gap = 0; // số tia không dùng được liên tiếp kể từ điểm cuối của cụm + for (std::size_t i = 0; i < rays_.size(); ++i) + { + if (!usable(i)) + { + if (!cluster_.empty()) + { + ++gap; + if (gap > 1) + { + processCluster(dtheta); + cluster_.clear(); + } + } + continue; + } + + if (!cluster_.empty()) + { + const Ray& prev = rays_[cluster_.back()]; + const double threshold = std::max( + profile_.leg_cluster_gap, 2.0 * rays_[i].range * dtheta * static_cast(gap + 1)); + if (std::hypot(rays_[i].x - prev.x, rays_[i].y - prev.y) > threshold) + { + processCluster(dtheta); + cluster_.clear(); + } + } + cluster_.push_back(i); + gap = 0; + } + if (!cluster_.empty()) + { + processCluster(dtheta); + cluster_.clear(); + } + + if (legs_.size() > kMaxLegCandidates) + { + std::stable_sort(legs_.begin(), legs_.end(), [](const LegCandidate& a, const LegCandidate& b) { + return a.r_min < b.r_min; + }); + legs_.resize(kMaxLegCandidates); + truncated_ = true; + } +} + +std::string LegPatternMatcher::describeClusterRejections() const +{ + std::string text = std::to_string(clusters_) + " cluster(s) in range: " + + std::to_string(rejected_attached_) + " attached to a surface, " + + std::to_string(rejected_width_) + " wrong width, " + + std::to_string(rejected_points_) + " too few rays"; + if (profile_.tape_enabled && profile_.tape_legs == TapeLegs::kAll) + { + text += ", " + std::to_string(rejected_tape_) + " without reflective tape"; + } + if (rejected_width_ > 0 && std::isfinite(width_miss_)) + { + text += format(" (closest width miss %.3f m; leg_width %.3f m)", width_miss_, + profile_.leg_width); + } + return text; +} + +// ================================================================================================ +// Bước 4: giả thuyết +// ================================================================================================ + +void LegPatternMatcher::addHypothesis(double cx, double cy, double axis, + const Pose2D& scan_in_prior_frame) +{ + // Quay trục x của xe về phía cảm biến: cạnh quay về robot là cạnh vào mặc định. Bước 8 có thể + // lật lại theo dải `entry` hoặc prior. + if (std::cos(axis) * (-cx) + std::sin(axis) * (-cy) < 0.0) + { + axis += M_PI; + } + axis = wrap(axis); + + if (profile_.has_prior) + { + const std::array c = toFrame(scan_in_prior_frame, cx, cy); + if (std::hypot(c[0] - profile_.prior_x, c[1] - profile_.prior_y) > + profile_.search_radius + kPriorPreGateSlack) + { + return; + } + } + + for (const Hypothesis& h : hypotheses_) + { + if (std::hypot(h.pose.x - cx, h.pose.y - cy) < kDedupDistance && + axisDiff(h.pose.yaw, axis) < kDedupAxis) + { + return; + } + } + + Hypothesis h; + h.pose.x = cx; + h.pose.y = cy; + h.pose.yaw = axis; + hypotheses_.push_back(std::move(h)); +} + +void LegPatternMatcher::generateHypotheses(double dtheta, const Pose2D& scan_in_prior_frame) +{ + hypotheses_.clear(); + const double opening = profile_.cart_opening; + const double depth = profile_.cart_depth; + const double diagonal = profile_.cartDiagonal(); + const double alpha = std::atan2(opening, depth); + + for (std::size_t i = 0; i < legs_.size(); ++i) + { + for (std::size_t j = i + 1; j < legs_.size(); ++j) + { + const LegCandidate& a = legs_[i]; + const LegCandidate& b = legs_[j]; + const double dx = b.rough_x - a.rough_x; + const double dy = b.rough_y - a.rough_y; + const double d = std::hypot(dx, dy); + if (d < 1e-6) + { + continue; + } + const double ux = dx / d; + const double uy = dy / d; + const double nx = -uy; + const double ny = ux; + const double mx = (a.rough_x + b.rough_x) / 2.0; + const double my = (a.rough_y + b.rough_y) / 2.0; + + // Dung sai nới theo lượng tử góc ở cự ly xa hơn, và thêm nửa chân cho mỗi chân partial: + // tâm thô của chân bị che một nửa lệch tới nửa bề rộng. + const double r = std::max(a.r_min, b.r_min); + const double tol = profile_.cart_dim_tolerance + r * dtheta + + (a.partial ? profile_.leg_width / 2.0 : 0.0) + + (b.partial ? profile_.leg_width / 2.0 : 0.0); + + if (std::fabs(d - opening) <= tol) + { + // Cặp là một cạnh dài `opening`: trục x của xe vuông góc với cặp; xe nằm về một trong hai + // phía của cặp. + const double axis = std::atan2(ny, nx); + addHypothesis(mx + nx * depth / 2.0, my + ny * depth / 2.0, axis, scan_in_prior_frame); + addHypothesis(mx - nx * depth / 2.0, my - ny * depth / 2.0, axis, scan_in_prior_frame); + } + if (std::fabs(d - depth) <= tol) + { + // Cặp là một cạnh dọc hướng chui: trục x của xe song song với cặp. + const double axis = std::atan2(uy, ux); + addHypothesis(mx + nx * opening / 2.0, my + ny * opening / 2.0, axis, scan_in_prior_frame); + addHypothesis(mx - nx * opening / 2.0, my - ny * opening / 2.0, axis, scan_in_prior_frame); + } + if (std::fabs(d - diagonal) <= tol) + { + // Cặp là đường chéo: tâm ở trung điểm; hai cách đặt hình chữ nhật đối xứng gương. + const double phi = std::atan2(uy, ux); + addHypothesis(mx, my, phi - alpha, scan_in_prior_frame); + addHypothesis(mx, my, phi + alpha, scan_in_prior_frame); + } + } + } +} + +// ================================================================================================ +// Bước 5–10: gán, khớp, kiểm +// ================================================================================================ + +int LegPatternMatcher::associate(Hypothesis& h, double dtheta) +{ + assoc_pairs_.clear(); + for (int k = 0; k < kLegCount; ++k) + { + const std::array corner = toScan(h.pose, model_.corner(k)); + const double radius = profile_.leg_assoc_radius + std::hypot(corner[0], corner[1]) * dtheta; + for (std::size_t c = 0; c < legs_.size(); ++c) + { + const double dist = + std::hypot(legs_[c].rough_x - corner[0], legs_[c].rough_y - corner[1]); + if (dist <= radius) + { + AssocPair p; + p.distance = dist; + p.corner = k; + p.leg = static_cast(c); + assoc_pairs_.push_back(p); + } + } + } + + // Gán tham lam theo cự ly tăng dần; hoà thì theo chỉ số — tất định. + std::sort(assoc_pairs_.begin(), assoc_pairs_.end(), [](const AssocPair& a, const AssocPair& b) { + if (a.distance != b.distance) + { + return a.distance < b.distance; + } + if (a.corner != b.corner) + { + return a.corner < b.corner; + } + return a.leg < b.leg; + }); + + h.legs = { { -1, -1, -1, -1 } }; + int count = 0; + for (const AssocPair& p : assoc_pairs_) + { + if (h.legs[p.corner] >= 0) + { + continue; + } + bool used = false; + for (int k = 0; k < kLegCount; ++k) + { + used = used || h.legs[k] == p.leg; + } + if (used) + { + continue; + } + h.legs[p.corner] = p.leg; + ++count; + } + return count; +} + +int LegPatternMatcher::classifyMissingCorner(double px, double py, const ScanLimits& limits) const +{ + const double rp = std::hypot(px, py); + if (rp < limits.min_range || rp > limits.max_range) + { + return 0; + } + + const double half_width = profile_.maxApparentLegWidth() / 2.0; + const double bearing = std::atan2(py, px); + const double half_angle = half_width / rp; + + const double t0 = (bearing - half_angle - angle_min_) / angle_increment_; + const double t1 = (bearing + half_angle - angle_min_) / angle_increment_; + long lo = static_cast(std::ceil(std::min(t0, t1))); + long hi = static_cast(std::floor(std::max(t0, t1))); + if (lo > hi) + { + lo = hi = static_cast(std::lround((bearing - angle_min_) / angle_increment_)); + } + const long n = static_cast(rays_.size()); + if (hi < 0 || lo >= n) + { + return 0; // ngoài góc quét + } + lo = std::max(lo, 0L); + hi = std::min(hi, n - 1); + + const double band = profile_.maxApparentLegWidth(); + bool nearer = false; + bool near = false; + for (long i = lo; i <= hi; ++i) + { + const Ray& r = rays_[i]; + if (r.valid && !r.in_fan) + { + return 0; // ngoài quạt tìm kiếm + } + if (!r.valid) + { + if (std::isfinite(r.range) && r.range < limits.min_range) + { + nearer = true; + } + continue; // không phản hồi: tia đi qua + } + if (r.range < rp - band) + { + nearer = true; + } + else if (std::fabs(r.range - rp) <= band) + { + near = true; + } + } + + if (near) + { + return 2; + } + if (nearer) + { + return 1; + } + return 3; +} + +void LegPatternMatcher::classifyMissingCorners(const Hypothesis& h, const ScanLimits& limits, + int& occluded, int& distorted, int& out_of_view, + int& see_through) const +{ + occluded = distorted = out_of_view = see_through = 0; + for (int k = 0; k < kLegCount; ++k) + { + if (h.legs[k] >= 0) + { + continue; + } + const std::array corner = toScan(h.pose, model_.corner(k)); + switch (classifyMissingCorner(corner[0], corner[1], limits)) + { + case 0: + ++out_of_view; + break; + case 1: + ++occluded; + break; + case 2: + ++distorted; + break; + default: + ++see_through; + break; + } + } +} + +bool LegPatternMatcher::evaluate(Hypothesis& h, const ScanLimits& limits, + const Pose2D& scan_in_prior_frame, double dtheta) +{ + int occluded = 0, distorted = 0, out_of_view = 0, see_through = 0; + + // --- Gán thô: cổng rẻ nhất, cắt phần lớn giả thuyết trước khi khớp ------------------------------ + if (associate(h, dtheta) < profile_.min_legs) + { + h.stage = kStageLegs; + classifyMissingCorners(h, limits, occluded, distorted, out_of_view, see_through); + int seen = 0; + for (int k = 0; k < kLegCount; ++k) + { + seen += h.legs[k] >= 0 ? 1 : 0; + } + h.failure = std::to_string(seen) + " leg(s) seen, " + std::to_string(occluded) + + " occluded, " + std::to_string(distorted) + " distorted, " + + std::to_string(out_of_view) + " out of view (min_legs " + + std::to_string(profile_.min_legs) + ")"; + return false; + } + + // --- Khởi tạo bằng Procrustes trên tâm thô -------------------------------------------------------- + std::vector> model_pts; + std::vector> scan_pts; + for (int k = 0; k < kLegCount; ++k) + { + if (h.legs[k] >= 0) + { + model_pts.push_back(model_.corner(k)); + scan_pts.push_back({ legs_[h.legs[k]].rough_x, legs_[h.legs[k]].rough_y }); + } + } + Pose2D init; + if (!procrustes2D(model_pts, scan_pts, init)) + { + h.stage = kStageFit; + h.failure = "could not initialise the pose"; + return false; + } + h.pose = init; + + // --- Gán lại và khớp trên mọi điểm chân, lặp tới khi phép gán đứng yên -------------------------- + FitNoise noise; + noise.range_sigma = limits.range_sigma; + noise.angle_increment = dtheta; + PoseFitResult fit; + for (int round = 0; round < kMaxFitRounds; ++round) + { + if (associate(h, dtheta) < profile_.min_legs) + { + h.stage = kStageLegs; + h.failure = "legs drifted out of their corners while fitting"; + return false; + } + fit_points_.clear(); + for (int k = 0; k < kLegCount; ++k) + { + if (h.legs[k] < 0) + { + continue; + } + for (std::size_t idx : legs_[h.legs[k]].points) + { + FitPoint p; + p.x = rays_[idx].x; + p.y = rays_[idx].y; + p.corner = k; + fit_points_.push_back(p); + } + } + fit = fitCartPose(model_, fit_points_, h.pose, noise); + if (!fit.valid) + { + h.stage = kStageFit; + h.failure = "pose fit diverged"; + return false; + } + const std::array before = h.legs; + h.pose = fit.pose; + associate(h, dtheta); + if (h.legs == before) + { + break; + } + } + + int seen = 0; + int partial = 0; + for (int k = 0; k < kLegCount; ++k) + { + if (h.legs[k] >= 0) + { + ++seen; + partial += legs_[h.legs[k]].partial ? 1 : 0; + } + } + if (seen < profile_.min_legs) + { + h.stage = kStageLegs; + h.failure = "only " + std::to_string(seen) + " leg(s) remain after fitting"; + return false; + } + + // --- Khoảng cách giữa các chân đã gán ------------------------------------------------------------ + // Khớp cứng luôn ra MỘT pose, kể cả khi bốn "chân" là chân của hai xe kề nhau đứng lệch vài cm so + // với mô hình: phần dư dàn đều, điểm tin vẫn có thể qua. Kiểm thẳng từng cặp chặn ca đó, cùng + // dung sai với bước ghép cặp. + static const int kPairs[6][2] = { { kEntryLeft, kEntryRight }, { kFarLeft, kFarRight }, + { kEntryLeft, kFarLeft }, { kEntryRight, kFarRight }, + { kEntryLeft, kFarRight }, { kEntryRight, kFarLeft } }; + for (int pair = 0; pair < 6; ++pair) + { + const int ia = h.legs[kPairs[pair][0]]; + const int ib = h.legs[kPairs[pair][1]]; + if (ia < 0 || ib < 0) + { + continue; + } + const LegCandidate& la = legs_[ia]; + const LegCandidate& lb = legs_[ib]; + const double expected = pair < 2 ? profile_.cart_opening : + pair < 4 ? profile_.cart_depth : + profile_.cartDiagonal(); + const double tol = profile_.cart_dim_tolerance + std::max(la.r_min, lb.r_min) * dtheta + + (la.partial ? profile_.leg_width / 2.0 : 0.0) + + (lb.partial ? profile_.leg_width / 2.0 : 0.0); + const double d = std::hypot(la.rough_x - lb.rough_x, la.rough_y - lb.rough_y); + if (std::fabs(d - expected) > tol) + { + h.stage = kStageFit; + h.failure = format("two legs %.3f m apart where the cart has %.3f m (tolerance %.3f m)", d, + expected, tol); + return false; + } + } + + // --- Bước 6: bằng chứng phủ định ------------------------------------------------------------------ + classifyMissingCorners(h, limits, occluded, distorted, out_of_view, see_through); + if (see_through > 0) + { + h.stage = kStageMissing; + h.failure = std::to_string(see_through) + + " leg position(s) seen straight through (leg_missing): the scan passes where a " + "leg must stand"; + return false; + } + + // --- Bước 7: lòng xe trống ---------------------------------------------------------------------- + if (profile_.max_interior_points >= 0) + { + const double hx = profile_.cart_depth / 2.0 - profile_.interior_margin; + const double hy = profile_.cart_opening / 2.0 - profile_.interior_margin; + const double c = std::cos(h.pose.yaw); + const double s = std::sin(h.pose.yaw); + int inside = 0; + for (const Ray& r : rays_) + { + if (!r.valid || r.shadow) + { + continue; + } + const double dx = r.x - h.pose.x; + const double dy = r.y - h.pose.y; + const double lx = c * dx + s * dy; + const double ly = -s * dx + c * dy; + if (std::fabs(lx) < hx && std::fabs(ly) < hy) + { + ++inside; + } + } + if (inside > profile_.max_interior_points) + { + h.stage = kStageInterior; + h.failure = std::to_string(inside) + " scan point(s) inside the cart (max_interior_points " + + std::to_string(profile_.max_interior_points) + ")"; + return false; + } + } + + // --- Bước 8: chọn cạnh vào ------------------------------------------------------------------------ + bool flip = false; + if (profile_.tape_enabled && profile_.tape_legs == TapeLegs::kEntry) + { + bool bright_entry = false; + bool bright_far = false; + for (int k = 0; k < kLegCount; ++k) + { + if (h.legs[k] < 0 || legs_[h.legs[k]].bright < profile_.tape_min_points) + { + continue; + } + if (k == kEntryLeft || k == kEntryRight) + { + bright_entry = true; + } + else + { + bright_far = true; + } + } + if (!bright_entry && !bright_far) + { + h.stage = kStageEntryTape; + h.failure = "no taped leg seen (entry_tape_not_seen)"; + return false; + } + if (bright_entry && bright_far) + { + h.stage = kStageEntryTape; + h.failure = "taped legs on both ends (entry_tape_ambiguous)"; + return false; + } + flip = bright_far; + } + else if (profile_.has_prior && profile_.prior_yaw_tolerance < M_PI / 2.0) + { + const double yaw_prior = h.pose.yaw + scan_in_prior_frame.yaw; + flip = angleDiff(yaw_prior + M_PI, profile_.prior_yaw) < angleDiff(yaw_prior, profile_.prior_yaw); + } + if (flip) + { + // Lật hệ xe 180°: góc k cũ thành góc 3 − k mới (trước-trái ↔ sau-phải, trước-phải ↔ sau-trái). + h.pose.yaw = wrap(h.pose.yaw + M_PI); + const std::array old = h.legs; + for (int k = 0; k < kLegCount; ++k) + { + h.legs[3 - k] = old[k]; + } + } + + // --- Bước 9: cổng prior --------------------------------------------------------------------------- + if (profile_.has_prior) + { + const std::array c = toFrame(scan_in_prior_frame, h.pose.x, h.pose.y); + const double dist = std::hypot(c[0] - profile_.prior_x, c[1] - profile_.prior_y); + const double dyaw = angleDiff(h.pose.yaw + scan_in_prior_frame.yaw, profile_.prior_yaw); + if (dist > profile_.search_radius || dyaw > profile_.prior_yaw_tolerance) + { + h.stage = kStagePrior; + h.failure = format("centre (%.2f, %.2f) in prior frame, %.2f m from the prior; yaw off by " + "%.2f rad", + c[0], c[1], dist, dyaw); + return false; + } + } + + // --- Bước 10: điểm tin ---------------------------------------------------------------------------- + // Nửa từ số chân thấy, nửa từ mức khớp: RMS chuẩn hoá ≤ 1 là khớp đúng mô hình nhiễu, 2 là tệ. + const double seen_term = static_cast(seen) / static_cast(kLegCount); + const double fit_term = std::max(0.0, std::min(1.0, 2.0 - fit.normalized_rms)); + h.confidence = 0.5 * seen_term + 0.5 * fit_term; + if (h.confidence < profile_.min_confidence) + { + h.stage = kStageConfidence; + h.failure = format("confidence %.2f < min_confidence %.2f (fit rms %.4f m, %.0f legs seen)", + h.confidence, profile_.min_confidence, fit.rms, static_cast(seen)); + return false; + } + + // --- Kết quả -------------------------------------------------------------------------------------- + LegDetection& d = h.detail; + d = LegDetection(); + d.valid = true; + d.center_x = h.pose.x; + d.center_y = h.pose.y; + d.center_yaw = h.pose.yaw; + d.confidence = h.confidence; + d.legs_seen = seen; + d.legs_partial = partial; + d.legs_occluded = occluded; + d.legs_distorted = distorted; + d.legs_out_of_view = out_of_view; + d.fit_rms = fit.rms; + d.fit_iterations = fit.iterations; + + // Đích = tâm dịch theo offset, trong hệ của chính xe: x dọc pháp tuyến cạnh vào hướng ra phía + // robot, y sang trái — cùng công thức V/arc. + const double cos_y = std::cos(h.pose.yaw); + const double sin_y = std::sin(h.pose.yaw); + d.x = h.pose.x + cos_y * profile_.offset_x - sin_y * profile_.offset_y; + d.y = h.pose.y + sin_y * profile_.offset_x + cos_y * profile_.offset_y; + d.yaw = wrap(h.pose.yaw + profile_.offset_yaw); + + // Kích thước đo từ tâm thô: chẩn đoán sớm khai sai số hoặc xe méo, không dùng để tính pose. + const auto measure = [&](int a, int b, double& sum, int& count) { + if (h.legs[a] >= 0 && h.legs[b] >= 0) + { + const LegCandidate& la = legs_[h.legs[a]]; + const LegCandidate& lb = legs_[h.legs[b]]; + sum += std::hypot(la.rough_x - lb.rough_x, la.rough_y - lb.rough_y); + ++count; + } + }; + double opening_sum = 0.0, depth_sum = 0.0; + int opening_n = 0, depth_n = 0; + measure(kEntryLeft, kEntryRight, opening_sum, opening_n); + measure(kFarLeft, kFarRight, opening_sum, opening_n); + measure(kEntryLeft, kFarLeft, depth_sum, depth_n); + measure(kEntryRight, kFarRight, depth_sum, depth_n); + d.measured_opening = opening_n > 0 ? opening_sum / opening_n : 0.0; + d.measured_depth = depth_n > 0 ? depth_sum / depth_n : 0.0; + + for (int k = 0; k < kLegCount; ++k) + { + d.tape_bright_rays[k] = h.legs[k] >= 0 ? legs_[h.legs[k]].bright : 0; + } + + h.stage = kStagePassed; + return true; +} + +// ================================================================================================ +// Toàn bộ +// ================================================================================================ + +LegDetection LegPatternMatcher::match(const robot_line_extraction::ScanGeometry& geometry, + const std::vector& ranges, + const std::vector& intensities, + const ScanLimits& limits, const Pose2D& scan_in_prior_frame) +{ + LegDetection out; + if (!configured_) + { + out.reason = "leg matcher is not configured"; + return out; + } + if (geometry.size == 0 || ranges.size() != geometry.size || + !std::isfinite(geometry.angle_min) || !std::isfinite(geometry.angle_increment) || + geometry.angle_increment == 0.0) + { + out.reason = "scan geometry does not match the ranges (" + std::to_string(ranges.size()) + + " ranges, " + std::to_string(geometry.size) + " rays)"; + return out; + } + if (!std::isfinite(limits.min_range) || !std::isfinite(limits.max_range) || + limits.max_range <= limits.min_range || !(limits.range_sigma > 0.0)) + { + out.reason = "invalid scan limits (min_range, max_range, range_sigma)"; + return out; + } + if (profile_.tape_enabled && intensities.size() != ranges.size()) + { + // Nói ra thay vì im lặng dò không xong: profile đòi dải mà driver không gửi cường độ. + out.reason = intensities.empty() + ? "profile requires reflective tape but the scan has no intensity data" + : "intensities size " + std::to_string(intensities.size()) + + " differs from ranges size " + std::to_string(ranges.size()); + return out; + } + + const double dtheta = std::fabs(geometry.angle_increment); + angle_min_ = geometry.angle_min; + angle_increment_ = geometry.angle_increment; + min_range_ = limits.min_range; + + prepareRays(geometry, ranges, intensities, limits, scan_in_prior_frame); + filterShadows(dtheta); + buildCandidates(dtheta); + out.leg_candidates = legs_.size(); + + if (legs_.size() < 2) + { + out.reason = std::to_string(legs_.size()) + " leg-like cluster(s) — " + + describeClusterRejections(); + return out; + } + + generateHypotheses(dtheta, scan_in_prior_frame); + out.hypotheses = hypotheses_.size(); + if (hypotheses_.empty()) + { + double closest = std::numeric_limits::infinity(); + for (std::size_t i = 0; i < legs_.size(); ++i) + { + for (std::size_t j = i + 1; j < legs_.size(); ++j) + { + const double d = std::hypot(legs_[i].rough_x - legs_[j].rough_x, + legs_[i].rough_y - legs_[j].rough_y); + const double miss = std::min({ std::fabs(d - profile_.cart_opening), + std::fabs(d - profile_.cart_depth), + std::fabs(d - profile_.cartDiagonal()) }); + closest = std::min(closest, miss); + } + } + out.reason = std::to_string(legs_.size()) + + " leg-like cluster(s) but no pair spaced like the cart" + + format(" (cart_opening %.3f, cart_depth %.3f, diagonal %.3f m; closest pair " + "misses by %.3f m)", + profile_.cart_opening, profile_.cart_depth, profile_.cartDiagonal(), + closest); + if (profile_.has_prior) + { + out.reason += ", or all were outside the search gate"; + } + return out; + } + + std::array stage_counts{}; + std::vector accepted; + for (std::size_t i = 0; i < hypotheses_.size(); ++i) + { + if (evaluate(hypotheses_[i], limits, scan_in_prior_frame, dtheta)) + { + accepted.push_back(i); + } + ++stage_counts[hypotheses_[i].stage]; + } + out.accepted = accepted.size(); + + if (accepted.empty()) + { + // Báo cổng XA NHẤT mà giả thuyết nào đó đã tới: đó là chỗ gần thành công nhất, và là chỗ + // cần chỉnh. + int furthest = kStageLegs; + for (const Hypothesis& h : hypotheses_) + { + furthest = std::max(furthest, h.stage); + } + std::string detail; + for (const Hypothesis& h : hypotheses_) + { + if (h.stage == furthest) + { + detail = h.failure; + break; + } + } + static const char* const kStageText[kStageCount] = { + "too few legs", "pose fit failed", "a leg is missing", "cart interior not empty", + "entry tape check failed", "outside the search gate", "low confidence", "passed" + }; + out.reason = std::to_string(hypotheses_.size()) + " cart hypothesis(es) from " + + std::to_string(legs_.size()) + " leg-like cluster(s), " + + std::to_string(stage_counts[furthest]) + " stopped at '" + + kStageText[furthest] + "': " + detail; + return out; + } + + // Xếp theo điểm tin; hoà thì xe gần cảm biến hơn, rồi theo thứ tự lập — tất định. + std::stable_sort(accepted.begin(), accepted.end(), [this](std::size_t a, std::size_t b) { + const Hypothesis& ha = hypotheses_[a]; + const Hypothesis& hb = hypotheses_[b]; + if (ha.confidence != hb.confidence) + { + return ha.confidence > hb.confidence; + } + return std::hypot(ha.pose.x, ha.pose.y) < std::hypot(hb.pose.x, hb.pose.y); + }); + + const Hypothesis& best = hypotheses_[accepted.front()]; + for (std::size_t k = 1; k < accepted.size(); ++k) + { + const Hypothesis& other = hypotheses_[accepted[k]]; + if (std::hypot(other.pose.x - best.pose.x, other.pose.y - best.pose.y) <= kAmbiguityDistance) + { + continue; // cùng một xe, lập từ cặp chân khác + } + if (other.confidence >= (1.0 - profile_.ambiguity_margin) * best.confidence) + { + // Hai xe điểm sát nhau ở hai chỗ: dãy xe đỗ sát, hoặc chân của hai xe kề nhau ghép thành + // một "xe" giả. Chọn một trong hai là đoán — từ chối cả lượt. + out.reason = format("ambiguous: two carts score %.2f and %.2f at (%.2f, %.2f)", best.confidence, + other.confidence, best.pose.x, best.pose.y) + + format(" and (%.2f, %.2f); set a prior to pick one", other.pose.x, + other.pose.y); + return out; + } + break; + } + + LegDetection result = best.detail; + result.leg_candidates = out.leg_candidates; + result.hypotheses = out.hypotheses; + result.accepted = out.accepted; + return result; +} + +} // namespace dock_pattern_detector diff --git a/src/leg_pose_fit.cpp b/src/leg_pose_fit.cpp new file mode 100644 index 0000000..5a5cbb0 --- /dev/null +++ b/src/leg_pose_fit.cpp @@ -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 + +#include +#include +#include +#include + +#include + +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 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::infinity(); + double t_max = std::numeric_limits::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& 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 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 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>& model, + const std::vector>& 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(n); + my /= static_cast(n); + sx /= static_cast(n); + sy /= static_cast(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& 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(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 diff --git a/src/leg_profile.cpp b/src/leg_profile.cpp new file mode 100644 index 0000000..520b50d --- /dev/null +++ b/src/leg_profile.cpp @@ -0,0 +1,237 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * dock_pattern_detector — kiểm miền của LegProfile. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include + +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 diff --git a/test/leg_pattern_matcher_test.cpp b/test/leg_pattern_matcher_test.cpp new file mode 100644 index 0000000..12e9a70 --- /dev/null +++ b/test/leg_pattern_matcher_test.cpp @@ -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 + +#include +#include +#include + +#include + +#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 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(); +} diff --git a/test/leg_pose_fit_test.cpp b/test/leg_pose_fit_test.cpp new file mode 100644 index 0000000..ab56fe9 --- /dev/null +++ b/test/leg_pose_fit_test.cpp @@ -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 + +#include +#include + +#include + +#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 pointsOf(const LegProfile& p, double cx, double cy, double axis, + double sigma = 0.0) +{ + leg_scan_sim::World world; + const std::vector 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 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(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 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 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 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 all = pointsOf(p, cx, cy, axis); + std::vector 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 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> model_pts, scan_pts; + for (int k = 0; k < 3; ++k) + { + const std::array 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 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(); +} diff --git a/test/leg_scan_sim.h b/test/leg_scan_sim.h new file mode 100644 index 0000000..25d9020 --- /dev/null +++ b/test/leg_scan_sim.h @@ -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 +#include +#include +#include +#include + +#include + +#include + +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 segments; + std::vector circles; + std::vector 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 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 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(g.size - 1); + return g; +} + +struct Scan +{ + std::vector ranges; + std::vector intensities; + std::vector 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::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 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(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_