fix(leg_pose_fit): estimate the taped range bias when every leg is taped, gated by its per-leg posterior std

This commit is contained in:
2026-10-30 10:58:55 +07:00
parent 588ed58b6d
commit a6c09f2386
11 changed files with 456 additions and 21 deletions

View File

@@ -193,23 +193,19 @@ toàn bộ điểm không sáng (chân trần); điểm sáng được hiệu ch
bias gần 0. `0` tắt ước lượng và dùng fit 3-DoF cũ. Fit từ chối kết quả nếu `|b| > 0.1 m` để tránh
đưa hiệu chỉnh bất thường vào pose.
**Lỗi đã biết, chưa sửa (30/10): dán băng gương cả 4 chân thì bias không được hiệu chỉnh.** Lidar KIT
đọc điểm băng gương ngắn hơn thật khoảng b ≈ 0.028–0.032 m (tia gần bão hoà), mỗi chân dán bị kéo
về phía lidar dọc theo tia của chính nó. Khi `tape_legs: all` không còn chân trần làm mốc, nên fit
4-DoF ở trên không chạy và b giữ nguyên trong pose:
- Đứng gần (lidar sát đường cạnh vào, hai chân trước lệch nhau ~88° nhìn từ lidar): hai chân bị kéo
gần như ngược chiều, cặp cạnh vào co 1.4·b ≈ 4–6 cm. Bag 29/10 13:35 (run6): 3 lần detect fail ở
225/225 scan với `two legs 0.701–0.719 m apart where the cart has 0.762 (tolerance 0.042)`.
- 0.8–1.5 m: còn qua nhưng sát ngưỡng (30/10: opening 0.752 ở 1.5 m, 0.734 ở 0.78 m).
- Đứng xa: khoảng cách cặp gần đúng, nhưng cả xe bị kéo gần lidar thêm ~2.5 cm mà không báo lỗi
(thiếu chiều sâu khi dock).
Cặp chân nằm dọc theo tia nhìn bị kéo cùng chiều nên vẫn đúng (depth 0.478–0.484). Hướng sửa đã thử
offline trên run6: fit pose cộng một b chung trên các chân đều dán cho b = 0.028–0.032 ổn định, RMS chân
giảm từ 1.7–2.0 cm xuống 0.3–0.5 cm, tâm xe dịch 2.4–2.7 cm. Sai số ước lượng σ_b tăng theo khoảng cách
(≈ 0.009 ở 0.65 m, 0.013 ở 1.0 m, 0.023 ở 2.0 m), nên chỉ nên dùng b khi σ_b đủ nhỏ và phải gắn sau
`tape_enabled` cộng khoá riêng để detect không dán gương giữ nguyên.
**Dán cả 4 chân (30/10):** `tape_range_bias_all_max_std` [m] mặc định 0 giữ đường cũ.
Khi bật tape, `tape_legs: all` và `tape_range_bias_sigma > 0`, fit thử thêm bias không có chân
trần rồi chỉ nhận nếu σ hậu nghiệm không vượt ngưỡng; nếu không thì chạy lại fit 3-DoF cũ. Điểm
sáng được đẩy ra xa lidar dọc theo tia; kết quả xa vẫn có thể bị kéo gần lidar khi gate từ chối.
Giá trị trong [0, 0.1]: tăng nhận nhiều hơn nhưng có nguy cơ bù sai pose ở xa; giảm bảo thủ hơn.
σ dùng trọng số từng tia chia số tia trong cùng chân và prior, để mỗi chân đóng góp như một
phép đo do lỗi các tia cùng chân tương quan. Đây là xấp xỉ, chưa mô hình hoá sai số kích thước
xe, nên không phải cam kết độ chính xác robot. KIT dùng 0.02 m, chọn từ replay toàn bộ scan của 3
bag dán gương (30/10): detect thường có σ 0.0076 (0.6 m, 4 chân) tới ~0.015 (1.6 m, 3 chân); ca hình
học yếu 0.021–0.05 bị loại. Kết quả replay: 3 lần detect robot FAIL ở run6 từ 0 lên 229/229 scan
(pose dao động ≤ 4 mm), không mất scan nào đang hợp lệ, opening sau hiệu chỉnh 0.754–0.765 (thật
0.762), xe dịch xa lidar trung bình 2.2–2.6 cm; bag dán 2 chân giống hệt. Chưa có dữ liệu dán cả 4
chân xa hơn 1.6 m, và chưa chạy trên robot.
**Điểm tin** = ½ · (số chân thấy / 4) + ½ · clamp(2 − RMS chuẩn hoá, 0, 1). RMS chuẩn hoá chia phần dư
cho `sqrt(σ_điểm² + (cart_dim_tolerance / 2)²)`: σ_điểm là nhiễu lidar (`range_sigma`), còn

