fix(leg_pattern): accept attached legs, treat zero range as no echo, rank ties by fit

On the KIT robot (28/10), hiding one trolley leg with a post always made
detection fail with "too few legs". The far-right leg stood less than
leg_min_depth_gap in front of another object, so its cluster was rejected
as "attached". Hiding one more leg left only two free-standing legs.

- LegProfile::accept_attached_legs (default false): an attached cluster
  that passes the width and point gates becomes a weak leg. A weak leg
  can be assigned to a corner, counts toward min_legs and enters the fit,
  but it cannot start a hypothesis. So every cart still needs one pair of
  free-standing legs at the right spacing.
- ScanLimits::zero_range_is_no_echo (default false): the KIT driver
  reports no echo as range 0. The matcher read 0 as "blocked closer than
  min_range", so every leg edge was marked partial, and a 0 ray at a
  missing corner always read as occluded. With the flag set, an edge next
  to a 0 ray is free. A corner that sees only 0 rays carries no evidence.
  A ray that passes the corner and returns from a surface behind it still
  rejects the cart.
- Confidence ties: fit_term saturates at 1, so two 4-leg hypotheses can
  both score 1.00. The nearer one used to win, even when it had taken a
  post standing 9 cm from a leg (3.4 cm off). Ties now go to the lower
  normalized RMS first.
- LegDetection::legs_attached; the reason text says when only attached
  legs were found at the cart spacing.

