This commit is contained in:
trung09122002
2026-09-29 10:00:22 +07:00
parent 7258f15ab5
commit ca3b7854ea
7 changed files with 1355 additions and 0 deletions

View File

@@ -38,6 +38,7 @@ vslam_add_library(vslam_slam
sensor_data_builder.h
occupancy_export.h
voxel_export.h
global_localizer.h
FIND_DEPS
vslam_common
RTABMap

View File

@@ -0,0 +1,190 @@
#ifndef VSLAM_GLOBAL_LOCALIZER_H
#define VSLAM_GLOBAL_LOCALIZER_H
// Dinh vi TOAN CUC bang khop scan LiDAR voi luoi chiem dung -- port tu
// vSLAM_ws/src/localization_ops/scripts/global_scan_init.py (ban ROS).
//
// ============ BAI TOAN ============
// Tha robot xuong mot cho bat ky tren ban do da quet, KHONG cho biet dang o
// dau. Robot xoay tai cho gom scan. Phai suy ra pose trong ban do -- roi dua
// cho RTAB-Map lam pose ban dau (no chi bat duoc khi lech < ~0.3 m / 5 do, xem
// docs/SLAM.md).
//
// ============ VI SAO KHOP SCAN, KHONG TUI TU ============
// Ban ROS do tren hospital: 194 lan tui tu de xuat, 186 lan co DUNG 0 inlier
// (D410 chi co anh IR, hanh lang giong nhau). Khop scan tinh diem MOI gia
// thuyet (x, y, theta) cung luc nen SO SANH duoc cac ung vien -- hai hanh lang
// giong nhau cho hai diem gan bang nhau -> biet la nhap nhang va IM LANG thay
// vi chon bua.
//
// ============ ⚠️ DA DO BEN ROS, KHONG DUOC QUEN ============
// - Xac minh bang depth QUANH mot gia thuyet (GICP) bi bac: pose SAI 22.4 m
// duoc cham TOT hon pose dung. Xac minh cuc bo khong bat duoc nham lan
// toan cuc.
// - Tren phan cung that da CHOT SAI mot lan (22.5 m, lat 180 do) du qua ca
// hai cong ty le. Ty le mot lan khop KHONG tach duoc dung/sai o dai
// 1.31-1.39 -> moi co cong nhieu vong (`min_ratio_fast`, `min_cycles`).
//
// Module nay KHONG goi RTAB-Map, khong co luong, khong doc dong ho: chi la
// ham thuan tren (luoi, diem). Viec gom scan khi xoay va dat pose ban dau la
// cua ben goi.
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
#include "vslam/vslam_common.h"
namespace vslam {
// So lay NGUYEN tu ban ROS (global_scan_init.py). Doi so nao thi ghi ly do va
// so do o ben canh -- ban ROS da hai lan rut ket luan tu 2 mau roi mau thu
// ba lat nguoc.
struct GlobalLocalizerConfig {
// Do rong truong likelihood exp(-d^2 / 2 sigma^2). 0.15 m ~ 3 o luoi 0.05:
// chiu duoc sai so luoi ma khong lam nhoe het dac trung.
double sigma = 0.15;
// = Grid/RangeMax: ban do chi dung tu tia <= 12 m. Dung tia xa hon la khop
// vao vung chua tung ghi.
double max_range = 12.0;
// --- Tim tho ---
double coarse_res = 0.80; // m
double angle_step_deg = 5.0;
int top_k = 24; // dinh tho xet de gom ung vien
int max_candidates = 8; // ung vien (da khu trung) dem tinh chinh
size_t max_points = 1500; // sau khi gop diem ve o luoi
// --- Doi thu ---
// Doi thu VI TRI phai cach nguoi thang it nhat ngan nay.
double reject_radius = 2.0;
// Doi thu HUONG: CUNG cho (trong reject_radius) nhung lech it nhat ngan nay.
// Ban ROS do: dam may 360 do doi xung quay -> vi tri dung, huong sai 40-160
// do ma ty le vi tri van 1.6.
double min_angle_sep_deg = 25.0;
// --- Cong ---
double min_ratio = 1.30; // s1 / s2 (vi tri)
double min_ratio_yaw = 1.30; // s1 / s2_yaw (huong)
// Tren nguong nay chot ngay. Duoi thi phai dung dau `min_cycles` vong lien
// tiep. Ban ROS: 7 ca DUNG 1.315-1.581, 3 ca SAI 1.31-1.39.
double min_ratio_fast = 1.60;
int min_cycles = 2;
double assoc_radius = 0.8; // m, ghep gia thuyet giua hai vong
// Chi tinh mot vong vao streak khi robot DA DI it nhat ngan nay: ban sao doi
// xung 180 do cung lap lai y het khi dung yen.
double acc_min_move = 0.20;
double acc_timeout = 120.0; // s
// --- Canh "da lac" ---
double lost_score_ratio = 0.55; // diem tut duoi ty le nay so voi luc khop
double lost_hold = 3.0; // s, phai tut lien tuc ngan nay
};
// Truong likelihood tren luoi chiem dung. Dung chung cho khop toan cuc VA cho
// canh "da lac" -- cung mot thang do.
class LikelihoodField {
public:
// o >= 50 la tuong, o == 0 la trong (robot chi co the dung o day), -1 chua
// biet. Khoang cach bang EDT chinh xac (Felzenszwalb-Huttenlocher).
static LikelihoodField FromGrid(const OccupancyGrid& g, double sigma);
bool empty() const { return width_ == 0 || height_ == 0; }
int width() const { return width_; }
int height() const { return height_; }
double resolution() const { return res_; }
double origin_x() const { return ox_; }
double origin_y() const { return oy_; }
// Gia tri tai o (r, c); 0 ngoai luoi.
float At(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return 0.0f;
return lf_[static_cast<size_t>(r) * width_ + c];
}
bool Free(int r, int c) const {
if (r < 0 || c < 0 || r >= height_ || c >= width_) return false;
return free_[static_cast<size_t>(r) * width_ + c] != 0;
}
// Diem TRUNG BINH moi diem (frame map). Diem ngoai luoi khong tinh; tra -1
// neu it hon `min_points` diem roi vao luoi.
double MeanScore(const std::vector<Point>& pts_map, size_t min_points = 50) const;
private:
int width_ = 0, height_ = 0;
double res_ = 0.05, ox_ = 0.0, oy_ = 0.0;
std::vector<float> lf_;
std::vector<uint8_t> free_;
};
struct RelocHypothesis {
Pose2D map_from_odom; // T_map_odom
double score = 0.0; // diem sau tinh chinh
};
struct RelocMatch {
bool ok = false;
Pose2D map_from_odom; // nguoi thang
double s1 = 0.0; // diem nguoi thang
double s2 = 0.0; // doi thu VI TRI tot nhat (> reject_radius)
double s2_yaw = 0.0; // doi thu HUONG tot nhat (cung cho)
size_t points = 0; // so diem da dung sau khi gop
std::vector<RelocHypothesis> hyps; // da tinh chinh, [0] = nguoi thang
double ratio() const { return s1 / (s2 > 1e-9 ? s2 : 1e-9); }
double ratio_yaw() const { return s1 / (s2_yaw > 1e-9 ? s2_yaw : 1e-9); }
};
// Gop diem ve o luoi `res` roi rut con toi `max_points` (giu thu tu).
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points);
// Khop TOAN CUC. `pts_odom`: diem da gom trong frame ODOM (co dinh trong luc
// xoay), da cat theo max_range. Tra ok=false neu khong co dinh nao > 0.
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg);
// Tich luy gia thuyet qua nhieu vong, truyen bang ODOM (pose toan cuc chua
// biet). "Streak" = so vong LIEN TIEP mot gia thuyet dung dau.
class HypothesisTracker {
public:
explicit HypothesisTracker(const GlobalLocalizerConfig& cfg) : cfg_(cfg) {}
// `odom_now`: pose odom->base luc vong nay ket thuc. `now_s`: giay, don dieu.
void Add(const RelocMatch& m, const Pose2D& odom_now, double now_s);
// Streak cua gia thuyet gan `map_from_odom` nhat (trong assoc_radius).
int Streak(const Pose2D& map_from_odom) const;
size_t size() const { return acc_.size(); }
void Clear() { acc_.clear(); have_odom_ = false; }
private:
struct Entry {
Pose2D map_from_odom;
int streak = 0;
double t_last = 0.0;
};
GlobalLocalizerConfig cfg_;
std::vector<Entry> acc_;
Pose2D odom_mark_; // odom luc streak duoc cong lan cuoi
Pose2D last_odom_; // odom luc Add() gan nhat -- de so vi tri
bool have_odom_ = false;
double t_prev_ = 0.0;
};
enum class RelocVerdict {
kAccept, // qua het cong -> dat pose ban dau
kNeedCycles, // ty le o dai bien, chua du so vong lien tiep
kAmbiguous, // ty le vi tri < min_ratio (hanh lang lap)
kAmbiguousYaw, // vi tri co the dung, HUONG khong tin duoc
kFailed, // khong khop duoc gi
};
const char* RelocVerdictName(RelocVerdict v);
// Thu tu cong nhu ban ROS: huong truoc, roi vi tri, roi dai bien + streak.
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg);
} // namespace vslam
#endif // VSLAM_GLOBAL_LOCALIZER_H

