reloc: LocalMatch + bench --split-id/--vpr-csv + phan tich ghep VPR/LiDAR; robot that: 85 -> 108 chot dung, 0 sai

This commit is contained in:
trung09122002
2026-09-29 10:26:00 +07:00
parent ca3b7854ea
commit 399a46139e
8 changed files with 549 additions and 92 deletions

View File

@@ -146,6 +146,15 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg);
// Khop CUC BO: robot phai nam trong `radius` quanh `center` (frame map), MOI
// huong. De XAC MINH ung vien tu nguon khac (VPR). `odom_now`: pose robot
// trong frame odom luc gom -- rang buoc dat tren vi tri ROBOT, khong phai tam
// dam diem (o hanh lang tam lech robot nhieu met). score = -1 neu khong khop.
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
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 {

View File

@@ -9,6 +9,7 @@
// canh bao -- cho toi khi goi `uncompressDataConst()`. Do dung la ly do
// `tools/probe_rtabmap` lan dau chay ra "1990 node, 0 o".
#include <set>
#include <string>
#include "vslam/vslam_common.h"
@@ -39,9 +40,14 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out);
// Doc thang tu DB, khong can Rtabmap dang chay. Dung cho
// `tools/vslam_slam_bench` va cho viec doi DB cu sang PGM.
//
// `only_ids`: chi dung cac node co id trong tap nay (nullptr = moi node). De
// do relocalization CONG BANG tren mot phien: ban do tu nua dau, hoi bang nua
// sau -- scan dung de hoi khong duoc gop vao ban do.
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out);
OccupancyGrid* out,
const std::set<int>* only_ids = nullptr);
} // namespace vslam

View File