Tests: leg_pattern_matcher_kit_test replays 6 real KIT scans
(test/data/kit_f_scan_trolley_occlusion.txt). leg_pattern_matcher_test
adds 4 synthetic cases. With both keys off, behaviour is unchanged except
for the tie rule. All 111 tests of this package and the trolley handler
pass.
This commit is contained in:
2026-10-28 16:37:28 +07:00
parent cb401e6316
commit 979bef360d
8 changed files with 489 additions and 16 deletions

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,209 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* Kiểm dò xe hàng 4 chân trên scan THẬT của lidar KIT (`/f_scan`, 1600 tia quanh 360°, trả range 0
* khi không có phản hồi). Lần lượt một cột 6×6 cm che từng chân; chân xa-phải luôn dính một vật
* phía sau nó. Đây là ca đã fail trên robot ngày 28/10: chân dính bị loại, che thêm một chân là còn
* hai chân sạch.
*
* `reference` trong file dữ liệu là kết quả dò của chính robot trong cùng bố trí, không phải đáp án
* đo bằng thước — nên dung sai test rộng hơn test tổng hợp.
*
* Author: DuongTD
*********************************************************************/
#include <gtest/gtest.h>
#include <cmath>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <dock_pattern_detector/leg_pattern_matcher.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;
constexpr double kDeg = M_PI / 180.0;
struct RecordedScan
{
std::string name;
robot_line_extraction::ScanGeometry geometry;
std::vector<double> ranges;
double ref_x = 0.0; // [m]
double ref_y = 0.0; // [m]
double ref_yaw = 0.0; // [rad]
};
std::vector<RecordedScan> loadScans()
{
std::vector<RecordedScan> scans;
std::ifstream in(std::string(DOCK_PATTERN_DETECTOR_TEST_DATA_DIR) +
"/kit_f_scan_trolley_occlusion.txt");
std::string line;
while (std::getline(in, line))
{
if (line.empty() || line[0] == '#')
{
continue;
}
std::istringstream header(line);
std::string tag;
RecordedScan s;
header >> tag >> s.name >> s.geometry.angle_min >> s.geometry.angle_increment >>
s.geometry.size >> s.ref_x >> s.ref_y >> s.ref_yaw;
if (tag != "scan" || !std::getline(in, line))
{
break;
}
std::istringstream values(line);
double r = 0.0;
while (values >> r)
{
s.ranges.push_back(r);
}
scans.push_back(s);
}
return scans;
}
const RecordedScan& scanNamed(const std::vector<RecordedScan>& scans, const std::string& name)
{
for (const RecordedScan& s : scans)
{
if (s.name == name)
{
return s;
}
}
ADD_FAILURE() << "no scan '" << name << "' in the data file";
static const RecordedScan kEmpty;
return kEmpty;
}
/// @brief Profile đang chạy trên robot KIT (số tâm–tâm đo tay, dung sai gia công 6 cm).
LegProfile kitTrolley(bool accept_attached_legs)
{
LegProfile p;
p.cart_opening = 0.48;
p.cart_depth = 0.762;
p.cart_dim_tolerance = 0.06;
p.leg_shape = LegShape::kBox;
p.leg_width = 0.030;
p.leg_width_tolerance = 0.03;
p.min_legs = 3;
p.accept_attached_legs = accept_attached_legs;
return p;
}
LegDetection detect(const RecordedScan& s, bool accept_attached_legs, bool zero_is_no_echo)
{
LegPatternMatcher matcher;
std::string error;
EXPECT_TRUE(matcher.configure(kitTrolley(accept_attached_legs), error)) << error;
ScanLimits limits;
limits.min_range = 0.10;
limits.max_range = 3.0;
limits.range_sigma = 0.01;
limits.zero_range_is_no_echo = zero_is_no_echo;
return matcher.match(s.geometry, s.ranges, {}, limits, Pose2D());
}
double yawError(double a, double b)
{
return std::fabs(std::atan2(std::sin(a - b), std::cos(a - b)));
}
const char* const kHiddenLegScans[] = { "entry_left_hidden", "entry_right_hidden",
"far_left_hidden", "close_entry_right_hidden",
"close_entry_left_hidden" };
TEST(LegPatternMatcherKit, DataFileLoads)
{
const std::vector<RecordedScan> scans = loadScans();
ASSERT_EQ(scans.size(), 6u);
for (const RecordedScan& s : scans)
{
EXPECT_EQ(s.ranges.size(), s.geometry.size) << s.name;
}
}
TEST(LegPatternMatcherKit, AllFourLegsVisibleIsFoundEitherWay)
{
// Cột đứng cạnh chân xa-phải 9 cm cũng ghép được thành "chân xa-phải". Khi tắt khoá, cả hai giả
// thuyết qua mọi cổng và cùng điểm tin 1.00; giả thuyết lấy nhầm cột gần cảm biến hơn nhưng khớp
// tệ hơn. Phải chọn theo mức khớp, không theo khoảng cách.
const std::vector<RecordedScan> scans = loadScans();
const RecordedScan& s = scanNamed(scans, "far_right_leg_beside_post");
for (int mode = 0; mode < 2; ++mode)
{
const bool on = mode == 1;
const LegDetection d = detect(s, on, on);
ASSERT_TRUE(d.valid) << "keys " << (on ? "on" : "off") << ": " << d.reason;
EXPECT_EQ(d.legs_seen, 4);
EXPECT_NEAR(d.center_x, s.ref_x, 0.02) << "keys " << (on ? "on" : "off");
EXPECT_NEAR(d.center_y, s.ref_y, 0.02) << "keys " << (on ? "on" : "off");
EXPECT_LT(yawError(d.center_yaw, s.ref_yaw), 1.5 * kDeg) << "keys " << (on ? "on" : "off");
}
}
TEST(LegPatternMatcherKit, OneHiddenLegFailsWithoutTheNewKeys)
{
// Hành vi trước 28/10, giữ nguyên khi tắt cả hai khoá: chân xa-phải dính vật phía sau bị loại,
// nên che thêm một chân là chỉ còn hai chân sạch.
const std::vector<RecordedScan> scans = loadScans();
for (const char* name : kHiddenLegScans)
{
const LegDetection d = detect(scanNamed(scans, name), false, false);
EXPECT_FALSE(d.valid) << name << ": unexpectedly found at (" << d.center_x << ", "
<< d.center_y << ")";
}
}
TEST(LegPatternMatcherKit, OneHiddenLegIsFoundWithAttachedLegsAndNoEcho)
{
const std::vector<RecordedScan> scans = loadScans();
for (const char* name : kHiddenLegScans)
{
const RecordedScan& s = scanNamed(scans, name);
const LegDetection d = detect(s, true, true);
ASSERT_TRUE(d.valid) << name << ": " << d.reason;
EXPECT_EQ(d.legs_seen, 3) << name;
EXPECT_EQ(d.legs_attached, 1) << name << ": the far-right leg is the attached one";
// Chân bị cột che: cột gần hơn chỗ chân (occluded) hoặc nằm trong dải range của chân (distorted).
EXPECT_EQ(d.legs_occluded + d.legs_distorted, 1) << name;
EXPECT_NEAR(d.center_x, s.ref_x, 0.02) << name;
EXPECT_NEAR(d.center_y, s.ref_y, 0.02) << name;
EXPECT_LT(yawError(d.center_yaw, s.ref_yaw), 1.5 * kDeg) << name;
}
}
TEST(LegPatternMatcherKit, ZeroRangeAsNoEchoClearsTheFalsePartialFlags)
{
// Driver trả 0 cho tia không phản hồi. Đọc 0 là "bị chắn sát cảm biến" thì mọi mép chân kề tia 0
// thành mép bị che: cả bốn chân partial dù đứng trơ trọi.
const std::vector<RecordedScan> scans = loadScans();
const RecordedScan& s = scanNamed(scans, "far_right_leg_beside_post");
const LegDetection blocked = detect(s, false, false);
const LegDetection no_echo = detect(s, false, true);
ASSERT_TRUE(blocked.valid) << blocked.reason;
ASSERT_TRUE(no_echo.valid) << no_echo.reason;
EXPECT_EQ(blocked.legs_partial, 4);
EXPECT_LT(no_echo.legs_partial, blocked.legs_partial);
}
} // namespace
int main(int argc, char** argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

View File

@@ -5,12 +5,15 @@
* 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:
* Sáu 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.
* 5. chân dính làm chân yếu, lidar trả 0 khi không phản hồi;
* 6. config hỏng.
*
* Scan thật của lidar KIT nằm ở `leg_pattern_matcher_kit_test.cpp`.
*
* Author: DuongTD
*********************************************************************/
@@ -457,7 +460,127 @@ TEST(LegPatternMatcher, IsDeterministic)
}
// ================================================================================================
// 5. Config
// 5. Chân dính (`accept_attached_legs`) và lidar trả 0 khi không phản hồi (`zero_range_is_no_echo`)
// ================================================================================================
/// @brief Như detect(), nhưng chọn được ScanLimits và đổi tia không trúng gì (inf) thành 0 như driver
/// lidar KIT.
LegDetection detectWith(const LegProfile& p, const World& world, bool zero_for_no_echo,
bool zero_range_is_no_echo)
{
LegPatternMatcher matcher;
std::string error;
EXPECT_TRUE(matcher.configure(p, error)) << error;
const auto g = leg_scan_sim::s300Geometry();
leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g);
if (zero_for_no_echo)
{
for (double& r : scan.ranges)
{
r = std::isfinite(r) ? r : 0.0;
}
}
ScanLimits limits = s300Limits();
limits.zero_range_is_no_echo = zero_range_is_no_echo;
return matcher.match(g, scan.ranges, scan.intensities, limits, Pose2D());
}
TEST(LegPatternMatcher, AttachedLegCountsWhenEnabled)
{
// Ca robot KIT 28/10: một chân bị che (ở đây: chân xa-trái nấp sau chân vào-trái), và chân xa-phải
// đứng trước một vật cách 8 cm — gần hơn leg_min_depth_gap nên mép cụm "dính". Chỉ còn hai chân tự
// do.
LegProfile p = tciTrolley();
World w;
const double cy = p.cart_opening / 2.0;
leg_scan_sim::addCart(w, p, kCx, cy, M_PI);
const double behind = kCx + p.cart_depth / 2.0 + p.leg_width / 2.0 + 0.08;
w.addWall(behind, p.cart_opening - 0.15, behind, p.cart_opening + 0.15);
p.accept_attached_legs = false;
const LegDetection off = detectWith(p, w, false, false);
EXPECT_FALSE(off.valid);
EXPECT_NE(off.reason.find("too few legs"), std::string::npos) << off.reason;
p.accept_attached_legs = true;
const LegDetection on = detectWith(p, w, false, false);
ASSERT_TRUE(on.valid) << on.reason;
EXPECT_EQ(on.legs_seen, 3);
EXPECT_EQ(on.legs_attached, 1);
EXPECT_EQ(on.legs_occluded, 1);
EXPECT_NEAR(on.center_x, kCx, 0.005);
EXPECT_NEAR(on.center_y, cy, 0.005);
EXPECT_LT(yawError(on.center_yaw, M_PI), 0.5 * kDeg);
}
TEST(LegPatternMatcher, AttachedLegsCannotStartAHypothesis)
{
// Chỉ còn hai chân xa, cả hai dính tường phía sau: đúng khoảng cách cart_opening nhưng là chân yếu.
// Hai chỗ lồi trên tường cũng trông y như vậy, nên không được tự dựng xe.
LegProfile p = tciTrolley();
p.accept_attached_legs = true;
World w;
const bool skip[4] = { true, true, false, false };
leg_scan_sim::addCart(w, p, kCx, 0.0, M_PI, skip);
const double behind = kCx + p.cart_depth / 2.0 + p.leg_width / 2.0 + 0.08;
w.addWall(behind, -0.8, behind, 0.8);
const LegDetection d = detectWith(p, w, false, false);
EXPECT_FALSE(d.valid);
EXPECT_EQ(d.leg_candidates, 2u);
EXPECT_EQ(d.hypotheses, 0u);
EXPECT_NE(d.reason.find("attached legs cannot start a hypothesis"), std::string::npos)
<< d.reason;
}
TEST(LegPatternMatcher, ZeroRangeAsNoEchoMatchesAnInfScan)
{
const LegProfile p = tciTrolley();
World w;
leg_scan_sim::addCart(w, p, kCx, 0.05, M_PI + 10.0 * kDeg);
const LegDetection inf_scan = detectWith(p, w, false, false);
const LegDetection zero_blocked = detectWith(p, w, true, false);
const LegDetection zero_no_echo = detectWith(p, w, true, true);
ASSERT_TRUE(inf_scan.valid) << inf_scan.reason;
ASSERT_TRUE(zero_blocked.valid) << zero_blocked.reason;
ASSERT_TRUE(zero_no_echo.valid) << zero_no_echo.reason;
// Đọc 0 là "bị chắn sát cảm biến": mép nào cũng thành mép bị che.
EXPECT_EQ(inf_scan.legs_partial, 0);
EXPECT_EQ(zero_blocked.legs_partial, 4);
// Đọc 0 là "không phản hồi": y hệt scan trả inf, từng bit.
EXPECT_EQ(zero_no_echo.legs_partial, 0);
EXPECT_EQ(zero_no_echo.center_x, inf_scan.center_x);
EXPECT_EQ(zero_no_echo.center_y, inf_scan.center_y);
EXPECT_EQ(zero_no_echo.center_yaw, inf_scan.center_yaw);
}
TEST(LegPatternMatcher, ZeroRangeIsNoEvidenceButABackgroundStillSeesThrough)
{
const LegProfile p = tciTrolley();
const bool skip[4] = { false, false, false, true }; // thiếu chân sau-phải
// Phía sau trống, mọi tia đi qua chỗ chân đều trả 0: không biết tia đi tới đâu, nên không loại
// xe (với scan trả inf thì loại — xem RejectsWhenTheScanPassesWhereALegMustStand).
World open;
leg_scan_sim::addCart(open, p, kCx, 0.0, M_PI, skip);
const LegDetection unknown = detectWith(p, open, true, true);
ASSERT_TRUE(unknown.valid) << unknown.reason;
EXPECT_EQ(unknown.legs_seen, 3);
EXPECT_EQ(unknown.legs_out_of_view, 1);
// Có tường phía sau: tia đi qua chỗ chân rồi trả về từ tường, đó là bằng chứng thật.
World backed = open;
backed.addWall(2.4, -1.0, 2.4, 1.0);
const LegDetection missing = detectWith(p, backed, true, true);
EXPECT_FALSE(missing.valid);
EXPECT_NE(missing.reason.find("leg_missing"), std::string::npos) << missing.reason;
}
// ================================================================================================
// 6. Config
// ================================================================================================
TEST(LegProfile, ValidateRefusesBrokenProfiles)