From 6735b53423c4f45d36aca6497cc4ab2255a90bc1 Mon Sep 17 00:00:00 2001 From: trung09122002 Date: Sun, 4 Oct 2026 00:02:53 +0700 Subject: [PATCH] tools: so nguon z tren doc (G3) -- vslam_vo_bench (F2M RTAB-Map tren IR+depth, hang tham chieu ds*sin(pitch) bang GravityAlign, num IMU Hz/bias/truot/nhieu IR), slope_eval/slope_fuse/slope_summary/slope_bakeoff.sh (3 muc giong that, DM-VIO ngoai repo); vslam_vsr_export them bias/nhieu IR; vslam_record --gl-headlight/--gl-ambient --- tools/CMakeLists.txt | 10 + tools/slope_bakeoff.sh | 165 +++++++++++++++ tools/slope_eval.py | 241 ++++++++++++++++++++++ tools/slope_fuse.py | 110 ++++++++++ tools/slope_summary.py | 118 +++++++++++ tools/vslam_record.cc | 8 +- tools/vslam_vo_bench.cc | 411 ++++++++++++++++++++++++++++++++++++++ tools/vslam_vsr_export.cc | 35 +++- 8 files changed, 1093 insertions(+), 5 deletions(-) create mode 100755 tools/slope_bakeoff.sh create mode 100644 tools/slope_eval.py create mode 100644 tools/slope_fuse.py create mode 100644 tools/slope_summary.py create mode 100644 tools/vslam_vo_bench.cc diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 58c64f0..05e7f54 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -50,6 +50,16 @@ if(VSLAM_BUILD_SLAM) add_executable(vslam_pnp_eval vslam_pnp_eval.cc) target_link_libraries(vslam_pnp_eval PRIVATE vslam_slam vslam_common) + # vslam_vo_bench: odometry thi giac RTAB-Map (F2M) tren anh IR + depth cua + # .vsr -> quy dao TUM. Cham z tren doc (G3), bo tham so RIENG, khong ke + # thua slam.yaml (ICP + Force3DoF lam mat z). + # Hang tham chieu ds*sin(pitch) dung GravityAlign cua vslam_perception. + if(VSLAM_BUILD_DRIVERS AND VSLAM_BUILD_PERCEPTION) + add_executable(vslam_vo_bench vslam_vo_bench.cc) + target_link_libraries(vslam_vo_bench + PRIVATE vslam_slam vslam_perception vslam_drivers vslam_common) + endif() + # vslam_vpr_check: doi chieu VPR TensorRT (C++) voi PyTorch -- chi khi co TensorRT. if(VSLAM_WITH_TENSORRT) add_executable(vslam_vpr_check vslam_vpr_check.cc) diff --git a/tools/slope_bakeoff.sh b/tools/slope_bakeoff.sh new file mode 100755 index 0000000..c3c7927 --- /dev/null +++ b/tools/slope_bakeoff.sh @@ -0,0 +1,165 @@ +#!/usr/bin/env bash +# So tai nguon z tren doc (G3): tham chieu ds*sin(pitch), F2M (RTAB-Map), +# DM-VIO -- tren cac ban ghi doc cua `vslam_record --scenario slope_all --gl`. +# +# tools/slope_bakeoff.sh DS_DIR OUT_DIR [kich_ban ...] +# +# DS_DIR chua slope_*.vsr. Can build co vslam_vo_bench, vslam_vsr_export; +# DM-VIO build NGOAI repo (GPLv3, khong link vao vslam_node) -- dat DMVIO_BIN +# (mac dinh ~/opt/dmvio/src/dm-vio/build/bin/dmvio_dataset); khong co thi bo qua. +# +# Ba muc "giong that", CHOT TRUOC khi chay (03/10): +# L0 sach : IMU 200 Hz, khong bias, banh khong truot, anh sach +# L1 nang cap : IMU 100 Hz, bias accel 0.02 / gyro 0.001, truot 3%, nhieu IR +# sigma 2, lech gio camera-IMU 5 ms (chi DM-VIO dung) +# L2 hien tai : IMU 10 Hz (WT61PC bay gio), bias 0.05 / 0.003, truot 5%, +# nhieu IR sigma 3, lech gio 20 ms +# F2M va DM-VIO moi cau hinh chay 2 lan (ca hai khong tat dinh). +# DM-VIO chay hai che do: mode=1 (khong hieu chuan quang hoc, uoc luong do +# sang affine -- dung cho camera that co tu phoi sang; CHOT TRUOC) va mode=2 +# (anh "hoan hao", co dinh affine -- sim khong doi phoi sang; THEM SAU khi +# mode=1 vo tren slope_lane5, la truong hop tot nhat cua DM-VIO trong sim). +# +# STEPS="ref f2m dmvio" (mac dinh ca ba) chon buoc; EVAL_ONLY=1 chi cham diem. +# Tham so F2M (Odom/VisKeyFrameThr=60, Vis/MaxDepth=0) va nhieu IMU cua DM-VIO +# (x10 mat do that cua sim) chon tren slope_lane15 -- cac kich ban khac la du +# lieu CHUA NHIN. +set -euo pipefail + +DS=${1:?DS_DIR} +OUT=${2:?OUT_DIR} +shift 2 +SCEN=("$@") +if [ ${#SCEN[@]} -eq 0 ]; then + SCEN=(slope_loop slope_lane5 slope_lane10 slope_lane15 slope_lane20 slope_lane30) +fi +ROOT=$(cd "$(dirname "$0")/.." && pwd) +BIN=${BIN:-$ROOT/build/tools} +DMVIO_BIN=${DMVIO_BIN:-$HOME/opt/dmvio/src/dm-vio/build/bin/dmvio_dataset} +ROBOT=${ROBOT:-$ROOT/configuration_files/robot.yaml} +JOBS=${JOBS:-6} +mkdir -p "$OUT" + +level_args() { # $1 = muc -> bien dung chung + case $1 in + L0) IMU_HZ=0; AB=0,0,0; GB=0,0,0; ENC=1.0; IRN=0; OFS=0 ;; + L1) IMU_HZ=100; AB=0.02,-0.01,0.02; GB=0.001,-0.001,0.0005; ENC=1.03; IRN=2; OFS=5 ;; + L2) IMU_HZ=10; AB=0.05,-0.03,0.05; GB=0.003,-0.002,0.001; ENC=1.05; IRN=3; OFS=20 ;; + esac +} + +# Nhieu IMU cho DM-VIO: x10 mat do that cua sim (sigma moi mau 4.9e-4 rad/s, +# 6.9e-3 m/s^2 o 200 Hz). euroc.yaml cua DM-VIO (x100) lam hong ti le. +cat > "$OUT/dmvio_sim_x10.yaml" <<'EOF' +accelerometer_noise_density: 4.88e-3 +gyroscope_noise_density: 3.46e-4 +accelerometer_random_walk: 1.0e-3 +gyroscope_random_walk: 1.0e-4 +integration_sigma: 0.316227 +EOF + +run_f2m() { # scen level rep + local s=$1 l=$2 r=$3 + level_args "$l" + "$BIN/vslam_vo_bench" --in "$DS/$s.vsr" --robot "$ROBOT" \ + --out "$OUT/$s/$l/f2m_r$r.txt" --stats "$OUT/$s/$l/f2m_r$r.json" \ + --param Odom/VisKeyFrameThr=60 --param Vis/MaxDepth=0 \ + --enc-scale "$ENC" --ir-noise "$IRN" --seed "$r" > "$OUT/$s/$l/f2m_r$r.log" 2>&1 || true +} + +run_ref() { # scen level + local s=$1 l=$2 + level_args "$l" + "$BIN/vslam_vo_bench" --in "$DS/$s.vsr" --robot "$ROBOT" --no-vo \ + --out /dev/null --ref-out "$OUT/$s/$l/ref.txt" \ + --imu-hz "$IMU_HZ" --accel-bias "$AB" --gyro-bias "$GB" --enc-scale "$ENC" \ + > "$OUT/$s/$l/ref.log" 2>&1 || true +} + +run_dmvio() { # scen level rep mode + local s=$1 l=$2 r=$3 m=$4 d="$OUT/$s/$l/dmvio_data" + local o="$OUT/$s/$l/dmvio_m${m}_r$r" + rm -rf "$o" + mkdir -p "$o" + (cd "$o" && env LD_LIBRARY_PATH= "$DMVIO_BIN" files="$d/cam0/images" imuFile="$d/imu.txt" \ + calib="$d/camera.txt" imuCalib="$d/camchain.yaml" settingsFile="$OUT/dmvio_sim_x10.yaml" \ + mode="$m" nogui=1 preset=0 quiet=1 useimu=1 start=2 resultsPrefix="$o/" > "$o/run.log" 2>&1) || true +} + +STEPS=${STEPS:-ref f2m dmvio} +has_step() { [[ " $STEPS " == *" $1 "* ]]; } +if [ "${EVAL_ONLY:-0}" != 1 ]; then +# --- 1. Tham chieu + F2M (song song, moi tien trinh ~1 nhan) --- +pids=() +for s in "${SCEN[@]}"; do + for l in L0 L1 L2; do + mkdir -p "$OUT/$s/$l" + if has_step ref; then + run_ref "$s" "$l" & + pids+=($!) + fi + if has_step f2m; then + for r in 1 2; do + run_f2m "$s" "$l" "$r" & + pids+=($!) + if [ ${#pids[@]} -ge "$JOBS" ]; then wait "${pids[0]}"; pids=("${pids[@]:1}"); fi + done + fi + done +done +wait + +# --- 2. DM-VIO (xuat dataset da lam xau, roi chay; moi lan da luong) --- +if ! has_step dmvio; then + : +elif [ -x "$DMVIO_BIN" ]; then + for s in "${SCEN[@]}"; do + for l in L0 L1 L2; do + level_args "$l" + d="$OUT/$s/$l/dmvio_data" + rm -rf "$d" + "$BIN/vslam_vsr_export" --in "$DS/$s.vsr" --out "$d" --robot "$ROBOT" \ + --imu-hz "$IMU_HZ" --imu-offset-ms "$OFS" --accel-bias "$AB" --gyro-bias "$GB" \ + --ir-noise "$IRN" > "$OUT/$s/$l/export.log" 2>&1 + for m in 1 2; do + run_dmvio "$s" "$l" 1 "$m" & + run_dmvio "$s" "$l" 2 "$m" & + done + wait + # Giu gt, bo anh (moi bo ~100 MB). + rm -rf "$d/cam0/images" + done + done +else + echo "khong co DM-VIO ($DMVIO_BIN) -- bo qua" >&2 +fi +fi # EVAL_ONLY + +# --- 3. Cham diem --- +rm -f "$OUT/summary.txt" +for s in "${SCEN[@]}"; do + gt="$OUT/$s/L0/dmvio_data/gt_base_tum.txt" + [ -f "$gt" ] || { "$BIN/vslam_vsr_export" --in "$DS/$s.vsr" --out "$OUT/$s/gt" --robot "$ROBOT" >/dev/null 2>&1; rm -rf "$OUT/$s/gt/cam0/images"; gt="$OUT/$s/gt/gt_base_tum.txt"; } + for l in L0 L1 L2; do + # Bo loc z ung vien cho G4, ghep offline: kep mat bang, lai F2M + pitch IMU. + python3 "$ROOT/tools/slope_fuse.py" "$OUT/$s/$l" + args=(--gt "$gt" --title "$s $l" --json "$OUT/$s/$l/eval.json" --plot "$OUT/$s/$l/z.png" + --plot-only ref,ref_clamp,f2m_r1,f2m_clamp_r1,hyb_clamp_r1,dmvio_m1_r1,dmvio_m2_r1 + --est "ref=$OUT/$s/$l/ref.txt" --est "ref_clamp=$OUT/$s/$l/ref_clamp.txt") + for r in 1 2; do + if [ -s "$OUT/$s/$l/f2m_r$r.txt" ]; then + args+=(--est "f2m_r$r=$OUT/$s/$l/f2m_r$r.txt" --stats "f2m_r$r=$OUT/$s/$l/f2m_r$r.json") + args+=(--est "hyb_r$r=$OUT/$s/$l/hyb_r$r.txt" --est "hyb_clamp_r$r=$OUT/$s/$l/hyb_clamp_r$r.txt" + --est "f2m_clamp_r$r=$OUT/$s/$l/f2m_clamp_r$r.txt") + fi + for m in 1 2; do + if [ -s "$OUT/$s/$l/dmvio_m${m}_r$r/resultScaled.txt" ]; then + args+=(--est "dmvio_m${m}_r$r=$OUT/$s/$l/dmvio_m${m}_r$r/resultScaled.txt,0.1465") + fi + done + done + n=$(grep -c . "$OUT/$s/L0/dmvio_data/cam0/times.txt" 2>/dev/null || echo 0) + python3 "$ROOT/tools/slope_eval.py" "${args[@]}" --frames "$n" | tee -a "$OUT/summary.txt" + done +done +python3 "$ROOT/tools/slope_summary.py" "$OUT" --md "$OUT/summary.md" diff --git a/tools/slope_eval.py b/tools/slope_eval.py new file mode 100644 index 0000000..2a61d13 --- /dev/null +++ b/tools/slope_eval.py @@ -0,0 +1,241 @@ +#!/usr/bin/env python3 +"""Cham diem z tren doc: so quy dao uoc luong (TUM) voi su that cua bo mo phong. + +Dung cho G3 (so F2M / DM-VIO / tham chieu ds*sin(pitch)). Moi quy dao NEO z +tai pose DAU TIEN cua no (z_uoc(t) - z_uoc(t0) + z_that(t0)) -- giong vslam_node +neo z vao ban do; khong can ti le, khong can xoay (moi frame deu da theo trong +luc: odom F2M bat dau tu robot dung tren san phang, DM-VIO tu can trong luc). + +Chi so (tieu chi DANG KY TRUOC trong ke hoach, 03/10): + * Sai dz moi lan qua doc: tu mau CUOI tren mat bang xuat phat toi mau DAU tren + mat bang den (chan -> dinh hoac nguoc lai). Dat: <= max(5 cm, 3% do cao) + voi doc <= 15 do, <= 10 cm voi 20/30 do. + * Troi z tren mat bang: |dz uoc| tren moi doan mat bang (cat 1 m hai dau -- + chuyen tiep chan/dinh doc), doan con >= 2 m, quy ra cm / 100 m quang + duong. Dat: <= 5 cm / 100 m. + * Bam: ti le khung co pose (tu file --stats neu co). Dat: >= 98%. + * Kem theo: RMSE z ca lan chay, sai z cuoi, RMSE pitch, ms/khung. + + python3 tools/slope_eval.py --gt DIR/gt_base_tum.txt \\ + --est f2m=f2m.txt --est ref=ref.txt --est dmvio=resultScaled.txt,0.1465 \\ + [--stats f2m=f2m.json] [--title lane15] [--plot out.png] [--json out.json] + +`--est TEN=FILE[,body_z]`: body_z = do cao diem cua quy dao tren base_footprint +theo truc z THAN (DM-VIO xuat diem IMU: 0.1465 m) -- doi ve base_footprint. +""" +import argparse +import json +import math +import sys + +import numpy as np + + +def load_tum(path): + d = np.loadtxt(path, comments='#') + if d.ndim == 1: + d = d[None, :] + return d + + +def quat_to_R(qx, qy, qz, qw): + n = np.sqrt(qx * qx + qy * qy + qz * qz + qw * qw) + qx, qy, qz, qw = qx / n, qy / n, qz / n, qw / n + R = np.empty(qx.shape + (3, 3)) + R[..., 0, 0] = 1 - 2 * (qy * qy + qz * qz) + R[..., 0, 1] = 2 * (qx * qy - qz * qw) + R[..., 0, 2] = 2 * (qx * qz + qy * qw) + R[..., 1, 0] = 2 * (qx * qy + qz * qw) + R[..., 1, 1] = 1 - 2 * (qx * qx + qz * qz) + R[..., 1, 2] = 2 * (qy * qz - qx * qw) + R[..., 2, 0] = 2 * (qx * qz - qy * qw) + R[..., 2, 1] = 2 * (qy * qz + qx * qw) + R[..., 2, 2] = 1 - 2 * (qx * qx + qy * qy) + return R + + +def pitch_of(d): + """Pitch ROS (duong = mui chuc xuong) tu cot qx qy qz qw.""" + qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7] + return np.arcsin(np.clip(2 * (qw * qy - qz * qx), -1, 1)) + + +def to_footprint(d, body_z): + """Doi diem cach base_footprint `body_z` theo truc z than ve base_footprint.""" + if body_z == 0.0: + return d + R = quat_to_R(d[:, 4], d[:, 5], d[:, 6], d[:, 7]) + out = d.copy() + out[:, 1:4] -= body_z * R[:, :, 2] + return out + + +def plateaus(z, lo, hi, tol): + """Nhan tung mau GT: 0 = mat bang duoi, 1 = mat bang tren, -1 = tren doc.""" + lab = np.full(len(z), -1) + lab[np.abs(z - lo) < tol] = 0 + lab[np.abs(z - hi) < tol] = 1 + return lab + + +def runs(lab): + """Cac doan lien tiep cung nhan: (nhan, i_dau, i_cuoi).""" + out = [] + s = 0 + for i in range(1, len(lab) + 1): + if i == len(lab) or lab[i] != lab[s]: + out.append((lab[s], s, i - 1)) + s = i + return out + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('--gt', required=True, help='gt_base_tum.txt (base_footprint)') + ap.add_argument('--est', action='append', default=[], help='TEN=FILE[,body_z]') + ap.add_argument('--stats', action='append', default=[], help='TEN=FILE.json (vslam_vo_bench)') + ap.add_argument('--frames', type=int, default=0, help='so khung anh (de tinh %% bam khi khong co --stats)') + ap.add_argument('--title', default='') + ap.add_argument('--plot', default='') + ap.add_argument('--plot-only', default='', help='ten,ten,... chi ve cac quy dao nay') + ap.add_argument('--json', default='') + a = ap.parse_args() + + gt = load_tum(a.gt) + tg, zg, pg = gt[:, 0], gt[:, 3], pitch_of(gt) + H = zg.max() - zg.min() + lo, hi = zg.min(), zg.max() + lab = plateaus(zg, lo, hi, 0.005) + segs = runs(lab) + # Lan qua doc: mat bang A -> (doc) -> mat bang B khac A. + crossings = [] + for k in range(1, len(segs) - 1): + if segs[k][0] != -1: + continue + a_lab, a_s, a_e = segs[k - 1] + b_lab, b_s, b_e = segs[k + 1] + if a_lab in (0, 1) and b_lab in (0, 1) and a_lab != b_lab: + i0, i1 = a_e, b_s + ang = np.degrees(np.median(np.abs(pg[i0:i1 + 1]))) + crossings.append((i0, i1, 'len' if b_lab == 1 else 'xuong', ang)) + flats = [(s, e) for l, s, e in segs if l in (0, 1)] + xy = gt[:, 1:3] + + stats = {} + for s in a.stats: + k, p = s.split('=', 1) + with open(p) as f: + stats[k] = json.load(f) + + results = {'title': a.title, 'H': H, 'methods': {}} + series = {} + for spec in a.est: + name, rest = spec.split('=', 1) + parts = rest.split(',') + body_z = float(parts[1]) if len(parts) > 1 else 0.0 + e = to_footprint(load_tum(parts[0]), body_z) + te = e[:, 0] + ze = e[:, 3] - e[0, 3] + np.interp(te[0], tg, zg) + series[name] = (te, ze) + zei = lambda t: np.interp(t, te, ze) + zgi = np.interp(te, tg, zg) + err = ze - zgi + pe = pitch_of(e) + perr = pe - np.interp(te, tg, pg) + m = { + 'poses': int(len(e)), + 'rmse_z': float(np.sqrt(np.mean(err ** 2))), + 'max_abs_z': float(np.max(np.abs(err))), + 'end_z': float(err[-1]), + 'rmse_pitch_deg': float(np.degrees(np.sqrt(np.mean(perr ** 2)))), + 'crossings': [], + 'flats': [], + } + for i0, i1, kind, ang in crossings: + t0, t1 = tg[i0], tg[i1] + dz_true = zg[i1] - zg[i0] + dz_est = zei(t1) - zei(t0) + lim = max(0.05, 0.03 * abs(dz_true)) if ang <= 15.5 else 0.10 + m['crossings'].append({ + 't0': float(t0 - tg[0]), 't1': float(t1 - tg[0]), 'kind': kind, + 'angle_deg': float(ang), 'dz_true': float(dz_true), 'dz_err': float(dz_est - dz_true), + 'limit': float(lim), 'pass': bool(abs(dz_est - dz_true) <= lim)}) + for s, e_ in flats: + # Cat 1 m hai dau: o chan/dinh doc than xe da chuc trong khi tam + # xe (z that) chua len -- do la chuyen tiep, khong phai mat bang. + cum = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(xy[s:e_ + 1], axis=0), axis=1))]) + if cum[-1] < 4.0: + continue + i_s = int(np.searchsorted(cum, 1.0)) + i_e = int(np.searchsorted(cum, cum[-1] - 1.0)) + d = float(cum[i_e] - cum[i_s]) + s, e_ = s + i_s, s + i_e + if d < 2.0: + continue + dz = float(zei(tg[e_]) - zei(tg[s])) + m['flats'].append({'t0': float(tg[s] - tg[0]), 'dist_m': d, 'dz': dz, + 'cm_per_100m': 100.0 * abs(dz) / d * 100.0}) + if name in stats: + st = stats[name] + m['track_pct'] = 100.0 * (st['frames'] - st['lost']) / max(1, st['frames']) + m['ms_mean'] = st.get('ms_mean') + elif a.frames > 0: + m['track_pct'] = 100.0 * len(e) / a.frames + worst_flat = max([f['cm_per_100m'] for f in m['flats']], default=0.0) + m['worst_flat_cm_per_100m'] = worst_flat + m['pass_crossings'] = all(c['pass'] for c in m['crossings']) + m['pass_flat'] = worst_flat <= 5.0 + m['pass_track'] = m.get('track_pct', 100.0) >= 98.0 + results['methods'][name] = m + + # --- In bang --- + print(f"== {a.title} (do cao {H:.3f} m, {len(crossings)} lan qua doc, {len(flats)} doan mat bang)") + for name, m in results['methods'].items(): + cr = ' '.join(f"{c['kind']}{c['angle_deg']:.0f}:{c['dz_err']*100:+.1f}cm{'' if c['pass'] else '!'}" + for c in m['crossings']) + tr = f"{m['track_pct']:.1f}%" if 'track_pct' in m else '-' + ms = f"{m['ms_mean']:.1f}" if m.get('ms_mean') is not None else '-' + print(f" {name:10s} dz qua doc [{cr}] | troi mat bang max {m['worst_flat_cm_per_100m']:.1f} cm/100m " + f"| RMSE z {m['rmse_z']*100:.1f} cm, cuoi {m['end_z']*100:+.1f} cm | pitch {m['rmse_pitch_deg']:.2f} do " + f"| bam {tr} | {ms} ms") + + if a.json: + with open(a.json, 'w') as f: + json.dump(results, f, indent=1) + if a.plot: + import matplotlib + matplotlib.use('Agg') + import matplotlib.pyplot as plt + colors = {'ref': 'tab:blue', 'ref_clamp': 'tab:cyan', 'f2m': 'tab:green', 'f2m_clamp': 'tab:brown', 'hyb': 'tab:olive', + 'hyb_clamp': 'tab:purple', 'dmvio_m1': 'tab:red', 'dmvio_m2': 'tab:orange'} + only = [x for x in a.plot_only.split(',') if x] + fig, ax = plt.subplots(2, 1, figsize=(10, 6.5), sharex=True) + ax[0].plot(tg - tg[0], zg, 'k-', lw=2, label='that') + for name, (te, ze) in series.items(): + if only and name not in only: + continue + fam = name.rsplit('_r', 1)[0] if name.rsplit('_r', 1)[-1].isdigit() else name + c = colors.get(fam) + ax[0].plot(te - tg[0], ze, lw=1, label=name, color=c) + ax[1].plot(te - tg[0], (ze - np.interp(te, tg, zg)) * 100, lw=1, label=name, color=c) + # Kep truc: quy dao vo (DM-VIO mat ti le) di ra ngoai khung thay vi + # ep moi thu khac thanh duong thang. + ax[0].set_ylim(zg.min() - 0.6, zg.max() + 0.6) + ax[1].set_ylim(-60, 60) + for i0, i1, kind, ang in crossings: + for x in ax: + x.axvspan(tg[i0] - tg[0], tg[i1] - tg[0], color='0.9', zorder=0) + ax[0].set_ylabel('z (m)') + ax[1].set_ylabel('sai z (cm)') + ax[1].set_xlabel('t (s) -- nen xam = dang tren doc; duong ra ngoai khung = vo') + ax[0].set_title(a.title) + ax[0].legend(loc='best', fontsize=8) + ax[1].axhline(0, color='k', lw=0.5) + ax[1].grid(alpha=0.3) + fig.tight_layout() + fig.savefig(a.plot, dpi=110) + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/slope_fuse.py b/tools/slope_fuse.py new file mode 100644 index 0000000..6b51a4e --- /dev/null +++ b/tools/slope_fuse.py @@ -0,0 +1,110 @@ +#!/usr/bin/env python3 +"""Ghep nguon z OFFLINE tu ket qua vslam_vo_bench -- thu cac bo loc z cho G4 +truoc khi viet C++. + +Vao (cung thu muc, ra cua vslam_vo_bench): + ref.txt tham chieu: z = tich -ds*sin(pitch), pitch/roll cua GravityAlign + f2m_rN.txt odometry F2M (base_footprint, frame odom) +Ra (TUM, cung thu muc): + ref_clamp.txt tham chieu + KEP MAT BANG: |pitch IMU| < nguong -> dz = 0 + hyb_rN.txt LAI: buoc dich chuyen trong frame THAN tu F2M (met, khong + truot banh), xoay bang roll/pitch IMU (khong troi): + dz = -sin(p)*dx + cos(p)*sin(r)*dy + cos(p)*cos(r)*dz + hyb_clamp_rN.txt lai + kep mat bang + f2m_clamp_rN.txt dz cua CHINH F2M, kep mat bang theo pitch IMU -- dung + thiet ke G4 trong ke hoach (dz VO + dz = 0 o node phang) + +Nguong kep mac dinh 1.5 do: duoi doc thu nho nhat (5 do), tren sai pitch do +bias IMU muc L2 (~0.9 do). CHOT TRUOC khi cham. Doc that < 1.5 do se bi coi +la phang -- noi ro trong bao cao. + + python3 tools/slope_fuse.py DIR [--clamp-deg 1.5] +""" +import argparse +import glob +import os +import sys + +import numpy as np + + +def load(p): + d = np.loadtxt(p, comments='#') + return d[None, :] if d.ndim == 1 else d + + +def rpy(d): + qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7] + roll = np.arctan2(2 * (qw * qx + qy * qz), 1 - 2 * (qx * qx + qy * qy)) + pitch = np.arcsin(np.clip(2 * (qw * qy - qz * qx), -1, 1)) + return roll, pitch + + +def rot(d): + qx, qy, qz, qw = d[:, 4], d[:, 5], d[:, 6], d[:, 7] + R = np.empty((len(d), 3, 3)) + R[:, 0, 0] = 1 - 2 * (qy * qy + qz * qz) + R[:, 0, 1] = 2 * (qx * qy - qz * qw) + R[:, 0, 2] = 2 * (qx * qz + qy * qw) + R[:, 1, 0] = 2 * (qx * qy + qz * qw) + R[:, 1, 1] = 1 - 2 * (qx * qx + qz * qz) + R[:, 1, 2] = 2 * (qy * qz - qx * qw) + R[:, 2, 0] = 2 * (qx * qz - qy * qw) + R[:, 2, 1] = 2 * (qy * qz + qx * qw) + R[:, 2, 2] = 1 - 2 * (qx * qx + qy * qy) + return R + + +def save(p, d, z, header): + out = d.copy() + out[:, 3] = z + np.savetxt(p, out, fmt='%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f', header=header) + + +def main(): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument('dir') + ap.add_argument('--clamp-deg', type=float, default=1.5) + a = ap.parse_args() + th = np.radians(a.clamp_deg) + + ref_p = os.path.join(a.dir, 'ref.txt') + if not os.path.exists(ref_p): + print(f'{a.dir}: thieu ref.txt', file=sys.stderr) + return 1 + ref = load(ref_p) + r_roll, r_pitch = rpy(ref) + + dz = np.diff(ref[:, 3]) + dz[np.abs(r_pitch[1:]) < th] = 0.0 + save(os.path.join(a.dir, 'ref_clamp.txt'), ref, ref[0, 3] + np.concatenate([[0.0], np.cumsum(dz)]), + f'tham chieu + kep mat bang (|pitch| < {a.clamp_deg} do -> dz = 0)') + + for f in sorted(glob.glob(os.path.join(a.dir, 'f2m_r*.txt'))): + tag = os.path.basename(f)[len('f2m_'):-len('.txt')] + e = load(f) + if len(e) < 2: + continue + R = rot(e) + dp_w = np.diff(e[:, 1:4], axis=0) + dp_b = np.einsum('kji,kj->ki', R[:-1], dp_w) # R_prev^T * dp + roll = np.interp(e[1:, 0], ref[:, 0], r_roll) + pitch = np.interp(e[1:, 0], ref[:, 0], r_pitch) + dzh = (-np.sin(pitch) * dp_b[:, 0] + np.cos(pitch) * np.sin(roll) * dp_b[:, 1] + + np.cos(pitch) * np.cos(roll) * dp_b[:, 2]) + z0 = e[0, 3] + save(os.path.join(a.dir, f'hyb_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzh)]), + 'lai: buoc than F2M xoay bang roll/pitch IMU') + dzc = dzh.copy() + dzc[np.abs(pitch) < th] = 0.0 + save(os.path.join(a.dir, f'hyb_clamp_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzc)]), + f'lai + kep mat bang (|pitch| < {a.clamp_deg} do)') + dzf = np.diff(e[:, 3]) + dzf[np.abs(pitch) < th] = 0.0 + save(os.path.join(a.dir, f'f2m_clamp_{tag}.txt'), e, z0 + np.concatenate([[0.0], np.cumsum(dzf)]), + f'dz F2M + kep mat bang theo pitch IMU (|pitch| < {a.clamp_deg} do)') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/slope_summary.py b/tools/slope_summary.py new file mode 100644 index 0000000..3438cb2 --- /dev/null +++ b/tools/slope_summary.py @@ -0,0 +1,118 @@ +#!/usr/bin/env python3 +"""Tong hop ket qua tools/slope_bakeoff.sh: doc OUT///eval.json, +gop theo (phuong phap, muc), in bang markdown. + + python3 tools/slope_summary.py OUT_DIR [--md OUT.md] + +Phuong phap = ten bo hau to _rN (moi lan chay lap). Lan chay KHONG co ket qua +(DM-VIO vo tien trinh) tinh la HONG, khong bo qua. +""" +import argparse +import glob +import json +import os +import re +import sys +from collections import defaultdict + +import numpy as np + +# So lan chay ky vong moi (kich ban, muc) -- de dem lan vo. +EXPECT = {'ref': 1, 'ref_clamp': 1, 'f2m': 2, 'f2m_clamp': 2, 'hyb': 2, 'hyb_clamp': 2, + 'dmvio_m1': 2, 'dmvio_m2': 2} +ORDER = ['ref', 'ref_clamp', 'f2m', 'f2m_clamp', 'hyb', 'hyb_clamp', 'dmvio_m1', 'dmvio_m2'] +LABEL = { + 'ref': 'Tham chieu ds*sin(pitch IMU)', + 'ref_clamp': 'Tham chieu + kep mat bang', + 'f2m': 'F2M (RTAB-Map, IR+depth)', + 'f2m_clamp': 'F2M + kep mat bang (thiet ke G4 cu)', + 'hyb': 'Lai: buoc F2M + pitch IMU', + 'hyb_clamp': 'Lai + kep mat bang', + 'dmvio_m1': 'DM-VIO mode=1 (nhu camera that)', + 'dmvio_m2': 'DM-VIO mode=2 (anh hoan hao)', +} +LEVEL = {'L0': 'L0 sach', 'L1': 'L1 nang cap (IMU 100 Hz)', 'L2': 'L2 hien tai (IMU 10 Hz)'} +BROKEN_CM = 50.0 # sai dz qua doc > 50 cm = vo (mat ti le / no) + + +def family(name): + return re.sub(r'_r\d+$', '', name) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument('out') + ap.add_argument('--md', default='') + a = ap.parse_args() + + agg = defaultdict(lambda: {'cross': [], 'cross_pass': 0, 'cross_n': 0, 'flat': [], 'rmse': [], + 'end': [], 'runs': 0, 'broken': 0, 'scen': set(), 'by_angle': defaultdict(list), + 'ms': []}) + scen_levels = defaultdict(set) + for p in sorted(glob.glob(os.path.join(a.out, '*', 'L*', 'eval.json'))): + lvl = os.path.basename(os.path.dirname(p)) + scen = os.path.basename(os.path.dirname(os.path.dirname(p))) + scen_levels[lvl].add(scen) + with open(p) as f: + ev = json.load(f) + for name, m in ev['methods'].items(): + fam = family(name) + g = agg[(fam, lvl)] + g['runs'] += 1 + g['scen'].add(scen) + errs = [abs(c['dz_err']) * 100 for c in m['crossings']] + if any(e > BROKEN_CM for e in errs): + g['broken'] += 1 + g['cross'] += errs + g['cross_pass'] += sum(c['pass'] for c in m['crossings']) + g['cross_n'] += len(m['crossings']) + for c in m['crossings']: + g['by_angle'][round(c['angle_deg'])].append(abs(c['dz_err']) * 100) + g['flat'].append(m['worst_flat_cm_per_100m']) + g['rmse'].append(m['rmse_z'] * 100) + g['end'].append(abs(m['end_z']) * 100) + if m.get('ms_mean'): + g['ms'].append(m['ms_mean']) + + lines = [] + for lvl in sorted(scen_levels): + n_scen = len(scen_levels[lvl]) + lines.append(f"\n### {LEVEL.get(lvl, lvl)} -- {n_scen} kich ban\n") + lines.append('| Phuong phap | Lan chay (vo) | Qua doc dat | Sai dz trung vi / max (cm) | ' + 'Troi mat bang trung vi / max (cm/100m) | RMSE z trung vi (cm) | ms/khung |') + lines.append('|---|---|---|---|---|---|---|') + for fam in ORDER: + g = agg.get((fam, lvl)) + exp = EXPECT.get(fam, 1) * n_scen + if g is None: + lines.append(f"| {LABEL.get(fam, fam)} | 0/{exp} | - | - | - | - | - |") + continue + missing = exp - g['runs'] + bad = g['broken'] + max(0, missing) + cr = np.array(g['cross']) if g['cross'] else np.array([np.nan]) + ms = f"{np.mean(g['ms']):.1f}" if g['ms'] else '-' + lines.append( + f"| {LABEL.get(fam, fam)} | {g['runs']}/{exp} ({bad}) | {g['cross_pass']}/{g['cross_n']} | " + f"{np.nanmedian(cr):.1f} / {np.nanmax(cr):.0f} | {np.median(g['flat']):.0f} / {np.max(g['flat']):.0f} | " + f"{np.median(g['rmse']):.1f} | {ms} |") + # Theo goc doc, muc L1 (phan cung dich). + lines.append('\n### Sai dz qua doc theo goc, L1 (trung vi |cm|)\n') + angles = sorted({ang for (fam, lvl), g in agg.items() if lvl == 'L1' for ang in g['by_angle']}) + lines.append('| Phuong phap | ' + ' | '.join(f'{x} do' for x in angles) + ' |') + lines.append('|---|' + '---|' * len(angles)) + for fam in ORDER: + g = agg.get((fam, 'L1')) + if g is None: + continue + cells = [f"{np.median(g['by_angle'][x]):.1f}" if g['by_angle'].get(x) else '-' for x in angles] + lines.append(f"| {LABEL.get(fam, fam)} | " + ' | '.join(cells) + ' |') + text = '\n'.join(lines) + print(text) + if a.md: + with open(a.md, 'w') as f: + f.write(text + '\n') + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/tools/vslam_record.cc b/tools/vslam_record.cc index 268419d..de37a9c 100644 --- a/tools/vslam_record.cc +++ b/tools/vslam_record.cc @@ -271,6 +271,7 @@ int main(int argc, char** argv) { bool write_gt = false; bool use_gl = false; // ve camera bang GPU (anh IR) -- chi kich ban doc uint32_t cam_decimate = 2; // anh 640x480 / N, nhu crop_decimate cua robot + double gl_headlight = -1.0, gl_ambient = -1.0; // am = mac dinh renderer for (int i = 1; i < argc; ++i) { const std::string a = argv[i]; @@ -282,6 +283,8 @@ int main(int argc, char** argv) { else if (a == "--gt") write_gt = true; else if (a == "--gl") use_gl = true; else if (a == "--cam-decimate") cam_decimate = static_cast(std::atoi(next().c_str())); + else if (a == "--gl-headlight") gl_headlight = std::atof(next().c_str()); + else if (a == "--gl-ambient") gl_ambient = std::atof(next().c_str()); else if (a == "--help") { std::printf("cach dung: %s --scenario TEN --out-dir D [--robot robot.yaml] [--gt]\n" " %s --list\n" @@ -382,7 +385,10 @@ int main(int argc, char** argv) { if (use_gl) { #ifdef VSLAM_HAVE_SIM_GL std::string gerr; - auto r = vslam::CreateGlCameraRenderer(sim.world(), vslam::DefaultGlRendererConfig(), &gerr); + vslam::GlRendererConfig gc = vslam::DefaultGlRendererConfig(); + if (gl_headlight >= 0.0) gc.headlight = gl_headlight; + if (gl_ambient >= 0.0) gc.ambient = gl_ambient; + auto r = vslam::CreateGlCameraRenderer(sim.world(), gc, &gerr); if (!r) { std::fprintf(stderr, "%s: --gl: %s\n", s.name, gerr.c_str()); return 1; diff --git a/tools/vslam_vo_bench.cc b/tools/vslam_vo_bench.cc new file mode 100644 index 0000000..30548fa --- /dev/null +++ b/tools/vslam_vo_bench.cc @@ -0,0 +1,411 @@ +// vslam_vo_bench -- chay odometry thi giac RTAB-Map (mac dinh F2M) tren anh +// IR + depth cua mot ban ghi .vsr, xuat quy dao TUM de cham diem z tren doc. +// +// vslam_vo_bench --in X.vsr --out TRAJ.txt [--robot robot.yaml] +// [--guess wheel|none] [--param Key=Value]... [--stats S.json] +// [--reset-after N] [--ref-out REF.txt] [--imu-orient] +// [--imu-hz N] [--accel-bias x,y,z] [--gyro-bias x,y,z] +// [--enc-scale K] [--ir-noise SIGMA] [--seed N] [--no-vo] +// [--ga-alpha A] +// +// Ra: TRAJ.txt = "giay x y z qx qy qz qw" cua base_footprint trong frame +// odom (goc = tu the robot o khung dau), chi khung odometry TINH DUOC. +// S.json = so khung, so khung mat bam, so lan reset, ms/khung. +// REF.txt = HANG THAM CHIEU, cung dinh dang, tai cung cac khung anh: z tich +// tu encoder va pitch cua GravityAlign (dung class vslam_node dung): +// z += -ds * sin(pitch), xy += ds * cos(pitch). VO phai thang hang nay moi +// dang chi phi. +// +// --imu-orient: dua roll/pitch cua GravityAlign vao moi khung (rtabmap::IMU, +// khong co yaw). RTAB-Map dung no de dat tu the dau theo trong luc va doan +// phep quay -- giu pitch khoi troi, la thu F2M mot minh khong co. +// +// ================== NUM "GIONG THAT" ================== +// Ban ghi sim SACH (IMU 200 Hz khong bias, banh khong truot, anh khong +// nhieu) -- thuan loi qua muc cho moi thu song nho IMU. Lam xau o day: +// --imu-hz N chi giu ~N mau IMU/giay (WT61PC hien 10 Hz) +// --accel-bias x,y,z cong bias co dinh (m/s^2) -- x lam lech pitch +// --gyro-bias x,y,z (rad/s) +// --enc-scale K encoder doc K lan quang duong that (truot banh / +// sai ban kinh) -- ca doan F2M lan tham chieu +// --ir-noise SIGMA nhieu Gauss tren anh IR truoc khi vao VO +// --no-vo chi tinh tham chieu (nhanh) +// --ga-alpha A alpha bo loc bu cua GravityAlign (mac dinh 0.98 cua +// pipeline.yaml, tinh MOI MAU: 10 Hz -> tau 5 s, +// 200 Hz -> tau 0.25 s) +// +// ================== BO THAM SO RIENG ================== +// KHONG ke thua slam.yaml: SLAM dang chay Reg/Strategy=1 (ICP) va +// Reg/Force3DoF=true -- ke thua la mat z ngay tu dau. O day: +// Odom/Strategy=0 (F2M), Reg/Strategy=0 (thi giac), Reg/Force3DoF=false, +// Vis/MaxDepth=4 (depth stereo xa hon thi sai so binh phuong khoang cach), +// Vis/MinInliers=15, OdomF2M/BundleAdjustment=1. +// Ngoai lai base_link <- camera_depth_optical_frame TINH tu robot.yaml (khong +// TiltLift: odometry tu tinh chuc ngoc cua than). +// +// Doan chuyen dong (--guess wheel, mac dinh): encoder banh -> buoc SE(2) cua +// than giua hai khung. Tren doc buoc nay van dung trong frame THAN (banh lan +// doc mat doc = truc x cua than). +// +// Mat bam: odometry tra pose rong. Sau N khung mat lien tiep (--reset-after, +// mac dinh 5) thi reset odometry TAI pose doan bang encoder -- giong cach +// vslam_node se lam khi VO hong. Moi lan reset la mot lan dem. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "vslam/gravity_align.h" +#include "vslam/node_constants.h" +#include "vslam/record_format.h" +#include "vslam/record_io.h" +#include "vslam/robot_model.h" +#include "vslam/sensor_data_builder.h" + +namespace { + +struct PendingImage { + int64_t t = -1; + cv::Mat mat; +}; + +cv::Mat ToMat(const vslam::Image& img) { + const int type = img.format == vslam::PixelFormat::kMono16 ? CV_16UC1 : CV_8UC1; + // Ban sao sau: payload cua chunk bi ghi de o lan doc ke tiep. + return cv::Mat(static_cast(img.height), static_cast(img.width), type, + const_cast(img.data), img.step) + .clone(); +} + +bool ParseVec3(const std::string& s, double v[3]) { + return std::sscanf(s.c_str(), "%lf,%lf,%lf", &v[0], &v[1], &v[2]) == 3; +} + +void WriteTum(FILE* f, double t, const rtabmap::Transform& T) { + float x, y, z, qx, qy, qz, qw; + T.getTranslation(x, y, z); + const Eigen::Quaternionf q = T.getQuaternionf(); + qx = q.x(); qy = q.y(); qz = q.z(); qw = q.w(); + std::fprintf(f, "%.9f %.6f %.6f %.6f %.9f %.9f %.9f %.9f\n", t, x, y, z, qx, qy, qz, qw); +} + +} // namespace + +int main(int argc, char** argv) { + std::string in, out, robot_yaml, stats_path, ref_path, guess_mode = "wheel"; + int reset_after = 5; + bool imu_orient = false, no_vo = false; + double imu_hz = 0.0, enc_scale = 1.0, ir_noise = 0.0, ga_alpha = -1.0; + double accel_bias[3] = {0, 0, 0}, gyro_bias[3] = {0, 0, 0}; + uint32_t seed = 1; + rtabmap::ParametersMap params; + params[rtabmap::Parameters::kOdomStrategy()] = "0"; + params[rtabmap::Parameters::kRegStrategy()] = "0"; + params[rtabmap::Parameters::kRegForce3DoF()] = "false"; + params[rtabmap::Parameters::kVisMaxDepth()] = "4.0"; + params[rtabmap::Parameters::kVisMinInliers()] = "15"; + params[rtabmap::Parameters::kOdomF2MBundleAdjustment()] = "1"; + params[rtabmap::Parameters::kOdomResetCountdown()] = "0"; + 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 == "--out") out = next(); + else if (a == "--robot") robot_yaml = next(); + else if (a == "--stats") stats_path = next(); + else if (a == "--guess") guess_mode = next(); + else if (a == "--reset-after") reset_after = std::atoi(next().c_str()); + else if (a == "--ref-out") ref_path = next(); + else if (a == "--imu-orient") imu_orient = true; + else if (a == "--no-vo") no_vo = true; + else if (a == "--imu-hz") imu_hz = std::atof(next().c_str()); + else if (a == "--enc-scale") enc_scale = std::atof(next().c_str()); + else if (a == "--ga-alpha") ga_alpha = std::atof(next().c_str()); + else if (a == "--ir-noise") ir_noise = std::atof(next().c_str()); + else if (a == "--seed") seed = static_cast(std::atoi(next().c_str())); + else if (a == "--accel-bias" || a == "--gyro-bias") { + if (!ParseVec3(next(), a == "--accel-bias" ? accel_bias : gyro_bias)) { + std::fprintf(stderr, "%s can x,y,z\n", a.c_str()); + return 2; + } + } + else if (a == "--param") { + const std::string kv = next(); + const size_t eq = kv.find('='); + if (eq == std::string::npos) { + std::fprintf(stderr, "--param can Key=Value: %s\n", kv.c_str()); + return 2; + } + params[kv.substr(0, eq)] = kv.substr(eq + 1); + } else { + std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str()); + return 2; + } + } + if (in.empty() || out.empty() || (guess_mode != "wheel" && guess_mode != "none")) { + std::fprintf(stderr, "can --in, --out; --guess wheel|none\n"); + return 2; + } + if (robot_yaml.empty()) { + const char* cd = std::getenv("VSLAM_CONFIG_DIR"); + robot_yaml = (cd != nullptr && *cd != '\0' ? std::string(cd) : std::string("configuration_files")) + + "/robot.yaml"; + } + + vslam::RobotModel robot; + const vslam::StatusResponse rs = robot.LoadFile(robot_yaml); + if (!rs.ok()) { + std::fprintf(stderr, "%s: %s\n", robot_yaml.c_str(), rs.message.c_str()); + return 1; + } + vslam::Transform T_bl_cam, T_bl_imu; + if (!robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kCameraDepthOpticalFrame, &T_bl_cam) || + !robot.StaticTransform(vslam::kBaseLinkFrame, vslam::kImuFrame, &T_bl_imu)) { + std::fprintf(stderr, "robot.yaml thieu camera_depth_optical_frame / imu_link\n"); + return 1; + } + const rtabmap::Transform imu_local = vslam::ToRtabmap(T_bl_imu); + const rtabmap::Transform local = vslam::ToRtabmap(T_bl_cam); + const double r_wheel = robot.geometry().wheel_radius; + const double sep = robot.geometry().wheel_separation; + // base_link -> base_footprint: chi tinh tien z. + const rtabmap::Transform T_bl_fp(0, 0, static_cast(-r_wheel), 0, 0, 0); + + ULogger::setType(ULogger::kTypeConsole); + ULogger::setLevel(ULogger::kError); + std::unique_ptr odom(rtabmap::Odometry::create(params)); + + vslam::RecordReader reader; + const vslam::StatusResponse st = reader.Open(in); + if (!st.ok()) { + std::fprintf(stderr, "%s: %s\n", in.c_str(), st.message.c_str()); + return 1; + } + FILE* fo = std::fopen(out.c_str(), "w"); + if (fo == nullptr) { + std::fprintf(stderr, "khong ghi duoc %s\n", out.c_str()); + return 1; + } + std::fprintf(fo, "# vslam_vo_bench %s: base_footprint trong frame odom (TUM)\n", in.c_str()); + FILE* fr = nullptr; + if (!ref_path.empty()) { + fr = std::fopen(ref_path.c_str(), "w"); + if (fr == nullptr) { + std::fprintf(stderr, "khong ghi duoc %s\n", ref_path.c_str()); + return 1; + } + std::fprintf(fr, "# tham chieu ds*sin(pitch GravityAlign) %s: base_footprint (TUM)\n", + in.c_str()); + } + // Mac dinh cua GravityAlignConfig = pipeline.yaml (alpha 0.98, LPF 0.05, + // cong 1.0, tru gia toc odom). + vslam::GravityAlignConfig gcfg; + gcfg.wheel_radius = r_wheel; + if (ga_alpha >= 0.0) gcfg.alpha = ga_alpha; + vslam::GravityAlign ga(gcfg); + double rx = 0, ry = 0, rz = 0; // tham chieu: xy ngang + z tich luy + int64_t enc_t = -1, imu_kept_t = -1; + std::mt19937 rng(seed); + std::normal_distribution n01(0.0, 1.0); + + vslam::CameraInfo info; + bool have_info = false; + PendingImage depth, ir; + // Odometry banh: pose SE(2) tich luy cua than, cap nhat moi encoder. + bool enc_init = false; + double enc_l = 0, enc_r = 0, wx = 0, wy = 0, wyaw = 0; + double fx_prev = 0, fy_prev = 0, fyaw_prev = 0; // pose banh luc khung truoc + int frames = 0, lost = 0, lost_run = 0, resets = 0, keyframes = 0; + long inliers_sum = 0; + std::vector ms; + rtabmap::Transform last_pose = rtabmap::Transform::getIdentity(); + rtabmap::Transform guess_since_last = rtabmap::Transform::getIdentity(); + + vslam::VsrChunkHeader h; + std::string payload; + std::vector storage; + while (reader.Next(&h, &payload)) { + const int64_t t = static_cast(h.stamp_ns); + if (h.stream == vslam::VsrStream::kCameraInfo && !have_info) { + have_info = vslam::DecodeCameraInfoPayload(payload, &info); + continue; + } + if (h.stream == vslam::VsrStream::kEncoder) { + double l, r; + if (!vslam::DecodeEncoderPayload(payload, &l, &r)) continue; + if (enc_init) { + const double dl = (l - enc_l) * r_wheel * enc_scale; + const double dr = (r - enc_r) * r_wheel * enc_scale; + const double ds = 0.5 * (dl + dr), dth = (dr - dl) / sep; + wx += ds * std::cos(wyaw + 0.5 * dth); + wy += ds * std::sin(wyaw + 0.5 * dth); + // Tham chieu: pitch duong = mui chuc xuong, nen len doc pitch am. + const double p = ga.pitch(); + rx += ds * std::cos(p) * std::cos(wyaw + 0.5 * dth); + ry += ds * std::cos(p) * std::sin(wyaw + 0.5 * dth); + rz += -ds * std::sin(p); + wyaw += dth; + const double dt = (t - enc_t) * 1e-9; + if (dt > 0.0) ga.FeedOdom(vslam::UnixTime::fromNSec(t), ds / dt, dth / dt); + } + enc_l = l; + enc_r = r; + enc_t = t; + enc_init = true; + continue; + } + if (h.stream == vslam::VsrStream::kImu) { + vslam::Imu m; + if (!vslam::DecodeImuPayload(payload, &m)) continue; + // Ha tan so: giu mau cach mau giu truoc >= 1/N (dung sai 1 ms). + if (imu_hz > 0.0 && imu_kept_t >= 0 && + t - imu_kept_t < static_cast(1e9 / imu_hz) - 1000000) { + continue; + } + imu_kept_t = t; + m.linear_acceleration.x += accel_bias[0]; + m.linear_acceleration.y += accel_bias[1]; + m.linear_acceleration.z += accel_bias[2]; + m.angular_velocity.x += gyro_bias[0]; + m.angular_velocity.y += gyro_bias[1]; + m.angular_velocity.z += gyro_bias[2]; + ga.FeedImu(m); + continue; + } + if (h.stream != vslam::VsrStream::kDepth && h.stream != vslam::VsrStream::kInfra1) continue; + vslam::Image img; + if (!vslam::DecodeImagePayload(payload, &img, &storage)) continue; + PendingImage& slot = h.stream == vslam::VsrStream::kDepth ? depth : ir; + slot.t = t; + slot.mat = ToMat(img); + if (depth.t != ir.t || !have_info) continue; // cho du cap cung gio + + // Buoc banh tu khung truoc, trong frame than. + const double c = std::cos(fyaw_prev), s = std::sin(fyaw_prev); + const double ddx = c * (wx - fx_prev) + s * (wy - fy_prev); + const double ddy = -s * (wx - fx_prev) + c * (wy - fy_prev); + const double ddyaw = wyaw - fyaw_prev; + fx_prev = wx; fy_prev = wy; fyaw_prev = wyaw; + const rtabmap::Transform wheel_step(static_cast(ddx), static_cast(ddy), 0.0f, + 0.0f, 0.0f, static_cast(ddyaw)); + rtabmap::Transform guess = guess_mode == "wheel" ? wheel_step : rtabmap::Transform(); + if (no_vo) { + frames++; + depth.t = ir.t = -1; + if (fr != nullptr) { + const rtabmap::Transform ref(static_cast(rx), static_cast(ry), + static_cast(rz), static_cast(ga.roll()), + static_cast(ga.pitch()), static_cast(wyaw)); + WriteTum(fr, t * 1e-9, ref); + } + continue; + } + if (ir_noise > 0.0) { + for (int yy = 0; yy < ir.mat.rows; ++yy) { + uint8_t* row = ir.mat.ptr(yy); + for (int xx = 0; xx < ir.mat.cols; ++xx) { + const double v = row[xx] + ir_noise * n01(rng); + row[xx] = static_cast(std::min(255.0, std::max(0.0, std::round(v)))); + } + } + } + + rtabmap::CameraModel model(info.fx_binned(), info.fy_binned(), info.cx_binned(), + info.cy_binned(), local, 0.0, + cv::Size(ir.mat.cols, ir.mat.rows)); + rtabmap::SensorData data(ir.mat, depth.mat, model, frames + 1, t * 1e-9); + if (imu_orient && ga.valid()) { + // Huong IMU trong the gioi, yaw 0: RTAB-Map chi lay roll/pitch. + const Eigen::Quaterniond q = rtabmap::Transform(0, 0, 0, static_cast(ga.roll()), + static_cast(ga.pitch()), 0) + .getQuaterniond(); + data.setIMU(rtabmap::IMU(cv::Vec4d(q.x(), q.y(), q.z(), q.w()), + cv::Mat::eye(3, 3, CV_64FC1) * 1e-4, cv::Vec3d(), cv::Mat(), + cv::Vec3d(), cv::Mat(), imu_local)); + } + rtabmap::OdometryInfo oi; + const auto t0 = std::chrono::steady_clock::now(); + rtabmap::Transform pose = odom->process(data, guess, &oi); + ms.push_back(std::chrono::duration(std::chrono::steady_clock::now() - t0) + .count()); + frames++; + depth.t = ir.t = -1; + if (fr != nullptr) { + const rtabmap::Transform ref(static_cast(rx), static_cast(ry), + static_cast(rz), static_cast(ga.roll()), + static_cast(ga.pitch()), static_cast(wyaw)); + WriteTum(fr, t * 1e-9, ref); + } + if (pose.isNull()) { + lost++; + lost_run++; + guess_since_last = guess_since_last * wheel_step; + if (reset_after > 0 && lost_run >= reset_after) { + // Tiep tuc tu pose doan bang banh -- VO mat bam thi vslam_node cung + // chi con banh + IMU. + last_pose = last_pose * guess_since_last; + guess_since_last = rtabmap::Transform::getIdentity(); + odom->reset(last_pose); + resets++; + lost_run = 0; + } + continue; + } + lost_run = 0; + last_pose = pose; + guess_since_last = rtabmap::Transform::getIdentity(); + inliers_sum += oi.reg.inliers; + if (oi.keyFrameAdded) keyframes++; + WriteTum(fo, t * 1e-9, pose * T_bl_fp); + } + std::fclose(fo); + if (fr != nullptr) std::fclose(fr); + if (frames == 0) { + std::fprintf(stderr, "khong co cap IR + depth nao (ghi bang vslam_record --gl)\n"); + return 1; + } + + if (no_vo) { + std::printf("%d khung, chi tham chieu (--no-vo)\n", frames); + return 0; + } + std::vector sorted = ms; + std::sort(sorted.begin(), sorted.end()); + double sum = 0; + for (double v : ms) sum += v; + const double mean = sum / ms.size(); + const double p95 = sorted[static_cast(0.95 * (sorted.size() - 1))]; + const int ok = frames - lost; + std::printf("%d khung, mat bam %d (%.1f%%), reset %d, keyframe %d, inlier TB %.0f, " + "%.1f ms/khung (p95 %.1f)\n", + frames, lost, 100.0 * lost / frames, resets, keyframes, + ok > 0 ? static_cast(inliers_sum) / ok : 0.0, mean, p95); + if (!stats_path.empty()) { + FILE* fs = std::fopen(stats_path.c_str(), "w"); + if (fs != nullptr) { + std::fprintf(fs, + "{\"in\":\"%s\",\"frames\":%d,\"lost\":%d,\"resets\":%d,\"keyframes\":%d," + "\"inliers_mean\":%.1f,\"ms_mean\":%.2f,\"ms_p95\":%.2f,\"guess\":\"%s\"}\n", + in.c_str(), frames, lost, resets, keyframes, + ok > 0 ? static_cast(inliers_sum) / ok : 0.0, mean, p95, + guess_mode.c_str()); + std::fclose(fs); + } + } + return 0; +} diff --git a/tools/vslam_vsr_export.cc b/tools/vslam_vsr_export.cc index 0c51951..de41685 100644 --- a/tools/vslam_vsr_export.cc +++ b/tools/vslam_vsr_export.cc @@ -4,6 +4,7 @@ // vslam_vsr_export --in X.vsr --out DIR [--robot robot.yaml] // [--imu-hz 0] [--imu-offset-ms 0] // [--gyro-noise 0] [--accel-noise 0] [--seed 1] +// [--accel-bias x,y,z] [--gyro-bias x,y,z] [--ir-noise 0] // // Ra (DM-VIO doc theo src/dso/util/DatasetReader.h): // DIR/cam0/images/.png anh IR 8 bit. DM-VIO ghep anh voi times.txt @@ -28,6 +29,8 @@ // --imu-offset-ms D CONG D ms vao stamp IMU: lech dong ho camera-IMU ma // DM-VIO khong tu uoc luong // --gyro-noise S, --accel-noise S them nhieu trang (sigma moi mau) +// --accel-bias / --gyro-bias x,y,z cong bias co dinh (m/s^2, rad/s) +// --ir-noise S nhieu Gauss tren anh IR (muc xam) #include @@ -120,7 +123,8 @@ ImuS Lerp(const ImuS& a, const ImuS& b, int64_t t) { int main(int argc, char** argv) { std::string in, out, robot_yaml; - double imu_hz = 0.0, offset_ms = 0.0, gyro_noise = 0.0, accel_noise = 0.0; + double imu_hz = 0.0, offset_ms = 0.0, gyro_noise = 0.0, accel_noise = 0.0, ir_noise = 0.0; + double accel_bias[3] = {0, 0, 0}, gyro_bias[3] = {0, 0, 0}; // Nhieu SAN co trong ban ghi (sigma moi mau) -- de ghi mat do nhieu dung vao // imu_noise.yaml. vslam_record ghi chung vao header cua kich ban doc; am = // chua biet, lay tu header. @@ -139,6 +143,14 @@ int main(int argc, char** argv) { else if (a == "--sim-gyro-sigma") sim_gyro_sigma = std::atof(next().c_str()); else if (a == "--sim-accel-sigma") sim_accel_sigma = std::atof(next().c_str()); else if (a == "--seed") seed = static_cast(std::atoi(next().c_str())); + else if (a == "--ir-noise") ir_noise = std::atof(next().c_str()); + else if (a == "--accel-bias" || a == "--gyro-bias") { + double* v = a == "--accel-bias" ? accel_bias : gyro_bias; + if (std::sscanf(next().c_str(), "%lf,%lf,%lf", &v[0], &v[1], &v[2]) != 3) { + std::fprintf(stderr, "%s can x,y,z\n", a.c_str()); + return 2; + } + } else { std::fprintf(stderr, "tham so la: %s (xem dau file)\n", a.c_str()); return 2; @@ -259,6 +271,8 @@ int main(int argc, char** argv) { for (int k = 0; k < 3; ++k) { if (gyro_noise > 0.0) s.w[k] += gyro_noise * n01(rng); if (accel_noise > 0.0) s.a[k] += accel_noise * n01(rng); + s.w[k] += gyro_bias[k]; + s.a[k] += accel_bias[k]; } q.push_back(s); } @@ -283,10 +297,21 @@ int main(int argc, char** argv) { return 1; } FILE* ft = std::fopen((out + "/cam0/times.txt").c_str(), "w"); + std::mt19937 rng_img(seed + 7); // rieng: doi --ir-noise khong doi nhieu IMU + std::vector noisy; for (const Frame* f : used) { char name[64]; std::snprintf(name, sizeof(name), "/cam0/images/%019lld.png", static_cast(f->t)); - const cv::Mat m(f->h, f->w, CV_8UC1, const_cast(f->px.data())); + const uint8_t* px = f->px.data(); + if (ir_noise > 0.0) { + noisy.resize(f->px.size()); + for (size_t i = 0; i < noisy.size(); ++i) { + const double v = f->px[i] + ir_noise * n01(rng_img); + noisy[i] = static_cast(std::min(255.0, std::max(0.0, std::round(v)))); + } + px = noisy.data(); + } + const cv::Mat m(f->h, f->w, CV_8UC1, const_cast(px)); cv::imwrite(out + name, m); std::fprintf(ft, "%lld %.9f\n", static_cast(f->t), f->t * 1e-9); } @@ -372,10 +397,12 @@ int main(int argc, char** argv) { std::fprintf(fj, "{\"in\":\"%s\",\"robot\":\"%s\",\"images\":%zu,\"imu_src_hz\":%.3f," "\"imu_out_hz\":%.3f,\"imu_offset_ms\":%.3f,\"gyro_noise\":%.3g," - "\"accel_noise\":%.3g,\"seed\":%u,\"fx\":%.4f,\"fy\":%.4f,\"cx\":%.4f," + "\"accel_noise\":%.3g,\"accel_bias\":[%g,%g,%g],\"gyro_bias\":[%g,%g,%g]," + "\"ir_noise\":%.3g,\"seed\":%u,\"fx\":%.4f,\"fy\":%.4f,\"cx\":%.4f," "\"cy\":%.4f,\"width\":%d,\"height\":%d}\n", in.c_str(), robot_yaml.c_str(), used.size(), src_hz, out_hz, offset_ms, - gyro_noise, accel_noise, seed, fx, fy, cx, cy, W, H); + gyro_noise, accel_noise, accel_bias[0], accel_bias[1], accel_bias[2], gyro_bias[0], + gyro_bias[1], gyro_bias[2], ir_noise, seed, fx, fy, cx, cy, W, H); std::fclose(fj); std::printf("xuat %zu anh %dx%d, %zu mau IMU (%.1f Hz -> %.1f Hz, lech %.1f ms), %zu su that "