@@ -206,6 +206,119 @@ std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
return out;
}
namespace {
// Luoi tho + dam diem da can tam -- dung chung cho GlobalMatch va LocalMatch.
struct Coarse {
double res = 0.05;
int k = 1; // o tho = k x k o min
double rc = 0.8; // canh o tho, met
int Wc = 0, Hc = 0;
std::vector<float> Lc; // max-pool truong likelihood
std::vector<uint8_t> Fc; // o tho co it nhat mot o min TRONG
Point cen; // tam dam diem (frame odom)
std::vector<Point> P; // diem da tru tam
double step = 0.0; // buoc goc, rad
int n_ang = 0;
int R = 0; // ban kinh histogram do lech, o tho
// Tam cua khoi tho b, met tuong doi goc luoi. O min i co tam i*res.
double BlockCenter(int b) const { return (b * k + (k - 1) / 2.0) * res; }
bool FreeCell(int r, int c) const { return Fc[static_cast<size_t>(r) * Wc + c] != 0; }
};
Coarse PrepareCoarse(const LikelihoodField& field, const std::vector<Point>& pts,
const GlobalLocalizerConfig& cfg) {
Coarse cz;
cz.res = field.resolution();
// 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.
cz.k = std::max(1, static_cast<int>(std::lround(cfg.coarse_res / cz.res)));
cz.rc = cz.res * cz.k;
const int W = field.width(), H = field.height();
cz.Wc = (W + cz.k - 1) / cz.k;
cz.Hc = (H + cz.k - 1) / cz.k;
cz.Lc.assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
cz.Fc.assign(static_cast<size_t>(cz.Wc) * cz.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 / cz.k) * cz.Wc + (c / cz.k);
cz.Lc[ci] = std::max(cz.Lc[ci], field.At(r, c));
if (field.Free(r, c)) cz.Fc[ci] = 1;
}
}
// Xoay quanh TAM dam diem cho on dinh so hoc.
for (const Point& p : pts) { cz.cen.x += p.x; cz.cen.y += p.y; }
cz.cen.x /= static_cast<double>(pts.size());
cz.cen.y /= static_cast<double>(pts.size());
cz.P.resize(pts.size());
double maxn = 0.0;
for (size_t i = 0; i < pts.size(); ++i) {
cz.P[i].x = pts[i].x - cz.cen.x;
cz.P[i].y = pts[i].y - cz.cen.y;
maxn = std::max(maxn, std::hypot(cz.P[i].x, cz.P[i].y));
}
cz.step = cfg.angle_step_deg * kDegToRad;
cz.n_ang = std::max(1, static_cast<int>(std::lround(2.0 * M_PI / cz.step)));
cz.R = static_cast<int>(std::ceil(maxn / cz.rc)) + 1;
return cz;
}
struct AnglePeak { double score; int r, c; double th; };
// Diem THO cua goc thu `ia` tai moi o `allowed(r, c)` (o khac = 0).
//
// 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.
template <class Allowed>
AnglePeak ScoreAngle(const Coarse& cz, int ia, Allowed allowed, std::vector<float>* sc) {
struct Off { int dr, dc; float n; };
const double th = ia * cz.step;
const double ct = std::cos(th), st = std::sin(th);
const int HW = 2 * cz.R + 1;
std::vector<float> hist(static_cast<size_t>(HW) * HW, 0.0f);
for (const Point& p : cz.P) {
const int dc = static_cast<int>(std::lround((ct * p.x - st * p.y) / cz.rc));
const int dr = static_cast<int>(std::lround((st * p.x + ct * p.y) / cz.rc));
hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)] += 1.0f;
}
std::vector<Off> offs;
for (int dr = -cz.R; dr <= cz.R; ++dr) {
for (int dc = -cz.R; dc <= cz.R; ++dc) {
const float n = hist[static_cast<size_t>(dr + cz.R) * HW + (dc + cz.R)];
if (n > 0.0f) offs.push_back({dr, dc, n});
}
}
sc->assign(static_cast<size_t>(cz.Wc) * cz.Hc, 0.0f);
AnglePeak pk{-1.0, 0, 0, th};
for (int r = 0; r < cz.Hc; ++r) {
for (int c = 0; c < cz.Wc; ++c) {
if (!allowed(r, 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 >= cz.Hc || cc >= cz.Wc) continue;
s += o.n * cz.Lc[static_cast<size_t>(rr) * cz.Wc + cc];
}
(*sc)[static_cast<size_t>(r) * cz.Wc + c] = static_cast<float>(s);
if (s > pk.score) pk = AnglePeak{s, r, c, th};
}
}
return pk;
}
// (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
Pose2D ToMap(const Refined& rf, const Point& cen, const LikelihoodField& f) {
const double ct = std::cos(rf.th), st = std::sin(rf.th);
return Pose2D{rf.x + f.origin_x() - (ct * cen.x - st * cen.y),
rf.y + f.origin_y() - (st * cen.x + ct * cen.y),
NormalizeAngle(rf.th)};
}
} // namespace
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg) {
@@ -217,86 +330,25 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
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));
}
const Coarse cz = PrepareCoarse(field, pts, cfg);
const int k = cz.k;
const double rc = cz.rc;
const int Wc = cz.Wc, Hc = cz.Hc;
const std::vector<Point>& P = cz.P;
const double step = cz.step;
const int n_ang = cz.n_ang;
auto block_center = [&](int b) { return cz.BlockCenter(b); };
// --- 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; };
// ⚠️ Rang buoc "o trong" dat tren TAM dam diem, dung nhu ban ROS
// (`sc[~Fc] = 0` tren luoi dat tam). Dam may 300 do quanh robot co tam gan
// robot nen gan nhu tuong duong.
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);
peaks.push_back(ScoreAngle(cz, ia, [&](int r, int c) { return cz.FreeCell(r, c); },
&scores[ia]));
}
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
@@ -389,15 +441,7 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
}
}
// (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});
for (const Refined& rf : refined) out.hyps.push_back({ToMap(rf, cz.cen, field), rf.score});
out.map_from_odom = out.hyps[0].map_from_odom;
out.s1 = best.score;
out.s2 = s2;
@@ -406,6 +450,58 @@ RelocMatch GlobalMatch(const LikelihoodField& field,
return out;
}
RelocHypothesis LocalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom, const Pose2D& odom_now,
const Point& center, double radius,
const GlobalLocalizerConfig& cfg) {
RelocHypothesis out;
out.score = -1.0;
if (field.empty() || pts_odom.empty()) return out;
const std::vector<Point> pts =
DownsamplePoints(pts_odom, field.resolution(), cfg.max_points);
if (pts.empty()) return out;
const Coarse cz = PrepareCoarse(field, pts, cfg);
// Rang buoc dat tren vi tri ROBOT, khong phai tam dam diem: o hanh lang tam
// lech robot nhieu met. Voi goc th, robot roi dung `center` khi tam dat tai
// center - R(th) * (robot_odom - tam)
// (met tuong doi goc luoi). Nua o tho cong them de khong cat hut o bien.
const double bx = odom_now.x - cz.cen.x, by = odom_now.y - cz.cen.y;
const double cx = center.x - field.origin_x(), cy = center.y - field.origin_y();
const double r2 = (radius + 0.5 * cz.rc) * (radius + 0.5 * cz.rc);
std::vector<AnglePeak> peaks;
std::vector<float> sc;
for (int ia = 0; ia < cz.n_ang; ++ia) {
const double th = ia * cz.step;
const double ct = std::cos(th), st = std::sin(th);
const double px = cx - (ct * bx - st * by), py = cy - (st * bx + ct * by);
const AnglePeak pk = ScoreAngle(
cz, ia,
[&](int r, int c) {
if (!cz.FreeCell(r, c)) return false;
const double dx = cz.BlockCenter(c) - px, dy = cz.BlockCenter(r) - py;
return dx * dx + dy * dy <= r2;
},
&sc);
if (pk.score > 0.0) peaks.push_back(pk);
}
if (peaks.empty()) return out;
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
// Tinh chinh vai dinh dau (cung ly do nhu GlobalMatch: so o muc tho la sai).
Refined best;
for (size_t i = 0; i < peaks.size() && i < 3; ++i) {
const Refined rf = Refine(field, cz.P, cz.BlockCenter(peaks[i].c),
cz.BlockCenter(peaks[i].r), peaks[i].th, cz.rc, cfg);
if (rf.score > best.score) best = rf;
}
if (best.score < 0.0) return out;
out.map_from_odom = ToMap(best, cz.cen, field);
out.score = best.score;
return out;
}
// ---------------------------------------------------------------------------
// Tich luy qua nhieu vong
// ---------------------------------------------------------------------------

