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

View File

@@ -0,0 +1,510 @@
#include "vslam/global_localizer.h"
#include <algorithm>
#include <cmath>
#include <limits>
#include <unordered_set>
#include "vslam/geometry.h"
namespace vslam {
namespace {
constexpr double kDegToRad = M_PI / 180.0;
// EDT 1D (Felzenszwalb-Huttenlocher): d[i] = min_j (f[j] + (i-j)^2).
// Phan tu f = inf (khong co tuong) KHONG BAO GIO nam tren duong bao duoi, nen
// bo qua han -- de nguyen trong cong thuc giao diem thi ra inf - inf = NaN.
void Edt1d(const std::vector<float>& f, std::vector<float>* d,
std::vector<int>* v, std::vector<double>* z) {
const int n = static_cast<int>(f.size());
const float inf = std::numeric_limits<float>::infinity();
int k = -1;
for (int q = 0; q < n; ++q) {
if (f[q] == inf) continue;
if (k < 0) {
k = 0;
(*v)[0] = q;
(*z)[0] = -std::numeric_limits<double>::infinity();
(*z)[1] = std::numeric_limits<double>::infinity();
continue;
}
double s;
while (true) {
const int p = (*v)[k];
s = ((f[q] + static_cast<double>(q) * q) - (f[p] + static_cast<double>(p) * p)) /
(2.0 * (q - p));
// z[0] = -inf nen k khong bao gio xuong duoi 0.
if (s <= (*z)[k]) { --k; continue; }
break;
}
++k;
(*v)[k] = q;
(*z)[k] = s;
(*z)[k + 1] = std::numeric_limits<double>::infinity();
}
if (k < 0) { // ca hang/cot khong co tuong
for (int q = 0; q < n; ++q) (*d)[q] = inf;
return;
}
k = 0;
for (int q = 0; q < n; ++q) {
while ((*z)[k + 1] < q) ++k;
const int p = (*v)[k];
(*d)[q] = static_cast<float>((q - p) * static_cast<double>(q - p) + f[p]);
}
}
struct Refined {
double score = -1.0;
double x = 0.0, y = 0.0, th = 0.0; // (x, y) tuong doi goc luoi, met
};
// Mot luot luoi (x, y, theta) quanh (x0, y0, th0): x, y trong +-n_xy buoc
// dxy, theta trong +-n_a buoc da. Tinh truc tiep, khong FFT.
Refined SearchGrid(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, int n_xy, double dxy,
int n_a, double da) {
const double res = f.resolution();
Refined best;
std::vector<double> qx(P.size()), qy(P.size());
for (int ia = -n_a; ia <= n_a; ++ia) {
const double th = th0 + ia * da;
const double ct = std::cos(th), st = std::sin(th);
for (size_t i = 0; i < P.size(); ++i) {
qx[i] = ct * P[i].x - st * P[i].y;
qy[i] = st * P[i].x + ct * P[i].y;
}
for (int ix = -n_xy; ix <= n_xy; ++ix) {
const double x = x0 + ix * dxy;
for (int iy = -n_xy; iy <= n_xy; ++iy) {
const double y = y0 + iy * dxy;
double s = 0.0;
for (size_t i = 0; i < P.size(); ++i) {
const int c = static_cast<int>(std::lround((qx[i] + x) / res));
const int r = static_cast<int>(std::lround((qy[i] + y) / res));
s += f.At(r, c);
}
if (s > best.score) best = Refined{s, x, y, th};
}
}
}
return best;
}
// Tinh chinh mot ung vien o do phan giai ban do.
Refined Refine(const LikelihoodField& f, const std::vector<Point>& P,
double x0, double y0, double th0, double rc,
const GlobalLocalizerConfig& cfg) {
const double res = f.resolution();
const double step = cfg.angle_step_deg * kDegToRad;
// Luot 1 = ban ROS: +-nua o tho buoc 2*res, +-mot buoc goc buoc (buoc / 5).
const int n_xy = std::max(1, static_cast<int>(std::lround((rc / 2.0) / (2.0 * res))));
const Refined r1 = SearchGrid(f, P, x0, y0, th0, n_xy, 2.0 * res, 5, step / 5.0);
if (r1.score < 0.0) return r1;
// [vslam] Luot 2 min hon: +-0.1 m buoc res/2, +-(buoc / 5) buoc (buoc / 25).
// Lech 1.5 do o 7 m la 0.19 m ~ 1.3 sigma -- keo diem pose DUNG xuong va lam
// ty le kem tach bach (test tong hop 2026-09-29: sai 1.57 do). Ap cho MOI
// ung vien -- ca doi thu -- de so diem cong bang.
return SearchGrid(f, P, r1.x, r1.y, r1.th, 4, res / 2.0, 5, step / 25.0);
}
} // namespace
// ---------------------------------------------------------------------------
// LikelihoodField
// ---------------------------------------------------------------------------
LikelihoodField LikelihoodField::FromGrid(const OccupancyGrid& g, double sigma) {
LikelihoodField out;
out.width_ = static_cast<int>(g.width);
out.height_ = static_cast<int>(g.height);
out.res_ = g.resolution;
out.ox_ = g.origin.position.x;
out.oy_ = g.origin.position.y;
const size_t n = static_cast<size_t>(out.width_) * out.height_;
out.lf_.assign(n, 0.0f);
out.free_.assign(n, 0);
if (n == 0 || g.data.size() != n) return out;
const float inf = std::numeric_limits<float>::infinity();
std::vector<float> d2(n, inf);
bool any_occ = false;
for (size_t i = 0; i < n; ++i) {
if (g.data[i] >= 50) { d2[i] = 0.0f; any_occ = true; }
out.free_[i] = (g.data[i] == 0) ? 1 : 0;
}
if (!any_occ) return out;
// EDT tach duoc: cot roi hang, don vi o^2.
const int W = out.width_, H = out.height_;
const int m = std::max(W, H);
std::vector<float> f(m), d(m);
std::vector<double> z(m + 1);
std::vector<int> v(m);
for (int c = 0; c < W; ++c) {
f.resize(H); d.resize(H);
for (int r = 0; r < H; ++r) f[r] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int r = 0; r < H; ++r) d2[static_cast<size_t>(r) * W + c] = d[r];
}
for (int r = 0; r < H; ++r) {
f.resize(W); d.resize(W);
for (int c = 0; c < W; ++c) f[c] = d2[static_cast<size_t>(r) * W + c];
Edt1d(f, &d, &v, &z);
for (int c = 0; c < W; ++c) d2[static_cast<size_t>(r) * W + c] = d[c];
}
const double k = (out.res_ * out.res_) / (2.0 * sigma * sigma);
for (size_t i = 0; i < n; ++i) {
out.lf_[i] = static_cast<float>(std::exp(-d2[i] * k));
}
return out;
}
double LikelihoodField::MeanScore(const std::vector<Point>& pts_map,
size_t min_points) const {
double s = 0.0;
size_t cnt = 0;
for (const Point& p : pts_map) {
const int c = static_cast<int>(std::lround((p.x - ox_) / res_));
const int r = static_cast<int>(std::lround((p.y - oy_) / res_));
if (r < 0 || c < 0 || r >= height_ || c >= width_) continue;
s += lf_[static_cast<size_t>(r) * width_ + c];
++cnt;
}
if (cnt < min_points || cnt == 0) return -1.0;
return s / static_cast<double>(cnt);
}
// ---------------------------------------------------------------------------
// Khop toan cuc
// ---------------------------------------------------------------------------
std::vector<Point> DownsamplePoints(const std::vector<Point>& pts, double res,
size_t max_points) {
// Nhieu tia roi vao mot o thi khong them thong tin, chi lam cham.
std::vector<Point> out;
out.reserve(pts.size());
std::unordered_set<uint64_t> seen;
seen.reserve(pts.size() * 2);
for (const Point& p : pts) {
const int64_t kx = static_cast<int64_t>(std::llround(p.x / res));
const int64_t ky = static_cast<int64_t>(std::llround(p.y / res));
const uint64_t key = (static_cast<uint64_t>(kx) << 32) ^
static_cast<uint32_t>(ky);
if (seen.insert(key).second) out.push_back(p);
}
if (max_points > 0 && out.size() > max_points) {
const size_t step = (out.size() + max_points - 1) / max_points;
std::vector<Point> thin;
thin.reserve(out.size() / step + 1);
for (size_t i = 0; i < out.size(); i += step) thin.push_back(out[i]);
out.swap(thin);
}
return out;
}
RelocMatch GlobalMatch(const LikelihoodField& field,
const std::vector<Point>& pts_odom,
const GlobalLocalizerConfig& cfg) {
RelocMatch out;
if (field.empty() || pts_odom.empty()) return out;
const double res = field.resolution();
const std::vector<Point> pts = DownsamplePoints(pts_odom, res, cfg.max_points);
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));
}
// --- 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; };
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);
}
std::sort(peaks.begin(), peaks.end(),
[](const AnglePeak& a, const AnglePeak& b) { return a.score > b.score; });
if (peaks.empty() || peaks[0].score <= 0.0) return out;
// --- Gom TOP-K dinh tho, khu trung trong reject_radius ---
// Xet nhieu dinh chu khong chi cai cao nhat: muc tho dung max-pool nen rat
// rong rai, thu tu o day chua chac dung.
const double rad_c = cfg.reject_radius / rc;
std::vector<AnglePeak> cand;
for (int i = 0; i < std::min<int>(cfg.top_k, static_cast<int>(peaks.size())); ++i) {
const AnglePeak& p = peaks[i];
bool dup = false;
for (const AnglePeak& q : cand) {
const double dr = p.r - q.r, dc = p.c - q.c;
if (dr * dr + dc * dc <= rad_c * rad_c) { dup = true; break; }
}
if (!dup) cand.push_back(p);
if (static_cast<int>(cand.size()) >= cfg.max_candidates) break;
}
// ⚠️ Tinh chinh TUNG ung vien roi moi so diem voi nhau. So o muc tho (co
// max-pool) thi gan nhu moi cho canh tuong deu diem cao -- ban ROS do duoc
// tot/xau chi cach nhau 1.18 lan, cong chan loai ca ca DUNG.
std::vector<Refined> refined;
for (const AnglePeak& p : cand) {
const Refined rf = Refine(field, P, block_center(p.c), block_center(p.r), p.th, rc, cfg);
if (rf.score >= 0.0) refined.push_back(rf);
}
if (refined.empty()) return out;
std::sort(refined.begin(), refined.end(),
[](const Refined& a, const Refined& b) { return a.score > b.score; });
const Refined& best = refined[0];
// --- Doi thu VI TRI ---
// ⚠️ Phai LUON tim duoc, ke ca ngoai top-K. Ban ROS: tren ban do nho ca 8
// ung vien nam gon trong 2 m cua nhau -> s2 = 0 -> ty le len vo cuc va node
// chot bua (9.3% duong tinh gia, sai 9-13 m). Nen quet lai diem THO o vung xa.
double s2 = 0.0;
for (size_t i = 1; i < refined.size(); ++i) {
if (std::hypot(refined[i].x - best.x, refined[i].y - best.y) > cfg.reject_radius) {
s2 = std::max(s2, refined[i].score);
}
}
const int rw = static_cast<int>(std::lround(best.y / res)) / k;
const int cw = static_cast<int>(std::lround(best.x / res)) / k;
auto is_far = [&](int r, int c) {
const double dr = r - rw, dc = c - cw;
return dr * dr + dc * dc > rad_c * rad_c;
};
{
double fv = -1.0;
int fr = -1, fc = -1;
double fth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > fv && is_far(r, c)) { fv = v; fr = r; fc = c; fth = ia * step; }
}
}
}
if (fr >= 0 && fv > 0.0) {
const Refined alt = Refine(field, P, block_center(fc), block_center(fr), fth, rc, cfg);
s2 = std::max(s2, alt.score);
}
}
// --- Doi thu HUONG: CUNG cho, KHAC huong ---
double s2_yaw = 0.0;
{
const double min_sep = cfg.min_angle_sep_deg * kDegToRad;
double gv = -1.0;
int gr = -1, gc = -1;
double gth = 0.0;
for (int ia = 0; ia < n_ang; ++ia) {
const double th = ia * step;
if (std::fabs(AngleDiff(th, best.th)) < min_sep) continue;
const std::vector<float>& sc = scores[ia];
for (int r = 0; r < Hc; ++r) {
for (int c = 0; c < Wc; ++c) {
const float v = sc[static_cast<size_t>(r) * Wc + c];
if (v > gv && !is_far(r, c)) { gv = v; gr = r; gc = c; gth = th; }
}
}
}
if (gr >= 0 && gv > 0.0) {
s2_yaw = Refine(field, P, block_center(gc), block_center(gr), gth, rc, cfg).score;
}
}
// (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});
out.map_from_odom = out.hyps[0].map_from_odom;
out.s1 = best.score;
out.s2 = s2;
out.s2_yaw = s2_yaw;
out.ok = true;
return out;
}
// ---------------------------------------------------------------------------
// Tich luy qua nhieu vong
// ---------------------------------------------------------------------------
//
// Luu T_map_odom chu khong luu pose robot: T_map_odom KHONG doi khi robot di
// (frame odom co dinh), nen khong phai truyen tung gia thuyet theo delta odom
// nhu ban ROS -- chi can ghep voi odom HIEN TAI khi so sanh vi tri.
//
// ⚠️ Khac ban ROS mot cho, co chu y: ban ROS dat lai moc odom MOI vong, ke ca
// vong chua du `acc_min_move` -- nen di cham (moi vong < 0.2 m) thi KHONG bao
// gio cong duoc streak. O day moc chi dat lai khi DA cong: quang duong duoc
// cong don cho toi khi du.
void HypothesisTracker::Add(const RelocMatch& m, const Pose2D& odom_now, double now_s) {
if (!m.ok || m.hyps.empty()) return;
if (!acc_.empty() && now_s - t_prev_ > cfg_.acc_timeout) acc_.clear();
t_prev_ = now_s;
last_odom_ = odom_now;
if (acc_.empty() || !have_odom_) {
acc_.clear();
for (size_t i = 0; i < m.hyps.size(); ++i) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
}
odom_mark_ = odom_now;
have_odom_ = true;
return;
}
// Cung cho -> streak KHONG duoc cong: ban sao doi xung cung lap lai y het.
if (std::hypot(odom_now.x - odom_mark_.x, odom_now.y - odom_mark_.y) < cfg_.acc_min_move) {
for (Entry& e : acc_) e.t_last = now_s;
return;
}
odom_mark_ = odom_now;
const double r2 = cfg_.assoc_radius * cfg_.assoc_radius;
for (size_t i = 0; i < m.hyps.size(); ++i) {
const Pose2D ph = Pose2DCompose(m.hyps[i].map_from_odom, odom_now);
Entry* hit = nullptr;
double bd = r2;
for (Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, odom_now);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; hit = &e; }
}
if (hit == nullptr) {
acc_.push_back({m.hyps[i].map_from_odom, i == 0 ? 1 : 0, now_s});
continue;
}
hit->map_from_odom = m.hyps[i].map_from_odom; // bam theo do do moi nhat
hit->t_last = now_s;
hit->streak = (i == 0) ? hit->streak + 1 : 0;
}
// Bo gia thuyet khong xuat hien lai o vong nay.
acc_.erase(std::remove_if(acc_.begin(), acc_.end(),
[&](const Entry& e) { return e.t_last < now_s; }),
acc_.end());
}
int HypothesisTracker::Streak(const Pose2D& map_from_odom) const {
const Pose2D ph = Pose2DCompose(map_from_odom, last_odom_);
int best = 0;
double bd = cfg_.assoc_radius * cfg_.assoc_radius;
for (const Entry& e : acc_) {
const Pose2D pe = Pose2DCompose(e.map_from_odom, last_odom_);
const double d = (pe.x - ph.x) * (pe.x - ph.x) + (pe.y - ph.y) * (pe.y - ph.y);
if (d < bd) { bd = d; best = e.streak; }
}
return best;
}
// ---------------------------------------------------------------------------
// Cong
// ---------------------------------------------------------------------------
const char* RelocVerdictName(RelocVerdict v) {
switch (v) {
case RelocVerdict::kAccept: return "CHOT";
case RelocVerdict::kNeedCycles: return "DAI_BIEN_CHO_VONG";
case RelocVerdict::kAmbiguous: return "NHAP_NHANG";
case RelocVerdict::kAmbiguousYaw: return "NHAP_NHANG_HUONG";
case RelocVerdict::kFailed: return "THAT_BAI";
}
return "?";
}
RelocVerdict Decide(const RelocMatch& m, int streak, const GlobalLocalizerConfig& cfg) {
if (!m.ok) return RelocVerdict::kFailed;
// Huong truoc: khong co cong nay thi vi tri dung, huong sai 40-160 do ma ty
// le vi tri van 1.6 (ban ROS).
if (m.ratio_yaw() < cfg.min_ratio_yaw) return RelocVerdict::kAmbiguousYaw;
// Hanh lang lap: tra loi sai tu tin te hon nhieu so voi im lang.
if (m.ratio() < cfg.min_ratio) return RelocVerdict::kAmbiguous;
// Dai bien: ty le mot lan khop khong tach duoc dung/sai o day.
if (m.ratio() < cfg.min_ratio_fast && streak < cfg.min_cycles) {
return RelocVerdict::kNeedCycles;
}
return RelocVerdict::kAccept;
}
} // namespace vslam