#!/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())