View File

@@ -140,7 +140,8 @@ StatusResponse ExportOccupancyGrid(rtabmap::Rtabmap& slam, OccupancyGrid* out) {
StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
double cell_size, double range_max,
OccupancyGrid* out) {
OccupancyGrid* out,
const std::set<int>* only_ids) {
std::unique_ptr<rtabmap::DBDriver> driver(rtabmap::DBDriver::create());
bool opened = false;
try {
@@ -153,7 +154,13 @@ StatusResponse ExportOccupancyGridFromDb(const std::string& db_path,
return StatusResponse::Error(StatusCode::kNotFound, "khong mo duoc DB: " + db_path);
}
const std::map<int, rtabmap::Transform> poses = driver->loadOptimizedPoses();
const std::map<int, rtabmap::Transform> all_poses = driver->loadOptimizedPoses();
// Chi node DA DUNG moi duoc dua vao update(): pose thua khong co luoi trong
// cache thi vo hai, nhung de ro rang la ban do dung tu tap nao.
std::map<int, rtabmap::Transform> poses;
for (const auto& kv : all_poses) {
if (only_ids == nullptr || only_ids->count(kv.first) != 0) poses.insert(kv);
}
rtabmap::LocalGridCache cache;
int with_grid = 0;

View File

@@ -165,6 +165,39 @@ TEST(GlobalLocalizer, PhongKhongDoiXungTimDungPose) {
<< "ty le " << m.ratio() << ", ty le huong " << m.ratio_yaw();
}
TEST(GlobalLocalizer, KhopCucBoQuanhUngVien) {
// Ung vien tu nguon khac (VPR) lech 0.8 m khoi cho that: khop cuc bo phai
// tim ra cho that. Ung vien o goc kia cua phong: diem phai thap han.
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};
const std::vector<Point> pts = ToOdom(Raycast(g, truth), odom);
Point near_c;
near_c.x = truth.x + 0.8;
near_c.y = truth.y - 0.5;
const RelocHypothesis h = LocalMatch(f, pts, odom, near_c, 2.5, cfg);
ASSERT_GT(h.score, 0.0);
const Pose2D est = Pose2DCompose(h.map_from_odom, odom);
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);
Point far_c;
far_c.x = 9.5;
far_c.y = 8.5;
const RelocHypothesis hf = LocalMatch(f, pts, odom, far_c, 1.0, cfg);
const Pose2D ef = Pose2DCompose(hf.map_from_odom, odom);
EXPECT_LT(hf.score, 0.7 * h.score) << "cho sai ma diem " << hf.score << " / " << h.score;
// Rang buoc tren ROBOT: pose tim duoc phai nam quanh tam da cho (ban kinh
// 1 m + nua o tho 0.4 m + tinh chinh toi 0.5 m), khong phai o cho that
// cach do ~6 m.
EXPECT_LT(std::hypot(ef.x - far_c.x, ef.y - far_c.y), 2.0);
}
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

