drivers,sim: moi khung anh mot bo dem rieng (sua tranh chap voi SlamLoop o RealSense/sim/replay); sim: IMU dong hoc tu quy dao 6-DoF, tan so phat/tre/bias, ground truth vao .vsr, vslam_record --robot --gt

This commit is contained in:
trung09122002
2026-10-03 18:55:55 +07:00
parent 26ee1a3b72
commit 0dd2546ab1
13 changed files with 845 additions and 51 deletions

View File

@@ -90,6 +90,8 @@ if(VSLAM_BUILD_SIM)
# Dia hinh 3D: doc, san cao, robot di tren mat san, LiDAR tia 3D. Fixture
# test/data/world/ramp.world (mot doc 10 do).
vslam_add_test(test_sim_terrain LIBS vslam_sim vslam_drivers vslam_common)
# IMU mo phong (mo hinh dong hoc, phat thua, tre, bias) va su that 6-DoF.
vslam_add_test(test_sim_imu LIBS vslam_sim vslam_drivers vslam_common)
if(VSLAM_BUILD_ODOMETRY)
# Test TICH HOP: sim -> encoder -> wheel_odom -> EKF, do sai so so voi
# ground truth. Day la bai L2 cua repo cu viet lai khong ROS.

View File

@@ -149,6 +149,35 @@ TEST(RecordIo, RoundTripImuVaEncoder) {
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripGroundTruth) {
// Stream MO RONG cua ban ghi mo phong: tu the THAT 6-DoF de cham diem
// offline. Ten stream phai co, khong thi log replay in "?".
const std::string path = TempPath("gt");
const double pose[6] = {1.5, -2.25, 0.4363, 0.01, -0.1745, 1.5708};
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
std::string p;
EncodeGroundTruthPayload(pose, &p);
w.Write(VsrStream::kGroundTruth, UnixTime::fromSec(200.0), p);
w.Close();
}
RecordReader r;
ASSERT_TRUE(r.Open(path).ok());
VsrChunkHeader h;
std::string payload;
ASSERT_TRUE(r.Next(&h, &payload));
EXPECT_EQ(h.stream, VsrStream::kGroundTruth);
EXPECT_STREQ(VsrStreamName(h.stream), "ground_truth");
double back[6] = {};
ASSERT_TRUE(DecodeGroundTruthPayload(payload, back));
for (int i = 0; i < 6; ++i) EXPECT_DOUBLE_EQ(back[i], pose[i]) << "truong " << i;
r.Close();
std::remove(path.c_str());
}
TEST(RecordIo, RoundTripImage) {
const std::string path = TempPath("img");
std::vector<uint8_t> pixels(320 * 240 * 2);

View File

@@ -5,6 +5,7 @@
#include <cmath>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
#include <unistd.h>
@@ -320,6 +321,66 @@ TEST(ReplaySource, LenhMotorKhiReplayDiVaoHuKhong) {
std::remove(path.c_str());
}
TEST(ReplaySource, AnhCuKhongBiKhungSauGhiDe) {
// Nhu bo mo phong va driver RealSense: anh da phat ra phai giu nguyen noi
// dung du nguon da giai ma them nhieu khung -- SlamLoop giu khung moi nhat
// qua Rtabmap::process tren luong khac. Truoc day ba kho giai ma dung chung.
const std::string path = TempPath("img_hold");
{
RecordWriterConfig c;
c.path = path;
RecordWriter w(c);
ASSERT_TRUE(w.Open().ok());
for (int k = 0; k < 6; ++k) {
const UnixTime stamp = UnixTime::fromSec(1737000000.0 + 0.1 * k);
std::vector<uint8_t> depth(4 * 2 * 2), ir(4 * 2);
for (size_t i = 0; i < depth.size(); ++i) depth[i] = static_cast<uint8_t>(10 * k + i);
for (size_t i = 0; i < ir.size(); ++i) ir[i] = static_cast<uint8_t>(100 + 10 * k + i);
Image d;
d.header.stamp = stamp;
d.width = 4; d.height = 2; d.step = 8;
d.format = PixelFormat::kMono16;
d.depth_scale = 0.001f;
d.data = depth.data();
Image r = d;
r.step = 4;
r.format = PixelFormat::kMono8;
r.data = ir.data();
std::string pd, pr;
EncodeImagePayload(d, &pd);
EncodeImagePayload(r, &pr);
w.Write(VsrStream::kDepth, stamp, pd);
w.Write(VsrStream::kInfra1, stamp, pr);
}
w.Close();
}
ReplayConfig cfg;
cfg.path = path;
cfg.deterministic = true;
ReplaySource rs(cfg);
ASSERT_TRUE(rs.Open().ok());
std::vector<CameraFrame> frames;
std::vector<std::vector<uint8_t>> depth_copy, ir_copy;
rs.camera()->SetCallback([&](const CameraFrame& f) {
frames.push_back(f);
depth_copy.emplace_back(f.depth->data, f.depth->data + 16);
ir_copy.emplace_back(f.infra1->data, f.infra1->data + 8);
});
rs.camera()->Open();
rs.Run();
ASSERT_EQ(frames.size(), 6u);
for (size_t k = 0; k < frames.size(); ++k) {
EXPECT_EQ(std::memcmp(frames[k].depth->data, depth_copy[k].data(), 16), 0)
<< "depth khung " << k << " bi ghi de";
EXPECT_EQ(std::memcmp(frames[k].infra1->data, ir_copy[k].data(), 8), 0)
<< "IR khung " << k << " bi ghi de";
EXPECT_EQ(frames[k].depth->data[0], static_cast<uint8_t>(10 * k));
}
std::remove(path.c_str());
}
TEST(ReplaySource, FileKhongTonTaiThiBaoLoi) {
ReplayConfig cfg;
cfg.path = "/khong/ton/tai/abc.vsr";

308
test/test_sim_imu.cc Normal file
View File

@@ -0,0 +1,308 @@
// IMU mo phong va su that 6-DoF.
//
// ================== VI SAO BAI KIEM NAY TON TAI ==================
// VIO (DM-VIO, F2M co IMU) tin rang tich phan gyro ra dung tu the va tich
// phan gia toc ke (tru trong luc) ra dung quy dao. Mot IMU mo phong noi doi
// mot chut la VIO trong sim "tot" vi ly do sai, hoac "te" vi ly do sai. Mo
// hinh cu chi xap xi (bo gia toc theo phuong dung khi len doc, bo canh tay
// don cua diem dat IMU) -- du cho gravity_align, khong du cho VIO.
//
// Bai nay khoa:
// * tich phan gyro ra DUNG tu the that, ke ca khi quay tren doc;
// * tich phan gia toc ke ra DUNG vi tri that cua diem dat IMU;
// * tan so phat thap (WT61PC 10 Hz) khong keo buoc vat ly theo;
// * do tre: mau phat ra la mau cu, dung bang so buoc;
// * bias dau lam lech gyro nhu cau hinh;
// * su that phat dung tan so; hinh hoc lay dung tu robot.yaml.
#include <gtest/gtest.h>
#include <cmath>
#include <cstdlib>
#include <string>
#include <vector>
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
#include "vslam/sim_source.h"
using namespace vslam;
namespace {
constexpr double kDeg = M_PI / 180.0;
std::string DataDir() {
const char* e = std::getenv("VSLAM_TEST_DATA_DIR");
return e != nullptr ? std::string(e) : std::string("test/data");
}
std::string ConfigSrcDir() {
const char* e = std::getenv("VSLAM_CONFIG_SRC_DIR");
return e != nullptr ? std::string(e) : std::string("configuration_files");
}
// Doc 10 do cua test/data/world/ramp.world, khong nhieu, IMU dong hoc.
SimConfig RampCfg() {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.world_path = DataDir() + "/world/ramp.world";
c.world_model_paths = {DataDir() + "/world/models"};
c.wheel_radius = 0.0865;
c.wheel_separation = 0.40;
c.lidar_x = 0.0;
c.lidar_z = 0.13;
c.lidar_noise_stddev = 0.0;
c.gyro_noise_stddev = 0.0;
c.accel_noise_stddev = 0.0;
c.imu_model = SimConfig::ImuModel::kKinematic;
c.start_x = -2.0;
return c;
}
SimConfig FlatCfg() {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.gyro_noise_stddev = 0.0;
c.accel_noise_stddev = 0.0;
return c;
}
// --- Ma tran 3x3 hang-chinh, chi cho bai kiem ---
struct M3 {
double m[9];
};
M3 FromRPY(double r, double p, double y) {
const double cr = std::cos(r), sr = std::sin(r);
const double cp = std::cos(p), sp = std::sin(p);
const double cy = std::cos(y), sy = std::sin(y);
return M3{{cy * cp, cy * sp * sr - sy * cr, cy * sp * cr + sy * sr,
sy * cp, sy * sp * sr + cy * cr, sy * sp * cr - cy * sr,
-sp, cp * sr, cp * cr}};
}
M3 Mul(const M3& a, const M3& b) {
M3 o{};
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 3; ++j) {
double s = 0.0;
for (int k = 0; k < 3; ++k) s += a.m[i * 3 + k] * b.m[k * 3 + j];
o.m[i * 3 + j] = s;
}
}
return o;
}
// Exp(w) theo Rodrigues.
M3 Exp(double wx, double wy, double wz) {
const double th = std::sqrt(wx * wx + wy * wy + wz * wz);
const M3 K{{0, -wz, wy, wz, 0, -wx, -wy, wx, 0}};
const M3 K2 = Mul(K, K);
const double a = th < 1e-12 ? 1.0 : std::sin(th) / th;
const double b = th < 1e-12 ? 0.5 : (1.0 - std::cos(th)) / (th * th);
M3 o{{1, 0, 0, 0, 1, 0, 0, 0, 1}};
for (int i = 0; i < 9; ++i) o.m[i] += a * K.m[i] + b * K2.m[i];
return o;
}
double AngleBetween(const M3& a, const M3& b) {
double tr = 0.0; // trace(a^T b)
for (int i = 0; i < 3; ++i) {
for (int k = 0; k < 3; ++k) tr += a.m[k * 3 + i] * b.m[k * 3 + i];
}
return std::acos(std::max(-1.0, std::min(1.0, (tr - 1.0) / 2.0)));
}
// Vi tri diem dat IMU theo tu the that, cung quy uoc voi bo mo phong.
void ImuPoint(const SimConfig& c, const SimPose3& p, double out[3]) {
const M3 R = FromRPY(p.roll, p.pitch, p.yaw);
const double v[3] = {c.imu_x, c.imu_y, c.wheel_radius + c.imu_z};
const double base[3] = {p.x, p.y, p.z};
for (int i = 0; i < 3; ++i) {
out[i] = base[i] + R.m[i * 3 + 0] * v[0] + R.m[i * 3 + 1] * v[1] + R.m[i * 3 + 2] * v[2];
}
}
// Lai: tu x = -2 thang len doc (~1.8 m vao doc, z ~0.3 m), roi re trai nhe
// NGAY TREN doc -- doi ca roll lan pitch.
void DriveRampAndTurn(SimSource* sim) {
for (int i = 0; i < 260; ++i) { sim->base()->SetVelocity(0.30, 0.0); sim->RunFor(0.05); }
for (int i = 0; i < 60; ++i) { sim->base()->SetVelocity(0.25, 0.25); sim->RunFor(0.05); }
}
} // namespace
TEST(SimImu, TichPhanGyroRaDungTuThe) {
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
const double dt = 1.0 / RampCfg().imu_rate_hz;
const SimPose3 p0 = sim.ground_truth_3d();
M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw);
sim.mcu()->SetImuCallback([&](ImuPtr m) {
R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt,
m->angular_velocity.z * dt));
});
sim.mcu()->Open();
sim.base()->Open();
DriveRampAndTurn(&sim);
const SimPose3 p1 = sim.ground_truth_3d();
ASSERT_GT(p1.z, 0.2) << "chua len doc";
ASSERT_GT(std::fabs(p1.roll), 0.5 * kDeg) << "chua quay tren doc -- roll khong doi";
EXPECT_LT(AngleBetween(R, FromRPY(p1.roll, p1.pitch, p1.yaw)), 1e-6);
}
TEST(SimImu, TichPhanGiaTocRaDungQuyDao) {
const SimConfig c = RampCfg();
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
const double dt = 1.0 / c.imu_rate_hz;
const SimPose3 p0 = sim.ground_truth_3d();
M3 R = FromRPY(p0.roll, p0.pitch, p0.yaw);
double pos[3];
ImuPoint(c, p0, pos);
double vel[3] = {0.0, 0.0, 0.0};
sim.mcu()->SetImuCallback([&](ImuPtr m) {
// Tu the lay tu tich phan gyro (da kiem o bai tren la dung).
R = Mul(R, Exp(m->angular_velocity.x * dt, m->angular_velocity.y * dt,
m->angular_velocity.z * dt));
const double f[3] = {m->linear_acceleration.x, m->linear_acceleration.y,
m->linear_acceleration.z};
for (int i = 0; i < 3; ++i) {
double a = R.m[i * 3 + 0] * f[0] + R.m[i * 3 + 1] * f[1] + R.m[i * 3 + 2] * f[2];
if (i == 2) a -= kGravity;
vel[i] += a * dt;
pos[i] += vel[i] * dt;
}
});
sim.mcu()->Open();
sim.base()->Open();
DriveRampAndTurn(&sim);
double truth[3];
ImuPoint(c, sim.ground_truth_3d(), truth);
const double err = std::hypot(std::hypot(pos[0] - truth[0], pos[1] - truth[1]),
pos[2] - truth[2]);
EXPECT_LT(err, 1e-3) << "tich phan IMU lech quy dao that " << err << " m";
EXPECT_GT(truth[2], 0.3) << "phai len doc thi bai nay moi kiem gia toc dung";
}
TEST(SimImu, TanSoPhatThapKhongKeoTheoVatLy) {
// WT61PC that phat 10 Hz. Ha tan so PHAT khong duoc keo LiDAR, encoder va
// buoc vat ly xuong theo.
SimConfig c = FlatCfg();
c.imu_output_hz = 10.0;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
int imu = 0, scans = 0, enc = 0;
sim.mcu()->SetImuCallback([&](ImuPtr) { imu++; });
sim.lidar()->SetCallback([&](LaserScanPtr) { scans++; });
sim.base()->SetEncoderCallback([&](const EncoderReading&) { enc++; });
sim.mcu()->Open();
sim.lidar()->Open();
sim.base()->Open();
sim.RunFor(2.0);
EXPECT_EQ(imu, 20);
EXPECT_EQ(scans, 50);
EXPECT_EQ(enc, 100);
}
TEST(SimImu, DoTreLaMauCuDungSoBuoc) {
// Tre 0.05 s o buoc 5 ms: mau phat thu j la mau do o buoc j, phat muon 10
// buoc. Hai lan chay giong het nhau (khong nhieu) nen so duoc tung gia tri.
auto run = [](double delay, std::vector<double>* gz) {
SimConfig c = FlatCfg();
c.imu_delay_sec = delay;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.mcu()->SetImuCallback([gz](ImuPtr m) { gz->push_back(m->angular_velocity.z); });
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.2, 0.6); sim.RunFor(0.05); }
};
std::vector<double> a, b;
run(0.0, &a);
run(0.05, &b);
ASSERT_EQ(a.size() - b.size(), 10u);
for (size_t j = 0; j < b.size(); ++j) {
ASSERT_EQ(b[j], a[j]) << "mau " << j;
}
}
TEST(SimImu, BiasDauLamLechGyroKhiDungYen) {
SimConfig c = FlatCfg();
c.imu_model = SimConfig::ImuModel::kKinematic;
c.gyro_bias_sigma = 0.01;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
std::vector<double> gz;
sim.mcu()->SetImuCallback([&](ImuPtr m) { gz.push_back(m->angular_velocity.z); });
sim.mcu()->Open();
sim.RunFor(1.0);
ASSERT_FALSE(gz.empty());
// Dung yen, khong nhieu: gyro bang dung bias, va bias khac 0.
EXPECT_GT(std::fabs(gz.back()), 1e-5);
for (double v : gz) EXPECT_EQ(v, gz.back());
}
TEST(SimImu, MacDinhWorldPhangGiuMoHinhCu) {
// kAuto khong co dia hinh = mo hinh cu. Hai lan chay (kAuto, kLegacy) phai
// ra cung tung mau -- dieu kien de ban ghi hoi quy khong doi.
auto run = [](SimConfig::ImuModel model, std::vector<double>* v) {
SimConfig c;
c.speed = 0.0;
c.enable_depth_camera = false;
c.imu_model = model;
SimSource sim(c);
ASSERT_TRUE(sim.Open().ok());
sim.mcu()->SetImuCallback([v](ImuPtr m) {
v->push_back(m->linear_acceleration.x);
v->push_back(m->angular_velocity.z);
});
sim.mcu()->Open();
sim.base()->Open();
for (int i = 0; i < 20; ++i) { sim.base()->SetVelocity(0.3, 0.4); sim.RunFor(0.05); }
};
std::vector<double> a, b;
run(SimConfig::ImuModel::kAuto, &a);
run(SimConfig::ImuModel::kLegacy, &b);
EXPECT_EQ(a, b);
}
TEST(SimGroundTruth, PhatDungTanSoVaKhopTuThe) {
SimSource sim(RampCfg());
ASSERT_TRUE(sim.Open().ok());
int every = 0;
SimPose3 last;
sim.SetGroundTruthCallback([&](UnixTime, const SimPose3& p) { every++; last = p; });
sim.RunFor(1.0);
EXPECT_EQ(every, 200); // moi buoc vat ly
const SimPose3 now = sim.ground_truth_3d();
EXPECT_EQ(last.x, now.x);
EXPECT_EQ(last.z, now.z);
int at25 = 0;
sim.SetGroundTruthCallback([&](UnixTime, const SimPose3&) { at25++; }, 25.0);
sim.RunFor(2.0);
EXPECT_EQ(at25, 50);
}
TEST(SimConfigRobot, LayHinhHocRobotThat) {
RobotModel robot;
ASSERT_TRUE(robot.LoadFile(ConfigSrcDir() + "/robot.yaml").ok());
SimConfig c;
SimConfigFromRobot(robot, &c);
EXPECT_NEAR(c.wheel_radius, robot.geometry().wheel_radius, 1e-12);
EXPECT_NEAR(c.wheel_separation, robot.geometry().wheel_separation, 1e-12);
EXPECT_NEAR(c.camera_z, robot.camera_height_above_floor(), 1e-12);
// LiDAR o 0.2165 m tren SAN: tam truc (r banh) + laser_link z.
EXPECT_NEAR(c.wheel_radius + c.lidar_z, 0.2165, 1e-6);
Transform t;
ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kImuFrame, &t));
EXPECT_NEAR(c.imu_z, t.translation.z, 1e-12);
ASSERT_TRUE(robot.StaticTransform(kBaseLinkFrame, kCameraFrame, &t));
EXPECT_NEAR(c.camera_x, t.translation.x, 1e-12);
}

