feat(leg_pattern): add LegPatternMatcher for 4-leg trolleys

Finds a 4-leg trolley in a raw LaserScan without line extraction:
shadow filter, leg clusters in ray order with free/occluded/attached edges,
pair hypotheses from cart_opening/cart_depth/diagonal, then a Gauss-Newton
pose fit over every leg point with an along-ray residual, Huber weights and
backtracking. Gates: pair spacing after the fit, see-through leg positions,
optional empty interior, entry side (entry tape / prior yaw / facing the
sensor), optional prior, confidence, and ambiguity between two carts.

LegProfile validates every key at load. Two gtests (7 + 23) run on a
synthetic ray-cast scan (test/leg_scan_sim.h). Used by trolley_detection_action.
This commit is contained in:
2026-10-28 13:43:56 +07:00
parent edc6b30431
commit c568e90c53
11 changed files with 3324 additions and 0 deletions

1141
src/leg_pattern_matcher.cpp Normal file

File diff suppressed because it is too large Load Diff

394
src/leg_pose_fit.cpp Normal file
View File

@@ -0,0 +1,394 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* dock_pattern_detector — khớp tư thế xe hàng 4 chân.
*
* Author: DuongTD
*********************************************************************/
#include <dock_pattern_detector/leg_pose_fit.h>
#include <algorithm>
#include <cmath>
#include <limits>
#include <vector>
#include <Eigen/Dense>
namespace dock_pattern_detector
{
namespace
{
constexpr double kStepTranslation = 1e-6; // [m] bước sai phân số cho Jacobian
constexpr double kStepRotation = 1e-6; // [rad]
constexpr double kStopTranslation = 1e-4; // [m] 0.1 mm
constexpr double kStopRotation = 1.745329e-4; // [rad] 0.01°
constexpr double kMinSigma = 1e-4; // [m] sàn σ để điểm đơn lẻ không thống trị
constexpr double kHuberK = 2.0; // Huber δ = 2σ
constexpr int kMaxHalvings = 6; // tìm bước lùi: tối đa 6 lần chia đôi
double wrapAngle(double a)
{
return std::atan2(std::sin(a), std::cos(a));
}
/**
* @brief [m] Cự ly dọc tia (từ gốc, hướng @p ux, @p uy) tới mặt chân @p corner của xe đặt ở pose
* (x, y, yaw). @return false nếu tia không cắt chân.
*/
bool rayEntry(const LegModel& model, int corner, double x, double y, double yaw, double ux,
double uy, double& t)
{
const std::array<double, 2> local = model.corner(corner);
const double c = std::cos(yaw);
const double s = std::sin(yaw);
const double cx = x + c * local[0] - s * local[1];
const double cy = y + s * local[0] + c * local[1];
if (model.shape == LegShape::kRound)
{
const double b = ux * cx + uy * cy;
const double disc = b * b - (cx * cx + cy * cy - model.leg_width * model.leg_width / 4.0);
if (disc < 0.0)
{
return false;
}
t = b - std::sqrt(disc);
return t > 0.0;
}
// Hộp: đưa tia về hệ của chân rồi cắt hai cặp mặt song song (slab).
const double phi = yaw + model.leg_yaw_offset;
const double cp = std::cos(phi);
const double sp = std::sin(phi);
const double ox = cp * (-cx) + sp * (-cy);
const double oy = -sp * (-cx) + cp * (-cy);
const double dx = cp * ux + sp * uy;
const double dy = -sp * ux + cp * uy;
const double half[2] = { model.leg_depth / 2.0, model.leg_width / 2.0 };
const double origin[2] = { ox, oy };
const double dir[2] = { dx, dy };
double t_min = -std::numeric_limits<double>::infinity();
double t_max = std::numeric_limits<double>::infinity();
for (int axis = 0; axis < 2; ++axis)
{
if (std::fabs(dir[axis]) < 1e-12)
{
if (std::fabs(origin[axis]) > half[axis])
{
return false;
}
continue;
}
const double t1 = (-half[axis] - origin[axis]) / dir[axis];
const double t2 = (half[axis] - origin[axis]) / dir[axis];
t_min = std::max(t_min, std::min(t1, t2));
t_max = std::min(t_max, std::max(t1, t2));
}
if (t_min > t_max || t_min <= 0.0)
{
return false;
}
t = t_min;
return true;
}
/**
* @brief Phần dư của một điểm với pose (x, y, yaw) của xe.
*
* Tia cắt chân dự đoán: phần dư = cự ly dự đoán dọc tia − cự ly đo. Đây đúng là chiều nhiễu của
* lidar, và nó biết mặt nào của chân quay về cảm biến. Tia trượt chân (điểm mép khi pose còn lệch):
* rơi về khoảng cách có dấu tới biên chân.
*
* Vì sao không dùng khoảng cách có dấu cho mọi điểm: nó không biết mặt nào đang được nhìn. Chân tròn
* khi đó có nghiệm "gương" — điểm nằm trên nửa SAU của đường tròn, tâm lệch về phía cảm biến cỡ một
* đường kính. Chân hộp dưới nhiễu thì điểm lọt vào trong hộp bị tính tới mặt GẦN NHẤT (thường là mặt
* bên) thay vì mặt tia đi vào, nên cả xe bị kéo về phía cảm biến vài mm có hệ thống.
*/
double residual(const LegModel& model, const FitPoint& p, double x, double y, double yaw,
bool& on_ray)
{
const double range = std::hypot(p.x, p.y);
double t = 0.0;
if (range > 1e-9 && rayEntry(model, p.corner, x, y, yaw, p.x / range, p.y / range, t))
{
on_ray = true;
return t - range;
}
on_ray = false;
const double c = std::cos(yaw);
const double s = std::sin(yaw);
const double dx = p.x - x;
const double dy = p.y - y;
return model.signedDistance(p.corner, c * dx + s * dy, -s * dx + c * dy);
}
double residual(const LegModel& model, const FitPoint& p, double x, double y, double yaw)
{
bool on_ray = false;
return residual(model, p, x, y, yaw, on_ray);
}
struct PointTerm
{
double r = 0.0; // [m] phần dư
Eigen::Vector3d jacobian; // ∂r/∂(x, y, yaw)
double sigma = kMinSigma; // [m]
};
PointTerm evaluate(const LegModel& model, const FitPoint& p, const Eigen::Vector3d& pose,
const FitNoise& noise)
{
PointTerm t;
bool on_ray = false;
t.r = residual(model, p, pose.x(), pose.y(), pose.z(), on_ray);
// Jacobian bằng sai phân trung tâm: SDF hộp không khả vi ở góc, và vài chục điểm × 3 bậc tự do
// thì sai phân rẻ hơn viết đạo hàm giải tích cho từng nhánh của SDF.
t.jacobian.x() = (residual(model, p, pose.x() + kStepTranslation, pose.y(), pose.z()) -
residual(model, p, pose.x() - kStepTranslation, pose.y(), pose.z())) /
(2.0 * kStepTranslation);
t.jacobian.y() = (residual(model, p, pose.x(), pose.y() + kStepTranslation, pose.z()) -
residual(model, p, pose.x(), pose.y() - kStepTranslation, pose.z())) /
(2.0 * kStepTranslation);
t.jacobian.z() = (residual(model, p, pose.x(), pose.y(), pose.z() + kStepRotation) -
residual(model, p, pose.x(), pose.y(), pose.z() - kStepRotation)) /
(2.0 * kStepRotation);
if (on_ray)
{
// Phần dư dọc tia: nhiễu chính là nhiễu range.
t.sigma = std::max(kMinSigma, noise.range_sigma);
return t;
}
// Tia trượt chân: phần dư là khoảng cách tới biên. Pháp tuyến biên tại điểm, trong frame scan:
// r phụ thuộc (p − t), nên ∂r/∂p = −∂r/∂t.
double nx = -t.jacobian.x();
double ny = -t.jacobian.y();
const double nn = std::hypot(nx, ny);
const double range = std::hypot(p.x, p.y);
if (nn > 1e-9 && range > 1e-9)
{
nx /= nn;
ny /= nn;
const double ux = p.x / range;
const double uy = p.y / range;
const double along = nx * ux + ny * uy; // thành phần dọc tia: nhiễu range
const double across = -nx * uy + ny * ux; // thành phần ngang tia: lượng tử góc
const double sigma_across = range * noise.angle_increment / std::sqrt(12.0);
const double var = along * along * noise.range_sigma * noise.range_sigma +
across * across * sigma_across * sigma_across;
t.sigma = std::max(kMinSigma, std::sqrt(var));
}
else
{
t.sigma = std::max(kMinSigma, noise.range_sigma);
}
return t;
}
/// @brief Tổng mất mát Huber của mọi điểm tại @p pose — thước đo để chấp nhận một bước.
double robustCost(const LegModel& model, const std::vector<FitPoint>& points,
const Eigen::Vector3d& pose, const FitNoise& noise)
{
double cost = 0.0;
for (const FitPoint& p : points)
{
const PointTerm t = evaluate(model, p, pose, noise);
const double e = std::fabs(t.r) / t.sigma;
cost += (e <= kHuberK) ? 0.5 * e * e : kHuberK * e - 0.5 * kHuberK * kHuberK;
}
return cost;
}
} // namespace
LegModel LegModel::fromProfile(const LegProfile& profile)
{
LegModel m;
m.cart_opening = profile.cart_opening;
m.cart_depth = profile.cart_depth;
m.shape = profile.leg_shape;
m.leg_width = profile.leg_width;
m.leg_depth = profile.effectiveLegDepth();
m.leg_yaw_offset = profile.leg_shape == LegShape::kBox ? profile.leg_yaw_offset : 0.0;
return m;
}
std::array<double, 2> LegModel::corner(int corner) const
{
const double hx = cart_depth / 2.0;
const double hy = cart_opening / 2.0;
switch (corner)
{
case kEntryLeft:
return { hx, hy };
case kEntryRight:
return { hx, -hy };
case kFarLeft:
return { -hx, hy };
default:
return { -hx, -hy };
}
}
double LegModel::signedDistance(int corner_id, double px, double py) const
{
const std::array<double, 2> c = corner(corner_id);
const double dx = px - c[0];
const double dy = py - c[1];
if (shape == LegShape::kRound)
{
return std::hypot(dx, dy) - leg_width / 2.0;
}
// Đưa điểm về hệ của chân (chân có thể lắp xoay so với cạnh xe), rồi SDF hình chữ nhật.
const double co = std::cos(leg_yaw_offset);
const double so = std::sin(leg_yaw_offset);
const double lx = co * dx + so * dy;
const double ly = -so * dx + co * dy;
const double qx = std::fabs(lx) - leg_depth / 2.0;
const double qy = std::fabs(ly) - leg_width / 2.0;
const double outside = std::hypot(std::max(qx, 0.0), std::max(qy, 0.0));
const double inside = std::min(std::max(qx, qy), 0.0);
return outside + inside;
}
bool procrustes2D(const std::vector<std::array<double, 2>>& model,
const std::vector<std::array<double, 2>>& scan, Pose2D& out)
{
const std::size_t n = std::min(model.size(), scan.size());
if (n < 2)
{
return false;
}
double mx = 0.0, my = 0.0, sx = 0.0, sy = 0.0;
for (std::size_t i = 0; i < n; ++i)
{
mx += model[i][0];
my += model[i][1];
sx += scan[i][0];
sy += scan[i][1];
}
mx /= static_cast<double>(n);
my /= static_cast<double>(n);
sx /= static_cast<double>(n);
sy /= static_cast<double>(n);
double dot = 0.0;
double cross = 0.0;
double spread = 0.0;
for (std::size_t i = 0; i < n; ++i)
{
const double ax = model[i][0] - mx;
const double ay = model[i][1] - my;
const double bx = scan[i][0] - sx;
const double by = scan[i][1] - sy;
dot += ax * bx + ay * by;
cross += ax * by - ay * bx;
spread += ax * ax + ay * ay;
}
if (spread < 1e-12)
{
return false;
}
const double yaw = std::atan2(cross, dot);
const double c = std::cos(yaw);
const double s = std::sin(yaw);
out.yaw = yaw;
out.x = sx - (c * mx - s * my);
out.y = sy - (s * mx + c * my);
return true;
}
PoseFitResult fitCartPose(const LegModel& model, const std::vector<FitPoint>& points,
const Pose2D& initial, const FitNoise& noise, int max_iterations)
{
PoseFitResult result;
result.pose = initial;
if (points.size() < 3)
{
return result; // 3 bậc tự do cần ít nhất 3 phần dư
}
Eigen::Vector3d pose(initial.x, initial.y, initial.yaw);
for (int iter = 0; iter < max_iterations; ++iter)
{
Eigen::Matrix3d normal = Eigen::Matrix3d::Zero();
Eigen::Vector3d rhs = Eigen::Vector3d::Zero();
for (const FitPoint& p : points)
{
const PointTerm t = evaluate(model, p, pose, noise);
const double e = std::fabs(t.r) / t.sigma;
const double huber = (e <= kHuberK) ? 1.0 : kHuberK / e;
const double w = huber / (t.sigma * t.sigma);
normal += w * t.jacobian * t.jacobian.transpose();
rhs -= w * t.jacobian * t.r;
}
// Giảm chấn rất nhỏ: chỉ để nghiệm tồn tại khi hình học suy biến (ví dụ chỉ thấy hai chân
// thẳng hàng với tia), không đủ lớn để làm chậm hội tụ ở ca thường.
normal += 1e-9 * (1.0 + normal.trace()) * Eigen::Matrix3d::Identity();
Eigen::Vector3d step = normal.ldlt().solve(rhs);
if (!step.allFinite())
{
return result;
}
// Tìm bước lùi: phần dư không trơn ở mép chân (tia vừa trượt khỏi chân đổi công thức), nên một
// bước Gauss-Newton đủ dài có thể làm tệ đi. Chỉ nhận bước làm giảm mất mát Huber; chia đôi tới
// khi giảm, hết lượt chia mà vẫn không giảm thì coi như đã ở đáy.
const double cost_now = robustCost(model, points, pose, noise);
bool accepted = false;
for (int halving = 0; halving <= kMaxHalvings; ++halving)
{
Eigen::Vector3d candidate = pose + step;
candidate.z() = wrapAngle(candidate.z());
if (robustCost(model, points, candidate, noise) < cost_now)
{
pose = candidate;
accepted = true;
break;
}
step *= 0.5;
}
result.iterations = iter + 1;
if (!accepted)
{
result.converged = true;
break;
}
if (std::hypot(step.x(), step.y()) < kStopTranslation && std::fabs(step.z()) < kStopRotation)
{
result.converged = true;
break;
}
}
double sum_r2 = 0.0;
double sum_e2 = 0.0;
for (const FitPoint& p : points)
{
const PointTerm t = evaluate(model, p, pose, noise);
sum_r2 += t.r * t.r;
sum_e2 += (t.r / t.sigma) * (t.r / t.sigma);
}
const double n = static_cast<double>(points.size());
result.rms = std::sqrt(sum_r2 / n);
result.normalized_rms = std::sqrt(sum_e2 / n);
result.pose.x = pose.x();
result.pose.y = pose.y();
result.pose.yaw = pose.z();
result.valid = pose.allFinite() && std::isfinite(result.rms);
return result;
}
} // namespace dock_pattern_detector