View File

@@ -0,0 +1,151 @@
#!/usr/bin/env python3
"""So cac cach GHEP camera (VPR) + LiDAR cho relocalization, tu CSV cua bench.
Dau vao: `vslam_reloc_bench --vpr-csv ... --fusion-csv F` -- moi dong mot cap
(node hoi, ung vien VPR), kem ket qua khop LiDAR TOAN CUC cua node hoi va ket
qua khop LiDAR CUC BO quanh ung vien.
KHONG chon nguong tu bench: in ra de nhin, roi moi quyet dinh luat ghep dua
vao node. Con so quan trong nhat moi dong la cot CHOT SAI.
python3 tools/reloc_fusion_analyze.py logs/reloc_fusion.csv --db DB_BAN_DO.db
============ VI SAO CAN --db ============
Do lan dau (robot that 2026-09-29): dong thuan "LiDAR toan cuc trung khop cuc
bo quanh ung vien VPR" chot SAI 7 lan:
- 4 ca VPR DUNG CHO (0.1-0.3 m, giong 0.78-0.91) nhung khop cuc bo TRUOT
sang huong lon (105-177 do) cung voi LiDAR toan cuc -- hai nguon KHONG doc
lap ve huong, vi khop cuc bo van dung LiDAR de chon huong;
- 3 ca VPR SAI CHO (7-9 m) nhung giong THAP (0.42-0.59).
Nen luat phai dung ca HUONG cua node anh VPR (camera nhin ve do) va do giong.
Huong node doc tu DB (sqlite, chi doc).
"""
import argparse
import csv
import math
import sqlite3
import zlib
from collections import defaultdict
import numpy as np
def ang(a, b):
return abs(math.degrees(math.atan2(math.sin(a - b), math.cos(a - b))))
def node_yaws(db):
"""Huong (rad) cua moi node theo pose DA TOI UU trong DB."""
c = sqlite3.connect(f"file:{db}?mode=ro", uri=True).cursor()
ids_b, poses_b = c.execute("select opt_ids, opt_poses from Admin").fetchone()
ids = np.frombuffer(zlib.decompress(ids_b[:-12]), dtype=np.int32)
P = np.frombuffer(zlib.decompress(poses_b[:-12]), dtype=np.float32).reshape(-1, 3, 4)
return {int(i): math.atan2(float(P[k][1, 0]), float(P[k][0, 0])) for k, i in enumerate(ids)}
def main():
ap = argparse.ArgumentParser()
ap.add_argument("csv")
ap.add_argument("--ok-m", type=float, default=0.5, help="chot DUNG neu sai < ngan nay")
ap.add_argument("--ok-deg", type=float, default=10.0)
ap.add_argument("--agree-m", type=float, default=1.0, help="hai nguon DONG THUAN neu lech < ngan nay")
ap.add_argument("--agree-deg", type=float, default=10.0)
ap.add_argument("--db", required=True, help="DB ban do -- lay huong cac node ung vien VPR")
ap.add_argument("--vpr-yaw-deg", type=float, default=45.0,
help="huong chot phai lech huong node anh VPR it hon ngan nay")
a = ap.parse_args()
yaw = node_yaws(a.db)
q = {}
cands = defaultdict(list)
for r in csv.DictReader(open(a.csv)):
qid = int(r["query_id"])
if qid not in q:
q[qid] = dict(
glob_ok=r["glob_ok"] == "1", verdict=r["glob_verdict"], ratio=float(r["glob_ratio"]),
g=(float(r["glob_x"]), float(r["glob_y"]), float(r["glob_th"])),
t=(float(r["truth_x"]), float(r["truth_y"]), float(r["truth_th"])))
if int(r["rank"]) > 0:
cands[qid].append(dict(
rank=int(r["rank"]), node=int(r["vpr_node"]), sim=float(r["vpr_sim"]),
node_dist=float(r["vpr_node_dist_m"]),
score=float(r["loc_score"]),
l=(float(r["loc_x"]), float(r["loc_y"]), float(r["loc_th"]))))
def correct(p, t):
return math.hypot(p[0] - t[0], p[1] - t[1]) < a.ok_m and ang(p[2], t[2]) < a.ok_deg
def agree(p, r):
return math.hypot(p[0] - r[0], p[1] - r[1]) < a.agree_m and ang(p[2], r[2]) < a.agree_deg
n = len(q)
rows = []
def add(name, picks):
"""picks: {qid: pose da chot} -- node hoi KHONG co mat la 'khong chot'."""
ok = sum(1 for k, p in picks.items() if correct(p, q[k]["t"]))
rows.append((name, len(picks), ok, len(picks) - ok))
add("LiDAR, cong hien tai (1 vong)",
{k: v["g"] for k, v in q.items() if v["glob_ok"] and v["verdict"] == "CHOT"})
add("LiDAR top-1, KHONG cong", {k: v["g"] for k, v in q.items() if v["glob_ok"]})
vpr_top1_near = sum(1 for k in q if cands[k] and cands[k][0]["node_dist"] < 2.0)
add("VPR top-1 + khop cuc bo, KHONG cong",
{k: cands[k][0]["l"] for k in q if cands[k] and cands[k][0]["score"] > 0})
for K in (1, 3, 5):
picks = {}
for k, v in q.items():
if not v["glob_ok"]:
continue
if any(c["score"] > 0 and agree(v["g"], c["l"]) for c in cands[k] if c["rank"] <= K):
picks[k] = v["g"]
add(f"DONG THUAN LiDAR toan cuc + VPR top-{K}", picks)
# Hop: cong LiDAR hien tai HOAC dong thuan top-3.
union = {k: v["g"] for k, v in q.items() if v["glob_ok"] and v["verdict"] == "CHOT"}
for k, v in q.items():
if v["glob_ok"] and any(c["score"] > 0 and agree(v["g"], c["l"])
for c in cands[k] if c["rank"] <= 3):
union[k] = v["g"]
add("cong LiDAR HOAC dong thuan top-3", union)
# --- Dong thuan CO dieu kien: VPR xac nhan ca HUONG, va du giong ---
def vpr_ok(c, pose, tau):
return (c["score"] > 0 and c["sim"] >= tau and c["node"] in yaw
and ang(pose[2], yaw[c["node"]]) < a.vpr_yaw_deg)
best = None
for K in (1, 3):
for tau in (0.6, 0.7, 0.8):
picks = {}
for k, v in q.items():
if v["glob_ok"] and any(agree(v["g"], c["l"]) and vpr_ok(c, v["g"], tau)
for c in cands[k] if c["rank"] <= K):
picks[k] = v["g"]
add(f"DONG THUAN top-{K} + giong>={tau} + huong", picks)
ok = sum(1 for kk, p in picks.items() if correct(p, q[kk]["t"]))
if len(picks) == ok and (best is None or ok > best[1]):
best = ((K, tau), ok, picks)
# Luat tot nhat (0 sai) HOP voi cong LiDAR hien tai.
if best is not None:
(K, tau), _, picks = best
u = {k: v["g"] for k, v in q.items() if v["glob_ok"] and v["verdict"] == "CHOT"}
u.update(picks)
add(f"cong LiDAR HOAC dong thuan top-{K} giong>={tau} huong", u)
print(f"{n} node hoi (cho robot quay lai), dung = < {a.ok_m} m & < {a.ok_deg} do, "
f"dong thuan = < {a.agree_m} m & < {a.agree_deg} do")
print(f"VPR top-1 ROI DUNG CHO (node ung vien < 2 m): {vpr_top1_near}/{n} "
f"({100.0 * vpr_top1_near / max(1, n):.1f}%)\n")
print(f" {'cach':44s} {'chot':>5s} {'DUNG':>5s} {'SAI':>5s} {'dung/tong':>9s}")
for name, acc, ok, bad in rows:
print(f" {name:44s} {acc:5d} {ok:5d} {bad:5d} {100.0 * ok / max(1, n):8.1f}%"
+ (" ⚠️" if bad > 0 else ""))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -247,6 +247,12 @@ def main():
ap.add_argument("--device", default="cuda")
ap.add_argument("--csv", default="logs/vpr_eval.csv")
ap.add_argument("--fig", default="report/vpr/vi_du.png")
# Xuat ung vien cho tools/vslam_reloc_bench --vpr-csv: moi node hoi (id >=
# split-id) lay top-K node GIONG NHAT trong phan ban do (id < split-id).
ap.add_argument("--split-id", type=int, default=-1)
ap.add_argument("--topk-csv", default="")
ap.add_argument("--topk", type=int, default=5)
ap.add_argument("--topk-method", default="eigenplaces+clahe")
a = ap.parse_args()
nodes = load_db(a.db)
@@ -266,13 +272,14 @@ def main():
raw = [n["img"] for n in nodes]
enh = [clahe(im) for im in raw]
nodot = [dedot(im) for im in raw]
results, all_rows = [], {}
results, all_rows, descs = [], {}, {}
print(f"\n===== loai tru +-{a.excl_sec:.0f} s | dung = < {a.pos_m} m & < {a.pos_deg:.0f} do =====")
for tag, imgs in (("", raw), ("+clahe", enh), ("+khu_cham", nodot)):
if "tiny" in variants:
D, ms = desc_tiny(imgs)
rows = evaluate(D, nodes, a.excl_sec, a.pos_m, a.pos_deg)
nm = "tiny" + tag
descs[nm] = D
s = summarize(nm, rows, ms)
if s:
results.append(s)
@@ -281,6 +288,7 @@ def main():
D, ms = torch_desc(fn, imgs, wh, a.device)
rows = evaluate(D, nodes, a.excl_sec, a.pos_m, a.pos_deg)
nm = mname + tag
descs[nm] = D
s = summarize(nm, rows, ms)
if s:
results.append(s)
@@ -303,6 +311,33 @@ def main():
f"{int(r['ok5'])},{int(r['ok10'])}\n")
save_examples(a.fig, nodes, all_rows[best["name"]], best["name"])
print(f" csv -> {a.csv}\n anh vi du -> {a.fig}")
if a.topk_csv:
D = descs.get(a.topk_method)
if D is None:
print(f" ⚠️ khong co mo ta '{a.topk_method}' (co: {', '.join(descs)}) -- khong xuat top-K")
return 1
ids = np.array([n["id"] for n in nodes])
t = np.array([n["t"] for n in nodes])
in_map = ids < a.split_id if a.split_id > 0 else np.ones(len(ids), bool)
is_q = ids >= a.split_id if a.split_id > 0 else np.ones(len(ids), bool)
mi = np.nonzero(in_map)[0]
n_rows = 0
os.makedirs(os.path.dirname(a.topk_csv) or ".", exist_ok=True)
with open(a.topk_csv, "w") as f:
f.write("query_id,rank,node_id,sim\n")
for qi in np.nonzero(is_q)[0]:
s = D[mi] @ D[qi]
# Cung luat loai tru nhu phan cham: node ban do qua gan thoi
# diem hoi (ngay truoc diem chia) giong la hien nhien.
s[np.abs(t[mi] - t[qi]) < a.excl_sec] = -np.inf
for r, j in enumerate(np.argsort(-s)[:a.topk], start=1):
if not np.isfinite(s[j]):
break
f.write(f"{ids[qi]},{r},{ids[mi[j]]},{s[j]:.4f}\n")
n_rows += 1
print(f" top-{a.topk} ({a.topk_method}, ban do id < {a.split_id}): {int(is_q.sum())} node hoi, "
f"{n_rows} dong -> {a.topk_csv}")
return 0