View File

@@ -5,6 +5,7 @@
#include <gtest/gtest.h>
#include <cmath>
#include <cstring>
#include <limits>
#include <vector>
@@ -743,6 +744,37 @@ TEST(SimTilt, TatFollowTerrainThiKhongNghiengTheoDoc) {
EXPECT_NEAR(p, 0.0, 0.02);
}
TEST(SimCamera, KhungCuKhongBiKhungSauGhiDe) {
// SlamLoop giu khung depth moi nhat qua Rtabmap::process (100-600 ms) tren
// luong khac, va BuildSensorData boc cv::Mat quanh bo dem ma khong copy.
// Mot bo dem dung chung thi khung sau ghi de len anh DANG duoc doc -- anh
// luu vao DB la nua khung nay nua khung kia. Moi khung phai co bo dem rieng.
SimSource sim(CamCfg());
ASSERT_TRUE(sim.Open().ok());
sim.base()->Open();
std::vector<CameraFrame> frames;
std::vector<std::vector<uint8_t>> copies;
sim.camera()->SetCallback([&](const CameraFrame& f) {
frames.push_back(f);
const size_t n = static_cast<size_t>(f.depth->step) * f.depth->height;
copies.emplace_back(f.depth->data, f.depth->data + n);
});
sim.camera()->Open();
// Quay tai cho: moi khung nhin mot huong khac.
for (int i = 0; i < 10; ++i) { sim.base()->SetVelocity(0.0, 0.8); sim.RunFor(0.1); }
ASSERT_GE(frames.size(), 10u);
size_t overwritten = 0;
for (size_t i = 0; i < frames.size(); ++i) {
if (std::memcmp(frames[i].depth->data, copies[i].data(), copies[i].size()) != 0) {
overwritten++;
}
}
EXPECT_EQ(overwritten, 0u) << "anh da phat ra bi khung sau ghi de";
// Cac khung phai khac nhau that (robot dang quay), khong thi bai nay khong
// kiem duoc gi.
EXPECT_NE(copies.front(), copies.back());
}
TEST(SimCamera, CAMERA_NGHIENG_THEO_THAN) {
// Camera gan cung vao than. Than ngoc len thi camera nhin xa hon tren san.
// Day la thu lam `cliff_detect` kho: mat phang san ky vong dich theo tung