diff --git a/include/robot_line_extraction/line.h b/include/robot_line_extraction/line.h index 484e948..a1cabab 100644 --- a/include/robot_line_extraction/line.h +++ b/include/robot_line_extraction/line.h @@ -106,6 +106,19 @@ public: /// @brief Cheap fit through the first and last supporting point. Used while splitting. void endpointFit(); + /** + * @brief Closed-form total-least-squares fit over every supporting point. + * + * The line through the centroid along the principal axis of the point scatter — the same + * perpendicular-distance criterion @ref leastSqFit minimises, only unweighted and solved in one + * step instead of iterated. No convergence to fail. + * + * It seeds @ref leastSqFit, and it is what a segment keeps when that iteration gives up. Both + * matter: two endpoints carry two measurements, so their angle inherits the full range noise of + * exactly two rays, while this uses all of them and its angular error falls as sqrt(N). + */ + void totalLeastSqFit(); + /** * @brief Weighted least-squares fit, iterated to convergence, then the covariance. * diff --git a/src/line.cpp b/src/line.cpp index 1783268..2e68c04 100644 --- a/src/line.cpp +++ b/src/line.cpp @@ -133,6 +133,57 @@ void Line::radiusFromEndpoints() } } +// ================================================================================================ +// Total least squares — closed form, seeds the weighted fit +// ================================================================================================ + +void Line::totalLeastSqFit() +{ + const std::size_t n = indices_.size(); + if (n < 2) + { + return; + } + + double mean_x = 0.0; + double mean_y = 0.0; + for (const unsigned int index : indices_) + { + mean_x += r_data_.xs[index]; + mean_y += r_data_.ys[index]; + } + mean_x /= static_cast(n); + mean_y /= static_cast(n); + + double s_xx = 0.0; + double s_xy = 0.0; + double s_yy = 0.0; + for (const unsigned int index : indices_) + { + const double dx = r_data_.xs[index] - mean_x; + const double dy = r_data_.ys[index] - mean_y; + s_xx += dx * dx; + s_xy += dx * dy; + s_yy += dy * dy; + } + + if (s_xx + s_yy < 1e-18) + { + // Every point on top of every other. No direction to speak of; leave whatever fit is in place. + return; + } + + // Principal axis of the scatter, then the normal a quarter turn off it. The half-angle form is + // exact for a symmetric 2x2 and needs no eigen decomposition. + angle_ = piToPi(0.5 * std::atan2(2.0 * s_xy, s_xx - s_yy) + M_PI / 2.0); + radius_ = mean_x * std::cos(angle_) + mean_y * std::sin(angle_); + if (radius_ < 0.0) + { + radius_ = -radius_; + angle_ = piToPi(angle_ + M_PI); + } +} + // ================================================================================================ // Weighted least squares // ================================================================================================ @@ -141,6 +192,18 @@ bool Line::leastSqFit() { calcPointCovariances(); + // Seed from the closed-form fit over all points rather than from the two endpoints. The iteration + // is Newton on a non-convex objective: from a poor start it can wander or oscillate and spend the + // whole iteration budget, and measured on a V dock plate at 1.7-2.5 m roughly a quarter of all + // segments did exactly that. Starting at the answer, it converges in a step or two. + // + // Keeping the seed also decides what a failed fit falls back to, and the two-endpoint fit is a + // poor thing to fall back to: its direction rests on two rays, so it carries several times the + // angular noise of a seventeen-point fit, and that noise lands straight on the apex of the V. + totalLeastSqFit(); + const double seed_angle = angle_; + const double seed_radius = radius_; + double prev_radius = 0.0; double prev_angle = 0.0; int iterations = 0; @@ -150,6 +213,9 @@ bool Line::leastSqFit() { if (++iterations > kMaxLeastSqIterations) { + angle_ = seed_angle; + radius_ = seed_radius; + projectEndpoints(); return false; } @@ -163,6 +229,9 @@ bool Line::leastSqFit() { // 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. + angle_ = seed_angle; + radius_ = seed_radius; + projectEndpoints(); return false; } } diff --git a/test/line_extraction_test.cpp b/test/line_extraction_test.cpp index 8564585..8934278 100644 --- a/test/line_extraction_test.cpp +++ b/test/line_extraction_test.cpp @@ -305,6 +305,51 @@ TEST(LineExtractor, TheLeastSquaresLoopIsBounded) SUCCEED(); } +TEST(Line, TotalLeastSquaresIsAnchoredByEveryPointNotJustTheTwoEnds) +{ + // Mầm của phép tinh chỉnh quyết định hai chuyện: nó có hội tụ không, và còn lại gì nếu không. + // Mầm qua hai đầu mút để hướng của cả đoạn tựa lên đúng HAI tia, nên nhiễu tầm của hai tia đó + // vào thẳng góc của đoạn — rồi vào thẳng đỉnh chữ V, vì đỉnh là giao của hai cánh. + // + // Dựng đúng tình huống phân biệt hai cách: tường phẳng, 19 điểm giữa sạch, chỉ hai đầu mút bị + // đẩy ngược chiều nhau. Phản đối xứng nên nó XOAY đoạn chứ không tịnh tiến. Khớp hai đầu mút + // nghiêng theo trọn vẹn; khớp đủ điểm bị 19 điểm giữa neo lại. + const ScanGeometry g = geometry(21, -0.3, 0.3); + std::vector ranges = wallScan(g, 2.0); + ranges.front() += 0.03; // [m] đẩy ra + ranges.back() -= 0.03; // [m] kéo vào + + robot_line_extraction::CachedData c_data; + robot_line_extraction::RangeData r_data; + std::vector indices; + for (std::size_t i = 0; i < g.size; ++i) + { + const double bearing = bearingOf(g, i); + c_data.bearings.push_back(bearing); + c_data.cos_bearings.push_back(std::cos(bearing)); + c_data.sin_bearings.push_back(std::sin(bearing)); + c_data.indices.push_back(static_cast(i)); + r_data.ranges.push_back(ranges[i]); + r_data.xs.push_back(ranges[i] * std::cos(bearing)); + r_data.ys.push_back(ranges[i] * std::sin(bearing)); + indices.push_back(static_cast(i)); + } + + Line line(c_data, r_data, tightParams(), indices); + + line.endpointFit(); + const double endpoint_angle = line.getAngle(); + + line.totalLeastSqFit(); + const double tls_angle = line.getAngle(); + + // Pháp tuyến thật của tường ở 0. Hai đầu bị đẩy kéo khớp hai đầu mút đi hẳn; khớp đủ điểm chịu + // chưa tới một phần ba mức đó. + EXPECT_GT(std::fabs(endpoint_angle), 0.040); + EXPECT_LT(std::fabs(tls_angle), 0.020); + EXPECT_LT(std::fabs(tls_angle), std::fabs(endpoint_angle) / 3.0); +} + 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ỏ