commit 1d38e77afafb63afebae4b1ae58ddef1dc661fb7 Author: duongtd Date: Wed Aug 26 12:09:28 2026 +0700 Extract line segments from an ordered range scan Fitting a line needs the ranges in ray order with a known angular step. A costmap has neither: at 0.05 m with inflation it has already destroyed ray order and object shape, so the two 0.2 m wings of a dock plate are one blob there. This is the consumer that robot_sensor_ports keeps readings raw for. Pure geometry - the input is a scan layout and a vector of ranges, the output is segments in polar form with their endpoints, supporting rays and covariance. Eigen is the only dependency and only the merge step uses it. No robot_cpp, no costmap, no message types, which is what makes it testable against synthetic scans with no runtime around it: build the shape, generate the rays, and the answer is known in advance. Polar rather than slope-intercept because a vertical wall has no finite slope and a laser sees vertical walls constantly. Radius is kept non-negative so one line has one representation - otherwise the merge step sees two. Ported from laser_line_extraction (Marc Gallant, BSD) with the ROS layer removed, and four defects fixed, each with a test that fails without the fix: split() sliced with &indices[i_split - 1] and &indices.back(), dropping a point off each half at every split. Anything angular came out a ray short at both ends of every arm. mergeLines() called resize() and then inserted at end(), leaving the first half of the vector zero-filled. A merged line reported twice its real support and every index in that half pointed at ray 0. The least-squares loop had no iteration cap. The increment is a ratio of two sums that can both approach zero on a degenerate run, and when it oscillates the loop never exits - in a control thread that is a stopped robot, not a slow frame. Segments that will not converge are now dropped, since their covariance would be meaningless and the merge step decides by covariance. Merging compared line parameters and nothing else, so two halves of a wall either side of a doorway - perfectly collinear - were rejoined into one segment spanning the doorway, undoing the split that had just separated them for that exact reason. Merging now also requires the facing endpoints to be within max_line_gap, so split and merge agree on what one surface means. The corner point at a distance split now belongs to both halves. It is the last point of one surface and the first of the next; giving it to one side shortens the other arm by a ray and tilts its fit. split() is iterative over an explicit stack rather than recursive: depth is bounded only by the ray count, and a noisy scan that splits at nearly every point would recurse a thousand deep in the control thread. Parameters are validated at configure time rather than per scan. A threshold that can never produce a fit otherwise shows up as "the detector finds nothing", which is indistinguishable from a sensor fault. diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..17d6908 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,163 @@ +cmake_minimum_required(VERSION 3.0.2) +project(robot_line_extraction VERSION 0.1.0 LANGUAGES CXX) + +# ======================================================== +# Build mode detection +# ======================================================== +if(DEFINED CATKIN_DEVEL_PREFIX OR DEFINED CATKIN_TOPLEVEL) + set(BUILDING_WITH_CATKIN TRUE) + message(STATUS "Building robot_line_extraction with Catkin") +else() + set(BUILDING_WITH_CATKIN FALSE) + message(STATUS "Building robot_line_extraction with Standalone CMake") +endif() + + +# ======================================================== +# C++ Standard +# ======================================================== +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD_REQUIRED ON) +set(CMAKE_CXX_EXTENSIONS OFF) + + +# ======================================================== +# Dependencies +# ======================================================== +# Eigen là phụ thuộc DUY NHẤT, và chỉ dùng ở bước gộp hai đoạn. Gói này cố ý không kéo robot_cpp, +# costmap hay message nào — đó là thứ khiến nó test được bằng scan tổng hợp, không cần runtime. +find_package(Eigen3 REQUIRED) + + +# ======================================================== +# Catkin configuration +# ======================================================== +if(BUILDING_WITH_CATKIN) + + find_package(catkin REQUIRED) + + catkin_package( + INCLUDE_DIRS + include + + LIBRARIES + robot_line_extraction + + DEPENDS + EIGEN3 + ) + +endif() + + +# ======================================================== +# Library +# ======================================================== +add_library(robot_line_extraction SHARED + src/types.cpp + src/line.cpp + src/line_extractor.cpp +) + +target_compile_options(robot_line_extraction PRIVATE -Wall -Wextra) + +target_include_directories(robot_line_extraction + PUBLIC + $ + $ +) + +# Header của Eigen vào dạng SYSTEM: gói này build với -Wall -Wextra, mà Eigen sinh warning riêng +# của nó — để lẫn vào thì warning của chính gói này vô hình. +target_include_directories(robot_line_extraction SYSTEM + PUBLIC + ${EIGEN3_INCLUDE_DIRS} +) + +if(NOT BUILDING_WITH_CATKIN) + set_target_properties(robot_line_extraction PROPERTIES + POSITION_INDEPENDENT_CODE ON + LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} + BUILD_RPATH "${CMAKE_BINARY_DIR}" + INSTALL_RPATH "${CMAKE_INSTALL_PREFIX}/lib" + ) +endif() + + +# ======================================================== +# Install +# ======================================================== +if(BUILDING_WITH_CATKIN) + + install(TARGETS robot_line_extraction + ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION} + RUNTIME DESTINATION ${CATKIN_GLOBAL_BIN_DESTINATION} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CATKIN_PACKAGE_INCLUDE_DESTINATION} + FILES_MATCHING PATTERN "*.h" + ) + +else() + + include(GNUInstallDirs) + + install(TARGETS robot_line_extraction + EXPORT ${PROJECT_NAME}-targets + ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR} + LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} + RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} + ) + + install(EXPORT ${PROJECT_NAME}-targets + FILE ${PROJECT_NAME}-targets.cmake + NAMESPACE ${PROJECT_NAME}:: + DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${PROJECT_NAME} + ) + + install(DIRECTORY include/${PROJECT_NAME}/ + DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}/${PROJECT_NAME} + FILES_MATCHING PATTERN "*.h" + ) + +endif() + + +# ======================================================== +# Tests +# ======================================================== +if(CATKIN_ENABLE_TESTING AND BUILDING_WITH_CATKIN) + + if(NOT COMMAND catkin_add_gtest) + message(FATAL_ERROR "catkin_add_gtest NOT FOUND") + endif() + + catkin_add_gtest(line_extraction_test test/line_extraction_test.cpp) + + if(TARGET line_extraction_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(line_extraction_test PROPERTIES EXCLUDE_FROM_ALL FALSE) + + target_compile_options(line_extraction_test PRIVATE -Wall -Wextra) + + target_include_directories(line_extraction_test + PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + + target_include_directories(line_extraction_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(line_extraction_test + robot_line_extraction + pthread + ) + endif() + +endif() diff --git a/README.md b/README.md new file mode 100644 index 0000000..732c832 --- /dev/null +++ b/README.md @@ -0,0 +1,106 @@ +# robot_line_extraction + +Trích đoạn thẳng từ **một scan cự ly có thứ tự**, bằng split-and-merge cộng khớp bình phương tối +thiểu có trọng số. + +Hình học thuần. Gói này không biết ROS, TF, costmap hay kiểu message nào. + +```cpp +robot_line_extraction::LineExtractor extractor; +std::string error; +if (!extractor.configure(params, error)) { /* sai tham số — nổ lúc boot */ } + +robot_line_extraction::ScanGeometry g{scan.angle_min, scan.angle_increment, scan.ranges.size()}; +std::vector lines; +extractor.extract(g, ranges, lines, error); +``` + +## Vì sao cần bản THÔ + +Khớp đường thẳng cần `ranges` **đúng thứ tự tia** kèm **bước góc đã biết**. Costmap ở `0.05 m` đã +inflate và xoá cả hai — hai cánh dài 0.2 m của tấm V ở trạm sạc trên lưới ấy chỉ còn là một cục. +Đó là lý do `robot_sensor_ports` giữ bản chưa lọc, và lý do gói này nhận scan chứ không nhận grid. + +## Đầu ra + +Mỗi `Line` ở **dạng cực**: `angle` (hướng pháp tuyến, trong `(-pi, pi]`) và `radius` (khoảng cách +vuông góc từ gốc cảm biến, luôn **không âm**), cộng hai đầu mút, tập tia đỡ nó, và ma trận hiệp +phương sai 2×2 của `(radius, angle)`. + +Dạng cực chứ không phải hệ số góc: tường thẳng đứng không có hệ số góc hữu hạn, mà laser thì gặp +tường thẳng đứng suốt. Giữ `radius` không âm để một đường không có hai cách biểu diễn — nếu không, +bước gộp sẽ thấy chúng là hai đường khác nhau. + +## Cách chạy + +1. **Lọc điểm** — ngoài `[min_range, max_range]` thì bỏ. `NaN` trượt **cả hai** phép so nên rơi ra + ngay; cảm biến báo tia hụt bằng `NaN` hay `inf` đều không cần ca đặc biệt ở đâu khác. +2. **Lọc outlier** — điểm cách xa **cả hai** hàng xóm về cự ly *và* nằm lệch khỏi đường nối chúng. + Hai điều kiện chứ không phải một: một góc tường thật cũng cách xa cả hai hàng xóm. +3. **Tách** — khớp thô qua hai đầu mút, tách ở điểm lệch xa nhất (`min_split_dist`) hoặc ở khe hở + rộng nhất (`max_line_gap`), lặp cho tới khi mọi mảnh đều thẳng và liền. +4. **Khớp** — bình phương tối thiểu có trọng số theo hiệp phương sai từng điểm, ra cả hiệp phương + sai của đường. +5. **Gộp** — hai đoạn KỀ NHAU gộp lại khi tham số của chúng trùng nhau trong phạm vi hiệp phương + sai của chính chúng **và** hai đầu mút đối diện cách nhau không quá `max_line_gap`. + +## Bốn lỗi của bản gốc đã sửa + +Port từ [`laser_line_extraction`](https://github.com/kam3k/laser_line_extraction) (Marc Gallant, +BSD). Không phải chép cơ học — bản gốc có bốn lỗi, mỗi lỗi có một test canh: + +| lỗi bản gốc | hậu quả | test | +|---|---|---| +| `split()` cắt bằng `&indices[i_split-1]` và `&indices.back()` | **rơi một điểm ở mỗi nửa, mỗi lần tách** — cánh của mọi hình góc cạnh ngắn đi một tia ở cả hai đầu | `ASplitLosesNoPoint` | +| `mergeLines()` gọi `resize()` rồi `insert(end())` | nửa đầu vector toàn số 0; đoạn đã gộp báo **gấp đôi** số điểm thật, mọi chỉ số nửa đầu trỏ về tia 0 | `AMergedLineReportsItsRealSupport` | +| vòng bình phương tối thiểu **không có trần** | số gia dao động trên run suy biến = **treo control thread**, không phải chậm một frame | `TheLeastSquaresLoopIsBounded` | +| gộp chỉ so tham số đường, **không nhìn khe hở** | hai nửa tường hai bên một ô cửa thẳng hàng hoàn hảo nên bị gộp lại thành đoạn **bắc ngang qua chỗ trống** — vừa tách xong đã bị gộp lại | `SplitsAtAGapEvenWhenBothSidesAreCollinear` | + +Cộng thêm: `i_max`/`i_gap` chưa khởi tạo, `split()` đệ quy (đổi sang stack tường minh — độ sâu chỉ +bị chặn bởi số tia, mà đây chạy trong control thread), `tan`/`sin` chia cho 0 khi đường thẳng đứng +trong `projectEndpoints`, và `boost::array` → `std::array`. + +**Điểm góc thuộc về CẢ HAI nửa khi tách theo độ lệch.** Nó là điểm cuối của mặt này và điểm đầu của +mặt kia; đưa cho một bên là cánh bên kia ngắn đi một tia và nghiêng đi. Tách theo khe hở thì không +chia sẻ gì — hai bên khe không phải một mặt. + +## Tham số + +Mọi tham số có default tại chỗ khai, có đơn vị, và đi qua `validate()`. Bộ tham số hỏng bị từ chối +**lúc `configure()`**, giữ nguyên bộ cũ — không có "khớp mãi không ra gì" mà nhìn giống hệt cảm +biến chết: + +- `range_var`/`bearing_var` = 0 → tin tuyệt đối một phép đo, số gia ra vô cực ngay vòng đầu; +- `least_sq_*_thresh` = 0 → không bao giờ hội tụ; +- `min_split_dist` = 0 → tách ở mọi điểm, không đoạn nào sống sót; +- `min_line_points` < 3 → hai điểm xác định đường chính xác nên hiệp phương sai vô nghĩa, mà bước + gộp lại quyết định **bằng** hiệp phương sai; +- `max_range` <= `min_range`. + +Khoá đáng chỉnh nhất là `min_split_dist`: nó quyết định "thẳng tới mức nào thì coi là một đường". + +## Chi phí + +Tách là đệ quy trên run, khớp lặp trên từng đoạn. **Chạy một lần cho mỗi scan MỚI, không phải mỗi +control cycle** — vòng 20 Hz đọc cảm biến 15 Hz sẽ làm lại một phần tư công việc trên dữ liệu đã +xử lý. Dùng cursor `sequence` của `robot_sensor_ports` để biết khi nào có scan mới. + +Bảng bearing (`cos`/`sin` từng tia) chỉ dựng lại khi `ScanGeometry` đổi. Cảm biến ổn định thì trả +tiền đúng một lần; tính lại nghìn phép sin mỗi frame cho một hằng số là thứ control loop không +gánh nổi. + +`LineExtractor` **không thread-safe** — mỗi consumer một instance. + +## Build và test + +```bash +catkin_make --pkg robot_line_extraction +./devel/lib/robot_line_extraction/line_extraction_test # 15 test +``` + +Test dùng **scan tổng hợp**: dựng hình trước (tường phẳng, tường nghiêng, tấm chữ V, tường có lỗ), +sinh tia sau, nên đáp án biết trước và sai lệch đo được bằng số — không cần bag, không cần runtime. + +Phụ thuộc duy nhất là Eigen, và chỉ ở bước gộp (nghịch đảo hiệp phương sai, khoảng cách +chi-squared). Không kéo `robot_cpp`, costmap hay message nào — đó chính là thứ khiến nó test được +mà không cần dựng gì quanh nó. diff --git a/include/robot_line_extraction/line.h b/include/robot_line_extraction/line.h new file mode 100644 index 0000000..5ea5a1c --- /dev/null +++ b/include/robot_line_extraction/line.h @@ -0,0 +1,140 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — one fitted line segment. + * + * Author: DuongTD + * Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS. + *********************************************************************/ +#ifndef ROBOT_LINE_EXTRACTION_LINE_H_ +#define ROBOT_LINE_EXTRACTION_LINE_H_ + +#include +#include + +#include + +namespace robot_line_extraction +{ + +/** + * @class Line + * @brief A line in polar form (`angle`, `radius`) plus the endpoints and support that produced it. + * + * Polar rather than slope-intercept because a vertical line has no finite slope, and a laser sees + * vertical walls constantly. `radius` is the perpendicular distance from the sensor origin to the + * line and is kept non-negative; `angle` is the bearing of that perpendicular, in (-pi, pi]. + * + * Two fits, used in sequence. @ref endpointFit is cheap and runs during splitting, where only a + * rough line is needed to measure how far points stray from it. @ref leastSqFit is the real fit, + * weighting each point by its own covariance, and it also produces the covariance that decides + * whether two lines are the same line. + * + * @note Holds copies of the scan data it was built from. That is deliberate: a segment outlives the + * split recursion that created it, and pointing back at a buffer being rebuilt each frame is + * how a use-after-free gets written. + */ +class Line +{ +public: + /// @brief Build from a run of consecutive rays. Nothing is fitted yet. + Line(const CachedData& c_data, const RangeData& r_data, const LineExtractionParams& params, + std::vector indices); + + /// @brief Build from already-known parameters. Used when two lines merge into one. + Line(double angle, double radius, const std::array& covariance, + const std::array& start, const std::array& end, + const std::vector& indices); + + double getAngle() const + { + return angle_; + } + + double getRadius() const + { + return radius_; + } + + /// @brief Row-major 2x2 covariance of (radius, angle). Only meaningful after @ref leastSqFit. + const std::array& getCovariance() const + { + return covariance_; + } + + const std::array& getStart() const + { + return start_; + } + + const std::array& getEnd() const + { + return end_; + } + + /// @brief Ray numbers supporting this line, ascending. + const std::vector& getIndices() const + { + return indices_; + } + + /// @brief [m] Perpendicular distance from ray @p index to this line. + double distToPoint(unsigned int index) const; + + /// @brief [m] Distance between the endpoints. + double length() const; + + std::size_t numPoints() const + { + return indices_.size(); + } + + /// @brief Cheap fit through the first and last supporting point. Used while splitting. + void endpointFit(); + + /** + * @brief Weighted least-squares fit, iterated to convergence, then the covariance. + * + * @return false if it did not converge within the iteration cap, leaving the endpoint fit in + * place. Upstream looped unbounded here; a scan that makes the increment oscillate then + * hangs the control thread outright, which is worse than a line that failed to refine. + */ + bool leastSqFit(); + + /// @brief Slide the endpoints onto the fitted line, perpendicular to it. + void projectEndpoints(); + +private: + void angleFromEndpoints(); + void radiusFromEndpoints(); + void angleFromLeastSq(); + double angleIncrement() const; + void calcCovariance(); + void calcPointCovariances(); + void calcPointParameters(); + void calcPointScalarCovariances(); + void radiusFromLeastSq(); + + // Declaration order is destruction and initialisation order; keep it matching the member list of + // the constructors so -Wreorder stays quiet and the two never drift apart. + CachedData c_data_; + RangeData r_data_; + LineExtractionParams params_; + std::vector indices_; + + PointParams p_params_; + std::vector point_scalar_vars_; + std::vector> point_covs_; + double p_rr_ = 0.0; + + double angle_ = 0.0; + double radius_ = 0.0; + std::array start_{ { 0.0, 0.0 } }; + std::array end_{ { 0.0, 0.0 } }; + std::array covariance_{ { 0.0, 0.0, 0.0, 0.0 } }; +}; + +} // namespace robot_line_extraction + +#endif // ROBOT_LINE_EXTRACTION_LINE_H_ diff --git a/include/robot_line_extraction/line_extractor.h b/include/robot_line_extraction/line_extractor.h new file mode 100644 index 0000000..195b261 --- /dev/null +++ b/include/robot_line_extraction/line_extractor.h @@ -0,0 +1,117 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — split-and-merge line extraction from an ordered range scan. + * + * Author: DuongTD + * Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS. + *********************************************************************/ +#ifndef ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_ +#define ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_ + +#include +#include + +#include +#include + +namespace robot_line_extraction +{ + +/** + * @class LineExtractor + * @brief Turns one ordered range scan into line segments. + * + * Pure geometry. It knows nothing about ROS, TF, costmaps or message types — the input is a + * @ref ScanGeometry and a vector of ranges, which is what makes it testable against synthetic + * scans with no runtime around it. + * + * The method is split-and-merge: fit a rough line through a run of rays, split it where a point + * strays too far or a gap opens, refine each surviving run by weighted least squares, then merge + * neighbouring segments whose parameters agree within their own covariance. + * + * ## Why it needs the raw scan + * + * Fitting needs the ranges in ray order with a known angular step. A costmap has neither: at + * 0.05 m with inflation it has already destroyed ray order and object shape, so the two 0.2 m wings + * of a dock plate are one blob there. This is why `robot_sensor_ports` keeps readings raw. + * + * ## Cost + * + * Splitting is recursive over the run and the least-squares step iterates per segment, so this is + * not free. Run it once per new scan, never once per control cycle — a 20 Hz loop reading a 15 Hz + * sensor would otherwise redo a quarter of its work on data it already processed. The bearing + * tables are rebuilt only when the geometry changes, so a steady sensor pays for them once. + * + * @note Not thread-safe. One extractor per consumer. + */ +class LineExtractor +{ +public: + LineExtractor() = default; + + /** + * @brief Set the parameters. Rejected here rather than per scan. + * @param[out] error Which field is wrong, and why. + * @return false if the parameters cannot produce a sensible fit; the previous set is kept. + */ + bool configure(const LineExtractionParams& params, std::string& error); + + const LineExtractionParams& params() const + { + return params_; + } + + /** + * @brief Extract lines from one scan. + * + * @param geometry Ray count and angular layout. The bearing tables are rebuilt only if this + * differs from the previous call. + * @param ranges [m] One entry per ray. Non-finite entries and entries outside + * [`min_range`, `max_range`] are dropped — NaN fails both comparisons, so a + * sensor reporting misses as NaN needs no special handling from the caller. + * @param[out] lines Cleared, then filled. Empty is a normal answer, not a failure. + * @param[out] error Why the scan could not be processed at all. + * @return false only when the input is unusable: geometry invalid, or `ranges.size()` disagreeing + * with `geometry.size`. A scan that simply contains no lines returns true and no lines. + */ + bool extract(const ScanGeometry& geometry, const std::vector& ranges, + std::vector& lines, std::string& error); + +private: + /// @brief Rebuild the bearing tables. Only called when the geometry actually changed. + void rebuildCache(const ScanGeometry& geometry); + + /// @brief Cartesian form of every ray, in the sensor frame. + void projectRanges(const std::vector& ranges); + + void filterCloseAndFarPoints(); + void filterOutlierPoints(); + void filterLines(); + void mergeLines(); + + /** + * @brief Split a run of rays until every piece is straight enough and has no gap in it. + * + * Iterative over an explicit stack rather than recursive: the depth is bounded only by the scan, + * and this runs in the control thread where a deep recursion on a noisy scan is a stack overflow + * rather than a slow frame. + */ + void split(const std::vector& indices); + + double distBetweenPoints(unsigned int index_1, unsigned int index_2) const; + + LineExtractionParams params_; + ScanGeometry geometry_; + bool cache_valid_ = false; + + CachedData c_data_; + RangeData r_data_; + std::vector filtered_indices_; + std::vector lines_; +}; + +} // namespace robot_line_extraction + +#endif // ROBOT_LINE_EXTRACTION_LINE_EXTRACTOR_H_ diff --git a/include/robot_line_extraction/types.h b/include/robot_line_extraction/types.h new file mode 100644 index 0000000..8863375 --- /dev/null +++ b/include/robot_line_extraction/types.h @@ -0,0 +1,152 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — parameters and the per-scan data the fit works on. + * + * Author: DuongTD + * Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS. + *********************************************************************/ +#ifndef ROBOT_LINE_EXTRACTION_TYPES_H_ +#define ROBOT_LINE_EXTRACTION_TYPES_H_ + +#include +#include +#include +#include + +namespace robot_line_extraction +{ + +/// @brief Wrap an angle into (-pi, pi]. Inline because it runs per point, per iteration. +inline double piToPi(double angle) +{ + angle = std::fmod(angle, 2.0 * M_PI); + if (angle >= M_PI) + { + angle -= 2.0 * M_PI; + } + else if (angle < -M_PI) + { + angle += 2.0 * M_PI; + } + return angle; +} + +/** + * @struct LineExtractionParams + * @brief Everything that steers the split-and-merge fit. + * + * Every field has a default here, a unit at its declaration, and a range checked by @ref validate. + * Nothing reads a parameter this struct has not vetted. + */ +struct LineExtractionParams +{ + /// [rad^2] Variance of one bearing measurement. Feeds the per-point covariance. + double bearing_var = 1e-4; + + /// [m^2] Variance of one range measurement. + double range_var = 9e-4; + + /// [rad] Least-squares iteration stops when the angle moves less than this. + double least_sq_angle_thresh = 1e-4; + + /// [m] Least-squares iteration stops when the radius moves less than this. + double least_sq_radius_thresh = 1e-4; + + /// [m] A gap wider than this between consecutive points splits the run, however straight it is. + double max_line_gap = 0.05; + + /// [m] Lines shorter than this are dropped. + double min_line_length = 0.05; + + /// [m] Points nearer than this are ignored. Keep at or above the sensor's own range_min. + double min_range = 0.05; + + /// [m] Points further than this are ignored. + double max_range = 30.0; + + /// [m] A point further than this from the fitted line splits it. The core sensitivity knob. + double min_split_dist = 0.04; + + /// [m] A point this far from both neighbours is treated as an outlier and dropped. + double outlier_dist = 0.05; + + /// Fewer supporting points than this and the line is dropped. Below 3 a fit is meaningless. + unsigned int min_line_points = 6; + + /** + * @brief Reject a parameter set that cannot produce a sensible fit. + * @param[out] error Which field, and why. + * + * Checked at configure time rather than per scan: a bad threshold otherwise shows up as "the + * detector finds nothing", which looks identical to a sensor fault. + */ + bool validate(std::string& error) const; +}; + +/** + * @struct ScanGeometry + * @brief The shape of a scan: how many rays, starting where, spaced how far apart. + * + * Separate from the ranges because it almost never changes while the ranges change every frame. + * The bearing tables depend only on this, so they are rebuilt only when it differs — computing a + * thousand sines per frame for a value that has not moved is pure waste in a control loop. + */ +struct ScanGeometry +{ + double angle_min = 0.0; ///< [rad] Bearing of ray 0. + double angle_increment = 0.0; ///< [rad] Bearing step between consecutive rays. Must be non-zero. + std::size_t size = 0; ///< Number of rays. + + bool operator==(const ScanGeometry& other) const; + + bool operator!=(const ScanGeometry& other) const + { + return !(*this == other); + } + + /// @brief Reject a geometry the fit cannot use. + bool validate(std::string& error) const; +}; + +/** + * @struct CachedData + * @brief Bearing tables for one @ref ScanGeometry. + * + * @warning `indices` is 0..size-1 and nothing else. @ref RangeData is indexed by ray number, so the + * identity mapping is what makes `xs[i]` the Cartesian form of ray `i`. The upstream code + * relies on this without saying so; break it and every lookup silently reads another ray. + */ +struct CachedData +{ + std::vector bearings; ///< [rad] + std::vector cos_bearings; + std::vector sin_bearings; + std::vector indices; +}; + +/// @brief One frame of ranges, plus their Cartesian form in the sensor frame. +struct RangeData +{ + std::vector ranges; ///< [m] + std::vector xs; ///< [m] + std::vector ys; ///< [m] +}; + +/// @brief Scratch buffers of the least-squares iteration. Kept out of Line so they can be reused. +struct PointParams +{ + std::vector a; + std::vector ap; + std::vector app; + std::vector b; + std::vector bp; + std::vector bpp; + std::vector c; + std::vector s; +}; + +} // namespace robot_line_extraction + +#endif // ROBOT_LINE_EXTRACTION_TYPES_H_ diff --git a/package.xml b/package.xml new file mode 100644 index 0000000..d15679b --- /dev/null +++ b/package.xml @@ -0,0 +1,31 @@ + + robot_line_extraction + 0.1.0 + + Trích đoạn thẳng từ một scan cự ly có thứ tự, bằng split-and-merge cộng khớp bình phương tối + thiểu có trọng số. + + Hình học thuần: đầu vào là bố cục scan (`angle_min`, `angle_increment`, số tia) cộng một vector + `ranges`, đầu ra là các đoạn ở dạng cực (`angle`, `radius`) kèm hai đầu mút, tập tia đỡ nó và + ma trận hiệp phương sai. Không biết ROS, TF, costmap hay kiểu message nào — nên test được bằng + scan tổng hợp mà không cần dựng runtime. + + Vì sao cần bản THÔ: khớp đường thẳng cần `ranges` đúng thứ tự tia kèm bước góc đã biết. Costmap + ở 0.05 m đã inflate và xoá cả hai thứ đó — hai cánh dài 0.2 m của tấm V ở trạm sạc trên lưới ấy + chỉ còn là một cục. Đây là lý do `robot_sensor_ports` giữ bản chưa lọc. + + Port từ `laser_line_extraction` (Marc Gallant, BSD), bỏ toàn bộ phần ROS. Ba lỗi của bản gốc đã + được sửa và có test canh: điểm bị rơi ở mỗi lần tách, tập tia của đoạn đã gộp bị hỏng, và vòng + lặp bình phương tối thiểu không có trần. + + T800 Robotics + T800 Robotics + BSD + + catkin + + + eigen + eigen + + diff --git a/src/line.cpp b/src/line.cpp new file mode 100644 index 0000000..bacd492 --- /dev/null +++ b/src/line.cpp @@ -0,0 +1,342 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — fitting one line segment. + * + * Author: DuongTD + * Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS. + *********************************************************************/ +#include + +#include +#include + +namespace robot_line_extraction +{ +namespace +{ + +/** + * @brief Cap on least-squares iterations. + * + * Upstream looped until convergence with no bound. The increment is a ratio of two sums that can + * both approach zero on a degenerate run, and when it oscillates the loop never exits — in a + * control thread that is not a slow frame, it is a stopped robot. Convergence normally takes a + * handful of passes, so a run that hits this cap is pathological and the caller is better served by + * the endpoint fit it already has. + */ +constexpr int kMaxLeastSqIterations = 50; + +} // namespace + +Line::Line(const CachedData& c_data, const RangeData& r_data, const LineExtractionParams& params, + std::vector indices) + : c_data_(c_data), r_data_(r_data), params_(params), indices_(std::move(indices)) +{ +} + +Line::Line(double angle, double radius, const std::array& covariance, + const std::array& start, const std::array& end, + const std::vector& indices) + : indices_(indices) + , angle_(angle) + , radius_(radius) + , start_(start) + , end_(end) + , covariance_(covariance) +{ +} + +// ================================================================================================ +// Geometry +// ================================================================================================ + +double Line::distToPoint(unsigned int index) const +{ + const double p_rad = std::hypot(r_data_.xs[index], r_data_.ys[index]); + const double p_ang = std::atan2(r_data_.ys[index], r_data_.xs[index]); + return std::fabs(p_rad * std::cos(p_ang - angle_) - radius_); +} + +double Line::length() const +{ + return std::hypot(start_[0] - end_[0], start_[1] - end_[1]); +} + +void Line::projectEndpoints() +{ + // Foot of the perpendicular from each endpoint onto the fitted line. Written in slope form, so a + // line whose normal points along y (angle near 0 or pi) makes tan and sin blow up. Handle that + // case directly instead: the line is then vertical in the sensor frame, x = radius. + const double sin_a = std::sin(angle_); + if (std::fabs(sin_a) < 1e-9) + { + const double x = radius_ * std::cos(angle_); + start_[0] = x; + end_[0] = x; + return; + } + + const double s = -1.0 / std::tan(angle_); + const double b = radius_ / sin_a; + const double denom = s * s + 1.0; + + double x = start_[0]; + double y = start_[1]; + start_[0] = (s * y + x - s * b) / denom; + start_[1] = (s * s * y + s * x + b) / denom; + + x = end_[0]; + y = end_[1]; + end_[0] = (s * y + x - s * b) / denom; + end_[1] = (s * s * y + s * x + b) / denom; +} + +// ================================================================================================ +// Endpoint fit — cheap, used while splitting +// ================================================================================================ + +void Line::endpointFit() +{ + start_[0] = r_data_.xs[indices_.front()]; + start_[1] = r_data_.ys[indices_.front()]; + end_[0] = r_data_.xs[indices_.back()]; + end_[1] = r_data_.ys[indices_.back()]; + angleFromEndpoints(); + radiusFromEndpoints(); +} + +void Line::angleFromEndpoints() +{ + if (std::fabs(end_[0] - start_[0]) > 1e-9) + { + const double slope = (end_[1] - start_[1]) / (end_[0] - start_[0]); + angle_ = piToPi(std::atan(slope) + M_PI / 2.0); + } + else + { + angle_ = 0.0; + } +} + +void Line::radiusFromEndpoints() +{ + radius_ = start_[0] * std::cos(angle_) + start_[1] * std::sin(angle_); + if (radius_ < 0.0) + { + // Keep radius non-negative by flipping the normal instead. Two representations of one line + // would otherwise look like two different lines to the merge step. + radius_ = -radius_; + angle_ = piToPi(angle_ + M_PI); + } +} + +// ================================================================================================ +// Weighted least squares +// ================================================================================================ + +bool Line::leastSqFit() +{ + calcPointCovariances(); + + double prev_radius = 0.0; + double prev_angle = 0.0; + int iterations = 0; + + while (std::fabs(radius_ - prev_radius) > params_.least_sq_radius_thresh || + std::fabs(angle_ - prev_angle) > params_.least_sq_angle_thresh) + { + if (++iterations > kMaxLeastSqIterations) + { + return false; + } + + prev_radius = radius_; + prev_angle = angle_; + calcPointScalarCovariances(); + radiusFromLeastSq(); + angleFromLeastSq(); + + if (!std::isfinite(radius_) || !std::isfinite(angle_)) + { + // A degenerate run can drive the increment to infinity. Carrying that into the covariance + // would poison the merge step, which compares lines through their covariances. + return false; + } + } + + calcCovariance(); + projectEndpoints(); + return true; +} + +void Line::angleFromLeastSq() +{ + calcPointParameters(); + angle_ += angleIncrement(); +} + +double Line::angleIncrement() const +{ + const std::vector& a = p_params_.a; + const std::vector& ap = p_params_.ap; + const std::vector& app = p_params_.app; + const std::vector& b = p_params_.b; + const std::vector& bp = p_params_.bp; + const std::vector& bpp = p_params_.bpp; + + double numerator = 0.0; + double denominator = 0.0; + for (std::size_t i = 0; i < a.size(); ++i) + { + const double b2 = b[i] * b[i]; + numerator += (b[i] * ap[i] - a[i] * bp[i]) / b2; + denominator += + ((app[i] * b[i] - a[i] * bpp[i]) * b[i] - 2.0 * (ap[i] * b[i] - a[i] * bp[i]) * bp[i]) / + (b2 * b[i]); + } + + if (denominator == 0.0) + { + return 0.0; // No curvature to descend. leastSqFit's finite check then ends the iteration. + } + return -(numerator / denominator); +} + +void Line::calcCovariance() +{ + covariance_[0] = p_rr_; + + const std::vector& a = p_params_.a; + const std::vector& ap = p_params_.ap; + const std::vector& app = p_params_.app; + const std::vector& b = p_params_.b; + const std::vector& bp = p_params_.bp; + const std::vector& bpp = p_params_.bpp; + + double G = 0.0; + double A = 0.0; + double B = 0.0; + + for (std::size_t i = 0; i < a.size(); ++i) + { + const double r = r_data_.ranges[indices_[i]]; + const double phi = c_data_.bearings[indices_[i]]; + const double b2 = b[i] * b[i]; + const double sin_dev = std::sin(angle_ - phi); + + G += ((app[i] * b[i] - a[i] * bpp[i]) * b[i] - 2.0 * (ap[i] * b[i] - a[i] * bp[i]) * bp[i]) / + (b2 * b[i]); + A += 2.0 * r * sin_dev / b[i]; + B += 4.0 * r * r * sin_dev * sin_dev / b[i]; + } + + if (G == 0.0) + { + covariance_[1] = 0.0; + covariance_[2] = 0.0; + covariance_[3] = 0.0; + return; + } + + covariance_[1] = p_rr_ * A / G; + covariance_[2] = covariance_[1]; + covariance_[3] = (1.0 / G) * (1.0 / G) * B; +} + +void Line::calcPointCovariances() +{ + point_covs_.clear(); + point_covs_.reserve(indices_.size()); + + for (const unsigned int index : indices_) + { + const double r = r_data_.ranges[index]; + const double phi = c_data_.bearings[index]; + const double var_r = params_.range_var; + const double var_phi = params_.bearing_var; + + std::array Q; + Q[0] = r * r * var_phi * std::pow(std::sin(phi), 2) + var_r * std::pow(std::cos(phi), 2); + Q[1] = -r * r * var_phi * std::sin(2.0 * phi) / 2.0 + var_r * std::sin(2.0 * phi) / 2.0; + Q[2] = Q[1]; + Q[3] = r * r * var_phi * std::pow(std::cos(phi), 2) + var_r * std::pow(std::sin(phi), 2); + point_covs_.push_back(Q); + } +} + +void Line::calcPointParameters() +{ + const std::size_t n = indices_.size(); + p_params_.a.clear(); + p_params_.ap.clear(); + p_params_.app.clear(); + p_params_.b.clear(); + p_params_.bp.clear(); + p_params_.bpp.clear(); + p_params_.c.clear(); + p_params_.s.clear(); + p_params_.a.reserve(n); + p_params_.ap.reserve(n); + p_params_.app.reserve(n); + p_params_.b.reserve(n); + p_params_.bp.reserve(n); + p_params_.bpp.reserve(n); + p_params_.c.reserve(n); + p_params_.s.reserve(n); + + for (const unsigned int index : indices_) + { + const double r = r_data_.ranges[index]; + const double phi = c_data_.bearings[index]; + const double var_r = params_.range_var; + const double var_phi = params_.bearing_var; + + const double c = std::cos(angle_ - phi); + const double s = std::sin(angle_ - phi); + const double residual = r * c - radius_; + + p_params_.a.push_back(residual * residual); + p_params_.ap.push_back(-2.0 * r * s * residual); + p_params_.app.push_back(2.0 * r * r * s * s - 2.0 * r * c * residual); + p_params_.b.push_back(var_r * c * c + var_phi * r * r * s * s); + p_params_.bp.push_back(2.0 * (r * r * var_phi - var_r) * c * s); + p_params_.bpp.push_back(2.0 * (r * r * var_phi - var_r) * (c * c - s * s)); + p_params_.c.push_back(c); + p_params_.s.push_back(s); + } +} + +void Line::calcPointScalarCovariances() +{ + point_scalar_vars_.clear(); + point_scalar_vars_.reserve(point_covs_.size()); + + const double cos_a = std::cos(angle_); + const double sin_a = std::sin(angle_); + + double inverse_P_sum = 0.0; + for (const std::array& cov : point_covs_) + { + const double P = cov[0] * cos_a * cos_a + 2.0 * cov[1] * sin_a * cos_a + cov[3] * sin_a * sin_a; + inverse_P_sum += 1.0 / P; + point_scalar_vars_.push_back(P); + } + + p_rr_ = 1.0 / inverse_P_sum; +} + +void Line::radiusFromLeastSq() +{ + radius_ = 0.0; + for (std::size_t i = 0; i < indices_.size(); ++i) + { + const double r = r_data_.ranges[indices_[i]]; + const double phi = c_data_.bearings[indices_[i]]; + radius_ += r * std::cos(angle_ - phi) / point_scalar_vars_[i]; + } + radius_ *= p_rr_; +} + +} // namespace robot_line_extraction diff --git a/src/line_extractor.cpp b/src/line_extractor.cpp new file mode 100644 index 0000000..5043d0e --- /dev/null +++ b/src/line_extractor.cpp @@ -0,0 +1,408 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — split-and-merge over one ordered range scan. + * + * Author: DuongTD + * Derived from laser_line_extraction (Marc Gallant, BSD), stripped of ROS. + *********************************************************************/ +#include + +#include +#include + +#include + +namespace robot_line_extraction +{ +namespace +{ + +/// @brief Mahalanobis-style distance between two lines, given their covariances. +double chiSquared(const Eigen::Vector2d& dL, const Eigen::Matrix2d& P_1, const Eigen::Matrix2d& P_2) +{ + return dL.transpose() * (P_1 + P_2).inverse() * dL; +} + +/// Two segments merge when their parameters agree this closely relative to their own uncertainty. +/// 3 is roughly the 78% ellipse for two degrees of freedom: loose enough to rejoin one wall broken +/// by a passing reflection, tight enough to leave the two arms of a dock plate apart. +constexpr double kMergeChiSquaredThresh = 3.0; + +Eigen::Matrix2d toMatrix(const std::array& covariance) +{ + Eigen::Matrix2d P; + P << covariance[0], covariance[1], covariance[2], covariance[3]; + return P; +} + +} // namespace + +bool LineExtractor::configure(const LineExtractionParams& params, std::string& error) +{ + if (!params.validate(error)) + { + return false; // Keep the previous set; a half-applied parameter block is worse than none. + } + params_ = params; + return true; +} + +bool LineExtractor::extract(const ScanGeometry& geometry, const std::vector& ranges, + std::vector& lines, std::string& error) +{ + lines.clear(); + + if (!geometry.validate(error)) + { + return false; + } + if (ranges.size() != geometry.size) + { + error = "ranges.size() (" + std::to_string(ranges.size()) + ") does not match geometry.size (" + + std::to_string(geometry.size) + ")"; + return false; + } + + // The bearing tables depend only on the layout, which a sensor repeats frame after frame. + // Recomputing a thousand sines every cycle for a constant is exactly the kind of waste a control + // loop cannot afford. + if (!cache_valid_ || geometry_ != geometry) + { + rebuildCache(geometry); + } + + projectRanges(ranges); + + filtered_indices_ = c_data_.indices; + lines_.clear(); + + filterCloseAndFarPoints(); + filterOutlierPoints(); + + // Nothing left to fit is a normal answer — an empty room, or a sensor pointed at open space. + if (filtered_indices_.size() <= std::max(params_.min_line_points, 3)) + { + return true; + } + + split(filtered_indices_); + filterLines(); + + // Refine every surviving run, dropping the ones that will not converge. A segment whose fit blew + // up carries a meaningless covariance, and the merge step decides by covariance. + std::vector refined; + refined.reserve(lines_.size()); + for (Line& line : lines_) + { + if (line.leastSqFit()) + { + refined.push_back(line); + } + } + lines_ = refined; + + if (lines_.size() > 1) + { + mergeLines(); + } + + lines = lines_; + return true; +} + +// ================================================================================================ +// Per-scan preparation +// ================================================================================================ + +void LineExtractor::rebuildCache(const ScanGeometry& geometry) +{ + geometry_ = geometry; + cache_valid_ = true; + + const std::size_t n = geometry.size; + c_data_.bearings.resize(n); + c_data_.cos_bearings.resize(n); + c_data_.sin_bearings.resize(n); + c_data_.indices.resize(n); + + for (std::size_t i = 0; i < n; ++i) + { + const double bearing = geometry.angle_min + static_cast(i) * geometry.angle_increment; + c_data_.bearings[i] = bearing; + c_data_.cos_bearings[i] = std::cos(bearing); + c_data_.sin_bearings[i] = std::sin(bearing); + // Identity mapping, and everything downstream depends on it: RangeData is indexed by ray + // number, so xs[i] is only the Cartesian form of ray i while this holds. + c_data_.indices[i] = static_cast(i); + } +} + +void LineExtractor::projectRanges(const std::vector& ranges) +{ + r_data_.ranges = ranges; + r_data_.xs.resize(ranges.size()); + r_data_.ys.resize(ranges.size()); + + for (std::size_t i = 0; i < ranges.size(); ++i) + { + r_data_.xs[i] = c_data_.cos_bearings[i] * ranges[i]; + r_data_.ys[i] = c_data_.sin_bearings[i] * ranges[i]; + } +} + +double LineExtractor::distBetweenPoints(unsigned int index_1, unsigned int index_2) const +{ + return std::hypot(r_data_.xs[index_1] - r_data_.xs[index_2], + r_data_.ys[index_1] - r_data_.ys[index_2]); +} + +// ================================================================================================ +// Point filtering +// ================================================================================================ + +void LineExtractor::filterCloseAndFarPoints() +{ + std::vector output; + output.reserve(filtered_indices_.size()); + + for (const unsigned int index : filtered_indices_) + { + const double range = r_data_.ranges[index]; + // NaN fails both comparisons and is dropped here, which is why a sensor that reports misses as + // NaN needs no special case anywhere else. Infinity fails the upper bound the same way. + if (range >= params_.min_range && range <= params_.max_range) + { + output.push_back(index); + } + } + + filtered_indices_ = output; +} + +void LineExtractor::filterOutlierPoints() +{ + if (filtered_indices_.size() < 3) + { + return; + } + + std::vector output; + output.reserve(filtered_indices_.size()); + + for (std::size_t i = 0; i < filtered_indices_.size(); ++i) + { + const unsigned int p_i = filtered_indices_[i]; + + unsigned int p_j = 0; + unsigned int p_k = 0; + if (i == 0) + { + p_j = filtered_indices_[i + 1]; + p_k = filtered_indices_[i + 2]; + } + else if (i == filtered_indices_.size() - 1) + { + p_j = filtered_indices_[i - 1]; + p_k = filtered_indices_[i - 2]; + } + else + { + p_j = filtered_indices_[i - 1]; + p_k = filtered_indices_[i + 1]; + } + + if (std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_j]) > params_.outlier_dist && + std::fabs(r_data_.ranges[p_i] - r_data_.ranges[p_k]) > params_.outlier_dist) + { + // Far from both neighbours in range. That is still not enough to call it an outlier: a real + // corner looks the same. Only drop it if it also sits off the line joining those neighbours. + Line line(c_data_, r_data_, params_, { p_j, p_k }); + line.endpointFit(); + if (line.distToPoint(p_i) > params_.min_split_dist) + { + continue; + } + } + + output.push_back(p_i); + } + + filtered_indices_ = output; +} + +// ================================================================================================ +// Splitting +// ================================================================================================ + +void LineExtractor::split(const std::vector& indices) +{ + // Explicit stack rather than recursion. Depth is bounded only by the ray count, and a noisy scan + // that splits at nearly every point would recurse a thousand deep in the control thread — a + // stack overflow, not a slow frame. Pushing the right half first keeps the output in scan order, + // which mergeLines depends on since it only ever compares neighbours. + std::vector> pending; + pending.push_back(indices); + + while (!pending.empty()) + { + const std::vector run = std::move(pending.back()); + pending.pop_back(); + + // A single point is not a line. It reaches here when a gap orphans it, and dropping it is the + // right answer rather than emitting a zero-length segment. + if (run.size() < 2) + { + continue; + } + + Line line(c_data_, r_data_, params_, run); + line.endpointFit(); + + double dist_max = 0.0; + std::size_t i_dist = 0; + bool have_dist = false; + + double gap_max = 0.0; + std::size_t i_gap = 0; + bool have_gap = false; + + // Interior points only: the endpoints are on the fitted line by construction, so splitting at + // one of them would produce a one-point half and make no progress. + for (std::size_t i = 1; i + 1 < run.size(); ++i) + { + const double dist = line.distToPoint(run[i]); + if (dist > dist_max) + { + dist_max = dist; + i_dist = i; + have_dist = true; + } + } + + for (std::size_t i = 0; i + 1 < run.size(); ++i) + { + const double gap = distBetweenPoints(run[i], run[i + 1]); + if (gap > gap_max) + { + gap_max = gap; + i_gap = i; + have_gap = true; + } + } + + const bool split_on_dist = have_dist && dist_max >= params_.min_split_dist; + const bool split_on_gap = have_gap && gap_max >= params_.max_line_gap; + + if (!split_on_dist && !split_on_gap) + { + lines_.push_back(line); + continue; + } + + std::vector first; + std::vector second; + + if (split_on_dist) + { + // The corner point belongs to BOTH halves. It is the last point of one wall and the first of + // the next, and a dock plate needs each arm to keep its apex endpoint — giving it to one side + // shortens the other arm by a ray and tilts its fit. + first.assign(run.begin(), run.begin() + static_cast(i_dist) + 1); + second.assign(run.begin() + static_cast(i_dist), run.end()); + } + else + { + // A gap means the two sides are not the same surface, so nothing is shared across it. + first.assign(run.begin(), run.begin() + static_cast(i_gap) + 1); + second.assign(run.begin() + static_cast(i_gap) + 1, run.end()); + } + + // Both halves are strictly shorter than the run, so this always terminates. Upstream sliced + // with `&indices[i_split - 1]` and `&indices.back()`, which silently dropped a point off each + // half at every split — the arms of anything angular came out a ray short on both ends. + pending.push_back(std::move(second)); + pending.push_back(std::move(first)); + } +} + +// ================================================================================================ +// Line filtering and merging +// ================================================================================================ + +void LineExtractor::filterLines() +{ + std::vector output; + output.reserve(lines_.size()); + + for (const Line& line : lines_) + { + if (line.length() >= params_.min_line_length && line.numPoints() >= params_.min_line_points) + { + output.push_back(line); + } + } + + lines_ = output; +} + +void LineExtractor::mergeLines() +{ + std::vector merged_lines; + merged_lines.reserve(lines_.size()); + + for (std::size_t i = 1; i < lines_.size(); ++i) + { + const Eigen::Vector2d L_1(lines_[i - 1].getRadius(), lines_[i - 1].getAngle()); + const Eigen::Vector2d L_2(lines_[i].getRadius(), lines_[i].getAngle()); + const Eigen::Matrix2d P_1 = toMatrix(lines_[i - 1].getCovariance()); + const Eigen::Matrix2d P_2 = toMatrix(lines_[i].getCovariance()); + + // Two conditions, and the second is not upstream's. Merging on line parameters alone rejoins + // anything collinear no matter how far apart, so a wall either side of a doorway comes back as + // one segment spanning the doorway — and split had already separated them for exactly that + // reason. Requiring the facing endpoints to be within max_line_gap makes split and merge agree + // on what "one surface" means, so a gap that forced a split cannot be undone here. It also + // stops a later consumer measuring a bridged segment: a dock detector checking wing length + // would otherwise accept one. + const double endpoint_gap = std::hypot(lines_[i].getStart()[0] - lines_[i - 1].getEnd()[0], + lines_[i].getStart()[1] - lines_[i - 1].getEnd()[1]); + + if (endpoint_gap <= params_.max_line_gap && + chiSquared(L_1 - L_2, P_1, P_2) < kMergeChiSquaredThresh) + { + const Eigen::Matrix2d P_m = (P_1.inverse() + P_2.inverse()).inverse(); + const Eigen::Vector2d L_m = P_m * (P_1.inverse() * L_1 + P_2.inverse() * L_2); + + const std::array cov{ { P_m(0, 0), P_m(0, 1), P_m(1, 0), P_m(1, 1) } }; + + // Concatenate the support of both. Upstream called resize() and then inserted at end(), + // which left the first half of the vector zero-filled and doubled numPoints() — a merged + // line then reported twice its real support, and every index in the first half read ray 0. + const std::vector& ind_1 = lines_[i - 1].getIndices(); + const std::vector& ind_2 = lines_[i].getIndices(); + std::vector indices; + indices.reserve(ind_1.size() + ind_2.size()); + indices.insert(indices.end(), ind_1.begin(), ind_1.end()); + indices.insert(indices.end(), ind_2.begin(), ind_2.end()); + + Line merged_line(L_m[1], L_m[0], cov, lines_[i - 1].getStart(), lines_[i].getEnd(), indices); + merged_line.projectEndpoints(); + lines_[i] = merged_line; + } + else + { + merged_lines.push_back(lines_[i - 1]); + } + + if (i == lines_.size() - 1) + { + merged_lines.push_back(lines_[i]); + } + } + + lines_ = merged_lines; +} + +} // namespace robot_line_extraction diff --git a/src/types.cpp b/src/types.cpp new file mode 100644 index 0000000..9df75a7 --- /dev/null +++ b/src/types.cpp @@ -0,0 +1,109 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * robot_line_extraction — parameter and geometry validation. + * + * Author: DuongTD + *********************************************************************/ +#include + +namespace robot_line_extraction +{ +namespace +{ + +bool positive(double value) +{ + return std::isfinite(value) && value > 0.0; +} + +} // namespace + +bool LineExtractionParams::validate(std::string& error) const +{ + if (!positive(bearing_var) || !positive(range_var)) + { + // Both divide the weighted fit. Zero or negative variance means an infinitely trusted + // measurement, which drives the least-squares increment to infinity on the first iteration. + error = "bearing_var and range_var must be finite and > 0"; + return false; + } + if (!positive(least_sq_angle_thresh) || !positive(least_sq_radius_thresh)) + { + // These are the only thing stopping the iteration. Zero means it never converges. + error = "least_sq_angle_thresh and least_sq_radius_thresh must be finite and > 0"; + return false; + } + if (!positive(max_line_gap)) + { + error = "max_line_gap must be finite and > 0"; + return false; + } + if (!positive(min_line_length)) + { + error = "min_line_length must be finite and > 0"; + return false; + } + if (!positive(min_split_dist)) + { + // A non-positive split distance splits at every point, so no run ever survives to be a line. + error = "min_split_dist must be finite and > 0"; + return false; + } + if (!positive(outlier_dist)) + { + error = "outlier_dist must be finite and > 0"; + return false; + } + if (!std::isfinite(min_range) || min_range < 0.0) + { + error = "min_range must be finite and >= 0"; + return false; + } + if (!positive(max_range) || max_range <= min_range) + { + error = "max_range must be finite and > min_range"; + return false; + } + if (min_line_points < 3) + { + // Two points define a line exactly, so a covariance from them is meaningless and the merge + // step would then compare noise against noise. + error = "min_line_points must be >= 3"; + return false; + } + return true; +} + +bool ScanGeometry::operator==(const ScanGeometry& other) const +{ + // Exact comparison on purpose: these come from a sensor driver that repeats the same constants + // frame after frame, so any difference at all means the layout genuinely changed and the bearing + // tables must be rebuilt. A tolerance here would keep stale tables after a real reconfiguration. + return size == other.size && angle_min == other.angle_min && + angle_increment == other.angle_increment; +} + +bool ScanGeometry::validate(std::string& error) const +{ + if (size < 2) + { + error = "scan geometry needs at least 2 rays"; + return false; + } + if (!std::isfinite(angle_min)) + { + error = "scan angle_min must be finite"; + return false; + } + if (!std::isfinite(angle_increment) || angle_increment == 0.0) + { + // Zero increment puts every ray on the same bearing, collapsing the scan to one point. + error = "scan angle_increment must be finite and non-zero"; + return false; + } + return true; +} + +} // namespace robot_line_extraction diff --git a/test/line_extraction_test.cpp b/test/line_extraction_test.cpp new file mode 100644 index 0000000..613b4e8 --- /dev/null +++ b/test/line_extraction_test.cpp @@ -0,0 +1,459 @@ +/********************************************************************* + * + * Software License Agreement (BSD License) + * + * Kiểm trích đoạn thẳng bằng scan TỔNG HỢP — dựng hình trước, sinh tia sau, nên biết trước đáp án. + * + * Bốn nhóm: + * 1. hình cơ bản — tường thẳng, chữ V, khe hở; + * 2. ba lỗi của bản gốc — điểm rơi khi tách, tập tia của đoạn đã gộp, vòng lặp không trần; + * 3. đầu vào rác — rỗng, NaN, inf, sai kích thước; + * 4. cache bố cục scan. + * + * Author: DuongTD + *********************************************************************/ +#include + +#include +#include +#include +#include + +#include + +namespace +{ +using robot_line_extraction::Line; +using robot_line_extraction::LineExtractionParams; +using robot_line_extraction::LineExtractor; +using robot_line_extraction::ScanGeometry; + +constexpr double kNaN = std::numeric_limits::quiet_NaN(); +constexpr double kInf = std::numeric_limits::infinity(); + +ScanGeometry geometry(std::size_t rays, double angle_min = -M_PI / 2.0, + double angle_max = M_PI / 2.0) +{ + ScanGeometry g; + g.angle_min = angle_min; + g.angle_increment = (angle_max - angle_min) / static_cast(rays - 1); + g.size = rays; + return g; +} + +double bearingOf(const ScanGeometry& g, std::size_t i) +{ + return g.angle_min + static_cast(i) * g.angle_increment; +} + +/** + * @brief Cự ly tới đường thẳng vô hạn dạng cực (@p angle, @p radius) dọc tia @p bearing. + * @return kInf khi tia không bao giờ cắt đường đó. + */ +double rangeToLine(double bearing, double angle, double radius) +{ + const double denom = std::cos(bearing - angle); + if (denom <= 1e-9) + { + return kInf; + } + return radius / denom; +} + +/// @brief Scan nhìn thẳng vào một BỨC TƯỜNG phẳng cách @p radius, pháp tuyến ở @p angle. +std::vector wallScan(const ScanGeometry& g, double radius, double angle = 0.0) +{ + std::vector ranges(g.size); + for (std::size_t i = 0; i < g.size; ++i) + { + ranges[i] = rangeToLine(bearingOf(g, i), angle, radius); + } + return ranges; +} + +/** + * @brief Scan nhìn vào một tấm chữ V — đúng hình của tấm dẫn hướng ở trạm sạc. + * + * Hai cánh gặp nhau tại đỉnh trên trục x, cách cảm biến @p apex_x, mỗi cánh nghiêng @p half_angle + * so với trục y. Tia nào không trúng cánh nào thì trả kInf, y như tia bay ra khoảng trống. + */ +std::vector vPlateScan(const ScanGeometry& g, double apex_x, double half_angle, + double wing_length) +{ + std::vector ranges(g.size, kInf); + + // Hai đầu cánh, đối xứng qua trục x. + const double tip_x = apex_x + wing_length * std::sin(half_angle); + const double tip_y = wing_length * std::cos(half_angle); + + for (std::size_t i = 0; i < g.size; ++i) + { + const double bearing = bearingOf(g, i); + const double dx = std::cos(bearing); + const double dy = std::sin(bearing); + + // Cắt tia với hai đoạn (apex -> tip) và (apex -> tip đối xứng); lấy điểm gần nhất. + for (const double side : { 1.0, -1.0 }) + { + const double ax = apex_x; + const double ay = 0.0; + const double bx = tip_x; + const double by = side * tip_y; + + // Giải t*d = a + u*(b-a), u thuộc [0,1], t > 0. + const double ex = bx - ax; + const double ey = by - ay; + const double det = dx * (-ey) - dy * (-ex); + if (std::fabs(det) < 1e-12) + { + continue; + } + const double t = (ax * (-ey) - ay * (-ex)) / det; + const double u = (dx * ay - dy * ax) / det; + if (t > 0.0 && u >= 0.0 && u <= 1.0 && t < ranges[i]) + { + ranges[i] = t; + } + } + } + + return ranges; +} + +LineExtractionParams tightParams() +{ + LineExtractionParams p; + p.min_split_dist = 0.02; // [m] + p.max_line_gap = 0.10; // [m] + p.min_line_length = 0.05; // [m] + p.min_line_points = 5; + p.outlier_dist = 0.10; // [m] + p.min_range = 0.05; // [m] + p.max_range = 20.0; // [m] + return p; +} + +/// @brief Extractor đã cấu hình, để test không lặp lại bốn dòng giống nhau. +class Rig +{ +public: + explicit Rig(const LineExtractionParams& params = tightParams()) + { + ok_ = extractor_.configure(params, error_); + } + + bool run(const ScanGeometry& g, const std::vector& ranges) + { + return extractor_.extract(g, ranges, lines_, error_); + } + + bool ok_ = false; + std::string error_; + LineExtractor extractor_; + std::vector lines_; +}; + +// ================================================================================================ +// 1. Hình cơ bản +// ================================================================================================ + +TEST(LineExtractor, FindsOneLineInAFlatWall) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_; + + ASSERT_EQ(rig.lines_.size(), 1U); + // Tường dựng ở radius 2.0, pháp tuyến 0. Khớp phải trả lại đúng hai con số đó. + EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-3); + EXPECT_NEAR(rig.lines_[0].getAngle(), 0.0, 1e-3); + EXPECT_GT(rig.lines_[0].numPoints(), 100U); +} + +TEST(LineExtractor, RecoversTheAngleOfATiltedWall) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(g, wallScan(g, 1.5, 0.3))) << rig.error_; + + ASSERT_EQ(rig.lines_.size(), 1U); + EXPECT_NEAR(rig.lines_[0].getRadius(), 1.5, 1e-3); + EXPECT_NEAR(rig.lines_[0].getAngle(), 0.3, 1e-3); +} + +TEST(LineExtractor, SplitsAVPlateIntoTwoWings) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + // Đúng hình tấm dẫn hướng: đỉnh cách 1.2 m, hai cánh mở 45 độ, mỗi cánh 0.30 m. + const ScanGeometry g = geometry(400, -0.5, 0.5); + ASSERT_TRUE(rig.run(g, vPlateScan(g, 1.2, M_PI / 4.0, 0.30))) << rig.error_; + + // Hai cánh phải RA HAI ĐOẠN. Ra một đoạn nghĩa là bước gộp đã nuốt mất góc kẹp, và bộ dò V + // không còn gì để đo. + ASSERT_EQ(rig.lines_.size(), 2U) << "V plate must not collapse into a single segment"; + + // Góc kẹp giữa hai pháp tuyến = góc mở của tấm. Hai cánh nghiêng +-45 độ so với trục y nên hai + // pháp tuyến cách nhau 90 độ. + const double delta = + std::fabs(robot_line_extraction::piToPi(rig.lines_[0].getAngle() - rig.lines_[1].getAngle())); + EXPECT_NEAR(delta, M_PI / 2.0, 0.10); + + for (const Line& line : rig.lines_) + { + EXPECT_NEAR(line.length(), 0.30, 0.05) << "wing length must survive the fit"; + } +} + +TEST(LineExtractor, SplitsAtAGapEvenWhenBothSidesAreCollinear) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(300, -0.6, 0.6); + std::vector ranges = wallScan(g, 2.0); + + // Đục một lỗ giữa tường: hai nửa vẫn thẳng hàng hoàn hảo, nhưng chúng KHÔNG phải một bề mặt + // liền. Chỉ độ tản không phân biệt được ca này — phải là luật khe hở. + for (std::size_t i = 140; i < 170; ++i) + { + ranges[i] = kInf; + } + + ASSERT_TRUE(rig.run(g, ranges)) << rig.error_; + EXPECT_EQ(rig.lines_.size(), 2U); +} + +// ================================================================================================ +// 2. Ba lỗi của bản gốc +// ================================================================================================ + +TEST(LineExtractor, ASplitLosesNoPoint) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(400, -0.5, 0.5); + ASSERT_TRUE(rig.run(g, vPlateScan(g, 1.2, M_PI / 4.0, 0.30))) << rig.error_; + ASSERT_EQ(rig.lines_.size(), 2U); + + // Bản gốc cắt bằng `&indices[i_split-1]` và `&indices.back()`, làm rơi một điểm ở MỖI nửa tại + // MỖI lần tách. Đỉnh V thuộc về cả hai cánh, nên tổng số điểm đỡ phải bằng số tia trúng tấm + // CỘNG một (đỉnh được đếm hai lần), không được ít hơn. + const std::vector ranges = vPlateScan(g, 1.2, M_PI / 4.0, 0.30); + std::size_t hits = 0; + for (const double r : ranges) + { + if (std::isfinite(r)) + { + ++hits; + } + } + + const std::size_t support = rig.lines_[0].numPoints() + rig.lines_[1].numPoints(); + EXPECT_EQ(support, hits + 1) << "split dropped points: " << hits << " hits but " << support + << " supporting rays"; +} + +TEST(LineExtractor, AMergedLineReportsItsRealSupport) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(300, -0.6, 0.6); + std::vector ranges = wallScan(g, 2.0); + + // Một vết lồi nhỏ giữa tường, đủ để tách làm đôi nhưng hai nửa vẫn là một mặt phẳng — chính là + // ca mà bước gộp sinh ra để nối lại. + ranges[150] += 0.03; + + ASSERT_TRUE(rig.run(g, ranges)) << rig.error_; + ASSERT_FALSE(rig.lines_.empty()); + + // Bản gốc gọi resize() rồi insert(end()), để lại nửa đầu vector toàn số 0: đoạn đã gộp báo gấp + // đôi số điểm thật, và mọi chỉ số ở nửa đầu đều trỏ về tia 0. + for (const Line& line : rig.lines_) + { + EXPECT_LE(line.numPoints(), g.size) << "merged support exceeds the whole scan"; + + const std::vector& indices = line.getIndices(); + ASSERT_FALSE(indices.empty()); + const std::size_t zeros = static_cast(std::count(indices.begin(), indices.end(), 0U)); + EXPECT_LE(zeros, 1U) << "merged indices are zero-filled"; + } +} + +TEST(LineExtractor, TheLeastSquaresLoopIsBounded) +{ + // Ngưỡng hội tụ đặt cực nhỏ so với độ chính xác của double: bản gốc lặp vô hạn ở đây, tức treo + // luôn control thread. Bản này bỏ đoạn không hội tụ và ĐI TIẾP. + LineExtractionParams params = tightParams(); + params.least_sq_angle_thresh = 1e-300; + params.least_sq_radius_thresh = 1e-300; + + Rig rig(params); + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_; + // Trả về được là đã đủ: test này chết bằng cách TREO, không phải bằng cách fail. + SUCCEED(); +} + +// ================================================================================================ +// 3. Đầu vào rác +// ================================================================================================ + +TEST(LineExtractor, AnEmptySceneYieldsNoLineAndNoError) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180); + // Không có gì trong tầm. Đây là câu trả lời bình thường, không phải lỗi — phòng trống thì trông + // đúng như vậy. + ASSERT_TRUE(rig.run(g, std::vector(g.size, kInf))) << rig.error_; + EXPECT_TRUE(rig.lines_.empty()); +} + +TEST(LineExtractor, NaNRangesAreDroppedWithoutSpecialCasing) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180); + ASSERT_TRUE(rig.run(g, std::vector(g.size, kNaN))) << rig.error_; + EXPECT_TRUE(rig.lines_.empty()); +} + +TEST(LineExtractor, AWallStillReadsCorrectlyThroughScatteredNaN) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(300, -0.6, 0.6); + std::vector ranges = wallScan(g, 2.0); + + // Tia hụt rải rác, đúng như cảm biến thật gặp bề mặt hấp thụ. NaN trượt cả hai phép so trong + // bộ lọc cự ly nên rơi ra ngay, không cần ca đặc biệt ở đâu khác. + for (std::size_t i = 20; i < g.size; i += 37) + { + ranges[i] = kNaN; + } + + ASSERT_TRUE(rig.run(g, ranges)) << rig.error_; + ASSERT_FALSE(rig.lines_.empty()); + EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-2); +} + +TEST(LineExtractor, RefusesRangesThatDoNotMatchTheGeometry) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180); + // Sai kích thước là lỗi lập trình, không phải cảnh quan — nói ra thay vì đọc ngoài mảng. + EXPECT_FALSE(rig.run(g, std::vector(10, 1.0))); + EXPECT_NE(rig.error_.find("does not match"), std::string::npos); +} + +TEST(LineExtractor, RefusesAGeometryItCannotUse) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + ScanGeometry zero_step = geometry(180); + zero_step.angle_increment = 0.0; // mọi tia chung một hướng, scan sụp thành một điểm + EXPECT_FALSE(rig.run(zero_step, std::vector(180, 1.0))); + + ScanGeometry tiny; + tiny.angle_min = 0.0; + tiny.angle_increment = 0.01; + tiny.size = 1; + EXPECT_FALSE(rig.run(tiny, std::vector(1, 1.0))); +} + +TEST(LineExtractor, RefusesParametersThatCanNeverFit) +{ + LineExtractor extractor; + std::string error; + + LineExtractionParams zero_var = tightParams(); + zero_var.range_var = 0.0; + // Phương sai 0 = tin tuyệt đối một phép đo; số gia bình phương tối thiểu ra vô cực ngay vòng đầu. + EXPECT_FALSE(extractor.configure(zero_var, error)); + EXPECT_NE(error.find("range_var"), std::string::npos); + + LineExtractionParams zero_split = tightParams(); + zero_split.min_split_dist = 0.0; + // Tách ở mọi điểm thì không đoạn nào sống sót thành đường. + EXPECT_FALSE(extractor.configure(zero_split, error)); + EXPECT_NE(error.find("min_split_dist"), std::string::npos); + + LineExtractionParams two_points = tightParams(); + two_points.min_line_points = 2; + // Hai điểm xác định đường chính xác nên hiệp phương sai của chúng vô nghĩa, mà bước gộp lại + // quyết định BẰNG hiệp phương sai. + EXPECT_FALSE(extractor.configure(two_points, error)); + EXPECT_NE(error.find("min_line_points"), std::string::npos); + + LineExtractionParams range_swap = tightParams(); + range_swap.max_range = range_swap.min_range; + EXPECT_FALSE(extractor.configure(range_swap, error)); + + // Bộ tham số hỏng bị từ chối thì bộ cũ phải còn nguyên. + LineExtractionParams good = tightParams(); + ASSERT_TRUE(extractor.configure(good, error)) << error; + EXPECT_DOUBLE_EQ(extractor.params().range_var, good.range_var); +} + +// ================================================================================================ +// 4. Cache bố cục scan +// ================================================================================================ + +TEST(LineExtractor, TheSameGeometryTwiceGivesTheSameAnswer) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_; + ASSERT_EQ(rig.lines_.size(), 1U); + const double first_radius = rig.lines_[0].getRadius(); + + // Lần hai dùng lại bảng bearing đã cache. Kết quả phải khớp từng bit — lệch nghĩa là cache mang + // trạng thái của lần chạy trước sang. + ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_; + ASSERT_EQ(rig.lines_.size(), 1U); + EXPECT_DOUBLE_EQ(rig.lines_[0].getRadius(), first_radius); +} + +TEST(LineExtractor, ChangingTheGeometryRebuildsTheBearings) +{ + Rig rig; + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry coarse = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(coarse, wallScan(coarse, 2.0))) << rig.error_; + ASSERT_EQ(rig.lines_.size(), 1U); + + // Bố cục khác hẳn. Giữ bảng cũ là mọi tia bị gán sai hướng, và tường 2 m ra một đường bịa. + const ScanGeometry fine = geometry(400, -1.0, 1.0); + ASSERT_TRUE(rig.run(fine, wallScan(fine, 2.0))) << rig.error_; + ASSERT_EQ(rig.lines_.size(), 1U); + EXPECT_NEAR(rig.lines_[0].getRadius(), 2.0, 1e-3); + EXPECT_NEAR(rig.lines_[0].getAngle(), 0.0, 1e-3); +} + +} // namespace + +int main(int argc, char** argv) +{ + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +}