diff --git a/tools/reloc_fusion_analyze.py b/tools/reloc_fusion_analyze.py index 14cce48..e9d9469 100644 --- a/tools/reloc_fusion_analyze.py +++ b/tools/reloc_fusion_analyze.py @@ -78,7 +78,12 @@ def main(): # Khop cuc bo GIOI HAN HUONG quanh huong node anh VPR (neu CSV co). vscore=float(r.get("vloc_score", -1) or -1), v=(float(r.get("vloc_x", 0) or 0), float(r.get("vloc_y", 0) or 0), - float(r.get("vloc_th", 0) or 0)))) + float(r.get("vloc_th", 0) or 0)), + # GICP 3D xac minh gia thuyet `v` (0 neu bench khong chay --gicp). + g3=dict(ok=r.get("g3_ok") == "1", inl=float(r.get("g3_inl", 0) or 0), + inl0=float(r.get("g3_inl0", 0) or 0), + dz=float(r.get("g3_dz", 0) or 0), tilt=float(r.get("g3_tilt", 0) or 0), + n=int(float(r.get("g3_nsrc", 0) or 0))))) q[qid]["s1"] = float(r["glob_s1"]) def correct(p, t): @@ -195,6 +200,90 @@ def main(): print(f" top-{K} tau {tau:.1f} alpha {alpha:.2f} {len(picks):5d} {ok:5d} {bad:4d} | " f"{uok:21d} {ubad:4d} {100.0 * uok / max(1, n):8.1f}%" + (" ⚠️" if ubad > 0 else "")) + + # --- GICP 3D: bang chung doc lap ve hinh hoc cho gia thuyet cua VPR dan --- + rows3 = [(k, c) for k, cs in cands.items() for c in cs + if c["vscore"] > 0 and c["g3"]["n"] >= 200] + if not rows3: + print("\n(CSV khong co cot g3_* hop le -- chay bench voi --gicp)") + return 0 + + def pct(v, p): + return v[min(len(v) - 1, int(p * len(v)))] if v else float("nan") + + good = sorted(c["g3"]["inl"] for k, c in rows3 if correct(c["v"], q[k]["t"])) + bad = sorted(c["g3"]["inl"] for k, c in rows3 if not correct(c["v"], q[k]["t"])) + print(f"\nGICP 3D: {len(rows3)} gia thuyet co du diem depth. Ty le diem khop trong 10 cm:") + for name, v in (("khi pose vloc DUNG", good), ("khi pose vloc SAI ", bad)): + print(f" {name}: n={len(v):4d} p10 {pct(v, .1):.2f} p50 {pct(v, .5):.2f} p90 {pct(v, .9):.2f}") + print(" (GICP tach duoc khi p10 cua DUNG > p90 cua SAI)") + print(f"\n {'luat GICP':28s} {'chot':>5s} {'DUNG':>5s} {'SAI':>4s} | {'HOP cong LiDAR: DUNG':>21s} {'SAI':>4s} {'dung/tong':>9s}") + for K in (1, 3, 5): + for tau in (0.0, 0.5): + for theta in (0.5, 0.6, 0.7, 0.8): + picks = {} + for k in q: + best_c = None + for c in cands[k]: + g = c["g3"] + if (c["rank"] > K or c["vscore"] <= 0 or c["sim"] < tau or not g["ok"] + or g["n"] < 200 or g["inl"] < theta + or abs(g["dz"]) > 0.15 or g["tilt"] > 3.0): + continue + nxy = pos.get(c["node"]) + if nxy is None or math.hypot(c["v"][0] - nxy[0], c["v"][1] - nxy[1]) >= 2.0: + continue + if best_c is None or g["inl"] > best_c["g3"]["inl"]: + best_c = c + if best_c is not None: + picks[k] = best_c["v"] + ok = sum(1 for k, p in picks.items() if correct(p, q[k]["t"])) + u = dict(picks) + u.update(lidar) + uok = sum(1 for k, p in u.items() if correct(p, q[k]["t"])) + print(f" top-{K} giong>={tau:.1f} khop>={theta:.1f} {len(picks):5d} {ok:5d} {len(picks) - ok:4d} | " + f"{uok:21d} {len(u) - uok:4d} {100.0 * uok / max(1, n):8.1f}%" + + (" ⚠️" if len(u) - uok > 0 else "")) + + # --- Trung khop 3D NGAY TAI pose doan (inl0), KHONG can chinh --- + # Do 2026-09-30 (R3, 249 cau hoi): can chinh GICP 6-DoF tren MOT khung depth + # 69 do troi nghieng/cao (tilt p90 14 do ngay ca o gia thuyet DUNG), keo gia + # thuyet SAI khop vao (inl>=0.5: 52 SAI) va lam 162/872 pose DUNG thanh sai. + # Do ngay tai pose LiDAR+VPR thi tach sach hon han (inl0>=0.5: 617 DUNG / 8 SAI). + good0 = sorted(c["g3"]["inl0"] for k, c in rows3 if correct(c["v"], q[k]["t"])) + bad0 = sorted(c["g3"]["inl0"] for k, c in rows3 if not correct(c["v"], q[k]["t"])) + print("\nTRUNG KHOP 3D TAI pose doan (khong can chinh), ty le diem trong 10 cm:") + for name, v in (("khi pose vloc DUNG", good0), ("khi pose vloc SAI ", bad0)): + print(f" {name}: n={len(v):4d} p10 {pct(v, .1):.2f} p50 {pct(v, .5):.2f} p90 {pct(v, .9):.2f}") + print(f"\n {'luat trung khop 3D':34s} {'chot':>5s} {'DUNG':>5s} {'SAI':>4s} | {'HOP cong LiDAR: DUNG':>21s} {'SAI':>4s} {'dung/tong':>9s}") + for K in (1, 3, 5): + for tau in (0.0, 0.5): + for theta in (0.4, 0.5, 0.6, 0.7): + for alpha in (0.0, 0.9): + picks = {} + for k in q: + best_c = None + for c in cands[k]: + g = c["g3"] + if (c["rank"] > K or c["vscore"] <= 0 or c["sim"] < tau + or g["n"] < 200 or g["inl0"] < theta): + continue + if alpha > 0 and c["vscore"] < alpha * q[k].get("s1", 0.0): + continue + nxy = pos.get(c["node"]) + if nxy is None or math.hypot(c["v"][0] - nxy[0], c["v"][1] - nxy[1]) >= 2.0: + continue + if best_c is None or g["inl0"] > best_c["g3"]["inl0"]: + best_c = c + if best_c is not None: + picks[k] = best_c["v"] + ok = sum(1 for k, p in picks.items() if correct(p, q[k]["t"])) + u = dict(picks) + u.update(lidar) + uok = sum(1 for k, p in u.items() if correct(p, q[k]["t"])) + print(f" top-{K} giong>={tau:.1f} khop>={theta:.1f} alpha>={alpha:.1f} {len(picks):5d} {ok:5d} {len(picks) - ok:4d} | " + f"{uok:21d} {len(u) - uok:4d} {100.0 * uok / max(1, n):8.1f}%" + + (" ⚠️" if len(u) - uok > 0 else "")) return 0 diff --git a/tools/vslam_reloc_bench.cc b/tools/vslam_reloc_bench.cc index 716619f..09fa7e9 100644 --- a/tools/vslam_reloc_bench.cc +++ b/tools/vslam_reloc_bench.cc @@ -26,6 +26,12 @@ #include #include +#include +#include +#include +#include +#include + #include #include #include @@ -36,12 +42,14 @@ #include #include #include +#include #include #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 { @@ -142,6 +150,142 @@ void PrintRange(const char* name, std::vector v) { 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; + +// 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& 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 pts; + vslam::NodeCloudFromSensorData(data, opt_, &pts); + return cache_.emplace(id, std::move(pts)).first->second; + } + + private: + std::unique_ptr driver_; + bool ok_ = false; + vslam::VoxelExportOptions opt_; + std::unordered_map> cache_; +}; + +void AppendNode(const std::vector& 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(p.x + c * pts[i] - s * pts[i + 1]), + static_cast(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 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& nodes, + size_t idx, size_t last, const std::map& 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> 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 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 kd; + kd.setInputCloud(tgt); + auto inlier = [&](const Cloud& c) { + std::vector id(1); + std::vector 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(n) / static_cast(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(std::chrono::steady_clock::now() - t0).count(); + return r; +} + } // namespace int main(int argc, char** argv) { @@ -158,6 +302,9 @@ int main(int argc, char** argv) { 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]; @@ -176,12 +323,16 @@ int main(int argc, char** argv) { 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", + " [--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; } @@ -287,8 +438,28 @@ int main(int argc, char** argv) { 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\n"); + "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 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). @@ -366,7 +537,7 @@ int main(int argc, char** argv) { 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\n", head); + 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) { @@ -389,10 +560,20 @@ int main(int argc, char** argv) { const vslam::Pose2D ve = hv.score > 0.0 ? vslam::Pose2DCompose(hv.map_from_odom, nodes[last].odom) : vslam::Pose2D{}; - std::fprintf(fus, "%s,%d,%d,%.4f,%.3f,%.2f,%.3f,%.3f,%.4f,%.2f,%.3f,%.3f,%.4f\n", head, + Gicp3d g3; + if (gicp && hv.score > 0.0) { + g3 = Verify3d(*mclouds, *qc, nodes, idx, last, map_nodes, ve, gicp_radius, + static_cast(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); } } } @@ -473,5 +654,9 @@ int main(int argc, char** argv) { 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; }