View File

@@ -0,0 +1,510 @@
#include "vslam/global_localizer.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <unordered_set>
#include "vslam/geometry.h"
namespace vslam {
namespace {
constexpr double kDegToRad = M_PI / 180.0;
// EDT 1D (Felzenszwalb-Huttenlocher): d[i] = min_j (f[j] + (i-j)^2).
// Phan tu f = inf (khong co tuong) KHONG BAO GIO nam tren duong bao duoi, nen
// bo qua han -- de nguyen trong cong thuc giao diem thi ra inf - inf = NaN.
void Edt1d(const std::vector<float>& f, std::vector<float>* d,
std::vector<int>* v, std::vector<double>* z) {
const int n = static_cast<int>(f.size());
const float inf = std::numeric_limits<float>::infinity();
int k = -1;
for (int q = 0; q < n; ++q) {
if (f[q] == inf) continue;
if (k < 0) {
k = 0;
(*v)[0] = q;
(*z)[0] = -std::numeric_limits<double>::infinity();
(*z)[1] = std::numeric_limits<double>::infinity();
continue;
}
double s;
while (true) {
const int p = (*v)[k];
s = ((f[q] + static_cast<double>(q) * q) - (f[p] + static_cast<double>(p) * p)) /
(2.0 * (q - p));
// z[0] = -inf nen k khong bao gio xuong duoi 0.
if (s <= (*z)[k]) { --k; continue; }
break;
}
++k;
(*v)[k] = q;
(*z)[k] = s;
(*z)[k + 1] = std::numeric_limits<double>::infinity();
}
if (k < 0) { // ca hang/cot khong co tuong
for (int q = 0; q < n; ++q) (*d)[q] = inf;
return;
}
k = 0;
for (int q = 0; q < n; ++q) {
while ((*z)[k + 1] < q) ++k;
const int p = (*v)[k];
(*d)[q] = static_cast<float>((q - p) * static_cast<double>(q - p) + f[p]);
}
}
struct Refined {
double score = -1.0;
double x = 0.0, y = 0.0, th = 0.0; // (x, y) tuong doi goc luoi, met
};
// Mot luot luoi (x, y, theta) quanh (x0, y0, th0): x, y trong +-n_xy buoc
// dxy, theta trong +-n_a buoc da. Tinh truc tiep, khong FFT.
Refined SearchGrid(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, int n_xy, double dxy,
int n_a, double da) {
const double res = f.resolution();
Refined best;
std::vector<double> qx(P.size()), qy(P.size());
for (int ia = -n_a; ia <= n_a; ++ia) {
const double th = th0 + ia * da;
const double ct = std::cos(th), st = std::sin(th);
for (size_t i = 0; i < P.size(); ++i) {
qx[i] = ct * P[i].x - st * P[i].y;
qy[i] = st * P[i].x + ct * P[i].y;
}
for (int ix = -n_xy; ix <= n_xy; ++ix) {
const double x = x0 + ix * dxy;
for (int iy = -n_xy; iy <= n_xy; ++iy) {
const double y = y0 + iy * dxy;
double s = 0.0;
for (size_t i = 0; i < P.size(); ++i) {
const int c = static_cast<int>(std::lround((qx[i] + x) / res));
const int r = static_cast<int>(std::lround((qy[i] + y) / res));
s += f.At(r, c);
}
if (s > best.score) best = Refined{s, x, y, th};
}
}
}
return best;
}
// Tinh chinh mot ung vien o do phan giai ban do.
Refined Refine(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, double rc,
const GlobalLocalizerConfig& cfg) {
const double res = f.resolution();
const double step = cfg.angle_step_deg * kDegToRad;
// Luot 1 = ban ROS: +-nua o tho buoc 2*res, +-mot buoc goc buoc (buoc / 5).
const int n_xy = std::max(1, static_cast<int>(std::lround((rc / 2.0) / (2.0 * res))));
const Refined r1 = SearchGrid(f, P, x0, y0, th0, n_xy, 2.0 * res, 5, step / 5.0);
if (r1.score < 0.0) return r1;
// [vslam] Luot 2 min hon: +-0.1 m buoc res/2, +-(buoc / 5) buoc (buoc / 25).
// Lech 1.5 do o 7 m la 0.19 m ~ 1.3 sigma -- keo diem pose DUNG xuong va lam
// ty le kem tach bach (test tong hop 2026-09-29: sai 1.57 do). Ap cho MOI
// ung vien -- ca doi thu -- de so diem cong bang.
return SearchGrid(f, P, r1.x, r1.y, r1.th, 4, res / 2.0, 5, step / 25.0);
}
} // namespace
// ---------------------------------------------------------------------------
// LikelihoodField
// ---------------------------------------------------------------------------
LikelihoodField LikelihoodField::FromGrid(const OccupancyGrid& g, double sigma) {
LikelihoodField out;
out.width_ = static_cast<int>(g.width);
out.height_ = static_cast<int>(g.height);
out.res_ = g.resolution;
out.ox_ = g.origin.position.x;
out.oy_ = g.origin.position.y;
const size_t n = static_cast<size_t>(out.width_) * out.height_;
out.lf_.assign(n, 0.0f);
out.free_.assign(n, 0);
if (n == 0 || g.data.size() != n) return out;
const float inf = std::numeric_limits<float>::infinity();
std::vector<float> d2(n, inf);
bool any_occ = false;
for (size_t i = 0; i < n; ++i) {
if (g.data[i] >= 50) { d2[i] = 0.0f; any_occ = true; }
out.free_[i] = (g.data[i] == 0) ? 1 : 0;
}
if (!any_occ) return out;
// EDT tach duoc: cot roi hang, don vi o^2.
const int W = out.width_, H = out.height_;
const int m = std::max(W, H);
std::vector<float> f(m), d(m);
std::vector<double> z(m + 1);
std::vector<int> v(m);
for (int c = 0; c < W; ++c) {
f.resize(H); d.resize(H);
for (int r = 0; r < H; ++r) f[r] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int r = 0; r < H; ++r) d2[static_cast<size_t>(r) * W + c] = d[r];
}
for (int r = 0; r < H; ++r) {
f.resize(W); d.resize(W);
for (int c = 0; c < W; ++c) f[c] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int c = 0; c < W; ++c) d2[static_cast<size_t>(r) * W + c] = d[c];
}
const double k = (out.res_ * out.res_) / (2.0 * sigma * sigma);
for (size_t i = 0; i < n; ++i) {
out.lf_[i] = static_cast<float>(std::exp(-d2[i] * k));
}
return out;
}
double LikelihoodField::MeanScore(const std::vector<Point>& pts_map,
size_t min_points) const {
double s = 0.0;
size_t cnt = 0;
for (const Point& p : pts_map) {
const int c = static_cast<int>(std::lround((p.x - ox_) / res_));
const int r = static_cast<int>(std::lround((p.y - oy_) / res_));
if (r < 0 || c < 0 || r >= height_ || c >= width_) continue;
s += lf_[static_cast<size_t>(r) * width_ + c];
++cnt;
}
if (cnt < min_points || cnt == 0) return -1.0;
return s / static_cast<double>(cnt);
}
// ---------------------------------------------------------------------------
// Khop toan cuc
// ---------------------------------------------------------------------------
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points) {
// Nhieu tia roi vao mot o thi khong them thong tin, chi lam cham.
std::vector<Point> out;
out.reserve(pts.size());
std::unordered_set<uint64_t> seen;
seen.reserve(pts.size() * 2);
for (const Point& p : pts) {
const int64_t kx = static_cast<int64_t>(std::llround(p.x / res));
const int64_t ky = static_cast<int64_t>(std::llround(p.y / res));
const uint64_t key = (static_cast<uint64_t>(kx) << 32) ^
static_cast<uint32_t>(ky);
if (seen.insert(key).second) out.push_back(p);
}
if (max_points > 0 && out.size() > max_points) {
const size_t step = (out.size() + max_points - 1) / max_points;
std::vector<Point> thin;
thin.reserve(out.size() / step + 1);
for (size_t i = 0; i < out.size(); i += step) thin.push_back(out[i]);
out.swap(thin);
}
return out;
}
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg) {
RelocMatch out;
if (field.empty() || pts_odom.empty()) return out;
const double res = field.resolution();
const std::vector<Point> pts = DownsamplePoints(pts_odom, res, cfg.max_points);
out.points = pts.size();
if (pts.empty()) return out;
// --- Luoi tho: max-pool k x k ---
// Phai la MAX chu khong phai trung binh: muc tho de SANG LOC, bo sot mot
// dinh that o day thi khong con co hoi tinh chinh no nua.
const int k = std::max(1, static_cast<int>(std::lround(cfg.coarse_res / res)));
const double rc = res * k;
const int W = field.width(), H = field.height();
const int Wc = (W + k - 1) / k, Hc = (H + k - 1) / k;
std::vector<float> Lc(static_cast<size_t>(Wc) * Hc, 0.0f);
std::vector<uint8_t> Fc(static_cast<size_t>(Wc) * Hc, 0);
for (int r = 0; r < H; ++r) {
for (int c = 0; c < W; ++c) {
const size_t ci = static_cast<size_t>(r / k) * Wc + (c / k);
Lc[ci] = std::max(Lc[ci], field.At(r, c));
if (field.Free(r, c)) Fc[ci] = 1;
}
}
// Tam cua khoi tho (r, c), met tuong doi goc luoi. O min i co tam i*res.
auto block_center = [&](int b) { return (b * k + (k - 1) / 2.0) * res; };
// Xoay quanh TAM dam diem cho on dinh so hoc.
Point cen;
for (const Point& p : pts) { cen.x += p.x; cen.y += p.y; }
cen.x /= static_cast<double>(pts.size());
cen.y /= static_cast<double>(pts.size());
std::vector<Point> P(pts.size());
double maxn = 0.0;
for (size_t i = 0; i < pts.size(); ++i) {
P[i].x = pts[i].x - cen.x;
P[i].y = pts[i].y - cen.y;
maxn = std::max(maxn, std::hypot(P[i].x, P[i].y));
}
// --- Quet tho: MOI goc x MOI o trong ---
// Ban ROS dung FFT; o day cong truc tiep tren cac do lech DA GOP (histogram
// do lech o tho) -- cung ket qua (khong cuon vong), khong can FFT.
const double step = cfg.angle_step_deg * kDegToRad;
const int n_ang = std::max(1, static_cast<int>(std::lround(2.0 * M_PI / step)));
const int R = static_cast<int>(std::ceil(maxn / rc)) + 1;
const int HW = 2 * R + 1;
struct Off { int dr, dc; float n; };
struct AnglePeak { double score; int r, c; double th; };
std::vector<std::vector<float>> scores(n_ang);
std::vector<AnglePeak> peaks;
peaks.reserve(n_ang);
std::vector<float> hist(static_cast<size_t>(HW) * HW);
std::vector<Off> offs;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
const double ct = std::cos(th), st = std::sin(th);
std::fill(hist.begin(), hist.end(), 0.0f);
for (const Point& p : P) {
const int dc = static_cast<int>(std::lround((ct * p.x - st * p.y) / rc));
const int dr = static_cast<int>(std::lround((st * p.x + ct * p.y) / rc));
hist[static_cast<size_t>(dr + R) * HW + (dc + R)] += 1.0f;
}
offs.clear();
for (int dr = -R; dr <= R; ++dr) {
for (int dc = -R; dc <= R; ++dc) {
const float n = hist[static_cast<size_t>(dr + R) * HW + (dc + R)];
if (n > 0.0f) offs.push_back({dr, dc, n});
}
}
std::vector<float>& sc = scores[ia];
sc.assign(static_cast<size_t>(Wc) * Hc, 0.0f);
AnglePeak pk{-1.0, 0, 0, th};
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
// Robot phai dung trong vung TRONG.
if (!Fc[static_cast<size_t>(r) * Wc + c]) continue;
double s = 0.0;
for (const Off& o : offs) {
const int rr = r + o.dr, cc = c + o.dc;
if (rr < 0 || cc < 0 || rr >= Hc || cc >= Wc) continue;
s += o.n * Lc[static_cast<size_t>(rr) * Wc + cc];
}
sc[static_cast<size_t>(r) * Wc + c] = static_cast<float>(s);
if (s > pk.score) pk = AnglePeak{s, r, c, th};
}
}
peaks.push_back(pk);
}
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
if (peaks.empty() || peaks[0].score <= 0.0) return out;
// --- Gom TOP-K dinh tho, khu trung trong reject_radius ---
// Xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool nen rat
// rong rai, thu tu o day chua chac dung.
const double rad_c = cfg.reject_radius / rc;
std::vector<AnglePeak> cand;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(peaks.size())); ++i) {
const AnglePeak& p = peaks[i];
bool dup = false;
for (const AnglePeak& q : cand) {
const double dr = p.r - q.r, dc = p.c - q.c;
if (dr * dr + dc * dc <= rad_c * rad_c) { dup = true; break; }
}
if (!dup) cand.push_back(p);
if (static_cast<int>(cand.size()) >= cfg.max_candidates) break;
}
// ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. So o muc tho (co
// max-pool) thi gan nhu moi cho canh tuong deu diem cao -- ban ROS do duoc
// tot/xau chi cach nhau 1.18 lan, cong chan loai ca ca DUNG.
std::vector<Refined> refined;
for (const AnglePeak& p : cand) {
const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg);
if (rf.score >= 0.0) refined.push_back(rf);
}
if (refined.empty()) return out;
std::sort(refined.begin(), refined.end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
const Refined& best = refined[0];
// --- Doi thu VI TRI ---
// ⚠️ Phai LUON tim duoc, ke ca ngoai top-K. Ban ROS: tren ban do nho ca 8
// ung vien nam gon trong 2 m cua nhau -> s2 = 0 -> ty le len vo cuc va node
// chot bua (9.3% duong tinh gia, sai 9-13 m). Nen quet lai diem THO o vung xa.
double s2 = 0.0;
for (size_t i = 1; i < refined.size(); ++i) {
if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius) {
s2 = std::max(s2, refined[i].score);
}
}
const int rw = static_cast<int>(std::lround(best.y / res)) / k;
const int cw = static_cast<int>(std::lround(best.x / res)) / k;
auto is_far = [&](int r, int c) {
const double dr = r - rw, dc = c - cw;
return dr * dr + dc * dc > rad_c * rad_c;
};
{
double fv = -1.0;
int fr = -1, fc = -1;
double fth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > fv && is_far(r, c)) { fv = v; fr = r; fc = c; fth = ia * step; }
}
}
}
if (fr >= 0 && fv > 0.0) {
const Refined alt = Refine(field, P, block_center(fc), block_center(fr), fth, rc, cfg);
s2 = std::max(s2, alt.score);
}
}
// --- Doi thu HUONG: CUNG cho, KHAC huong ---
double s2_yaw = 0.0;
{
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
double gv = -1.0;
int gr = -1, gc = -1;
double gth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
if (std::fabs(AngleDiff(th, best.th)) < min_sep) continue;
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > gv && !is_far(r, c)) { gv = v; gr = r; gc = c; gth = th; }
}
}
}
if (gr >= 0 && gv > 0.0) {
s2_yaw = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg).score;
}
}
// (x, y, th) dat TAM dam diem vao cho nao tren luoi. Doi sang T_map_odom:
// p_map = R(th) * p_odom + t, t = (x, y) + goc_luoi - R(th) * tam
auto to_map = [&](const Refined& rf) {
const double ct = std::cos(rf.th), st = std::sin(rf.th);
return Pose2D{rf.x + field.origin_x() - (ct * cen.x - st * cen.y),
rf.y + field.origin_y() - (st * cen.x + ct * cen.y),
NormalizeAngle(rf.th)};
};
for (const Refined& rf : refined) out.hyps.push_back({to_map(rf), rf.score});
out.map_from_odom = out.hyps[0].map_from_odom;
out.s1 = best.score;
out.s2 = s2;
out.s2_yaw = s2_yaw;
out.ok = true;
return out;
}
// ---------------------------------------------------------------------------
// Tich luy qua nhieu vong
// ---------------------------------------------------------------------------
//
// Luu T_map_odom chu khong luu pose robot: T_map_odom KHONG doi khi robot di
// (frame odom co dinh), nen khong phai truyen tung gia thuyet theo delta odom
// nhu ban ROS -- chi can ghep voi odom HIEN TAI khi so sanh vi tri.
//
// ⚠️ Khac ban ROS mot cho, co chu y: ban ROS dat lai moc odom MOI vong, ke ca
// vong chua du `acc_min_move` -- nen di cham (moi vong < 0.2 m) thi KHONG bao
// gio cong duoc streak. O day moc chi dat lai khi DA cong: quang duong duoc
// cong don cho toi khi du.
void HypothesisTracker::Add(const RelocMatch& m, const Pose2D& odom_now, double now_s) {
if (!m.ok || m.hyps.empty()) return;
if (!acc_.empty() && now_s - t_prev_ > cfg_.acc_timeout) acc_.clear();
t_prev_ = now_s;
last_odom_ = odom_now;
if (acc_.empty() || !have_odom_) {
acc_.clear();
for (size_t i = 0; i < m.hyps.size(); ++i) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
}
odom_mark_ = odom_now;
have_odom_ = true;
return;
}
// Cung cho -> streak KHONG duoc cong: ban sao doi xung cung lap lai y het.
if (std::hypot(odom_now.x - odom_mark_.x, odom_now.y - odom_mark_.y) < cfg_.acc_min_move) {
for (Entry& e : acc_) e.t_last = now_s;
return;
}
odom_mark_ = odom_now;
const double r2 = cfg_.assoc_radius * cfg_.assoc_radius;
for (size_t i = 0; i < m.hyps.size(); ++i) {
const Pose2D ph = Pose2DCompose(m.hyps[i].map_from_odom, odom_now);
Entry* hit = nullptr;
double bd = r2;
for (Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, odom_now);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; hit = &e; }
}
if (hit == nullptr) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
continue;
}
hit->map_from_odom = m.hyps[i].map_from_odom; // bam theo do do moi nhat
hit->t_last = now_s;
hit->streak = (i == 0) ? hit->streak + 1 : 0;
}
// Bo gia thuyet khong xuat hien lai o vong nay.
acc_.erase(std::remove_if(acc_.begin(), acc_.end(),
[&](const Entry& e) { return e.t_last < now_s; }),
acc_.end());
}
int HypothesisTracker::Streak(const Pose2D& map_from_odom) const {
const Pose2D ph = Pose2DCompose(map_from_odom, last_odom_);
int best = 0;
double bd = cfg_.assoc_radius * cfg_.assoc_radius;
for (const Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, last_odom_);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; best = e.streak; }
}
return best;
}
// ---------------------------------------------------------------------------
// Cong
// ---------------------------------------------------------------------------
const char* RelocVerdictName(RelocVerdict v) {
switch (v) {
case RelocVerdict::kAccept: return "CHOT";
case RelocVerdict::kNeedCycles: return "DAI_BIEN_CHO_VONG";
case RelocVerdict::kAmbiguous: return "NHAP_NHANG";
case RelocVerdict::kAmbiguousYaw: return "NHAP_NHANG_HUONG";
case RelocVerdict::kFailed: return "THAT_BAI";
}
return "?";
}
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg) {
if (!m.ok) return RelocVerdict::kFailed;
// Huong truoc: khong co cong nay thi vi tri dung, huong sai 40-160 do ma ty
// le vi tri van 1.6 (ban ROS).
if (m.ratio_yaw() < cfg.min_ratio_yaw) return RelocVerdict::kAmbiguousYaw;
// Hanh lang lap: tra loi sai tu tin te hon nhieu so voi im lang.
if (m.ratio() < cfg.min_ratio) return RelocVerdict::kAmbiguous;
// Dai bien: ty le mot lan khop khong tach duoc dung/sai o day.
if (m.ratio() < cfg.min_ratio_fast && streak < cfg.min_cycles) {
return RelocVerdict::kNeedCycles;
}
return RelocVerdict::kAccept;
}
} // namespace vslam