View File

@@ -83,6 +83,8 @@ struct LegDetection
double tape_range_bias = 0.0; ///< [m] Bias đã bù cho tia sáng; 0 nếu không ước lượng.
bool tape_range_bias_estimated = false;
double tape_range_bias_std = 0.0; ///< [m] σ hậu nghiệm, kể cả khi nhánh all bị từ chối.
bool tape_range_bias_all_bright = false;
/// Số tia sáng trên từng chân (thứ tự @ref LegCorner), 0 khi dải tắt hoặc chân không thấy.
std::array<std::size_t, kLegCount> tape_bright_rays = { { 0, 0, 0, 0 } };

View File

@@ -91,6 +91,8 @@ struct PoseFitResult
bool converged = false;
double bright_range_bias = 0.0; ///< [m] Sai lệch cự ly chung ước lượng cho điểm sáng.
bool bright_range_bias_estimated = false;
double bright_range_bias_std = 0.0; ///< [m] σ hậu nghiệm; 0 nếu không tính.
bool bright_range_bias_all_bright = false; ///< Đã nhận nhánh không có góc chân trần.
std::string reason; ///< Lý do fit không hợp lệ; rỗng khi fit hợp lệ hoặc dùng đường 3-DoF cũ.
};
@@ -112,6 +114,7 @@ struct FitNoise
/// [m] σ tiên nghiệm của bias cự ly chung cho điểm sáng; 0 = không ước lượng bias.
double bright_range_bias_sigma = 0.0;
double bright_range_bias_all_max_std = 0.0; ///< [m] 0 = tắt nhánh không có chân trần.
};
/**
@@ -138,7 +141,8 @@ bool procrustes2D(const std::vector<std::array<double, 2>>& model,
* cự ly |p| + b. Nhánh 4-DoF cũng dùng Jacobian sai phân,
* Huber và chia đôi bước. Hai nhánh dừng khi bước tịnh tiến nhỏ hơn 0.1 mm và bước yaw nhỏ hơn
* 0.01°; nhánh 4-DoF còn yêu cầu |db| < 0.1 mm. Bias |b| > 0.1 m làm fit không hợp lệ. Nếu σ = 0
* hoặc không có cả góc sáng lẫn góc chân trần, dùng đường 3-DoF cũ. Tất định; tối đa
* hoặc không có cả góc sáng lẫn góc chân trần, dùng đường 3-DoF cũ, trừ khi bật ngưỡng
* `bright_range_bias_all_max_std` và σ hậu nghiệm không vượt ngưỡng. Tất định; tối đa
* @p max_iterations vòng.
*/
PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& points,

View File

@@ -170,6 +170,9 @@ struct LegProfile
*/
double tape_range_bias_sigma = 0.0;
/// [m] Ngưỡng σ hậu nghiệm của bias khi không có góc chân trần; 0 = tắt.
double tape_range_bias_all_max_std = 0.0;
// --- Prior, trong `prior_frame` của handler (thường là base_link) -------------------------------
bool has_prior = false;

View File

