slam: pose odometry DUNG LUC QUET cho SLAM (noi suy lich su EKF -- luc quay tai cho, ghep scan voi pose hien tai lam lech 0.7 do va xoay ca ban do) + vong dong xa (slam.yaml far_loops, mac dinh bat: node vua tao vs node cu cach >= 100 buoc trong 1 m, ICP xac nhan, addLink) -- sim vong doc 52 m: cuoi vong 17-22 cm -> 1.5 cm

This commit is contained in:
trung09122002
2026-10-04 01:36:35 +07:00
parent f064dcf3ec
commit 6d552e231e
8 changed files with 232 additions and 0 deletions

View File

@@ -625,6 +625,29 @@ StatusResponse LoadAppConfig(const std::string& dir, AppConfig* out) {
}
}
// Khoi `far_loops:` -- vong dong xa luc quet. Vang mat = mac dinh.
if (!root["far_loops"].IsNull()) {
const ConfigNode v = root["far_loops"];
const StatusResponse r =
Reject(v, "slam.yaml far_loops",
{"enabled", "radius_m", "min_graph_gap", "max_corr_m", "max_corr_deg", "period_s"});
if (!r.ok()) return r;
FarLoopsConfig& c = out->far_loops;
c.enabled = v.get<bool>("enabled", c.enabled);
c.radius_m = v.get<double>("radius_m", c.radius_m);
c.min_graph_gap = v.get<int>("min_graph_gap", c.min_graph_gap);
c.max_corr_m = v.get<double>("max_corr_m", c.max_corr_m);
c.max_corr_deg = v.get<double>("max_corr_deg", c.max_corr_deg);
c.period_s = v.get<double>("period_s", c.period_s);
if (c.radius_m <= 0.0 || c.min_graph_gap < 10 || c.max_corr_m <= 0.0 ||
c.max_corr_deg <= 0.0 || c.period_s < 0.0) {
return StatusResponse::Error(
StatusCode::kInvalidArgument,
"slam.yaml far_loops: radius_m > 0, min_graph_gap >= 10, max_corr_m/deg > 0, "
"period_s >= 0");
}
}
// Khoi `slope:` -- di tren doc. Vang mat = tat.
if (!root["slope"].IsNull()) {
const ConfigNode v = root["slope"];

View File

@@ -90,6 +90,17 @@ struct SlopeConfig {
int depth_stride = 4;
};
// Vong dong XA luc quet ban do (RtabmapSlam::TryFarLoopClosure). Doc tu khoi
// `far_loops:` trong slam.yaml.
struct FarLoopsConfig {
bool enabled = true;
double radius_m = 1.0; // node cu trong ban kinh nay (theo do thi)
int min_graph_gap = 100; // cach toi thieu bay nhieu node trong do thi
double max_corr_m = 0.5; // ICP chinh lon hon -> bo (sai cho)
double max_corr_deg = 10.0;
double period_s = 1.0; // toi da 1 lan thu moi chung nay giay
};
struct ThreadConfig {
int safety_priority = 50;
int driver_priority = 45;
@@ -152,6 +163,7 @@ struct AppConfig {
SlamRuntimeConfig slam_runtime;
VoxelConfig voxel;
SlopeConfig slope;
FarLoopsConfig far_loops;
RecordConfig record;
std::string log_level = "info";

View File

@@ -1142,6 +1142,30 @@ void Runtime::SlamLoop() {
// ra de chan.
odom = ekf_->pose();
have_odom = have_odom_;
// Pose LUC QUET, khong phai luc vong nay chay toi (xem odom_hist_ trong
// runtime.h). Noi suy giua hai buoc encoder bao quanh stamp cua scan.
if (scan && !odom_hist_.empty()) {
const UnixTime ts = scan->header.stamp;
const OdomAt* lo = nullptr;
const OdomAt* hi = nullptr;
for (const OdomAt& e : odom_hist_) {
if (SecondsBetween(e.stamp, ts) <= 0.0) lo = &e;
else { hi = &e; break; }
}
if (lo != nullptr && hi != nullptr) {
const double span = SecondsBetween(hi->stamp, lo->stamp);
const double u = span > 0.0 ? SecondsBetween(ts, lo->stamp) / span : 0.0;
odom.x = lo->pose.x + u * (hi->pose.x - lo->pose.x);
odom.y = lo->pose.y + u * (hi->pose.y - lo->pose.y);
odom.theta = NormalizeAngle(lo->pose.theta +
u * NormalizeAngle(hi->pose.theta - lo->pose.theta));
if (slope_on_) z_now = lo->z + u * (hi->z - lo->z);
} else if (hi != nullptr) {
odom = hi->pose; // scan cu hon lich su (hiem): lay pose cu nhat
}
// lo != nullptr && hi == nullptr: scan moi hon buoc encoder cuoi --
// pose hien tai la gan nhat (EKF da cap nhat yaw tu IMU sau do).
}
}
if (!scan || !have_odom ||
@@ -1214,6 +1238,30 @@ void Runtime::SlamLoop() {
// --- KHONG MOT MUTEX NAO duoc giu qua dong nay ---
const SlamOutput out = slam_->Process(in);
// --- Vong dong xa (far_loops), CHI luc quet ---
// Phat hien ke can online cua RTAB-Map chi xet node trong 50 buoc do thi
// (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong dai thi
// khong bao gio noi duoc. O day: node vua tao vs node CU gan nhat theo khong
// gian, ICP xac nhan. Xem RtabmapSlam::TryFarLoopClosure.
if (cfg_->far_loops.enabled && slam_->mode() == SlamMode::kMapping && out.processed) {
const auto now_fl = std::chrono::steady_clock::now();
if (std::chrono::duration<double>(now_fl - far_loops_at_).count() >= cfg_->far_loops.period_s) {
far_loops_at_ = now_fl;
std::string why;
const int r = slam_->TryFarLoopClosure(
cfg_->far_loops.radius_m, cfg_->far_loops.min_graph_gap, cfg_->far_loops.max_corr_m,
cfg_->far_loops.max_corr_deg * M_PI / 180.0, &why);
if (r > 0) {
far_loops_added_++;
VSLAM_INFO("slam: vong dong xa #" << far_loops_added_ << " -- " << why);
std::lock_guard<std::mutex> lk(slam_mu_);
map_correction_ = slam_->map_correction();
} else if (!why.empty()) {
VSLAM_INFO_THROTTLE(10.0, "slam: vong dong xa khong nhan -- " << why);
}
}
}
// --- Di tren doc: z ban do + neo z robot ---
// Do thi z giai lai khi do thi doi (theo nhip, toi da 1 lan/giay -- getGraph
// va giai Cholesky vai ms cho ca nghin node). Neo: z robot keo ve mat san

View File

@@ -28,6 +28,7 @@
#include <atomic>
#include <chrono>
#include <deque>
#include <functional>
#include <memory>
#include <map>
@@ -247,6 +248,17 @@ class Runtime {
mutable std::mutex odom_mu_;
Odometry latest_odom_;
bool have_odom_ = false;
// Lich su pose EKF (moi buoc encoder, ~2 s) de SLAM lay pose DUNG LUC QUET.
// Ghep scan voi pose HIEN TAI thi luc quay tai cho 0.6 rad/s, tre 20 ms la
// lech 0.7 do -- lien ket ICP ke can o cho quay mang lech goc do vao do
// thi va xoay ca ban do (do trong sim doc 04/10: 0.56 do -> 0.2 m sau 20 m
// hanh lang).
struct OdomAt {
UnixTime stamp;
Pose2D pose;
double z = 0.0;
};
std::deque<OdomAt> odom_hist_;
// perc_mu_: ket qua perception.
mutable std::mutex perc_mu_;
@@ -506,6 +518,10 @@ class Runtime {
// CHI luong slam: lan giai do thi z cuoi; da neo z lan nao chua (lan DAU
// sau khoi dong / dinh vi lai thi DAT THANG z ban do, khong qua cong).
bool height_anchored_ = false;
// CHI luong slam: lan thu vong dong xa cuoi (far_loops).
std::chrono::steady_clock::time_point far_loops_at_{};
uint64_t far_loops_added_ = 0;
uint64_t heights_version_ = 0;
std::chrono::steady_clock::time_point heights_at_{};

View File

@@ -207,6 +207,12 @@ StatusResponse Runtime::Wire() {
std::lock_guard<std::mutex> lk2(elev_mu_);
elev_->AddFootprint(p.x, p.y, height_->z(), 0.15, e.stamp);
}
// Lich su pose cho SLAM (pose LUC QUET, xem runtime.h).
odom_hist_.push_back(OdomAt{e.stamp, ekf_->pose(), slope_on_ ? height_->z() : 0.0});
while (odom_hist_.size() > 2 &&
SecondsBetween(e.stamp, odom_hist_.front().stamp) > 2.0) {
odom_hist_.pop_front();
}
}
gyro_dtheta_ = 0.0;
gyro_dt_ = 0.0;

View File

@@ -170,6 +170,32 @@ voxel:
# Tuong va ban ghe dung yen thi nhieu node thay nen van giu.
min_node_hits: 3
# ============ VONG DONG XA (chi khi quet) ============
# Phat hien ke can cua RTAB-Map chi xet node trong 50 buoc do thi
# (RGBD/ProximityMaxGraphDepth), nen quay lai cho cu sau mot vong DAI thi
# khong bao gio noi duoc -- sai so cuoi vong o lai trong ban do. Khoi nay: sau
# moi node, tim node CU (cach >= min_graph_gap buoc) trong ban kinh radius_m
# theo do thi, ICP giua hai scan (Icp/* cua chinh ban do), nhan neu chinh <
# max_corr, them lien ket.
#
# Do trong sim (slope_test, vong 52 m, 04/10):
# khong co (cu) cuoi vong lech 11.7 cm
# RGBD/ProximityMaxGraphDepth 0 van 0 lien ket ve dau vong
# detectMoreLoopClosures cua RTAB-Map TE HON: 33 cm -- them hang tram
# lien ket giua node CUNG luot trong hanh lang, ICP khong rang buoc doc
# truc keo ban do truot
# far_loops (khoi nay) 1.5 cm, 2 lien ket
#
# Ban kinh 1 m: chi ghep node ma do thi DA cho la cung cho -- khong tao vong
# giua hai noi khac nhau tru khi ban do da vo san. Tat: enabled: false.
far_loops:
enabled: true
radius_m: 1.0
min_graph_gap: 100 # ~10 m quang duong o RGBD/LinearUpdate 0.1
max_corr_m: 0.5
max_corr_deg: 10.0
period_s: 1.0
# ============ DI TREN DOC (G4) ============
# Pose SLAM van la SE(2) (Reg/Force3DoF). Khoi nay them, BEN CANH no:
# * z robot = tich -ds*sin(pitch IMU), kep ve 0 khi |pitch| < clamp_deg, neo

View File

@@ -116,6 +116,19 @@ class RtabmapSlam {
// O 2D noi camera thay mat san trong lan ExportVoxels cuoi (che do doc).
const std::vector<uint64_t>& floor_cells() const;
// Vong dong XA: node vua tao vs node CU (cach >= min_graph_gap buoc trong do
// thi) nam trong ban kinh `radius_m` theo do thi da toi uu -- tuc lan di
// TRUOC qua cung cho. Dang ky ICP giua hai scan (tham so Icp/* cua chinh ban
// do); nhan neu ICP dat va chinh so voi do thi < max_corr; them lien ket.
//
// KHONG ghep node cung mot luot di: lien ket ICP trong hanh lang khong rang
// buoc doc truc va keo ban do truot (do trong sim 04/10: detectMoreLoopClosures
// cua RTAB-Map them hang tram lien ket nhu vay, sai 12 cm -> 33 cm).
// Tra 1 = da them, 0 = khong co ung vien / ICP khong dat, -1 = loi. `detail`:
// ly do. CHI luong slam, CHI che do mapping.
int TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail);
StatusResponse Close(bool save_database);
const SlamStats& stats() const;

View File

@@ -3,12 +3,14 @@
#include <rtabmap/core/Memory.h>
#include <rtabmap/core/Optimizer.h>
#include <rtabmap/core/Parameters.h>
#include <rtabmap/core/RegistrationIcp.h>
#include <rtabmap/core/Rtabmap.h>
#include <rtabmap/core/SensorData.h>
#include <rtabmap/core/Statistics.h>
#include <rtabmap/utilite/ULogger.h>
#include <algorithm>
#include <cmath>
#include <chrono>
#include <mutex>
#include <set>
@@ -416,6 +418,92 @@ void RtabmapSlam::SetUseHeights(bool on) { impl_->use_heights = on; }
const std::vector<uint64_t>& RtabmapSlam::floor_cells() const { return impl_->floor_cells; }
int RtabmapSlam::TryFarLoopClosure(double radius_m, int min_graph_gap, double max_corr_m,
double max_corr_rad, std::string* detail) {
if (!impl_->inited || impl_->cfg.mode != SlamMode::kMapping) return 0;
const int cur = impl_->rtabmap.getLastLocationId();
const std::map<int, rtabmap::Transform>& poses = impl_->rtabmap.getLocalOptimizedPoses();
const auto itc = poses.find(cur);
if (cur <= 0 || itc == poses.end() || itc->second.isNull()) return 0;
// Ung vien: node CU (thu tu id = thu tu thoi gian), gan nhat trong ban kinh.
std::vector<int> ids;
ids.reserve(poses.size());
for (const auto& kv : poses) ids.push_back(kv.first);
const long ci = std::lower_bound(ids.begin(), ids.end(), cur) - ids.begin();
int cand = 0;
double best = radius_m;
for (long i = 0; i + min_graph_gap < ci; ++i) {
const rtabmap::Transform& p = poses.at(ids[static_cast<size_t>(i)]);
if (p.isNull()) continue;
const double d = std::hypot(p.x() - itc->second.x(), p.y() - itc->second.y());
if (d <= best) {
best = d;
cand = ids[static_cast<size_t>(i)];
}
}
if (cand == 0) return 0;
const rtabmap::Memory* mem = impl_->rtabmap.getMemory();
if (mem == nullptr) return -1;
const std::multimap<int, rtabmap::Link> links = mem->getLinks(cur);
if (links.find(cand) != links.end()) return 0; // da noi roi
try {
rtabmap::SensorData a = mem->getNodeData(cur, false, true, false, false);
rtabmap::SensorData b = mem->getNodeData(cand, false, true, false, false);
a.uncompressData();
b.uncompressData();
if (a.laserScanRaw().isEmpty() || b.laserScanRaw().isEmpty()) {
if (detail != nullptr) *detail = "node khong co scan";
return 0;
}
const rtabmap::Transform guess = itc->second.inverse() * poses.at(cand);
rtabmap::RegistrationIcp reg(impl_->rtabmap.getParameters());
rtabmap::RegistrationInfo info;
const rtabmap::Transform t = reg.computeTransformation(a, b, guess, &info);
if (t.isNull()) {
if (detail != nullptr) *detail = "ICP tu choi: " + info.rejectedMsg;
return 0;
}
const rtabmap::Transform corr = guess.inverse() * t;
const double ct = std::hypot(corr.x(), corr.y());
const double cr = std::fabs(corr.theta());
if (ct > max_corr_m || cr > max_corr_rad) {
if (detail != nullptr) {
*detail = "chinh qua lon (" + std::to_string(ct) + " m, " + std::to_string(cr) + " rad)";
}
return 0;
}
// Thong tin = nghich dao hiep phuong sai ICP, chan duoi phuong sai de
// khong co truc nao "chac tuyet doi".
cv::Mat inf = cv::Mat::eye(6, 6, CV_64FC1);
for (int k = 0; k < 6; ++k) {
const double v = info.covariance.empty() ? 1e-4 : info.covariance.at<double>(k, k);
inf.at<double>(k, k) = 1.0 / std::max(v, 1e-6);
}
if (!impl_->rtabmap.addLink(rtabmap::Link(cur, cand, rtabmap::Link::kUserClosure, t, inf))) {
if (detail != nullptr) *detail = "addLink tu choi";
return 0;
}
if (detail != nullptr) {
*detail = "noi " + std::to_string(cur) + " -> " + std::to_string(cand) + " (cach " +
std::to_string(ci - (std::lower_bound(ids.begin(), ids.end(), cand) - ids.begin())) +
" node, " + std::to_string(best) + " m), chinh " + std::to_string(ct) + " m / " +
std::to_string(cr * 180.0 / M_PI) + " do, ti le khop " +
std::to_string(info.icpInliersRatio);
}
} catch (const std::exception& e) {
if (detail != nullptr) *detail = std::string("nem: ") + e.what();
return -1;
}
std::lock_guard<std::mutex> lk(impl_->out_mu);
impl_->map_correction = FromRtabmap(impl_->rtabmap.getMapCorrection());
impl_->map_version++;
impl_->stats.loop_closures++;
return 1;
}
const FloorModel& RtabmapSlam::floor_model() const { return impl_->floor; }
StatusResponse RtabmapSlam::UpdateHeights(const ZGraphConfig& cfg, size_t* nodes_out) {