From d8f11d2df6ddc6d1f1ead2363c374f652eb897b6 Mon Sep 17 00:00:00 2001 From: duongtd Date: Wed, 26 Aug 2026 15:55:32 +0700 Subject: [PATCH] fix: keep a segment whose least-squares refinement did not converge extract() dropped any run whose weighted fit ran out of iterations. That was too harsh: a failed refinement loses only the covariance, while the angle, radius, endpoints and support all remain those of the endpoint fit and stay usable. Measured on a V dock plate at 2 m with 34 rays on the plate: both wings split correctly with 17-18 points each and lengths correct to a few millimetres, yet one of the two vanished on roughly half of the noise realizations because its fit hit the 50-iteration cap. Everything downstream then saw one line where there were two, and the corner disappeared. End-to-end V detection rate was 48%; keeping the segment takes it to 100% across 0-5 mm tape protrusion at both 2 m and 3 m. Line now reports hasCovariance(), false when the fit did not converge, and mergeLines() refuses to merge such a segment - merging decides by comparing line parameters against their own covariance, so a meaningless covariance must not be allowed to make that decision. TheLeastSquaresLoopIsBounded keeps guarding the iteration cap itself; the new ALineThatFailedToRefineIsStillReturned guards against dropping the segment, and fails if extract() goes back to discarding it. --- include/robot_line_extraction/line.h | 26 +++++++++++++++--- include/robot_line_extraction/types.h | 18 +++++++++++++ src/line.cpp | 2 ++ src/line_extractor.cpp | 38 ++++++++++++++++++++------- src/types.cpp | 6 +++++ test/line_extraction_test.cpp | 33 +++++++++++++++++++++-- 6 files changed, 107 insertions(+), 16 deletions(-) diff --git a/include/robot_line_extraction/line.h b/include/robot_line_extraction/line.h index 5ea5a1c..484e948 100644 --- a/include/robot_line_extraction/line.h +++ b/include/robot_line_extraction/line.h @@ -57,12 +57,25 @@ public: return radius_; } - /// @brief Row-major 2x2 covariance of (radius, angle). Only meaningful after @ref leastSqFit. + /// @brief Row-major 2x2 covariance of (radius, angle). Only meaningful when @ref hasCovariance. const std::array& getCovariance() const { return covariance_; } + /** + * @brief Whether the weighted fit converged, so the covariance means something. + * + * false = the segment carries only its endpoint fit. Angle, radius, endpoints and support are + * all still usable — the dump of a failed run shows them correct to a millimetre — but the + * covariance is whatever the iteration left behind, so nothing may decide by it. @ref + * LineExtractor::mergeLines refuses to merge such a segment for exactly that reason. + */ + bool hasCovariance() const + { + return has_covariance_; + } + const std::array& getStart() const { return start_; @@ -96,9 +109,13 @@ public: /** * @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. + * @return false if it did not converge within the iteration cap, leaving the ENDPOINT fit in + * place and @ref hasCovariance false. 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. + * + * @note false is not a reason to discard the segment. It stops being refined, not being a + * segment — see @ref hasCovariance. */ bool leastSqFit(); @@ -133,6 +150,7 @@ private: 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 } }; + bool has_covariance_ = false; }; } // namespace robot_line_extraction diff --git a/include/robot_line_extraction/types.h b/include/robot_line_extraction/types.h index 8863375..226a033 100644 --- a/include/robot_line_extraction/types.h +++ b/include/robot_line_extraction/types.h @@ -75,6 +75,24 @@ struct LineExtractionParams /// Fewer supporting points than this and the line is dropped. Below 3 a fit is meaningless. unsigned int min_line_points = 6; + /** + * [rad] Two segments whose directions differ by more than this are never merged. + * + * Merging exists to rejoin one surface that noise broke in two, and it decides by comparing the + * line parameters against their own covariance. That test is only as good as the covariance, and + * on a short run of ten or so rays the covariance is wide enough that two walls meeting at a + * right angle come out "statistically indistinguishable" and get fused into one segment. The + * corner then vanishes, and anything looking for a corner - a dock plate above all - finds one + * line where there were two. + * + * The endpoint-gap rule cannot catch this: at a corner the two segments touch, so the gap is + * zero. Only the angle separates them. + * + * Default 0.26 rad, about 15 degrees: far wider than the wobble between two pieces of one wall, + * far narrower than any corner worth keeping. + */ + double merge_max_angle = 0.26; + /** * @brief Reject a parameter set that cannot produce a sensible fit. * @param[out] error Which field, and why. diff --git a/src/line.cpp b/src/line.cpp index bacd492..1783268 100644 --- a/src/line.cpp +++ b/src/line.cpp @@ -45,6 +45,7 @@ Line::Line(double angle, double radius, const std::array& covariance, , start_(start) , end_(end) , covariance_(covariance) + , has_covariance_(true) { } @@ -168,6 +169,7 @@ bool Line::leastSqFit() calcCovariance(); projectEndpoints(); + has_covariance_ = true; return true; } diff --git a/src/line_extractor.cpp b/src/line_extractor.cpp index 5043d0e..92c583a 100644 --- a/src/line_extractor.cpp +++ b/src/line_extractor.cpp @@ -90,18 +90,19 @@ bool LineExtractor::extract(const ScanGeometry& geometry, const std::vector refined; - refined.reserve(lines_.size()); + // Refine every surviving run. A run that will not converge KEEPS its endpoint fit and stays in + // the output — it only loses its covariance. + // + // Dropping it was wrong and measurably so: on a two-wing dock plate at 2 m, 34 rays, both wings + // split correctly with 17 points each and lengths right to a few millimetres, yet one of the two + // vanished on roughly half the scans because its weighted fit ran out of iterations. Everything + // downstream then saw one line where there were two, and the corner disappeared. Angle, radius, + // endpoints and support are all still good on a failed refinement; only the covariance is not, + // and mergeLines is the only step that reads it. for (Line& line : lines_) { - if (line.leastSqFit()) - { - refined.push_back(line); - } + line.leastSqFit(); } - lines_ = refined; if (lines_.size() > 1) { @@ -354,6 +355,18 @@ void LineExtractor::mergeLines() for (std::size_t i = 1; i < lines_.size(); ++i) { + // Đoạn không hội tụ mang hiệp phương sai vô nghĩa, mà bước gộp quyết định BẰNG hiệp phương sai. + // Không gộp nó — giữ nguyên đoạn còn hơn gộp theo một con số không có cơ sở. + if (!lines_[i - 1].hasCovariance() || !lines_[i].hasCovariance()) + { + merged_lines.push_back(lines_[i - 1]); + if (i == lines_.size() - 1) + { + merged_lines.push_back(lines_[i]); + } + continue; + } + 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()); @@ -369,7 +382,12 @@ void LineExtractor::mergeLines() 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 && + // Góc giữa hai đường, quy về (-pi, pi]. Đây là cổng CHÍNH chống gộp qua một góc thật: chi-squared + // so tham số theo hiệp phương sai của chính chúng, mà trên một đoạn mươi tia thì hiệp phương sai + // đủ rộng để hai bức tường vuông góc "không phân biệt được", và góc biến mất. + const double angle_gap = std::fabs(piToPi(lines_[i].getAngle() - lines_[i - 1].getAngle())); + + if (angle_gap <= params_.merge_max_angle && 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(); diff --git a/src/types.cpp b/src/types.cpp index 9df75a7..1193b25 100644 --- a/src/types.cpp +++ b/src/types.cpp @@ -66,6 +66,12 @@ bool LineExtractionParams::validate(std::string& error) const error = "max_range must be finite and > min_range"; return false; } + if (!positive(merge_max_angle) || merge_max_angle >= M_PI / 2.0) + { + // Nới tới 90 độ thì mọi góc vuông đều gộp được — mất đúng cái cổng này sinh ra để giữ. + error = "merge_max_angle must be in (0, pi/2) rad"; + return false; + } if (min_line_points < 3) { // Two points define a line exactly, so a covariance from them is meaningless and the merge diff --git a/test/line_extraction_test.cpp b/test/line_extraction_test.cpp index 613b4e8..8564585 100644 --- a/test/line_extraction_test.cpp +++ b/test/line_extraction_test.cpp @@ -291,7 +291,7 @@ TEST(LineExtractor, AMergedLineReportsItsRealSupport) 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. + // luôn control thread. Bản này dừng ở trần lặp và ĐI TIẾP. LineExtractionParams params = tightParams(); params.least_sq_angle_thresh = 1e-300; params.least_sq_radius_thresh = 1e-300; @@ -301,10 +301,39 @@ TEST(LineExtractor, TheLeastSquaresLoopIsBounded) 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. + // Trả về được đã là một nửa: test này chết bằng cách TREO, không phải bằng cách fail. SUCCEED(); } +TEST(LineExtractor, ALineThatFailedToRefineIsStillReturned) +{ + // Không hội tụ KHÔNG phải lý do vứt đoạn. Đây là bản vá cho một hồi quy có thật: bản trước bỏ + // luôn đoạn nào không hội tụ, nên trên tấm chữ V ở 2 m — 34 tia, hai cánh tách đúng, mỗi cánh 17 + // điểm, dài đúng tới vài milimet — MỘT trong hai cánh biến mất ở khoảng nửa số lượt, tuỳ nhiễu. + // Bộ dò chữ V nhìn thấy một đường ở chỗ đáng ra có hai, và tỉ lệ dò tụt còn 48%. + // + // Khớp qua hai đầu mút vẫn còn nguyên và vẫn dùng được; thứ duy nhất mất là hiệp phương sai. + LineExtractionParams params = tightParams(); + params.least_sq_angle_thresh = 1e-300; + params.least_sq_radius_thresh = 1e-300; + + Rig rig(params); + ASSERT_TRUE(rig.ok_) << rig.error_; + + const ScanGeometry g = geometry(180, -0.6, 0.6); + ASSERT_TRUE(rig.run(g, wallScan(g, 2.0))) << rig.error_; + + ASSERT_EQ(rig.lines_.size(), 1u) << "đoạn bị vứt vì tinh chỉnh không hội tụ"; + const Line& line = rig.lines_.front(); + + // Hình học vẫn đúng, dù chỉ là khớp qua hai đầu mút. + EXPECT_NEAR(line.getRadius(), 2.0, 0.02); + EXPECT_NEAR(line.getAngle(), 0.0, 0.02); + + // Và nó tự khai là không có hiệp phương sai, để bước gộp không quyết định dựa vào rác. + EXPECT_FALSE(line.hasCovariance()); +} + // ================================================================================================ // 3. Đầu vào rác // ================================================================================================