237
src/leg_profile.cpp Normal file
View File

@@ -0,0 +1,237 @@
/*********************************************************************
*
* Software License Agreement (BSD License)
*
* dock_pattern_detector — kiểm miền của LegProfile.
*
* Author: DuongTD
*********************************************************************/
#include <dock_pattern_detector/leg_profile.h>
#include <cmath>
#include <string>
namespace dock_pattern_detector
{
namespace
{
bool positiveFinite(double value)
{
return std::isfinite(value) && value > 0.0;
}
} // namespace
const char* toString(LegShape shape)
{
switch (shape)
{
case LegShape::kBox:
return "box";
case LegShape::kRound:
return "round";
}
return "unknown";
}
bool legShapeFromString(const std::string& name, LegShape& out, std::string& error)
{
if (name == "box")
{
out = LegShape::kBox;
return true;
}
if (name == "round")
{
out = LegShape::kRound;
return true;
}
error = "unknown leg_shape '" + name + "'; known values are: box, round";
return false;
}
const char* toString(TapeLegs legs)
{
switch (legs)
{
case TapeLegs::kAll:
return "all";
case TapeLegs::kEntry:
return "entry";
}
return "unknown";
}
bool tapeLegsFromString(const std::string& name, TapeLegs& out, std::string& error)
{
if (name == "all")
{
out = TapeLegs::kAll;
return true;
}
if (name == "entry")
{
out = TapeLegs::kEntry;
return true;
}
error = "unknown tape_legs '" + name + "'; known values are: all, entry";
return false;
}
bool LegProfile::validate(std::string& error) const
{
if (!positiveFinite(cart_opening) || !positiveFinite(cart_depth))
{
error = "cart_opening and cart_depth must be finite and > 0 [m] (both are required)";
return false;
}
if (!positiveFinite(leg_width))
{
error = "leg_width must be finite and > 0 [m] (it is required)";
return false;
}
if (cart_opening <= leg_width + 0.2)
{
// Khe lọt giữa hai chân cạnh vào dưới 0.2 m: không robot nào chui được. Gần như chắc là khai
// nhầm đơn vị (mm thay vì m) hoặc nhầm hai khoá.
error = "cart_opening must exceed leg_width + 0.2 m; nothing fits through a narrower opening "
"(wrong unit?)";
return false;
}
if (!std::isfinite(cart_dim_tolerance) || cart_dim_tolerance <= 0.0 ||
cart_dim_tolerance >= std::min(cart_opening, cart_depth) / 4.0)
{
error = "cart_dim_tolerance must be > 0 and < min(cart_opening, cart_depth)/4 [m]";
return false;
}
if (!std::isfinite(leg_width_tolerance) || leg_width_tolerance < 0.0)
{
error = "leg_width_tolerance must be finite and >= 0 [m]";
return false;
}
if (!std::isfinite(leg_depth) || leg_depth < 0.0)
{
error = "leg_depth must be finite and >= 0 [m] (0 = same as leg_width)";
return false;
}
if (!std::isfinite(leg_yaw_offset))
{
error = "leg_yaw_offset must be finite [rad]";
return false;
}
if (leg_shape == LegShape::kRound && (leg_depth > 0.0 || leg_yaw_offset != 0.0))
{
// Nói thẳng thay vì nhận rồi lờ đi: chân tròn không có bề dày riêng hay góc xoay.
error = "leg_depth and leg_yaw_offset only apply to leg_shape 'box'";
return false;
}
if (min_leg_points < 1)
{
error = "min_leg_points must be >= 1";
return false;
}
if (!std::isfinite(shadow_min_angle) || shadow_min_angle < 0.0 ||
shadow_min_angle >= M_PI / 2.0)
{
error = "shadow_min_angle must be in [0, pi/2) [rad] (0 disables the shadow filter)";
return false;
}
if (!positiveFinite(leg_cluster_gap))
{
error = "leg_cluster_gap must be finite and > 0 [m]";
return false;
}
if (!positiveFinite(leg_min_depth_gap))
{
error = "leg_min_depth_gap must be finite and > 0 [m]";
return false;
}
if (min_legs < 2 || min_legs > 4)
{
error = "min_legs must be 2, 3 or 4";
return false;
}
if (min_legs == 2 && !has_prior)
{
// Hai chân có thể là cạnh vào, cạnh dọc hoặc đường chéo, mỗi loại hai phía. Không có prior thì
// không có gì chọn giữa các khả năng đó.
error = "min_legs 2 requires has_prior: two legs alone fit several cart poses";
return false;
}
if (!positiveFinite(leg_assoc_radius))
{
error = "leg_assoc_radius must be finite and > 0 [m]";
return false;
}
if (!std::isfinite(interior_margin) || interior_margin < 0.0 ||
2.0 * interior_margin >= std::min(cart_opening, cart_depth))
{
error = "interior_margin must be >= 0 and leave a non-empty interior [m]";
return false;
}
if (!std::isfinite(ambiguity_margin) || ambiguity_margin < 0.0 || ambiguity_margin >= 1.0)
{
error = "ambiguity_margin must be in [0, 1)";
return false;
}
if (!std::isfinite(min_confidence) || min_confidence < 0.0 || min_confidence > 1.0)
{
error = "min_confidence must be in [0, 1]";
return false;
}
if (tape_legs == TapeLegs::kEntry && !tape_enabled)
{
error = "tape_legs 'entry' requires tape_enabled: true (forgot to turn the tape on?)";
return false;
}
if (tape_enabled && (!std::isfinite(tape_min_intensity) || tape_min_points < 1))
{
error = "tape_min_intensity must be finite and tape_min_points >= 1";
return false;
}
if (std::fabs(cart_opening - cart_depth) < 2.0 * cart_dim_tolerance)
{
// Xe gần vuông: hình học không biết cạnh nào là cạnh vào. Dò ra cạnh bên là robot chui ngang
// vào chân xe — phải có thứ khác chọn hộ.
const bool yaw_prior = has_prior && prior_yaw_tolerance < M_PI / 4.0;
const bool entry_tape = tape_enabled && tape_legs == TapeLegs::kEntry;
if (!yaw_prior && !entry_tape)
{
error = "cart_opening and cart_depth differ by less than 2*cart_dim_tolerance, so the entry "
"side is ambiguous by 90 deg; set has_prior with prior_yaw_tolerance < pi/4, or "
"tape_legs: entry";
return false;
}
}
if (has_prior)
{
if (!std::isfinite(prior_x) || !std::isfinite(prior_y) || !std::isfinite(prior_yaw))
{
error = "prior_x, prior_y and prior_yaw must be finite";
return false;
}
if (!positiveFinite(search_radius))
{
error = "search_radius must be finite and > 0 [m] when has_prior is true";
return false;
}
if (!std::isfinite(prior_yaw_tolerance) || prior_yaw_tolerance <= 0.0 ||
prior_yaw_tolerance > M_PI)
{
error = "prior_yaw_tolerance must be in (0, pi] [rad]";
return false;
}
}
if (!std::isfinite(search_fov))
{
error = "search_fov must be finite [rad] (<= 0 disables the fan)";
return false;
}
if (!std::isfinite(offset_x) || !std::isfinite(offset_y) || !std::isfinite(offset_yaw))
{
error = "offset_x, offset_y and offset_yaw must be finite";
return false;
}
return true;
}
} // namespace dock_pattern_detector