@@ -943,6 +943,8 @@ bool LegPatternMatcher::evaluate(Hypothesis& h, const ScanLimits& limits,
noise.range_sigma = limits.range_sigma;
noise.angle_increment = dtheta;
noise.bright_range_bias_sigma = profile_.tape_enabled ? profile_.tape_range_bias_sigma : 0.0;
noise.bright_range_bias_all_max_std = profile_.tape_enabled && profile_.tape_legs == TapeLegs::kAll
? profile_.tape_range_bias_all_max_std : 0.0;
// Xe cùng loại vẫn lệch vài cm do gia công: một cạnh lệch tối đa `cart_dim_tolerance` đẩy mỗi
// chân lệch tối đa tolerance/2 khỏi góc của mô hình. Coi mức đó là 1σ của mô hình, để điểm tin
// không trừ điểm xe nằm trong dung sai mà vẫn trừ điểm xe lệch xa hơn.
@@ -988,6 +990,10 @@ bool LegPatternMatcher::evaluate(Hypothesis& h, const ScanLimits& limits,
break;
}
}
// Preserve the attempted all-bright uncertainty even if a later geometric gate rejects this
// hypothesis. It is diagnostic only and does not affect ranking or the legacy detection.
h.detail.tape_range_bias_std = fit.bright_range_bias_std;
h.detail.tape_range_bias_all_bright = fit.bright_range_bias_all_bright;
int seen = 0;
int partial = 0;
@@ -1204,6 +1210,8 @@ bool LegPatternMatcher::evaluate(Hypothesis& h, const ScanLimits& limits,
d.fit_iterations = fit.iterations;
d.tape_range_bias = fit.bright_range_bias;
d.tape_range_bias_estimated = fit.bright_range_bias_estimated;
d.tape_range_bias_std = fit.bright_range_bias_std;
d.tape_range_bias_all_bright = fit.bright_range_bias_all_bright;
// Đích = tâm dịch theo offset, trong hệ của chính xe: x dọc pháp tuyến cạnh vào hướng ra phía
// robot, y sang trái — cùng công thức V/arc.
@@ -1365,6 +1373,8 @@ LegDetection LegPatternMatcher::match(const robot_line_extraction::ScanGeometry&
if (h.stage == furthest)
{
detail = h.failure;
out.tape_range_bias_std = h.detail.tape_range_bias_std;
out.tape_range_bias_all_bright = h.detail.tape_range_bias_all_bright;
break;
}
}

View File

@@ -594,6 +594,51 @@ PoseFitResult fitCartPose4D(const LegModel& model, const std::vector<FitPoint>&
}
return result;
}
// Posterior covariance at the final state. Ranges from one leg share an offset, so they must not
// count as independent evidence: divide each point's Huber/variance weight by its corner's point
// count. This changes only the uncertainty gate, not the solver's weights or fitted state.
// No numerical damping: adding it here would falsely improve observability.
double biasPosteriorStd(const LegModel& model, const std::vector<FitPoint>& points,
const PoseFitResult& fit, const FitNoise& noise)
{
const Eigen::Vector4d state(fit.pose.x, fit.pose.y, fit.pose.yaw, fit.bright_range_bias);
Eigen::Matrix4d normal = Eigen::Matrix4d::Zero();
std::array<std::size_t, kLegCount> corner_counts{};
for (const FitPoint& point : points)
{
if (point.corner < 0 || point.corner >= kLegCount)
{
return std::numeric_limits<double>::infinity();
}
++corner_counts[static_cast<std::size_t>(point.corner)];
}
for (const FitPoint& point : points)
{
const PointTerm4 term = evaluateWithBias(model, point, state, noise);
const double error = std::fabs(term.r) / term.sigma;
const double huber = error <= kHuberK ? 1.0 : kHuberK / error;
const double count = static_cast<double>(corner_counts[static_cast<std::size_t>(point.corner)]);
normal += (huber / (count * term.sigma * term.sigma)) * term.jacobian * term.jacobian.transpose();
}
normal(3, 3) += 1.0 / (noise.bright_range_bias_sigma * noise.bright_range_bias_sigma);
if (!normal.allFinite())
{
return std::numeric_limits<double>::infinity();
}
Eigen::LDLT<Eigen::Matrix4d> ldlt(normal);
if (ldlt.info() != Eigen::Success || !ldlt.isPositive() ||
(ldlt.vectorD().array() <= 0.0).any())
{
return std::numeric_limits<double>::infinity();
}
const Eigen::Vector4d column = ldlt.solve(Eigen::Vector4d::Unit(3));
if (ldlt.info() != Eigen::Success || !column.allFinite() || column[3] <= 0.0)
{
return std::numeric_limits<double>::infinity();
}
return std::sqrt(column[3]);
}
} // namespace
PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& points,
@@ -624,6 +669,22 @@ PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& po
{
return fitCartPose4D(model, points, initial, noise, max_iterations);
}
if (noise.bright_range_bias_sigma > 0.0 && has_bright_corner && !has_bare_corner &&
noise.bright_range_bias_all_max_std > 0.0)
{
PoseFitResult candidate = fitCartPose4D(model, points, initial, noise, max_iterations);
const double std = candidate.valid ? biasPosteriorStd(model, points, candidate, noise)
: std::numeric_limits<double>::infinity();
if (std::isfinite(std) && std <= noise.bright_range_bias_all_max_std)
{
candidate.bright_range_bias_std = std;
candidate.bright_range_bias_all_bright = true;
return candidate;
}
PoseFitResult legacy = fitCartPose3D(model, points, initial, noise, max_iterations);
legacy.bright_range_bias_std = std;
return legacy;
}
return fitCartPose3D(model, points, initial, noise, max_iterations);
}

