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

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;
}