View File

@@ -150,6 +150,12 @@ int main(int argc, char** argv) {
unsigned seed = 1;
double ok_m = 0.5, ok_deg = 10.0;
vslam::GlobalLocalizerConfig cfg;
// Chia MOT phien: ban do tu node id < split_id, hoi bang node >= split_id o
// cho robot quay lai. Scan dung de hoi KHONG gop vao ban do.
int split_id = -1;
// Ung vien VPR (tools/vpr_eval.py --topk-csv): query_id,rank,node_id,sim.
std::string vpr_csv, fusion_csv;
double vpr_radius = 2.5;
for (int i = 1; i < argc; ++i) {
const std::string a = argv[i];
@@ -163,10 +169,16 @@ int main(int argc, char** argv) {
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 == "--split-id") split_id = std::atoi(next().c_str());
else if (a == "--vpr-csv") vpr_csv = next();
else if (a == "--fusion-csv") fusion_csv = next();
else if (a == "--vpr-radius") vpr_radius = 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",
" [--cycles 2] [--seed 1] [--csv out.csv] [--ok-m 0.5] [--ok-deg 10]\n"
" [--split-id N] ban do tu node < N, hoi bang node >= N (cung DB)\n"
" [--vpr-csv F --fusion-csv G [--vpr-radius 2.5]] xac minh ung vien VPR\n",
argv[0]);
return 0;
}
@@ -175,15 +187,40 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "can --map-db\n");
return 2;
}
if (query_db.empty()) {
const bool split = split_id > 0;
if (split) {
if (!query_db.empty() && query_db != map_db) {
std::fprintf(stderr, "--split-id chia MOT DB: bo --query-db\n");
return 2;
}
query_db = map_db;
} else 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");
}
// Pose toi uu cua ban do: de chon node ban do (--split-id), kiem "robot co
// quay lai day khong", va lay vi tri ung vien VPR.
std::map<int, vslam::Pose2D> map_nodes;
{
std::unique_ptr<rtabmap::DBDriver> d(rtabmap::DBDriver::create());
if (d == nullptr || !d->openConnection(map_db, false)) {
std::fprintf(stderr, "khong mo duoc %s\n", map_db.c_str());
return 1;
}
for (const auto& kv : d->loadOptimizedPoses()) {
if (!split || kv.first < split_id) map_nodes[kv.first] = vslam::FromRtabmap(kv.second);
}
d->closeConnection(false);
}
std::set<int> map_ids;
for (const auto& kv : map_nodes) map_ids.insert(kv.first);
// --- 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);
const vslam::StatusResponse st = vslam::ExportOccupancyGridFromDb(
map_db, 0.05, cfg.max_range, &grid, split ? &map_ids : nullptr);
if (!st.ok()) {
std::fprintf(stderr, "xuat luoi tu %s: %s\n", map_db.c_str(), st.message.c_str());
return 1;
@@ -202,7 +239,55 @@ int main(int argc, char** argv) {
}
std::printf("hoi tu %s: %zu node co scan + pose toi uu\n", query_db.c_str(), nodes.size());
if (query_db != map_db) {
if (split) {
// Chi hoi o cho robot QUAY LAI: node >= split_id co node ban do trong 2 m.
std::vector<Node> keep;
for (Node& n : nodes) {
if (n.id < split_id) continue;
bool revisit = false;
for (const auto& kv : map_nodes) {
if (std::hypot(kv.second.x - n.truth.x, kv.second.y - n.truth.y) < 2.0) {
revisit = true;
break;
}
}
if (revisit) keep.push_back(std::move(n));
}
nodes.swap(keep);
n_queries = static_cast<int>(nodes.size());
std::printf("chia tai node %d: ban do %zu node, hoi %zu node o cho quay lai (HET, "
"khong boc ngau nhien)\n", split_id, map_ids.size(), nodes.size());
if (nodes.empty()) return 1;
}
// Ung vien VPR theo tung node hoi.
std::map<int, std::vector<std::pair<int, double>>> vpr;
if (!vpr_csv.empty()) {
FILE* f = std::fopen(vpr_csv.c_str(), "r");
if (f == nullptr) {
std::fprintf(stderr, "khong mo duoc %s\n", vpr_csv.c_str());
return 1;
}
char line[256];
int qid = 0, rank = 0, nid = 0;
double sim = 0.0;
while (std::fgets(line, sizeof(line), f) != nullptr) {
if (std::sscanf(line, "%d,%d,%d,%lf", &qid, &rank, &nid, &sim) == 4) {
vpr[qid].push_back({nid, sim});
}
}
std::fclose(f);
std::printf("VPR: %zu node hoi co ung vien, ban kinh xac minh %.1f m\n", vpr.size(), vpr_radius);
}
FILE* fus = fusion_csv.empty() ? nullptr : std::fopen(fusion_csv.c_str(), "w");
if (fus != nullptr) {
std::fprintf(fus,
"query_id,glob_ok,glob_verdict,glob_ratio,glob_ratio_yaw,glob_s1,glob_x,glob_y,"
"glob_th,truth_x,truth_y,truth_th,rank,vpr_node,vpr_sim,vpr_node_dist_m,"
"loc_score,loc_x,loc_y,loc_th\n");
}
if (!split && 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);
@@ -246,7 +331,7 @@ int main(int argc, char** argv) {
int top1_ok_cnt = 0, top1_total = 0;
for (int q = 0; q < n_queries; ++q) {
size_t idx = pick(rng);
size_t idx = split ? static_cast<size_t>(q) : pick(rng);
vslam::HypothesisTracker tracker(cfg);
vslam::RelocVerdict final_v = vslam::RelocVerdict::kFailed;
bool accepted = false, accepted_ok = false;
@@ -265,6 +350,40 @@ int main(int argc, char** argv) {
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);
// --- Xac minh ung vien VPR (chi vong dau): MOT dong moi ung vien ---
if (fus != nullptr && c == 0) {
const vslam::Pose2D& tru = nodes[last].truth;
const vslam::Pose2D ge = m.ok ? vslam::Pose2DCompose(m.map_from_odom, nodes[last].odom)
: vslam::Pose2D{};
char head[512];
std::snprintf(head, sizeof(head), "%d,%d,%s,%.4f,%.4f,%.2f,%.3f,%.3f,%.4f,%.3f,%.3f,%.4f",
nodes[idx].id, m.ok ? 1 : 0, vslam::RelocVerdictName(v),
m.ok ? m.ratio() : 0.0, m.ok ? m.ratio_yaw() : 0.0, m.s1, ge.x, ge.y,
ge.theta, tru.x, tru.y, tru.theta);
const auto it = vpr.find(nodes[idx].id);
if (it == vpr.end()) {
std::fprintf(fus, "%s,0,-1,0,0,-1,0,0,0\n", head);
} else {
int rank = 0;
for (const auto& cand : it->second) {
++rank;
const auto mp = map_nodes.find(cand.first);
if (mp == map_nodes.end()) continue; // ung vien khong thuoc phan ban do
vslam::Point center;
center.x = mp->second.x;
center.y = mp->second.y;
const vslam::RelocHypothesis h =
vslam::LocalMatch(field, pts, nodes[last].odom, center, vpr_radius, cfg);
const vslam::Pose2D le = h.score > 0.0
? vslam::Pose2DCompose(h.map_from_odom, nodes[last].odom)
: vslam::Pose2D{};
std::fprintf(fus, "%s,%d,%d,%.4f,%.3f,%.2f,%.3f,%.3f,%.4f\n", head, rank, cand.first,
cand.second, std::hypot(center.x - tru.x, center.y - tru.y), h.score,
le.x, le.y, le.theta);
}
}
}
final_v = v;
double err_m = NAN, err_deg = NAN;
@@ -325,6 +444,7 @@ int main(int argc, char** argv) {
}
}
if (csv != nullptr) std::fclose(csv);
if (fus != nullptr) std::fclose(fus);
const int total = n_queries;
std::printf("\n===== %d cau hoi, --seq %d, --cycles %d, dung = < %.2f m & < %.1f do =====\n",