View File

@@ -96,6 +96,7 @@ endif()
if(VSLAM_BUILD_SLAM)
vslam_add_test(test_slam LIBS vslam_slam vslam_common)
vslam_add_test(test_voxel_export LIBS vslam_slam vslam_common)
vslam_add_test(test_global_localizer LIBS vslam_slam vslam_common)
endif()
if(VSLAM_BUILD_WEB)

View File

@@ -0,0 +1,303 @@
// Test cho dinh vi toan cuc (vslam/global_localizer.h), tren ban do TONG HOP.
//
// Ba thu phai khoa, vi ban ROS da tra gia cho tung cai:
// 1. Tim dung pose khi ban do KHONG doi xung.
// 2. Hai cho giong het nhau -> NHAP NHANG, khong duoc chon bua.
// 3. Phong doi xung quay 180 do -> chan o cong HUONG (vi tri dung, huong sai
// van cho ty le vi tri cao).
#include <gtest/gtest.h>
#include <algorithm>
#include <cmath>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/global_localizer.h"
using namespace vslam;
namespace {
constexpr double kRes = 0.05;
// O (r, c) co TAM tai goc + (c, r) * res -- cung quy uoc lam tron voi module.
OccupancyGrid MakeGrid(double w_m, double h_m) {
OccupancyGrid g;
g.resolution = static_cast<float>(kRes);
g.width = static_cast<uint32_t>(std::lround(w_m / kRes));
g.height = static_cast<uint32_t>(std::lround(h_m / kRes));
g.origin.position.x = 0.0;
g.origin.position.y = 0.0;
g.data.assign(static_cast<size_t>(g.width) * g.height, -1);
return g;
}
void Fill(OccupancyGrid* g, double x0, double y0, double x1, double y1, int8_t v) {
for (uint32_t r = 0; r < g->height; ++r) {
for (uint32_t c = 0; c < g->width; ++c) {
const double x = c * kRes, y = r * kRes;
if (x >= x0 - 1e-9 && x <= x1 + 1e-9 && y >= y0 - 1e-9 && y <= y1 + 1e-9) {
g->data[static_cast<size_t>(r) * g->width + c] = v;
}
}
}
}
// Phong chu nhat: ben trong trong, vien tuong day 0.1 m.
void Room(OccupancyGrid* g, double x0, double y0, double x1, double y1) {
Fill(g, x0, y0, x1, y1, 0);
Fill(g, x0, y0, x1, y0 + 0.1, 100);
Fill(g, x0, y1 - 0.1, x1, y1, 100);
Fill(g, x0, y0, x0 + 0.1, y1, 100);
Fill(g, x1 - 0.1, y0, x1, y1, 100);
}
// Tuong thang tu (x0, y0) toi (x1, y1), day ~0.1 m -- ke ca duong CHEO.
void Line(OccupancyGrid* g, double x0, double y0, double x1, double y1) {
const double vx = x1 - x0, vy = y1 - y0, len2 = vx * vx + vy * vy;
for (uint32_t r = 0; r < g->height; ++r) {
for (uint32_t c = 0; c < g->width; ++c) {
const double x = c * kRes, y = r * kRes;
const double t = std::max(0.0, std::min(1.0, ((x - x0) * vx + (y - y0) * vy) / len2));
if (std::hypot(x - (x0 + t * vx), y - (y0 + t * vy)) <= 0.06) {
g->data[static_cast<size_t>(r) * g->width + c] = 100;
}
}
}
}
// Phong KHONG doi xung, goc (dx, dy).
//
// ⚠️ Ban dau vach ngan nam o GIUA (x = 6): hai nua trai/phai la hai hop gan
// giong het nhau (5.4 m vs 5.3 m), tinh tien 5.4 m la khop gan het -> ty le
// chi 1.22 va cong tu choi DUNG. Gio: vach lech han sang trai, mot tuong CHEO
// pha moi doi xung vuong goc, them khoi va doan tuong o hai goc khac nhau.
void AsymRoom(OccupancyGrid* g, double dx, double dy) {
Room(g, dx + 0.5, dy + 0.5, dx + 11.5, dy + 9.5);
Fill(g, dx + 4.0, dy + 0.5, dx + 4.1, dy + 5.0, 100); // vach ngan lech trai
Line(g, dx + 7.0, dy + 6.0, dx + 10.0, dy + 8.5); // tuong cheo
Fill(g, dx + 8.5, dy + 1.5, dx + 9.5, dy + 2.5, 100); // khoi goc phai duoi
Fill(g, dx + 1.5, dy + 7.0, dx + 3.5, dy + 7.1, 100); // doan tuong goc trai tren
}
// Pose that dung trong AsymRoom: thay vach ngan, tuong cheo va khoi.
const Pose2D kAsymTruth{6.0, 3.0, 0.6};
// Scan 360 do tu `pose` (frame map), tra diem trong frame BASE.
std::vector<Point> Raycast(const OccupancyGrid& g, const Pose2D& pose, int n_rays = 720,
double max_range = 12.0) {
std::vector<Point> out;
for (int i = 0; i < n_rays; ++i) {
const double a_rel = -M_PI + 2.0 * M_PI * i / n_rays;
const double a = pose.theta + a_rel;
for (double r = 0.1; r < max_range; r += kRes / 2.0) {
const int c = static_cast<int>(std::lround((pose.x + r * std::cos(a)) / kRes));
const int rr = static_cast<int>(std::lround((pose.y + r * std::sin(a)) / kRes));
if (c < 0 || rr < 0 || c >= static_cast<int>(g.width) || rr >= static_cast<int>(g.height)) break;
if (g.data[static_cast<size_t>(rr) * g.width + c] >= 50) {
Point p;
p.x = r * std::cos(a_rel);
p.y = r * std::sin(a_rel);
out.push_back(p);
break;
}
}
}
return out;
}
// Diem frame base -> frame odom cua mot phien bat ky (odom lech han map).
std::vector<Point> ToOdom(const std::vector<Point>& base, const Pose2D& odom) {
std::vector<Point> out;
const double c = std::cos(odom.theta), s = std::sin(odom.theta);
for (const Point& p : base) {
Point q;
q.x = odom.x + c * p.x - s * p.y;
q.y = odom.y + s * p.x + c * p.y;
out.push_back(q);
}
return out;
}
std::vector<Point> ToMap(const std::vector<Point>& base, const Pose2D& pose) {
return ToOdom(base, pose);
}
} // namespace
TEST(GlobalLocalizer, LikelihoodTheoKhoangCachToiTuong) {
OccupancyGrid g = MakeGrid(2.0, 2.0);
Fill(&g, 0.0, 0.0, 2.0, 2.0, 0);
g.data[static_cast<size_t>(20) * g.width + 20] = 100; // mot o tuong o (1.0, 1.0)
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
EXPECT_NEAR(f.At(20, 20), 1.0, 1e-6);
// 3 o = 0.15 m = 1 sigma -> exp(-0.5)
EXPECT_NEAR(f.At(20, 23), std::exp(-0.5), 1e-4);
// cheo 3-4-5: 5 o = 0.25 m
EXPECT_NEAR(f.At(23, 24), std::exp(-(0.25 * 0.25) / (2 * 0.15 * 0.15)), 1e-4);
EXPECT_TRUE(f.Free(0, 0));
EXPECT_FALSE(f.Free(20, 20));
}
TEST(GlobalLocalizer, PhongKhongDoiXungTimDungPose) {
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const Pose2D odom{-1.0, 0.5, -0.3}; // frame odom lech han frame map
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
const RelocMatch m = GlobalMatch(f, pts, cfg);
ASSERT_TRUE(m.ok);
const Pose2D est = Pose2DCompose(m.map_from_odom, odom);
// RTAB-Map "bat ngay" khi lech < 0.1 m / 3 do (docs/SLAM.md) -- doi chat hon.
EXPECT_LT(std::hypot(est.x - truth.x, est.y - truth.y), 0.1);
EXPECT_LT(std::fabs(AngleDiff(est.theta, truth.theta)) * 180.0 / M_PI, 1.0);
// ⚠️ Doi thu XA phai tim duoc (ban ROS: s2 = 0 -> ty le vo cuc -> chot bua).
EXPECT_GT(m.s2, 0.0);
EXPECT_LT(m.ratio(), 100.0);
// Du so vong thi phai qua moi cong (ty le vi tri >= 1.30, huong >= 1.30).
EXPECT_EQ(Decide(m, cfg.min_cycles, cfg), RelocVerdict::kAccept)
<< "ty le " << m.ratio() << ", ty le huong " << m.ratio_yaw();
}
TEST(GlobalLocalizer, HaiPhongGiongHetLaNhapNhang) {
// Hai phong KHONG doi xung nhung GIONG HET nhau, cach 12 m, khong thong
// nhau. Scan chi thay phong minh dang dung -> khong co cach nao biet la
// phong nao. Tra loi sai tu tin te hon nhieu so voi im lang.
OccupancyGrid g = MakeGrid(24.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
AsymRoom(&g, 12.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth = kAsymTruth;
const RelocMatch m = GlobalMatch(f, ToOdom(Raycast(g, truth), Pose2D{}), cfg);
ASSERT_TRUE(m.ok);
EXPECT_LT(m.ratio(), cfg.min_ratio) << "hai phong giong het ma ty le " << m.ratio();
EXPECT_NE(Decide(m, 5, cfg), RelocVerdict::kAccept)
<< "streak cao cung KHONG duoc chot khi hai cho giong het";
}
TEST(GlobalLocalizer, PhongDoiXungQuay180ChanOCongHuong) {
// Robot o TAM phong chu nhat: huong theta va theta + 180 do cho CUNG mot
// scan. Vi tri dung, huong khong tin duoc -> phai chan truoc cong vi tri.
OccupancyGrid g = MakeGrid(9.0, 6.0);
Room(&g, 0.5, 0.5, 8.5, 5.5);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const GlobalLocalizerConfig cfg;
const Pose2D truth{4.5, 3.0, 0.3};
const RelocMatch m = GlobalMatch(f, ToOdom(Raycast(g, truth), Pose2D{}), cfg);
ASSERT_TRUE(m.ok);
EXPECT_LT(m.ratio_yaw(), cfg.min_ratio_yaw);
EXPECT_EQ(Decide(m, 5, cfg), RelocVerdict::kAmbiguousYaw);
}
TEST(GlobalLocalizer, DiemCanhLacTutKhiPoseSai) {
OccupancyGrid g = MakeGrid(12.0, 10.0);
AsymRoom(&g, 0.0, 0.0);
const LikelihoodField f = LikelihoodField::FromGrid(g, 0.15);
const Pose2D truth = kAsymTruth;
const std::vector<Point> base = Raycast(g, truth);
const double good = f.MeanScore(ToMap(base, truth));
// Lech CHEO + xoay: chi lech theo x thi diem tren tuong ngang van trung tuong.
const double bad =
f.MeanScore(ToMap(base, Pose2D{truth.x + 0.7, truth.y + 0.7, truth.theta + 0.4}));
ASSERT_GT(good, 0.0);
ASSERT_GE(bad, 0.0);
EXPECT_GT(good, 0.8);
EXPECT_LT(bad, GlobalLocalizerConfig().lost_score_ratio * good);
// Qua it diem roi vao luoi -> -1 ("chua do duoc"), khong phai 0 ("rat te").
EXPECT_EQ(f.MeanScore({}), -1.0);
}
TEST(GlobalLocalizer, StreakChiTangKhiDaDiChuyen) {
GlobalLocalizerConfig cfg;
HypothesisTracker tr(cfg);
RelocMatch m;
m.ok = true;
m.map_from_odom = Pose2D{2.0, 1.0, 0.4};
m.hyps.push_back({m.map_from_odom, 10.0});
m.hyps.push_back({Pose2D{9.0, 1.0, 0.4}, 8.0}); // doi thu o cho khac
tr.Add(m, Pose2D{0.0, 0.0, 0.0}, 0.0);
EXPECT_EQ(tr.Streak(m.map_from_odom), 1);
// Dung yen: ban sao doi xung cung lap lai y het -> KHONG cong.
tr.Add(m, Pose2D{0.05, 0.0, 0.0}, 10.0);
tr.Add(m, Pose2D{0.10, 0.0, 0.0}, 20.0);
EXPECT_EQ(tr.Streak(m.map_from_odom), 1);
// Di cham nhung CONG DON du 0.2 m -> cong (ban ROS dat lai moc moi vong nen
// di cham khong bao gio cong duoc).
tr.Add(m, Pose2D{0.21, 0.0, 0.0}, 30.0);
EXPECT_EQ(tr.Streak(m.map_from_odom), 2);
// Doi thu khong dung dau -> streak 0.
EXPECT_EQ(tr.Streak(Pose2D{9.0, 1.0, 0.4}), 0);
}
TEST(GlobalLocalizer, NguoiThangDoiThiStreakVe0) {
GlobalLocalizerConfig cfg;
HypothesisTracker tr(cfg);
RelocMatch a;
a.ok = true;
a.hyps = {{Pose2D{2.0, 1.0, 0.0}, 10.0}, {Pose2D{9.0, 1.0, 0.0}, 8.0}};
a.map_from_odom = a.hyps[0].map_from_odom;
RelocMatch b = a;
std::swap(b.hyps[0], b.hyps[1]);
b.map_from_odom = b.hyps[0].map_from_odom;
tr.Add(a, Pose2D{0.0, 0.0, 0.0}, 0.0);
tr.Add(a, Pose2D{0.5, 0.0, 0.0}, 10.0);
EXPECT_EQ(tr.Streak(a.map_from_odom), 2);
tr.Add(b, Pose2D{1.0, 0.0, 0.0}, 20.0);
EXPECT_EQ(tr.Streak(a.map_from_odom), 0);
EXPECT_EQ(tr.Streak(b.map_from_odom), 1);
}
TEST(GlobalLocalizer, ThuTuCong) {
const GlobalLocalizerConfig cfg;
RelocMatch m;
EXPECT_EQ(Decide(m, 9, cfg), RelocVerdict::kFailed);
m.ok = true;
m.s1 = 10.0;
// Huong truoc: ty le vi tri 5 van bi chan neu huong nhap nhang.
m.s2 = 2.0;
m.s2_yaw = 9.0;
EXPECT_EQ(Decide(m, 9, cfg), RelocVerdict::kAmbiguousYaw);
m.s2_yaw = 1.0;
m.s2 = 10.0 / 1.2;
EXPECT_EQ(Decide(m, 9, cfg), RelocVerdict::kAmbiguous);
m.s2 = 10.0 / 1.45; // dai bien 1.30-1.60
EXPECT_EQ(Decide(m, 1, cfg), RelocVerdict::kNeedCycles);
EXPECT_EQ(Decide(m, 2, cfg), RelocVerdict::kAccept);
m.s2 = 10.0 / 1.7; // tren nguong nhanh
EXPECT_EQ(Decide(m, 0, cfg), RelocVerdict::kAccept);
}
TEST(GlobalLocalizer, GopDiemVaRutCon) {
std::vector<Point> pts;
for (int i = 0; i < 100; ++i) {
Point p;
p.x = 1.0 + 0.0001 * i; // cung mot o 0.05 m
p.y = 2.0;
pts.push_back(p);
}
EXPECT_EQ(DownsamplePoints(pts, 0.05, 1500).size(), 1u);
pts.clear();
for (int i = 0; i < 3000; ++i) {
Point p;
p.x = 0.1 * i;
pts.push_back(p);
}
EXPECT_LE(DownsamplePoints(pts, 0.05, 1500).size(), 1500u);
}

View File

@@ -40,6 +40,11 @@ if(VSLAM_BUILD_SLAM)
# nao ngoai vslam_common, va nho no ban do xuat ra dung duoc NGAY voi
# `vslam_node --sim --map`.
target_link_libraries(vslam_slam_bench PRIVATE vslam_slam vslam_sim vslam_common)
# vslam_reloc_bench: do dinh vi TOAN CUC offline -- ban do tu mot DB, cau
# hoi la scan cua DB lan chay khac, dap an la pose da toi uu.
add_executable(vslam_reloc_bench vslam_reloc_bench.cc)
target_link_libraries(vslam_reloc_bench PRIVATE vslam_slam vslam_common)
endif()
# vslam_record: ghi .vsr tu bo mo phong theo kich ban co ten. Hat giong co

345
tools/vslam_reloc_bench.cc Normal file
View File

@@ -0,0 +1,345 @@
// Do dinh vi TOAN CUC (vslam/global_localizer.h) OFFLINE, khong can robot.
//
// ============ CACH DO ============
// Ban do dung tu `--map-db`. Cau hoi "toi dang o dau?" la scan cua node trong
// `--query-db`, ghep K node lien tiep bang odom (gia lap viec gom scan). Dap
// an that = pose DA TOI UU cua node do trong DB hoi.
//
// ⚠️ Nen hoi bang DB CUA LAN CHAY KHAC: scan cua chinh DB ban do da gop vao
// ban do, nen khop tai pose dung gan nhu hoan hao -- lac quan. Hai DB phai
// CUNG khung toa do (mo phong cung diem xuat phat); bench kiem node dau cua
// hai DB va tu choi neu lech.
//
// Moi cau hoi chay toi `--cycles` vong (mac dinh 2), vong sau cach vong truoc
// >= 0.5 m theo odom -- dung dieu kien cong streak cua HypothesisTracker.
//
// ============ KET QUA ============
// CHOT DUNG / CHOT SAI (ca nguy hiem nhat) / DAI BIEN / NHAP NHANG / ...
// ty le s1/s2 khi top-1 DUNG va khi top-1 SAI -- de biet cong co tach duoc
// khong. Ban ROS: 7 ca dung 1.315-1.581, 3 ca sai 1.31-1.39.
//
// vslam_reloc_bench --map-db A.db [--query-db B.db] [--n 200] [--seq 1]
// [--cycles 2] [--seed 1] [--csv out.csv]
#include <rtabmap/core/DBDriver.h>
#include <rtabmap/core/LaserScan.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/util3d_transforms.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <string>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/global_localizer.h"
#include "vslam/occupancy_export.h"
#include "vslam/sensor_data_builder.h"
namespace {
struct Node {
int id = 0;
vslam::Pose2D odom; // Node.pose -- odom THO cua phien do
vslam::Pose2D truth; // pose DA TOI UU
std::vector<vslam::Point> pts_base; // scan, frame base, <= max_range
};
bool LoadNodes(const std::string& db, double max_range, std::vector<Node>* out) {
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
if (driver == nullptr || !driver->openConnection(db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", db.c_str());
return false;
}
const std::map<int, rtabmap::Transform> opt = driver->loadOptimizedPoses();
for (const auto& kv : opt) {
const int id = kv.first;
Node n;
n.id = id;
n.truth = vslam::FromRtabmap(kv.second);
rtabmap::Transform pose, gt;
int map_id = 0, weight = 0;
std::string label;
double stamp = 0.0;
std::vector<float> vel;
rtabmap::GPS gps;
rtabmap::EnvSensors sensors;
if (!driver->getNodeInfo(id, pose, map_id, weight, label, stamp, gt, vel, gps,
sensors)) {
continue;
}
n.odom = vslam::FromRtabmap(pose);
rtabmap::SensorData data;
driver->getNodeData(id, data, false, true, false, false);
data.uncompressData();
const rtabmap::LaserScan& raw = data.laserScanRaw();
if (raw.isEmpty()) continue;
// Diem trong frame LASER; cat theo max_range tai day (tinh tu laser).
// Frame cuc bo cua laser nam trong scan -- bo qua la lech ~24 cm.
const rtabmap::LaserScan s = raw.localTransform().isNull()
? raw
: rtabmap::util3d::transformLaserScan(raw, raw.localTransform());
const cv::Mat& m = s.data();
const cv::Mat& ml = raw.data();
const int cnt = m.rows == 1 ? m.cols : m.rows;
for (int i = 0; i < cnt; ++i) {
const float* pl = ml.rows == 1 ? ml.ptr<float>(0, i) : ml.ptr<float>(i, 0);
if (std::hypot(pl[0], pl[1]) >= max_range) continue;
const float* p = m.rows == 1 ? m.ptr<float>(0, i) : m.ptr<float>(i, 0);
if (!std::isfinite(p[0]) || !std::isfinite(p[1])) continue;
vslam::Point q;
q.x = p[0];
q.y = p[1];
n.pts_base.push_back(q);
}
if (n.pts_base.size() < 50) continue;
out->push_back(std::move(n));
}
driver->closeConnection(false);
std::sort(out->begin(), out->end(), [](const Node& a, const Node& b) { return a.id < b.id; });
return !out->empty();
}
// Diem cua K node tu `start` trong frame ODOM cua phien hoi.
std::vector<vslam::Point> Gather(const std::vector<Node>& nodes, size_t start, int k) {
std::vector<vslam::Point> pts;
for (size_t j = start; j < nodes.size() && j < start + static_cast<size_t>(k); ++j) {
const vslam::Pose2D& o = nodes[j].odom;
const double c = std::cos(o.theta), s = std::sin(o.theta);
for (const vslam::Point& p : nodes[j].pts_base) {
vslam::Point q;
q.x = o.x + c * p.x - s * p.y;
q.y = o.y + s * p.x + c * p.y;
pts.push_back(q);
}
}
return pts;
}
double Median(std::vector<double> v) {
if (v.empty()) return NAN;
std::sort(v.begin(), v.end());
return v[v.size() / 2];
}
void PrintRange(const char* name, std::vector<double> v) {
if (v.empty()) {
std::printf(" %-26s: (khong co)\n", name);
return;
}
std::sort(v.begin(), v.end());
std::printf(" %-26s: %zu ca, min %.3f p10 %.3f trung vi %.3f p90 %.3f max %.3f\n",
name, v.size(), v.front(), v[v.size() / 10], v[v.size() / 2],
v[(v.size() * 9) / 10], v.back());
}
} // namespace
int main(int argc, char** argv) {
std::string map_db, query_db, csv_path;
int n_queries = 200, seq = 1, cycles = 2;
unsigned seed = 1;
double ok_m = 0.5, ok_deg = 10.0;
vslam::GlobalLocalizerConfig cfg;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
auto next = [&]() -> std::string { return i + 1 < argc ? argv[++i] : ""; };
if (a == "--map-db") map_db = next();
else if (a == "--query-db") query_db = next();
else if (a == "--n") n_queries = std::atoi(next().c_str());
else if (a == "--seq") seq = std::max(1, std::atoi(next().c_str()));
else if (a == "--cycles") cycles = std::max(1, std::atoi(next().c_str()));
else if (a == "--seed") seed = static_cast<unsigned>(std::atoi(next().c_str()));
else if (a == "--csv") csv_path = next();
else if (a == "--ok-m") ok_m = std::atof(next().c_str());
else if (a == "--ok-deg") ok_deg = std::atof(next().c_str());
else if (a == "--help") {
std::printf(
"cach dung: %s --map-db A.db [--query-db B.db] [--n 200] [--seq K]\n"
" [--cycles 2] [--seed 1] [--csv out.csv] [--ok-m 0.5] [--ok-deg 10]\n",
argv[0]);
return 0;
}
}
if (map_db.empty()) {
std::fprintf(stderr, "can --map-db\n");
return 2;
}
if (query_db.empty()) {
query_db = map_db;
std::printf("⚠️ hoi bang CHINH DB ban do -- lac quan (scan da gop vao ban do).\n");
}
// --- Ban do ---
const auto t_map0 = std::chrono::steady_clock::now();
vslam::OccupancyGrid grid;
const vslam::StatusResponse st = vslam::ExportOccupancyGridFromDb(map_db, 0.05, cfg.max_range, &grid);
if (!st.ok()) {
std::fprintf(stderr, "xuat luoi tu %s: %s\n", map_db.c_str(), st.message.c_str());
return 1;
}
const vslam::LikelihoodField field = vslam::LikelihoodField::FromGrid(grid, cfg.sigma);
const double t_map = std::chrono::duration<double>(std::chrono::steady_clock::now() - t_map0).count();
std::printf("ban do %s: %ux%u o @ %.2f m (%.1f x %.1f m), dung trong %.2f s\n",
map_db.c_str(), grid.width, grid.height, grid.resolution,
grid.width * grid.resolution, grid.height * grid.resolution, t_map);
// --- Cau hoi ---
std::vector<Node> nodes;
if (!LoadNodes(query_db, cfg.max_range, &nodes)) {
std::fprintf(stderr, "khong co node nao co scan + pose toi uu trong %s\n", query_db.c_str());
return 1;
}
std::printf("hoi tu %s: %zu node co scan + pose toi uu\n", query_db.c_str(), nodes.size());
if (query_db != map_db) {
// Hai DB phai cung khung: so node dau (id nho nhat co pose toi uu).
std::unique_ptr<rtabmap::DBDriver> d(rtabmap::DBDriver::create());
d->openConnection(map_db, false);
const std::map<int, rtabmap::Transform> opt = d->loadOptimizedPoses();
d->closeConnection(false);
if (opt.empty()) {
std::fprintf(stderr, "%s khong co pose toi uu\n", map_db.c_str());
return 1;
}
const vslam::Pose2D a = vslam::FromRtabmap(opt.begin()->second);
// Node dau cua DB hoi (id nho nhat co pose toi uu, ke ca khong co scan).
std::unique_ptr<rtabmap::DBDriver> dq(rtabmap::DBDriver::create());
dq->openConnection(query_db, false);
const std::map<int, rtabmap::Transform> optq = dq->loadOptimizedPoses();
dq->closeConnection(false);
const vslam::Pose2D b = vslam::FromRtabmap(optq.begin()->second);
const double dd = std::hypot(a.x - b.x, a.y - b.y);
const double da = std::fabs(vslam::AngleDiff(a.theta, b.theta)) * 180.0 / M_PI;
std::printf("node dau: ban do (%.2f, %.2f, %.1f do) hoi (%.2f, %.2f, %.1f do)\n",
a.x, a.y, a.theta * 180.0 / M_PI, b.x, b.y, b.theta * 180.0 / M_PI);
if (dd > 0.5 || da > 5.0) {
std::fprintf(stderr,
"hai DB KHAC khung toa do (node dau lech %.2f m / %.1f do) -- dap an "
"that khong so duoc. Chi dung DB cung diem xuat phat.\n", dd, da);
return 1;
}
}
// --- Chay ---
std::mt19937 rng(seed);
const size_t max_start = nodes.size() > static_cast<size_t>(seq) ? nodes.size() - seq : 0;
std::uniform_int_distribution<size_t> pick(0, max_start);
FILE* csv = csv_path.empty() ? nullptr : std::fopen(csv_path.c_str(), "w");
if (csv != nullptr) {
std::fprintf(csv, "query_id,cycle,verdict,ratio,ratio_yaw,err_m,err_deg,top1_ok,points,ms\n");
}
int n_accept_ok = 0, n_accept_bad = 0, n_need = 0, n_amb = 0, n_amb_yaw = 0, n_fail = 0;
std::vector<double> ratio_ok, ratio_bad, ms_all, err_ok;
int top1_ok_cnt = 0, top1_total = 0;
for (int q = 0; q < n_queries; ++q) {
size_t idx = pick(rng);
vslam::HypothesisTracker tracker(cfg);
vslam::RelocVerdict final_v = vslam::RelocVerdict::kFailed;
bool accepted = false, accepted_ok = false;
double acc_err_m = 0.0, acc_err_deg = 0.0;
for (int c = 0; c < cycles && idx < nodes.size(); ++c) {
const std::vector<vslam::Point> pts = Gather(nodes, idx, seq);
const size_t last = std::min(nodes.size() - 1, idx + seq - 1);
const auto t0 = std::chrono::steady_clock::now();
const vslam::RelocMatch m = vslam::GlobalMatch(field, pts, cfg);
const double ms = std::chrono::duration<double, std::milli>(
std::chrono::steady_clock::now() - t0).count();
ms_all.push_back(ms);
tracker.Add(m, nodes[last].odom, 10.0 * c);
const int streak = m.ok ? tracker.Streak(m.map_from_odom) : 0;
const vslam::RelocVerdict v = vslam::Decide(m, streak, cfg);
final_v = v;
double err_m = NAN, err_deg = NAN;
bool top1_ok = false;
if (m.ok) {
const vslam::Pose2D est = vslam::Pose2DCompose(m.map_from_odom, nodes[last].odom);
const vslam::Pose2D& tru = nodes[last].truth;
err_m = std::hypot(est.x - tru.x, est.y - tru.y);
err_deg = std::fabs(vslam::AngleDiff(est.theta, tru.theta)) * 180.0 / M_PI;
top1_ok = err_m < ok_m && err_deg < ok_deg;
++top1_total;
if (top1_ok) { ++top1_ok_cnt; ratio_ok.push_back(m.ratio()); }
else ratio_bad.push_back(m.ratio());
}
if (csv != nullptr) {
std::fprintf(csv, "%d,%d,%s,%.4f,%.4f,%.4f,%.3f,%d,%zu,%.1f\n", nodes[idx].id, c,
vslam::RelocVerdictName(v), m.ok ? m.ratio() : 0.0,
m.ok ? m.ratio_yaw() : 0.0, err_m, err_deg, top1_ok ? 1 : 0,
m.points, ms);
}
if (v == vslam::RelocVerdict::kAccept) {
accepted = true;
accepted_ok = top1_ok;
acc_err_m = err_m;
acc_err_deg = err_deg;
break;
}
// Vong sau: node dau tien cach node cuoi vong nay >= 0.5 m theo odom.
size_t nxt = last + 1;
while (nxt < nodes.size() &&
std::hypot(nodes[nxt].odom.x - nodes[last].odom.x,
nodes[nxt].odom.y - nodes[last].odom.y) < 0.5) {
++nxt;
}
idx = nxt;
}
if (accepted) {
if (accepted_ok) { ++n_accept_ok; err_ok.push_back(acc_err_m); }
else {
++n_accept_bad;
std::printf(" ⚠️ CHOT SAI: node %d, sai %.2f m / %.1f do\n", nodes[std::min(idx, nodes.size() - 1)].id,
acc_err_m, acc_err_deg);
}
} else {
switch (final_v) {
case vslam::RelocVerdict::kNeedCycles: ++n_need; break;
case vslam::RelocVerdict::kAmbiguous: ++n_amb; break;
case vslam::RelocVerdict::kAmbiguousYaw: ++n_amb_yaw; break;
default: ++n_fail; break;
}
}
if ((q + 1) % 20 == 0) {
std::printf(" [%d/%d] chot dung %d, chot SAI %d\n", q + 1, n_queries, n_accept_ok,
n_accept_bad);
std::fflush(stdout);
}
}
if (csv != nullptr) std::fclose(csv);
const int total = n_queries;
std::printf("\n===== %d cau hoi, --seq %d, --cycles %d, dung = < %.2f m & < %.1f do =====\n",
total, seq, cycles, ok_m, ok_deg);
std::printf(" CHOT DUNG : %4d (%.1f%%)\n", n_accept_ok, 100.0 * n_accept_ok / total);
std::printf(" CHOT SAI ⚠️ : %4d (%.1f%%)\n", n_accept_bad, 100.0 * n_accept_bad / total);
std::printf(" DAI BIEN (chua du vong): %4d\n", n_need);
std::printf(" NHAP NHANG vi tri : %4d\n", n_amb);
std::printf(" NHAP NHANG huong : %4d\n", n_amb_yaw);
std::printf(" THAT BAI : %4d\n", n_fail);
std::printf(" top-1 dung (moi vong, chua xet cong): %d/%d\n", top1_ok_cnt, top1_total);
PrintRange("ty le khi top-1 DUNG", ratio_ok);
PrintRange("ty le khi top-1 SAI", ratio_bad);
std::printf(" sai so khi CHOT DUNG: trung vi %.3f m\n", Median(err_ok));
std::printf(" thoi gian moi lan khop: trung vi %.0f ms, max %.0f ms\n", Median(ms_all),
ms_all.empty() ? 0.0 : *std::max_element(ms_all.begin(), ms_all.end()));
return 0;
}