Files
vslam_cpp/tools/vslam_reloc_bench.cc

663 lines
27 KiB
C++

// 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 <pcl/filters/voxel_grid.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/registration/gicp.h>
#include <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <string>
#include <unordered_map>
#include <vector>
#include "vslam/geometry.h"
#include "vslam/global_localizer.h"
#include "vslam/occupancy_export.h"
#include "vslam/sensor_data_builder.h"
#include "vslam/voxel_export.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());
}
// ============ XAC MINH 3D BANG GICP (--gicp) ============
// VPR chon CHO, khop LiDAR cuc bo cho POSE; GICP hoi them: may depth cua node
// hoi, dat vao pose do, co trung voi may depth cua ban do quanh do khong. Bang
// chung DOC LAP voi LiDAR: nhin do dac 3D (ban, tu, cot) chu khong chi tuong o
// 0.22 m.
using Cloud = pcl::PointCloud<pcl::PointXYZ>;
// Diem 3D cua node (frame base, z tinh tu SAN -- calib trong DB da gom nghieng +
// nang banh) tu depth trong DB. Cache theo id: mot node ban do phuc vu nhieu
// ung vien.
class NodeClouds {
public:
explicit NodeClouds(const std::string& db) : driver_(rtabmap::DBDriver::create()) {
ok_ = driver_ != nullptr && driver_->openConnection(db, false);
opt_.emit_size_m = 0.08;
opt_.z_min = 0.10; // bo san: san chi rang buoc z/nghieng, khong rang buoc x, y, yaw
opt_.z_max = 1.80;
opt_.depth_min_m = 0.30;
opt_.depth_max_m = 4.0;
opt_.depth_decimation = 2;
}
~NodeClouds() {
if (ok_) driver_->closeConnection(false);
}
bool ok() const { return ok_; }
const std::vector<float>& Get(int id) {
auto it = cache_.find(id);
if (it != cache_.end()) return it->second;
rtabmap::SensorData data;
driver_->getNodeData(id, data, true, false, false, false); // chi anh + calib
data.uncompressData();
std::vector<float> pts;
vslam::NodeCloudFromSensorData(data, opt_, &pts);
return cache_.emplace(id, std::move(pts)).first->second;
}
private:
std::unique_ptr<rtabmap::DBDriver> driver_;
bool ok_ = false;
vslam::VoxelExportOptions opt_;
std::unordered_map<int, std::vector<float>> cache_;
};
void AppendNode(const std::vector<float>& pts, const vslam::Pose2D& p, Cloud* out) {
const double c = std::cos(p.theta), s = std::sin(p.theta);
for (size_t i = 0; i + 2 < pts.size(); i += 3) {
out->push_back(pcl::PointXYZ(static_cast<float>(p.x + c * pts[i] - s * pts[i + 1]),
static_cast<float>(p.y + s * pts[i] + c * pts[i + 1]),
pts[i + 2]));
}
}
Cloud::Ptr Downsample(const Cloud::Ptr& in, float leaf) {
Cloud::Ptr out(new Cloud);
pcl::VoxelGrid<pcl::PointXYZ> vg;
vg.setInputCloud(in);
vg.setLeafSize(leaf, leaf, leaf);
vg.filter(*out);
return out;
}
struct Gicp3d {
bool ok = false;
vslam::Pose2D pose; // pose node hoi trong map SAU tinh chinh
double inl0 = 0.0, inl = 0.0; // ty le diem nguon trong 10 cm cua dich: truoc / sau
double fit = NAN, dz = 0.0, tilt_deg = 0.0, ms = 0.0;
size_t n_src = 0, n_tgt = 0;
};
// Xac minh gia thuyet `hyp` (pose node hoi `last` trong map): GICP giua may depth
// cua node hoi [idx..last] va may depth cua node ban do trong `radius` quanh `hyp`.
Gicp3d Verify3d(NodeClouds& maps, NodeClouds& queries, const std::vector<Node>& nodes,
size_t idx, size_t last, const std::map<int, vslam::Pose2D>& map_nodes,
const vslam::Pose2D& hyp, double radius, size_t max_nodes) {
Gicp3d r;
const auto t0 = std::chrono::steady_clock::now();
Cloud::Ptr src_raw(new Cloud), tgt_raw(new Cloud);
for (size_t j = idx; j <= last; ++j) {
const vslam::Pose2D rel = vslam::Pose2DBetween(nodes[last].odom, nodes[j].odom);
AppendNode(queries.Get(nodes[j].id), vslam::Pose2DCompose(hyp, rel), src_raw.get());
}
std::vector<std::pair<double, int>> close_nodes;
for (const auto& kv : map_nodes) {
const double d = std::hypot(kv.second.x - hyp.x, kv.second.y - hyp.y);
if (d < radius) close_nodes.push_back({d, kv.first});
}
std::sort(close_nodes.begin(), close_nodes.end());
if (close_nodes.size() > max_nodes) close_nodes.resize(max_nodes);
for (const auto& nd : close_nodes) {
AppendNode(maps.Get(nd.second), map_nodes.at(nd.second), tgt_raw.get());
}
if (src_raw->size() < 200 || tgt_raw->size() < 500) return r;
const Cloud::Ptr src = Downsample(src_raw, 0.10f);
const Cloud::Ptr tgt = Downsample(tgt_raw, 0.10f);
r.n_src = src->size();
r.n_tgt = tgt->size();
if (r.n_src < 200 || r.n_tgt < 500) return r;
try {
pcl::GeneralizedIterativeClosestPoint<pcl::PointXYZ, pcl::PointXYZ> gicp;
gicp.setInputSource(src);
gicp.setInputTarget(tgt);
gicp.setMaxCorrespondenceDistance(0.5); // chi TINH CHINH quanh gia thuyet
gicp.setMaximumIterations(30);
gicp.setTransformationEpsilon(1e-6);
Cloud aligned;
gicp.align(aligned);
r.ok = gicp.hasConverged();
r.fit = gicp.getFitnessScore(0.3);
pcl::KdTreeFLANN<pcl::PointXYZ> kd;
kd.setInputCloud(tgt);
auto inlier = [&](const Cloud& c) {
std::vector<int> id(1);
std::vector<float> d2(1);
size_t n = 0;
for (const pcl::PointXYZ& p : c.points) {
if (kd.nearestKSearch(p, 1, id, d2) > 0 && d2[0] < 0.01f) ++n; // 10 cm
}
return c.points.empty() ? 0.0 : static_cast<double>(n) / static_cast<double>(c.points.size());
};
r.inl0 = inlier(*src);
r.inl = inlier(aligned);
const Eigen::Matrix4f T = gicp.getFinalTransformation(); // hieu chinh trong frame map
const double dyaw = std::atan2(T(1, 0), T(0, 0));
const double cy = std::cos(dyaw), sy = std::sin(dyaw);
r.pose.x = cy * hyp.x - sy * hyp.y + T(0, 3);
r.pose.y = sy * hyp.x + cy * hyp.y + T(1, 3);
r.pose.theta = vslam::NormalizeAngle(hyp.theta + dyaw);
r.dz = T(2, 3);
r.tilt_deg = std::acos(std::max(-1.0f, std::min(1.0f, T(2, 2)))) * 180.0 / M_PI;
} catch (const std::exception&) {
r.ok = false;
}
r.ms = std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0).count();
return r;
}
} // 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;
// 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;
// Cua so huong quanh huong node anh VPR cho lan khop cuc bo THU HAI (vloc).
double vpr_yaw_deg = 45.0;
bool gicp = false; // xac minh gia thuyet vloc bang may depth (GICP)
double gicp_radius = 3.0;
int gicp_nodes = 40;
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 == "--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 == "--vpr-yaw-deg") vpr_yaw_deg = std::atof(next().c_str());
else if (a == "--gicp") gicp = true;
else if (a == "--gicp-radius") gicp_radius = std::atof(next().c_str());
else if (a == "--gicp-nodes") gicp_nodes = std::max(1, std::atoi(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"
" [--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"
" [--gicp [--gicp-radius 3.0] [--gicp-nodes 40]] them xac minh GICP 3D\n",
argv[0]);
return 0;
}
}
if (map_db.empty()) {
std::fprintf(stderr, "can --map-db\n");
return 2;
}
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, 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;
}
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 (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,vloc_score,vloc_x,vloc_y,vloc_th,"
"g3_ok,g3_x,g3_y,g3_th,g3_inl0,g3_inl,g3_fit,g3_dz,g3_tilt,g3_nsrc,g3_ntgt,g3_ms\n");
}
// Mot DB (--split-id) thi hai phia dung chung MOT cache: node hoi va node ban
// do deu doc tu cung file.
std::unique_ptr<NodeClouds> mclouds, qclouds;
NodeClouds* qc = nullptr;
if (gicp) {
if (fus == nullptr || vpr.empty()) {
std::fprintf(stderr, "--gicp can --vpr-csv va --fusion-csv\n");
return 2;
}
mclouds.reset(new NodeClouds(map_db));
if (!mclouds->ok()) return 1;
qc = mclouds.get();
if (query_db != map_db) {
qclouds.reset(new NodeClouds(query_db));
if (!qclouds->ok()) return 1;
qc = qclouds.get();
}
}
int g3_ran = 0, g3_empty = 0;
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);
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 = 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;
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);
// --- 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,-1,0,0,0%s\n", head, ",0,0,0,0,0,0,0,0,0,0,0,0");
} 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{};
// Lan hai: HUONG do anh VPR chon (+-vpr_yaw_deg quanh huong node
// anh), LiDAR chi chinh vi tri/huong trong cua so do.
const vslam::RelocHypothesis hv = vslam::LocalMatch(
field, pts, nodes[last].odom, center, vpr_radius, cfg, mp->second.theta,
vpr_yaw_deg * M_PI / 180.0);
const vslam::Pose2D ve = hv.score > 0.0
? vslam::Pose2DCompose(hv.map_from_odom, nodes[last].odom)
: vslam::Pose2D{};
Gicp3d g3;
if (gicp && hv.score > 0.0) {
g3 = Verify3d(*mclouds, *qc, nodes, idx, last, map_nodes, ve, gicp_radius,
static_cast<size_t>(gicp_nodes));
if (g3.n_src >= 200 && g3.n_tgt >= 500) ++g3_ran; else ++g3_empty;
}
std::fprintf(fus, "%s,%d,%d,%.4f,%.3f,%.2f,%.3f,%.3f,%.4f,%.2f,%.3f,%.3f,%.4f", head,
rank, cand.first, cand.second,
std::hypot(center.x - tru.x, center.y - tru.y), h.score, le.x, le.y,
le.theta, hv.score, ve.x, ve.y, ve.theta);
std::fprintf(fus, ",%d,%.3f,%.3f,%.4f,%.3f,%.3f,%.5f,%.3f,%.2f,%zu,%zu,%.0f\n",
g3.ok ? 1 : 0, g3.pose.x, g3.pose.y, g3.pose.theta, g3.inl0, g3.inl,
std::isfinite(g3.fit) ? g3.fit : 0.0, g3.dz, g3.tilt_deg, g3.n_src,
g3.n_tgt, g3.ms);
}
}
}
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);
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",
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()));
if (gicp) {
std::printf(" GICP 3D: %d gia thuyet chay, %d thieu diem depth%s\n", g3_ran, g3_empty,
g3_ran == 0 ? " -- RTAB-Map 0.21 khong doc duoc camera model cua DB 0.23?" : "");
}
return 0;
}