View File

@@ -200,6 +200,18 @@ bool LegProfile::validate(std::string& error) const
error = "tape_range_bias_sigma must be finite and in [0, 0.2] [m]";
return false;
}
if (!std::isfinite(tape_range_bias_all_max_std) || tape_range_bias_all_max_std < 0.0 ||
tape_range_bias_all_max_std > 0.1)
{
error = "tape_range_bias_all_max_std must be finite and in [0, 0.1] [m]";
return false;
}
if (tape_range_bias_all_max_std > 0.0 && (!tape_enabled || tape_range_bias_sigma <= 0.0))
{
error = "non-zero tape_range_bias_all_max_std requires tape_enabled: true and "
"tape_range_bias_sigma > 0";
return false;
}
if (!std::isfinite(tape_plateau_min_fraction) || tape_plateau_min_fraction < 0.0 ||
tape_plateau_min_fraction >= 1.0)
{

File diff suppressed because one or more lines are too long

View File

@@ -193,12 +193,14 @@ LegProfile mirrorTapeTrolley(bool enable_fixes = true,
}
LegDetection detectMirrorTape(const RecordedScan& scan, bool enable_fixes = true,
TapeLegs tape_legs = TapeLegs::kEntry, double plateau_fraction = 0.0)
TapeLegs tape_legs = TapeLegs::kEntry, double plateau_fraction = 0.0,
double all_max_std = 0.0)
{
LegPatternMatcher matcher;
std::string error;
LegProfile profile = mirrorTapeTrolley(enable_fixes, tape_legs);
profile.tape_plateau_min_fraction = plateau_fraction;
profile.tape_range_bias_all_max_std = all_max_std;
EXPECT_TRUE(matcher.configure(profile, error)) << error;
ScanLimits limits;
limits.min_range = 0.10;
@@ -478,6 +480,80 @@ TEST(LegPatternMatcherKit, RejectsFarBrightCoreCorruptedByNearMirrorBloom)
}
}
TEST(LegPatternMatcherKit, AllTapedBiasNearAndFar)
{
const auto scans = loadTapeScans("kit_f_scan_trolley_tape_all_near.txt");
ASSERT_EQ(scans.size(), 15u);
for (const auto& scan : scans)
{
const auto old = detectMirrorTape(scan, true, TapeLegs::kAll, 0.65, 0.0);
const auto corrected = detectMirrorTape(scan, true, TapeLegs::kAll, 0.65, 0.02);
if (scan.name.find("near_fail_run6_") == 0)
{
EXPECT_FALSE(old.valid) << scan.name;
EXPECT_NE(old.reason.find("two legs"), std::string::npos) << old.reason;
ASSERT_TRUE(corrected.valid) << scan.name << " " << corrected.reason;
EXPECT_TRUE(corrected.tape_range_bias_all_bright);
EXPECT_TRUE(corrected.tape_range_bias_estimated);
EXPECT_GE(corrected.tape_range_bias, 0.015);
EXPECT_LE(corrected.tape_range_bias, 0.05);
EXPECT_NEAR(corrected.measured_opening, 0.762, 0.04);
EXPECT_NEAR(corrected.measured_depth, 0.480, 0.04);
}
else if (scan.name.find("far_ok_run17_m5_") == 0)
{
ASSERT_TRUE(old.valid) << scan.name << " " << old.reason;
ASSERT_TRUE(corrected.valid) << scan.name << " " << corrected.reason;
std::cout << scan.name << ": bias std=" << corrected.tape_range_bias_std << " m"
<< " all-bright=" << corrected.tape_range_bias_all_bright << std::endl;
EXPECT_LE(std::fabs(corrected.tape_range_bias), 0.05);
if (!corrected.tape_range_bias_all_bright)
{
EXPECT_EQ(old.center_x, corrected.center_x);
EXPECT_EQ(old.center_y, corrected.center_y);
EXPECT_EQ(old.center_yaw, corrected.center_yaw);
}
else
{
const double dx = corrected.center_x - old.center_x;
const double dy = corrected.center_y - old.center_y;
EXPECT_GT(dx * old.center_x + dy * old.center_y, 0.0);
EXPECT_LE(std::hypot(dx, dy), 0.04);
}
}
else
{
ASSERT_EQ(scan.name.find("near_ok_run17_m15_"), 0u);
ASSERT_TRUE(old.valid) << old.reason;
ASSERT_TRUE(corrected.valid) << corrected.reason;
const double dx = corrected.center_x - old.center_x;
const double dy = corrected.center_y - old.center_y;
EXPECT_GT(dx * old.center_x + dy * old.center_y, 0.0);
EXPECT_GE(std::hypot(dx, dy), 0.01);
EXPECT_LE(std::hypot(dx, dy), 0.05);
}
}
}
TEST(LegPatternMatcherKit, EntryTapeUnchangedWithAllBiasEnabled)
{
const auto scans = loadTapeScans("kit_f_scan_trolley_tape.txt");
ASSERT_FALSE(scans.empty());
for (const auto& scan : scans)
{
const auto a = detectMirrorTape(scan, true, TapeLegs::kEntry, 0.65, 0.0);
const auto b = detectMirrorTape(scan, true, TapeLegs::kEntry, 0.65, 0.02);
EXPECT_EQ(a.valid, b.valid) << scan.name;
EXPECT_EQ(a.reason, b.reason);
EXPECT_EQ(a.center_x, b.center_x);
EXPECT_EQ(a.center_y, b.center_y);
EXPECT_EQ(a.center_yaw, b.center_yaw);
EXPECT_EQ(a.tape_range_bias, b.tape_range_bias);
EXPECT_EQ(a.measured_opening, b.measured_opening);
EXPECT_EQ(a.measured_depth, b.measured_depth);
}
}
TEST(LegPatternMatcherKitReplay, BagReplayComparesPlateauOnAndOff)
{
const char* files_env = std::getenv("LEG_REPLAY_FILES");
@@ -573,6 +649,139 @@ TEST(LegPatternMatcherKitReplay, BagReplayComparesPlateauOnAndOff)
ASSERT_TRUE(csv.good()) << "Could not write replay CSV: " << output_path;
}
TEST(LegPatternMatcherKitReplay, BagReplayComparesAllTapedBias)
{
const char* files_env = std::getenv("LEG_REPLAY_FILES");
if (files_env == nullptr || *files_env == '\0')
{
GTEST_SKIP() << "Set LEG_REPLAY_FILES and LEG_REPLAY_OUT_BIAS to replay recorded scans.";
}
const char* output_path = std::getenv("LEG_REPLAY_OUT_BIAS");
ASSERT_TRUE(output_path != nullptr && *output_path != '\0')
<< "LEG_REPLAY_OUT_BIAS is required when LEG_REPLAY_FILES is set";
std::ofstream csv(output_path);
ASSERT_TRUE(csv.is_open()) << "Cannot open LEG_REPLAY_OUT_BIAS: " << output_path;
csv << "label,stamp,config,valid,legs_seen,center_x,center_y,center_yaw,"
"measured_opening,measured_depth,bias_estimated,bias,bias_std,bias_all_bright,reason\n";
csv << std::fixed << std::setprecision(6);
const auto csvSafe = [](std::string text) {
for (char& c : text)
{
if (c == ',' || c == '"' || c == '\n' || c == '\r')
{
c = ' ';
}
}
return text;
};
const auto printStdPercentiles = [](const char* label, std::vector<double>& samples) {
std::cout << " " << label << " n=" << samples.size() << " std p10/p50/p90=";
if (samples.empty())
{
std::cout << "n/a";
return;
}
std::sort(samples.begin(), samples.end());
const auto percentile = [&](double fraction) {
const std::size_t rank = static_cast<std::size_t>(std::ceil(fraction * samples.size()));
return samples[std::max<std::size_t>(1, rank) - 1];
};
std::cout << percentile(0.10) << "/" << percentile(0.50) << "/" << percentile(0.90);
};
std::istringstream entries(files_env);
std::string entry;
while (std::getline(entries, entry, ','))
{
const std::size_t first = entry.find(':');
const std::size_t second = first == std::string::npos ? first : entry.find(':', first + 1);
ASSERT_TRUE(first != std::string::npos && first > 0 && second != std::string::npos &&
second + 1 < entry.size())
<< "LEG_REPLAY_FILES entry must be label:all|entry:absolute_path: " << entry;
const std::string label = entry.substr(0, first);
const std::string tape_name = entry.substr(first + 1, second - first - 1);
const std::string path = entry.substr(second + 1);
ASSERT_TRUE(tape_name == "all" || tape_name == "entry") << "Invalid tape_legs: " << tape_name;
ASSERT_EQ(path.front(), '/') << "Replay path must be absolute: " << path;
const TapeLegs tape_legs = tape_name == "all" ? TapeLegs::kAll : TapeLegs::kEntry;
std::ifstream input(path);
ASSERT_TRUE(input.is_open()) << "Cannot open replay file: " << path;
input.close();
const std::vector<RecordedScan> scans = loadTapeScans(path);
ASSERT_FALSE(scans.empty()) << "No scans loaded from " << path;
std::size_t valid_a = 0, valid_b = 0, only_b = 0, only_a = 0, changed = 0;
double max_dxy = 0.0, max_dyaw = 0.0, signed_shift_sum = 0.0;
std::size_t both = 0, valid_all_bright = 0;
std::vector<double> accepted_std, rejected_std;
for (const RecordedScan& scan : scans)
{
ASSERT_EQ(scan.ranges.size(), scan.geometry.size) << path << ": " << scan.name;
ASSERT_EQ(scan.intensities.size(), scan.geometry.size) << path << ": " << scan.name;
const std::size_t separator = scan.name.rfind('_');
ASSERT_NE(separator, std::string::npos) << "Missing timestamp in scan name: " << scan.name;
const std::string stamp_text = scan.name.substr(separator + 1);
char* stamp_end = nullptr;
const double stamp = std::strtod(stamp_text.c_str(), &stamp_end);
ASSERT_TRUE(stamp_end != stamp_text.c_str() && *stamp_end == '\0' && std::isfinite(stamp))
<< "Invalid timestamp in scan name: " << scan.name;
// detectMirrorTape configures a fresh matcher and the robot limits for each call.
const LegDetection a = detectMirrorTape(scan, true, tape_legs, 0.65, 0.0);
const LegDetection b = detectMirrorTape(scan, true, tape_legs, 0.65, 0.02);
const auto writeRow = [&](const char* config, const LegDetection& detection) {
csv << csvSafe(label) << ',' << stamp << ',' << config << ',' << detection.valid << ','
<< detection.legs_seen << ',' << detection.center_x << ',' << detection.center_y << ','
<< detection.center_yaw << ',' << detection.measured_opening << ','
<< detection.measured_depth << ',' << detection.tape_range_bias_estimated << ','
<< detection.tape_range_bias << ',' << detection.tape_range_bias_std << ','
<< detection.tape_range_bias_all_bright << ',' << csvSafe(detection.reason) << '\n';
};
writeRow("A", a);
writeRow("B", b);
valid_a += a.valid;
valid_b += b.valid;
valid_all_bright += b.valid && b.tape_range_bias_all_bright;
// The matcher exposes one selected (or furthest rejected) hypothesis per scan. A zero
// means no all-bright attempt; infinity denotes a failed covariance or invalid fit.
if (b.tape_range_bias_std > 0.0)
{
(b.tape_range_bias_all_bright ? accepted_std : rejected_std).push_back(b.tape_range_bias_std);
}
only_a += a.valid && !b.valid;
only_b += b.valid && !a.valid;
if (a.valid && b.valid)
{
++both;
const double range = std::hypot(a.center_x, a.center_y);
if (range > 0.0)
{
signed_shift_sum += ((b.center_x - a.center_x) * a.center_x +
(b.center_y - a.center_y) * a.center_y) / range;
}
const double dxy = std::hypot(a.center_x - b.center_x, a.center_y - b.center_y);
const double dyaw = yawError(a.center_yaw, b.center_yaw);
changed += dxy > 1e-9 || dyaw > 1e-9;
max_dxy = std::max(max_dxy, dxy);
max_dyaw = std::max(max_dyaw, dyaw);
}
}
std::cout << label << ": scans=" << scans.size() << " valid A=" << valid_a
<< " valid B=" << valid_b << " only B=" << only_b << " only A=" << only_a
<< " both valid with pose changed=" << changed << std::fixed << std::setprecision(12)
<< " max |dxy|=" << max_dxy << " max |dyaw|=" << max_dyaw
<< " mean signed radial shift=" << (both ? signed_shift_sum / both : 0.0)
<< " B-valid all-bright=" << valid_all_bright << "/" << valid_b
<< " (fraction=" << (valid_b ? static_cast<double>(valid_all_bright) / valid_b : 0.0)
<< ")";
printStdPercentiles("selected accepted", accepted_std);
printStdPercentiles("selected rejected", rejected_std);
std::cout << std::endl;
}
csv.flush();
ASSERT_TRUE(csv.good()) << "Could not write replay CSV: " << output_path;
}
} // namespace
int main(int argc, char** argv)

