Files
vslam_cpp/tools/vslam_replay.cc
trung09122002 48bd5377dc upload
2026-09-18 18:14:42 +07:00

411 lines
13 KiB
C++

// Phat lai mot ban ghi `.vsr` qua TOAN BO duong ong, roi xuat mot ban tom tat
// JSON PHANG. Tuy chon: so voi mot file ky vong theo dung sai.
//
// ================== VI SAO JSON PHANG ==================
// Chi khoa -> so vo huong. Khong long nhau, khong mang. Nho vay phep so sanh
// la mot vong lap 20 dong dung CHINH `JsonGetNumber` ma lop xac thuc web
// dung -- khong them thu vien JSON, khong them Python, va khong co cho nao de
// hai cach doc cung mot file lech nhau.
//
// ================== NGUON KHONG PHAN BIET DUOC ==================
// `ReplaySource` implement CHINH cac interface driver ma `SimSource` va phan
// cung that implement. Khong co nhanh `if (replay)` nao trong logic duoi day.
// Do la loi ich kien truc lon nhat cua interface + factory.
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <vector>
#include "vslam/ekf_se2.h"
#include "vslam/geometry.h"
#include "vslam/json_parse.h"
#include "vslam/node_constants.h"
#include "vslam/robot_model.h"
#include "vslam/perception_pipeline.h"
#include "vslam/replay_source.h"
#include "vslam/safety_monitor.h"
#include "vslam/wheel_odometry.h"
namespace {
// Ban tom tat: khoa -> so. Giu thu tu chen de file de doc.
class Summary {
public:
void Set(const std::string& k, double v) {
auto it = index_.find(k);
if (it == index_.end()) {
index_[k] = order_.size();
order_.emplace_back(k, v);
} else {
order_[it->second].second = v;
}
}
void Add(const std::string& k, double d) {
auto it = index_.find(k);
if (it == index_.end()) Set(k, d);
else order_[it->second].second += d;
}
const std::vector<std::pair<std::string, double>>& items() const { return order_; }
std::string ToJson(const std::string& scenario) const {
std::ostringstream o;
o << "{\n \"scenario\": \"" << scenario << "\"";
for (const auto& kv : order_) {
// %.6g giu du y nghia ma khong in ra rac cua dau phay dong. So sanh van
// theo dung sai chu khong theo van ban, nhung file phai doc duoc bang mat.
char buf[64];
std::snprintf(buf, sizeof(buf), "%.6g", kv.second);
o << ",\n \"" << kv.first << "\": " << buf;
}
o << "\n}\n";
return o.str();
}
private:
std::vector<std::pair<std::string, double>> order_;
std::map<std::string, size_t> index_;
};
// Dung sai theo TIEN TO khoa.
//
// Mot dung sai duy nhat cho moi thu la sai: so dem phai khop TUYET DOI (lech
// mot khung nghia la duong di qua code da doi), con pose thi khong bao gio
// khop bit-for-bit qua cac muc toi uu hay cac phien ban libm.
struct Tol {
const char* prefix;
double abs_tol;
double rel_tol;
};
const Tol kTolerances[] = {
{"n_", 0.0, 0.0}, // so dem: khop chinh xac
{"count_", 0.0, 0.0}, // so dem theo nhanh: khop chinh xac
{"pose_", 0.002, 0.0}, // met
{"dist_", 0.002, 0.0},
{"yaw_", 0.001, 0.0}, // rad
{"metric_", 0.01, 0.0},
{"", 0.005, 1e-6}, // con lai
};
const Tol& ToleranceFor(const std::string& key) {
for (const Tol& t : kTolerances) {
const size_t n = std::strlen(t.prefix);
if (n == 0) return t;
if (key.size() >= n && key.compare(0, n, t.prefix) == 0) return t;
}
return kTolerances[0];
}
std::string ReadFile(const std::string& path) {
std::ifstream f(path);
if (!f) return "";
std::ostringstream o;
o << f.rdbuf();
return o.str();
}
// Dem so khoa o muc goc cua mot JSON phang. Dung de phat hien khoa BIEN MAT:
// mot nhanh ngung chay cung la hoi quy, va so sanh theo tung khoa mot khong
// bat duoc dieu do.
size_t CountKeys(const std::string& json) {
size_t n = 0;
bool in_str = false;
for (size_t i = 0; i < json.size(); ++i) {
const char c = json[i];
if (c != '"') continue;
if (i > 0 && json[i - 1] == '\\') continue;
if (in_str) {
// Chuoi vua ket thuc: no la mot KHOA neu ky tu khong-trang tiep theo la
// dau hai cham.
const size_t j = json.find_first_not_of(" \t\r\n", i + 1);
if (j != std::string::npos && json[j] == ':') n++;
}
in_str = !in_str;
}
return n;
}
} // namespace
int main(int argc, char** argv) {
std::string in, expect, emit;
bool quiet = false;
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 == "--in") in = next();
else if (a == "--expect") expect = next();
else if (a == "--emit") emit = next();
else if (a == "--quiet") quiet = true;
else if (a == "--help") {
std::printf("cach dung: %s --in X.vsr [--expect X.json] [--emit X.json] [--quiet]\n",
argv[0]);
return 0;
}
}
if (in.empty()) {
std::fprintf(stderr, "can --in\n");
return 2;
}
// --- Nguon ---
vslam::ReplayConfig rc;
rc.path = in;
// TAT DINH: khong ngu theo dong ho tuong, xu ly dung thu tu stamp. Day la
// dieu kien de hai lan chay cho ra cung mot ket qua -- neu khong thi moi
// khac biet deu la nhieu va bo hoi quy vo dung.
rc.deterministic = true;
rc.apply_sanitizer = true;
constexpr double kPi = 3.14159265358979323846;
rc.sanitizer.range_min = 0.05;
rc.sanitizer.range_max = 40.0;
rc.sanitizer.sector_masks.push_back(vslam::SectorMask{118.0 * kPi / 180.0, kPi});
rc.sanitizer.sector_masks.push_back(vslam::SectorMask{-kPi, -118.0 * kPi / 180.0});
vslam::ReplaySource src(rc);
const vslam::StatusResponse st = src.Open();
if (!st.ok()) {
std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str());
return 1;
}
std::string scenario = "?";
vslam::JsonGetString(src.recorded_config_json(), "scenario", &scenario);
// --- Duong ong, DUNG cac lop se chay tren robot that ---
// Hinh hoc lay tu robot.yaml, KHONG go tay o day.
//
// Truoc khi co RobotModel, phep dung `cam_to_base` bi lap lai o bon file va
// `nominal_tz` da lech (0.803 vs 0.80). Gio no la HE QUA cua camera_link.z
// cong wheel_radius, doc tu mot nguon duy nhat.
vslam::RobotModel robot;
{
const vslam::StatusResponse rs =
robot.LoadFile(vslam::ConfigPath(vslam::kRobotConfigFile));
if (!rs.ok()) {
std::fprintf(stderr, "robot.yaml: %s\n", rs.message.c_str());
return 1;
}
}
vslam::Transform cam_to_base;
if (!robot.StaticTransform(vslam::kBaseLinkFrame,
vslam::kCameraDepthOpticalFrame, &cam_to_base)) {
std::fprintf(stderr, "robot.yaml: khong co duong camera -> base_link\n");
return 1;
}
vslam::PerceptionConfig pc;
pc.cliff.nominal_tz = robot.camera_height_above_floor();
pc.cliff.wheel_radius = robot.geometry().wheel_radius;
pc.gravity.wheel_radius = robot.geometry().wheel_radius;
pc.filter.max_rate = 0.0;
pc.enable_cloud = false; // hoi quy chi can co-vuc/khong, khong can cloud
vslam::PerceptionPipeline perception(pc, *src.clock());
perception.SetCameraExtrinsic(cam_to_base);
vslam::WheelOdometryConfig wo_cfg;
wo_cfg.wheel_radius = robot.geometry().wheel_radius;
wo_cfg.wheel_separation = robot.geometry().wheel_separation;
vslam::WheelOdometry wheel_odom(wo_cfg);
vslam::EkfSe2 ekf;
vslam::SafetyMonitor safety;
Summary s;
vslam::LaserScanPtr last_scan;
vslam::UnixTime last_scan_stamp;
bool cliff_flag = false;
vslam::UnixTime cliff_stamp;
bool have_cliff = false;
std::string cliff_detail = "judged";
double max_slip = 0.0;
src.lidar()->SetCallback([&](vslam::LaserScanPtr sc) {
last_scan = sc;
last_scan_stamp = sc->header.stamp;
s.Add("n_scan", 1);
});
std::map<std::string, double> us_map;
vslam::UnixTime us_stamp;
bool have_us = false;
bool bumper = false;
vslam::UnixTime bumper_stamp;
bool have_bumper = false;
src.mcu()->SetUltrasonicCallback([&](const vslam::UltrasonicReading& u) {
s.Add("n_ultrasonic", 1);
us_map.clear();
for (size_t i = 0; i < u.count; ++i) {
// GIU CA NaN -- FSM phan biet ba ngu nghia, day chi truyen nguyen ven.
// Loc NaN o day lam mot day cam bien DUT tro nen vo hinh.
us_map["us" + std::to_string(i)] = u.range[i];
}
us_stamp = u.stamp;
have_us = true;
});
src.mcu()->SetBumperCallback([&](const vslam::BumperReading& b) {
s.Add("n_bumper", 1);
bumper = b.any();
bumper_stamp = b.stamp;
have_bumper = true;
});
src.mcu()->SetImuCallback([&](vslam::ImuPtr m) {
s.Add("n_imu", 1);
perception.FeedImu(*m);
wheel_odom.FeedGyroZ(m->header.stamp, m->angular_velocity.z);
ekf.UpdateImuYawRate(m->header.stamp, m->angular_velocity.z, 2.4e-7);
});
src.base()->SetEncoderCallback([&](const vslam::EncoderReading& e) {
if (!e.valid) return;
s.Add("n_encoder", 1);
vslam::Odometry o;
if (!wheel_odom.Update(e.stamp, e.left_rad, e.right_rad, &o)) return;
ekf.UpdateOdomTwist(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z,
o.twist.covariance[0], o.twist.covariance[35]);
perception.FeedOdom(e.stamp, o.twist.twist.linear.x, o.twist.twist.angular.z);
max_slip = std::max(max_slip, wheel_odom.slip_metric());
// FSM chay o day vi ban ghi khong co dong ho doc lap. Tren robot that no
// la mot luong 20 Hz rieng -- xem vslam_sim_run.cc. Lenh dua vao la van
// toc DO DUOC, tuc la cau hoi "robot dang di the nay, co an toan khong".
vslam::SafetyInputs si;
si.now = e.stamp;
vslam::Twist cmd;
cmd.linear.x = o.twist.twist.linear.x;
cmd.angular.z = o.twist.twist.angular.z;
si.cmd = &cmd;
si.cmd_stamp = e.stamp;
if (last_scan) {
si.scan = last_scan.get();
si.scan_stamp = last_scan_stamp;
}
if (have_us) {
si.ultrasonic = us_map;
si.us_stamp = us_stamp;
}
if (have_bumper) {
si.have_bumper = true;
si.bumper = bumper;
si.bumper_stamp = bumper_stamp;
}
if (have_cliff) {
si.have_cliff = true;
si.cliff = cliff_flag;
si.cliff_stamp = cliff_stamp;
// Giong `Runtime`: FSM phan biet "THAY vuc" voi "mu nen gia dinh co
// vuc". Bo hoi quy phai di DUNG duong ma node di.
si.cliff_judged = (cliff_detail == "judged");
si.cliff_window_min = pc.cliff.min_dist;
}
const vslam::SafetyOutput so = safety.Step(si);
s.Add(std::string("count_state_") + vslam::SafetyStateName(so.state), 1);
s.Add("n_safety_step", 1);
});
if (src.camera() != nullptr) {
src.camera()->SetCallback([&](const vslam::CameraFrame& f) {
if (!f.depth) return;
s.Add("n_camera", 1);
const vslam::PerceptionOutput po = perception.Process(*f.depth, f.depth_info);
cliff_flag = po.cliff_detected;
cliff_stamp = po.stamp;
cliff_detail = po.cliff_detail;
have_cliff = true;
if (po.cliff_detected) s.Add("count_cliff_detected", 1);
if (po.cliff_detail == "judged") s.Add("count_cliff_judged", 1);
else s.Add("count_bail_" + po.cliff_detail, 1);
});
src.camera()->Open();
}
src.lidar()->Open();
src.mcu()->Open();
src.base()->Open();
src.Run();
// --- Ket qua ---
const vslam::ReplaySource::Stats rs = src.stats();
const vslam::Pose2D ekf_pose = ekf.pose();
const vslam::Pose2D wheel_pose = wheel_odom.pose();
s.Set("n_chunks", static_cast<double>(rs.chunks));
s.Set("n_truncated", rs.truncated ? 1.0 : 0.0);
s.Set("dist_duration_sec", rs.duration_sec);
s.Set("pose_ekf_x", ekf_pose.x);
s.Set("pose_ekf_y", ekf_pose.y);
s.Set("yaw_ekf", ekf_pose.theta);
s.Set("pose_wheel_x", wheel_pose.x);
s.Set("pose_wheel_y", wheel_pose.y);
s.Set("yaw_wheel", wheel_pose.theta);
s.Set("dist_ekf_vs_wheel", vslam::Distance2D(ekf_pose, wheel_pose));
s.Set("metric_slip_max", max_slip);
const std::string json = s.ToJson(scenario);
if (!quiet) std::fputs(json.c_str(), stdout);
if (!emit.empty()) {
std::ofstream f(emit);
if (!f) {
std::fprintf(stderr, "khong ghi duoc %s\n", emit.c_str());
return 1;
}
f << json;
}
if (expect.empty()) return 0;
// --- So voi ky vong ---
const std::string want = ReadFile(expect);
if (want.empty()) {
std::fprintf(stderr, "%s: khong doc duoc file ky vong\n", expect.c_str());
return 1;
}
int bad = 0;
for (const auto& kv : s.items()) {
double w = 0.0;
if (!vslam::JsonGetNumber(want, kv.first, &w)) {
std::fprintf(stderr, " MOI %-28s = %.6g (ky vong khong co khoa nay)\n",
kv.first.c_str(), kv.second);
bad++;
continue;
}
const Tol& t = ToleranceFor(kv.first);
const double limit = t.abs_tol + t.rel_tol * std::fabs(w);
const double d = std::fabs(kv.second - w);
if (d > limit) {
std::fprintf(stderr, " LECH %-28s co %.6g, ky vong %.6g (lech %.3g > %.3g)\n",
kv.first.c_str(), kv.second, w, d, limit);
bad++;
}
}
// Khoa CO trong ky vong ma KHONG con trong ket qua cung la hoi quy: no
// nghia la mot nhanh da ngung chay. So sanh theo tung khoa mot khong bat
// duoc dieu do, nen phai dem.
const size_t want_keys = CountKeys(want);
const size_t have_keys = s.items().size() + 1; // +1 cho "scenario"
if (want_keys != have_keys) {
std::fprintf(stderr,
" SO KHOA ky vong %zu, co %zu -- mot nhanh da ngung chay?\n",
want_keys, have_keys);
bad++;
}
if (bad > 0) {
std::fprintf(stderr, "%s: %d khac biet\n", scenario.c_str(), bad);
return 1;
}
if (!quiet) std::printf("%s: KHOP\n", scenario.c_str());
return 0;
}