View File

@@ -173,6 +173,28 @@ LegProfile reflectiveTrolley()
// 1. Dò đúng
// ================================================================================================
TEST(LegProfile, ValidatesAllBrightBiasThreshold)
{
LegProfile p = tciTrolley();
std::string error;
EXPECT_TRUE(p.validate(error)) << error;
for (double value : {-0.001, 0.101, std::numeric_limits<double>::quiet_NaN()})
{
p.tape_range_bias_all_max_std = value;
EXPECT_FALSE(p.validate(error));
}
p.tape_range_bias_all_max_std = 0.02;
EXPECT_FALSE(p.validate(error));
p.tape_enabled = true;
EXPECT_FALSE(p.validate(error));
p.tape_range_bias_sigma = 0.05;
EXPECT_TRUE(p.validate(error)) << error;
p.tape_range_bias_all_max_std = 0.0;
p.tape_enabled = false;
p.tape_range_bias_sigma = 0.0;
EXPECT_TRUE(p.validate(error)) << error;
}
TEST(LegPatternMatcher, FindsACartFacingTheSensor)
{
const LegProfile p = tciTrolley();

View File

@@ -42,11 +42,17 @@ LegProfile tciTrolley()
/// @brief Điểm của từng chân lấy từ ray-cast, gán đúng góc theo id vật trúng.
std::vector<FitPoint> pointsOf(const LegProfile& p, double cx, double cy, double axis,
double sigma = 0.0)
double sigma = 0.0, std::size_t ray_count = 541)
{
leg_scan_sim::World world;
const std::vector<int> ids = leg_scan_sim::addCart(world, p, cx, cy, axis);
const auto g = leg_scan_sim::s300Geometry();
auto g = leg_scan_sim::s300Geometry();
if (ray_count != g.size)
{
const double angular_span = (g.size - 1) * g.angle_increment;
g.size = ray_count;
g.angle_increment = angular_span / (g.size - 1);
}
const leg_scan_sim::Scan scan = leg_scan_sim::rayCast(world, g, sigma);
std::vector<FitPoint> points;
@@ -324,6 +330,62 @@ TEST(LegPoseFit, MixedBrightAndDimPointsOnEveryCornerDoNotEstimateBias)
EXPECT_EQ(with_sigma.iterations, legacy.iterations);
}
TEST(LegPoseFit, AllBrightBiasUsesObservableGeometryAndFallsBackAtDistance)
{
LegProfile p = tciTrolley();
p.cart_opening = 0.762;
p.cart_depth = 0.480;
const LegModel model = LegModel::fromProfile(p);
for (double cx : {0.70, 2.5})
{
// Dense angular sampling keeps all four legs represented at 2.5 m.
auto points = pointsOf(p, cx, 0.03, M_PI + 0.05, 0.0, 2161);
ASSERT_GE(points.size(), 12u);
std::array<std::size_t, dock_pattern_detector::kLegCount> corner_counts{};
for (auto& point : points)
{
++corner_counts[static_cast<std::size_t>(point.corner)];
point.bright = true;
const double range = std::hypot(point.x, point.y);
point.x *= (range - 0.03) / range;
point.y *= (range - 0.03) / range;
}
for (std::size_t count : corner_counts)
{
ASSERT_GT(count, 0u) << "cart range " << cx;
}
Pose2D initial;
initial.x = cx - 0.03;
initial.y = 0.03;
initial.yaw = M_PI + 0.05;
FitNoise noise = s300Noise();
noise.bright_range_bias_sigma = 0.05;
const auto legacy = fitCartPose(model, points, initial, noise);
// Synthetic geometry, not the KIT value: per-corner std is ~0.008 at 0.70 m and ~0.018 at 2.5 m
// here, so 0.012 sits between them. The KIT threshold (0.02) comes from the bag replay instead.
noise.bright_range_bias_all_max_std = 0.012;
const auto fit = fitCartPose(model, points, initial, noise);
ASSERT_TRUE(fit.valid) << fit.reason;
if (cx < 1.0)
{
EXPECT_TRUE(fit.bright_range_bias_all_bright);
EXPECT_NEAR(fit.bright_range_bias, 0.03, 0.005);
EXPECT_LE(fit.bright_range_bias_std, noise.bright_range_bias_all_max_std);
}
else
{
EXPECT_FALSE(fit.bright_range_bias_all_bright);
EXPECT_GT(fit.bright_range_bias_std, noise.bright_range_bias_all_max_std);
EXPECT_EQ(fit.pose.x, legacy.pose.x);
EXPECT_EQ(fit.pose.y, legacy.pose.y);
EXPECT_EQ(fit.pose.yaw, legacy.pose.yaw);
EXPECT_EQ(fit.rms, legacy.rms);
EXPECT_EQ(fit.normalized_rms, legacy.normalized_rms);
EXPECT_EQ(fit.iterations, legacy.iterations);
}
}
}
TEST(LegPoseFit, IsDeterministic)
{
const LegProfile p = tciTrolley();